cdk-real-drift 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","names":["resolve","yamlParse","safeDecode","cache","GetV2AuthorizersCommand","ListLambdaAliasesCommand","ListAppSyncFunctionsCommand","str","GetPolicyCommand","LambdaGetPolicyCommand","DescribeDaxParametersCommand","DescribeDBInstancesCommand","DescribeParametersCommand","DescribeCacheUsersCommand","DescribeMemoryDbUsersCommand","fetch","pointerToDotted","UpdateDaxParameterGroupCommand","DRIFT_TIERS","sleep","err","isCancel"],"sources":["../src/aws-errors.ts","../src/revert/transient.ts","../src/cli-args.ts","../src/commands/glob-match.ts","../src/construct-path.ts","../src/config/config-file.ts","../src/synth/resolve-app.ts","../src/synth/io-host.ts","../src/synth/synth.ts","../src/commands/resolve-stacks.ts","../src/normalize/intrinsic-resolver.ts","../src/corpus/record.ts","../src/normalize/noise.ts","../src/desired/recover-nonascii.ts","../src/desired/yaml-cfn.ts","../src/desired/template-adapter.ts","../src/normalize/arn-identity.ts","../src/normalize/cc-api-strip.ts","../src/normalize/path-strip.ts","../src/normalize/policy-canonical.ts","../src/normalize/pipeline.ts","../src/diff/drift-calculator.ts","../src/diff/classify.ts","../src/read/client-config.ts","../src/read/kms-aliases.ts","../src/read/child-enumerators.ts","../src/read/pem.ts","../src/read/overrides.ts","../src/read/router.ts","../src/schema/schema-strip.ts","../src/commands/gather.ts","../src/commands/progress.ts","../src/baseline/baseline-file.ts","../src/report/style.ts","../src/commands/bulk-multiselect.ts","../src/revert/apply-ops.ts","../src/revert/writers.ts","../src/revert/plan.ts","../src/revert/apply.ts","../src/commands/stack-actions.ts","../src/commands/record.ts","../src/commands/ignore.ts","../src/diff/hints.ts","../src/report/report.ts","../src/commands/action-picker.ts","../src/commands/interactive-resolve.ts","../src/commands/check.ts","../src/commands/revert.ts","../src/cli.ts"],"sourcesContent":["// Classify \"this CloudFormation stack is not deployed (yet)\" errors. Synth-based\n// stack discovery can surface a stack that exists in the CDK code but has not been\n// deployed (new stack, renamed stack, different region) — that is not an error, it\n// just means there is nothing to drift-check.\nexport function isStackNotDeployed(e: unknown): boolean {\n const msg = (e as { message?: string })?.message ?? String(e);\n return /does not exist/i.test(msg) || (/ValidationError/i.test(msg) && /stack/i.test(msg));\n}\n\n// A stack that EXISTS but is in a state with no meaningful deployed reality to compare\n// against — REVIEW_IN_PROGRESS (a change set was created but never executed; nothing is\n// deployed) or a delete in progress. loadDesired throws this so `check` SKIPS it with a\n// clear note instead of silently comparing live state against a template that was never\n// deployed (which would read as a meaningless CLEAN).\nexport class StackNotCheckableError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'StackNotCheckableError';\n }\n}\n\n// Classify a CloudFormation StackStatus for checkability:\n// skip — REVIEW_IN_PROGRESS (change set never deployed) or DELETE_IN_PROGRESS: no\n// meaningful deployed reality, so comparing is nonsense (loadDesired throws).\n// warn — any OTHER `*_IN_PROGRESS` (mid-operation: live state in flux) or `*_FAILED`\n// (the deployed template may not match live reality): the comparison runs but\n// results may be transient/unreliable, so `check` prints a warning.\n// ok — a stable `*_COMPLETE` state (incl. ROLLBACK_COMPLETE / IMPORT_COMPLETE): a\n// valid comparison. Pure + exported for tests.\nexport function classifyStackStatus(status: string | undefined): {\n kind: 'ok' | 'skip' | 'warn';\n message: string;\n} {\n const s = status ?? '';\n if (s === 'REVIEW_IN_PROGRESS')\n return {\n kind: 'skip',\n message:\n 'in REVIEW_IN_PROGRESS — a change set was created but never deployed, so there is no deployed state to check',\n };\n if (s === 'DELETE_IN_PROGRESS')\n return {\n kind: 'skip',\n message: 'is being deleted (DELETE_IN_PROGRESS) — nothing stable to check',\n };\n if (s.endsWith('_IN_PROGRESS'))\n return {\n kind: 'warn',\n message: `stack is mid-operation (${s}) — live state is in flux, so drift results may be transient`,\n };\n if (s.endsWith('_FAILED'))\n return {\n kind: 'warn',\n message: `stack is in a failed state (${s}) — the deployed template may not match live reality, so drift results may be unreliable`,\n };\n return { kind: 'ok', message: '' };\n}\n\n// \"the resource itself no longer exists in AWS\" — i.e. it was deleted out of band.\n// Covers Cloud Control GetResource + every SDK-override reader's not-found error:\n// CC API / Lambda : ResourceNotFoundException\n// S3 : NoSuchBucket / NoSuchBucketPolicy\n// SQS : AWS.SimpleQueueService.NonExistentQueue / QueueDoesNotExist\n// SNS / Budgets : NotFoundException\n// IAM : NoSuchEntity / NoSuchEntityException\n// EC2 EIP : InvalidAllocationID.NotFound / InvalidAddress.NotFound\n// Glue : EntityNotFoundException (GetTable on a deleted table/db)\n// cdkrd ResourceGoneError : a list/describe-based override whose PARENT container\n// exists but whose specific keyed resource is absent (a\n// Route53 record / MetricFilter deleted while its zone /\n// log group survives) — the SDK returns success+empty, not\n// a throw, so the reader raises this to mean \"deleted\".\n// Distinct from \"target not resolvable from the template\" (override returns\n// undefined → skipped) — this means the resource was read for and is gone.\nconst NOT_FOUND_ERROR_NAMES = new Set([\n 'ResourceNotFoundException',\n 'NoSuchBucket',\n 'NoSuchBucketPolicy',\n 'QueueDoesNotExist',\n 'AWS.SimpleQueueService.NonExistentQueue',\n 'NotFoundException',\n 'NoSuchEntity',\n 'NoSuchEntityException',\n 'InvalidAllocationID.NotFound',\n 'InvalidAddress.NotFound',\n 'EntityNotFoundException',\n // DocumentDB describe-db-clusters / describe-db-instances on a deleted target.\n 'DBClusterNotFoundFault',\n 'DBInstanceNotFoundFault',\n // Cloud Map (ServiceDiscovery) GetNamespace / GetService on a deleted target.\n 'NamespaceNotFound',\n 'ServiceNotFound',\n // SES DescribeReceiptRuleSet / DescribeReceiptRule on a deleted inbound rule set / rule.\n 'RuleSetDoesNotExistException',\n 'RuleDoesNotExistException',\n 'ResourceGoneError',\n]);\n\n// Raised by a list/describe-based SDK-override reader when the parent container was\n// queried successfully but the specific keyed resource is ABSENT — i.e. it was deleted\n// out of band (the AWS API returns success with the item missing, not a not-found\n// throw). The router maps this (via isResourceNotFoundError) to the `deleted` tier, the\n// same as a native not-found error. NOT used for \"couldn't resolve the target from the\n// template\" — that case returns undefined → `skipped`.\nexport class ResourceGoneError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ResourceGoneError';\n }\n}\n\nexport function isResourceNotFoundError(e: unknown): boolean {\n const name = (e as { name?: string })?.name ?? '';\n if (NOT_FOUND_ERROR_NAMES.has(name)) return true;\n const code = (e as { Code?: string })?.Code ?? '';\n return NOT_FOUND_ERROR_NAMES.has(code);\n}\n","// Cross-service classification of TRANSIENT \"the resource is mid-operation, retry\n// later\" revert failures — as opposed to terminal validation/permission/state errors.\n//\n// The motivating case (issue #467): after an out-of-band `route53resolver\n// update-resolver-rule`, the rule stays `Status: UPDATING` for minutes (async\n// propagation to endpoint ENIs). A `cdkrd revert` issued in that window fails with\n// [RSLVR-00705] Cannot update Resolver Rule because it's currently updating.\n// That is not a real failure — a later revert succeeds. The whole class (concurrent\n// modification, throttling, \"another operation in progress\") is retry-then-hint\n// material, not generic-FAILED material.\n//\n// We only have the error TEXT to work with (Cloud Control surfaces async failures as a\n// FAILED ProgressEvent StatusMessage; thrown SDK errors are caught to a message string).\n// `errorText` prepends the error `name`/`code` so name-only signals (e.g.\n// `ThrottlingException`) survive into the string the classifier matches on.\n\n// Verdict for a single error string.\nexport interface TransientVerdict {\n transient: boolean;\n // A short human-facing explanation, shown once retries are exhausted (hybrid UX:\n // bounded backoff first, then this hint instead of a bare `FAILED: … — <raw error>`).\n hint?: string;\n}\n\nconst RETRY_HINT = 'the resource is still applying a previous update — retry in a few minutes';\nconst THROTTLE_HINT = 'AWS throttled the request — retry shortly';\n\n// First match wins. Patterns match against `errorText` (case-insensitive). Keep this\n// focused on the genuinely-transient class: a false positive here turns a permanent\n// failure into wasted backoff + a misleading \"retry later\" hint, so err toward\n// specificity (service codes, unambiguous phrases) over broad substrings.\nconst TRANSIENT_PATTERNS: readonly { pattern: RegExp; hint: string }[] = [\n // Route53Resolver rule/endpoint mid-update (async ENI propagation).\n {\n pattern: /RSLVR-00705|currently updating/i,\n hint:\n 'the resource is still applying a previous update (async propagation) — ' +\n 'retry in a few minutes',\n },\n // Generic concurrent-modification / operation-in-progress across services\n // (e.g. ConcurrentModificationException, OperationInProgressException,\n // ResourceConflictException/ConflictException) plus Cloud Control's bare\n // HandlerErrorCode forms (ResourceConflict, NetworkFailure, InternalFailure,\n // ServiceInternalError) surfaced on a FAILED ProgressEvent.\n {\n pattern:\n /ConcurrentModificationException|OperationInProgressException|OperationAbortedException|ResourceConflictException|ConflictException|\\bResourceConflict\\b|\\bNetworkFailure\\b|\\bInternalFailure\\b|\\bServiceInternalError\\b/i,\n hint: RETRY_HINT,\n },\n {\n pattern:\n /another (operation|update|change|request)[^.]*in progress|operation[^.]*(already )?in progress|update[^.]*in progress|modification[^.]*in progress|(currently )?being (created|updated|modified|deleted|provisioned)|is not in a stable state|resource is in use|please try again|try again (later|in a few)/i,\n hint: RETRY_HINT,\n },\n // Stateful resources (RDS / Aurora / DocDB / Neptune / ElastiCache / Redshift / DAX) reject\n // a modify while the resource is mid-change with an \"invalid state\" fault whose message\n // says it is \"not in the available state\". This is the SAME mid-update-retry-later class\n // as RSLVR-00705 for the DB reverts cdkrd already supports (RDS/DocDB BackupRetention,\n // DBInstanceClass, ElastiCache node type, …): an out-of-band `modify-*` leaves the\n // resource `modifying`/`rebooting` for minutes, so an immediate revert fails and only a\n // later retry succeeds. Matched by the service state-fault codes plus AWS's shared\n // \"not in the available state\" / \"not in available state\" phrasing. InvalidClusterStateFault\n // / InvalidParameterGroupStateFault cover DAX (#552): a fresh dax:update-parameter-group leaves\n // the group \"applying\" for a few seconds, so a same-run revert hits \"the parameter <x> is being\n // modified\" (live-verified during the #552 detect→revert live-test).\n {\n pattern:\n /InvalidDBInstanceState|InvalidDBClusterState|InvalidClusterState|InvalidParameterGroupState|InvalidReplicationGroupState|InvalidCacheClusterState|InvalidGlobalClusterState|is not (currently )?in (the |an? )?available state/i,\n hint: RETRY_HINT,\n },\n // Throttling / rate limiting — retryable, but a distinct hint.\n {\n pattern:\n /ThrottlingException|ThrottledException|TooManyRequestsException|RequestThrottled|RequestLimitExceeded|ServiceUnavailable|\\bThrottling\\b|rate exceeded/i,\n hint: THROTTLE_HINT,\n },\n];\n\n// Best-effort text extraction: `name: message` when the name adds signal the message\n// lacks, else the message alone. Accepts already-stringified errors too.\nexport function errorText(e: unknown): string {\n if (typeof e === 'string') return e;\n const o = (e ?? {}) as { name?: unknown; code?: unknown; message?: unknown };\n const name = typeof o.name === 'string' ? o.name : typeof o.code === 'string' ? o.code : '';\n const message = typeof o.message === 'string' ? o.message : '';\n if (name && (!message || !message.includes(name))) {\n return message ? `${name}: ${message}` : name;\n }\n return message || String(e);\n}\n\nexport function classifyTransient(error: string | undefined): TransientVerdict {\n if (!error) return { transient: false };\n for (const { pattern, hint } of TRANSIENT_PATTERNS) {\n if (pattern.test(error)) return { transient: true, hint };\n }\n return { transient: false };\n}\n\n// The shape a retryable revert step returns. `applyRevertItem` / `applyRevertDelete`\n// and the SDK-writer path all normalize to this (ok + error string); on exhaustion the\n// retry annotates it with `transient` + `hint` for the report layer.\nexport interface RetryableResult {\n ok: boolean;\n error?: string;\n transient?: boolean;\n hint?: string;\n}\n\nexport interface RetryOptions {\n // Total attempts including the first (default 3 → up to 2 retries). Ignored when\n // `deadlineMs` is set (the `revert --wait` path retries until the deadline instead).\n maxAttempts?: number;\n // Linear backoff base: waits baseDelayMs * attempt between tries (3s, 6s, …).\n baseDelayMs?: number;\n // Cap on a single backoff wait, so the deadline mode's linear growth stays bounded.\n maxDelayMs?: number;\n // `revert --wait` mode: keep retrying a transient failure until this wall-clock time\n // (ms epoch), NOT a fixed attempt count — so a resource that stays UPDATING for\n // minutes (RSLVR-00705) can converge in ONE command. `maxAttempts` is ignored.\n deadlineMs?: number;\n // Injectable clock (default Date.now) so deadline-mode tests don't wait for real time.\n now?: () => number;\n // Called before each backoff wait (a transient failure about to be retried) — the\n // report layer uses it to print a per-retry progress line so a multi-minute `--wait`\n // never looks frozen. `attempt` is the 1-based number of the attempt that just failed.\n onRetry?: (info: { attempt: number; delayMs: number; hint?: string }) => void;\n // Injectable for tests (default real setTimeout).\n sleep?: (ms: number) => Promise<void>;\n}\n\nexport const DEFAULT_MAX_ATTEMPTS = 3;\nexport const DEFAULT_BASE_DELAY_MS = 3000;\nexport const DEFAULT_MAX_DELAY_MS = 30_000;\n// `revert --wait` with no explicit duration: block for up to 10 minutes (a\n// Route53Resolver rule's UPDATING window is typically a few minutes).\nexport const DEFAULT_WAIT_MS = 10 * 60 * 1000;\n\n// Parse a `--wait` duration: a bare number is SECONDS; a `s`/`m`/`h` suffix scales\n// (e.g. \"300\", \"300s\", \"5m\", \"1h\"). Returns ms. Throws on a malformed value so a\n// typo'd `--wait=5min` fails fast rather than silently defaulting.\nexport function parseDurationMs(raw: string): number {\n const m = /^(\\d+)(s|m|h)?$/.exec(raw.trim());\n if (!m) {\n throw new Error(`invalid --wait duration \"${raw}\" — use e.g. 90, 30s, 5m, 1h`);\n }\n const n = Number(m[1]);\n const unit = m[2] ?? 's';\n const scale = unit === 'h' ? 3_600_000 : unit === 'm' ? 60_000 : 1000;\n return n * scale;\n}\n\nconst realSleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));\n\n// Run `op` with bounded backoff, retrying ONLY while its failure classifies as\n// transient. A terminal failure returns immediately (no wasted waiting). Two stop\n// conditions: the default fixed `maxAttempts`, or — when `deadlineMs` is set\n// (`revert --wait`) — a wall-clock deadline so a minutes-long UPDATING window can\n// converge in one command. When the retries are exhausted on a still-transient failure,\n// the returned result carries `transient: true` + the classifier's `hint` so the caller\n// can show the targeted message instead of a bare FAILED. `op` must be self-contained\n// (catch its own throws into `{ ok:false, error }`) — it is re-invoked verbatim each try.\nexport async function retryTransient<T extends RetryableResult>(\n op: () => Promise<T>,\n opts: RetryOptions = {}\n): Promise<T> {\n const max = opts.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const base = opts.baseDelayMs ?? DEFAULT_BASE_DELAY_MS;\n const cap = opts.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n const doSleep = opts.sleep ?? realSleep;\n const clock = opts.now ?? Date.now;\n const deadline = opts.deadlineMs;\n let result = await op();\n let attempt = 1;\n while (!result.ok) {\n const verdict = classifyTransient(result.error);\n if (!verdict.transient) return result; // terminal — stop, no annotation\n // More tries allowed? deadline mode: only if there is time left to at least retry\n // AFTER a (possibly shortened) wait; attempt mode: until maxAttempts.\n const more = deadline !== undefined ? clock() < deadline : attempt < max;\n if (!more) return { ...result, transient: true, hint: verdict.hint };\n // In deadline mode, never sleep past the deadline (so the last wait doesn't overrun).\n const wait =\n deadline !== undefined\n ? Math.max(0, Math.min(base * attempt, cap, deadline - clock()))\n : Math.min(base * attempt, cap);\n opts.onRetry?.({ attempt, delayMs: wait, ...(verdict.hint && { hint: verdict.hint }) });\n await doSleep(wait);\n attempt++;\n result = await op();\n }\n return result;\n}\n","// Tiny shared CLI arg parser (no dependency).\nimport { DEFAULT_WAIT_MS, parseDurationMs } from './revert/transient.js';\n\n// The complete known-option surface. parseCommonArgs is shared by all three\n// verbs, so verb-specific flags (--dry-run) are recorded here and interpreted\n// by the verb. Anything NOT listed is a fail-fast error — a typo'd flag must\n// never silently turn its value into a positional stack name (cdkrd has an\n// AWS-mutating verb, so a misparse can target the wrong stacks).\nconst VALUE_FLAGS = new Set(['--region', '--profile', '--app', '-a', '-c', '--context']);\nconst BOOLEAN_FLAGS = new Set([\n '--json',\n '--fail',\n '--show-all',\n '--yes',\n '-y',\n '--pre-deploy',\n '--undeclared-only',\n '--declared-only',\n '--dry-run',\n '--remove-unrecorded',\n '--verbose',\n '-v',\n '--strict',\n '--all',\n]);\n\nexport interface CommonArgs {\n stackNames: string[]; // positional stack names (may be empty → all stacks the CDK app defines)\n all: boolean; // explicitly target EVERY stack the app defines (the default when no name is given); overrides any positional names\n region: string | undefined; // resolved region (no silent default — caller errors if absent)\n profile: string | undefined; // AWS profile (--profile or $AWS_PROFILE)\n app: string | undefined; // CDK app command OR pre-synthesized cloud-assembly dir\n context: Record<string, string>; // -c/--context key=value overrides for synth (cdk.json is the base layer)\n json: boolean;\n showAll: boolean; // inventory mode: ignore baseline, show ALL undeclared values\n yes: boolean;\n preDeploy: boolean; // compare live vs the LOCAL synth template (drift your next deploy would clobber)\n // (check) scope flags (R59) — at most ONE of --pre-deploy / --declared-only /\n // --undeclared-only; the parser rejects combinations.\n // --undeclared-only skips the declared-side comparison entirely — for pairing\n // cdkrd with `cdk drift` / CFn drift detection, which already own declared\n // drift. Deleted resources still report (a gone resource has no undeclared\n // values to check; silence would be a lie).\n undeclaredOnly: boolean;\n // --declared-only skips the undeclared tier (baseline untouched): declared\n // drift vs the DEPLOYED template only. NOT the same as --pre-deploy, which\n // compares against the LOCAL SYNTH template (a different question: what would\n // my next deploy clobber).\n declaredOnly: boolean;\n // (check) automation mode, following the `cdk diff --fail` / `cdk drift --fail`\n // convention (R53): drift sets exit 1 and prompts are suppressed. Without it,\n // check REPORTS drift but exits 0 (report-only).\n fail: boolean;\n // (check) coverage axis, ORTHOGONAL to --fail (which is about drift): make a run\n // whose coverage was incomplete — any resource SKIPPED (CC-unsupported + no SDK\n // override, a read error, a missing physical id) or any nested stack not recursed\n // into — exit non-zero. A loud coverage `warning:` always prints regardless of this\n // flag; --strict additionally turns that gap into a CI-failing exit. Does not change\n // the --fail default (a transient throttle should not silently start failing CI).\n strict: boolean;\n removeUnrecorded: boolean; // (revert) opt in to REMOVING undeclared drift on a stack with no baseline\n verbose: boolean; // (check) expand informational tiers / (revert) the NOT-revertable summary to full lists\n // (revert) `--wait[=DURATION]`: block on a TRANSIENT \"resource is mid-update\" failure\n // (RSLVR-00705 & friends), retrying until the resource settles instead of stopping at\n // the short default backoff. undefined = not requested (default short backoff → hint);\n // a number = the wait budget in ms (bare `--wait` = DEFAULT_WAIT_MS). Issue #467.\n waitMs: number | undefined;\n}\n\n/**\n * Whether prompts may be shown: only in a real TTY. Non-interactive now simply means\n * non-TTY (real CI/cron/pipes). The single source of truth — command code threads this\n * in rather than reading `process.stdin.isTTY` directly. Optional prompts skip when\n * false; required-decision prompts error (exit 2) when false.\n */\nexport function isInteractive(): boolean {\n return Boolean(process.stdin.isTTY);\n}\n\nexport function parseCommonArgs(args: string[]): CommonArgs {\n const values: Record<string, string> = {}; // canonical value-flag → its (last) value\n const found = new Set<string>(); // boolean flags seen\n const stackNames: string[] = [];\n const context: Record<string, string> = {};\n let waitMs: number | undefined; // (revert) --wait[=DURATION]; undefined = not requested\n\n for (let i = 0; i < args.length; i++) {\n const a = args[i];\n if (a === undefined) continue;\n if (!a.startsWith('-')) {\n stackNames.push(a);\n continue;\n }\n // Record `--flag=value` (and `-a=value`) like the cdk CLI / yargs do. Split on\n // the FIRST '=' only so `--context=env=prod` keeps the value \"env=prod\" whole.\n const eq = a.indexOf('=');\n const flag = eq > 0 ? a.slice(0, eq) : a;\n const inlineValue = eq > 0 ? a.slice(eq + 1) : undefined;\n\n if (VALUE_FLAGS.has(flag)) {\n let v: string;\n if (inlineValue !== undefined) {\n // `--app=` with nothing after the '=' is still a missing value\n if (inlineValue === '') {\n throw new Error(`option \"${flag}\" requires a value — see cdkrd --help`);\n }\n v = inlineValue;\n } else {\n const next = args[i + 1];\n // a following token that is itself a flag is NOT a value (catches `--region --json`).\n // An empty token (`--region \"\"`) is also \"no value\": accepting it would let `''`\n // shadow the env fallback (`?? process.env.AWS_REGION` does not fire on `''`),\n // and the inline form `--region=` already rejects empty — stay consistent.\n if (next === undefined || next === '' || next.startsWith('-')) {\n throw new Error(`option \"${flag}\" requires a value — see cdkrd --help`);\n }\n v = next;\n i++; // consume the value\n }\n if (flag === '-c' || flag === '--context') {\n const kvEq = v.indexOf('=');\n if (kvEq <= 0) {\n throw new Error(`option \"${flag}\" expects key=value, got \"${v}\" — see cdkrd --help`);\n }\n context[v.slice(0, kvEq)] = v.slice(kvEq + 1);\n } else {\n values[flag === '-a' ? '--app' : flag] = v;\n }\n continue;\n }\n if (BOOLEAN_FLAGS.has(flag)) {\n // a boolean flag takes no value: `--json=true` is a mistake, not a stack name\n if (inlineValue !== undefined) {\n throw new Error(`option \"${flag}\" does not take a value — see cdkrd --help`);\n }\n found.add(flag);\n continue;\n }\n // `--wait` (revert): optional value, INLINE form only (`--wait` or `--wait=5m`). A\n // following separate token is deliberately NOT consumed — `--wait 5m` would be\n // ambiguous with a positional stack name, the exact misparse this parser guards\n // against for an AWS-mutating verb.\n if (flag === '--wait') {\n waitMs = inlineValue === undefined ? DEFAULT_WAIT_MS : parseDurationMs(inlineValue);\n continue;\n }\n throw new Error(`unknown option \"${a}\" — see cdkrd --help`);\n }\n\n const has = (flag: string): boolean => found.has(flag);\n // scope flags select WHICH comparison runs — more than one is contradictory\n // (--pre-deploy + --undeclared-only would compare nothing) or redundant\n // (--pre-deploy is already declared-side). Reject at parse.\n const scopes = ['--pre-deploy', '--declared-only', '--undeclared-only'].filter(has);\n if (scopes.length > 1) {\n throw new Error(`${scopes.join(' and ')} are mutually exclusive — see cdkrd --help`);\n }\n return {\n stackNames,\n all: has('--all'),\n context,\n region: values['--region'] ?? process.env.AWS_REGION ?? process.env.AWS_DEFAULT_REGION,\n profile: values['--profile'] ?? process.env.AWS_PROFILE,\n // -a/--app > CDKRD_APP env (cdk.json \"app\" fallback resolved in the synth layer)\n app: values['--app'] ?? process.env.CDKRD_APP,\n json: has('--json'),\n fail: has('--fail'),\n strict: has('--strict'),\n showAll: has('--show-all'),\n yes: has('--yes') || has('-y'),\n preDeploy: has('--pre-deploy'),\n undeclaredOnly: has('--undeclared-only'),\n declaredOnly: has('--declared-only'),\n removeUnrecorded: has('--remove-unrecorded'),\n verbose: has('--verbose') || has('-v'),\n waitMs,\n };\n}\n","// Tiny glob matcher for stack-name selection:\n// * matches any run of characters (including empty)\n// ? matches exactly one character\n// Anchored full-string match; every other character (incl. regex metachars like\n// `.` `+` `(`) is treated as a literal. No `[...]` classes, no `**` semantics.\n\n/** True when `s` contains a glob metachar (`*` or `?`). */\nexport function isGlob(s: string): boolean {\n return s.includes('*') || s.includes('?');\n}\n\n/** Convert a glob pattern to an anchored RegExp (other metachars escaped to literals). */\nexport function globToRegExp(pattern: string): RegExp {\n let out = '^';\n // Collapse runs of consecutive `*` to a single `*` FIRST: `***` is semantically\n // identical to `*` (any run of characters), but compiling each star to `.*` yields\n // `.*.*.*…` which backtracks CATASTROPHICALLY (O(len^N)) on a long non-matching\n // subject — a self-inflicted multi-second hang (ReDoS) on a user-authored glob like\n // `*****` (a natural gitignore-style attempt). One `.*` per run can't backtrack.\n for (const ch of pattern.replace(/\\*+/g, '*')) {\n if (ch === '*') out += '.*';\n else if (ch === '?') out += '.';\n else out += ch.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n }\n out += '$';\n return new RegExp(out);\n}\n\n/** True when `name` matches the glob `pattern` (anchored full-string match). */\nexport function matchesGlob(pattern: string, name: string): boolean {\n return globToRegExp(pattern).test(name);\n}\n\n/**\n * Path-axis glob (for ignore-rule `path` patterns against a `<id>.<sub.path>` target):\n * a SEGMENT-aware variant where `*` / `?` do NOT cross a `.` or `[` boundary. So\n * `*.DesiredCount` matches `<anyId>.DesiredCount` (the documented intent — `*` = one id\n * segment) but NOT a same-named leaf nested deeper (`Tbl.Config.DesiredCount`, or a\n * free-form-map key literally named `DesiredCount`). Subtree coverage of a PARENT rule\n * (`X.Policies` covering `X.Policies[Mp].Name`) is handled separately by the ancestor\n * walk in `pathMatches`, so bounding `*` here does not under-match. The stack/region\n * axes keep `matchesGlob` (their names contain no `.`/`[`, so it is equivalent there).\n */\nexport function matchesPathGlob(pattern: string, target: string): boolean {\n let out = '^';\n for (const ch of pattern.replace(/\\*+/g, '*')) {\n if (ch === '*') out += '[^.[]*';\n else if (ch === '?') out += '[^.[]';\n else out += ch.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n }\n out += '$';\n return new RegExp(out).test(target);\n}\n","// The construct path WITHIN its stack — the stack (and any enclosing CDK Stage) prefix\n// removed. CDK forms the CloudFormation stack name by `-`-joining the leading construct-\n// path segments (the enclosing Stage ids + the Stack construct id), while the construct\n// path (`aws:cdk:path`) `/`-joins the same segments:\n//\n// plain stack MyStack/Api/Handler stackName = MyStack -> Api/Handler\n// CDK Stage dev-main/AuroraDB/Db/PG stackName = dev-main-AuroraDB -> Db/PG\n//\n// So strip the leading run of `/`-segments whose `-`-join equals the stack name. The\n// report header already states the stack name, so repeating it on every finding line is\n// noise — and dropping it makes the Stage form (a `/`-separated path beside a `-`-joined\n// name) read consistently instead of looking like two different stack identifiers.\n//\n// Robust to the naming variants: a hyphen INSIDE a stack/stage id is fine (the whole\n// segments are joined and compared to the actual stackName, never split); a stack whose id\n// already bakes in the stage (`dev-main-AuroraDB/...`) strips as one segment; a nested\n// Stage (`a/b/Stack/...` -> `a-b-Stack`) strips all of them. When nothing matches — e.g. an\n// explicitly overridden `stackName` that no longer mirrors the construct ids — the path is\n// returned UNCHANGED (a safe, self-contained fallback, never a wrong strip).\nexport function withinStackPath(constructPath: string, stackName: string): string {\n const segs = constructPath.split('/');\n // Largest k first so the most specific (full stage+stack) prefix wins; only one k can\n // match anyway, since stackName is exactly the `-`-join of those leading segments.\n for (let k = segs.length - 1; k >= 1; k--) {\n if (segs.slice(0, k).join('-') === stackName) return segs.slice(k).join('/');\n }\n return constructPath;\n}\n","// Git-committed project config: .cdkrd/ignore.yaml (cwd-relative, loaded once per run).\n//\n// YAML, not JSON, ON PURPOSE: this is a hand-edited POLICY file (the ignore-file\n// family — .gitignore / .dockerignore / .trivyignore — is conventionally comment-bearing,\n// never JSON), and the single most valuable hand-edit is recording WHY a property is\n// ignored. JSON cannot hold a comment; YAML can. The companion baseline file stays JSON\n// because it is the opposite — a machine-generated, wholesale-rewritten data artifact, not\n// a human policy. The file format itself signals the role: data = JSON, policy = YAML.\n//\n// Kept SEPARATE from the per-stack baseline file on purpose:\n// 1. the baseline is a machine-generated artifact that `record` (writeBaseline)\n// rewrites WHOLESALE every time — hand-written ignore rules would be erased on\n// every record (and a carry-over special case would be an accident magnet);\n// 2. ignore rules express an APP-WIDE intent (\"this property is managed by an\n// external system\"), not a per-stack/account/region fact, so they should live\n// once, not be duplicated into every baseline.\n//\n// The only field today is `ignore`: path-level rules for properties an external\n// system legitimately keeps rewriting (Application Auto Scaling moving an ECS\n// Service DesiredCount, DynamoDB autoscaled capacity, externally-managed Lambda\n// reserved concurrency). Without this, `record` (a value snapshot) would re-detect\n// and force a re-record every time the value moves — an infinite loop. This is the\n// `.driftignore` / Terraform `ignore_changes` equivalent. The file is an extension\n// point: future settings (concurrency, etc.) can be added here.\n//\n// Every ignore rule is a MAPPING `{ path, stack?, account?, region? }` — one uniform,\n// self-labelling shape (no bare-string shorthand: `\"*.DesiredCount\"` alone reads as\n// an unlabelled value, so the required `path` key spells out what it is). `path` is\n// the property pattern; `stack` / `account` / `region` are optional scopes (absent =\n// any). These three scope axes are EXACTLY the baseline file's identity axes (stack ×\n// account × region): the same stack name can be deployed to several accounts and/or\n// regions (the common `env: { account, region }` CDK pattern, or a `*` stack glob), and\n// a property may legitimately drift in only one of those — so a rule must be able to\n// narrow to any of the three. `account` matters for the same reason `region` does:\n// stack-name uniqueness only holds WITHIN one account/App, so without it a `stack: \"Prod*\"`\n// rule leaks into a same-named stack in another account. All four of `path` / `stack` /\n// `account` / `region` accept the same `*` / `?` glob.\n// ignore:\n// # ServiceRole inline policies are managed by an external system\n// - path: ApiStack/ServiceRole.Policies # any stack, account, region\n// - path: \"*.DesiredCount\" # us-* regions, prod account only\n// account: \"111111111111\"\n// region: us-*\n// - path: Fn*.ReservedConcurrentExecutions\n// stack: Prod*\n// region: ap-northeast-1\n\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { type Document, isSeq, parseDocument, YAMLSeq } from 'yaml';\nimport { matchesGlob, matchesPathGlob } from '../commands/glob-match.js';\nimport { withinStackPath } from '../construct-path.js';\nimport type { Finding } from '../types.js';\n\n// An ignore rule. `path` is the glob against \"<logicalId>.<path>\" /\n// \"<constructPath>.<path>\"; `stack` / `account` / `region` are optional globs that further\n// restrict WHERE the rule applies (absent = any) — the baseline file's three identity axes.\nexport interface IgnoreRuleObject {\n path: string;\n stack?: string;\n account?: string;\n region?: string;\n}\n\nexport interface CdkrdConfig {\n ignore: IgnoreRuleObject[];\n}\n\nconst CONFIG_PATH = '.cdkrd/ignore.yaml';\nconst KNOWN_KEYS = new Set(['ignore']);\nconst RULE_OBJECT_KEYS = new Set(['path', 'stack', 'account', 'region']);\n\n// Header written above a freshly-created ignore.yaml so a hand-editor immediately sees the\n// shape and the comment convention. Existing files keep their own comments (append-only).\nconst FILE_HEADER =\n '# cdkrd ignore rules — properties cdkrd should stop reporting as drift.\\n' +\n '# Each rule: { path, stack?, account?, region? }; `path` is a\\n' +\n '# \"<constructPath|logicalId>.<property>\" glob, the scopes narrow WHERE it applies.\\n' +\n '# Add a comment above a rule to record WHY it is ignored.\\n';\n\n/**\n * Load `.cdkrd/ignore.yaml` (cwd-relative). Absent file -> empty config (no migration\n * needed). A comments-only / empty file parses to null -> empty config too. Invalid\n * YAML, a wrong-typed `ignore`, or an unknown top-level key throws a clear error (caller\n * surfaces exit 2): a silently-ignored ignore-rule file is the most dangerous failure\n * mode (the user thinks a property is suppressed when it is not), so this fails fast.\n * Unknown-key rejection closes the typo variant of the same mode (`ignroe` would\n * otherwise load as an empty config without a sound).\n */\nexport async function loadConfig(): Promise<CdkrdConfig> {\n let raw: string;\n try {\n raw = await readFile(CONFIG_PATH, 'utf8');\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === 'ENOENT') return { ignore: [] };\n throw e;\n }\n let parsed: unknown;\n // parseDocument collects syntax problems in `doc.errors` (it does NOT throw), so check\n // them explicitly to fail fast. YAML is a JSON superset, so this also reads a legacy\n // all-JSON ignore.yaml.\n const doc = parseDocument(raw, { prettyErrors: true });\n if (doc.errors.length > 0) throw new Error(`${CONFIG_PATH} is not valid YAML`);\n try {\n parsed = doc.toJS();\n } catch {\n throw new Error(`${CONFIG_PATH} is not valid YAML`);\n }\n // A file that is empty or only comments parses to null/undefined — an empty config,\n // not an error (the `ignore` verb writes a header-comment-only file before any rule).\n if (parsed === null || parsed === undefined) return { ignore: [] };\n if (typeof parsed !== 'object' || Array.isArray(parsed))\n throw new Error(`${CONFIG_PATH} must be a YAML mapping`);\n const unknown = Object.keys(parsed).filter((k) => !KNOWN_KEYS.has(k));\n if (unknown.length > 0)\n throw new Error(\n `${CONFIG_PATH}: unknown key(s) ${unknown.map((k) => `\"${k}\"`).join(', ')} — known keys: ${[...KNOWN_KEYS].map((k) => `\"${k}\"`).join(', ')}`\n );\n const ignore = (parsed as Record<string, unknown>).ignore ?? [];\n if (!Array.isArray(ignore)) throw new Error(`${CONFIG_PATH}: \"ignore\" must be an array`);\n ignore.forEach((entry, i) => validateIgnoreEntry(entry, i));\n return { ignore: ignore as IgnoreRuleObject[] };\n}\n\n/**\n * Validate one `ignore` array entry: a mapping with a required string `path` and\n * optional string `stack` / `account` / `region` (and no other keys — the same fail-fast\n * typo guard as the unknown-top-level-key check, so a mistyped `reigon` is rejected\n * rather than silently ignored, which would leave a property unscoped).\n */\nfunction validateIgnoreEntry(entry: unknown, index: number): void {\n const at = `${CONFIG_PATH}: \"ignore\"[${index}]`;\n if (typeof entry !== 'object' || entry === null || Array.isArray(entry))\n throw new Error(`${at} must be a mapping { path, stack?, account?, region? }`);\n const obj = entry as Record<string, unknown>;\n const unknown = Object.keys(obj).filter((k) => !RULE_OBJECT_KEYS.has(k));\n if (unknown.length > 0)\n throw new Error(\n `${at}: unknown key(s) ${unknown.map((k) => `\"${k}\"`).join(', ')} — known keys: \"path\", \"stack\", \"account\", \"region\"`\n );\n if (typeof obj.path !== 'string')\n throw new Error(`${at}: \"path\" is required and must be a string`);\n if (obj.path === '')\n // an empty path matches NOTHING (the glob `^$` never matches a `<id>.<path>` target\n // and the ancestor walk never reaches empty) — a silent no-op rule the user believes\n // is suppressing a property. Reject it loudly so the no-op can't masquerade as active.\n throw new Error(`${at}: \"path\" must not be empty`);\n for (const k of ['stack', 'account', 'region'] as const)\n if (obj[k] !== undefined && typeof obj[k] !== 'string')\n throw new Error(`${at}: \"${k}\" must be a string`);\n}\n\n/**\n * The exact ignore rule the `ignore` verb writes for a finding — always the unscoped\n * rule (just `path`); the optional `stack` / `region` scopes stay hand-authored (the\n * verb writes the simplest rule; narrowing is a manual edit). Prefer the human-friendly\n * `<constructPath>.<path>` when present (CDK stacks): it is what `cdk-local` targets on\n * and readable in the git-committed config diff. The construct path is written WITHIN the\n * stack (the stack/Stage prefix stripped, given `stackName`) so it is byte-identical to\n * what the report prints for the finding — copy what you see. Naturally stack-scoped even\n * without the prefix (a `stack:` scope narrows further). Falls back to `<logicalId>.<path>`,\n * ALWAYS present (the CloudFormation key) so a rule is writable even on a non-CDK /\n * metadata-stripped stack. Pure + exported; `applyIgnores` matches the within-stack path,\n * the full construct path (older rules), AND the logicalId, so every form works.\n */\nexport function ignoreRuleFor(finding: Finding, stackName = ''): IgnoreRuleObject {\n const id = finding.constructPath\n ? withinStackPath(finding.constructPath, stackName)\n : finding.logicalId;\n return { path: finding.path ? `${id}.${finding.path}` : id };\n}\n\n/** Canonical identity of a rule (path + the three optional scopes), for dedupe. */\nfunction ruleKey(r: IgnoreRuleObject): string {\n return JSON.stringify([r.path, r.stack ?? null, r.account ?? null, r.region ?? null]);\n}\n\n/** A rule as a plain object with keys in canonical order (path, stack, account, region),\n * undefined scopes omitted — the shape serialized into a YAML mapping node. */\nfunction orderedRule(r: IgnoreRuleObject): Record<string, string> {\n const o: Record<string, string> = { path: r.path };\n if (r.stack !== undefined) o.stack = r.stack;\n if (r.account !== undefined) o.account = r.account;\n if (r.region !== undefined) o.region = r.region;\n return o;\n}\n\n/**\n * Union new rules into an existing rule list: dedupe by full identity (path + stack +\n * account + region — so a scoped rule never collides with the unscoped one for the same\n * path), drop already-present ones. APPEND-ONLY: new rules go to the END, existing order\n * untouched. Unlike the baseline (machine-rewritten, so a stable sort keeps its diff\n * clean), ignore.yaml is HAND-CURATED with `#` comments that group and explain rules —\n * re-sorting on every append would shuffle the user's layout and detach those comments.\n * The user owns the order; the verb only appends. Pure + exported — the IO wrapper\n * `addIgnoreRules` is a thin shell over this so the merge logic is unit-tested off disk.\n */\nexport function mergeIgnoreRules(\n existing: IgnoreRuleObject[],\n incoming: IgnoreRuleObject[]\n): { merged: IgnoreRuleObject[]; added: IgnoreRuleObject[]; alreadyPresent: IgnoreRuleObject[] } {\n const have = new Set(existing.map(ruleKey));\n const added: IgnoreRuleObject[] = [];\n const alreadyPresent: IgnoreRuleObject[] = [];\n // dedupe the incoming list against itself too (a stack can surface the same rule twice)\n const seen = new Set<string>();\n for (const rule of incoming) {\n const key = ruleKey(rule);\n if (seen.has(key)) continue;\n seen.add(key);\n if (have.has(key)) alreadyPresent.push(rule);\n else added.push(rule);\n }\n return { merged: [...existing, ...added], added, alreadyPresent };\n}\n\n/**\n * Serialize an append: parse the existing YAML (preserving its comments + layout via the\n * document/CST model), append the new rules to the `ignore` sequence, and re-emit. A fresh\n * file starts from `FILE_HEADER` so a first-time hand-editor sees the shape + the comment\n * convention. Comment-preserving is the whole point of choosing YAML — a naive parse->emit\n * (like `JSON.stringify`) would erase the user's \"why\" comments on every `ignore` run.\n */\nfunction appendRulesToYaml(existingRaw: string | undefined, added: IgnoreRuleObject[]): string {\n const doc: Document =\n existingRaw !== undefined && existingRaw.trim() !== ''\n ? parseDocument(existingRaw)\n : parseDocument(`${FILE_HEADER}ignore:\\n`);\n let seq = doc.get('ignore');\n if (!isSeq(seq)) {\n seq = new YAMLSeq();\n doc.set('ignore', seq);\n }\n for (const rule of added) (seq as YAMLSeq).add(doc.createNode(orderedRule(rule)));\n return doc.toString();\n}\n\n/**\n * Append ignore rules to `.cdkrd/ignore.yaml` (cwd-relative), creating the file (and\n * the `.cdkrd/` dir) if absent. Idempotent: rules already present are reported, not\n * duplicated. Loads through `loadConfig` first so a malformed config fails fast rather\n * than being silently overwritten. Returns the path + what changed so the caller can\n * report it. The only mutating entry point for config (parallel to `writeBaseline`).\n */\nexport async function addIgnoreRules(\n newRules: IgnoreRuleObject[]\n): Promise<{ path: string; added: IgnoreRuleObject[]; alreadyPresent: IgnoreRuleObject[] }> {\n const config = await loadConfig(); // validates first — a malformed file throws, not overwritten\n const { added, alreadyPresent } = mergeIgnoreRules(config.ignore, newRules);\n // Only touch disk when something actually changed — an all-already-present run leaves\n // the file (and its git status) untouched.\n if (added.length > 0) {\n let existingRaw: string | undefined;\n try {\n existingRaw = await readFile(CONFIG_PATH, 'utf8');\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e;\n }\n await mkdir(dirname(CONFIG_PATH), { recursive: true });\n await writeFile(CONFIG_PATH, appendRulesToYaml(existingRaw, added));\n }\n return { path: CONFIG_PATH, added, alreadyPresent };\n}\n\ninterface IgnoreRule {\n raw: string; // human-readable form for the \"ignored by config rule ...\" note\n pathPattern: string; // glob against \"<logicalId>.<path>\" / \"<constructPath>.<path>\"\n stackGlob?: string | undefined; // when set, the rule applies only to stacks whose name matches it\n accountGlob?: string | undefined; // when set, the rule applies only in accounts matching it\n regionGlob?: string | undefined; // when set, the rule applies only in regions matching it\n}\n\n/**\n * Normalize one ignore rule object into a matchable rule. `path` is the pattern; an\n * optional `stack` / `account` / `region` glob scopes it (absent = any). All four reuse\n * the existing `*` / `?` glob. `raw` is a readable rendering for the report's \"ignored by\n * config rule …\" note (a scoped rule shows its scope in parentheses).\n */\nexport function parseIgnoreRule(entry: IgnoreRuleObject): IgnoreRule {\n const scope = [\n entry.stack !== undefined ? `stack:${entry.stack}` : undefined,\n entry.account !== undefined ? `account:${entry.account}` : undefined,\n entry.region !== undefined ? `region:${entry.region}` : undefined,\n ].filter((s): s is string => s !== undefined);\n return {\n raw: scope.length > 0 ? `${entry.path} (${scope.join(', ')})` : entry.path,\n pathPattern: entry.path,\n stackGlob: entry.stack,\n accountGlob: entry.account,\n regionGlob: entry.region,\n };\n}\n\n/**\n * True when `pattern` matches `target` (= \"<logicalId>.<path>\"), either exactly or\n * as a PARENT path: a rule \"X.Policies\" also ignores child paths like\n * \"X.Policies.0.PolicyName\" AND \"X.Policies[MyPol].PolicyName\" (so ignoring a\n * structured property covers its leaves, including array / identity-keyed elements).\n * Parent matching walks ancestors at each `.` OR `[` boundary, combined with the glob.\n */\nfunction pathMatches(pattern: string, target: string): boolean {\n if (matchesPathGlob(pattern, target)) return true;\n // A rule on a PARENT property ignores its whole subtree — including array / identity-\n // keyed children whose path glues the index to its key inside ONE dot-segment\n // (`Policies[MyPol].PolicyName`, `Statement[0].Condition`, `Tags[env]`). Walk ancestor\n // paths by trimming at each `.` OR `[` boundary (not just `.`), so a rule `X.Policies`\n // covers `X.Policies[MyPol].PolicyName` and `X.Statement` covers\n // `X.Statement[0].Condition` — the dot-only split silently failed for bracket children.\n let t = target;\n while (true) {\n const cut = Math.max(t.lastIndexOf('.'), t.lastIndexOf('['));\n if (cut <= 0) break;\n t = t.slice(0, cut);\n if (matchesPathGlob(pattern, t)) return true;\n }\n return false;\n}\n\n/**\n * Re-tag declared/undeclared/added findings that match an ignore rule to the\n * `ignored` tier (informational) — they are SURFACED, never silently dropped,\n * preserving the \"everything is reported\" invariant. `added` (a whole out-of-band\n * resource) is ignorable like declared/undeclared — accepting it is a deliberate\n * decision, symmetric with revert. `deleted` is never ignorable (a path rule must\n * not silence a resource deletion); readGap/unresolved/skipped are already\n * informational and left untouched. Pure: no IO.\n *\n * A rule matches against EITHER `<logicalId>.<path>` OR (when present)\n * `<constructPath>.<path>`, so both styles work:\n * - logicalId (`ApiRole1234ABCD.Policies`) is the CloudFormation template's resource\n * key — ALWAYS present, so a rule keyed on it works on ANY stack, CDK or not.\n * This is what makes ignore rules usable on non-CDK / raw-CloudFormation stacks.\n * - constructPath (`MyStack/ApiRole.Policies`) is the human-friendly path, the same\n * id `cdk-local` uses for targeting. It comes from optional `aws:cdk:path`\n * Metadata (absent on non-CDK stacks, disableable on CDK ones), so it is offered\n * as an ADDITIONAL match target, never the only one — a rule written against it\n * keeps working on CDK stacks while logicalId covers everything else.\n *\n * A scoped object rule additionally gates on `stack` / `account` / `region` globs (absent\n * = any) — the baseline file's three identity axes. `account` and `region` are independent\n * axes from the stack name: the same stack can be deployed to multiple accounts and/or\n * regions (or be matched by a `*` stack glob), and a property may legitimately drift in only\n * one — so the caller passes the current env via `scope`. Without `account`, a\n * `stack: \"Prod*\"` rule would leak into a same-named stack in another account.\n *\n * `scope` is an OBJECT, not positional args: `accountId` and `region` are both strings on\n * adjacent axes, so a positional `(…, accountId, region, …)` signature invites a silent\n * transposition at the 11 call sites (the compiler can't tell two strings apart). The named\n * `{ stackName, accountId, region }` makes a swap a compile error and self-documents intent.\n */\nexport interface IgnoreScope {\n stackName: string;\n accountId: string;\n region: string;\n}\n\nexport function applyIgnores(\n findings: Finding[],\n scope: IgnoreScope,\n config: CdkrdConfig\n): Finding[] {\n if (config.ignore.length === 0) return findings;\n const { stackName, accountId, region } = scope;\n const rules = config.ignore.map(parseIgnoreRule);\n return findings.map((f) => {\n if (f.tier !== 'declared' && f.tier !== 'undeclared' && f.tier !== 'added') return f;\n // A whole-resource `added` finding has an empty path, so omit the `.<path>` suffix:\n // the rule target is then just the id, matching ignoreRuleFor's empty-path form\n // (a trailing dot would only match via the parent-segment fallback — fragile).\n const suffix = f.path ? `.${f.path}` : '';\n const targets = [`${f.logicalId}${suffix}`];\n if (f.constructPath) {\n // The within-stack path is what the report shows and what `ignoreRuleFor` now writes;\n // the FULL construct path is kept too so rules authored before the strip (or a\n // Stage's full `dev-main/AuroraDB/...` form) still match. When there is no stack\n // prefix to strip, both are identical — a harmless duplicate (`some` short-circuits).\n targets.push(`${withinStackPath(f.constructPath, stackName)}${suffix}`);\n targets.push(`${f.constructPath}${suffix}`);\n }\n const hit = rules.find(\n (r) =>\n (r.stackGlob === undefined || matchesGlob(r.stackGlob, stackName)) &&\n (r.accountGlob === undefined || matchesGlob(r.accountGlob, accountId)) &&\n (r.regionGlob === undefined || matchesGlob(r.regionGlob, region)) &&\n targets.some((t) => pathMatches(r.pathPattern, t))\n );\n if (!hit) return f;\n // Clear the `unrecorded` flag (set by applyBaseline for a not-yet-recorded\n // undeclared/added value): an `ignored` finding is a DECIDED value — the user told\n // cdkrd to STOP reporting it — so it must not still surface under `[Potential Drift]`\n // nor nag \"run cdkrd record\" (report/stack-actions filter that section by the FLAG,\n // not the tier). This upholds the `record` vs `ignore` invariant (ignore stops\n // watching). The exit code was always safe (ignored is not a drift tier); this fixes\n // the spurious reporting that defeated the purpose of `ignore`.\n const { unrecorded: _unrecorded, ...rest } = f;\n return { ...rest, tier: 'ignored', note: `ignored by config rule \"${hit.raw}\"` };\n });\n}\n","// Resolve the CDK app: explicit value (already covers --app + $CDKRD_APP via\n// cli-args) → cdk.json \"app\". Mirrors cdk-local's resolveApp precedence.\nimport { existsSync, readFileSync } from 'node:fs';\n\nexport function resolveApp(explicit: string | undefined): string | undefined {\n if (explicit) return explicit;\n try {\n if (existsSync('cdk.json')) {\n const json = JSON.parse(readFileSync('cdk.json', 'utf8')) as { app?: unknown };\n if (typeof json.app === 'string' && json.app.length > 0) return json.app;\n }\n } catch {\n /* unreadable cdk.json → no app */\n }\n return undefined;\n}\n","// IoHost for toolkit-lib synth. Two jobs:\n// 1. Drop toolkit-lib's own info/debug/trace chatter so synth does not pollute\n// cdkrd's drift output (warnings + real errors still surface).\n// 2. Render the CDK app subprocess's OWN output in the default color.\n//\n// toolkit-lib's source-builder relays the app subprocess stdout as\n// `CDK_ASSEMBLY_I1001` and its stderr as `CDK_ASSEMBLY_E1002`. The stderr one is\n// tagged at ERROR level, so the default NonInteractiveIoHost prints it in red — but\n// bundlers (esbuild / tsc / pip / docker, …) write ordinary progress (\"Bundling\n// asset …\", file-size tables) to stderr, so red is misleading and alarming. We\n// re-tag both passthrough codes to INFO so they print in the default color, matching\n// cdk-local. A genuine synth failure still surfaces: the subprocess exits non-zero,\n// toolkit-lib throws, and cdkrd's own error handling reports it (a different path\n// from these per-line E1002 passthrough messages).\nimport { NonInteractiveIoHost } from '@aws-cdk/toolkit-lib';\nimport type { IoMessage } from '@aws-cdk/toolkit-lib';\n\ntype Level = IoMessage<unknown>['level'];\n\n// CDK app subprocess passthrough message codes (toolkit-lib source-builder.ts).\nconst APP_STDOUT = 'CDK_ASSEMBLY_I1001';\nconst APP_STDERR = 'CDK_ASSEMBLY_E1002';\n\nexport type IoPlan = { action: 'drop' } | { action: 'emit'; level: Level };\n\n/**\n * Decide what QuietIoHost does with a message (pure, so it is unit-testable):\n * - the CDK app's own stdout/stderr passthrough -> emit at INFO (default color, like\n * cdk-local; never the alarming red the E1002/error tag would otherwise produce);\n * - a real toolkit warning / error -> emit unchanged (still yellow / red);\n * - everything else (toolkit info/debug/trace chatter) -> drop.\n */\nexport function planIoMessage(msg: Pick<IoMessage<unknown>, 'code' | 'level'>): IoPlan {\n if (msg.code === APP_STDOUT || msg.code === APP_STDERR) return { action: 'emit', level: 'info' };\n if (msg.level === 'warn' || msg.level === 'error') return { action: 'emit', level: msg.level };\n return { action: 'drop' };\n}\n\nexport class QuietIoHost extends NonInteractiveIoHost {\n override async notify(msg: IoMessage<unknown>): Promise<void> {\n const plan = planIoMessage(msg);\n if (plan.action === 'drop') return;\n return super.notify(plan.level === msg.level ? msg : { ...msg, level: plan.level });\n }\n}\n","// Synthesize a CDK app via @aws-cdk/toolkit-lib (the same dependency cdk-local\n// uses) to discover stacks. Records a CDK app COMMAND (`node app.js`) or a\n// pre-synthesized cloud-assembly DIRECTORY (`cdk.out`). Drift detection itself\n// does not need this — it is used for stack auto-discovery (and later clobber).\nimport { existsSync, statSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { BaseCredentials, CdkAppMultiContext, Toolkit } from '@aws-cdk/toolkit-lib';\nimport { QuietIoHost } from './io-host.js';\n\nexport interface SynthOptions {\n region?: string | undefined;\n profile?: string | undefined;\n context?: Record<string, string>;\n}\n\nexport interface SynthStack {\n stackName: string;\n region: string | undefined; // the stack's own env.region (concrete) — for per-stack drift reads\n template: Record<string, unknown>;\n}\n\nconst CONCRETE_REGION = /^[a-z]{2}-[a-z]+-\\d+$/;\n\nexport async function synthApp(app: string, opts: SynthOptions = {}): Promise<SynthStack[]> {\n const { region, profile, context = {} } = opts;\n const toolkit = new Toolkit({\n ioHost: new QuietIoHost(),\n sdkConfig: {\n baseCredentials: BaseCredentials.awsCliCompatible({\n ...(region && { defaultRegion: region }),\n ...(profile && { profile }),\n }),\n },\n });\n\n const p = resolve(app);\n const isDir = existsSync(p) && statSync(p).isDirectory();\n let source;\n if (isDir) {\n // pre-synthesized assembly: no subprocess to feed region/profile/context to\n source = await toolkit.fromAssemblyDirectory(p, { failOnMissingContext: false });\n } else {\n const hasOverrides = Object.keys(context).length > 0;\n // feed the app subprocess the same region/profile the user gave so `this.region`\n // / env-based credential lookups resolve as they would under `cdk` (cdk-local).\n const env: Record<string, string> = {};\n if (region) {\n env.AWS_REGION = region;\n env.CDK_DEFAULT_REGION = region;\n }\n if (profile) env.AWS_PROFILE = profile;\n source = await toolkit.fromCdkApp(app, {\n ...(Object.keys(env).length > 0 && { env }),\n // CdkAppMultiContext reads cdk.json / cdk.context.json / ~/.cdk.json as the\n // base layer; our -c/--context overrides win on top (mirrors cdk CLI).\n ...(hasOverrides && { contextStore: new CdkAppMultiContext(process.cwd(), context) }),\n });\n }\n\n const cached = await toolkit.synth(source);\n try {\n // `stacksRecursively` (NOT `stacks`): `stacks` returns only the TOP-LEVEL\n // assembly's stacks, so every stack nested inside a CDK `Stage` (the CDK\n // Pipelines / multi-env pattern) is silently invisible — never discovered, never\n // checked, with no error. `stacksRecursively` descends into nested assemblies and\n // is a SUPERSET of `stacks`, so a non-staged app is unaffected. `s.stackName` is\n // the deployed CloudFormation stack name (CDK stage-qualifies it), which is the\n // correct live-read target.\n return cached.cloudAssembly.stacksRecursively.map((s) => ({\n stackName: s.stackName,\n region: CONCRETE_REGION.test(s.environment.region) ? s.environment.region : undefined,\n template: s.template as Record<string, unknown>,\n }));\n } finally {\n await cached.dispose();\n }\n}\n\nexport interface DiscoveredStack {\n stackName: string;\n region: string | undefined; // the stack's own env.region, when concrete\n // the synthesized template — carried through so the check path can recover GetTemplate's\n // `?`-masked non-ASCII literals from it without re-synthesizing (synthApp already built it).\n template: Record<string, unknown>;\n}\n\n/** Synth and return each stack's name + its own (concrete) region + template, for discovery. */\nexport async function discoverStacks(\n app: string,\n opts: SynthOptions = {}\n): Promise<DiscoveredStack[]> {\n return (await synthApp(app, opts)).map((s) => ({\n stackName: s.stackName,\n region: s.region,\n template: s.template,\n }));\n}\n","// Resolve which stacks a command operates on, each with the region to query it in.\n// cdkrd is CDK-only: it ALWAYS resolves a CDK app (synth, or a pre-synthesized\n// `cdk.out` assembly via `--app`) and operates on the stacks that app defines —\n// there is no \"check an arbitrary deployed CloudFormation stack by name\" mode. The\n// drift comparison still reads each stack's DEPLOYED template + live state from AWS\n// (reality vs intent); the app is used only to discover stack names + their regions\n// (and, downstream, construct-path display).\n//\n// no positional args → every stack the app defines, each in its OWN env.region\n// (env-agnostic stacks fall back to --region / $AWS_REGION,\n// then the active profile's configured region)\n// <stack>... positional → exact names must exist in the app; a name with a glob\n// char (`*`/`?`) is matched against the app's stack names\nimport { CloudControlClient } from '@aws-sdk/client-cloudcontrol';\nimport type { CommonArgs } from '../cli-args.js';\nimport { resolveApp } from '../synth/resolve-app.js';\nimport { discoverStacks } from '../synth/synth.js';\nimport { isGlob, matchesGlob } from './glob-match.js';\n\n// Resolve the region the AWS SDK would use for the active profile (the `region`\n// set for that profile in ~/.aws/config). Used as the LAST region fallback for an\n// env-agnostic CDK stack — one with no `env` on the stack and no --region /\n// $AWS_REGION — so it still has a region to query instead of erroring. Reads the\n// shared config only (no network call) and returns undefined if the profile sets\n// no region. AWS_PROFILE is already exported into the environment by the calling\n// command, so the SDK's region provider chain selects the right profile even when\n// `profile` is undefined here (e.g. $AWS_PROFILE was used instead of --profile).\nexport async function resolveProfileRegion(\n profile: string | undefined\n): Promise<string | undefined> {\n try {\n const client = new CloudControlClient(profile ? { profile } : {});\n const region = await client.config.region();\n client.destroy();\n return typeof region === 'string' && region.length > 0 ? region : undefined;\n } catch {\n return undefined; // the SDK throws \"Region is missing\" when nothing resolves\n }\n}\n\nexport interface ResolvedStack {\n stackName: string;\n region: string | undefined; // region to query this stack in (may be undefined → caller errors)\n // the synthesized template for this stack — used by check to recover GetTemplate's\n // `?`-masked non-ASCII literals. Carried from the same synth that discovered the stack.\n template: Record<string, unknown>;\n}\n\nexport async function resolveStacks(a: CommonArgs): Promise<ResolvedStack[]> {\n const app = resolveApp(a.app);\n if (!app) {\n throw new Error(\n 'cdkrd needs a CDK app: run in a directory with cdk.json, pass --app \"<cmd>\" or --app <cdk.out> (a pre-synthesized assembly), or set $CDKRD_APP'\n );\n }\n const discovered = await discoverStacks(app, {\n region: a.region,\n profile: a.profile,\n context: a.context,\n });\n\n // Region fallback chain for an env-agnostic stack (no `env` on the stack): an\n // explicit --region / $AWS_REGION (`a.region`) first, then the active AWS\n // profile's configured region. Resolve the profile region only when it is\n // actually needed — no explicit region AND at least one discovered stack lacks\n // its own — so a fully-region-pinned app makes no extra config read.\n let fallbackRegion = a.region;\n if (!fallbackRegion && discovered.some((s) => !s.region)) {\n fallbackRegion = await resolveProfileRegion(a.profile);\n // Backfill so EVERY downstream `?? a.region` site (notably check's --pre-deploy\n // synthTemplates keying) resolves an env-agnostic stack to the same region the\n // loop queries it in — otherwise the synthKey would mismatch and the stack would\n // wrongly read as \"not in the synth output\".\n a.region = fallbackRegion;\n }\n\n // --all, or no names → every stack the app defines. --all is the explicit form of the\n // no-argument default; it also overrides any positional names (target everything).\n if (a.all || a.stackNames.length === 0) {\n return discovered.map((s) => ({\n stackName: s.stackName,\n region: s.region ?? fallbackRegion,\n template: s.template,\n }));\n }\n\n // names (exact and/or glob) matched against the app's stacks\n const seen = new Set<string>();\n const out: ResolvedStack[] = [];\n const add = (\n stackName: string,\n region: string | undefined,\n template: Record<string, unknown>\n ): void => {\n const key = `${stackName}\\0${region ?? ''}`;\n if (seen.has(key)) return;\n seen.add(key);\n out.push({ stackName, region, template });\n };\n const known = (): string => discovered.map((s) => s.stackName).join(', ') || 'none';\n for (const name of a.stackNames) {\n if (isGlob(name)) {\n for (const s of discovered) {\n if (matchesGlob(name, s.stackName))\n add(s.stackName, s.region ?? fallbackRegion, s.template);\n }\n } else {\n const hit = discovered.find((s) => s.stackName === name);\n if (!hit)\n throw new Error(`stack \"${name}\" is not defined by the CDK app (found: ${known()})`);\n add(hit.stackName, hit.region ?? fallbackRegion, hit.template);\n }\n }\n if (out.length === 0) {\n throw new Error(`no stacks match ${a.stackNames.join(', ')} (found: ${known()})`);\n }\n return out;\n}\n","// Minimal CloudFormation intrinsic resolver for declared-property comparison.\n// Resolves Ref / Fn::Sub / Fn::If (+ condition eval) / Fn::Join / Fn::Select /\n// Fn::FindInMap / Fn::Split / Fn::ImportValue (exports prefetched by loadDesired).\n// Fn::GetAtt resolves to UNRESOLVED (needs live attributes) so callers skip that\n// path rather than report false drift. AWS::NoValue resolves to NOVALUE so callers\n// can prune it. (Will be swapped for cdkd's full IntrinsicFunctionResolver later.)\nimport type { ResolverContext } from '../types.js';\n\nexport const UNRESOLVED = Symbol('unresolved');\nexport const NOVALUE = Symbol('novalue');\n\n// CloudFormation dynamic-reference pattern: `{{resolve:<service>:<reference-key>}}`\n// where <service> is one of ssm / ssm-secure / secretsmanager. These are resolved by\n// CFn at deploy time to a live SSM/Secrets value, so a declared scalar carrying the\n// raw token can never equal the resolved live value — it must be treated as\n// UNRESOLVED. Anchored to the whole string so an arbitrary value that merely contains\n// the substring is not swallowed (a genuine declared value is never muted by accident).\nconst DYNAMIC_REFERENCE_RE = /^\\{\\{resolve:(ssm|ssm-secure|secretsmanager):[\\s\\S]+\\}\\}$/;\nexport function isDynamicReference(v: string): boolean {\n return DYNAMIC_REFERENCE_RE.test(v);\n}\n\n// A value safe to interpolate into a joined / substituted STRING: a primitive\n// (string / number / boolean). A symbol (UNRESOLVED / NOVALUE) or an object / array\n// means resolution was incomplete (a deep GetAtt) or the template is malformed —\n// fail closed to UNRESOLVED rather than leak `[object Object]` / `Symbol(unresolved)`\n// into the declared value, which would then mis-compare as false drift. (`Fn::Join`\n// filters NOVALUE out of the list FIRST, so its remaining non-scalar parts are the\n// genuinely-unresolved ones.)\nfunction isScalarInterpolant(v: unknown): boolean {\n const t = typeof v;\n return t === 'string' || t === 'number' || t === 'boolean';\n}\n\nexport function resolve(node: unknown, ctx: ResolverContext): unknown {\n if (Array.isArray(node)) return node.map((n) => resolve(n, ctx));\n // A CloudFormation DYNAMIC REFERENCE (`{{resolve:ssm:…}}`,\n // `{{resolve:ssm-secure:…}}`, `{{resolve:secretsmanager:…}}`) is a deploy-time\n // string substitution: CFn replaces it with the live SSM parameter / secret value\n // while creating the resource, so the deployed template still carries the literal\n // `{{resolve:…}}` token but the live resource holds the resolved value (e.g. an\n // RDS MasterUsername declared as `{{resolve:secretsmanager:…:username::}}` reads\n // back as `admin`). cdkrd cannot — and must not — fetch the secret to resolve it,\n // so the declared side is unknowable: mark UNRESOLVED so the path is skipped, the\n // same fail-closed treatment as Fn::GetAtt, never reported as false drift.\n if (typeof node === 'string' && isDynamicReference(node)) return UNRESOLVED;\n if (node === null || typeof node !== 'object') return node;\n const obj = node as Record<string, unknown>;\n const keys = Object.keys(obj);\n if (keys.length === 1) {\n const k = keys[0]!;\n const v = obj[k];\n switch (k) {\n case 'Ref':\n return resolveRef(String(v), ctx);\n case 'Fn::Sub':\n return resolveSub(v, ctx);\n case 'Fn::Base64': {\n // Fn::Base64 returns the base64 encoding of its (String) argument — a pure,\n // deterministic, environment-INDEPENDENT transform (unlike Fn::GetAZs, which\n // is deliberately left unresolved). CDK emits it for EC2 UserData\n // (`{ \"Fn::Base64\": { \"Fn::Sub\": \"#!/bin/bash …\" } }`), which is a readable,\n // mutable property on AWS::EC2::Instance / the LaunchTemplate's\n // LaunchTemplateData — so without resolving it the declared UserData is a blind\n // spot (UNRESOLVED) and out-of-band UserData drift is missed. Resolve the inner\n // first; CFn only accepts a String argument, so a non-string (or unresolved)\n // inner fails closed to UNRESOLVED rather than encoding `[object Object]`.\n const inner = resolve(v, ctx);\n if (typeof inner !== 'string') return UNRESOLVED;\n return Buffer.from(inner, 'utf8').toString('base64');\n }\n case 'Fn::If': {\n if (!Array.isArray(v)) return UNRESOLVED;\n const [cond, t, f] = v as [string, unknown, unknown];\n const c = evalCondition(String(cond), ctx);\n // Fail-closed: if the condition can't be cleanly evaluated, do NOT guess a\n // branch (a wrong branch silently produces false drift) — mark unresolved.\n if (c === UNRESOLVED) return UNRESOLVED;\n return c ? resolve(t, ctx) : resolve(f, ctx);\n }\n case 'Fn::Join': {\n if (!Array.isArray(v)) return UNRESOLVED;\n const [delim, list] = v as [string, unknown];\n const resolved = resolve(list, ctx);\n if (!Array.isArray(resolved)) return UNRESOLVED;\n const parts = resolved.filter((p) => p !== NOVALUE);\n // Any non-scalar remaining part (the UNRESOLVED symbol, OR a nested\n // object/array that leaked from a deep unresolved GetAtt / malformed list)\n // means we cannot faithfully join — fail closed rather than String()-leak.\n if (parts.some((p) => !isScalarInterpolant(p))) return UNRESOLVED;\n const joined = parts.join(delim);\n // CDK frequently ASSEMBLES a dynamic reference with Fn::Join (e.g. an RDS\n // MasterUsername = Join(\"\", [\"{{resolve:secretsmanager:\", Ref(secret),\n // \":SecretString:username::}}\"])); once joined the result is a deploy-time\n // dynamic reference cdkrd cannot resolve — UNRESOLVED, never false drift.\n return isDynamicReference(joined) ? UNRESOLVED : joined;\n }\n case 'Fn::Select': {\n if (!Array.isArray(v)) return UNRESOLVED;\n const [idxRaw, list] = v as [unknown, unknown];\n const arr = resolve(list, ctx);\n if (!Array.isArray(arr)) return UNRESOLVED;\n // The index may itself be an intrinsic (CFn allows e.g. { Ref: SomeParam } /\n // Fn::FindInMap as the index) — resolve it before coercing. (Number() on the\n // raw UNRESOLVED symbol would throw, so guard it first.)\n const idx = resolve(idxRaw, ctx);\n if (idx === UNRESOLVED) return UNRESOLVED;\n const i = Number(idx);\n // Fail-closed: out-of-range index (or a NaN index) would otherwise yield\n // `undefined` and report false `desired: undefined` drift. The selected\n // element itself being UNRESOLVED also propagates.\n if (!Number.isInteger(i) || i < 0 || i >= arr.length) return UNRESOLVED;\n const sel = arr[i];\n return sel === UNRESOLVED ? UNRESOLVED : sel;\n }\n case 'Fn::FindInMap': {\n if (!Array.isArray(v) || v.length < 3) return UNRESOLVED;\n const [mapName, topKey, secondKey] = v.slice(0, 3).map((x) => resolve(x, ctx));\n // All 3 keys must resolve to strings and the path must exist; else fail-closed.\n if (\n typeof mapName !== 'string' ||\n typeof topKey !== 'string' ||\n typeof secondKey !== 'string'\n )\n return UNRESOLVED;\n const val = ctx.mappings?.[mapName]?.[topKey]?.[secondKey];\n if (val !== undefined) return val;\n // CFn supports an optional 4th argument — { DefaultValue: ... } — returned when\n // the map path is absent. Honor it so a declared default is still compared (else\n // a knowable declared value is silently dropped to UNRESOLVED = missed drift).\n const fourth = v[3];\n if (\n fourth !== null &&\n typeof fourth === 'object' &&\n !Array.isArray(fourth) &&\n 'DefaultValue' in fourth\n ) {\n const def = resolve((fourth as Record<string, unknown>).DefaultValue, ctx);\n return def === UNRESOLVED ? UNRESOLVED : def;\n }\n return UNRESOLVED;\n }\n case 'Fn::Split': {\n if (!Array.isArray(v) || v.length < 2) return UNRESOLVED;\n const delim = v[0];\n const src = resolve(v[1], ctx);\n if (typeof delim !== 'string' || typeof src !== 'string') return UNRESOLVED;\n return src.split(delim);\n }\n case 'Fn::ImportValue': {\n const name = resolve(v, ctx);\n if (typeof name !== 'string') return UNRESOLVED;\n // Prefetched exports (see loadDesired); absent name -> fail-closed.\n return name in ctx.exports ? ctx.exports[name] : UNRESOLVED;\n }\n case 'Fn::GetAtt':\n return resolveGetAtt(v, ctx);\n case 'Fn::Equals': {\n if (!Array.isArray(v)) return UNRESOLVED;\n const [a, b] = v.map((x) => resolve(x, ctx));\n if (a === UNRESOLVED || b === UNRESOLVED) return UNRESOLVED; // fail-closed\n return scalarEqual(a, b);\n }\n case 'Fn::And': {\n if (!Array.isArray(v)) return UNRESOLVED;\n const rs = v.map((c) => condVal(c, ctx));\n if (rs.some((r) => r === UNRESOLVED)) return UNRESOLVED;\n return rs.every((r) => r === true);\n }\n case 'Fn::Or': {\n if (!Array.isArray(v)) return UNRESOLVED;\n const rs = v.map((c) => condVal(c, ctx));\n if (rs.some((r) => r === UNRESOLVED)) return UNRESOLVED;\n return rs.some((r) => r === true);\n }\n case 'Fn::Not': {\n if (!Array.isArray(v)) return UNRESOLVED;\n const r = condVal(v[0], ctx);\n return r === UNRESOLVED ? UNRESOLVED : !r;\n }\n case 'Condition':\n return evalCondition(String(v), ctx);\n default:\n // Any intrinsic we don't fully resolve → UNRESOLVED, so the declared\n // path is skipped (never reported as false drift).\n if (k.startsWith('Fn::')) return UNRESOLVED;\n break;\n }\n }\n const out: Record<string, unknown> = {};\n for (const [kk, vv] of Object.entries(obj)) out[kk] = resolve(vv, ctx);\n return out;\n}\n\nfunction scalarEqual(a: unknown, b: unknown): boolean {\n if (Array.isArray(a) || Array.isArray(b)) return JSON.stringify(a) === JSON.stringify(b);\n if (a === b) return true;\n // CloudFormation evaluates `Fn::Equals` as a STRING comparison. A Number/Boolean\n // template Parameter is carried as a string by buildResolverContext (params are\n // stringified), so `Fn::Equals[{Ref: MaxAZs=\"2\"}, 2]` (literal NUMBER) must be TRUE,\n // and `[{Ref: Enabled=\"true\"}, true]` TRUE — else the WRONG `Fn::If` branch bakes a\n // corrupted declared value into the diff (a phantom FP, or a hidden FN), and this\n // operator is fail-OPEN unlike the rest of the resolver. Coerce string<->number/\n // boolean via exact String() match (CFn does NOT fold \"2.0\"==2 in Equals, so no\n // numeric-format folding here); genuine inequality still differs.\n const prim = (x: unknown): x is number | boolean =>\n typeof x === 'number' || typeof x === 'boolean';\n if ((typeof a === 'string' && prim(b)) || (typeof b === 'string' && prim(a))) {\n return String(a) === String(b);\n }\n return false;\n}\n\n// Evaluate a condition operand to true | false | UNRESOLVED (fail-closed).\nfunction condVal(node: unknown, ctx: ResolverContext): boolean | typeof UNRESOLVED {\n if (node && typeof node === 'object' && 'Condition' in (node as object)) {\n const r = evalCondition(String((node as Record<string, unknown>)['Condition']), ctx);\n return r === UNRESOLVED ? UNRESOLVED : r === true;\n }\n const r = resolve(node, ctx);\n if (r === true) return true;\n if (r === false) return false;\n return UNRESOLVED;\n}\n\nexport function evalCondition(name: string, ctx: ResolverContext): boolean | typeof UNRESOLVED {\n if (ctx.condCache.has(name)) return ctx.condCache.get(name) as boolean | typeof UNRESOLVED;\n // Seed the cache with UNRESOLVED BEFORE recursing: a condition that references\n // itself (directly, or via a cycle A→B→A through a `{Condition: …}` operand) would\n // otherwise recurse forever and hang `cdkrd check`. CloudFormation rejects circular\n // conditions at deploy time, so a DEPLOYED template can't carry one — but a\n // `--pre-deploy` synth template is unvalidated and a hand-rolled `--app` output\n // could. Failing closed to UNRESOLVED on the cycle is the safe direction (the\n // dependent Fn::If branch is then skipped, never mis-evaluated).\n ctx.condCache.set(name, UNRESOLVED);\n const r = resolve(ctx.conditions[name], ctx);\n const val = r === true ? true : r === false ? false : UNRESOLVED;\n ctx.condCache.set(name, val);\n return val;\n}\n\n// A GetAtt attribute that MIRRORS a declared property of the referenced resource:\n// `<resourceType> -> { <getAttAttrName>: <declaredPropertyKey> }`. Such an attribute is\n// fully controlled by the template, so its INTENT is the declared property's value, not\n// the live value. Resolving it against the live model lets an out-of-band change to the\n// referenced resource cascade into PHANTOM drift on every consumer that interpolates the\n// attribute into one of its OWN declared properties — e.g. renaming a Cognito\n// IdentityPool in the console makes the readOnly `Name` GetAtt resolve to the new name,\n// which CDK bakes into each authenticated/unauthenticated Role `Description`\n// (\"Default … Role for Identity Pool ${IdPool.Name}\"), so the Roles falsely report\n// declared drift even though their live Description (frozen at create time) never\n// changed. Resolving from the declared `IdentityPoolName` instead keeps intent == the\n// real (unchanged) value. Curated, not derived: only listed (type, attr) pairs whose\n// attribute is genuinely a declared property — a runtime-only attribute (ARN, Id,\n// Endpoint) has no declared source and must stay live.\nconst GETATT_DECLARED_PROPERTY: Record<string, Record<string, string>> = {\n 'AWS::Cognito::IdentityPool': { Name: 'IdentityPoolName' },\n};\n\n// Resolve Fn::GetAtt against the referenced resource's LIVE model (ctx.liveAttrs),\n// NOT a guessed ARN format. `[LogicalId, AttrName]`; AttrName may be dotted\n// (e.g. \"Endpoint.Address\"). Returns the live attribute value, or UNRESOLVED\n// (fail-closed) when the target wasn't read or the attribute is absent — so a\n// missing live read never fabricates a value or reports false drift. Comparing a\n// GetAtt against the target's CURRENT attribute is still real drift detection on\n// the CONSUMING resource (does it actually point at that attribute's value?).\nexport function resolveGetAtt(v: unknown, ctx: ResolverContext): unknown {\n if (!Array.isArray(v) || v.length < 2) return UNRESOLVED;\n const logicalId = String(v[0]);\n const attr = String(v[1]);\n // When the attribute mirrors a declared property, prefer the template-declared value\n // (intent) over the live value, so out-of-band drift on the referenced resource does\n // not cascade into phantom drift on consumers. Fall through to live when the declared\n // property is absent or itself does not statically resolve to a scalar.\n const type = ctx.typeOf?.[logicalId];\n const declaredKey = type ? GETATT_DECLARED_PROPERTY[type]?.[attr] : undefined;\n if (declaredKey !== undefined) {\n const rawProps = ctx.declaredRawProps?.[logicalId];\n if (rawProps && declaredKey in rawProps) {\n const declared = resolve(rawProps[declaredKey], ctx);\n if (declared !== UNRESOLVED && declared !== NOVALUE && isScalarInterpolant(declared))\n return declared;\n }\n }\n const model = ctx.liveAttrs[logicalId];\n if (!model) return UNRESOLVED;\n const got = getPath(model, attr.split('.'));\n return got === undefined ? UNRESOLVED : got;\n}\n\nfunction getPath(obj: Record<string, unknown>, segs: string[]): unknown {\n let node: unknown = obj;\n for (const s of segs) {\n if (node === null || typeof node !== 'object') return undefined;\n node = (node as Record<string, unknown>)[s];\n }\n return node;\n}\n\nexport function resolveRef(name: string, ctx: ResolverContext): unknown {\n if (name in ctx.pseudo) return ctx.pseudo[name];\n if (name === 'AWS::NoValue') return NOVALUE;\n if (name in ctx.params) return ctx.params[name];\n if (name in ctx.physIds) return ctx.physIds[name];\n return UNRESOLVED;\n}\n\nexport function resolveSub(v: unknown, ctx: ResolverContext): unknown {\n let tmpl: string;\n let vars: Record<string, unknown> = {};\n if (typeof v === 'string') tmpl = v;\n else {\n const arr = v as [string, Record<string, unknown>];\n tmpl = arr[0];\n vars = arr[1] ?? {};\n }\n let unresolved = false;\n const out = tmpl.replace(/\\$\\{([^}]+)\\}/g, (_m, ref: string) => {\n // ${!Literal} is the CFn escape for a literal \"${Literal}\" — emit verbatim,\n // do NOT attempt resolution.\n if (ref.startsWith('!')) return `\\${${ref.slice(1)}}`;\n if (ref in vars) {\n const r = resolve(vars[ref], ctx);\n // Mirror the Ref / GetAtt branches below: a non-scalar resolution (UNRESOLVED,\n // NOVALUE, or a leaked object/array) cannot be interpolated — fail closed\n // instead of injecting `Symbol(novalue)` / `[object Object]` into the string.\n if (!isScalarInterpolant(r)) {\n unresolved = true;\n return '';\n }\n return String(r);\n }\n if (ref.includes('.')) {\n // ${LogicalId.Attr} GetAtt form — resolve against live attributes.\n const dot = ref.indexOf('.');\n const r = resolveGetAtt([ref.slice(0, dot), ref.slice(dot + 1)], ctx);\n // A non-scalar resolution can't be interpolated: an object GetAtt attribute\n // (`${DB.Endpoint}` = {Address,Port}) would leak `[object Object]`, an array\n // (a `CommaDelimitedList` Ref / `Fn::Split` value) the JS comma-join — either a\n // bogus declared value the diff then reports as drift on a clean stack. Fail\n // closed, mirroring the `vars` branch above (isScalarInterpolant is also false\n // for the UNRESOLVED / NOVALUE symbols, so it subsumes that earlier check).\n if (!isScalarInterpolant(r)) {\n unresolved = true;\n return '';\n }\n return String(r);\n }\n const r = resolveRef(ref, ctx);\n if (!isScalarInterpolant(r)) {\n unresolved = true;\n return '';\n }\n return String(r);\n });\n if (unresolved) return UNRESOLVED;\n // an Fn::Sub may also ASSEMBLE a dynamic reference (`{{resolve:…}}`) — the\n // assembled token is deploy-time-resolved and unknowable, so UNRESOLVED.\n return isDynamicReference(out) ? UNRESOLVED : out;\n}\n\nexport function hasUnresolved(v: unknown): boolean {\n if (v === UNRESOLVED) return true;\n if (Array.isArray(v)) return v.some(hasUnresolved);\n if (v && typeof v === 'object') return Object.values(v).some(hasUnresolved);\n return false;\n}\n\nexport function pruneNoValue(v: unknown): unknown {\n if (Array.isArray(v)) return v.filter((x) => x !== NOVALUE).map(pruneNoValue);\n if (v && typeof v === 'object') {\n const out: Record<string, unknown> = {};\n for (const [k, val] of Object.entries(v)) {\n if (val === NOVALUE) continue;\n out[k] = pruneNoValue(val);\n }\n return out;\n }\n return v;\n}\n\n/** resolve + prune NoValue, returning a property bag ready for classification. */\nexport function resolveProperties(\n props: Record<string, unknown>,\n ctx: ResolverContext\n): Record<string, unknown> {\n return pruneNoValue(resolve(props, ctx)) as Record<string, unknown>;\n}\n","// Golden-corpus recording (R63). The normalize→classify pipeline is pure, so a\n// resource's classification is fully determined by (resolved declared, raw live\n// model, schema info, classify opts). Recording those four during a REAL gather\n// turns every dogfood / integ run into permanent offline regression coverage:\n// the replay test (tests/corpus-replay.test.ts) re-runs `classifyResource` on\n// every committed case in tests/corpus/ and asserts the findings byte-for-byte\n// — no AWS, runs in CI on every push.\n//\n// Recording is opt-in: `CDKRD_CORPUS_DIR=<dir> cdkrd check ...` writes one JSON\n// case per readable resource. Account ids are sanitized automatically\n// (replaced with 111111111111 EVERYWHERE, so ARN-identity suppression still\n// replays identically); resource/stack NAMES are NOT — review a recording\n// before committing it, and never commit cases recorded from confidential\n// stacks (integ fixtures use fictional names and are always safe).\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { UNRESOLVED } from '../normalize/intrinsic-resolver.js';\nimport type { DesiredResource, Finding, SchemaInfo } from '../types.js';\n\nexport const CORPUS_DIR_ENV = 'CDKRD_CORPUS_DIR';\n\n// The UNRESOLVED marker is a Symbol (not JSON-serializable); a recorded declared\n// model swaps it for this sentinel string, and replay swaps it back — otherwise\n// JSON.stringify would silently DROP the key and the replayed classification\n// would diverge from the live one (no `unresolved` finding).\nexport const UNRESOLVED_SENTINEL = '__cdkrd_corpus_unresolved__';\n\nfunction swapUnresolved(v: unknown, from: unknown, to: unknown): unknown {\n if (v === from) return to;\n if (Array.isArray(v)) return v.map((x) => swapUnresolved(x, from, to));\n if (v && typeof v === 'object')\n return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, swapUnresolved(x, from, to)]));\n return v;\n}\n\nexport function encodeUnresolved<T>(v: T): T {\n return swapUnresolved(v, UNRESOLVED, UNRESOLVED_SENTINEL) as T;\n}\n\nexport function decodeUnresolved<T>(v: T): T {\n return swapUnresolved(v, UNRESOLVED_SENTINEL, UNRESOLVED) as T;\n}\n\n// JSON-serializable mirror of the classifyResource inputs + expected output.\nexport interface CorpusCase {\n corpusVersion: 1;\n // free-text: what this case locks in (filled in by hand when curating)\n description?: string;\n resource: {\n logicalId: string;\n resourceType: string;\n physicalId?: string;\n constructPath?: string;\n declared: Record<string, unknown>; // RESOLVED declared (post intrinsic resolution)\n siblingPolicyNames?: string[] | 'unresolved';\n };\n liveRaw: Record<string, unknown>; // un-stripped live model, as the reader returned it\n schema: {\n readOnly: string[];\n writeOnly: string[];\n createOnly: string[];\n readOnlyPaths: string[];\n writeOnlyPaths: string[];\n createOnlyPaths: string[];\n defaults: Record<string, unknown>;\n defaultPaths: Record<string, unknown>;\n unorderedScalarPaths?: string[]; // optional for backward compat with pre-insertionOrder cases\n unorderedObjectArrayPaths?: string[]; // optional for backward compat with pre-#459 cases\n freeFormMapPaths?: string[]; // optional for backward compat with pre-free-form-map cases\n };\n opts: {\n accountId: string;\n region: string;\n kmsAliasTargets: Record<string, string>;\n oaiCanonicalIds: Record<string, string>;\n // Sibling SecurityGroupIngress/Egress rules reflected into an SG's live arrays, keyed by\n // the SG's physical id. Only present (and only its own entry) on an AWS::EC2::SecurityGroup\n // case, so replay reproduces the sibling-rule subtraction; optional for back-compat.\n siblingSgRules?: Record<string, { ingress: unknown[]; egress: unknown[] }>;\n // This bucket's own physical id, present only when its S3 notifications are managed by a\n // Custom::S3BucketNotifications CR, so replay reproduces the NotificationConfiguration drop.\n // Stored as an array (JSON has no Set); replay revives it to a Set. Optional for back-compat.\n bucketNotificationManaged?: string[];\n // The parent DBCluster's live model keyed by THIS instance's physical id — present only on a\n // CLUSTER_ECHO_CHILD case (an Aurora DBInstance echoing its cluster), so replay reproduces the\n // cluster-echo strip. Without it a fresh-harvested reader/writer replays the un-folded echo\n // props as false undeclared drift. Optional for back-compat (pre-clusterEcho cases lack it).\n clusterEchoModel?: Record<string, Record<string, unknown>>;\n };\n expected: Finding[]; // what classifyResource produced at record time (reviewed at commit)\n}\n\n/** Deep-replace every occurrence of `accountId` inside string values (ARNs,\n * physical ids, policy principals, ...) with the fixed sanitized id. Applied\n * uniformly to inputs AND expected findings, so account-scoped suppression\n * (arn-identity) replays exactly as it ran live. */\nexport function sanitizeAccountId<T>(value: T, accountId: string): T {\n if (!accountId) return value;\n const walk = (v: unknown): unknown => {\n if (typeof v === 'string') return v.split(accountId).join('111111111111');\n if (Array.isArray(v)) return v.map(walk);\n if (v && typeof v === 'object')\n return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, walk(x)]));\n return v;\n };\n return walk(value) as T;\n}\n\n/** Assemble a corpus case from one classified resource (already-sanitized by the caller). */\nexport function buildCorpusCase(\n resource: DesiredResource,\n liveRaw: Record<string, unknown>,\n schema: SchemaInfo,\n opts: {\n accountId: string;\n region: string;\n kmsAliasTargets: Record<string, string>;\n oaiCanonicalIds: Record<string, string>;\n siblingSgRules?: Record<string, { ingress: unknown[]; egress: unknown[] }>;\n bucketNotificationManaged?: Set<string>;\n clusterEchoModel?: Record<string, Record<string, unknown>>;\n },\n findings: Finding[]\n): CorpusCase {\n // Carry only THIS SG's sibling-rule entry (keyed by its own physical id) into the case, so\n // replay reproduces the subtraction without bloating every case with the stack-wide map.\n const sgSibling =\n resource.resourceType === 'AWS::EC2::SecurityGroup' && resource.physicalId\n ? opts.siblingSgRules?.[resource.physicalId]\n : undefined;\n // Same shape as sgSibling: carry ONLY this resource's own entry from the stack-wide maps, so a\n // cluster-echo / bucket-notification case replays its strip without bloating every case.\n const bucketNotif =\n resource.physicalId && opts.bucketNotificationManaged?.has(resource.physicalId)\n ? [resource.physicalId]\n : undefined;\n const echoModel =\n resource.physicalId && opts.clusterEchoModel?.[resource.physicalId]\n ? opts.clusterEchoModel[resource.physicalId]\n : undefined;\n const c: CorpusCase = {\n corpusVersion: 1,\n resource: {\n logicalId: resource.logicalId,\n resourceType: resource.resourceType,\n ...(resource.physicalId !== undefined && { physicalId: resource.physicalId }),\n ...(resource.constructPath !== undefined && { constructPath: resource.constructPath }),\n declared: encodeUnresolved(resource.declared),\n ...(resource.siblingPolicyNames !== undefined && {\n siblingPolicyNames: resource.siblingPolicyNames,\n }),\n },\n liveRaw,\n schema: {\n readOnly: [...schema.readOnly].sort(),\n writeOnly: [...schema.writeOnly].sort(),\n createOnly: [...schema.createOnly].sort(),\n readOnlyPaths: [...schema.readOnlyPaths].sort(),\n writeOnlyPaths: [...schema.writeOnlyPaths].sort(),\n createOnlyPaths: [...schema.createOnlyPaths].sort(),\n defaults: schema.defaults,\n defaultPaths: schema.defaultPaths,\n unorderedScalarPaths: [...(schema.unorderedScalarPaths ?? [])].sort(),\n unorderedObjectArrayPaths: [...(schema.unorderedObjectArrayPaths ?? [])].sort(),\n freeFormMapPaths: [...(schema.freeFormMapPaths ?? [])].sort(),\n },\n opts: {\n accountId: opts.accountId,\n region: opts.region,\n kmsAliasTargets: opts.kmsAliasTargets,\n oaiCanonicalIds: opts.oaiCanonicalIds,\n ...(sgSibling && resource.physicalId\n ? { siblingSgRules: { [resource.physicalId]: sgSibling } }\n : {}),\n ...(bucketNotif ? { bucketNotificationManaged: bucketNotif } : {}),\n ...(echoModel && resource.physicalId\n ? { clusterEchoModel: { [resource.physicalId]: echoModel } }\n : {}),\n },\n expected: findings,\n };\n return sanitizeAccountId(c, opts.accountId);\n}\n\n/** Revive a case's schema arrays into the SchemaInfo Sets classify expects. */\nexport function reviveSchema(s: CorpusCase['schema']): SchemaInfo {\n return {\n readOnly: new Set(s.readOnly),\n writeOnly: new Set(s.writeOnly),\n createOnly: new Set(s.createOnly),\n readOnlyPaths: [...s.readOnlyPaths],\n writeOnlyPaths: [...s.writeOnlyPaths],\n createOnlyPaths: [...s.createOnlyPaths],\n defaults: s.defaults,\n defaultPaths: s.defaultPaths ?? {},\n unorderedScalarPaths: s.unorderedScalarPaths ?? [],\n unorderedObjectArrayPaths: s.unorderedObjectArrayPaths ?? [],\n freeFormMapPaths: s.freeFormMapPaths ?? [],\n };\n}\n\n/** Revive a case's stored opts into the shape classifyResource expects: the JSON case\n * stores `bucketNotificationManaged` as an array (JSON has no Set) but classify wants a\n * Set, so convert it; every other opts field passes through unchanged. Both replay call\n * sites (corpus-replay + measure-noise) go through here so they stay in lockstep. */\nexport function reviveOpts(o: CorpusCase['opts']): Omit<\n CorpusCase['opts'],\n 'bucketNotificationManaged'\n> & {\n bucketNotificationManaged?: Set<string>;\n} {\n const { bucketNotificationManaged, ...rest } = o;\n return {\n ...rest,\n ...(bucketNotificationManaged\n ? { bucketNotificationManaged: new Set(bucketNotificationManaged) }\n : {}),\n };\n}\n\n/** `AWS::S3::Bucket` + `MyBucket` -> `AWS__S3__Bucket.MyBucket.json` */\nexport function corpusFileName(resourceType: string, logicalId: string): string {\n return `${resourceType.replace(/::/g, '__')}.${logicalId}.json`;\n}\n\nexport async function recordCorpusCase(dir: string, c: CorpusCase): Promise<string> {\n await mkdir(dir, { recursive: true });\n const p = join(dir, corpusFileName(c.resource.resourceType, c.resource.logicalId));\n await writeFile(p, JSON.stringify(c, null, 2) + '\\n', 'utf8');\n return p;\n}\n","// Undeclared-property noise suppressors (slice fixes A1/A2/A4).\n// Keep conservative — over-suppression hides real undeclared drift.\n\n// A4: defaults AWS applies that are NOT in the CFn schema's `default` field.\n// Every entry is equality-gated: it only suppresses a live value EQUAL to the\n// listed default, so an out-of-band change to anything else still surfaces (and\n// a recorded baseline value that flips back to the default is still drift —\n// the entry only mutes the never-declared/never-decided first sighting). R66\n// entries were all OBSERVED on real default-config stacks during dogfooding.\nexport const KNOWN_DEFAULTS: Record<string, Record<string, unknown>> = {\n 'AWS::IAM::Role': { MaxSessionDuration: 3600, Path: '/', Description: '' },\n // A Managed Service for Apache Flink application that declares no ApplicationMode\n // reads back STREAMING — the constant service default for Flink runtimes (the only\n // other value, INTERACTIVE, requires a Zeppelin/Studio runtime, a different declared\n // config; ApplicationMode is createOnly so it cannot drift). Equality-gated. Observed\n // live on a fresh READY Flink app (streaming-rich fixture, 2026-07-03; #509).\n 'AWS::KinesisAnalyticsV2::Application': { ApplicationMode: 'STREAMING' },\n // S3 versioning can never return to the never-enabled state — a revert \"remove\"\n // lands on Suspended, which IS the off state. Without this entry an undeclared\n // {Status:\"Suspended\"} re-reports forever and revert can never converge (R46).\n 'AWS::S3::Bucket': {\n VersioningConfiguration: { Status: 'Suspended' },\n AbacStatus: 'Disabled', // R66\n // R86 (account-wide S3 defaults AWS has applied to every new bucket since 2023):\n // Block Public Access fully on (Apr 2023), ACLs disabled / BucketOwnerEnforced\n // (Apr 2023), and SSE-S3 (AES256) default encryption (Jan 2023). A CDK bucket that\n // does not declare these reports all three on every first run, yet they are the\n // (secure) AWS default, not an edit. Equality-gated like every KNOWN_DEFAULTS\n // entry: weaken any of them out of band (e.g. BlockPublicAcls=false) and the value\n // no longer matches, so it re-surfaces as real undeclared drift. The encryption\n // shape mirrors what Cloud Control returns today (incl. the newer\n // BlockedEncryptionTypes field); if AWS changes the shape the match simply falls\n // through and the value is shown again — never silently wrong.\n PublicAccessBlockConfiguration: {\n RestrictPublicBuckets: true,\n BlockPublicPolicy: true,\n BlockPublicAcls: true,\n IgnorePublicAcls: true,\n },\n OwnershipControls: { Rules: [{ ObjectOwnership: 'BucketOwnerEnforced' }] },\n BucketEncryption: {\n ServerSideEncryptionConfiguration: [\n {\n BucketKeyEnabled: false,\n BlockedEncryptionTypes: { EncryptionType: ['SSE-C'] },\n ServerSideEncryptionByDefault: { SSEAlgorithm: 'AES256' },\n },\n ],\n },\n },\n // S3 Express directory buckets are always encrypted; a never-declared bucket\n // reads back SSE-S3 with the bucket key ON (unlike general-purpose buckets,\n // which read BucketKeyEnabled:false and a BlockedEncryptionTypes field).\n // Observed live on a fresh s3express-s3tables-rich deploy.\n 'AWS::S3Express::DirectoryBucket': {\n BucketEncryption: {\n ServerSideEncryptionConfiguration: [\n {\n BucketKeyEnabled: true,\n ServerSideEncryptionByDefault: { SSEAlgorithm: 'AES256' },\n },\n ],\n },\n },\n // S3 Tables table buckets materialize three constant service defaults on read:\n // Standard storage class, table-level metrics off, and SSE-S3 encryption.\n // Observed live on a fresh s3express-s3tables-rich deploy; equality-gated like\n // every KNOWN_DEFAULTS entry, so moving any of them off the default (e.g. KMS\n // encryption set out of band) re-surfaces as real undeclared drift.\n 'AWS::S3Tables::TableBucket': {\n StorageClassConfiguration: { StorageClass: 'STANDARD' },\n MetricsConfiguration: { Status: 'Disabled' },\n EncryptionConfiguration: { SSEAlgorithm: 'AES256' },\n },\n // Vended-logs v2 (CloudWatch Logs Delivery family). DeliveryDestinationType is\n // DERIVED from the declared DestinationResourceArn (a log-group destination always\n // reads back \"CWL\") — observed-only like the ApiGateway Authorizer AuthType fold; an\n // S3/FH/XRay destination's value simply doesn't match and surfaces once, recordable.\n 'AWS::Logs::DeliveryDestination': { DeliveryDestinationType: 'CWL' },\n // A Delivery that declares no RecordFields materializes the source's FULL default\n // field list on read. This is the CloudFront ACCESS_LOGS default (the most common\n // vended source) — equality-gated, so a field added/removed/reordered out of band no\n // longer matches and surfaces as real undeclared drift; other sources' lists simply\n // don't fold. Observed live on a fresh cloudfront-kvs-logs-delivery deploy.\n 'AWS::Logs::Delivery': {\n RecordFields: [\n 'date',\n 'time',\n 'x-edge-location',\n 'sc-bytes',\n 'c-ip',\n 'cs-method',\n 'cs(Host)',\n 'cs-uri-stem',\n 'sc-status',\n 'cs(Referer)',\n 'cs(User-Agent)',\n 'cs-uri-query',\n 'cs(Cookie)',\n 'x-edge-result-type',\n 'x-edge-request-id',\n 'x-host-header',\n 'cs-protocol',\n 'cs-bytes',\n 'time-taken',\n 'x-forwarded-for',\n 'ssl-protocol',\n 'ssl-cipher',\n 'x-edge-response-result-type',\n 'cs-protocol-version',\n 'fle-status',\n 'fle-encrypted-fields',\n 'c-port',\n 'time-to-first-byte',\n 'x-edge-detailed-result-type',\n 'sc-content-type',\n 'sc-content-len',\n 'sc-range-start',\n 'sc-range-end',\n ],\n },\n // R66 (dogfood-observed service defaults):\n 'AWS::Lambda::Function': {\n TracingConfig: { Mode: 'PassThrough' },\n EphemeralStorage: { Size: 512 },\n PackageType: 'Zip',\n RecursiveLoop: 'Terminate',\n RuntimeManagementConfig: { UpdateRuntimeOn: 'Auto' },\n Architectures: ['x86_64'],\n // R70 (observed live on the lambda integ fixture): a never-declared\n // default-config function otherwise reports both on every first run.\n MemorySize: 128,\n Timeout: 3,\n },\n 'AWS::Lambda::Url': { InvokeMode: 'BUFFERED' },\n // A stream / self-managed-Kafka event source mapping created without these reads\n // them back as -1 (the documented \"infinite\" default: retry forever / no record-age\n // cap). A never-declared ESM otherwise reports both on every first run. Equality-gated\n // — set either to a finite value out of band and it no longer matches, so it\n // re-surfaces as real undeclared drift. (SQS event sources don't carry these props at\n // all, so the entry can't mis-fold there.) Observed live on a fresh esm-sourceaccess-rich\n // deploy.\n // Enabled: an ESM (e.g. CDK's SqsEventSource) is created enabled; the construct omits\n // Enabled when it leaves the default true, so the live read reports an undeclared\n // Enabled=true on every first run — observed live on a dev LineLink stack with no\n // out-of-band edit. (The off state Enabled=false is dropped upstream as trivially-empty\n // before this fold, mirroring the KMS Key Enabled case.) Merged into the single\n // EventSourceMapping entry — a duplicate object-literal key silently drops the earlier\n // retry/age fold (JS last-key-wins; #438 regressed it).\n 'AWS::Lambda::EventSourceMapping': {\n MaximumRetryAttempts: -1,\n MaximumRecordAgeInSeconds: -1,\n Enabled: true,\n // A mapping that declares no batching window reads back MaximumBatchingWindowInSeconds: 0\n // (the documented \"no window\" default) — the CDK SqsEventSource omits it unless set.\n // Equality-gated: a mapping that pins a real window no longer matches and surfaces.\n // Observed live on a dev SQS-triggered function.\n MaximumBatchingWindowInSeconds: 0,\n },\n // An alias created without a Description reads back the empty string. Folded as\n // atDefault so a never-declared alias does not report `Description=\"\"` as drift; it\n // is also the value REVERT_SET_DEFAULT_PATHS writes to undo an out-of-band Description\n // (UpdateAlias ignores an OMITTED description, so a bare `remove` is a silent no-op —\n // the alias must be sent Description:\"\" explicitly; proven live).\n 'AWS::Lambda::Alias': { Description: '' },\n // A published version inherits the function's runtime-management config; a version\n // that pins nothing reads back the Auto default (observed live across every\n // `currentVersion` in a multi-function stack). The twin of the AWS::Lambda::Function\n // RuntimeManagementConfig default above; pin a version to a specific runtime and the\n // object no longer matches (equality-gated). The version's CodeSha256 is a per-deploy\n // content hash (not a constant default) — folded as `generated` via\n // GENERATED_TOPLEVEL_PATHS instead.\n 'AWS::Lambda::Version': { RuntimePolicy: { UpdateRuntimeOn: 'Auto' } },\n 'AWS::Events::Rule': { EventBusName: 'default' },\n 'AWS::Athena::WorkGroup': {\n State: 'ENABLED',\n // A workgroup that declares ONLY Name/Description reads back AWS's whole default\n // WorkGroupConfiguration (the existing WorkGroupConfiguration.* nested paths only fire\n // when the object is PARTIALLY declared and thus descended; a fully-undeclared object is\n // reported whole, so it needs this top-level fold). EngineVersion's read-only\n // EffectiveEngineVersion is schema-stripped, leaving SelectedEngineVersion:AUTO. Observed\n // live (hunt 2026-07-03 round E). Equality-gated: any enforced non-default surfaces.\n WorkGroupConfiguration: {\n EnforceWorkGroupConfiguration: true,\n EngineVersion: { SelectedEngineVersion: 'AUTO' },\n PublishCloudWatchMetricsEnabled: true,\n RequesterPaysEnabled: false,\n },\n },\n // A fresh EKS cluster reads back several whole-object service defaults the template never\n // declares. Constants (equality-gated) — an out-of-band change to any surfaces. The\n // per-deploy-variable bits (KubernetesNetworkConfig.ServiceIpv4Cidr is 10.100 OR 172.20,\n // Version tracks the service default) are deliberately NOT folded — they stay record-worthy.\n // Observed live (hunt 2026-07-03 round E).\n 'AWS::EKS::Cluster': {\n ControlPlaneScalingConfig: { Tier: 'standard' },\n UpgradePolicy: { SupportType: 'EXTENDED' },\n },\n // A vpc-cni (and other) addon reads back the kube-system namespace it installs into when\n // the template declares no NamespaceConfig. AddonVersion is per-cluster-version → record-worthy.\n 'AWS::EKS::Addon': { NamespaceConfig: { Namespace: 'kube-system' } },\n // A WebACL that declares no on-source DDoS protection reads back AWS's default\n // OnSourceDDoSProtectionConfig — ALBLowReputationMode=ACTIVE_UNDER_DDOS (the first\n // enum value / documented default), so the live read reports it as undeclared\n // first-run noise on every WebACL. Equality-gated; a user that sets ALWAYS_ON still\n // surfaces. Observed live on a fresh wafv2-webacl-customkeys deploy (issue #440).\n 'AWS::WAFv2::WebACL': {\n OnSourceDDoSProtectionConfig: { ALBLowReputationMode: 'ACTIVE_UNDER_DDOS' },\n },\n // A VPC Lattice service network created without a SharingConfig reads back the\n // service default `{enabled: true}` (RAM sharing allowed — note the service model's\n // lowercase sub-key), so every fresh service network reports it as undeclared\n // first-run noise. Equality-gated; a network with sharing disabled out of band\n // ({enabled: false}) still surfaces. Observed live on a fresh vpclattice-listener\n // deploy (issue #483).\n 'AWS::VpcLattice::ServiceNetwork': { SharingConfig: { enabled: true } },\n // AmazonMQ Broker service defaults (observed live on the amazonmq-version-readgap\n // fixture): a broker created without these knobs reports all three as undeclared\n // first-run noise. AuthenticationStrategy is SIMPLE unless LDAP is configured;\n // EncryptionOptions falls back to the AWS-owned key when no KMS key is declared;\n // DataReplicationMode is NONE unless cross-region data replication (CRDR) is\n // enabled. Equality-gated like every KNOWN_DEFAULTS entry — a broker that sets a\n // KMS key / LDAP / CRDR reads back a non-matching value and stays undeclared.\n 'AWS::AmazonMQ::Broker': {\n AuthenticationStrategy: 'SIMPLE',\n EncryptionOptions: { UseAwsOwnedKey: true },\n DataReplicationMode: 'NONE',\n },\n // Chatbot applies the AdministratorAccess guardrail when none is declared\n // (verified live on a default-config SlackChannelConfiguration).\n 'AWS::Chatbot::SlackChannelConfiguration': {\n GuardrailPolicies: ['arn:aws:iam::aws:policy/AdministratorAccess'],\n },\n // CloudTrail materializes the default management-events selector when the\n // template declares EventSelectors [] or omits it (observed live on the\n // harvest3 fixture, R74 — CDK's Trail construct synthesizes `EventSelectors:\n // []` by default, so EVERY default CDK trail otherwise reports declared\n // drift). Also consulted by the declared loop's trivially-empty rule.\n 'AWS::CloudTrail::Trail': {\n EventSelectors: [\n {\n IncludeManagementEvents: true,\n ReadWriteType: 'All',\n ExcludeManagementEventSources: [],\n DataResources: [],\n },\n ],\n },\n // R104 (dogfood noise audit across the harvest fixtures): top-level service\n // defaults AWS materializes that the CFn schema does NOT annotate as `default`\n // (so the schema-driven R103 fold can't reach them). All OBSERVED on real\n // default-config resources; equality-gated, so a value set away from the default\n // still surfaces. Resource-/account-/region-specific values (names, ARNs, ids,\n // VpcId, KmsKeyId, NetworkBorderGroup, …) are deliberately NOT listed — those are\n // genuine undeclared inventory, not defaults.\n 'AWS::SQS::Queue': {\n DelaySeconds: 0,\n VisibilityTimeout: 30,\n MessageRetentionPeriod: 345600,\n ReceiveMessageWaitTimeSeconds: 0,\n SqsManagedSseEnabled: true,\n // AWS now provisions a 1 MiB max message size by default (observed unanimous\n // across 10 corpus queues that declare none); a queue that pins a smaller value\n // still surfaces (equality-gated).\n MaximumMessageSize: 1048576,\n FifoThroughputLimit: 'perQueue', // FIFO queues only\n DeduplicationScope: 'queue', // FIFO queues only\n KmsDataKeyReusePeriodSeconds: 300, // default 5 min; appears only on SSE-KMS queues\n },\n 'AWS::ElasticLoadBalancingV2::TargetGroup': {\n HealthCheckEnabled: true,\n HealthCheckPort: 'traffic-port',\n HealthCheckProtocol: 'HTTP',\n HealthCheckTimeoutSeconds: 5,\n UnhealthyThresholdCount: 2,\n ProtocolVersion: 'HTTP1',\n IpAddressType: 'ipv4',\n Matcher: { HttpCode: '200' },\n },\n 'AWS::ElasticLoadBalancingV2::LoadBalancer': {\n IpAddressType: 'ipv4',\n EnablePrefixForIpv6SourceNat: 'off',\n },\n 'AWS::ElasticLoadBalancingV2::Listener': {\n // A listener that declares no mutual-TLS config reads back the \"off\" default.\n // Observed live on an HTTPS listener.\n MutualAuthentication: { Mode: 'off' },\n },\n 'AWS::EC2::NatGateway': {\n ConnectivityType: 'public',\n AvailabilityMode: 'zonal',\n },\n 'AWS::CodeDeploy::DeploymentGroup': {\n // The schema carries no explicit `default`, but its description states the value\n // applied when the property is \"unspecified\" is UPDATE — CodeDeploy always echoes\n // it back on a group that never declared it (live-observed,\n // codedeploy-deploymentgroup-readgap). Equality-gated, so a switch to IGNORE\n // still surfaces.\n OutdatedInstancesStrategy: 'UPDATE',\n },\n 'AWS::EFS::FileSystem': {\n ThroughputMode: 'bursting',\n BackupPolicy: { Status: 'DISABLED' },\n FileSystemProtection: { ReplicationOverwriteProtection: 'ENABLED' },\n PerformanceMode: 'generalPurpose', // R-noise-sweep: default; switching to maxIO no longer matches and surfaces\n },\n 'AWS::StepFunctions::StateMachine': {\n StateMachineType: 'STANDARD',\n LoggingConfiguration: { IncludeExecutionData: false, Level: 'OFF' },\n EncryptionConfiguration: { Type: 'AWS_OWNED_KEY' },\n },\n 'AWS::ApiGateway::RestApi': {\n ApiKeySourceType: 'HEADER',\n SecurityPolicy: 'TLS_1_0',\n EndpointConfiguration: { IpAddressType: 'ipv4', Types: ['EDGE'] },\n DisableExecuteApiEndpoint: false,\n },\n // A custom domain created without an explicit TLS floor reads back TLS_1_2 (the\n // documented default for REGIONAL/EDGE custom domains; observed live). A domain that\n // pins TLS_1_0 reads a non-matching value and stays undeclared (equality-gated).\n 'AWS::ApiGateway::DomainName': {\n SecurityPolicy: 'TLS_1_2',\n },\n // NOTE: AWS::ApiGateway::Authorizer.AuthType is NOT a KNOWN_DEFAULTS entry — it is\n // folded value-independently via VALUE_INDEPENDENT_DEFAULT_TOPLEVEL_PATHS below\n // (AuthType is a derived, non-declarable read-back of the declared Type).\n // A VPC is in nearly every CDK stack. AWS reports these two constant defaults on\n // every first run when the template does not declare them (raw CfnVPC, or an L2 Vpc\n // that sets only DNS hostnames): InstanceTenancy \"default\" (vs dedicated/host) and\n // EnableDnsSupport on (the VPC default). Observed live on the vpcpeering-rich /\n // egressonly-rich fixtures. Equality-gated: a dedicated-tenancy VPC or DNS-support\n // disabled out of band no longer matches and surfaces as real undeclared drift.\n 'AWS::EC2::VPC': {\n InstanceTenancy: 'default',\n EnableDnsSupport: true,\n },\n 'AWS::EC2::Subnet': {\n PrivateDnsNameOptionsOnLaunch: {\n EnableResourceNameDnsARecord: false,\n HostnameType: 'ip-name',\n EnableResourceNameDnsAAAARecord: false,\n },\n // IPv6 feature flags AWS reports off by default on every IPv4 subnet.\n AssignIpv6AddressOnCreation: false,\n EnableDns64: false,\n Ipv6Native: false,\n },\n // R-noise-sweep (found by the ec2-instance-rich hunt, PR #310 follow-up): a fresh\n // EC2 Instance reports these three constant service defaults as undeclared on every\n // first run. They are documented account-/instance-independent defaults — Tenancy\n // \"default\" (vs dedicated/host), SourceDestCheck on (the routing default), and the\n // \"stop\" shutdown behavior. Resource-specific live values the same read returns\n // (PrivateIpAddress, SecurityGroups, Volumes, NetworkInterfaces, CpuOptions which is\n // instance-type-derived, …) are deliberately NOT listed — they are genuine undeclared\n // inventory. Equality-gated: flip any out of band and it no longer matches, so it\n // re-surfaces as real undeclared drift.\n 'AWS::EC2::Instance': {\n Tenancy: 'default',\n SourceDestCheck: true,\n InstanceInitiatedShutdownBehavior: 'stop',\n },\n // R105 (second dogfood-audit wave): more top-level constant service defaults\n // (same exclusions as R104 — no names/ids/ARNs, no region-/account-specific\n // values, no large/evolving config blobs like Athena WorkGroupConfiguration).\n 'AWS::ApiGatewayV2::Api': {\n RouteSelectionExpression: '$request.method $request.path',\n IpAddressType: 'ipv4', // R-noise-sweep: default; flipping to dualstack no longer matches and surfaces\n DisableExecuteApiEndpoint: false,\n },\n 'AWS::ApiGatewayV2::Integration': {\n ConnectionType: 'INTERNET',\n TimeoutInMillis: 30000,\n },\n 'AWS::CodeBuild::Project': {\n TimeoutInMinutes: 60,\n QueuedTimeoutInMinutes: 480,\n Visibility: 'PRIVATE', // the default; folds to atDefault so a never-declared project is not first-run noise — flipping to PUBLIC_READ no longer matches and surfaces\n Cache: { Type: 'NO_CACHE' }, // BatchGetProjects always returns cache; the unconfigured default folds to atDefault so a never-declared cache is not first-run noise — switching to S3/LOCAL no longer matches and surfaces\n },\n // A PAY_PER_REQUEST (on-demand) DynamoDB table reads back a baseline WarmThroughput\n // that AWS assigns to every fresh table (12000 read / 4000 write units) even though the\n // template never declares it — observed live on a dev LineLink stack (GlobalTable /\n // TableV2) and a dev reco-MailQueues stack (classic AWS::DynamoDB::Table), neither with\n // an out-of-band edit. The service default is identical for both CFn types, so both fold.\n // Equality-gated: a table that has WARMED UP to a higher value under traffic no longer\n // matches and surfaces as a real undeclared value (the warm throughput auto-ratchets and\n // never decreases), and an explicitly declared WarmThroughput compares as declared\n // instead. Top-level WarmThroughput only — the GSI-nested `*.WarmThroughput` stays\n // surfaced (see KNOWN_DEFAULT_PATHS note below).\n 'AWS::DynamoDB::Table': {\n BillingMode: 'PROVISIONED',\n DeletionProtectionEnabled: false,\n WarmThroughput: { ReadUnitsPerSecond: 12000, WriteUnitsPerSecond: 4000 },\n },\n 'AWS::DynamoDB::GlobalTable': {\n WarmThroughput: { ReadUnitsPerSecond: 12000, WriteUnitsPerSecond: 4000 },\n },\n 'AWS::ECR::Repository': {\n EncryptionConfiguration: { EncryptionType: 'AES256' },\n ImageTagMutability: 'MUTABLE', // R-noise-sweep: default; switching to IMMUTABLE no longer matches and surfaces\n },\n 'AWS::Kinesis::Stream': {\n MaxRecordSizeInKiB: 1024,\n },\n 'AWS::SSM::Parameter': {\n DataType: 'text',\n // AWS auto-assigns Standard when Tier is not declared (the SDK_SUPPLEMENTS reader\n // projects it); folds an undeclared Standard so it is not noise. A real Advanced /\n // Intelligent-Tiering value still surfaces (undeclared) or compares (declared).\n Tier: 'Standard',\n },\n 'AWS::StepFunctions::Activity': {\n EncryptionConfiguration: { Type: 'AWS_OWNED_KEY' },\n },\n 'AWS::SNS::Subscription': {\n FilterPolicyScope: 'MessageAttributes',\n },\n // R-noise-sweep (data-driven from scripts/measure-noise.sh over the golden corpus):\n // constant, documented AWS defaults for common types — never names/ids/ARNs, never\n // region-/account-/AZ-/time-specific values, never engine-derived (RDS windows/port/\n // option-group). Equality-gated like every entry: flip the value out of band and it\n // no longer matches, so it re-surfaces as real undeclared drift.\n 'AWS::Cognito::UserPool': {\n MfaConfiguration: 'OFF',\n DeletionProtection: 'INACTIVE',\n UserPoolTier: 'ESSENTIALS',\n // A user pool that does not wire up its own SES identity reads back the\n // Cognito-managed sender (observed live). EmailSendingAccount=COGNITO_DEFAULT is\n // the documented default; a pool that switches to DEVELOPER (its own SES) reads a\n // non-matching object and stays undeclared (equality-gated).\n EmailConfiguration: { EmailSendingAccount: 'COGNITO_DEFAULT' },\n // A pool that declares NO Policies reads back Cognito's constant default password\n // policy (min length 8, all four character classes required, 7-day temp-password\n // lifetime) plus the SignInPolicy default (PASSWORD as the sole first factor). The\n // whole object is live-only on such a pool, so the KNOWN_DEFAULT_PATHS sub-entries\n // (which fold only when a PARTIAL Policies is declared) never reach it — fold the\n // full default object here. Equality-gated (subset-tolerant): a pool that pins any\n // non-default policy value no longer matches and surfaces. Observed live.\n Policies: {\n PasswordPolicy: {\n MinimumLength: 8,\n RequireLowercase: true,\n RequireNumbers: true,\n RequireSymbols: true,\n RequireUppercase: true,\n TemporaryPasswordValidityDays: 7,\n },\n SignInPolicy: { AllowedFirstAuthFactors: ['PASSWORD'] },\n },\n // A pool that declares no custom KMS key reads back the AWS-owned-key default, and a\n // pool that does not customize its token issuer reads back Type \"ORIGINAL\" — both\n // Cognito-materialized constants the template never carries. Equality-gated: a pool\n // that wires its own CMK (KeyType != AWS_OWNED_KEY) or a non-original issuer no\n // longer matches and surfaces. Observed live.\n KeyConfiguration: { KeyType: 'AWS_OWNED_KEY' },\n IssuerConfiguration: { Type: 'ORIGINAL' },\n },\n // An identity pool that declares no allowClassicFlow reads back AllowClassicFlow=false\n // (the documented default). Equality-gated: switch it on out of band and the value no\n // longer matches, so it re-surfaces as real undeclared drift (and reverts to false via\n // REVERT_SET_DEFAULT_PATHS — a bare `remove` is a no-op because UpdateIdentityPool\n // leaves an omitted AllowClassicFlow unchanged).\n 'AWS::Cognito::IdentityPool': {\n AllowClassicFlow: false,\n },\n 'AWS::Cognito::UserPoolClient': {\n EnableTokenRevocation: true,\n AuthSessionValidity: 3,\n // Cognito's default refresh-token validity is 30 (days, the default unit) when a\n // client declares none — observed unanimous across the corpus clients.\n RefreshTokenValidity: 30,\n EnablePropagateAdditionalUserContextData: false,\n },\n 'AWS::ECS::Service': {\n SchedulingStrategy: 'REPLICA',\n // A service with no load-balancer health-check grace reads back 0 (the default) —\n // observed unanimous across the corpus services.\n HealthCheckGracePeriodSeconds: 0,\n EnableExecuteCommand: false,\n // A service that declares no deployment controller reads back the default rolling\n // (ECS) controller. Observed live on a fresh Fargate service.\n DeploymentController: { Type: 'ECS' },\n },\n 'AWS::AppSync::GraphQLApi': {\n ApiType: 'GRAPHQL',\n Visibility: 'GLOBAL',\n IntrospectionConfig: 'ENABLED',\n // Observed live on a fresh appsync-resolver-rich deploy: an API that declares\n // neither limit reads back the \"no limit\" sentinel 0 for both, so every default\n // AppSync API otherwise reports them as first-run undeclared inventory.\n QueryDepthLimit: 0,\n ResolverCountLimit: 0,\n XrayEnabled: false,\n },\n // AppSync Resolvers / Functions default MaxBatchSize to 0 (no batch invocation)\n // when the template declares no batching — observed live on a fresh\n // appsync-resolver-rich deploy across UNIT + PIPELINE resolvers and the Function.\n // Equality-gated: a real batch size set out of band still surfaces.\n 'AWS::AppSync::Resolver': {\n MaxBatchSize: 0,\n },\n 'AWS::AppSync::FunctionConfiguration': {\n MaxBatchSize: 0,\n },\n // Logs SubscriptionFilter defaults Distribution to \"ByLogStream\" when undeclared\n // (the only other value is \"Random\") — observed live on a fresh\n // logs-subscriptionfilter-rich deploy.\n 'AWS::Logs::SubscriptionFilter': {\n Distribution: 'ByLogStream',\n },\n 'AWS::KMS::Key': {\n Enabled: true,\n KeySpec: 'SYMMETRIC_DEFAULT',\n KeyUsage: 'ENCRYPT_DECRYPT',\n Origin: 'AWS_KMS',\n },\n 'AWS::IAM::Group': {\n Path: '/',\n },\n 'AWS::IAM::User': {\n Path: '/',\n },\n 'AWS::IAM::InstanceProfile': {\n Path: '/',\n },\n // A fresh ECS Cluster reads back `ClusterSettings: [{Name:'containerInsights',Value:'disabled'}]`\n // — Container Insights defaults to disabled unless the account-level ECS setting turns it on, and\n // CDK does not declare it unless `containerInsights` is passed. Equality-gated (an enabled cluster\n // reports a different Value and re-surfaces). CapacityProviders / DefaultCapacityProviderStrategy\n // are NOT defaults — they are declared by the sibling ClusterCapacityProviderAssociations resource\n // and dropped in classify (see hasSiblingCapacityProviders).\n 'AWS::ECS::Cluster': {\n ClusterSettings: [{ Name: 'containerInsights', Value: 'disabled' }],\n },\n 'AWS::Scheduler::Schedule': {\n GroupName: 'default',\n ActionAfterCompletion: 'NONE',\n ScheduleExpressionTimezone: 'UTC',\n },\n // R-noise-sweep (found by the eni-rich / dbproxy-rich / elasticache-cachecluster-rich\n // hunt): constant, documented service defaults a fresh resource reports as undeclared\n // on every first run. Resource-/AZ-/window-specific values the same read returns\n // (ENI PrivateIpAddress(es), CacheCluster Snapshot/MaintenanceWindow,\n // PreferredAvailabilityZones, CacheParameterGroupName which is engine-version-derived)\n // are deliberately NOT listed — they are genuine undeclared inventory. Equality-gated:\n // flip any out of band and it no longer matches, so it re-surfaces as real drift.\n 'AWS::EC2::NetworkInterface': {\n InterfaceType: 'interface',\n Ipv4PrefixCount: 0,\n Ipv6PrefixCount: 0,\n SecondaryPrivateIpAddressCount: 0,\n // The documented EC2 default: a standard ENI has source/destination checking on. A NAT\n // instance / router explicitly declares SourceDestCheck:false, which still surfaces\n // (equality-gated). Observed live (hunt 2026-07-03 round F).\n SourceDestCheck: true,\n },\n // A collection that declares no DeletionProtection reads back AWS's DISABLED default.\n // A user who enables it declares \"ENABLED\", which still surfaces (equality-gated).\n // Observed live (hunt 2026-07-03 round F).\n 'AWS::OpenSearchServerless::Collection': { DeletionProtection: 'DISABLED' },\n // A SAML provider that declares no AssertionEncryptionMode reads back AWS's \"Allowed\"\n // default. A user who requires encryption declares \"Required\", which still surfaces\n // (equality-gated). Observed live (hunt 2026-07-03 round F).\n 'AWS::IAM::SAMLProvider': { AssertionEncryptionMode: 'Allowed' },\n 'AWS::ElastiCache::CacheCluster': {\n NetworkType: 'ipv4',\n IpDiscovery: 'ipv4',\n AZMode: 'single-az',\n AutoMinorVersionUpgrade: true,\n SnapshotRetentionLimit: 0,\n },\n // MemoryDB (managed Redis/Valkey) constant service defaults, observed live on the\n // memorydb-rich fixture: the Redis default Port, auto minor-version upgrade on,\n // data tiering off (returned as the string \"false\"), and the ipv4 network/discovery\n // defaults. Equality-gated. Per-resource/random values the same read returns\n // (ParameterGroupName is engine-version-derived, Snapshot/MaintenanceWindow are\n // AWS-assigned) are deliberately NOT listed — they are genuine undeclared inventory.\n 'AWS::MemoryDB::Cluster': {\n Port: 6379,\n AutoMinorVersionUpgrade: true,\n DataTiering: 'false',\n NetworkType: 'ipv4',\n IpDiscovery: 'ipv4',\n },\n 'AWS::RDS::DBProxy': {\n TargetConnectionNetworkType: 'IPV4',\n DefaultAuthScheme: 'NONE',\n EndpointNetworkType: 'IPV4',\n },\n // R-noise-sweep (offline audit of the golden corpus via scripts/measure-noise.sh):\n // constant, documented service defaults common stateful/streaming types report as\n // first-run undeclared inventory. Same exclusions as every entry above — NO\n // names/ids/ARNs, no AZ (us-east-1x / use1-azN), no randomized window\n // (Snapshot/Maintenance/Backup), no engine-/version-derived value (EngineVersion,\n // OptionGroupName, *ParameterGroupName, port), no per-resource IP. Equality-gated:\n // flip any out of band and it no longer matches, so it re-surfaces as real drift.\n // The RDS DBInstance values were observed UNANIMOUS across 3 corpus instances\n // spanning different engines (aurora-mysql + mysql8.0), confirming they are\n // constant service defaults, not engine-derived.\n 'AWS::RDS::DBInstance': {\n AutoMinorVersionUpgrade: true,\n BackupTarget: 'region',\n DatabaseInsightsMode: 'standard',\n // EngineLifecycleSupport is NOT a constant default — AWS changed the enrollment default over\n // time (RDS Extended Support opt-in behavior changed 2024-02/03: newer resources default to\n // `open-source-rds-extended-support` / auto-enroll, older ones read back\n // `open-source-rds-extended-support-disabled`), so it varies by creation date. Folded\n // value-independent via VALUE_INDEPENDENT_DEFAULT_TOPLEVEL_PATHS instead (declared → detected).\n MonitoringInterval: 0,\n NetworkType: 'IPV4',\n StorageThroughput: 0,\n // Boolean feature flags off by default (observed unanimous across the corpus\n // instances). Engine-DERIVED values (Port, LicenseModel, StorageType, AllocatedStorage)\n // fold via ENGINE_DEFAULTS, and the default parameter/option groups via\n // DEFAULT_MANAGED_NAME_PATHS; still NOT folded here: genuinely per-resource values\n // (EngineVersion, MasterUsername).\n CopyTagsToSnapshot: false,\n DedicatedLogVolume: false,\n EnableIAMDatabaseAuthentication: false,\n EnablePerformanceInsights: false,\n ManageMasterUserPassword: false,\n MultiAZ: false,\n StorageEncrypted: false,\n // The current AWS default RDS server certificate authority — unanimous across every\n // corpus DBInstance (aurora-mysql AND mysql) and both real Aurora dogfood stacks. A\n // constant, not engine-derived. Equality-gated: AWS rotates the default CA over time, so\n // a differing identifier (an older CA, or one the user pinned) still surfaces.\n CACertificateIdentifier: 'rds-ca-rsa2048-g1',\n },\n 'AWS::RDS::DBCluster': {\n AutoMinorVersionUpgrade: true,\n DatabaseInsightsMode: 'standard',\n // EngineLifecycleSupport folds value-independent (see the DBInstance note above) — its\n // default varies by creation date, so it is not a constant KNOWN_DEFAULTS value.\n NetworkType: 'IPV4',\n EngineMode: 'provisioned', // default; serverless/parallelquery are explicit opt-ins\n },\n 'AWS::Neptune::DBInstance': {\n AutoMinorVersionUpgrade: true,\n },\n 'AWS::Neptune::DBCluster': {\n NetworkType: 'IPV4',\n DBPort: 8182, // Neptune's fixed default port\n },\n 'AWS::ElastiCache::ReplicationGroup': {\n AutoMinorVersionUpgrade: true,\n ClusterMode: 'disabled',\n IpDiscovery: 'ipv4',\n NetworkType: 'ipv4',\n ReplicasPerNodeGroup: 0,\n },\n 'AWS::ElastiCache::ServerlessCache': {\n SnapshotRetentionLimit: 0,\n },\n 'AWS::OpenSearchService::Domain': {\n IPAddressType: 'ipv4',\n // AWS-materialized defaults a domain reads back on every first run (found by the offline\n // noise sweep, unanimous across the corpus domains): the automated-snapshot hour AWS assigns\n // (0 = midnight UTC) and the two default AdvancedOptions the service always returns. Equality-\n // gated: a domain that sets a non-default snapshot hour / advanced option no longer matches\n // and surfaces. (OffPeakWindowOptions — an AWS-ASSIGNED window object — folds value-\n // independent below, not here, since its start time is AWS's per-domain choice, not a constant.)\n SnapshotOptions: { AutomatedSnapshotStartHour: 0 },\n AdvancedOptions: {\n override_main_response_version: 'false',\n 'rest.action.multi.allow_explicit_index': 'true',\n },\n // A domain that declares no deployment strategy reads back the AWS default\n // \"CapacityOptimized\" (live-verified on a fresh opensearch-rich deploy, undeclared).\n // Equality-gated: a different strategy surfaces. (EncryptionAtRestOptions.KmsKeyId — the\n // AWS-assigned encryption key — folds value-independent via GENERATED_NESTED_PATHS below.)\n DeploymentStrategyOptions: { DeploymentStrategy: 'CapacityOptimized' },\n },\n // A Redshift cluster reads back a raft of AWS-assigned constant defaults the template never\n // declares (found by the offline noise sweep, live-verified on a fresh redshift-rich RA3\n // single-node deploy — the clean-deploy=zero-potential-drift invariant). Equality-gated: any\n // value moved off the default surfaces. `NumberOfNodes` folds at 1 (the single-node default; a\n // resize to a multi-node cluster surfaces). `Encrypted` and `AvailabilityZoneRelocationStatus`\n // are NodeType-DERIVED (RA3 is always encrypted + AWS enables AZ relocation) so they fold via a\n // classify conditional keyed on the declared NodeType, not here. `ClusterVersion` is the AWS-\n // assigned engine version → value-independent below; `AvailabilityZone` likewise.\n 'AWS::Redshift::Cluster': {\n Port: 5439,\n AutomatedSnapshotRetentionPeriod: 1,\n ManualSnapshotRetentionPeriod: -1,\n AllowVersionUpgrade: true,\n AquaConfigurationStatus: 'auto',\n MaintenanceTrackName: 'current',\n KmsKeyId: 'AWS_OWNED_KMS_KEY',\n NumberOfNodes: 1,\n },\n 'AWS::EC2::VPCEndpoint': {\n IpAddressType: 'ipv4',\n },\n 'AWS::EC2::TransitGateway': {\n SecurityGroupReferencingSupport: 'disable',\n },\n 'AWS::EC2::FlowLog': {\n MaxAggregationInterval: 600,\n },\n // EC2 echoes SpreadLevel \"rack\" even on partition-strategy groups (where the\n // property is inapplicable); \"rack\" is also the documented default for spread.\n 'AWS::EC2::PlacementGroup': {\n SpreadLevel: 'rack',\n },\n // IPAM defaults metering to the IPAM owner's account.\n 'AWS::EC2::IPAM': {\n MeteredAccount: 'ipam-owner',\n },\n // A Client VPN endpoint that declares neither VpnPort nor DisconnectOnSessionTimeout\n // reads back the constant service defaults (port 443, disconnect-on-timeout on).\n // Observed live on a fresh ClientVPN deploy (us-east-1, 2026-07-03; #554 from #534's\n // live verify). Equality-gated: flip either out of band (e.g. VpnPort=1194) and the\n // value no longer matches, so it re-surfaces as real undeclared drift.\n 'AWS::EC2::ClientVpnEndpoint': {\n VpnPort: 443,\n DisconnectOnSessionTimeout: true,\n },\n // A DAX cluster that declares no ClusterEndpointEncryptionType reads back \"NONE\" (the\n // constant service default; the only other value, \"TLS\", is an explicit opt-in).\n // Observed live on a fresh DAX deploy (us-east-1, 2026-07-03; #554). Equality-gated.\n // (PreferredMaintenanceWindow / SecurityGroupIds and the ParameterGroup's parameter\n // values are per-resource/AWS-assigned, so they are deliberately NOT folded here.)\n 'AWS::DAX::Cluster': {\n ClusterEndpointEncryptionType: 'NONE',\n },\n // Managed Prometheus materializes a WorkspaceConfiguration of service defaults\n // (150-day retention, 60s rule-query offset / out-of-order window) on every\n // workspace that never declared one.\n 'AWS::APS::Workspace': {\n WorkspaceConfiguration: {\n RuleQueryOffsetInSeconds: 60,\n RetentionPeriodInDays: 150,\n OutOfOrderTimeWindowInSeconds: 60,\n LimitsPerLabelSets: [],\n },\n },\n 'AWS::Pipes::Pipe': {\n DesiredState: 'RUNNING',\n },\n 'AWS::Synthetics::Canary': {\n FailureRetentionPeriod: 31,\n SuccessRetentionPeriod: 31,\n ProvisionedResourceCleanup: 'AUTOMATIC',\n },\n 'AWS::MSK::Cluster': {\n EnhancedMonitoring: 'DEFAULT',\n StorageMode: 'LOCAL',\n },\n 'AWS::Glue::Job': {\n JobMode: 'SCRIPT',\n MaxRetries: 0,\n },\n // R-noise-sweep (PR #355 follow-up): constant service defaults a fresh resource\n // reports as undeclared on every first run. Each is a documented account-/region-\n // independent default (NOT a per-resource id/name/AZ/window/port-that-varies-by-engine),\n // equality-gated like every KNOWN_DEFAULTS entry — flip one out of band and it no\n // longer matches, so it re-surfaces as real drift.\n 'AWS::AutoScaling::AutoScalingGroup': {\n Cooldown: '300', // default cooldown 300s (CC returns it as a string)\n HealthCheckType: 'EC2',\n HealthCheckGracePeriod: 0,\n },\n // A warm pool that declares no MinSize reads back MinSize:0 — the documented\n // constant default (\"minimum 0 warmed instances\"). Observed undeclared on a fresh\n // ecs-capacityprovider-rich deploy. Equality-gated: raise it out of band and it\n // no longer matches, so it surfaces as real undeclared drift.\n 'AWS::AutoScaling::WarmPool': {\n MinSize: 0,\n },\n 'AWS::DocDB::DBCluster': {\n Port: 27017, // DocDB's fixed default port\n },\n 'AWS::SSM::Association': {\n DocumentVersion: '$DEFAULT', // default when no explicit version is pinned\n },\n // CloudWatch alarm defaults. A metric Alarm's `ActionsEnabled` already folds via its\n // CFn schema default, so only `TreatMissingData` (the documented \"missing\" default,\n // surfaced as undeclared whenever a template omits it — the common case) is added here.\n // DatapointsToAlarm is NOT folded — it defaults to EvaluationPeriods (a per-alarm value,\n // not a constant); EvaluationPeriods/Threshold/ComparisonOperator are required so they\n // are always declared, never first-run noise. CompositeAlarm has NO schema default for\n // `ActionsEnabled` (observed undeclared in the corpus), so it needs the explicit fold.\n 'AWS::CloudWatch::Alarm': {\n TreatMissingData: 'missing',\n },\n 'AWS::CloudWatch::CompositeAlarm': {\n ActionsEnabled: true,\n },\n 'AWS::CloudWatch::MetricStream': {\n IncludeLinkedAccountsMetrics: false,\n State: 'running', // steady state after a successful create\n },\n 'AWS::Logs::LogGroup': {\n LogGroupClass: 'STANDARD',\n DeletionProtectionEnabled: false,\n BearerTokenAuthenticationEnabled: false,\n },\n 'AWS::ApiGateway::Method': {\n ApiKeyRequired: false,\n },\n 'AWS::ApiGatewayV2::Route': {\n ApiKeyRequired: false,\n },\n 'AWS::ElasticLoadBalancingV2::ListenerRule': {\n IsDefault: false, // a declared rule is never the listener's default rule\n },\n // A Glue Crawler with no Lake Formation config reads back the \"off\" sentinel object\n // (empty AccountId + creds disabled) — whole-object equality-gated, so configuring\n // Lake Formation still surfaces.\n 'AWS::Glue::Crawler': {\n LakeFormationConfiguration: { AccountId: '', UseLakeFormationCredentials: false },\n },\n // A config-change-triggered ConfigRule reads back EvaluationModes [{Mode:\"DETECTIVE\"}]\n // (the default) when the template does not declare it. Observed live on the\n // config-rule-rich fixture. Equality-gated: a PROACTIVE mode no longer matches.\n 'AWS::Config::ConfigRule': {\n EvaluationModes: [{ Mode: 'DETECTIVE' }],\n },\n // CloudWatch RUM AppMonitor service defaults (observed live on the\n // rum-appmonitor-rich fixture): a monitor that does not declare Platform reads\n // back \"Web\" (the default/only web platform), and one that does not configure\n // source-map deobfuscation reads back the disabled-state object. Equality-gated:\n // an Android/iOS platform or an enabled deobfuscation config no longer matches and\n // surfaces as a real undeclared value.\n 'AWS::RUM::AppMonitor': {\n Platform: 'Web',\n DeobfuscationConfiguration: { JavaScriptSourceMaps: { Status: 'DISABLED' } },\n },\n // FIS experiment templates read back the documented option defaults (fail on\n // empty target resolution, single-account targeting) when the template declares\n // no ExperimentOptions. Observed live on the misc-0cov-rich fixture.\n // Equality-gated: multi-account targeting or skip-mode no longer matches.\n 'AWS::FIS::ExperimentTemplate': {\n ExperimentOptions: {\n EmptyTargetResolutionMode: 'fail',\n AccountTargeting: 'single-account',\n },\n },\n // A Verified Permissions policy store is created without deletion protection by\n // default. Observed live on the misc-0cov-rich fixture. Equality-gated: enabling\n // protection out of band no longer matches and surfaces.\n // Schema: a store created without a Cedar schema reads back the constant empty-schema\n // husk `{\"CedarJson\":\"{}\"}` (an empty Cedar schema serialized as the string \"{}\" inside\n // an object) — a JSON-string cousin of the #491 Workgroup husk, but the non-empty \"{}\"\n // string defeats the trivially-empty drop, so it needs an explicit equality-gated\n // default. A store that later declares a real Cedar schema reads a non-matching value\n // and surfaces (undeclared). Observed live on hunt round B (#496 note 2 — a top-level\n // undeclared key, so KNOWN_DEFAULTS not KNOWN_DEFAULT_PATHS is the fit).\n 'AWS::VerifiedPermissions::PolicyStore': {\n DeletionProtection: { Mode: 'DISABLED' },\n Schema: { CedarJson: '{}' },\n },\n // RedshiftServerless service defaults (observed live on hunt 2026-07-03, #492): a\n // namespace reads back the \"admin\" default admin username and the AWS-owned KMS key\n // sentinel; a workgroup reads back the Redshift default Port, the \"current\" release\n // track, and price-performance auto-scaling DISABLED. All equality-gated — a namespace\n // that sets its own admin/KMS, or a workgroup on a pinned track / non-default port, no\n // longer matches and surfaces. The Workgroup echo attribute (a full self-echo of the\n // model) is handled separately (see the ECHO_HUSK_DEFAULTS note / #491).\n 'AWS::RedshiftServerless::Namespace': {\n AdminUsername: 'admin',\n KmsKeyId: 'AWS_OWNED_KMS_KEY',\n },\n 'AWS::RedshiftServerless::Workgroup': {\n Port: 5439,\n TrackName: 'current',\n PricePerformanceTarget: { Status: 'DISABLED' },\n // The Workgroup echo attribute is a full self-echo of the model; the schema marks only\n // its LEAVES readOnly (WorkgroupId, NetworkInterfaceId, ...), so a strip residue \"husk\"\n // survives: `{Endpoint:{VpcEndpoints:[{NetworkInterfaces:[{},{}]}]}, PricePerformanceTarget:\n // {Status:\"DISABLED\"}}` (#491). matchesKnownDefault skips the trivially-empty `Endpoint`\n // (the extended isTrivialEmpty folds the `[{},{}]` ENI husk regardless of per-deploy ENI\n // count), so only the meaningful `PricePerformanceTarget` sub-key is matched here — a\n // workgroup with price-performance ENABLED reads a non-matching value and surfaces.\n Workgroup: { PricePerformanceTarget: { Status: 'DISABLED' } },\n },\n // Bedrock Agent service defaults (observed live on hunt 2026-07-03, #492): an agent\n // reads back multi-agent collaboration DISABLED and the DEFAULT orchestration type when\n // the template declares neither. Equality-gated — an agent that opts into collaboration\n // or a custom orchestration no longer matches and surfaces. (AgentAlias\n // RoutingConfiguration is per-resource state, NOT a default — deliberately not folded.)\n 'AWS::Bedrock::Agent': {\n AgentCollaboration: 'DISABLED',\n OrchestrationType: 'DEFAULT',\n },\n // A CodeStar notification rule / Recycle Bin rule read back the \"on\" default status when\n // the template declares none (observed live on hunt 2026-07-03, #492). These ARE\n // user-settable knobs (a user can pause a rule) — equality-gated, so a DISABLED rule no\n // longer matches and surfaces as a real undeclared value.\n 'AWS::CodeStarNotifications::NotificationRule': {\n Status: 'ENABLED',\n },\n 'AWS::Rbin::Rule': {\n Status: 'available',\n },\n // RolesAnywhere service-filled constant SETS on create (observed live on hunt\n // 2026-07-03, #492): a trust anchor reads back the two-entry certificate-expiry\n // notification set, and a profile reads back the default x509 attribute-mapping rules,\n // when the template declares neither. Whole-value equality-gated — a trust anchor with\n // custom notifications, or a profile with custom mappings, no longer matches and surfaces.\n 'AWS::RolesAnywhere::TrustAnchor': {\n NotificationSettings: [\n { Channel: 'ALL', Enabled: true, Event: 'CA_CERTIFICATE_EXPIRY', Threshold: 45 },\n { Channel: 'ALL', Enabled: true, Event: 'END_ENTITY_CERTIFICATE_EXPIRY', Threshold: 45 },\n ],\n },\n // Amazon Location deprecated `PricingPlan` parameter — the service echoes the constant\n // \"RequestBasedUsage\" on every tracker / geofence collection even though the parameter\n // is deprecated and un-settable (observed live on hunt 2026-07-03, #492). Equality-gated.\n 'AWS::Location::Tracker': {\n PricingPlan: 'RequestBasedUsage',\n },\n 'AWS::Location::GeofenceCollection': {\n PricingPlan: 'RequestBasedUsage',\n },\n // hunt 2026-07-03 round B (#496): constant service defaults on zero-coverage type\n // families (MediaTailor / IVS / Lightsail / Site-to-Site VPN / Transfer / DataSync /\n // AppFlow / DataBrew). Values are exactly what Cloud Control returned on a fresh\n // untouched deploy; none is a per-resource id/ARN/name, so the equality-gated fold can\n // never hide a real change. Per-resource derived state is deliberately NOT folded (ELB\n // AvailabilityZones mirrors declared Subnets — #496 note 1).\n 'AWS::MediaTailor::PlaybackConfiguration': {\n InsertionMode: 'STITCHED_ONLY',\n AdConditioningConfiguration: { StreamingMediaFileConditioning: 'TRANSCODE' },\n AvailSuppression: { Mode: 'OFF' },\n },\n 'AWS::IVS::Channel': {\n MultitrackInputConfiguration: { Enabled: false, MaximumResolution: 'FULL_HD', Policy: 'ALLOW' },\n },\n 'AWS::Lightsail::Instance': {\n KeyPairName: 'LightsailDefaultKeyPair',\n },\n 'AWS::Lightsail::Disk': {\n AddOns: [{ AddOnType: 'AutoSnapshot', Status: 'Disabled' }],\n },\n 'AWS::Lightsail::Bucket': {\n AccessRules: { AllowPublicOverrides: false, GetObject: 'private' },\n },\n 'AWS::Lightsail::Alarm': {\n NotificationTriggers: ['ALARM'],\n },\n 'AWS::EC2::VPNConnection': {\n RemoteIpv4NetworkCidr: '0.0.0.0/0',\n LocalIpv4NetworkCidr: '0.0.0.0/0',\n OutsideIpAddressType: 'PublicIpv4',\n TunnelInsideIpVersion: 'ipv4',\n },\n 'AWS::Transfer::Server': {\n IpAddressType: 'IPV4',\n ProtocolDetails: {\n PassiveIp: 'AUTO',\n SetStatOption: 'DEFAULT',\n TlsSessionResumptionMode: 'ENFORCED',\n },\n },\n 'AWS::DataSync::Task': {\n TaskMode: 'BASIC',\n },\n // AppFlow FlowStatus is a user-settable knob (a user can suspend a flow), like the\n // CodeStarNotifications Status above — equality-gated so a suspended flow surfaces.\n 'AWS::AppFlow::Flow': {\n FlowStatus: 'Active',\n },\n // DataBrew Dataset Source is a per-input-kind constant (\"S3\" for an S3 dataset); the\n // equality-gated fold is safe (a JDBC/Redshift dataset reads a non-matching value).\n 'AWS::DataBrew::Dataset': {\n Source: 'S3',\n },\n // Amazon Keyspaces service defaults (observed live on the misc-0cov-rich\n // fixture): a keyspace with no ReplicationSpecification is single-region; a\n // table with no explicit settings reads back the account-constant warm\n // throughput floor (12000/4000 — same constant DynamoDB TableV2 reports), the\n // AWS-owned KMS key, and CDC disabled. All equality-gated.\n 'AWS::Cassandra::Keyspace': {\n ReplicationSpecification: { ReplicationStrategy: 'SINGLE_REGION' },\n },\n 'AWS::Cassandra::Table': {\n WarmThroughput: { ReadUnitsPerSecond: 12000, WriteUnitsPerSecond: 4000 },\n EncryptionSpecification: { EncryptionType: 'AWS_OWNED_KMS_KEY' },\n CdcSpecification: { Status: 'DISABLED' },\n },\n // EMR Serverless application service defaults (observed live on the\n // misc-0cov-rich fixture): x86_64 architecture and managed-persistence\n // monitoring enabled. Equality-gated: an ARM64 app or disabled managed\n // persistence no longer matches and surfaces.\n 'AWS::EMRServerless::Application': {\n Architecture: 'X86_64',\n MonitoringConfiguration: {\n ManagedPersistenceMonitoringConfiguration: { Enabled: true },\n },\n },\n // Amplify app service defaults (observed live on the amplify-codeconnections-rich\n // fixture): the standard build compute size and the managed no-cookies CDN cache.\n // Equality-gated: a larger build machine or cookie-forwarding cache no longer\n // matches and surfaces.\n 'AWS::Amplify::App': {\n JobConfig: { BuildComputeType: 'STANDARD_8GB' },\n CacheConfig: { Type: 'AMPLIFY_MANAGED_NO_COOKIES' },\n },\n // A hostless connection (GitHub/Bitbucket cloud providers) reads HostArn back as\n // this literal ALL-ZEROS placeholder ARN — a service sentinel for \"no host\", not\n // a reference to anything in the user's account (region/account/id are all\n // zeroed constants). Observed live on the amplify-codeconnections-rich fixture.\n // Equality-gated: a real GitHub Enterprise / GitLab self-managed host ARN no\n // longer matches and surfaces.\n 'AWS::CodeStarConnections::Connection': {\n HostArn:\n 'arn:aws:codestar-connections:us-west-2:000000000000:host/00000000-0000-0000-0000-000000000000',\n },\n};\n\n// R108: nested service defaults — the NESTED-path twin of KNOWN_DEFAULTS. The\n// Cloud Control read returns the full live model, so a config-dense type's\n// DECLARED parent property (CloudFront DistributionConfig, ApiGateway Method\n// Integration, Glue TableInput, …) comes back carrying many sub-keys AWS\n// materialized as documented defaults the user never set. R103's\n// `schema.defaultPaths` folds the ones the CFn schema annotates with `default`;\n// the schema annotates very few, so the rest flood a first run as `undeclared`\n// (nested) noise. This table is the hand-coded equivalent for the nested paths\n// the schema does NOT annotate — exactly what KNOWN_DEFAULTS is for top-level\n// keys, lifted to dotted paths.\n//\n// Keyed BY DOTTED PATH with `*` for array elements, matching the shape the\n// classify nested loop computes (`path.replace(/\\[[^\\]]*\\]/g, '.*')`) and the\n// shape `schema.defaultPaths` already uses, so both sources read through one\n// lookup. The VALUE is the exact emitted live value: a leaf scalar when the\n// parent array/object is declared and only a sub-leaf is live-only, or the whole\n// sub-object when an entire sub-key is live-only. Every entry below was OBSERVED\n// verbatim in the golden corpus.\n//\n// Equality-gated exactly like KNOWN_DEFAULTS: a value folds to `atDefault` ONLY\n// when it deep-equals the listed default, so an out-of-band change away from the\n// default no longer matches and falls through to a real `undeclared` finding;\n// `atDefault` is still surfaced (folded into the report footer, listed by\n// --show-all), never dropped and never recorded by record. Values that are a\n// generated ID (not a constant) are EXCLUDED here and folded as `generated`\n// instead — via GENERATED_DEFAULTS / isGeneratedName, or GENERATED_PATHS for a\n// nested id cdkrd cannot template (ApiGateway Method `Integration.CacheNamespace`,\n// the parent Resource's id). Genuine resource-/account-specific inventory stays\n// EXCLUDED from both (Budgets `Budget.BudgetName`, the GSI-nested\n// `*.WarmThroughput`). The TOP-LEVEL TableV2 `WarmThroughput`, by contrast, IS a\n// constant first-run default (12000/4000) and folds via KNOWN_DEFAULTS above —\n// equality-gated, so a warmed-up table still surfaces.\nexport const KNOWN_DEFAULT_PATHS: Record<string, Record<string, unknown>> = {\n // A Managed Service for Apache Flink application that declares no encryption config\n // reads back the AWS-owned-key default. Constant (a customer CMK is set explicitly).\n // Equality-gated: an out-of-band switch to a customer key no longer matches. Observed\n // live on a fresh READY Flink app (streaming-rich fixture, 2026-07-03; #509).\n 'AWS::KinesisAnalyticsV2::Application': {\n 'ApplicationConfiguration.ApplicationEncryptionConfiguration': { KeyType: 'AWS_OWNED_KEY' },\n },\n 'AWS::Lambda::Function': {\n // A function whose LoggingConfig declares no explicit format/level reads back the AWS\n // defaults: plain-Text logs at the INFO system level. Equality-gated, so a function that\n // opts into JSON logging (or a different level) still surfaces the non-default value.\n 'LoggingConfig.LogFormat': 'Text',\n 'LoggingConfig.SystemLogLevel': 'INFO',\n // A function that opts into JSON logs (`LogFormat: 'JSON'`, declared) but does not pin an\n // application log level reads back the AWS default INFO for the undeclared\n // `ApplicationLogLevel` sub-key — observed live on fresh (non-imported) stacks whose\n // functions set only LogFormat. Equality-gated, so a function that pins a different level\n // (DEBUG/ERROR/…) still surfaces the non-default value. (A Lambda DURABLE FUNCTION defaults\n // LogFormat itself to JSON — see the DurableConfig override in classify.ts.)\n 'LoggingConfig.ApplicationLogLevel': 'INFO',\n },\n // EMR Serverless fills MaximumCapacity.Disk with the service-wide maximum\n // (\"400000 GB\") when the template declares only Cpu/Memory. A constant, not\n // capacity-derived (observed with a 4 vCPU / 16 GB cap on the misc-0cov-rich\n // fixture). Equality-gated: a real disk cap no longer matches and surfaces.\n 'AWS::EMRServerless::Application': {\n 'MaximumCapacity.Disk': '400000 GB',\n },\n // ECS materializes ManagedDraining:\"ENABLED\" (the documented constant default) into\n // AutoScalingGroupProvider when the template omits it — CDK's AsgCapacityProvider\n // doesn't render it unless set, so every ECS-on-EC2 first run reports it as\n // undeclared. Equality-gated: disable draining out of band and it surfaces.\n // Observed live on a fresh ecs-capacityprovider-rich deploy.\n 'AWS::ECS::CapacityProvider': {\n 'AutoScalingGroupProvider.ManagedDraining': 'ENABLED',\n },\n // AWS Backup materializes these defaults into each live BackupPlanRule (keyed by RuleName\n // — descended via NESTED_ARRAY_IDENTITY). Folding them keeps a clean plan clean; an\n // out-of-band change away from one still surfaces (equality-gated). Proven live: a\n // CDK-default daily rule reads back StartWindowMinutes 480 / CompletionWindowMinutes 10080\n // / ScheduleExpressionTimezone Etc/UTC (the empty CopyActions/ScanActions/IndexActions/\n // RecoveryPointTags fold via isTrivialEmpty).\n 'AWS::Backup::BackupPlan': {\n 'BackupPlan.BackupPlanRule.*.CompletionWindowMinutes': 10080,\n 'BackupPlan.BackupPlanRule.*.StartWindowMinutes': 480,\n 'BackupPlan.BackupPlanRule.*.ScheduleExpressionTimezone': 'Etc/UTC',\n },\n // AWS Data Lifecycle Manager materializes these constants into every live custom\n // EBS-snapshot policy the template leaves unset: ResourceLocations defaults to [\"CLOUD\"]\n // (vs an Outpost), PolicyLanguage to \"STANDARD\", each schedule's CreateRule.Location to\n // \"CLOUD\", and a Count-based RetainRule reads back Interval 0 (the interval-based\n // alternative unused). Schedules are keyed by Name (auto-detected identity). Folding keeps\n // a clean policy clean; a real change away from any default still surfaces (equality-gated).\n // Proven live on a minimal daily-backup policy (issue #468).\n 'AWS::DLM::LifecyclePolicy': {\n 'PolicyDetails.ResourceLocations': ['CLOUD'],\n 'PolicyDetails.PolicyLanguage': 'STANDARD',\n 'PolicyDetails.Schedules.*.CreateRule.Location': 'CLOUD',\n 'PolicyDetails.Schedules.*.RetainRule.Interval': 0,\n },\n // AWS Route53 Resolver materializes a FirewallDomainRedirectionAction default into each\n // live FirewallRule (keyed by Priority — descended via NESTED_ARRAY_IDENTITY).\n // Equality-gated, so a rule changed away from the default still surfaces. Proven live on a\n // CDK-default BLOCK rule. (The sibling FirewallThreatProtectionId is readOnly — stripped\n // before the nested loop — so it needs no entry here.)\n 'AWS::Route53Resolver::FirewallRuleGroup': {\n 'FirewallRules.*.FirewallDomainRedirectionAction': 'INSPECT_REDIRECTION_DOMAIN',\n },\n // AWS materializes the default AWS-managed KMS key into each live replica region (keyed\n // by Region — descended via NESTED_ARRAY_IDENTITY) when the replica declares no KmsKeyId.\n // Folding keeps a clean multi-region secret clean; a replica re-keyed to a different CMK\n // out of band no longer matches and surfaces. Proven live.\n 'AWS::SecretsManager::Secret': {\n 'ReplicaRegions.*.KmsKeyId': 'alias/aws/secretsmanager',\n },\n 'AWS::ApiGateway::DomainName': {\n // AWS sets a custom domain's IP address type to ipv4 when the template leaves\n // EndpointConfiguration.IpAddressType unset — a server default, not user intent.\n 'EndpointConfiguration.IpAddressType': 'ipv4',\n },\n 'AWS::ApiGateway::Method': {\n 'Integration.PassthroughBehavior': 'WHEN_NO_MATCH',\n 'Integration.ResponseTransferMode': 'BUFFERED',\n 'Integration.TimeoutInMillis': 29000,\n },\n // AWS materializes the caching scalar default into every live MethodSettings element\n // (keyed by HttpMethod — descended via NESTED_ARRAY_IDENTITY) when the stage declares\n // only throttling/tracing. Folding keeps a clean stage clean; a method whose cache TTL\n // was changed out of band no longer matches and surfaces. The sibling defaults\n // CacheDataEncrypted / CachingEnabled / MetricsEnabled all read back `false` and fold via\n // isTrivialEmpty (so enabling any of them out of band — a non-`false` value — surfaces).\n // The two Throttling* defaults are the account-level API Gateway throttle limits AWS\n // applies to every method that declares no per-method throttle (rate 10000 req/s,\n // burst 5000 — the documented account defaults). A stage that never set throttling\n // otherwise reports both on every first run as undeclared drift. Equality-gated: a\n // method pinned to a different limit (or an account whose quota was raised) no longer\n // matches and surfaces. Proven live (RestApi DeploymentStage with no method throttle).\n 'AWS::ApiGateway::Stage': {\n 'MethodSettings.*.CacheTtlInSeconds': 300,\n 'MethodSettings.*.ThrottlingBurstLimit': 5000,\n 'MethodSettings.*.ThrottlingRateLimit': 10000,\n },\n 'AWS::ApiGateway::UsagePlan': {\n 'Quota.Offset': 0,\n },\n 'AWS::CloudFront::Distribution': {\n 'DistributionConfig.OriginGroups': { Quantity: 0, Items: [] },\n 'DistributionConfig.Origins.*.ConnectionAttempts': 3,\n 'DistributionConfig.Origins.*.ConnectionTimeout': 10,\n 'DistributionConfig.Origins.*.CustomOriginConfig.HTTPPort': 80,\n 'DistributionConfig.Origins.*.CustomOriginConfig.HTTPSPort': 443,\n 'DistributionConfig.Origins.*.CustomOriginConfig.OriginKeepaliveTimeout': 5,\n 'DistributionConfig.Origins.*.S3OriginConfig.OriginReadTimeout': 30,\n 'DistributionConfig.Restrictions': {\n GeoRestriction: { Locations: [], RestrictionType: 'none' },\n },\n 'DistributionConfig.ViewerCertificate': {\n SslSupportMethod: 'vip',\n MinimumProtocolVersion: 'TLSv1',\n CloudFrontDefaultCertificate: true,\n },\n },\n 'AWS::CodeBuild::Project': {\n 'Environment.ImagePullCredentialsType': 'CODEBUILD',\n // A project with no explicit artifacts (NO_ARTIFACTS source) reads back the\n // Packaging default NONE — R-noise-sweep, observed live.\n 'Artifacts.Packaging': 'NONE',\n },\n 'AWS::Cognito::UserPool': {\n 'AdminCreateUserConfig.UnusedAccountValidityDays': 7,\n 'Policies.SignInPolicy': { AllowedFirstAuthFactors: ['PASSWORD'] },\n // A pool that declares a PasswordPolicy but omits the temporary-password lifetime\n // reads back the 7-day default (observed live); a pool that sets a different value\n // no longer matches and surfaces (equality-gated).\n 'Policies.PasswordPolicy.TemporaryPasswordValidityDays': 7,\n // A DECLARED standard schema attribute (email/name, keyed by Name via\n // NESTED_ARRAY_IDENTITY) that omits its data type / string constraints reads back\n // Cognito's constant defaults: a String attribute with a 0..2048 length range. The\n // whole live-only standard attributes fold via IDENTITY_KEYED_DEFAULT_ELEMENTS, but a\n // PARTIALLY-declared one (Required/Mutable set, type left to AWS) surfaces these two\n // AWS-filled sub-keys instead. Equality-gated: a Number attribute reads a non-String\n // type, and a custom-constrained String reads a non-matching range, so both surface.\n 'Schema.*.AttributeDataType': 'String',\n 'Schema.*.StringAttributeConstraints': { MinLength: '0', MaxLength: '2048' },\n },\n // A Google (or any social/OIDC) identity provider declares only its credentials\n // (client_id / client_secret / authorize_scopes) and attribute mappings; Cognito\n // DERIVES and returns the provider's well-known OIDC endpoints and its default\n // username->sub mapping, which the template never carries, so a fresh provider floods\n // every first run with these live-only sub-keys. They are Cognito-injected provider\n // metadata, not user intent. Equality-gated to Google's constant endpoints, so a\n // different provider's URLs (or a value AWS changes) do not match and surface.\n // Observed live on a dev Google IdP.\n 'AWS::Cognito::UserPoolIdentityProvider': {\n 'ProviderDetails.authorize_url': 'https://accounts.google.com/o/oauth2/v2/auth',\n 'ProviderDetails.token_url': 'https://www.googleapis.com/oauth2/v4/token',\n 'ProviderDetails.attributes_url': 'https://people.googleapis.com/v1/people/me?personFields=',\n 'ProviderDetails.oidc_issuer': 'https://accounts.google.com',\n 'ProviderDetails.token_request_method': 'POST',\n 'ProviderDetails.attributes_url_add_attributes': 'true',\n 'AttributeMapping.username': 'sub',\n },\n // A REGIONAL RestApi (EndpointConfiguration declares only Types:['REGIONAL']) reads\n // back EndpointConfiguration.IpAddressType: 'ipv4' — the server default the template\n // never sets. The whole-object KNOWN_DEFAULTS entry only covers the EDGE default shape,\n // so a REGIONAL api's IpAddressType surfaces as an undeclared sub-key; fold the path\n // here. Equality-gated: a dualstack api no longer matches and surfaces. Observed live.\n 'AWS::ApiGateway::RestApi': {\n 'EndpointConfiguration.IpAddressType': 'ipv4',\n },\n 'AWS::DynamoDB::Table': {\n 'PointInTimeRecoverySpecification.RecoveryPeriodInDays': 35,\n },\n 'AWS::ECS::TaskDefinition': {\n // A container that does not reserve CPU reads back Cpu: 0 (the documented \"no\n // reservation\" default) for EVERY container, so a multi-container task def floods\n // the first run with `ContainerDefinitions[*].Cpu = 0` not-recorded noise. Fold the\n // constant default to atDefault; a container that actually reserves CPU (Cpu != 0)\n // no longer matches and surfaces. Observed live on the ecs-taskdef-caps deploy.\n 'ContainerDefinitions.*.Cpu': 0,\n },\n 'AWS::Glue::Database': {\n 'DatabaseInput.CreateTableDefaultPermissions': [\n {\n Permissions: ['ALL'],\n Principal: { DataLakePrincipalIdentifier: 'IAM_ALLOWED_PRINCIPALS' },\n },\n ],\n },\n 'AWS::Glue::Table': {\n 'TableInput.Retention': 0,\n 'TableInput.StorageDescriptor.NumberOfBuckets': 0,\n },\n 'AWS::Route53::HealthCheck': {\n 'HealthCheckConfig.EnableSNI': true,\n },\n 'AWS::Route53::RecordSet': {\n // A geoproximity record may declare only AWSRegion (or Coordinates); AWS then sets\n // Bias to 0 and returns it. Fold that server default so a record that never set a\n // bias stays CLEAN, while a real out-of-band bias change still surfaces.\n 'GeoProximityLocation.Bias': 0,\n },\n 'AWS::S3::Bucket': {\n 'LifecycleConfiguration.TransitionDefaultMinimumObjectSize': 'all_storage_classes_128K',\n },\n 'AWS::Scheduler::Schedule': {\n 'Target.RetryPolicy': { MaximumEventAgeInSeconds: 86400, MaximumRetryAttempts: 185 },\n },\n 'AWS::ECS::Service': {\n // A service declaring no deployment configuration reads back AWS's defaults — the\n // ROLLING strategy with a 0-minute bake time. Observed unanimous across the corpus.\n 'DeploymentConfiguration.Strategy': 'ROLLING',\n 'DeploymentConfiguration.BakeTimeInMinutes': 0,\n // A service that enables the deployment circuit breaker reads back these AWS-filled\n // sub-defaults (reset the deployment count once a task is healthy, and the built-in\n // BOUNDED_PERCENT / 50% failure threshold). Observed live on a fresh Fargate service.\n 'DeploymentConfiguration.DeploymentCircuitBreaker.ResetOnHealthyTask': true,\n 'DeploymentConfiguration.DeploymentCircuitBreaker.ThresholdConfiguration': {\n Type: 'BOUNDED_PERCENT',\n Value: 50,\n },\n },\n 'AWS::OpenSearchService::Domain': {\n // A gp3 EBS volume reads back the gp3 baseline 3000 IOPS / 125 MiB/s throughput\n // when the template leaves them unset — server defaults, not user intent.\n 'EBSOptions.Iops': 3000,\n 'EBSOptions.Throughput': 125,\n },\n 'AWS::KinesisFirehose::DeliveryStream': {\n // S3 backup is Disabled by default when a destination declares no backup mode.\n 'ExtendedS3DestinationConfiguration.S3BackupMode': 'Disabled',\n // A destination declaring no compression / encryption reads back the AWS defaults:\n // UNCOMPRESSED delivery and no server-side encryption. Observed live.\n 'ExtendedS3DestinationConfiguration.CompressionFormat': 'UNCOMPRESSED',\n 'ExtendedS3DestinationConfiguration.EncryptionConfiguration': {\n NoEncryptionConfig: 'NoEncryption',\n },\n },\n 'AWS::Athena::WorkGroup': {\n // A workgroup that declares no configuration reads back AWS's defaults: the config is\n // enforced on member queries, the engine version auto-selects, and CloudWatch query\n // metrics are published. Observed live. These fold when WorkGroupConfiguration is DESCENDED\n // (DESCEND_UNDECLARED_OBJECT_PATHS, #565) because a non-default sibling made the whole\n // object miss the whole-object fold; RequesterPaysEnabled:false folds as trivially-empty.\n 'WorkGroupConfiguration.EnforceWorkGroupConfiguration': true,\n 'WorkGroupConfiguration.EngineVersion': { SelectedEngineVersion: 'AUTO' },\n 'WorkGroupConfiguration.PublishCloudWatchMetricsEnabled': true,\n },\n 'AWS::EKS::Cluster': {\n // A cluster that declares SubnetIds (partially declaring ResourcesVpcConfig, so it is\n // descended) reads back AWS's endpoint defaults on the sibling sub-keys. Constants,\n // equality-gated. Observed live (hunt 2026-07-03 round E).\n 'ResourcesVpcConfig.EndpointPublicAccess': true,\n 'ResourcesVpcConfig.PublicAccessCidrs': ['0.0.0.0/0'],\n 'ResourcesVpcConfig.ControlPlaneEgressMode': 'AWS_MANAGED',\n // KubernetesNetworkConfig is fully undeclared, so it is DESCENDED via\n // DESCEND_UNDECLARED_OBJECT_PATHS (#555). IpFamily is the constant \"ipv4\" default (the\n // only alternative, \"ipv6\", is an explicit opt-in); ElasticLoadBalancing {Enabled:false}\n // folds as trivially-empty, leaving only the per-deploy ServiceIpv4Cidr as residue.\n 'KubernetesNetworkConfig.IpFamily': 'ipv4',\n },\n 'AWS::ApplicationSignals::ServiceLevelObjective': {\n // An SLO goal that declares no warning threshold reads back the 50(%) default.\n // Observed live. Equality-gated, so a custom threshold still surfaces.\n 'Goal.WarningThreshold': 50,\n },\n // R-noise-sweep (offline corpus audit): nested constant defaults the schema does\n // not annotate. Equality-gated; a non-default value still surfaces.\n 'AWS::WAFv2::WebACL': {\n // A rate-based rule with no explicit window reads back the 5-minute (300s) default.\n 'Rules.*.Statement.RateBasedStatement.EvaluationWindowSec': 300,\n },\n 'AWS::WAFv2::RuleGroup': {\n // A RuleGroup hosts the SAME rate-based statement shape as a WebACL, so an\n // undeclared rate-based window reads back the identical 5-minute (300s) default.\n // Observed live on a fresh wafv2-ratecustomkeys deploy (issue #440).\n 'Rules.*.Statement.RateBasedStatement.EvaluationWindowSec': 300,\n },\n 'AWS::SES::EmailIdentity': {\n // A custom MAIL FROM domain reads back the documented default fallback behavior.\n 'MailFromAttributes.BehaviorOnMxFailure': 'USE_DEFAULT_VALUE',\n },\n 'AWS::SES::ReceiptRule': {\n // A rule that does not declare a TLS policy reads back the documented \"Optional\"\n // default. Equality-gated, so a rule switched to \"Require\" out of band still surfaces.\n // (The sibling Enabled / ScanEnabled booleans default false and fold via isTrivialEmpty.)\n 'Rule.TlsPolicy': 'Optional',\n },\n 'AWS::MSK::Cluster': {\n // Brokers spread across AZs read back the DEFAULT distribution when unspecified.\n 'BrokerNodeGroupInfo.BrokerAZDistribution': 'DEFAULT',\n },\n 'AWS::Batch::JobDefinition': {\n // A Fargate job definition reads back the documented runtime-platform defaults\n // (x86_64 / Linux) and the LATEST Fargate platform version when none is declared.\n 'ContainerProperties.RuntimePlatform.CpuArchitecture': 'X86_64',\n 'ContainerProperties.RuntimePlatform.OperatingSystemFamily': 'LINUX',\n 'ContainerProperties.FargatePlatformConfiguration.PlatformVersion': 'LATEST',\n },\n // DataSync task nested service defaults (observed live on hunt 2026-07-03 round B,\n // #496): a task whose declared `Options` block leaves these unset reads them back at\n // the documented transfer defaults, and a declared `Schedule` reads back Status ENABLED\n // (the schedule is active on create). Equality-gated per path — a task that pins any\n // Option / disables its schedule out of band no longer matches and surfaces. Per-input\n // BytesPerSecond -1 is the documented \"unlimited\" sentinel.\n 'AWS::DataSync::Task': {\n 'Options.Atime': 'BEST_EFFORT',\n 'Options.Mtime': 'PRESERVE',\n 'Options.Uid': 'NONE',\n 'Options.Gid': 'NONE',\n 'Options.PreserveDevices': 'NONE',\n 'Options.PosixPermissions': 'NONE',\n 'Options.ObjectTags': 'PRESERVE',\n 'Options.BytesPerSecond': -1,\n 'Options.SecurityDescriptorCopyFlags': 'NONE',\n 'Schedule.Status': 'ENABLED',\n },\n};\n\n// Default ELEMENTS of an identity-keyed SUBSET array (the per-element twin of\n// KNOWN_DEFAULT_PATHS): keyed by resourceType → array property → element identity →\n// the exact default element shape. When a live-only element of an\n// IDENTITY_KEYED_SUBSET_ARRAYS property (classify) deep-equals its entry here, it folds\n// to `atDefault` instead of nested `undeclared` — the same equality-gated treatment a\n// top-level default value gets, lifted to a keyed array element.\n//\n// The motivating case: a Cognito user pool ALWAYS returns the full set of ~20 OIDC\n// standard attributes in `Schema`, whether or not the template declares them, so a pool\n// that declares only custom (or a few standard) attributes floods every first run with\n// ~20 live-only standard-attribute entries. They are a FIXED, platform-provided default\n// set and are IMMUTABLE after pool creation (a standard attribute's Mutable / Required /\n// constraints cannot be changed later), so they can never be an out-of-band edit. A\n// standard attribute the template DECLARES (customizing it) is matched by identity and\n// compared instead (never reaching the live-only fold); any future shape AWS returns that\n// differs simply falls through to undeclared. Shapes captured live (ap-northeast-1).\nconst cognitoStdAttr = (\n Name: string,\n over: Record<string, unknown> = {}\n): Record<string, unknown> => ({\n AttributeDataType: 'String',\n DeveloperOnlyAttribute: false,\n Mutable: true,\n Name,\n Required: false,\n StringAttributeConstraints: { MinLength: '0', MaxLength: '2048' },\n ...over,\n});\nconst COGNITO_STRING_STD = [\n 'address',\n 'email',\n 'family_name',\n 'gender',\n 'given_name',\n 'locale',\n 'middle_name',\n 'name',\n 'nickname',\n 'phone_number',\n 'picture',\n 'preferred_username',\n 'profile',\n 'website',\n 'zoneinfo',\n];\nexport const IDENTITY_KEYED_DEFAULT_ELEMENTS: Record<\n string,\n Record<string, Record<string, Record<string, unknown>>>\n> = {\n 'AWS::Cognito::UserPool': {\n Schema: {\n ...Object.fromEntries(COGNITO_STRING_STD.map((n) => [n, cognitoStdAttr(n)])),\n birthdate: cognitoStdAttr('birthdate', {\n StringAttributeConstraints: { MinLength: '10', MaxLength: '10' },\n }),\n // `sub` is the immutable, required subject identifier\n sub: cognitoStdAttr('sub', {\n Mutable: false,\n Required: true,\n StringAttributeConstraints: { MinLength: '1', MaxLength: '2048' },\n }),\n // `identities` (federated-identity links) carries empty string constraints\n identities: cognitoStdAttr('identities', { StringAttributeConstraints: {} }),\n // `updated_at` is a Number with a min-value constraint and no string constraints\n updated_at: {\n AttributeDataType: 'Number',\n DeveloperOnlyAttribute: false,\n Mutable: true,\n Name: 'updated_at',\n NumberAttributeConstraints: { MinValue: '0' },\n Required: false,\n },\n // the two *_verified flags are Booleans with no constraints\n email_verified: {\n AttributeDataType: 'Boolean',\n DeveloperOnlyAttribute: false,\n Mutable: true,\n Name: 'email_verified',\n Required: false,\n },\n phone_number_verified: {\n AttributeDataType: 'Boolean',\n DeveloperOnlyAttribute: false,\n Mutable: true,\n Name: 'phone_number_verified',\n Required: false,\n },\n },\n },\n};\n\n// AWS/CDK auto-GENERATED values keyed by the resource's CFn-assigned physical id.\n// Unlike KNOWN_DEFAULTS (static values), each entry may interpolate the live\n// physical id via two placeholders, substituted by resolveGeneratedDefault before\n// the equality gate:\n// ${PHYSICAL_ID} - the PhysicalResourceId verbatim (an ARN or a bare name,\n// depending on the resource type)\n// ${PHYSICAL_NAME} - its trailing name segment (after the last ':' or '/'); for\n// an ARN physical id this is the bare resource name\n// These are the identifiers AWS minted for the resource, not user intent: a topic's\n// generated TopicName, a function's default LoggingConfig whose LogGroup is named\n// after the generated function name. They flood a first run as \"undeclared\" yet the\n// user never set and cannot meaningfully edit them. Classified as the `generated`\n// tier (folded inventory like atDefault), equality-gated exactly like KNOWN_DEFAULTS:\n// an out-of-band edit (a JSON LogFormat, say) no longer matches the substituted\n// template and falls through to a real `undeclared` finding. Never recorded by record.\n// GENERATED_DEFAULTS only carries the STRUCTURED cases the general name rule below\n// (isGeneratedName) cannot express — e.g. a Lambda's default LoggingConfig OBJECT,\n// where the generated name is one sub-field of an object also containing a literal\n// default (LogFormat: 'Text'). A bare generated NAME echoed as a scalar property\n// (a topic's TopicName, a state machine's StateMachineName, a bucket's BucketName)\n// needs no entry — isGeneratedName folds it for ANY resource type.\nexport const GENERATED_DEFAULTS: Record<string, Record<string, unknown>> = {\n 'AWS::Lambda::Function': {\n LoggingConfig: { LogFormat: 'Text', LogGroup: '/aws/lambda/${PHYSICAL_NAME}' },\n },\n};\n\n// NESTED paths whose value is an AWS-assigned generated id that ECHOES a segment of\n// the resource's physical id — for ids cdkrd cannot template from a single placeholder.\n// Example: an ApiGateway Method's `Integration.CacheNamespace` defaults to the PARENT\n// Resource's id, which is the MIDDLE segment of the Method's own physical id\n// (`RestApiId|ResourceId|HttpMethod`); neither KNOWN_DEFAULT_PATHS (a fixed value) nor\n// GENERATED_DEFAULTS (a single-placeholder template on the resource's own id) can express\n// it. Folded into the `generated` tier (inventory, never drift, never recorded) ONLY when\n// the value matches a physical-id segment (isPhysicalIdSegment) — so the AWS default stays\n// quiet while a CUSTOM value the user actually set still surfaces as undeclared, and an\n// out-of-band change to it reports as drift (R142; was value-independent in R140).\nexport const GENERATED_PATHS: Record<string, string[]> = {\n 'AWS::ApiGateway::Method': ['Integration.CacheNamespace'],\n // The live read echoes the rule's own ARN (== the resource's physical id) inside\n // the declared SamplingRule object — pure identity, never user-editable.\n // Observed live on the xray-insightrule-rich fixture.\n 'AWS::XRay::SamplingRule': ['SamplingRule.RuleARN'],\n};\n\n// Top-level UNDECLARED keys whose service default VALUE is derived from the READ\n// CONTEXT (the resource's own region), which a constant KNOWN_DEFAULTS entry cannot\n// express. Kinds: 'region' (the scalar region), 'regionList' (a single-element list\n// of the own region). Equality-gated against the resolved context like every default\n// fold — a value that differs (extra regions added out of band) no longer matches\n// and surfaces as real undeclared drift; with NO resolved region the value simply\n// stays `undeclared` (recordable), never a wrong fold. First case (observed live on\n// a fresh iot-vpces-rich deploy, issue #462): a VPC endpoint service that declares\n// no SupportedRegions reads back `[<own region>]`.\nexport const CONTEXT_DEFAULTS: Record<string, Record<string, 'region' | 'regionList'>> = {\n 'AWS::EC2::VPCEndpointService': { SupportedRegions: 'regionList' },\n};\n\n// Top-level UNDECLARED keys whose service default VALUE is derived from the resource's own\n// live ENGINE (RDS) — the engine-conditional twin of CONTEXT_DEFAULTS (region-derived) and\n// KNOWN_DEFAULTS (constant). A single constant cannot express these because the default\n// differs per engine family (aurora-mysql `StorageType`=\"aurora\" vs a provisioned MySQL's\n// \"gp2\", MySQL `Port`=3306 vs Postgres 5432), which is why the original KNOWN_DEFAULTS\n// comment left them unfolded — but that flooded every clean CDK Aurora first run with 4-7\n// potential-drift lines for values the user never set and (for the create-only ones) can\n// never change. Each entry maps the live `Engine` string to the default value, or `undefined`\n// when this engine has no single default (then the value stays `undeclared`, recordable).\n// Equality-gated with typed<->string coercion (a DBInstance echoes the port/storage as a\n// STRING \"3306\"/\"1\" while a DBCluster carries the NUMBER): a value that differs from the\n// engine default no longer matches and surfaces as real undeclared drift. Aurora is\n// create-only on StorageType, so its fold hides nothing revertable.\nexport const ENGINE_DEFAULTS: Record<string, Record<string, (engine: string) => unknown>> = {\n 'AWS::RDS::DBInstance': {\n StorageType: (e) => (e.startsWith('aurora') ? 'aurora' : undefined),\n AllocatedStorage: (e) => (e.startsWith('aurora') ? 1 : undefined),\n Port: rdsDefaultPort,\n LicenseModel: rdsDefaultLicense,\n },\n 'AWS::RDS::DBCluster': {\n StorageType: (e) => (e.startsWith('aurora') ? 'aurora' : undefined),\n AllocatedStorage: (e) => (e.startsWith('aurora') ? 1 : undefined),\n Port: rdsDefaultPort,\n },\n};\n\n// RDS engine-family default listener port. Only families with a single well-known default\n// are listed; an unknown engine returns undefined (no fold).\nfunction rdsDefaultPort(engine: string): number | undefined {\n if (/mysql|maria/.test(engine)) return 3306;\n if (/postgres/.test(engine)) return 5432;\n if (/oracle/.test(engine)) return 1521;\n if (/sqlserver/.test(engine)) return 1433;\n return undefined;\n}\n\n// RDS engine-family default LicenseModel. MySQL/MariaDB/Aurora-MySQL read back\n// \"general-public-license\"; Postgres/Aurora-Postgres \"postgresql-license\". Oracle/SQLServer\n// carry BYOL/license-included with no single default, so they return undefined (no fold).\nfunction rdsDefaultLicense(engine: string): string | undefined {\n if (/postgres/.test(engine)) return 'postgresql-license';\n if (/mysql|maria/.test(engine)) return 'general-public-license';\n return undefined;\n}\n\n// Top-level UNDECLARED keys whose value is an AWS-MANAGED default resource NAME, recognizable\n// by a `default`-family prefix rather than a constant. An RDS instance that pins no custom\n// parameter/option group reads back the engine's DEFAULT group — `DBParameterGroupName`\n// \"default.aurora-mysql8.0\" / \"default.mysql8.0\", `OptionGroupName` \"default:aurora-mysql-8-0\"\n// / \"default:mysql-8-0\". The `default.` / `default:` prefix is reserved by AWS for these\n// managed groups, so a CUSTOM group (whose name never starts with that prefix — observed in\n// the corpus, e.g. \"cdkrealdriftintegaurorarich-instancepg…\") still surfaces as real\n// undeclared inventory. Version-independent (matches any `default.<engine><ver>`), so it does\n// not go stale as KNOWN_DEFAULTS constants would.\nexport const DEFAULT_MANAGED_NAME_PATHS: Record<string, Record<string, RegExp>> = {\n 'AWS::RDS::DBInstance': {\n DBParameterGroupName: /^default\\./,\n OptionGroupName: /^default:/,\n },\n // The RDS-family + cache engines mirror the RDS `default.<engine><version>` precedent: a\n // cluster/instance/cache that declares no explicit parameter group reads back the AWS-managed\n // default group name (`default.redis7`, `default.docdb5.0`, `default.neptune1.3`,\n // `default.redshift-2.0`, `default.memorydb-redis7`). The name is version-derived (not a\n // pinnable constant), so it is regex-matched — a CUSTOM group name a user attached does not\n // start with `default.` and still surfaces. Undeclared-only, like the RDS precedent. Found by\n // the offline first-run-noise sweep across the corpus.\n 'AWS::ElastiCache::CacheCluster': { CacheParameterGroupName: /^default\\./ },\n 'AWS::DocDB::DBCluster': { DBClusterParameterGroupName: /^default\\./ },\n 'AWS::Neptune::DBCluster': { DBClusterParameterGroupName: /^default\\./ },\n 'AWS::Neptune::DBInstance': { DBParameterGroupName: /^default\\./ },\n 'AWS::Redshift::Cluster': { ClusterParameterGroupName: /^default\\./ },\n 'AWS::MemoryDB::Cluster': { ParameterGroupName: /^default\\./ },\n};\n\n// Top-level UNDECLARED keys that are ALWAYS a service-minted, AWS-managed generated\n// id — value-INDEPENDENT (unlike GENERATED_PATHS/isPhysicalIdSegment, the value is an\n// opaque churning id, not derivable from the physical id). An ApiGatewayV2 Stage with\n// AutoDeploy=true (the CDK HttpApi default) has its `DeploymentId` minted and re-minted\n// by the service on every auto-deployment; the user cannot set it (a manual set is\n// rejected: \"Deployment ID cannot be set ... because AutoDeploy is enabled\"). It is\n// live-only ONLY in the AutoDeploy case — a non-AutoDeploy stage DECLARES DeploymentId,\n// so it never reaches the undeclared loop — so folding it as `generated` (inventory:\n// never drift, never recorded, never reverted) is safe AND necessary: otherwise the id\n// churns into a false undeclared drift after ANY out-of-band API edit, and a revert of\n// it fails (AutoDeploy rejects the write) so the stack never converges. Observed live on\n// a fresh apigwv2-http-rich deploy.\nexport const GENERATED_TOPLEVEL_PATHS: Record<string, ReadonlySet<string>> = {\n 'AWS::ApiGatewayV2::Stage': new Set(['DeploymentId']),\n // A standalone SG rule that references another security group (self-ref or peer) reads back\n // a SourceSecurityGroupOwnerId AWS injects — the account that owns the referenced SG. The\n // template never declares it (CDK derives it from SourceSecurityGroupId), so on a fresh\n // self-referencing SG rule — the canonical ALB↔ASG / intra-cluster pattern — it floods the\n // first run as undeclared. It is tied to SourceSecurityGroupId (which IS compared), not an\n // independently-editable property, so folding it `generated` (inventory: never drift) is\n // safe; a meaningful change is a change to SourceSecurityGroupId itself. Observed live on\n // the securitygroup-protocols-rich fixture's self-ref rule.\n // A standalone SG rule reads back the GroupName of the SG it attaches to (CDK derives\n // the rule from GroupId, never declaring GroupName), so it floods a self-ref/peer rule's\n // first run as undeclared. Tied to GroupId (which IS compared), not independently\n // editable — a meaningful change is a change to the target SG. Observed live.\n 'AWS::EC2::SecurityGroupIngress': new Set(['SourceSecurityGroupOwnerId', 'GroupName']),\n // An awsvpc/Fargate ECS service that declares no service role reads back the AWS-injected\n // service-linked role ARN (`.../aws-service-role/ecs.amazonaws.com/AWSServiceRoleForECS`).\n // AWS-managed, not user intent, present on every such service. A service that DOES declare\n // a Role (classic-ELB pattern) carries it in the template and never reaches this loop.\n 'AWS::ECS::Service': new Set(['Role']),\n // A Secret whose Name the template omits reads back a CloudFormation-generated name\n // (`<constructId>-<random>` — NO stack prefix, so isCfnGeneratedName misses it). It is the\n // AWS-minted identity, not user intent; a Secret that DECLARES a Name carries it in the\n // template and never reaches this loop.\n 'AWS::SecretsManager::Secret': new Set(['Name']),\n // A target group's `Targets` that the template does not declare holds the targets AWS/ECS\n // registered at RUNTIME (dynamic task IPs) — not template intent, and they churn as tasks\n // recycle, so surfacing them as recordable drift is non-actionable (a record snapshot\n // immediately re-drifts). A group that DECLARES static Targets carries them in the template\n // and is compared normally, so a removed/changed static target still surfaces.\n 'AWS::ElasticLoadBalancingV2::TargetGroup': new Set(['Targets']),\n // An Application Auto Scaling policy attached to a target via ScalingTargetId (the CDK\n // pattern) reads back the target's ResourceId / ServiceNamespace / ScalableDimension,\n // which AWS derives from the target and the template never declares. They echo the\n // scalable target's identity, not independent settings. Observed live on an ECS\n // service-scaling policy.\n 'AWS::ApplicationAutoScaling::ScalingPolicy': new Set([\n 'ResourceId',\n 'ServiceNamespace',\n 'ScalableDimension',\n ]),\n // A published version's CodeSha256 is the base64 hash of the deployed code package —\n // a per-deploy, opaque, service-minted value (NOT a constant default, so KNOWN_DEFAULTS\n // cannot fold it). It is live-only ONLY when the template does not pin it; a version\n // that DECLARES CodeSha256 (to gate publication on specific code) carries it in the\n // template and never reaches the undeclared loop. Folding the live-only case as\n // `generated` (inventory: never drift, never recorded, never reverted) stops every\n // `currentVersion` in a stack flooding the first run — observed across a 7-function\n // stack. The version resource is immutable, so the hash can never be an out-of-band edit.\n 'AWS::Lambda::Version': new Set(['CodeSha256']),\n // An EFS AccessPoint's ClientToken is the idempotency token CloudFormation mints at\n // create time as `<logicalId>-<random>` (e.g. \"AccessPointE936DE82-b6xKi37R0Uio\"). It\n // is createOnly (immutable) and the CDK L2 never declares it, so it floods the first\n // run as undeclared on every AccessPoint. The value is opaque and not derivable from\n // the physical id (an fsap-… ARN), so neither isGeneratedName nor a physical-id echo\n // folds it. A raw-CFn user who DOES set ClientToken carries it in the template and\n // never reaches this undeclared loop, so folding the live-only case as `generated`\n // (inventory: never drift, recorded, or reverted) is safe — and necessary, since an\n // immutable token can never be an out-of-band edit. Observed live on lambda-efs-rich.\n 'AWS::EFS::AccessPoint': new Set(['ClientToken']),\n // NOTE: AWS::Lambda::LayerVersion.LayerName is NOT folded here. The flood case — a CDK\n // BucketDeployment's AwsCliLayer reads back its own logical id verbatim — is handled\n // PRECISELY by isCfnGeneratedName's `value === logicalId` echo (classify.ts). A\n // value-independent GENERATED_TOPLEVEL_PATHS entry would additionally fold an undeclared\n // user-set LayerName (e.g. \"my-custom-layer\") that is NOT the logical id, hiding real\n // undeclared drift — the exact differentiator cdkrd exists to surface.\n // NOTE: AWS::Cognito::UserPoolClient.ClientName is NOT folded here either. Its generated\n // form is `<logicalId>-<random>` (no stack prefix), now folded value-DEPENDENTLY via\n // GENERATED_LOGICALID_PREFIX_PATHS below. A value-independent entry would additionally\n // fold an undeclared user-set ClientName that is NOT the logical-id form, hiding real\n // undeclared drift.\n};\n\n// FULLY-undeclared top-level OBJECT properties to DESCEND into leaf-by-leaf instead of\n// reporting whole (#555). A fully-undeclared object is normally one `undeclared` finding, so\n// its constant sub-keys (which KNOWN_DEFAULT_PATHS folds only inside a PARTIALLY-declared —\n// thus descended — object) can't fold; the whole object surfaces even when only ONE leaf is\n// record-worthy. Listing (type → top-level path) here descends that object through the SAME\n// nested machinery: known-default / generated / trivially-empty leaves fold (atDefault /\n// generated / dropped) and only the non-default residue surfaces (nested, at `Prop.sub`).\n//\n// CURATED, not \"every fully-undeclared object\": a blanket descend would FRAGMENT objects with\n// no foldable defaults (a VPCEndpoint `PolicyDocument`, an S3 `NotificationConfiguration`) into\n// noisier per-leaf findings — strictly worse. Only add a (type, path) whose leaves genuinely\n// split into \"constant AWS defaults + a small record-worthy residue\", with the residue's\n// constants registered in KNOWN_DEFAULT_PATHS. EKS `KubernetesNetworkConfig` is the first: AWS\n// materializes `IpFamily: \"ipv4\"` (constant, folds) and `ElasticLoadBalancing: {Enabled:false}`\n// (trivially-empty, dropped), leaving only `ServiceIpv4Cidr` (10.100 or 172.20 per deploy) —\n// the single value worth recording.\nexport const DESCEND_UNDECLARED_OBJECT_PATHS: Record<string, ReadonlySet<string>> = {\n 'AWS::EKS::Cluster': new Set(['KubernetesNetworkConfig']),\n // A workgroup that declares no WorkGroupConfiguration reads back AWS's whole default config;\n // when it matches the default exactly the whole-object KNOWN_DEFAULTS fold (above) folds it\n // atDefault. But once ONE sub-key is set out of band (a ResultConfiguration output location, a\n // BytesScannedCutoffPerQuery cap) the whole object no longer matches and surfaces WHOLE,\n // obscuring which sub-key changed. Descend so the four constant defaults fold\n // (EnforceWorkGroupConfiguration / EngineVersion / PublishCloudWatchMetricsEnabled via\n // KNOWN_DEFAULT_PATHS, RequesterPaysEnabled:false as trivially-empty) and only the record-\n // worthy residue surfaces. Every other sub-key is a meaningful config value (not noise), so\n // fragmenting is the desired behavior here. Follow-up to #555 (#565).\n 'AWS::Athena::WorkGroup': new Set(['WorkGroupConfiguration']),\n};\n\n// Value-DEPENDENT generated-name fold, scoped by type + top-level path. Folds a live value\n// to `generated` ONLY when it is the `<logicalId>-<random>` CFn auto-generated form — the\n// resource's logical id, a `-`, then CFn's 12+ char random suffix — for a type whose\n// no-explicit-name physical name takes that shape WITHOUT a `<stack>-` prefix (so the\n// isCfnGeneratedName stack-prefix branches miss it). UNLIKE the value-independent\n// GENERATED_TOPLEVEL_PATHS, an undeclared user-SET name (no logical-id prefix) does NOT match\n// and still surfaces as real drift. Deliberately NOT applied generically in\n// isCfnGeneratedName: a short raw-CFn logical id (e.g. a WAFv2 RegexPatternSet's `RegexSet`)\n// carries no construct hash, so `<logicalId>-<random>` would coincide with genuine undeclared\n// names and over-fold — this table gates it to the specific types/paths observed to need it.\n// AWS::Cognito::UserPoolClient.ClientName — reads back `<logicalId>-<random>` when the\n// template declares no ClientName (observed live).\nexport const GENERATED_LOGICALID_PREFIX_PATHS: Record<string, ReadonlySet<string>> = {\n 'AWS::Cognito::UserPoolClient': new Set(['ClientName']),\n};\n\n// True when `value` is the `<logicalId>-<random>` CFn auto-generated-name form: the logical\n// id, a `-`, then CFn's random suffix. Consulted only for GENERATED_LOGICALID_PREFIX_PATHS\n// entries. Pure + exported for unit tests.\nconst CFN_LOGICALID_RANDOM = /-[0-9A-Za-z]{12,}$/;\nexport function isLogicalIdPrefixedGeneratedName(value: unknown, logicalId: string): boolean {\n return (\n typeof value === 'string' &&\n value.startsWith(`${logicalId}-`) &&\n CFN_LOGICALID_RANDOM.test(value)\n );\n}\n\n// Like GENERATED_TOPLEVEL_PATHS but for NESTED, value-INDEPENDENT paths (dotted, `*` for\n// array crossings) — a sub-key AWS/CloudFormation injects that the template never declares\n// and whose value is not derivable from the physical id (so isPhysicalIdSegment can't gate\n// it). Folded `generated` (inventory: never drift, recorded, or reverted) only in the\n// LIVE-only case: a user who DECLARES the sub-key carries it in the template and never\n// reaches the undeclared loop, so a meaningful out-of-band change to a declared value still\n// surfaces via the declared compare.\n// AWS::KMS::Key.KeyPolicy.Id — CloudFormation injects a doc-level policy `Id` (the stack\n// name) into a key policy that omits one, so a first check of a key with a default/simple\n// policy floods `KeyPolicy.Id` as undeclared. It is cosmetic (a policy label, like a\n// statement Sid) and stack-derived, not user intent.\nexport const GENERATED_NESTED_PATHS: Record<string, ReadonlySet<string>> = {\n 'AWS::KMS::Key': new Set(['KeyPolicy.Id']),\n // An ECR repository's lifecycle policy reads back a RegistryId AWS injects (the owning\n // account id) that the template never declares — folded regardless of value.\n 'AWS::ECR::Repository': new Set(['LifecyclePolicy.RegistryId']),\n // A Lambda function that declares no custom log group reads back the AWS-created default\n // `/aws/lambda/<functionName>`. The whole-object GENERATED_DEFAULTS fold misses it when the\n // function ALSO carries a non-default LogFormat/ApplicationLogLevel (so the object differs);\n // fold the LogGroup path itself, value-independently — a CUSTOM log group is DECLARED and\n // compared in the declared loop, never reaching here.\n 'AWS::Lambda::Function': new Set(['LoggingConfig.LogGroup']),\n // An OpenSearch domain that declares no explicit KMS key reads back the AWS-assigned key id\n // (a GUID) inside EncryptionAtRestOptions — never a constant, never user intent when undeclared\n // (like RDS KmsKeyId). Live-verified undeclared on a fresh opensearch-rich deploy.\n 'AWS::OpenSearchService::Domain': new Set(['EncryptionAtRestOptions.KmsKeyId']),\n};\n\n// Undeclared TOP-LEVEL keys whose AWS-chosen default is NON-DETERMINISTIC — the value\n// varies by account / CDK feature-flag / creation date, so a single KNOWN_DEFAULTS value\n// cannot fold every valid form (folding one leaves the other as false undeclared drift).\n// Folded to `atDefault` REGARDLESS of value: the property is not declared, so any value AWS\n// returns is AWS's choice, never user intent (a user who cares DECLARES it, and then it is\n// compared in the declared loop and never reaches here).\n// AWS::ECS::Service.AvailabilityZoneRebalancing — reads back \"ENABLED\" on some services\n// and \"DISABLED\" on others (both observed live), depending on how/when the service was\n// created; neither is \"the\" default.\nexport const VALUE_INDEPENDENT_DEFAULT_TOPLEVEL_PATHS: Record<string, ReadonlySet<string>> = {\n // AWS::ECS::Service.PlatformVersion — a service that declares no platform version reads\n // back the concrete version AWS provisioned (\"1.4.0\" today); \"use the default/latest\" is\n // satisfied by whatever concrete version is current, so any value is not user intent. (A\n // DECLARED \"LATEST\" is handled by LATEST_SENTINEL_PATHS in the declared loop.)\n 'AWS::ECS::Service': new Set(['AvailabilityZoneRebalancing', 'PlatformVersion']),\n // AWS::KinesisAnalyticsV2::Application.ApplicationMaintenanceConfiguration — a Flink\n // app that declares no maintenance window reads back a service-ASSIGNED window\n // ({ApplicationMaintenanceWindowStartTime}). The window is not a constant we can pin\n // (AWS may assign it per app/region — constancy unverified live), so fold it\n // value-independent: undeclared, so whatever window AWS chose is its default, not user\n // intent. A DECLARED window goes through the declared loop (compared), unaffected.\n 'AWS::KinesisAnalyticsV2::Application': new Set(['ApplicationMaintenanceConfiguration']),\n // AWS::ApiGateway::Authorizer.AuthType — a REST-API authorizer's schema carries NO\n // `AuthType` property (the template declares `Type`: TOKEN / REQUEST /\n // COGNITO_USER_POOLS); AWS DERIVES and reads back AuthType from it (\"custom\" for\n // TOKEN/REQUEST, \"cognito_user_pools\" for COGNITO_USER_POOLS). Since AuthType can\n // never be declared, any value AWS returns is a pure reflection of the declared Type,\n // not user intent — and a real change to Type surfaces in the declared loop on `Type`\n // itself. Fold value-independent so both derived forms (and any future enum) fold\n // without enumerating each. Both observed live first-run (LineLink cognito, dev-main\n // AimAssociation TOKEN \"custom\") with no out-of-band edit.\n 'AWS::ApiGateway::Authorizer': new Set(['AuthType']),\n // AWS::RDS::DBCluster / ::DBInstance — an Aurora cluster/instance that declares no explicit\n // KMS key, availability-zone placement, or maintenance/backup window reads back the values\n // AWS ASSIGNED at creation: a specific `KmsKeyId` (the account/CDK key — create-only, so it\n // can never drift), the `AvailabilityZone(s)` AWS placed it in (create-only), and a\n // RANDOMLY-assigned `PreferredMaintenanceWindow` / `PreferredBackupWindow`. None is a\n // constant we can pin, and none is user intent — a user who cares DECLARES it, and then it\n // is compared in the declared loop (detected) and never reaches here. Fold value-independent\n // (mirrors the KinesisAnalytics maintenance-window precedent above). Observed live first-run\n // on dev-main-AuroraDB / dev-main-DbUsers-DB with no out-of-band edit.\n // `PerformanceInsightsKmsKeyId` (cluster) / `PerformanceInsightsKMSKeyId` (instance — note\n // the API's different casing) is the same shape as `KmsKeyId`: a Performance-Insights-\n // enabled cluster/instance that pins no explicit PI key reads back the AWS-assigned key.\n // `EngineLifecycleSupport` — the RDS Extended Support enrollment default CHANGED over time\n // (opt-in behavior changed 2024-02/03: newer resources auto-enroll to\n // `open-source-rds-extended-support`, older ones read back\n // `open-source-rds-extended-support-disabled`). So the undeclared default varies by creation\n // date — AWS's choice, not user intent — and a constant KNOWN_DEFAULTS cannot fold both forms.\n // A user who cares about the enrollment (its billing / EOL implications) DECLARES it, and then\n // it is compared in the declared loop (detected). Observed live: fresh corpus deploys read\n // \"open-source-rds-extended-support\"; the older cdk-imported dev-main-AuroraDB reads\n // \"open-source-rds-extended-support-disabled\".\n 'AWS::RDS::DBCluster': new Set([\n 'KmsKeyId',\n 'PerformanceInsightsKmsKeyId',\n 'AvailabilityZones',\n 'PreferredMaintenanceWindow',\n 'PreferredBackupWindow',\n 'EngineLifecycleSupport',\n ]),\n 'AWS::RDS::DBInstance': new Set([\n 'KmsKeyId',\n 'PerformanceInsightsKMSKeyId',\n 'AvailabilityZone',\n 'PreferredMaintenanceWindow',\n 'PreferredBackupWindow',\n 'EngineLifecycleSupport',\n ]),\n // AWS::EKS::AccessEntry.Username — an access entry that declares no explicit Username reads\n // back the value EKS DERIVES from the declared PrincipalArn\n // (\"arn:aws:sts::<acct>:assumed-role/<role>/{{SessionName}}\" for an IAM role). It can never\n // be a constant we pin (it embeds the per-resource role name), and it is never user intent\n // when undeclared — a user who sets a custom Username declares it (compared in the declared\n // loop). Fold value-independent. Observed live first-run (hunt 2026-07-03 round E).\n 'AWS::EKS::AccessEntry': new Set(['Username']),\n // AWS::Glue::Job.MaxCapacity / .AllocatedCapacity — a job that sizes itself with the modern\n // `WorkerType` + `NumberOfWorkers` pair (a glueetl / gluestreaming job on Glue 2.0+) declares\n // NEITHER capacity field; AWS DERIVES both from the worker sizing and reads them back\n // (G.1X × 10 workers → MaxCapacity 10 / AllocatedCapacity 10; G.025X × 2 → MaxCapacity 0.5 /\n // AllocatedCapacity 0). The two are mutually exclusive with WorkerType/NumberOfWorkers, so\n // when undeclared they can only be an AWS reflection of the declared sizing, never user intent\n // — and a real change to the sizing surfaces on `WorkerType` / `NumberOfWorkers` in the\n // declared loop. `AllocatedCapacity` is additionally a legacy field AWS always echoes. Fold\n // value-independent so every DPU value folds without a table (a job that instead DECLARES\n // MaxCapacity — a Python-shell job — goes through the declared loop, compared). Observed live\n // first-run on dev-main-Db2Csv (five G.1X ETL jobs + one G.025X streaming job), no edit.\n 'AWS::Glue::Job': new Set(['MaxCapacity', 'AllocatedCapacity']),\n // AWS::EC2::SecurityGroupIngress / ::SecurityGroupEgress.SourceSecurityGroupName — a rule that\n // references its peer group by id (`SourceSecurityGroupId`, the CDK default) declares no\n // `SourceSecurityGroupName`; AWS DERIVES and reads back the referenced group's NAME\n // (\"dev-main-Db2Csv-Glue-sg\") from that id. It can never be a constant we pin (it embeds the\n // per-group name), and when undeclared it is a pure reflection of the declared\n // SourceSecurityGroupId, not user intent — a real change to the peer surfaces on\n // `SourceSecurityGroupId` in the declared loop. Fold value-independent. (A user who references\n // a peer by name — EC2-Classic style — DECLARES SourceSecurityGroupName, compared.) Observed\n // live first-run on dev-main-Db2Csv's self-referencing Glue SG ingress, no edit.\n 'AWS::EC2::SecurityGroupIngress': new Set(['SourceSecurityGroupName']),\n 'AWS::EC2::SecurityGroupEgress': new Set(['SourceSecurityGroupName']),\n // The RDS-family + cache engines all mirror the RDS precedent above: a cluster/instance\n // that declares no maintenance / backup / snapshot window reads back a window AWS\n // RANDOMLY ASSIGNED at creation (e.g. \"sat:03:00-sat:04:00\", \"03:10-03:40\"). It is not a\n // constant we can pin (AWS picks it per resource/region) and never user intent when\n // undeclared — a user who cares DECLARES it and is then compared in the declared loop.\n // Fold value-independent, exactly like AWS::RDS::* above. Found by the offline first-run-\n // noise sweep across the DocDB / Neptune / ElastiCache / MemoryDB / Redshift corpus cases\n // (undeclared on every one, no out-of-band edit). Equality is irrelevant — any window folds.\n 'AWS::DocDB::DBCluster': new Set(['PreferredMaintenanceWindow', 'PreferredBackupWindow']),\n 'AWS::DocDB::DBInstance': new Set(['PreferredMaintenanceWindow']),\n 'AWS::Neptune::DBCluster': new Set(['PreferredMaintenanceWindow', 'PreferredBackupWindow']),\n 'AWS::Neptune::DBInstance': new Set(['PreferredMaintenanceWindow']),\n 'AWS::ElastiCache::CacheCluster': new Set(['PreferredMaintenanceWindow', 'SnapshotWindow']),\n 'AWS::ElastiCache::ReplicationGroup': new Set(['PreferredMaintenanceWindow', 'SnapshotWindow']),\n 'AWS::ElastiCache::ServerlessCache': new Set(['DailySnapshotTime']),\n 'AWS::MemoryDB::Cluster': new Set(['MaintenanceWindow', 'SnapshotWindow']),\n // AWS::Redshift::Cluster.AvailabilityZone — AWS places an undeclared cluster in an AZ it picks\n // (create-only, never user intent when undeclared), exactly like RDS AvailabilityZone above.\n // OffPeakWindowOptions on an OpenSearch domain is the AWS-ASSIGNED off-peak maintenance window\n // (an object {OffPeakWindow:{WindowStartTime:{Hours,Minutes}},Enabled}); AWS enables it and\n // assigns the start time per domain, so fold the whole property value-independent (a domain\n // that DECLARES an off-peak window is compared in the declared loop).\n // AWS::Redshift::Cluster.ClusterVersion — a cluster that pins no explicit version reads back\n // the concrete engine version AWS provisioned (\"1.0\" today). \"use the current default\" is\n // satisfied by whatever version is current, so it is not user intent when undeclared (a user\n // who cares DECLARES ClusterVersion → compared). Live-verified undeclared on a fresh deploy.\n 'AWS::Redshift::Cluster': new Set([\n 'PreferredMaintenanceWindow',\n 'AvailabilityZone',\n 'ClusterVersion',\n ]),\n 'AWS::OpenSearchService::Domain': new Set(['OffPeakWindowOptions']),\n // AWS::AmazonMQ::Broker.MaintenanceWindowStartTime — a broker that declares no window reads\n // back an AWS-assigned one as an OBJECT ({DayOfWeek, TimeOfDay, TimeZone}); value-independent\n // folds the whole top-level property whatever its shape, so the assigned window is not first-\n // run noise (a DECLARED window is compared in the declared loop).\n 'AWS::AmazonMQ::Broker': new Set(['MaintenanceWindowStartTime']),\n};\n\n// R142: true when `value` equals a `|`/`:`/`/`-separated SEGMENT of the physical id.\n// Folds a GENERATED_PATHS value only when it ECHOES an id AWS minted (an ApiGateway\n// Method's CacheNamespace = the parent Resource id, the middle segment of\n// `RestApiId|ResourceId|HttpMethod`), leaving a user-set custom value to surface.\nexport function isPhysicalIdSegment(value: unknown, physicalId: string | undefined): boolean {\n if (typeof value !== 'string' || physicalId === undefined) return false;\n // The whole-id echo (XRay SamplingRule.RuleARN returns the rule's own ARN — the\n // physical id verbatim) is the purest physical-id segment; a split on `:` would\n // otherwise never reassemble a full ARN.\n if (value === physicalId) return true;\n return physicalId.split(/[|:/]/).includes(value);\n}\n\n// R107: a scalar property whose value IS this resource's generated NAME taken from\n// an ARN physical id — the ARN's trailing name segment (a topic's TopicName, a\n// state machine's StateMachineName). This is the identity AWS minted, never user\n// intent, and appears on every first run for any ARN-keyed auto-named type.\n// Generalizes the per-type GENERATED_DEFAULTS so such a type needs no table entry.\n// Deliberately EXCLUDES `value === physicalId` (the bare-id echo — e.g. a RoleName /\n// AlarmName whose physical id IS the name, or a property echoing the whole ARN):\n// that remains the long-standing structural-noise drop in classify, unchanged, so\n// this stays a narrow, additive rule (only the ARN name-segment case). Strict\n// equality + the hash suffix in a generated name make a coincidental user-value\n// match effectively impossible; a renamed/edited value simply won't match.\nexport function isGeneratedName(value: unknown, physicalId: string | undefined): boolean {\n if (typeof value !== 'string' || physicalId === undefined || value === physicalId) return false;\n return value === physicalNameOf(physicalId);\n}\n\nfunction physicalNameOf(physicalId: string): string {\n const segs = physicalId.split(/[:/]/);\n return segs[segs.length - 1] || physicalId;\n}\n\nfunction substitutePhysical(value: unknown, id: string, name: string): unknown {\n if (typeof value === 'string')\n return value.split('${PHYSICAL_ID}').join(id).split('${PHYSICAL_NAME}').join(name);\n if (Array.isArray(value)) return value.map((v) => substitutePhysical(v, id, name));\n if (value && typeof value === 'object')\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([k, v]) => [\n k,\n substitutePhysical(v, id, name),\n ])\n );\n return value;\n}\n\n// Resolve the GENERATED_DEFAULTS template for a resource type against its live\n// physical id, returning the per-property expected values (placeholders filled) or\n// undefined when the type has no template / the physical id is unknown. The classify\n// undeclared loop then equality-gates a live value against `result[key]`.\nexport function resolveGeneratedDefault(\n resourceType: string,\n physicalId: string | undefined\n): Record<string, unknown> | undefined {\n const tmpl = GENERATED_DEFAULTS[resourceType];\n if (!tmpl || physicalId === undefined) return undefined;\n return substitutePhysical(tmpl, physicalId, physicalNameOf(physicalId)) as Record<\n string,\n unknown\n >;\n}\n\n// Strip AWS-managed (aws:*) tag ELEMENTS from the live side so a declared tag\n// set (which never contains aws:* tags) compares equal to the live set (which\n// AWS augments with aws:cloudformation:* etc.). Handles {Key,Value}[] lists at\n// any depth (shape-specific enough to be safe) and key->value maps ONLY under a\n// key named `Tags` (R69): the old strip-any-`aws:`-map-key-anywhere rule also\n// deleted IAM condition keys (`Condition.Bool[\"aws:SecureTransport\"]`,\n// aws:SourceArn, aws:PrincipalOrgID, ...) from live policy documents, turning\n// every CDK enforceSSL-style statement into a desired-vs-undefined false drift\n// (found by the first live policies integ run).\nexport function stripAwsTagsDeep(v: unknown): unknown {\n return stripTagsWalk(v, false);\n}\n\nfunction stripTagsWalk(v: unknown, underTagsKey: boolean): unknown {\n if (Array.isArray(v)) {\n return v\n .filter(\n (t) =>\n !(\n t &&\n typeof t === 'object' &&\n typeof (t as { Key?: unknown }).Key === 'string' &&\n (t as { Key: string }).Key.startsWith('aws:')\n )\n )\n .map((t) => stripTagsWalk(t, false));\n }\n if (v && typeof v === 'object') {\n const out: Record<string, unknown> = {};\n for (const [k, val] of Object.entries(v as Record<string, unknown>)) {\n if (underTagsKey && k.startsWith('aws:')) continue;\n out[k] = stripTagsWalk(val, k === 'Tags');\n }\n return out;\n }\n return v;\n}\n\n// CFn arrays of IDENTITY-KEYED objects are UNORDERED sets: CDK declares them in one\n// order, AWS returns them in another, so a positional diff reports false drift on\n// every element. Two cases share this shape:\n// - tag lists ({Key,Value}[]) — keyed by `Key` (subnets are the worst offender);\n// - CloudFront DistributionConfig.Origins ({Id,DomainName,...}[]) — keyed by `Id`\n// (a multi-origin distribution returns the origins in a different order, which\n// otherwise reports a false drift on EVERY field of every swapped origin).\n// Canonicalize any array whose every element is an object carrying a string identity\n// field (`Key` preferred, else `Id`) by sorting on that field (JSON tiebreak for\n// stability). Applied to BOTH sides before the diff, so a reordered-but-equal set\n// compares equal; a genuine change to one element still differs after the sort.\n// Recurses so nested bags (LaunchTemplate TagSpecifications, Origins, ...) are covered.\n// ASSUMPTION: no `Key`- or `Id`-keyed AWS array is known to be order-significant, so\n// sorting is safe (same conservative bet as the scalar id-array canonicalizer).\n// R88: `AttributeName` and `IndexName` extend this to DynamoDB's identity-keyed\n// arrays — AttributeDefinitions / KeySchema (keyed by AttributeName) and\n// GlobalSecondaryIndexes (keyed by IndexName), which AWS returns in a different order\n// than the template declares them (a positional diff otherwise reports false drift on\n// every element). Both are set-like identities, not order-significant.\n// WAVE24: `Name` extends it to the very common `[{Name,Value}]` shape — ECS\n// TaskDefinition ContainerDefinitions[].Environment / Secrets / Ulimits and CloudWatch\n// Alarm Dimensions — which Cloud Control returns in a DIFFERENT order than declared\n// (PROVEN live: a 5-var Environment came back fully shuffled), false-flagging every\n// shifted element as `declared` drift. Sorting is comparison-only (both sides, never\n// written back) and `identityField` requires EVERY element to carry a string `Name`, so\n// order-significant arrays without a Name on every element (CloudFront CacheBehaviors —\n// precedence-ordered, no Name; un-named ECS PortMappings) stay UNSORTED. The baseline's\n// `DELTA_IDENTITY_FIELDS` already includes `Name`; this aligns the compare side to it.\nconst IDENTITY_FIELDS = ['Key', 'Id', 'AttributeName', 'IndexName', 'Name'] as const;\n// Exported for classify's nested-undeclared array descent (R98): an identity-keyed\n// object array (Tags/Origins/AttributeDefinitions/…) can be aligned element-by-element\n// by its identity value, so a live-only SUB-key inside a declared element is detected.\nexport function identityField(arr: unknown[]): string | undefined {\n return IDENTITY_FIELDS.find((f) =>\n arr.every(\n (t) => t && typeof t === 'object' && typeof (t as Record<string, unknown>)[f] === 'string'\n )\n );\n}\n\n// AWS sometimes GENERATES an identity field the template omitted — most commonly\n// `S3 LifecycleConfiguration.Rules[].Id`: `bucket.addLifecycleRule({...})` without an\n// `id` is the CDK default, so the template carries no `Id`, but S3 assigns a random one\n// and echoes it on read. The live element then has the identity field while the declared\n// element does not, so the per-side identity sort (`canonicalizeTagLists` / `identityField`)\n// sorts the LIVE array by the generated id but leaves the DECLARED array in template order\n// — misaligning every element into a wall of false `declared` drift (observed live: three\n// no-id lifecycle rules reported 8 phantom drifts). AWS preserves the array's declared\n// order (Cloud Control read), so the safe fix is to NOT let an asymmetric identity field\n// drive the sort: walk the declared/live pair in parallel and, at any object array where\n// an IDENTITY_FIELD is present on EVERY element of one side but NOT every element of the\n// other, delete that field from BOTH sides. Neither side is then keyed by it, both stay in\n// positional order, and the compare aligns. A field present on BOTH sides (CloudFront\n// Origins Id, Tags Key, …) is untouched, so the existing identity-keyed canonicalization is\n// unaffected. Mutates the passed (cloned) structures in place; run BEFORE canonicalization.\nexport function stripAsymmetricIdentityFields(declared: unknown, live: unknown): void {\n const isObj = (x: unknown): x is Record<string, unknown> =>\n !!x && typeof x === 'object' && !Array.isArray(x);\n if (Array.isArray(declared) && Array.isArray(live)) {\n if (declared.length > 0 && live.length > 0 && declared.every(isObj) && live.every(isObj)) {\n for (const f of IDENTITY_FIELDS) {\n const decAll = declared.every((e) => typeof (e as Record<string, unknown>)[f] === 'string');\n const liveAll = live.every((e) => typeof (e as Record<string, unknown>)[f] === 'string');\n if (decAll !== liveAll) {\n for (const e of declared) delete (e as Record<string, unknown>)[f];\n for (const e of live) delete (e as Record<string, unknown>)[f];\n }\n }\n }\n const n = Math.min(declared.length, live.length);\n for (let i = 0; i < n; i++) stripAsymmetricIdentityFields(declared[i], live[i]);\n return;\n }\n if (isObj(declared) && isObj(live)) {\n for (const k of Object.keys(declared))\n if (k in live) stripAsymmetricIdentityFields(declared[k], live[k]);\n }\n}\n// Identity-keyed OBJECT arrays that carry a per-element `Name` (so `identityField`\n// would otherwise sort them) but whose ARRAY ORDER is SEMANTICALLY SIGNIFICANT.\n// Sorting such an array is doubly wrong: (a) it MASKS a genuine reorder as no-drift\n// (FP/FN), and (b) the drift finding's array index then points into the SORTED model\n// while the revert (Cloud Control `UpdateResource`) patch addresses the RAW UNSORTED\n// live model — so the patch lands on the WRONG element and the revert silently no-ops\n// (the same index-misalignment class as the policy-statement bug, but CC-side).\n// Keyed by resourceType -> the set of property KEY NAMES (at ANY depth) whose array\n// value must stay in declared order. CodePipeline Stages execute top-to-bottom, and\n// each stage's Actions are returned by Cloud Control in declared order; both compare\n// positionally. The exclusion is type-scoped (only applied when canonicalizeForCompare\n// is given this resourceType), so a same-named array on an unrelated type is unaffected.\nexport const ORDER_SIGNIFICANT_ARRAY_KEYS: Record<string, ReadonlySet<string>> = {\n 'AWS::CodePipeline::Pipeline': new Set(['Stages', 'Actions']),\n // A Logs Transformer's `TransformerConfig` is an EXECUTION PIPELINE: processors run\n // top-to-bottom (a `parseJson` must precede an `addKeys` that reads the parsed fields),\n // and CloudWatch Logs returns them in declared order. Its CFn schema nonetheless marks it\n // `insertionOrder: false` (→ `schema.unorderedObjectArrayPaths`), which would sort it as an\n // unordered set: masking a genuine reorder AND — the #529 bug — skewing a drift finding's\n // array index into the SORTED model while the Cloud Control `UpdateResource` revert patch\n // addresses the RAW live model, so `revert` failed with `noSuchPath //TransformerConfig/0/...`.\n // Pinning it order-significant keeps both compare sides in raw order so the index aligns.\n 'AWS::Logs::Transformer': new Set(['TransformerConfig']),\n};\nexport function canonicalizeTagListsDeep(v: unknown, orderSig?: ReadonlySet<string>): unknown {\n return canonicalizeTagLists(v, orderSig, undefined);\n}\n// `keyHere` is the property name the value `v` sits under (undefined at the root and\n// for array ELEMENTS), so an array directly under an order-significant key is left in\n// place while its elements still recurse for nested tag/id-list canonicalization.\nfunction canonicalizeTagLists(\n v: unknown,\n orderSig: ReadonlySet<string> | undefined,\n keyHere: string | undefined\n): unknown {\n if (Array.isArray(v)) {\n const mapped = v.map((el) => canonicalizeTagLists(el, orderSig, undefined));\n if (keyHere !== undefined && orderSig?.has(keyHere)) return mapped;\n const idf = mapped.length > 0 ? identityField(mapped) : undefined;\n if (idf) {\n return [...mapped].sort((a, b) => {\n const ka = String((a as Record<string, unknown>)[idf]); // identityField verified string\n const kb = String((b as Record<string, unknown>)[idf]);\n if (ka !== kb) return ka < kb ? -1 : 1;\n return JSON.stringify(a) < JSON.stringify(b) ? -1 : 1;\n });\n }\n return mapped;\n }\n if (v && typeof v === 'object') {\n const out: Record<string, unknown> = {};\n for (const [k, val] of Object.entries(v as Record<string, unknown>))\n out[k] = canonicalizeTagLists(val, orderSig, k);\n return out;\n }\n return v;\n}\n\n// Per-attribute-key AWS defaults for the ELB attribute bags (LoadBalancerAttributes /\n// TargetGroupAttributes). ELB always echoes ~15-20 attribute keys the template never\n// declares (the server defaults); classify emits each live-only key as nested\n// `undeclared` inventory (R95, fail-closed). For a key whose live value EQUALS its\n// documented constant default, that is first-run NOISE — surface it in the `atDefault`\n// tier instead (informational, never drift, mirrors KNOWN_DEFAULT_PATHS for nested\n// scalar defaults). This is a CURATED, equality-gated, per-KEY table — NOT the wildcard\n// the R95 comment warned against: a key absent here, or present with a non-default value,\n// still classifies `undeclared` (recorded by `record`, a later change surfaces as drift).\n// Values are strings (the bag stores everything stringly); the empty-string keys\n// (access_logs.s3.bucket/prefix, …) are already dropped by isTrivialEmpty. Every value\n// below is OBSERVED constant across every ELB corpus case. Keys whose default is value-\n// identical but type-specific (e.g. an NLB's differing default) stay safe via the\n// equality gate — a non-matching live value simply does not fold.\nexport const ELB_ATTRIBUTE_DEFAULTS: Record<string, Record<string, string>> = {\n 'AWS::ElasticLoadBalancingV2::LoadBalancer': {\n 'access_logs.s3.enabled': 'false',\n // Deletion protection is off by default on every LB type (ALB/NLB/GWLB). Equality-gated,\n // so a load balancer that enables it still surfaces the non-default \"true\".\n 'deletion_protection.enabled': 'false',\n 'client_keep_alive.seconds': '3600',\n 'connection_logs.s3.enabled': 'false',\n 'health_check_logs.s3.enabled': 'false',\n // ALB idle_timeout default (observed live on a bare ALB that declared no\n // idleTimeout). NLB has no idle_timeout attribute, so no cross-type conflict.\n 'idle_timeout.timeout_seconds': '60',\n // ALB cross-zone load balancing is always on and not configurable -> AWS always\n // returns \"true\". An NLB's / GWLB's default is \"false\" — the OPPOSITE — so those\n // two override this entry via ELB_ATTRIBUTE_DEFAULTS_BY_LB_TYPE below (the shared\n // ALB value here previously mis-folded an out-of-band NLB cross_zone ENABLE as\n // atDefault — a real undeclared change `record` then never snapshotted).\n 'load_balancing.cross_zone.enabled': 'true',\n // NLB-only attribute keys (an ALB never returns them, so no conflict) — observed live\n // on a bare internal NLB.\n 'dns_record.client_routing_policy': 'any_availability_zone',\n 'secondary_ips.auto_assigned.per_subnet': '0',\n 'routing.http.desync_mitigation_mode': 'defensive',\n 'routing.http.drop_invalid_header_fields.enabled': 'false',\n 'routing.http.preserve_host_header.enabled': 'false',\n 'routing.http.x_amzn_tls_version_and_cipher_suite.enabled': 'false',\n 'routing.http.xff_client_port.enabled': 'false',\n 'routing.http.xff_header_processing.mode': 'append',\n 'routing.http2.enabled': 'true',\n 'waf.fail_open.enabled': 'false',\n 'zonal_shift.config.enabled': 'false',\n // A dualstack ALB reads back this IPv6 IGW-traffic attribute at its \"false\" default.\n // Observed live on a bare dualstack ALB.\n 'ipv6.deny_all_igw_traffic': 'false',\n },\n 'AWS::ElasticLoadBalancingV2::Listener': {\n // A listener that declares no attributes reads back AWS's defaults: the mTLS\n // advertise / response-header attributes are all empty (folded by isTrivialEmpty),\n // and the `server` response header is enabled. Observed live.\n 'routing.http.response.server.enabled': 'true',\n },\n 'AWS::ElasticLoadBalancingV2::TargetGroup': {\n 'load_balancing.algorithm.anomaly_mitigation': 'off',\n 'load_balancing.algorithm.type': 'round_robin',\n 'load_balancing.cross_zone.enabled': 'use_load_balancer_configuration',\n 'slow_start.duration_seconds': '0',\n // latent stickiness defaults AWS returns even while stickiness.enabled is false\n 'stickiness.app_cookie.duration_seconds': '86400',\n 'stickiness.lb_cookie.duration_seconds': '86400',\n 'stickiness.type': 'lb_cookie',\n 'target_group_health.dns_failover.minimum_healthy_targets.count': '1',\n 'target_group_health.dns_failover.minimum_healthy_targets.percentage': 'off',\n 'target_group_health.unhealthy_state_routing.minimum_healthy_targets.count': '1',\n 'target_group_health.unhealthy_state_routing.minimum_healthy_targets.percentage': 'off',\n },\n};\n\n// Load-balancer attribute defaults that differ BY LB TYPE (the LoadBalancer `Type`\n// property: application | network | gateway; omitted = application). Merged OVER the\n// shared ELB_ATTRIBUTE_DEFAULTS entry in classify, keyed by the live Type. cross_zone\n// is the one known split: an ALB is always-on (\"true\"), while an NLB / GWLB defaults\n// OFF (\"false\"). One shared entry could not fold the NLB first-run \"false\" AND\n// mis-folded an out-of-band NLB cross-zone ENABLE (\"true\" matched the shared ALB\n// default → atDefault, so `record` never snapshotted a real undeclared change and a\n// later flip could hide). Observed live on a fresh internal NLB (iot-vpces-rich).\nexport const ELB_ATTRIBUTE_DEFAULTS_BY_LB_TYPE: Record<string, Record<string, string>> = {\n network: { 'load_balancing.cross_zone.enabled': 'false' },\n gateway: { 'load_balancing.cross_zone.enabled': 'false' },\n};\n\n// (R95) The generic `projectLiveToDeclaredSubset` was REMOVED. It projected the live\n// side of an identity-keyed array down to only the keys the template declared, to\n// mute the extra default attributes ELB returns (declares 2, AWS returns ~15). But\n// projecting away every undeclared live element ALSO silently dropped genuine\n// out-of-band ADDITIONS to any identity-keyed array — a console-added Tag, an extra\n// CloudFront Origin — a false negative a drift tool must never produce (fail-closed:\n// report, do not suppress). The one type that needed subset behaviour, ELB attribute\n// bags, is handled in classify by ELB_ATTRIBUTE_BAGS (R78, compare BY KEY); the\n// golden corpus confirmed no other type relied on the projection.\n\n// A declared OBJECT/ARRAY whose live counterpart is the same value serialized as a\n// JSON STRING (R75: SSM Document.Content — CDK declares the parsed object, AWS\n// returns a JSON string, with keys in a different order). The compare is\n// key-order-insensitive, so a successful parse + structural equality means\n// equal-not-drift. One side must be a string and the other a non-null object; a\n// genuine content change still differs after the parse.\nconst SENTINEL_UNPARSEABLE = Symbol('unparseable');\nfunction deepCompareUnordered(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n const aObj = a !== null && typeof a === 'object';\n const bObj = b !== null && typeof b === 'object';\n // Leaf vs leaf: allow the typed<->string collapse. Inside a JSON string AWS serializes\n // numbers/booleans as quoted strings, so a declared object `{Port: 443, Tls: true}` reads\n // back as `'{\"Port\":\"443\",\"Tls\":\"true\"}'` — after parse the leaves are `443` vs `\"443\"`,\n // which strict `===` would false-drift the whole JSON-string prop. isStringlyEqualScalar\n // folds only the representation difference; a genuine value change (443 vs 8080) still differs.\n if (!aObj && !bObj) return isStringlyEqualScalar(a, b);\n // One side object/array, the other scalar/null: a genuine structural mismatch.\n if (aObj !== bObj) return false;\n const aArr = Array.isArray(a);\n if (aArr !== Array.isArray(b)) return false;\n if (aArr) {\n const ba = b as unknown[];\n return (\n (a as unknown[]).length === ba.length &&\n (a as unknown[]).every((v, i) => deepCompareUnordered(v, ba[i]))\n );\n }\n const ao = a as Record<string, unknown>;\n const bo = b as Record<string, unknown>;\n const ak = Object.keys(ao);\n return (\n ak.length === Object.keys(bo).length &&\n ak.every((k) => Object.hasOwn(bo, k) && deepCompareUnordered(ao[k], bo[k]))\n );\n}\nexport function isJsonStringStructEqual(a: unknown, b: unknown): boolean {\n const parse = (s: string): unknown => {\n try {\n return JSON.parse(s);\n } catch {\n return SENTINEL_UNPARSEABLE;\n }\n };\n if (typeof a === 'string' && b !== null && typeof b === 'object') {\n const pa = parse(a);\n return pa !== SENTINEL_UNPARSEABLE && deepCompareUnordered(pa, b);\n }\n if (typeof b === 'string' && a !== null && typeof a === 'object') {\n const pb = parse(b);\n return pb !== SENTINEL_UNPARSEABLE && deepCompareUnordered(a, pb);\n }\n return false;\n}\n\n// Per-type TOP-LEVEL properties the CloudFormation schema types as a JSON STRING\n// but which CDK declares (and the live read often returns) as a parsed OBJECT —\n// e.g. AWS::Config::ConfigRule `InputParameters`. The provider stores the whole\n// property as a single JSON string; Cloud Control surfaces it parsed for reads but\n// re-serializes the model to that string on UpdateResource. A sub-path RFC6902\n// patch (`/InputParameters/maxAccessKeyAge`) therefore makes Cloud Control rebuild\n// the JSON string in a shape the provider rejects (Config: \"Blank spaces are not\n// acceptable for input parameter\") — the revert never converges. So such a property\n// must be compared and reverted as a WHOLE UNIT: classify emits one finding at the\n// top-level path (folded stringly so a clean `90` vs `\"90\"` is not drift), and the\n// revert writes the whole property as a COMPACT JSON STRING (`JSON.stringify` of the\n// declared object), which the provider accepts verbatim. Curated, like the sibling\n// per-type tables — add a property here once its sub-path revert is observed to fail.\nexport const JSON_STRING_PROPS: Record<string, ReadonlySet<string>> = {\n 'AWS::Config::ConfigRule': new Set(['InputParameters']),\n};\n\n// Per-type JSON-STRING props whose service INJECTS a constant default MEMBER into the\n// parsed document that the template never sent — the same \"service fills a default\" class\n// as KNOWN_DEFAULT_PATHS / matchesKnownDefault, except the default lives INSIDE a parsed\n// JSON-string value, so those model-path-keyed tables can't reach it. Keyed\n// type -> prop -> a partial object of default KEY:VALUE pairs. Before the JSON_STRING_PROPS\n// structural compare, these are subtracted from the LIVE parsed side wherever the DECLARED\n// side omits the key AND the live value EQUALS the default (equality-gated: a member\n// declared with a non-default value still surfaces). If the parsed value is a top-level\n// ARRAY the subtraction runs per element; if an OBJECT, at its root.\n// AWS::CE::CostCategory.Rules — the service injects `\"Type\":\"REGULAR\"` (the default\n// rule type) into every rule, so a freshly deployed cost category reported permanent\n// declared drift and revert could never converge (#503). A split-charge rule that sets a\n// non-default Type is not omitted on the declared side, so it still compares.\nexport const JSON_STRING_DEFAULT_FILLS: Record<string, Record<string, Record<string, unknown>>> = {\n 'AWS::CE::CostCategory': { Rules: { Type: 'REGULAR' } },\n};\n\n// Per-type property paths AWS compares CASE-INSENSITIVELY (R75: Route53\n// RecordSet AliasTarget.DNSName — an ALB's generated DNS name is mixed-case in\n// the template's GetAtt and all-lowercase in the live record; DNS hostnames are\n// case-insensitive). Observed-only entries. The drift path is the dotted path\n// from calculateResourceDrift (e.g. `AliasTarget.DNSName`).\nexport const CASE_INSENSITIVE_PATHS: Record<string, ReadonlySet<string>> = {\n 'AWS::Route53::RecordSet': new Set(['AliasTarget.DNSName']),\n // Batch ComputeEnvironment `Type` — CDK's `FargateComputeEnvironment` /\n // `ManagedComputeEnvironment` emits the value LOWERCASE (`managed`) in the\n // template, but the Batch API accepts it case-insensitively and the live read\n // canonicalizes it UPPERCASE (`MANAGED`), so a case-sensitive compare false-flags\n // declared drift on every check of a freshly deployed managed compute environment.\n // `Type` is create-only (managed<->unmanaged can't be toggled out of band) and the\n // two valid values differ beyond case, so case-insensitive equality hides no real\n // drift. Observed live on a fresh batch-rich deploy.\n 'AWS::Batch::ComputeEnvironment': new Set(['Type']),\n // EMR Serverless Application `Type` — the CFn schema enum is UPPERCASE\n // (`SPARK`/`HIVE`) but the EMR Serverless API canonicalizes to mixed case on\n // read (`Spark`/`Hive`), so a case-sensitive compare false-flags declared drift\n // on every check of a freshly deployed application. `Type` is create-only and\n // the two valid values differ beyond case, so case-insensitive equality hides\n // no real drift. Observed live on a fresh misc-0cov-rich deploy.\n 'AWS::EMRServerless::Application': new Set(['Type']),\n // RDS lowercases DB instance / cluster identifiers on creation, so a template\n // that declares a mixed-case `DBInstanceIdentifier` (e.g. CDK derives it from the\n // construct id `dev-main-DbUsers-DB-writer`) reads back all-lowercase\n // (`dev-main-dbusers-db-writer`) and a case-sensitive compare false-flags declared\n // drift on every check. The lowercasing is unconditional and unenforceable — you\n // can never actually have an uppercase identifier live — so case-insensitive\n // equality hides no revertable drift; a genuine rename still differs beyond case.\n // Observed live on fresh (non-imported) Aurora stacks in ap-northeast-1.\n 'AWS::RDS::DBInstance': new Set(['DBInstanceIdentifier']),\n 'AWS::RDS::DBCluster': new Set(['DBClusterIdentifier']),\n // DMS Endpoint `EndpointType` — the CFn/CDK value is lowercase (`source` /\n // `target`) but the DMS API echoes it UPPERCASE (`SOURCE` / `TARGET`) on the\n // DescribeEndpoints read (the SDK_OVERRIDES reader), so a case-sensitive compare\n // false-flags declared drift on every check of a freshly deployed endpoint.\n // `EndpointType` is effectively immutable (source<->target can't be flipped out\n // of band) and the two valid values differ beyond case, so case-insensitive\n // equality hides no real drift. Observed live on a fresh DMS Endpoint deploy.\n 'AWS::DMS::Endpoint': new Set(['EndpointType']),\n // A WAFv2 LoggingConfiguration's RedactedFields SingleHeader.Name is stored/echoed\n // LOWERCASED (HTTP header names are case-insensitive per RFC 9110), so a template that\n // declares `Authorization` / `Cookie` false-flags declared drift against the live\n // `authorization` / `cookie` on every check. The `*` matches the array index (the path\n // arrives as `RedactedFields.0.SingleHeader.Name`); the lookup normalizes numeric\n // indices to `*`. Two header names that differ beyond case are a genuine change and\n // still surface. Observed live on a fresh WAF logging deploy.\n 'AWS::WAFv2::LoggingConfiguration': new Set(['RedactedFields.*.SingleHeader.Name']),\n};\nexport function isCaseInsensitiveScalarEqual(a: unknown, b: unknown): boolean {\n return typeof a === 'string' && typeof b === 'string' && a.toLowerCase() === b.toLowerCase();\n}\n\n// Per-type property paths that hold an RDS engine PARAMETER map (`Parameters`) whose MySQL\n// boolean system variables accept ON/OFF, 1/0, and TRUE/FALSE interchangeably. RDS\n// canonicalizes a declared \"ON\"/\"OFF\" to \"1\"/\"0\" on read, so a template that writes\n// `slow_query_log: \"ON\"` false-flags declared drift against the live \"1\" on every check of a\n// MySQL / Aurora-MySQL cluster (observed live on dev-main-AuroraDB). Matched on the map's TOP\n// path segment; the per-key leaf compare applies isBooleanTokenEquivalent below.\nexport const BOOLEAN_PARAM_MAP_PATHS: Record<string, ReadonlySet<string>> = {\n 'AWS::RDS::DBClusterParameterGroup': new Set(['Parameters']),\n 'AWS::RDS::DBParameterGroup': new Set(['Parameters']),\n};\nconst BOOL_TRUE_TOKENS = new Set(['on', '1', 'true']);\nconst BOOL_FALSE_TOKENS = new Set(['off', '0', 'false']);\n// True when both values are boolean tokens (on/off, 1/0, true/false — any case) mapping to\n// the SAME truthiness. Scoped by the caller to boolean-capable param maps. A non-boolean\n// value (a numeric enum \"2\", a size \"128M\") is not a token, so it never matches — and a real\n// flip (declared \"ON\" true vs live \"0\" false) maps to different truthiness, so it still\n// surfaces as drift.\nexport function isBooleanTokenEquivalent(a: unknown, b: unknown): boolean {\n const tok = (v: unknown): 'true' | 'false' | undefined => {\n const s =\n typeof v === 'string'\n ? v.toLowerCase()\n : typeof v === 'number' || typeof v === 'boolean'\n ? String(v)\n : undefined;\n if (s === undefined) return undefined;\n if (BOOL_TRUE_TOKENS.has(s)) return 'true';\n if (BOOL_FALSE_TOKENS.has(s)) return 'false';\n return undefined;\n };\n const ta = tok(a);\n return ta !== undefined && ta === tok(b);\n}\n\n// Per-type property paths that hold a FREE-FORM MAP whose KEYS the Cloud Control read\n// handler re-cases (#494). The map-KEY analogue of CASE_INSENSITIVE_PATHS (which folds a\n// VALUE case difference). On DataBrew Recipe `Steps[].Action.Parameters` the template AND\n// the DataBrew service both carry camelCase keys (`sourceColumn`), but `cloudcontrol\n// get-resource` remaps recognized keys onto the PascalCase `RecipeParameters` model\n// (`SourceColumn`) — so a case-sensitive diff false-flags DECLARED key drift on every\n// check of a freshly deployed recipe and revert can never converge (the re-read gets\n// PascalCase again). The drift path is the dotted path from calculateResourceDrift with\n// array indices (`Steps.0.Action.Parameters`); the table keys it with `[]` for element\n// segments and the lookup normalizes indices before matching. Observed live on hunt\n// 2026-07-03 round B.\nexport const CASE_INSENSITIVE_KEY_PATHS: Record<string, ReadonlySet<string>> = {\n 'AWS::DataBrew::Recipe': new Set(['Steps[].Action.Parameters']),\n};\n// True when two objects are equal modulo the ASCII CASE of their keys — the same key set\n// case-folded, with EQUAL values per matched key-pair. Equality-gated per key-pair: a real\n// key change (an added/removed parameter) or a value change on a matched key still differs,\n// so only a pure PascalCase<->camelCase re-casing of an otherwise-identical map folds. Both\n// sides must be plain objects (not arrays); a duplicate case-folded key on either side\n// (`SourceColumn` + `sourcecolumn`) fails closed (the folded-key sets differ in size).\nexport function isCaseInsensitiveKeyMapEqual(a: unknown, b: unknown): boolean {\n if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false;\n if (Array.isArray(a) || Array.isArray(b)) return false;\n const ao = a as Record<string, unknown>;\n const bo = b as Record<string, unknown>;\n const ak = Object.keys(ao);\n const bk = Object.keys(bo);\n if (ak.length !== bk.length) return false;\n const bLower = new Map<string, unknown>();\n for (const k of bk) bLower.set(k.toLowerCase(), bo[k]);\n if (bLower.size !== bk.length) return false; // duplicate case-folded key on b -> fail closed\n const aLowerSeen = new Set<string>();\n for (const k of ak) {\n const lk = k.toLowerCase();\n if (aLowerSeen.has(lk)) return false; // duplicate case-folded key on a -> fail closed\n aLowerSeen.add(lk);\n if (!bLower.has(lk)) return false;\n if (!deepEqualValue(bLower.get(lk), ao[k])) return false;\n }\n return true;\n}\n// Minimal structural deep-equal (noise.ts is dependency-free by design — no cross-module\n// import). Free-form map values are usually scalars, but a nested object/array value is\n// compared structurally so a real value change under a matched key still surfaces.\nfunction deepEqualValue(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false;\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n return a.every((v, i) => deepEqualValue(v, b[i]));\n }\n const ao = a as Record<string, unknown>;\n const bo = b as Record<string, unknown>;\n const ak = Object.keys(ao);\n if (ak.length !== Object.keys(bo).length) return false;\n return ak.every((k) => Object.hasOwn(bo, k) && deepEqualValue(ao[k], bo[k]));\n}\n\n// A WAFv2 ByteMatchStatement accepts its search pattern as either `SearchString` (the\n// plain form CDK emits) or `SearchStringBase64`; the live CC read echoes BOTH back — the\n// plain `SearchString` AND its redundant `SearchStringBase64` twin — so a template that\n// declares only `SearchString` reports the live-only `SearchStringBase64` as a spurious\n// UNDECLARED value on every byte-match rule (nested under a RateBasedStatement's\n// ScopeDownStatement it floods the first run). Canonicalize BOTH compare sides to the\n// plain `SearchString`: wherever an object carries a `SearchStringBase64`,\n// - if a `SearchString` sibling is present and the base64 IS its faithful echo, drop the\n// redundant twin (the observed CC shape), or\n// - if there is no `SearchString` sibling, decode the base64 to UTF-8 and rename it —\n// both gated on a base64 ROUND-TRIP (re-encoding yields the same base64), so a genuinely\n// binary pattern, or a mismatched twin, is left untouched and still surfaces. The declared\n// side (plain `SearchString`, no base64) is a no-op; the live side is folded to match, so a\n// clean rule is not drift while an out-of-band pattern change (both live keys change in\n// lockstep) still surfaces via the `SearchString` compare. Applied (via\n// canonicalizeForCompare) only for AWS::WAFv2::WebACL. Pure.\nexport function normalizeWafByteMatchDeep(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(normalizeWafByteMatchDeep);\n if (value === null || typeof value !== 'object') return value;\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>))\n out[k] = normalizeWafByteMatchDeep(v);\n const b64 = out.SearchStringBase64;\n if (typeof b64 === 'string') {\n const plain = out.SearchString;\n if (typeof plain === 'string') {\n // Both present: drop the base64 twin when it faithfully echoes the plain string.\n if (Buffer.from(plain, 'utf8').toString('base64') === b64) delete out.SearchStringBase64;\n } else if (!('SearchString' in out)) {\n // base64 only: decode to the plain form the template declares, if it round-trips.\n const decoded = Buffer.from(b64, 'base64').toString('utf8');\n if (Buffer.from(decoded, 'utf8').toString('base64') === b64) {\n delete out.SearchStringBase64;\n out.SearchString = decoded;\n }\n }\n }\n return out;\n}\n\n// Per-type OpenSSH public-key paths (EC2 KeyPair `PublicKeyMaterial`). EC2 stores\n// only the key MATERIAL: on read it rewrites the free-text comment field to the\n// key pair NAME and appends a trailing newline (declared\n// `ssh-ed25519 AAAA... me@laptop`, live `ssh-ed25519 AAAA... <KeyName>\\n`), so a\n// string compare false-flags declared drift on every check of an imported key\n// pair. The comment is not part of the key and is unenforceable (AWS always\n// overwrites it), so compare only `<type> <base64>`; a genuine key-material\n// change still differs. `PublicKeyMaterial` is create-only, so the folded\n// comment hides nothing revertable. Observed live on a fresh misc-0cov-rich deploy.\nexport const SSH_PUBLIC_KEY_PATHS: Record<string, ReadonlySet<string>> = {\n 'AWS::EC2::KeyPair': new Set(['PublicKeyMaterial']),\n};\n// True when both values parse as OpenSSH public keys (`<type> <base64> [comment]`)\n// with the same type + base64 material. Non-parsing inputs never match, so the\n// fold can't fire on an arbitrary string pair.\nexport function isSshPublicKeyEqual(a: unknown, b: unknown): boolean {\n if (typeof a !== 'string' || typeof b !== 'string') return false;\n const material = (s: string): string | undefined => {\n const parts = s.trim().split(/\\s+/);\n const type = parts[0];\n const blob = parts[1];\n if (type === undefined || blob === undefined) return undefined;\n if (!/^(?:sk-)?(?:ssh|ecdsa)-[a-z0-9-]+(?:@[a-z0-9.-]+)?$/.test(type)) return undefined;\n if (!/^[A-Za-z0-9+/]+={0,2}$/.test(blob)) return undefined;\n return `${type} ${blob}`;\n };\n const ma = material(a);\n return ma !== undefined && ma === material(b);\n}\n\n// Per-type Redis/Valkey ACL access-string paths (ElastiCache / MemoryDB `User.\n// AccessString`, read via SDK_SUPPLEMENTS — #482). The service CANONICALIZES the\n// string on write: a declared `on ~app:* +@read` reads back `on ~app:* -@all +@read`\n// (a `-@all` reset baseline is inserted after the key/channel patterns). A raw string\n// compare would false-flag every user on every check, hiding the very drift the\n// supplement exists to catch behind an instant FP.\nexport const ACCESS_STRING_PATHS: Record<string, ReadonlySet<string>> = {\n 'AWS::ElastiCache::User': new Set(['AccessString']),\n 'AWS::MemoryDB::User': new Set(['AccessString']),\n};\n// True when two ACL strings are equal modulo the service-inserted `-@all` baseline\n// term. Redis ACL rules are ORDER-SENSITIVE (later terms override earlier ones), so\n// this deliberately does NOT sort or set-compare: the token sequences must match\n// exactly once surplus `-@all` tokens on either side are dropped down to the other\n// side's count. Dropping `-@all` is safe because it is the ACL's implicit starting\n// state (every user starts with no commands granted): re-stating it cannot widen\n// access, and a canonicalized live string always re-inserts it — so a genuine\n// out-of-band grant (an added `+@write`, a changed key pattern) still differs\n// token-for-token.\nexport function isAccessStringEqual(a: unknown, b: unknown): boolean {\n if (typeof a !== 'string' || typeof b !== 'string') return false;\n const tokens = (s: string): string[] => s.trim().split(/\\s+/);\n const ta = tokens(a);\n const tb = tokens(b);\n const surplus = ta.filter((t) => t === '-@all').length - tb.filter((t) => t === '-@all').length;\n const drop = (list: string[], n: number): string[] => {\n if (n <= 0) return list;\n const out: string[] = [];\n let left = n;\n for (const t of list) {\n if (t === '-@all' && left > 0) {\n left--;\n continue;\n }\n out.push(t);\n }\n return out;\n };\n const na = drop(ta, surplus);\n const nb = drop(tb, -surplus);\n return na.length === nb.length && na.every((t, i) => t === nb[i]);\n}\n\n// Per-type property paths whose value is a Java `.properties` FILE (key=value lines) that\n// AWS accepts as plaintext but stores/echoes with its own formatting — line order, blank\n// lines, `#`/`!` comments and trailing newline are all cosmetic. Compared as parsed\n// key=value MAPS (order/comment/blank/trailing-newline insensitive) so a clean deploy is\n// not drift; a genuine key add/remove/value change still differs. AWS::MSK::Configuration\n// `ServerProperties` — the Kafka server.properties blob, supplemented via\n// DescribeConfigurationRevision (writeOnly, #508).\nexport const PROPERTIES_FILE_PATHS: Record<string, ReadonlySet<string>> = {\n 'AWS::MSK::Configuration': new Set(['ServerProperties']),\n};\nexport function isPropertiesFileEqual(a: unknown, b: unknown): boolean {\n if (typeof a !== 'string' || typeof b !== 'string') return false;\n const parse = (s: string): Map<string, string> => {\n const m = new Map<string, string>();\n for (const raw of s.split(/\\r?\\n/)) {\n const line = raw.trim();\n if (line.length === 0 || line.startsWith('#') || line.startsWith('!')) continue;\n const eq = line.indexOf('=');\n if (eq < 0) continue;\n m.set(line.slice(0, eq).trim(), line.slice(eq + 1).trim());\n }\n return m;\n };\n const ma = parse(a);\n const mb = parse(b);\n if (ma.size !== mb.size) return false;\n for (const [k, v] of ma) if (mb.get(k) !== v) return false;\n return true;\n}\n\n// Per-type property paths whose value is a set of HTTP HEADER NAMES, which AWS\n// stores/echoes LOWERCASED (header names are case-insensitive per RFC 9110). The\n// template keeps the author's casing (CDK CORS `AllowHeaders:\n// [\"Content-Type\",\"Authorization\"]`), but the live read returns them lowercased\n// (`[\"content-type\",\"authorization\"]`), so a positional/case-sensitive diff\n// reports false declared drift on every check. Compared case- AND order-\n// insensitively (a CORS header list is an unordered set); a genuine header\n// add/remove still differs. Observed live on a fresh apigwv2-http-rich deploy.\nexport const CASE_INSENSITIVE_ARRAY_PATHS: Record<string, ReadonlySet<string>> = {\n 'AWS::ApiGatewayV2::Api': new Set([\n 'CorsConfiguration.AllowHeaders',\n 'CorsConfiguration.ExposeHeaders',\n ]),\n};\n// True when both values are string arrays holding the same multiset of values\n// modulo ASCII case (order- and case-insensitive). Non-string-array inputs never\n// match — header sets only.\nexport function isCaseInsensitiveEqualScalarSet(a: unknown, b: unknown): boolean {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n if (!a.every((v) => typeof v === 'string') || !b.every((v) => typeof v === 'string'))\n return false;\n const norm = (arr: unknown[]): string[] => (arr as string[]).map((s) => s.toLowerCase()).sort();\n const na = norm(a);\n const nb = norm(b);\n return na.every((v, i) => v === nb[i]);\n}\n\n// Per-type property paths whose value is a `rate(N unit)` schedule expression that the\n// SERVICE canonicalizes to whole units. CloudWatch Synthetics rewrites a canary's\n// `rate(60 minutes)` to `rate(1 hour)` (CDK's Canary emits the minutes form from\n// `Duration.hours(1)`), so a string compare false-flags declared drift on every check.\n// Compared by NUMERIC DURATION, so an equivalent expression is not drift but a genuine\n// interval change still differs. Observed SYNTHETICS-SPECIFIC: EventBridge Scheduler\n// (and Events::Rule) echo the rate expression VERBATIM (proven live — a scheduler\n// fixture declaring `rate(1 hour)` read back identically), so they are deliberately NOT\n// listed; only paths where the service is observed to rewrite belong here.\nexport const RATE_EXPRESSION_PATHS: Record<string, ReadonlySet<string>> = {\n 'AWS::Synthetics::Canary': new Set(['Schedule.Expression']),\n};\nconst RATE_RE = /^rate\\(\\s*(\\d+)\\s+(minute|minutes|hour|hours|day|days)\\s*\\)$/i;\nconst RATE_UNIT_MIN: Record<string, number> = { minute: 1, hour: 60, day: 1440 };\n// True when both values are `rate(N unit)` expressions of the SAME total duration\n// (e.g. `rate(60 minutes)` == `rate(1 hour)`). Only the rate() form is parsed — a\n// cron() expression or any unparseable string returns false (strict compare), so a\n// genuine schedule change still surfaces.\nexport function isEquivalentRateExpression(a: unknown, b: unknown): boolean {\n if (typeof a !== 'string' || typeof b !== 'string') return false;\n const minutes = (s: string): number | undefined => {\n const m = RATE_RE.exec(s.trim());\n if (!m || m[1] === undefined || m[2] === undefined) return undefined;\n const unit = m[2].toLowerCase().replace(/s$/, '');\n const per = RATE_UNIT_MIN[unit];\n return per === undefined ? undefined : Number(m[1]) * per;\n };\n const ma = minutes(a);\n const mb = minutes(b);\n return ma !== undefined && mb !== undefined && ma === mb;\n}\n\n// Per-type property paths holding a Unix-epoch (seconds) timestamp that AWS rounds\n// DOWN to the hour on store: AppSync ApiKey `Expires` (documented \"rounded down to\n// the nearest hour\"), so a template's exact epoch (e.g. 1784632175) reads back as the\n// hour floor (1784631600) — a false declared drift. Compare by hour-floor equality; a\n// genuine expiry change to a DIFFERENT hour still differs.\nexport const EPOCH_HOUR_PATHS: Record<string, ReadonlySet<string>> = {\n 'AWS::AppSync::ApiKey': new Set(['Expires']),\n};\nexport function isEpochHourEqual(a: unknown, b: unknown): boolean {\n const sec = (v: unknown): number | undefined => {\n const n = typeof v === 'number' ? v : typeof v === 'string' ? Number(v) : Number.NaN;\n return Number.isFinite(n) ? Math.floor(n / 3600) : undefined;\n };\n const ha = sec(a);\n const hb = sec(b);\n return ha !== undefined && hb !== undefined && ha === hb;\n}\n\n// Per-type property paths where a value is a DNS FQDN whose trailing `.` is\n// OPTIONAL and semantically meaningless: AWS::Route53::HostedZone `Name` is declared\n// `example.com` in the template but Cloud Control returns it `example.com.` (the\n// root-anchored form), which a positional diff reports as false drift on every zone.\n// Equal once a single trailing dot is stripped from each side, so a genuinely\n// different zone name still differs. (The RecordSet override reader already aligns its\n// own Name/DNSName via alignTrailingDot; HostedZone is CC-native, handled here.)\nexport const TRAILING_DOT_PATHS: Record<string, ReadonlySet<string>> = {\n 'AWS::Route53::HostedZone': new Set(['Name']),\n // Route53 canonicalizes record names to FQDN form the same way (CDK L2 emits\n // the trailing dot, but raw-template / L1 users routinely omit it). The\n // override reader's alignTrailingDot already handles Name/DNSName; this entry\n // closes the same class for any non-override read path.\n 'AWS::Route53::RecordSet': new Set(['Name']),\n // Route53 Resolver appends the trailing dot to a FORWARD rule's DomainName on\n // read (live-proven: declared \"cdkrd-hunt.internal\" reads back\n // \"cdkrd-hunt.internal.\").\n 'AWS::Route53Resolver::ResolverRule': new Set(['DomainName']),\n};\nexport function isTrailingDotEqual(a: unknown, b: unknown): boolean {\n if (typeof a !== 'string' || typeof b !== 'string') return false;\n const strip = (s: string): string => (s.endsWith('.') ? s.slice(0, -1) : s);\n return strip(a) === strip(b);\n}\n\n// Per-type property paths whose trailing `/` is optional because the service\n// NORMALIZES it away on store while the declared/template form keeps it. Sibling of\n// TRAILING_DOT_PATHS (Route53 FQDN dots). Live-proven for ECR\n// RepositoryCreationTemplate `Prefix`: a template declares `Prefix: \"cdkrd-hunt/\"`\n// (S3-prefix habit — the trailing delimiter is conventional) but the service stores\n// `\"cdkrd-hunt\"`, so after the CC_IDENTIFIER_ADAPTERS read succeeds the residual\n// `Prefix` diff is pure trailing-delimiter noise, not drift. A genuine prefix change\n// still differs once both sides are stripped.\nexport const TRAILING_SLASH_PATHS: Record<string, ReadonlySet<string>> = {\n 'AWS::ECR::RepositoryCreationTemplate': new Set(['Prefix']),\n};\nexport function isTrailingSlashEqual(a: unknown, b: unknown): boolean {\n if (typeof a !== 'string' || typeof b !== 'string') return false;\n const strip = (s: string): string => (s.endsWith('/') ? s.slice(0, -1) : s);\n return strip(a) === strip(b);\n}\n\n// Per-type property paths where the declared `EngineVersion`/version track and the\n// live value differ only in PRECISION — one is a major/minor track, the other the\n// concrete patch version — so they name the same version and the difference is not\n// drift. This happens in BOTH directions:\n// - partial -> concrete (R130: RDS DBInstance declared `\"8.0\"` reads back `\"8.0.45\"`;\n// the engine auto-selects the latest patch within the declared track).\n// - concrete -> partial (ElastiCache Memcached CacheCluster declared `\"1.6.22\"` reads\n// back the major.minor track `\"1.6\"`; the service stores/echoes the track, not the\n// patch). `isVersionPrefixMatch` is symmetric and folds this too.\n// A deliberately narrow rule, NOT a generic string prefix: both sides must be\n// dot-separated version strings and the SHORTER must be a leading run of segments of\n// the LONGER, so `\"8.0\"` matches `\"8.0.45\"` but `\"8.0\"` never matches `\"8.05\"` (segment\n// boundary) and `\"8.1\"` never matches `\"8.0.45\"` (a genuine track change still differs).\n// Observed-only entries; the drift path is the dotted path from calculateResourceDrift.\nexport const VERSION_PREFIX_PATHS: Record<string, ReadonlySet<string>> = {\n 'AWS::RDS::DBInstance': new Set(['EngineVersion']),\n // Aurora clusters resolve a partial track the same way (declared `\"8.0\"` /\n // `\"5.7.mysql_aurora.2\"` reads back the full provisioned patch version).\n 'AWS::RDS::DBCluster': new Set(['EngineVersion']),\n // Live-observed on a fresh neptune-rich deploy: Neptune accepts a major.minor\n // EngineVersion (declared `\"1.3\"`) and provisions the latest patch in that track,\n // reading back the concrete 4-segment version (`\"1.3.5.0\"`) — the same partial->\n // concrete shape as RDS. A genuine track change still differs (the leading-run\n // check fails). MSK KafkaVersion is NOT added: MSK validates KafkaVersion against\n // an exact supported-version list and rejects a partial, so declared == live.\n 'AWS::Neptune::DBCluster': new Set(['EngineVersion']),\n // Live-observed on a fresh docdb-version-fp deploy: Amazon DocumentDB accepts a\n // partial EngineVersion (declared `\"5.0\"`) and provisions the concrete patch version,\n // reading back `\"5.0.0\"` — the same partial->concrete shape as RDS/Aurora/Neptune.\n // A genuine version change still differs (the leading-run check fails).\n 'AWS::DocDB::DBCluster': new Set(['EngineVersion']),\n // ElastiCache resolves a partial Redis EngineVersion the same way: a declared\n // `\"7.1\"` provisions and reads back the concrete `\"7.1.0\"` (live-proven). The\n // EngineVersion is writeOnly on the RG and supplied by the SDK_SUPPLEMENTS reader\n // (from the member cache cluster), so it must fold the prefix like its DB siblings.\n 'AWS::ElastiCache::ReplicationGroup': new Set(['EngineVersion']),\n // Live-observed on a fresh elasticache-memcached deploy: a Memcached CacheCluster\n // declared with a FULL version (`\"1.6.22\"`) reads back the major.minor TRACK\n // (`\"1.6\"`) — the CONCRETE->PARTIAL direction (the reverse of the DB-family\n // partial->concrete). Redis CacheCluster echoes its `\"7.1\"` verbatim (no patch\n // segment), so only the Memcached patch-truncation actually triggers the fold; the\n // symmetric isVersionPrefixMatch covers both. A genuine track change (`\"1.5\"` vs\n // `\"1.6.22\"`) still differs.\n 'AWS::ElastiCache::CacheCluster': new Set(['EngineVersion']),\n // Amazon MQ resolves a partial EngineVersion the same way (corpus-proven: declared\n // `\"5.18\"` provisions the concrete `\"5.18.7\"`, surfaced in the readOnly\n // `EngineVersionCurrent`). Today `EngineVersion` itself is writeOnly -> a readGap, so\n // this entry is a PROACTIVE guard, not an active fold: it fires ONLY if a future\n // SDK_SUPPLEMENTS reader ever projects the concrete `EngineVersion` back (as was done\n // for the ElastiCache RG above), at which point a declared `\"5.18\"` vs live `\"5.18.7\"`\n // would otherwise false-drift. Equality-gated + symmetric, so harmless while inert.\n 'AWS::AmazonMQ::Broker': new Set(['EngineVersion']),\n};\nexport function isVersionPrefixMatch(declared: unknown, live: unknown): boolean {\n if (typeof declared !== 'string' || typeof live !== 'string') return false;\n if (declared.length === 0 || live.length === 0) return false;\n const dSegs = declared.split('.');\n const lSegs = live.split('.');\n // The two sides differ only in precision: the SHORTER (the track) must be a leading\n // run of segments of the LONGER (the concrete patch version). Symmetric — the track\n // can be on either side (declared partial vs live concrete for the DB family; declared\n // concrete vs live partial for Memcached). Equal length is not a prefix (an exact-equal\n // value isn't drift and never reaches here; an equal-length mismatch is a real change).\n const [shortSegs, longSegs] = dSegs.length <= lSegs.length ? [dSegs, lSegs] : [lSegs, dSegs];\n if (shortSegs.length >= longSegs.length) return false;\n return shortSegs.every((seg, i) => seg === longSegs[i]);\n}\n\n// Per-type property paths where the template declares the literal sentinel\n// `\"LATEST\"` and AWS resolves it to whatever concrete version is current\n// (Fargate `PlatformVersion`: declared `\"LATEST\"` reads back the provisioned\n// `\"1.4.0\"`). \"Use the latest\" IS satisfied by any concrete version, so a\n// declared `\"LATEST\"` against a non-empty live string is not drift — reporting\n// it is a false positive every Fargate user who pins PlatformVersion hits. A\n// deliberately narrow rule: ONLY the exact sentinel `\"LATEST\"` folds (a declared\n// CONCRETE version like `\"1.3.0\"` still compares normally, so a genuine pin\n// change surfaces). Observed live on the ecs-taskset-rich fixture.\nexport const LATEST_SENTINEL_PATHS: Record<string, ReadonlySet<string>> = {\n 'AWS::ECS::Service': new Set(['PlatformVersion']),\n 'AWS::ECS::TaskSet': new Set(['PlatformVersion']),\n};\nexport function isLatestSentinelMatch(declared: unknown, live: unknown): boolean {\n // only the literal sentinel folds; the live side must be a non-empty concrete\n // string (a missing/empty live value is a different, real divergence).\n return declared === 'LATEST' && typeof live === 'string' && live.length > 0;\n}\n\n// Per-type paths where a declared `\"Intelligent-Tiering\"` is a REQUEST that AWS\n// resolves to the actual tier it provisioned (`\"Standard\"` or `\"Advanced\"`,\n// live-proven: a >4 KB value reads back \"Advanced\", a small one \"Standard\"). The\n// resolved tier is therefore not drift against the declared Intelligent-Tiering\n// request — but a real Standard↔Advanced change (or a declared concrete tier that\n// differs) still surfaces. Only AWS::SSM::Parameter `Tier` today.\nexport const INTELLIGENT_TIERING_PATHS: Record<string, ReadonlySet<string>> = {\n 'AWS::SSM::Parameter': new Set(['Tier']),\n};\nexport function isIntelligentTieringMatch(declared: unknown, live: unknown): boolean {\n return declared === 'Intelligent-Tiering' && (live === 'Standard' || live === 'Advanced');\n}\n\n// PEM-armored values (R125: CloudFront PublicKey EncodedKey; certificate/key\n// bodies generally) round-trip through AWS with surrounding whitespace added or\n// dropped — most commonly a trailing newline the service appends after the\n// `-----END …-----` line. Whitespace around a PEM block carries no meaning, so\n// two PEM-armored scalars are equal once outer whitespace is trimmed and line\n// endings normalized. BOTH sides must be PEM-armored (a BEGIN and an END marker),\n// so a genuine key/certificate change still differs and non-PEM strings are never\n// touched — same equality-gated, fail-closed philosophy as the helpers above.\nconst PEM_RE = /-----BEGIN [^-]+-----[\\s\\S]*?-----END [^-]+-----/;\nexport function isPemEqual(a: unknown, b: unknown): boolean {\n if (typeof a !== 'string' || typeof b !== 'string') return false;\n if (!PEM_RE.test(a) || !PEM_RE.test(b)) return false;\n const norm = (s: string): string => s.replace(/\\r\\n/g, '\\n').trim();\n return norm(a) === norm(b);\n}\n\n// CloudFormation's GetTemplate API is LOSSY for non-ASCII: every non-ASCII codepoint in\n// a string literal stored in the deployed template is returned as a literal `?` (observed\n// live — an SSM Parameter `Value: áéíóúABC` comes back `?????ABC`, one `?` per\n// non-ASCII character). We fetch the DECLARED side via GetTemplate, so it is corrupted\n// while the LIVE side (read from the service) is intact — a GUARANTEED false `declared`\n// drift on every check, with no out-of-band change. When the live value, with each of its\n// non-ASCII codepoints masked to `?`, exactly equals the declared value (so the ASCII\n// characters and the length match, and the declared side carries ≥1 `?` standing in for a\n// non-ASCII char the API ate), the declared value is unknowable from GetTemplate and the\n// difference cannot be confirmed as drift. Length-exact and equality-gated: a genuine\n// change that alters an ASCII char or the string length still differs and is reported;\n// only a same-length non-ASCII-only edit (inherently invisible through GetTemplate) is\n// missed. Astral codepoints (emoji) mask as one `?` here — if CFn emitted two, the\n// comparison simply falls through and the value is reported (fail-toward-reporting).\nexport function isCfnTemplateNonAsciiMask(declared: unknown, live: unknown): boolean {\n if (typeof declared !== 'string' || typeof live !== 'string') return false;\n if (!declared.includes('?')) return false; // no masked position → not this case\n let masked = '';\n let sawNonAscii = false;\n for (const ch of live) {\n if ((ch.codePointAt(0) ?? 0) > 0x7f) {\n masked += '?';\n sawNonAscii = true;\n } else {\n masked += ch;\n }\n }\n return sawNonAscii && masked === declared;\n}\n\n// AWS resource-id / ARN lists (SubnetIds, SecurityGroupIds, VPCSecurityGroups, ...)\n// are UNORDERED sets too, but unlike tags their elements\n// are bare scalars, so the tag canonicalizer doesn't touch them and a positional\n// diff reports false drift whenever CDK's order != AWS's. Sort only arrays whose\n// EVERY element is an AWS resource id (`subnet-0ab…`, `sg-…`, `vpc-…`) or an ARN —\n// (AvailabilityZones name/id lists are the same kind of set but lack the hex suffix;\n// they are handled by the parallel isAvailabilityZone test below) —\n// these are never order-significant. A plain scalar list like an enum sequence\n// ([\"a\",\"b\"]) is left untouched, so genuinely ordered lists keep reporting drift.\n// KNOWN LIMITATION: the heuristic is shape-based, so a list whose every element is\n// an arbitrary `prefix-<hex-looking-suffix>` name (e.g. `[\"svc-abc123\",\"svc-def456\"]`)\n// would also be sorted even if that array were order-significant. No such\n// order-significant AWS property is known; the trade-off favors killing the very\n// common id-set false drift over guarding a hypothetical one.\nconst ID_RE = /^[a-z][a-z0-9]*-[0-9a-f]{6,}$/;\nconst isIdLike = (s: unknown): boolean =>\n typeof s === 'string' && (s.startsWith('arn:') || ID_RE.test(s));\n\n// Availability-Zone NAMES (`us-east-1a`, `ap-northeast-1c`, `us-gov-east-1b`) and AZ\n// IDs (`use1-az1`, `apne1-az2`) have NO hex suffix, so ID_RE above does NOT match them\n// — yet an AvailabilityZones / PreferredAvailabilityZones / PreferredCacheClusterAZs\n// list is a SET (which AZs to span, order carries no meaning) that AWS returns in\n// account/assignment order, NOT declared order (observed live: an RDS DBCluster reads\n// back `[us-east-1c, us-east-1a, us-east-1b]`). Without folding, a positional compare\n// false-flags a declared AZ list, and a recorded undeclared AZ list re-read in a\n// different order false-drifts as \"changed since record\". An array whose EVERY element\n// is an AZ name/id is safe to sort (no AZ list is order-significant). Same content-based,\n// no-per-type-table philosophy as isIdLike.\nconst AZ_NAME_RE = /^[a-z]{2}-[a-z]+(-[a-z]+)?-\\d{1,2}[a-z]$/;\nconst AZ_ID_RE = /^[a-z]{3,5}\\d-az\\d+$/;\nconst isAvailabilityZone = (s: unknown): boolean =>\n typeof s === 'string' && (AZ_NAME_RE.test(s) || AZ_ID_RE.test(s));\n\n// HTTP-method enum sets (CloudFront DefaultCacheBehavior.AllowedMethods /\n// CachedMethods, ...) are UNORDERED: the template lists them in one order, AWS\n// returns them in another, so a positional diff reports false drift. The verb set\n// is closed and order-insensitive wherever AWS records it, so an array whose EVERY\n// element is one of these verbs is safe to sort. (Same content-based philosophy as\n// isIdLike: no per-type table, just a value-shape test.)\nconst HTTP_METHODS = new Set(['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']);\nconst isHttpMethod = (s: unknown): boolean => typeof s === 'string' && HTTP_METHODS.has(s);\n\n// THE one known order-SIGNIFICANT id/ARN array: AWS::Lambda::Function.Layers is a\n// list of layer-version ARNs where order is meaningful — later layers overlay files\n// from earlier ones, so swapping two layers changes the function's merged content.\n// Every other id/ARN array (SubnetIds, SecurityGroupIds, …) is a set, so the generic\n// sort above is safe; a layer ARN is uniquely shaped\n// (`arn:aws…:lambda:<region>:<acct>:layer:<name>:<version>`), so detect it by shape\n// and leave any array containing one UNSORTED — an out-of-band layer reorder then\n// surfaces as drift instead of being silently suppressed (the false negative the\n// blanket sort otherwise produced). Same content-based, no-per-type-table philosophy.\nconst LAMBDA_LAYER_ARN_RE = /^arn:aws[a-z-]*:lambda:[^:]*:\\d*:layer:/;\nconst hasOrderSignificantId = (arr: unknown[]): boolean =>\n arr.some((s) => typeof s === 'string' && LAMBDA_LAYER_ARN_RE.test(s));\n\nexport function canonicalizeIdArraysDeep(v: unknown): unknown {\n if (Array.isArray(v)) {\n const mapped = v.map(canonicalizeIdArraysDeep);\n if (\n mapped.length > 1 &&\n !hasOrderSignificantId(mapped) &&\n (mapped.every(isIdLike) || mapped.every(isHttpMethod) || mapped.every(isAvailabilityZone))\n )\n return [...(mapped as string[])].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n return mapped;\n }\n if (v && typeof v === 'object') {\n const out: Record<string, unknown> = {};\n for (const [k, val] of Object.entries(v as Record<string, unknown>))\n out[k] = canonicalizeIdArraysDeep(val);\n return out;\n }\n return v;\n}\n\n// Per-type SCALAR-array props AWS treats as UNORDERED SETS but whose elements\n// match none of the content-shape canonicalizers above (not ids/ARNs, not HTTP\n// verbs, no identity field): the service stores a set and echoes it in ITS\n// canonical order, so a positional diff against the template's order is false\n// drift on every check. Entries are added only when OBSERVED live (R74: a fresh\n// Cognito UserPoolClient deploy reported all three as declared drift with\n// identical elements). Consulted by classify's declared loop, equality-gated:\n// the two sides must be the SAME multiset — a genuine element change still\n// reports.\n// Per-type path patterns for a `[{<name>, <value>}]` pair array that the service\n// treats as an IDENTITY-KEYED SET (keyed by the name field) AND default-fills: the\n// template declares a SUBSET, the service REORDERS the set and INJECTS its own server\n// defaults. The name field is not in IDENTITY_FIELDS, so the whole array false-flags\n// as one `declared` drift. Matched against the dotted drift path (which carries the\n// parent array index, e.g. `…Processors.0.Parameters`). Cases (both observed live):\n// - Kinesis Firehose processor `Parameters` ({ParameterName,ParameterValue}): a\n// Lambda processor declared [RoleArn, BufferSizeInMBs, BufferIntervalInSeconds,\n// LambdaArn] reads back reordered with a server-injected NumberOfRetries=3\n// (firehose-processors-rich).\n// - RDS OptionGroup `OptionConfigurations[].OptionSettings` ({Name,Value}): RDS\n// materializes EVERY option setting of a configured option (a MariaDB audit\n// plugin declaring 2 settings reads back all 9, some Name-only with no Value) —\n// a whole-array declared FP on every fresh deploy (#480, rds-optiongroup-evsub).\nexport interface NameValueSubsetSpec {\n re: RegExp;\n nameField: string;\n valueField: string;\n}\nexport const NAME_VALUE_SUBSET_PATHS: Record<string, NameValueSubsetSpec> = {\n 'AWS::KinesisFirehose::DeliveryStream': {\n re: /(^|\\.)Processors\\.\\d+\\.Parameters$/,\n nameField: 'ParameterName',\n valueField: 'ParameterValue',\n },\n 'AWS::RDS::OptionGroup': {\n re: /(^|\\.)OptionConfigurations\\.\\d+\\.OptionSettings$/,\n nameField: 'Name',\n valueField: 'Value',\n },\n // RedshiftServerless Workgroup ConfigParameters (#490): once the writeOnly strip is\n // exempted (schema-strip OVERRIDE_READABLE_WRITEONLY), the top-level ConfigParameters the\n // CC read returns is the FULLY resolved default set (~9 entries: datestyle, query_group,\n // max_query_execution_time, enable_user_activity_logging, search_path, require_ssl,\n // use_fips_ssl, auto_mv, + any declared) vs the 1-2 the template declares — the RDS\n // OptionGroup default-fill shape. Fold as a ParameterKey-keyed subset so the service-filled\n // extras land in atDefault/undeclared-noise, while a declared entry that is MISSING live or\n // whose ParameterValue DIFFERS (the #490 FN: enable_case_sensitive_identifier true->false)\n // still surfaces as real declared drift.\n 'AWS::RedshiftServerless::Workgroup': {\n re: /(^|\\.)ConfigParameters$/,\n nameField: 'ParameterKey',\n valueField: 'ParameterValue',\n },\n};\n// Align a declared `[{<name>,<value>}]` array to a live one BY the spec's name field.\n// Returns the live-only entries (server-injected / out-of-band entries the template\n// never declared) when every DECLARED entry is present in live with an equal value\n// (declared ⊆ live, reorder-insensitive) — the caller suppresses the false whole-array\n// `declared` drift and surfaces the live-only entries as undeclared inventory\n// (fail-closed, recorded). Returns null when a declared entry is MISSING from live or\n// its value differs (a genuine declared drift the caller must keep), or when either\n// side is not a pure name/value pair array (an element carrying any OTHER key would\n// escape the value compare, so it disqualifies the fold rather than risk muting it).\nexport function alignNameValueSubset(\n declared: unknown,\n live: unknown,\n spec: NameValueSubsetSpec\n): unknown[] | null {\n if (!Array.isArray(declared) || !Array.isArray(live)) return null;\n const toMap = (arr: unknown[]): Map<string, unknown> | null => {\n const m = new Map<string, unknown>();\n for (const e of arr) {\n if (!e || typeof e !== 'object' || Array.isArray(e)) return null;\n const r = e as Record<string, unknown>;\n if (typeof r[spec.nameField] !== 'string') return null;\n if (Object.keys(r).some((k) => k !== spec.nameField && k !== spec.valueField)) return null;\n m.set(r[spec.nameField] as string, r[spec.valueField]);\n }\n return m;\n };\n const dm = toMap(declared);\n const lm = toMap(live);\n if (!dm || !lm) return null;\n for (const [name, dVal] of dm) {\n if (!lm.has(name)) return null;\n const lVal = lm.get(name);\n if (dVal !== lVal && !isStringlyEqualScalar(dVal, lVal)) return null;\n }\n return live.filter((e) => !dm.has((e as Record<string, unknown>)[spec.nameField] as string));\n}\n\nexport const UNORDERED_ARRAY_PROPS: Record<string, ReadonlySet<string>> = {\n 'AWS::Cognito::UserPoolClient': new Set([\n 'AllowedOAuthFlows',\n 'AllowedOAuthScopes',\n 'ExplicitAuthFlows',\n // Live-observed on a fresh cognito-callbackurls deploy: Cognito stores the\n // CallbackURLs / LogoutURLs as SETS and echoes them in its own canonical order\n // (declared [zeta,alpha,mike] read back [alpha,mike,zeta]) — a positional compare\n // false-drifts the URL list with identical elements. Same set-reorder class as the\n // sibling OAuth lists above; a genuine URL add/remove still changes the multiset.\n 'CallbackURLs',\n 'LogoutURLs',\n ]),\n // R84 (observed live on a fresh harvest6 deploy): WAFv2 stores the IP address\n // set and echoes it in its own canonical order, so a fresh deploy reports the\n // declared CIDR list as drift with identical elements in a different order.\n 'AWS::WAFv2::IPSet': new Set(['Addresses']),\n // Live-observed on a fresh route53-multivalue deploy: a DNS RecordSet's multiple\n // ResourceRecords are a SET (a multi-value A/TXT/MX record — DNS resolvers treat\n // the values as unordered), and Route53 echoes them in its own canonical order\n // (declared TXT [zeta,alpha,mike] read back [mike,alpha,zeta]; A IPs reordered).\n // A positional compare false-drifts identical value sets; a genuine value\n // add/remove still changes the multiset. (Weighted/latency routing uses separate\n // RecordSets with SetIdentifier, not ordered ResourceRecords, so this is FP-safe.)\n 'AWS::Route53::RecordSet': new Set(['ResourceRecords']),\n // Live-observed on a fresh codedeploy-deploymentgroup-readgap deploy: a deployment\n // group's AutoRollbackConfiguration.Events is a SET of rollback-trigger enums that\n // CodeDeploy echoes SORTED alphabetically, not in template order (declared\n // [DEPLOYMENT_STOP_ON_ALARM, DEPLOYMENT_FAILURE] read back [DEPLOYMENT_FAILURE,\n // DEPLOYMENT_STOP_ON_ALARM]) — a positional compare false-drifts the identical event\n // set. A genuine event add/remove still changes the multiset. (The sibling\n // TriggerConfigurations[].TriggerEvents set was observed to PRESERVE template order on\n // the same deploy, so it is deliberately NOT folded.) The path is nested but the\n // declared-loop suppression keys on the full dotted `d.path`, so the dotted key works.\n 'AWS::CodeDeploy::DeploymentGroup': new Set(['AutoRollbackConfiguration.Events']),\n // NOTE: ECS TaskDefinition `RequiresCompatibilities` and Route53 HealthCheck\n // `HealthCheckConfig.Regions` (both live-observed as AWS-sorted enum sets, #365) are\n // NO LONGER listed here — their CFn schema marks them `insertionOrder: false`, so the\n // schema-driven `SchemaInfo.unorderedScalarPaths` fold (classify) now covers them (and\n // any other insertionOrder:false scalar set) without a per-type entry. Only sets the\n // schema leaves `insertionOrder:true`/absent — which AWS STILL sorts — need a manual\n // entry below (the schema flag is unreliable: most sorted sets are default-true).\n // Live-observed on a fresh rds-logexports-reorder deploy: RDS echoes a DB instance's\n // EnableCloudwatchLogsExports (the SET of log types to ship to CloudWatch — error/\n // general/slowquery/audit for MySQL) SORTED alphabetically, not in template order\n // (declared [slowquery, general, error] read back [error, general, slowquery]). A\n // positional compare false-drifts the identical log-type set on every check — and a\n // huge fraction of RDS users enable DB logs. A genuine log-type add/remove still\n // changes the multiset. The tokens aren't ids/ARNs/HTTP/AZ, so the generic\n // canonicalizeIdArraysDeep leaves them untouched. The SAME property exists on the\n // whole RDS family (DBCluster/Aurora, Neptune DBCluster, DocDB DBCluster) and is a\n // log-type SET on each — folded for all four (equality-gated, so harmless on any that\n // happen to preserve order). DBInstance is the live-proven case.\n 'AWS::RDS::DBInstance': new Set(['EnableCloudwatchLogsExports']),\n 'AWS::RDS::DBCluster': new Set(['EnableCloudwatchLogsExports']),\n 'AWS::Neptune::DBCluster': new Set(['EnableCloudwatchLogsExports']),\n 'AWS::DocDB::DBCluster': new Set(['EnableCloudwatchLogsExports']),\n // Live-observed on a fresh codepipeline-triggers deploy: a V2 pipeline's Git trigger\n // filter lists — the Branches / FilePaths / Tags Includes/Excludes glob sets and the\n // PullRequest Events enum set — are declared in the CFn schema as `uniqueItems: true`\n // arrays WITHOUT `insertionOrder: false`, so the schema-driven `unorderedScalarPaths`\n // fold does NOT cover them. CodePipeline stores them as SETS: an out-of-band reorder of\n // an identical branch/path/tag list (or a console edit that re-canonicalizes them) reads\n // back in a different order, which a positional compare false-drifts (declared `Includes`\n // [release/*, main, develop] vs live [develop, release/*, main]). A genuine glob\n // add/remove still changes the multiset. Keyed with `*` wildcards (Triggers[] and Push[]/\n // PullRequest[] are arrays); the classify lookup normalizes numeric segments to `*`.\n 'AWS::CodePipeline::Pipeline': new Set([\n 'Triggers.*.GitConfiguration.Push.*.Branches.Includes',\n 'Triggers.*.GitConfiguration.Push.*.Branches.Excludes',\n 'Triggers.*.GitConfiguration.Push.*.FilePaths.Includes',\n 'Triggers.*.GitConfiguration.Push.*.FilePaths.Excludes',\n 'Triggers.*.GitConfiguration.Push.*.Tags.Includes',\n 'Triggers.*.GitConfiguration.Push.*.Tags.Excludes',\n 'Triggers.*.GitConfiguration.PullRequest.*.Branches.Includes',\n 'Triggers.*.GitConfiguration.PullRequest.*.Branches.Excludes',\n 'Triggers.*.GitConfiguration.PullRequest.*.FilePaths.Includes',\n 'Triggers.*.GitConfiguration.PullRequest.*.FilePaths.Excludes',\n 'Triggers.*.GitConfiguration.PullRequest.*.Events',\n ]),\n};\n\n// True when both values are scalar arrays containing the same multiset of\n// primitives (order-insensitive equality). Objects/nested arrays never match —\n// those have their own canonicalizers.\nexport function isEqualUnorderedScalarSet(a: unknown, b: unknown): boolean {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n const scalar = (v: unknown): boolean =>\n typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean';\n if (!a.every(scalar) || !b.every(scalar)) return false;\n const sort = (arr: unknown[]): string[] => arr.map((v) => `${typeof v}:${String(v)}`).sort();\n const sa = sort(a);\n const sb = sort(b);\n return sa.every((v, i) => v === sb[i]);\n}\n\n// A declared COLLECTION (object/array) property absent from the live read is, BY\n// DEFAULT, a real `declared` drift — not a readGap. Many AWS services OMIT a\n// sub-config entirely once it is empty/removed but RETURN it when set (EC2\n// SecurityGroup ingress/egress rules, IAM inline Policies, S3 Cors/Lifecycle/Website/\n// OwnershipControls/Metrics/IntelligentTiering/Analytics/…, Lambda Environment). The\n// old rule \"absent declared key → readGap (informational, never drift)\" SILENTLY\n// swallowed every such removal (someone deletes the SSH rule / inline policy / S3\n// lifecycle / Lambda env in the console → cdkrd reported CLEAN). Live-confirmed that\n// S3 omits ALL its sub-configs when empty, so a per-type allowlist was hopelessly\n// incomplete; classify therefore DETECTS an absent declared collection by default and\n// re-applies the whole property on revert. FP-safe: a populated collection is always\n// returned by AWS, so this only fires on a genuine removal — and an empty declared\n// collection is exempted (declared `{}`/`[]` vs absent is not drift).\n//\n// READGAP_COLLECTION_PATHS is the small DENYLIST of the EXCEPTIONS: declared collection\n// properties AWS genuinely NEVER returns even when set (a true readGap), so their\n// absence must stay informational, not false drift. Derived from a full golden-corpus\n// audit (only these few in ~480 cases). A new genuine-readGap collection surfaces as a\n// VISIBLE, denylist-able false positive — never a silent false negative.\nexport const READGAP_COLLECTION_PATHS: Record<string, ReadonlySet<string>> = {\n // `Timeout` ({AttemptDurationSeconds}) — not echoed by Cloud Control's JobDefinition read.\n 'AWS::Batch::JobDefinition': new Set(['Timeout']),\n // `NotificationsWithSubscribers` — write-only-style budget notifications, not read back.\n 'AWS::Budgets::Budget': new Set(['NotificationsWithSubscribers']),\n // `SSESpecification` — the SSE config is reflected via other readOnly props, not echoed verbatim.\n 'AWS::DynamoDB::GlobalTable': new Set(['SSESpecification']),\n 'AWS::DynamoDB::Table': new Set(['SSESpecification']),\n};\n\n// SCALAR_RETURNED_WHEN_SET is the ALLOWLIST inverse of the collection default in the\n// `else if (!(k in live))` branch (#416): a declared SCALAR absent from the live read\n// normally stays an informational `readGap` (\"AWS may legitimately not echo a scalar\"),\n// which is the right FP-cautious default — but it means every service with replace-omit\n// update semantics has silently clearable declared scalars (a real console/CLI slip that\n// `check` then reports CLEAN). For the paths listed here — scalars OBSERVED to be ALWAYS\n// returned by the live read when set (provable with a fresh deploy: zero readGap on a\n// clean check) — an absent-from-live declared scalar is DECLARED drift (whole-property\n// emit; revert re-adds it via a top-level `add`, same shape as the collection case).\n// FP-safety mirrors #416 exactly: a wrongly-listed path surfaces as a VISIBLE, removable\n// false positive, never a silent FN. Curated per-path; do NOT broaden to whole types.\n// AWS::NetworkFirewall::RuleGroup.Description — live-proven (#507): a fresh deploy\n// returns Description (zero readGap), and `update-rule-group` WITHOUT --description\n// CLEARS it (replace-omit semantics), which was a silent FN.\n// AWS::NetworkFirewall::FirewallPolicy.Description — same service, same update-replace\n// semantics.\nexport const SCALAR_RETURNED_WHEN_SET: Record<string, ReadonlySet<string>> = {\n 'AWS::NetworkFirewall::RuleGroup': new Set(['Description']),\n 'AWS::NetworkFirewall::FirewallPolicy': new Set(['Description']),\n};\n\n// Declared SCALAR properties AWS does NOT echo faithfully — a write-time authoring hint\n// it normalizes to a canonical STORED form on read, so a declared value that differs from\n// the normalized read is a spurious `declared` drift, never a real divergence (and it is\n// not actionable: you cannot make AWS report the authored form). Stripped from BOTH the\n// declared and live model before compare — unlike a readGap (absent from the read), the\n// value IS present, just re-normalized. Distinct from writeOnly (schema-driven) because\n// AWS DOES return the property; it just returns its own value.\n// AWS::SSM::Document.DocumentFormat — the format of the SUPPLIED content (\"YAML\"/\"TEXT\").\n// AWS parses and STORES every Automation/Command document as JSON, so Cloud Control\n// always reads DocumentFormat back as \"JSON\" regardless of the authored format.\nexport const READ_NORMALIZED_DECLARED_PATHS: Record<string, ReadonlySet<string>> = {\n 'AWS::SSM::Document': new Set(['DocumentFormat']),\n};\n\n// Per-type OBJECT-array props AWS treats as UNORDERED SETS whose element objects\n// carry NO single identity field (so canonicalizeTagListsDeep cannot key them) and\n// are NOT scalar (so isEqualUnorderedScalarSet does not apply): EC2 SecurityGroup\n// ingress/egress rules are the case (R88) — a set of {CidrIp,IpProtocol,FromPort,\n// ToPort,Description,...} rules AWS returns in a different order than declared, which\n// a positional diff reports as false drift on every field of every shifted rule.\n// A blanket \"sort every identity-less object array\" is unsafe (some object arrays ARE\n// order-significant — CloudFront cache behaviors by precedence, etc.), so this stays a\n// per-type opt-in. Consulted by classify's declared loop, which sorts BOTH sides by\n// canonical JSON before the positional diff — a genuine rule change still differs.\nexport const UNORDERED_OBJECT_ARRAY_PROPS: Record<string, ReadonlySet<string>> = {\n 'AWS::EC2::SecurityGroup': new Set(['SecurityGroupIngress', 'SecurityGroupEgress']),\n // (AccessAnalyzer Analyzer `ArchiveRules` — the reorder FP that motivated #459 — is\n // now folded by the schema-driven `SchemaInfo.unorderedObjectArrayPaths` (its schema\n // marks the array insertionOrder:false and RuleName is not an identity field), so it\n // needs no entry here. The entries below predate that fold or lack the schema flag —\n // Cognito UserPoolResourceServer `Scopes` is insertionOrder-ABSENT, proving the flag\n // is under-set and this manual table stays as the SUPPLEMENT, not replaced.)\n // An ApplicationSignals SLO's `BurnRateConfigurations` is a SET of burn-rate windows\n // ({LookBackWindowMinutes: N}) that AWS returns reordered relative to the template\n // (declared [{60}, {360}] reads back [{360}, {60}]), so a positional compare\n // false-flags each window's LookBackWindowMinutes as declared drift on a freshly\n // recorded SLO. The element has no IDENTITY_FIELD (only LookBackWindowMinutes), so the\n // keyed canonicalizer can't align it — sorting both sides by canonical JSON does, and a\n // genuine window add/remove/change still differs.\n 'AWS::ApplicationSignals::ServiceLevelObjective': new Set(['BurnRateConfigurations']),\n // Cognito UserPoolResourceServer `Scopes` is a SET of {ScopeName, ScopeDescription}\n // OAuth scopes that AWS echoes SORTED by ScopeName, not in template order (declared\n // [zeta.write, alpha.read, mike.admin] reads back [alpha.read, mike.admin, zeta.write]),\n // so a positional compare false-flags every shifted scope's ScopeName AND\n // ScopeDescription as declared drift on a freshly recorded resource server. The\n // element key `ScopeName` is NOT one of canonicalizeTagListsDeep's IDENTITY_FIELDS\n // (Key/Id/AttributeName/IndexName/Name), so that keyed canonicalizer can't align it —\n // hence the per-type opt-in. Sorting both sides by canonical JSON aligns equal scopes;\n // a genuine scope add/remove/change still differs. Observed live on a fresh\n // cognito-userpool-sets deploy. (The sibling UserPool `AliasAttributes` set was tested\n // in the SAME deploy with a deliberately non-sorted list and Cognito PRESERVED its\n // order, so it is NOT folded — observed-only.)\n 'AWS::Cognito::UserPoolResourceServer': new Set(['Scopes']),\n // ListenerRule `Conditions` is a SET keyed by Field (path-pattern / host-header /\n // http-header / …) that AWS returns REORDERED relative to the template, so a\n // positional compare false-flags every condition. Sorting both sides by canonical\n // JSON aligns them by Field (the first sorted key), and a genuine condition change\n // still differs. (`Actions` is NOT listed — its element Order is semantic.) The live\n // model also adds a legacy top-level `Values` mirror to each condition; that is\n // handled separately as undeclared nested inventory (subset descent walks only the\n // declared *Config keys). Observed live on a fresh elbv2-listenerrule-rich deploy.\n 'AWS::ElasticLoadBalancingV2::ListenerRule': new Set(['Conditions']),\n // An IAM principal's inline `Policies` is a SET of {PolicyName, PolicyDocument}\n // that AWS returns SORTED by PolicyName, not in template order: a role declaring\n // [readObjects, describeOnly] reads back [describeOnly, readObjects] (alphabetical),\n // so a positional compare false-flags every shifted policy's PolicyName AND its\n // whole PolicyDocument as declared drift on a freshly recorded role. The element key\n // `PolicyName` is NOT one of canonicalizeTagListsDeep's IDENTITY_FIELDS\n // (Key/Id/AttributeName/IndexName/Name), so that keyed canonicalizer can't align it —\n // hence the per-type opt-in. Sorting runs AFTER canonicalizeForCompare, so each\n // element's PolicyDocument is already statement-canonicalized; sorting both sides by\n // canonical JSON then aligns equal policies and a genuine policy add/remove/change\n // still differs. Observed live on a fresh iam-permboundary-rich deploy. The identical\n // inline-policy-set shape lives on IAM User and Group (CFn `Policies` of the same\n // {PolicyName, PolicyDocument} element) — folded by the same set-semantics reasoning.\n 'AWS::IAM::Role': new Set(['Policies']),\n 'AWS::IAM::User': new Set(['Policies']),\n 'AWS::IAM::Group': new Set(['Policies']),\n // A Redshift ClusterParameterGroup's `Parameters` is a SET of {ParameterName,\n // ParameterValue} that AWS returns SORTED by ParameterName, not in template order: a\n // group declaring [require_ssl, enable_user_activity_logging, max_concurrency_scaling\n // _clusters] reads back [enable_user_activity_logging, max_concurrency_scaling_clusters,\n // require_ssl] (alphabetical), so a positional compare false-flags every shifted\n // parameter's ParameterName AND ParameterValue as declared drift on a freshly recorded\n // group. ParameterName is NOT an IDENTITY_FIELD, so only the per-type fold aligns it.\n // Sorting both sides by canonical JSON aligns equal parameters; a genuine value change\n // still differs. Observed live on a fresh redshift-paramgroup-reorder deploy. (The\n // sibling RDS DB/DBClusterParameterGroup `Parameters` is a free-form Map<String,String>,\n // not this array shape, so it is key-canonicalized — not folded here.)\n 'AWS::Redshift::ClusterParameterGroup': new Set(['Parameters']),\n // An EC2 Auto Scaling group's inline `LifecycleHookSpecificationList` is a SET of\n // hooks AWS echoes SORTED by LifecycleHookName, not in template order (declared\n // [zeta-terminate, alpha-launch] reads back [alpha-launch, zeta-terminate]), so a\n // positional compare false-flags every field of every shifted hook as declared drift\n // on a freshly recorded ASG. The element key `LifecycleHookName` is NOT one of\n // canonicalizeTagListsDeep's IDENTITY_FIELDS (Key/Id/AttributeName/IndexName/Name), so\n // that keyed canonicalizer can't align it — hence the per-type opt-in. Sorting both\n // sides by canonical JSON aligns equal hooks; a genuine hook add/remove/change still\n // differs. Observed live on a fresh asg-lifecyclehook-inline deploy. (This is the\n // ASG's OWN inline hook list — distinct from the standalone AWS::AutoScaling::\n // LifecycleHook resource the autoscaling-lifecyclehook-rich fixture covers.)\n 'AWS::AutoScaling::AutoScalingGroup': new Set(['LifecycleHookSpecificationList']),\n // A multi-region Secret's `ReplicaRegions` is a SET of {Region, KmsKeyId} that Secrets\n // Manager echoes SORTED by Region, not in template order (declared [us-west-2,\n // eu-west-1] reads back [eu-west-1, us-west-2]), so a positional compare false-flags\n // every shifted replica's Region as declared drift on a freshly recorded secret. The\n // element key `Region` is NOT one of canonicalizeTagListsDeep's IDENTITY_FIELDS\n // (Key/Id/AttributeName/IndexName/Name), so that keyed canonicalizer can't align it —\n // hence the per-type opt-in. Sorting both sides by canonical JSON aligns equal replicas;\n // a genuine region add/remove still differs. Observed live on a fresh\n // secret-replica-regions deploy.\n 'AWS::SecretsManager::Secret': new Set(['ReplicaRegions']),\n // An ElastiCache CacheCluster's `LogDeliveryConfigurations` is a SET of {LogType,\n // LogFormat, DestinationType, DestinationDetails} that AWS echoes SORTED by LogType,\n // not in template order (declared [slow-log, engine-log] reads back [engine-log,\n // slow-log] alphabetically), so a positional compare false-flags every field of every\n // shifted config — LogType AND the resolved destination LogGroup — as declared drift on\n // a freshly recorded cluster. The element key `LogType` is NOT one of\n // canonicalizeTagListsDeep's IDENTITY_FIELDS (Key/Id/AttributeName/IndexName/Name), so\n // that keyed canonicalizer can't align it — hence the per-type opt-in. Sorting both\n // sides by canonical JSON aligns equal configs; a genuine destination/format change\n // still differs. Observed live on a fresh elasticache-logdelivery deploy (slow-log +\n // engine-log to CloudWatch Logs). The same shape exists on AWS::ElastiCache::\n // ReplicationGroup (`LogDeliveryConfigurations` of identical {LogType, …} elements) —\n // folded by the same set-semantics reasoning.\n 'AWS::ElastiCache::CacheCluster': new Set(['LogDeliveryConfigurations']),\n 'AWS::ElastiCache::ReplicationGroup': new Set(['LogDeliveryConfigurations']),\n // A WAFv2 LoggingConfiguration's `RedactedFields` is a SET of discriminated-union\n // FieldToMatch objects ({SingleHeader: {Name}}, {Method: {}}, {QueryString: {}}, …)\n // that WAF echoes SORTED by the discriminator key, not in template order (declared\n // [SingleHeader, Method, QueryString] reads back [Method, QueryString, SingleHeader]),\n // so a positional compare false-flags every shifted field as declared drift on a\n // freshly recorded LoggingConfiguration. The elements carry NO top-level identity\n // field (the discriminator IS the single object key, not one of canonicalizeTagListsDeep's\n // IDENTITY_FIELDS Key/Id/AttributeName/IndexName/Name), so that keyed canonicalizer can't\n // align them — hence the per-type opt-in. Sorting both sides by canonical JSON aligns\n // equal fields; a genuine redacted-field add/remove still differs. Observed live on a\n // fresh wafv2-logging-rich deploy. (The sibling `LoggingFilter.Filters[].Conditions`\n // set was tested in the SAME deploy with two conditions and WAF PRESERVED their order,\n // so it is NOT folded — observed-only.)\n 'AWS::WAFv2::LoggingConfiguration': new Set(['RedactedFields']),\n};\n\n// Per-type NESTED array paths AWS returns reordered (dotted from the resource\n// root, e.g. `ContentPolicyConfig.FiltersConfig`). This is the nested twin of\n// UNORDERED_OBJECT_ARRAY_PROPS, which only reaches TOP-LEVEL array keys. Mostly\n// object-array sets, but a nested SCALAR set works too (DynamoDB NonKeyAttributes):\n// sortNestedObjectArrays/sortUnorderedObjectArray sort by each element's canonical\n// JSON, which orders scalars as well. Bedrock\n// Guardrail nests its policy-config sets one level deep and AWS canonicalizes the\n// element order (the content filters come back sorted by an internal order, not the\n// template's declaration order), so a positional compare false-flags a reordered-but-\n// identical set as several declared drifts. Each listed array is a SET keyed by an\n// identity field (FiltersConfig/PiiEntitiesConfig by Type, TopicsConfig/RegexesConfig\n// by Name, WordsConfig by Text) so sorting both sides by canonical JSON aligns equal\n// elements positionally; a genuine element add/remove/change still differs after the\n// sort. Observed live on a fresh bedrock-guardrail-rich deploy.\nexport const UNORDERED_NESTED_OBJECT_ARRAY_PATHS: Record<string, ReadonlySet<string>> = {\n // A CloudFront cache policy's forwarded-header set\n // (`...HeadersConfig.Headers`) is order-insensitive — CloudFront echoes it in its\n // own canonical order, not template order (declared [Origin, A, B] reads back\n // [Origin, B, A]), so a positional compare false-flags the identical header set as\n // declared drift on a freshly recorded policy. A nested SCALAR set (plain header\n // names — not id/ARN-shaped, so canonicalizeIdArraysDeep leaves it);\n // sortNestedObjectArrays sorts scalar arrays by canonical JSON, so equal sets align\n // and a genuine header add/remove/change still differs.\n 'AWS::CloudFront::CachePolicy': new Set([\n 'CachePolicyConfig.ParametersInCacheKeyAndForwardedToOrigin.HeadersConfig.Headers',\n ]),\n // A CloudFront distribution's `Aliases` (the CNAME set) is order-insensitive —\n // CloudFront returns it reordered relative to the template (declared [apex, wildcard]\n // reads back [wildcard, apex]), so a positional compare false-flags the identical\n // alias set as declared drift. Same nested-scalar-set treatment as CachePolicy Headers.\n 'AWS::CloudFront::Distribution': new Set(['DistributionConfig.Aliases']),\n // RULE-OUT (observed-only, NOT folded): a WAFv2 RuleGroup/WebACL rate-based rule's\n // `Rules[].Statement.RateBasedStatement.CustomKeys` is a SET of discriminated-union\n // aggregate-key objects ({UriPath:{}}, {Header:{Name,…}}, {HTTPMethod:{}}, …) with\n // no top-level IDENTITY_FIELD — the same shape that produced reorder FPs for\n // LoggingConfiguration RedactedFields (#433) and Lambda ESM KafkaBootstrapServers\n // (#437). Fresh wafv2-ratecustomkeys (RuleGroup) AND wafv2-webacl-customkeys (WebACL)\n // deploys each declaring 5 keys in NON-sorted discriminator order ([UriPath, Header,\n // HTTPMethod, Cookie, QueryArgument]) read them back in the EXACT declared order on\n // BOTH host types — WAF PRESERVES CustomKeys order (like AndStatement.Statements and\n // LoggingFilter.Conditions), so there is no FP to fold. Pinned by both fixtures +\n // corpus cases (issue #440).\n 'AWS::Bedrock::Guardrail': new Set([\n 'ContentPolicyConfig.FiltersConfig',\n 'TopicPolicyConfig.TopicsConfig',\n 'WordPolicyConfig.WordsConfig',\n 'WordPolicyConfig.ManagedWordListsConfig',\n 'SensitiveInformationPolicyConfig.PiiEntitiesConfig',\n 'SensitiveInformationPolicyConfig.RegexesConfig',\n ]),\n // ECS reorders a container's `PortMappings` relative to the template: a\n // task definition declaring ports [8080, 443, 80] reads back [443, 8080, 80] (the\n // mappings are a SET — order carries no meaning), so a positional compare false-flags\n // every shifted mapping as declared drift on a freshly deployed + recorded task def.\n // The path crosses the `ContainerDefinitions` ARRAY (sortNestedObjectArrays recurses\n // element-wise into it), so this aligns the PortMappings set INSIDE each container.\n // Sorting both sides by canonical JSON keys on ContainerPort (the first key), so equal\n // mappings land in the same slot and a genuine port add/remove/change still differs.\n // Observed live on a fresh ecs-taskdef-caps deploy (capabilities/ulimits/dnsSearch on\n // the same container were NOT reordered — only PortMappings). `VolumesFrom` (a SET\n // keyed by SourceContainer) is reordered the same way — declared [logger, app] reads\n // back [app, logger] — observed on a fresh ecs-taskdef-mounts deploy; MountPoints and\n // SystemControls on the same container were NOT reordered, so they are not listed.\n // A container's legacy bridge-mode `Links` is a nested SCALAR set (`name:alias`\n // strings) that ECS echoes SORTED alphabetically, not in template order (declared\n // [logger:log, init:setup] reads back [init:setup, logger:log]), so a positional\n // compare false-flags the identical link set on every check of a freshly recorded\n // task def. The values aren't id/ARN/HTTP/AZ-shaped, so canonicalizeIdArraysDeep\n // leaves them; sortNestedObjectArrays sorts a scalar array by canonical JSON, so the\n // same machinery that aligns PortMappings aligns it. A genuine link add/remove still\n // changes the multiset. Observed live on a fresh ecs-taskdef-sets deploy (DependsOn,\n // ExtraHosts, DockerSecurityOptions, DnsServers, and task-level PlacementConstraints\n // were declared non-sorted in the SAME deploy and ECS PRESERVED their order, so they\n // are deliberately NOT listed — observed-only).\n 'AWS::ECS::TaskDefinition': new Set([\n 'ContainerDefinitions.PortMappings',\n 'ContainerDefinitions.VolumesFrom',\n 'ContainerDefinitions.Links',\n ]),\n // DynamoDB sorts an INCLUDE-projection `NonKeyAttributes` set into its own canonical\n // order: declared [\"zeta\",\"alpha\",\"mike\",\"bravo\"] reads back reordered, a positional\n // compare false-flags the whole set. This is a nested SCALAR set (plain attribute names\n // — not id/ARN-shaped, so canonicalizeIdArraysDeep leaves it) nested under the\n // (Global|Local)SecondaryIndexes ARRAY; sortNestedObjectArrays sorts scalar arrays by\n // canonical JSON too, so the same machinery aligns it. A genuine attribute add/remove\n // still changes the multiset. The GSI path was observed live on a fresh\n // ddb-gsi-projection deploy; the LSI path and the AWS::DynamoDB::GlobalTable (TableV2)\n // GSI *and* LSI paths — the identical projection shape on a Table's LSI and on the\n // GlobalTable type — were observed live on a fresh ddb-nested-sets deploy (declared\n // [\"yankee\",\"bravo\",\"oscar\",\"delta\"] read back [\"oscar\",\"delta\",\"yankee\",\"bravo\"], etc.).\n 'AWS::DynamoDB::Table': new Set([\n 'GlobalSecondaryIndexes.Projection.NonKeyAttributes',\n 'LocalSecondaryIndexes.Projection.NonKeyAttributes',\n ]),\n 'AWS::DynamoDB::GlobalTable': new Set([\n 'GlobalSecondaryIndexes.Projection.NonKeyAttributes',\n 'LocalSecondaryIndexes.Projection.NonKeyAttributes',\n ]),\n // An ALB ListenerRule path-pattern condition's `Values` is a SET of patterns OR'd\n // together (order carries no meaning — a request matches if ANY value matches), and\n // ALB returns them in its OWN canonical order: declared [\"/zebra/*\",\"/alpha/*\",\n // \"/mango/*\"] reads back [\"/alpha/*\",\"/zebra/*\",\"/mango/*\"], so a positional compare\n // false-flags the whole set. The set is nested one object level (PathPatternConfig)\n // under the `Conditions` ARRAY, so sortNestedObjectArrays recurses element-wise and\n // sorts the scalar Values array. Observed live on a fresh elbv2-rule-values deploy.\n // (HostHeaderConfig.Values was tested in the SAME deploy with a deliberately\n // non-sorted set and ALB PRESERVED its order, so it is NOT listed — observed-only.)\n // `Conditions` is ALSO an UNORDERED_OBJECT_ARRAY_PROPS set; classify composes the\n // two — inner Values sorted first, then the Conditions array sorted by canonical JSON.\n // A source-ip condition's `SourceIpConfig.Values` (a CIDR set) and an http-header\n // condition's `HttpHeaderConfig.Values` (a header-value-string set) are reordered the\n // same way — observed live on a fresh elbv2-rule-conditions deploy (declared\n // [10.3/16, 10.1/16, 10.2/16] read back [10.3/16, 10.2/16, 10.1/16]; declared\n // [zeta, alpha, mike] read back [zeta, mike, alpha]). Both are OR'd value SETS (a\n // request matches if ANY value matches), so order carries no meaning. CIDRs and\n // header-value strings aren't id/ARN/HTTP/AZ-shaped, so canonicalizeIdArraysDeep leaves\n // them. (`QueryStringConfig.Values` was reordered in the SAME deploy too, but its\n // elements are {Key, Value} pairs — Key IS an IDENTITY_FIELD, so canonicalizeTagListsDeep\n // already aligns them; `HttpRequestMethodConfig.Values` is a set of HTTP verbs the\n // generic isHttpMethod sort folds — neither needs a table entry. HostHeaderConfig.Values\n // was observed order-PRESERVING in the earlier elbv2-rule-values deploy.)\n 'AWS::ElasticLoadBalancingV2::ListenerRule': new Set([\n 'Conditions.PathPatternConfig.Values',\n 'Conditions.SourceIpConfig.Values',\n 'Conditions.HttpHeaderConfig.Values',\n ]),\n // A BackupSelection's tag-based membership `BackupSelection.ListOfTags` is a SET of\n // {ConditionKey, ConditionType, ConditionValue} that AWS Backup echoes SORTED by\n // ConditionKey, not in template order (declared [zeta, alpha, mike] reads back\n // [alpha, mike, zeta]), so a positional compare false-flags every shifted condition's\n // ConditionKey AND ConditionValue as declared drift on a freshly recorded selection.\n // ConditionKey is NOT an IDENTITY_FIELD (Key/Id/AttributeName/IndexName/Name), so the\n // keyed canonicalizer can't align it. The set is nested one OBJECT level under the\n // top-level `BackupSelection` key (not under an array), like Bedrock Guardrail's\n // ContentPolicyConfig.FiltersConfig — sortNestedObjectArrays sorts the object array by\n // canonical JSON, aligning equal conditions; a genuine condition add/remove/change\n // still differs. Observed live on a fresh backup-selection deploy. (The sibling\n // `BackupSelection.Conditions.StringEquals` — the newer condition shape — was declared\n // non-sorted in the SAME deploy and AWS PRESERVED its order, so it is deliberately NOT\n // listed — observed-only.)\n 'AWS::Backup::BackupSelection': new Set(['BackupSelection.ListOfTags']),\n // An EC2 Auto Scaling group's `MetricsCollection[].Metrics` (the group metrics to\n // enable) and `NotificationConfigurations[].NotificationTypes` (the lifecycle events to\n // publish to SNS) are scalar enum SETs nested under their respective arrays that AWS\n // echoes SORTED alphabetically, not in template order (declared\n // [GroupTotalInstances, GroupDesiredCapacity, GroupMaxSize, GroupMinSize] reads back\n // [GroupDesiredCapacity, GroupMaxSize, GroupMinSize, GroupTotalInstances]; declared\n // [TERMINATE, LAUNCH, LAUNCH_ERROR] reads back [LAUNCH, LAUNCH_ERROR, TERMINATE]), so a\n // positional compare false-flags the identical set as declared drift on a freshly\n // recorded ASG. The tokens aren't id/ARN/HTTP/AZ-shaped, so canonicalizeIdArraysDeep\n // leaves them; the schema marks both insertionOrder:false but the scalar auto-fold skips\n // array-crossing (`*`) paths, so they need this per-type entry. sortNestedObjectArrays\n // crosses the MetricsCollection / NotificationConfigurations array and sorts the inner\n // scalar set; a genuine metric/event add/remove still differs. Observed live on a fresh\n // asg-notification-metrics deploy.\n 'AWS::AutoScaling::AutoScalingGroup': new Set([\n 'MetricsCollection.Metrics',\n 'NotificationConfigurations.NotificationTypes',\n ]),\n // A self-managed Apache Kafka event source's `SelfManagedEventSource.Endpoints.\n // KafkaBootstrapServers` is a SET of `host:port` broker strings that Lambda echoes\n // REORDERED, not in template order (declared [b-1…:9092, b-2…:9092] reads back\n // [b-2…:9092, b-1…:9092]), so a positional compare false-flags the identical\n // bootstrap-server set as declared drift on a freshly recorded ESM. The brokers are a\n // SET (a Kafka client connects to ANY one to discover the rest — order carries no\n // meaning), and the `host:port` strings aren't id/ARN/HTTP/AZ-shaped so\n // canonicalizeIdArraysDeep leaves them; this nested scalar path folds them. A genuine\n // broker add/remove still changes the multiset. Observed live on a fresh\n // esm-sourceaccess-rich deploy. (The sibling `SourceAccessConfigurations` set — the\n // {Type, URI} VPC/SASL entries — was tested in the SAME deploy with a deliberately\n // non-sorted list and Lambda PRESERVED its order, so it is NOT folded — observed-only.)\n 'AWS::Lambda::EventSourceMapping': new Set([\n 'SelfManagedEventSource.Endpoints.KafkaBootstrapServers',\n ]),\n};\n\n// Return a deep clone of `value` (a declared/live property subtree rooted at one\n// top-level key) with the object array at each of `subPaths` (dotted, RELATIVE to that\n// root) sorted into canonical order. Applied to BOTH the declared and live side before\n// the positional nested diff so a reordered-but-equal set aligns; a non-array or absent\n// path is left untouched, and a genuine element change still differs after the sort.\nexport function sortNestedObjectArrays(value: unknown, subPaths: readonly string[]): unknown {\n if (subPaths.length === 0 || value === null || typeof value !== 'object') return value;\n // A sub-path may cross an ARRAY (ECS `ContainerDefinitions.PortMappings`: the parent\n // ContainerDefinitions is itself an array, so PortMappings lives one level down inside\n // EACH element). Recurse element-wise, applying the same remaining sub-paths inside\n // every element, so the nested set is sorted within each container.\n if (Array.isArray(value)) return value.map((el) => sortNestedObjectArrays(el, subPaths));\n const clone = structuredClone(value) as Record<string, unknown>;\n for (const sub of subPaths) {\n const segs = sub.split('.');\n let cur: Record<string, unknown> | undefined = clone;\n for (let i = 0; i < segs.length - 1 && cur; i++) {\n const next: unknown = cur[segs[i] as string];\n cur =\n next !== null && typeof next === 'object' ? (next as Record<string, unknown>) : undefined;\n }\n const last = segs[segs.length - 1] as string;\n if (cur && Array.isArray(cur[last])) cur[last] = sortUnorderedObjectArray(cur[last]);\n }\n return clone;\n}\n\n// Stable, key-order-insensitive JSON of a value (objects emit keys sorted), used as a\n// total order to sort an unordered object array deterministically on both sides.\nfunction canonicalJson(v: unknown): string {\n if (Array.isArray(v)) return `[${v.map(canonicalJson).join(',')}]`;\n if (v && typeof v === 'object') {\n const o = v as Record<string, unknown>;\n return `{${Object.keys(o)\n .sort()\n .map((k) => `${JSON.stringify(k)}:${canonicalJson(o[k])}`)\n .join(',')}}`;\n }\n return JSON.stringify(v) ?? 'null';\n}\n\n// Sort an array by each element's canonical JSON (a no-op on non-arrays). Applied to\n// BOTH the declared and live side of an UNORDERED_OBJECT_ARRAY_PROPS property so a\n// reordered-but-equal rule set aligns positionally; equal elements (modulo key order)\n// land in the same slot, so the subsequent element-wise diff sees no drift, while a\n// genuinely changed rule still differs.\nexport function sortUnorderedObjectArray(v: unknown): unknown {\n if (!Array.isArray(v)) return v;\n return [...v].sort((a, b) => {\n const ka = canonicalJson(a);\n const kb = canonicalJson(b);\n return ka < kb ? -1 : ka > kb ? 1 : 0;\n });\n}\n\n// CFn has many \"stringly-typed\" fields: Glue Table `Parameters` is a\n// `Map<String,String>`, ports/sizes are declared as `\"5432\"`, booleans come back as\n// `\"true\"`. CDK sometimes emits the typed JSON form (boolean `true`, number `5432`)\n// while AWS returns the string (`\"true\"` / `\"5432\"`) — a positional diff then reports\n// false drift. Treat a primitive and its EXACT `String()` form as equal. Scalars only\n// (never collapses objects/arrays); a genuine value change (`true` vs `\"false\"`,\n// `5` vs `\"6\"`) still differs, so real drift is preserved.\n//\n// SCOPE: this scalar check runs in classify's declared loop on LEAF drift records.\n// The drift-calculator reports a scalar-ARRAY mismatch as ONE parent-path record\n// (value = the whole array), so this per-leaf check never sees the ELEMENTS of a\n// typed `[80, 443]` vs live `[\"80\", \"443\"]`. That array shape is handled by\n// `isStringlyEqualScalarArray` (R23) below, which applies this same typed<->string\n// collapse element-wise — so both the scalar and scalar-array forms are suppressed.\nconst DECIMAL_RE = /^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$/;\n\nexport function isStringlyEqualScalar(a: unknown, b: unknown): boolean {\n const prim = (v: unknown): v is boolean | number =>\n typeof v === 'boolean' || typeof v === 'number';\n const eq = (p: boolean | number, s: string): boolean => {\n if (String(p) === s) return true;\n // Numeric FORMATTING variants (R67): AWS returns decimal strings like \"5.0\"\n // for a declared number 5 (Budgets BudgetLimit.Amount). Numbers only, and the\n // string must be a plain decimal literal (no '' -> 0, no '0x10' = 16), so a\n // genuine value change still differs.\n return typeof p === 'number' && DECIMAL_RE.test(s.trim()) && Number(s) === p;\n };\n if (prim(a) && typeof b === 'string') return eq(a, b);\n if (prim(b) && typeof a === 'string') return eq(b, a);\n return false;\n}\n\n// R23: a scalar ARRAY whose elements are pairwise stringly-equal is not drift.\n// CFn stringly-typed list fields (declared `[80, 443]` while AWS returns\n// `[\"80\", \"443\"]`, declared `[true]` vs live `[\"true\"]`) surface from the\n// drift-calculator as ONE parent-path record carrying the WHOLE array, so the\n// per-leaf `isStringlyEqualScalar` above never compares the elements. This applies\n// the same typed<->string collapse element-wise: positional (order-sensitive —\n// unordered sets are handled by UNORDERED_ARRAY_PROPS), equal length + all scalars\n// required, each pair equal either strictly or via `isStringlyEqualScalar`. A\n// genuine element change (`[80, 443]` vs `[\"80\", \"8443\"]`) still differs, so real\n// drift is preserved.\nexport function isStringlyEqualScalarArray(a: unknown, b: unknown): boolean {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n const scalar = (v: unknown): boolean =>\n typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean';\n if (!a.every(scalar) || !b.every(scalar)) return false;\n return a.every((v, i) => v === b[i] || isStringlyEqualScalar(v, b[i]));\n}\n\n// A whole OBJECT/MAP whose only differences are typed<->string scalar coercions is\n// not drift. A free-form `Map<String,String>` (Glue Table/Database `Parameters`,\n// DockerLabels, Lambda env `Variables`, map `Tags`) whose KEYS contain the path\n// grammar's separators (a Glue `projection.enabled` key) is emitted by the\n// drift-calculator as ONE parent-path record carrying the WHOLE map — it never\n// descends, so the per-leaf `isStringlyEqualScalar` never sees the values. CDK emits\n// the typed JSON form for some values (boolean `projection.enabled: true`, a numeric\n// `skip.header.line.count: 2`) while AWS stores every map value as a STRING\n// (`\"true\"`, `\"2\"`), so a single such value makes the strict `deepEqual` fail and the\n// whole map false-drifts. This recurses both sides key-by-key (order-insensitive),\n// folding each leaf via the same typed<->string collapse. A genuinely\n// added/removed key, or a real value change, still differs — so real drift is kept.\n// Not Glue-specific: it folds the coercion for ANY whole-emitted free-form map.\nexport function isStringlyEqualDeep(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (isStringlyEqualScalar(a, b)) return true;\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n return a.every((v, i) => isStringlyEqualDeep(v, b[i]));\n }\n if (typeof a === 'object' && typeof b === 'object' && a !== null && b !== null) {\n const ao = a as Record<string, unknown>;\n const bo = b as Record<string, unknown>;\n const ak = Object.keys(ao);\n if (ak.length !== Object.keys(bo).length) return false;\n return ak.every((k) => Object.hasOwn(bo, k) && isStringlyEqualDeep(ao[k], bo[k]));\n }\n return false;\n}\n\n// A1: trivially-empty/off values AWS returns for unset features. Objects recurse:\n// a struct whose EVERY value is itself trivially empty is a feature-off struct —\n// e.g. the empty VpcConfig ({Ipv6AllowedForDualStack:false, SecurityGroupIds:[],\n// SubnetIds:[]}) that Lambda materializes after a Cloud Control UpdateResource,\n// which otherwise phantom-drifts on every revert (R46).\n//\n// Arrays: a length-0 array is trivially empty. A NON-empty array is trivially empty\n// ONLY when EVERY element is an OBJECT that is itself trivially empty — the signature\n// shape of schema-strip RESIDUE, where an echo attribute's leaves are readOnly-stripped\n// leaving `[{}, {}]` husks (RedshiftServerless Workgroup Endpoint\n// `VpcEndpoints[].NetworkInterfaces[{},{}]`, #491). This objects-ONLY recursion keeps the\n// conservative `[false]` stance for SCALAR arrays (a `[false]`/`[0]`/`[\"\"]` list may be a\n// meaningful value, so a scalar-bearing array is never trivially empty), same as the\n// top-level scalars (0 stays meaningful, false does not).\nexport function isTrivialEmpty(v: unknown): boolean {\n if (v === false || v === '') return true;\n if (Array.isArray(v)) {\n if (v.length === 0) return true;\n // Objects-only recursion: [{}, {}] husks fold, but any scalar element keeps the array.\n return v.every((el) => el !== null && typeof el === 'object' && isTrivialEmpty(el));\n }\n if (v && typeof v === 'object') return Object.values(v).every(isTrivialEmpty);\n return false;\n}\n\n// The AWS-managed (`aws:*`) tag ELEMENTS of a {Key,Value}[] tag list — the exact\n// inverse of what `stripAwsTagsDeep` drops. AWS forbids an external write that\n// removes or re-asserts an `aws:`-prefixed tag key (\"aws: prefixed tag key names\n// are not allowed for external use\"), so a Tags REVERT must carry these forward\n// untouched (the revert only ever changes the USER tags). Returns [] for a\n// non-list / a list with no managed tags. Used by the revert plan's tag-op guard.\nexport function awsManagedTags(v: unknown): { Key: string }[] {\n if (!Array.isArray(v)) return [];\n return v.filter(\n (t): t is { Key: string } =>\n !!t &&\n typeof t === 'object' &&\n typeof (t as { Key?: unknown }).Key === 'string' &&\n (t as { Key: string }).Key.startsWith('aws:')\n );\n}\n\n// A2: AWS-managed (aws:*) tags only. Handles BOTH the {Key,Value}[] list shape\n// (most types) AND the key->value map shape (e.g. AWS::SSM::Parameter.Tags).\nexport function isAllAwsTags(v: unknown): boolean {\n if (Array.isArray(v)) {\n return (\n v.length > 0 &&\n v.every(\n (t) =>\n t &&\n typeof t === 'object' &&\n typeof (t as { Key?: unknown }).Key === 'string' &&\n (t as { Key: string }).Key.startsWith('aws:')\n )\n );\n }\n if (v && typeof v === 'object') {\n const keys = Object.keys(v as Record<string, unknown>);\n return keys.length > 0 && keys.every((k) => k.startsWith('aws:'));\n }\n return false;\n}\n","// Recover non-ASCII string literals that CloudFormation's GetTemplate masked as `?`.\n//\n// GetTemplate (cdkrd's declared source) replaces every non-ASCII character in a stored\n// string literal with a literal `?` — see `isCfnTemplateNonAsciiMask`. CloudFormation\n// compares against the INTACT value server-side (its own drift detection reports such a\n// property IN_SYNC), but the value it exposes through GetTemplate is lossy, so a\n// client-side compare against the live value would false-flag every check. Without a\n// recovery source the property degrades to a `readGap` (declared-but-unverifiable):\n// honest, but cdkrd then detects LESS than `cdk drift` on that property.\n//\n// The LOCAL synth template (the cdk.out assembly cdkrd already produces for stack\n// discovery) carries the intact UTF-8. When the synth value at the SAME template path\n// masks to the deployed `?`-value (same ASCII skeleton, same length, ≥1 non-ASCII char),\n// it IS the deployed declared value with its non-ASCII recovered — substitute it so the\n// comparison runs on real text and a genuine out-of-band non-ASCII change is detectable.\n//\n// Gated per-value by the mask: a synth value whose ASCII skeleton or length does NOT\n// match the deployed mask (the local code diverged structurally from what is deployed)\n// is NEVER substituted — that property stays a `readGap`. So this only ever fires on the\n// exact values GetTemplate corrupted; a pure-ASCII template is untouched (GetTemplate\n// never masks ASCII, so no `?`-leaf ever matches a non-ASCII synth value).\nimport { isCfnTemplateNonAsciiMask } from '../normalize/noise.js';\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\n// Walk the parsed DEPLOYED template and the LOCAL synth template in parallel by\n// key/index; replace any deployed string leaf that is a non-ASCII GetTemplate mask of the\n// synth value with the (intact) synth value. Returns the recovered template; mutates\n// nested objects/arrays of `deployed` in place (callers pass the freshly parsed template).\nexport function recoverNonAsciiMasks(deployed: unknown, recovery: unknown): unknown {\n if (typeof deployed === 'string') {\n return typeof recovery === 'string' && isCfnTemplateNonAsciiMask(deployed, recovery)\n ? recovery\n : deployed;\n }\n if (Array.isArray(deployed) && Array.isArray(recovery)) {\n for (let i = 0; i < deployed.length; i++) {\n deployed[i] = recoverNonAsciiMasks(deployed[i], recovery[i]);\n }\n return deployed;\n }\n if (isObject(deployed) && isObject(recovery)) {\n for (const k of Object.keys(deployed)) {\n deployed[k] = recoverNonAsciiMasks(deployed[k], recovery[k]);\n }\n return deployed;\n }\n return deployed;\n}\n","// CloudFormation-aware YAML parser (parse-only). Copied/trimmed from cdkd\n// src/cli/yaml-cfn.ts — preserves CFn shorthand tags (!Ref/!GetAtt/!Sub/...) by\n// resolving each to its long-form object ({Ref:...} / {Fn::Foo:...}) so the rest\n// of cdk-real-drift reads one canonical (JSON-equivalent) representation.\n\nimport type { CollectionTag, ScalarTag, YAMLMap, YAMLSeq } from 'yaml';\nimport { parse as yamlParse } from 'yaml';\n\nexport type TemplateFormat = 'json' | 'yaml';\n\nconst FN_TAGS = [\n 'GetAtt',\n 'Sub',\n 'Join',\n 'Select',\n 'Split',\n 'If',\n 'Equals',\n 'And',\n 'Or',\n 'Not',\n 'FindInMap',\n 'Base64',\n 'Cidr',\n 'GetAZs',\n 'ImportValue',\n 'Length',\n 'ToJsonString',\n 'ForEach',\n] as const;\n\nfunction nodeJs(node: unknown): unknown {\n if (node === null || node === undefined) return null;\n if (typeof node === 'object' && 'toJSON' in (node as object))\n return (node as { toJSON(): unknown }).toJSON();\n return node;\n}\n\nfunction buildCustomTags(): Array<ScalarTag | CollectionTag> {\n const tags: Array<ScalarTag | CollectionTag> = [];\n tags.push({\n tag: '!Ref',\n resolve: (v: string) => ({ Ref: v }),\n identify: () => false,\n } as ScalarTag);\n tags.push({\n tag: '!Condition',\n resolve: (v: string) => ({ Condition: v }),\n identify: () => false,\n } as ScalarTag);\n tags.push({\n tag: '!Transform',\n collection: 'map',\n resolve: (n: YAMLMap) => ({ 'Fn::Transform': nodeJs(n) }),\n identify: () => false,\n } as CollectionTag);\n tags.push({\n tag: '!GetAtt',\n resolve(value: string): unknown {\n const dot = value.indexOf('.');\n // A dot-less `!GetAtt X` is malformed (CFn wants `<LogicalId>.<Attribute>`),\n // but a custom-tag `resolve` that THROWS aborts the whole `yaml` parse — one\n // bad scalar would crash the entire stack check (GetTemplate returns the\n // deployed body verbatim, and a --pre-deploy synth / hand-written template can\n // carry it). Degrade to a 1-element Fn::GetAtt instead: resolveGetAtt requires\n // length >= 2, so it resolves to UNRESOLVED and that one property is skipped,\n // never mis-compared — the rest of the template still parses.\n if (dot < 0) return { 'Fn::GetAtt': [value] };\n return { 'Fn::GetAtt': [value.slice(0, dot), value.slice(dot + 1)] };\n },\n identify: () => false,\n } as ScalarTag);\n tags.push({\n tag: '!GetAtt',\n collection: 'seq',\n resolve: (n: YAMLSeq) => ({ 'Fn::GetAtt': nodeJs(n) }),\n identify: () => false,\n } as CollectionTag);\n for (const name of FN_TAGS) {\n if (name === 'GetAtt') continue;\n const longKey = `Fn::${name}`;\n tags.push({\n tag: `!${name}`,\n resolve: (v: string | number | null) => ({ [longKey]: v }),\n identify: () => false,\n } as ScalarTag);\n tags.push({\n tag: `!${name}`,\n collection: 'seq',\n resolve: (n: YAMLSeq) => ({ [longKey]: nodeJs(n) }),\n identify: () => false,\n } as CollectionTag);\n tags.push({\n tag: `!${name}`,\n collection: 'map',\n resolve: (n: YAMLMap) => ({ [longKey]: nodeJs(n) }),\n identify: () => false,\n } as CollectionTag);\n }\n return tags;\n}\n\nconst CUSTOM_TAGS = buildCustomTags();\n\nexport function detectTemplateFormat(text: string): TemplateFormat {\n const stripped = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;\n const trimmed = stripped.trimStart();\n if (trimmed.length === 0) return 'json';\n const first = trimmed.charCodeAt(0);\n return first === 0x7b || first === 0x5b ? 'json' : 'yaml'; // '{' or '['\n}\n\nexport function parseCfnTemplate(text: string): Record<string, unknown> {\n const format = detectTemplateFormat(text);\n const body = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;\n let parsed: unknown;\n if (format === 'json') {\n parsed = JSON.parse(body);\n } else {\n parsed = yamlParse(body, { customTags: CUSTOM_TAGS });\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('Template root is not an object.');\n }\n return parsed as Record<string, unknown>;\n}\n","// Builds the \"declared desired\" view of a deployed stack:\n// GetTemplate + ListStackResources (phys-id map, paginated) + DescribeStacks (params)\n// → intrinsic-resolve each resource's declared properties.\n// Slice scope: JSON templates (CDK app output). YAML support is a follow-up.\nimport {\n type CloudFormationClient,\n DescribeStacksCommand,\n GetTemplateCommand,\n ListExportsCommand,\n ListStackResourcesCommand,\n} from '@aws-sdk/client-cloudformation';\nimport { classifyStackStatus, StackNotCheckableError } from '../aws-errors.js';\nimport { resolveProperties } from '../normalize/intrinsic-resolver.js';\nimport type { DesiredResource, ResolverContext } from '../types.js';\nimport { recoverNonAsciiMasks } from './recover-nonascii.js';\nimport { parseCfnTemplate } from './yaml-cfn.js';\n\nexport interface Desired {\n stackName: string;\n region: string;\n accountId: string;\n resources: DesiredResource[];\n rawTemplate: string; // verbatim deployed template body (for baseline templateHash)\n ctx: ResolverContext; // exposed so gather can re-resolve GetAtt once live attrs are read\n // set when the stack's StackStatus is mid-operation / failed (a comparison still runs\n // but results may be unreliable — check prints this). REVIEW_IN_PROGRESS / deleting\n // states never reach here: loadDesired throws StackNotCheckableError for those.\n stackStatusWarning?: string | undefined;\n}\n\n/** Parse a deployed template body (JSON or CFn-flavored YAML). */\nexport function parseTemplateBody(body: string): Record<string, unknown> {\n return parseCfnTemplate(body);\n}\n\nexport function buildResolverContext(\n template: Record<string, any>,\n stackParams: Record<string, string>,\n physIds: Record<string, string>,\n region: string,\n accountId: string,\n stackName: string,\n stackId: string\n): ResolverContext {\n // CommaDelimitedList / List<> params must resolve to ARRAYS so Fn::Join /\n // Fn::Select / conditions over them evaluate correctly (a string would break\n // Fn::Join and mis-evaluate conditions like HasTrustedAccounts).\n const paramDefs = (template.Parameters ?? {}) as Record<\n string,\n { Default?: unknown; Type?: string }\n >;\n const isList = (k: string): boolean => {\n const t = paramDefs[k]?.Type ?? '';\n return t === 'CommaDelimitedList' || t.startsWith('List<');\n };\n // CommaDelimitedList values are whitespace-trimmed by CloudFormation\n // (\"a, b , c\" -> [\"a\",\"b\",\"c\"]); mirror that so a Fn::Select / membership test\n // over the list matches the deployed-resource value (untrimmed \" b\" would FP).\n const toParam = (k: string, raw: string): string | string[] =>\n isList(k) ? (raw === '' ? [] : raw.split(',').map((s) => s.trim())) : raw;\n const params: Record<string, string | string[]> = {};\n for (const [k, def] of Object.entries(paramDefs)) {\n if (def && 'Default' in def) params[k] = toParam(k, String(def.Default));\n }\n for (const [k, v] of Object.entries(stackParams)) params[k] = toParam(k, v); // deployed values win\n // logicalId -> type and -> raw declared Properties, for resolveGetAtt's\n // declared-property-mirroring attributes (GETATT_DECLARED_PROPERTY).\n const templateResources = (template.Resources ?? {}) as Record<\n string,\n { Type?: string; Properties?: Record<string, unknown> }\n >;\n const typeOf: Record<string, string> = {};\n const declaredRawProps: Record<string, Record<string, unknown>> = {};\n for (const [lid, res] of Object.entries(templateResources)) {\n if (res?.Type) typeOf[lid] = res.Type;\n if (res?.Properties) declaredRawProps[lid] = res.Properties;\n }\n return {\n params,\n pseudo: {\n 'AWS::Region': region,\n 'AWS::AccountId': accountId,\n 'AWS::Partition': 'aws',\n 'AWS::URLSuffix': 'amazonaws.com',\n 'AWS::StackName': stackName,\n 'AWS::StackId': stackId,\n },\n conditions: template.Conditions ?? {},\n physIds,\n liveAttrs: {},\n typeOf,\n declaredRawProps,\n mappings: template.Mappings ?? {},\n exports: {}, // populated by loadDesired's prefetch only when the template references Fn::ImportValue\n condCache: new Map(),\n };\n}\n\n// Per-region cache of CFn exports (Name -> Value). Listing exports is account+region\n// scoped, so a single fetch serves every ImportValue in the stack; cache so repeated\n// gather runs in the same process don't re-page.\nconst exportsCache = new Map<string, Record<string, string>>();\n\nasync function listExports(\n client: CloudFormationClient,\n region: string\n): Promise<Record<string, string>> {\n const cached = exportsCache.get(region);\n if (cached) return cached;\n const exports: Record<string, string> = {};\n let next: string | undefined;\n do {\n const res = await client.send(new ListExportsCommand({ NextToken: next }));\n for (const e of res.Exports ?? []) if (e.Name) exports[e.Name] = e.Value ?? '';\n next = res.NextToken;\n } while (next);\n exportsCache.set(region, exports);\n return exports;\n}\n\n// Page ListStackResources (DescribeStackResources caps at 100; CDK stacks reach ~500).\nasync function listStackResources(\n client: CloudFormationClient,\n stackName: string\n): Promise<{ physIds: Record<string, string>; typeOf: Record<string, string> }> {\n const physIds: Record<string, string> = {};\n const typeOf: Record<string, string> = {};\n let next: string | undefined;\n do {\n const res = await client.send(\n new ListStackResourcesCommand({ StackName: stackName, NextToken: next })\n );\n for (const r of res.StackResourceSummaries ?? []) {\n if (r.LogicalResourceId && r.PhysicalResourceId)\n physIds[r.LogicalResourceId] = r.PhysicalResourceId;\n if (r.LogicalResourceId && r.ResourceType) typeOf[r.LogicalResourceId] = r.ResourceType;\n }\n next = res.NextToken;\n } while (next);\n return { physIds, typeOf };\n}\n\nexport async function loadDesired(\n client: CloudFormationClient,\n stackName: string,\n region: string,\n // when provided (--pre-deploy), this LOCAL synth template is the declared source\n // instead of the deployed GetTemplate; physIds + params still come from the live stack\n templateOverride?: Record<string, unknown>,\n // the LOCAL synth template, used ONLY to recover non-ASCII string literals that\n // GetTemplate masked as `?` (see recoverNonAsciiMasks). Unlike templateOverride it does\n // NOT replace the declared source — it patches only the mask-matching corrupted leaves.\n recoveryTemplate?: Record<string, unknown>\n): Promise<Desired> {\n // GetTemplate + DescribeStacks are single calls (kept in Promise.all); ListStackResources\n // is paginated separately (DescribeStackResources caps at 100, CDK stacks reach ~500).\n const [tmplRes, stkRes, { physIds }] = await Promise.all([\n templateOverride\n ? Promise.resolve({ TemplateBody: undefined })\n : client.send(new GetTemplateCommand({ StackName: stackName })),\n client.send(new DescribeStacksCommand({ StackName: stackName })),\n listStackResources(client, stackName),\n ]);\n const stack = stkRes.Stacks?.[0];\n // Stack-state gate — runs BEFORE the template is parsed: a REVIEW_IN_PROGRESS stack\n // (a change set created but never deployed) returns an EMPTY GetTemplate body, which\n // would otherwise blow up parseTemplateBody with \"Unexpected end of JSON input\". Skip\n // a stack with no meaningful deployed reality (REVIEW_IN_PROGRESS / deleting) rather\n // than silently compare live state against a never-deployed template; carry a warning\n // for mid-operation / failed states. Skipped under --pre-deploy (the declared source\n // is the LOCAL synth, not the deployed stack).\n const stateClass = templateOverride\n ? ({ kind: 'ok', message: '' } as const)\n : classifyStackStatus(stack?.StackStatus);\n if (stateClass.kind === 'skip') throw new StackNotCheckableError(stateClass.message);\n const stackStatusWarning = stateClass.kind === 'warn' ? stateClass.message : undefined;\n const template = (templateOverride ?? parseTemplateBody(tmplRes.TemplateBody ?? '{}')) as Record<\n string,\n any\n >;\n // Recover GetTemplate's `?`-masked non-ASCII literals from the local synth template\n // (mask-gated, per leaf). Skipped under --pre-deploy: there the declared source already\n // IS the intact synth template, so there is nothing to recover.\n if (!templateOverride && recoveryTemplate) recoverNonAsciiMasks(template, recoveryTemplate);\n const rawTemplate = templateOverride\n ? JSON.stringify(templateOverride)\n : (tmplRes.TemplateBody ?? '{}');\n const stackId = stack?.StackId ?? '';\n const accountId = stackId.split(':')[4] ?? '';\n\n const stackParams: Record<string, string> = {};\n for (const p of stack?.Parameters ?? []) {\n if (!p.ParameterKey) continue;\n // SSM-typed params (Type: AWS::SSM::Parameter::Value<...>) carry the raw SSM\n // KEY in ParameterValue and the dereferenced value in ResolvedValue — prefer\n // ResolvedValue so Ref resolves to what AWS actually deployed, not the key.\n const value = p.ResolvedValue ?? p.ParameterValue ?? '';\n // A NoEcho parameter is returned MASKED as '****'. Comparing against the mask\n // would be a false positive, so skip it entirely: the param drops out of ctx,\n // Ref resolves UNRESOLVED, and the dependent property is skipped (not compared)\n // — same treatment as a dynamic reference we cannot resolve.\n if (value === '****') continue;\n stackParams[p.ParameterKey] = value;\n }\n\n const ctx = buildResolverContext(\n template,\n stackParams,\n physIds,\n region,\n accountId,\n stackName,\n stackId\n );\n\n // Fn::ImportValue is synchronous in the resolver, so prefetch exports here — but\n // ONLY when the template actually references it, so normal stacks pay nothing for the\n // extra ListExports call(s). Gate on the PARSED template, NOT the raw body: a YAML\n // deployed template carries the short-form `!ImportValue` tag, so a substring check on\n // the raw body would miss it and leave exports unfetched — the import then resolves\n // UNRESOLVED and its declared property is silently skipped (missed drift).\n // parseTemplateBody has already normalized short-form tags to long-form `Fn::ImportValue`.\n if (JSON.stringify(template).includes('Fn::ImportValue')) {\n ctx.exports = await listExports(client, region);\n }\n\n const resources: DesiredResource[] = [];\n // IAM principals (Role / User / Group) whose inline Policies are managed by SIBLING\n // AWS::IAM::Policy resources (the CDK pattern). classify uses the per-principal POLICY\n // NAMES to drop only the sibling-owned live entries — an out-of-band inline policy still\n // surfaces.\n const principalsWithSiblingPolicy = collectPrincipalsWithSiblingPolicies(\n template.Resources ?? {},\n ctx\n );\n // ECS Cluster logicalIds whose CapacityProviders / DefaultCapacityProviderStrategy are\n // declared by a sibling AWS::ECS::ClusterCapacityProviderAssociations resource (the only\n // CFn way to set them). classify drops those reflected live props on the flagged cluster.\n const clustersWithSiblingCapacityProviders = collectClustersWithSiblingCapacityProviders(\n template.Resources ?? {}\n );\n\n for (const [logicalId, res] of Object.entries(\n (template.Resources ?? {}) as Record<string, any>\n )) {\n if (res.Type === 'AWS::CDK::Metadata') continue;\n const cdkPath = res.Metadata?.['aws:cdk:path'];\n const declaredRaw = (res.Properties ?? {}) as Record<string, unknown>;\n resources.push({\n logicalId,\n resourceType: res.Type as string,\n physicalId: physIds[logicalId],\n constructPath: typeof cdkPath === 'string' ? prettyConstructPath(cdkPath) : undefined,\n // first-pass resolution (no live attrs yet → GetAtt is UNRESOLVED). gather\n // re-resolves declaredRaw once liveAttrs is populated, reducing UNRESOLVED.\n declared: resolveProperties(declaredRaw, ctx),\n declaredRaw,\n siblingPolicyNames: IAM_PRINCIPAL_TYPES.has(res.Type)\n ? principalsWithSiblingPolicy.get(logicalId)\n : undefined,\n hasSiblingCapacityProviders:\n res.Type === 'AWS::ECS::Cluster'\n ? clustersWithSiblingCapacityProviders.has(logicalId)\n : undefined,\n });\n }\n return { stackName, region, accountId, resources, rawTemplate, ctx, stackStatusWarning };\n}\n\n// The IAM principal types an AWS::IAM::Policy can attach an inline policy to, via its\n// Roles / Users / Groups reference lists (the CDK `<Principal>DefaultPolicy` pattern).\nconst IAM_PRINCIPAL_TYPES: ReadonlySet<string> = new Set([\n 'AWS::IAM::Role',\n 'AWS::IAM::User',\n 'AWS::IAM::Group',\n]);\n\n// CDK construct paths end in \"/Resource\" for the L1 node; drop it for readability\n// (e.g. \"MyStack/Bucket/Resource\" -> \"MyStack/Bucket\").\nfunction prettyConstructPath(p: string): string {\n return p.endsWith('/Resource') ? p.slice(0, -'/Resource'.length) : p;\n}\n\n/**\n * Map each IAM principal logicalId (Role / User / Group) to the PolicyNames of the\n * sibling AWS::IAM::Policy resources attached to it via its Roles / Users / Groups\n * reference lists. A sibling whose PolicyName cannot be resolved to a string (an\n * intrinsic the resolver can't evaluate) marks the principal 'unresolved' — classify\n * then falls back to suppressing the whole live Policies property rather than risk a\n * false positive on the unidentifiable sibling entry.\n */\nexport function collectPrincipalsWithSiblingPolicies(\n resources: Record<string, any>,\n ctx?: ResolverContext\n): Map<string, string[] | 'unresolved'> {\n const principals = new Map<string, string[] | 'unresolved'>();\n for (const res of Object.values(resources)) {\n if (res?.Type !== 'AWS::IAM::Policy') continue;\n const name = resolvePolicyName(res.Properties?.PolicyName, ctx);\n const refs = [\n ...((res.Properties?.Roles ?? []) as unknown[]),\n ...((res.Properties?.Users ?? []) as unknown[]),\n ...((res.Properties?.Groups ?? []) as unknown[]),\n ];\n for (const r of refs) {\n const ref = r && typeof r === 'object' ? (r as Record<string, unknown>).Ref : undefined;\n if (typeof ref !== 'string') continue;\n const prev = principals.get(ref);\n if (prev === 'unresolved') continue;\n if (name === undefined) principals.set(ref, 'unresolved');\n else principals.set(ref, [...(prev ?? []), name]);\n }\n }\n return principals;\n}\n\n/**\n * The set of ECS Cluster logicalIds that a sibling AWS::ECS::ClusterCapacityProviderAssociations\n * resource references (via its `Cluster: { Ref }`). CapacityProviders and\n * DefaultCapacityProviderStrategy can only be set through that separate resource — the Cluster's\n * own schema has no such property — so the association reflects them into the cluster's live model\n * where they read as false undeclared drift. The association is tracked + compared as its own\n * resource, so classify drops the reflected props on a flagged cluster.\n */\nexport function collectClustersWithSiblingCapacityProviders(\n resources: Record<string, any>\n): Set<string> {\n const clusters = new Set<string>();\n for (const res of Object.values(resources)) {\n if (res?.Type !== 'AWS::ECS::ClusterCapacityProviderAssociations') continue;\n const ref = res.Properties?.Cluster?.Ref;\n if (typeof ref === 'string') clusters.add(ref);\n }\n return clusters;\n}\n\n// CDK emits literal PolicyNames (e.g. \"RoleDefaultPolicyABC123\"); hand-written\n// templates may use intrinsics, which we resolve when a ctx is available.\nfunction resolvePolicyName(raw: unknown, ctx?: ResolverContext): string | undefined {\n if (typeof raw === 'string') return raw;\n if (raw === undefined || raw === null || !ctx) return undefined;\n const resolved = resolveProperties({ PolicyName: raw }, ctx).PolicyName;\n return typeof resolved === 'string' ? resolved : undefined; // UNRESOLVED is a symbol, never a string\n}\n","// Name <-> ARN identity normalization. Many AWS fields record a bare resource\n// NAME on input but AWS stores + returns the full ARN (Lambda\n// EventSourceMapping.FunctionName / Lambda Permission.FunctionName / ECS\n// Service.Cluster, etc.). A positional string diff then reports false drift:\n// desired = \"MyFn\" actual = \"arn:aws:lambda:us-east-1:123:function:MyFn\"\n//\n// Conservative + value-shape-based (NOT field-name-based, so it needs no per-type\n// table): treat the two as equal when EXACTLY ONE side is a well-formed ARN, the\n// other is a bare (non-ARN) name, and the name EQUALS the ARN's final component — its\n// whole final colon-segment, OR the part after that segment's last '/' (the resource\n// id of a `type/id` ARN). The match is on a COMPLETE component, never a partial path\n// suffix, so a declared `a/b/c` never equals a live `arn:…:bucket/x/a/b/c` (a different\n// object) — a real identity change is not hidden.\n//\n// BIDIRECTIONAL: the bare name may be on EITHER side. `desired=name, actual=ARN`\n// occurs when AWS stores the full ARN for a name-recording input (Lambda\n// EventSourceMapping.FunctionName, ECS Service.Cluster, ...); `desired=ARN,\n// actual=name` occurs the other way (AWS::Lambda::Url.TargetFunctionArn: the template\n// resolves Fn::GetAtt to the function ARN, but the live read returns the bare name).\n//\n// When the stack's accountId/region are supplied, ALSO require the ARN's region\n// (index 3) and account (index 4) segments to match the stack's — a same-named\n// resource in a DIFFERENT account/region is genuine drift, not a name<->ARN echo.\n// Some ARN partitions leave region/account empty (S3: `arn:aws:s3:::bucket/name`);\n// for those empty segments we skip the check and stay suffix-only.\nexport function isArnNameMatch(\n desired: unknown,\n actual: unknown,\n opts?: { accountId?: string; region?: string }\n): boolean {\n if (typeof desired !== 'string' || typeof actual !== 'string') return false;\n const dArn = desired.startsWith('arn:');\n const aArn = actual.startsWith('arn:');\n // exactly one side must be an ARN (both ARNs or neither = not a name<->ARN echo)\n if (dArn === aArn) return false;\n const arn = dArn ? desired : actual;\n const name = dArn ? actual : desired;\n return arnMatchesName(arn, name, opts);\n}\n\nfunction arnMatchesName(\n arn: string,\n name: string,\n opts?: { accountId?: string; region?: string }\n): boolean {\n if (name.length === 0) return false;\n // Match the ARN's EXACT final component, NOT a raw suffix. The final colon-segment is\n // the resource portion (`myFn`, `role/myRole`, `bucket/a/b/c`); the name must equal\n // that whole portion OR the part after its last `/` (the resource id of a `type/id`\n // ARN). A bare `endsWith('/'+name)` matched a MULTI-segment path suffix — declared\n // `a/b/c` falsely equalled live `arn:…:bucket/x/a/b/c` (a DIFFERENT object), hiding a\n // real identity change. Equality on the final component never spans a `/` boundary, so\n // that FN is closed while every real name<->ARN echo (`myRole` vs `…:role/myRole`,\n // `myFn` vs `…:function:myFn`, `my-bucket` vs `arn:aws:s3:::my-bucket`) still matches.\n const afterColon = arn.slice(arn.lastIndexOf(':') + 1);\n const afterSlash = afterColon.includes('/')\n ? afterColon.slice(afterColon.lastIndexOf('/') + 1)\n : afterColon;\n // arn:partition:service:region:account:resource — segments 3 (region) + 4 (account)\n const seg = arn.split(':');\n // A resource id that itself carries a colon (a Lambda function ARN qualified by an\n // alias/version: `arn:…:function:NAME:QUALIFIER`) reassembles as segments 6.. — the\n // declared side is the bare `NAME:QUALIFIER`, which the last-colon-segment rule would\n // otherwise truncate to just `QUALIFIER`. Compare the whole colon-joined resource id too.\n const colonId = seg.length >= 7 ? seg.slice(6).join(':') : afterColon;\n if (name !== afterColon && name !== afterSlash && name !== colonId) return false;\n const arnRegion = seg[3] ?? '';\n const arnAccount = seg[4] ?? '';\n if (opts?.region && arnRegion && arnRegion !== opts.region) return false;\n if (opts?.accountId && arnAccount && arnAccount !== opts.accountId) return false;\n return true;\n}\n\n// AWS-managed default KMS keys are declared by their well-known alias\n// (`alias/aws/rds`, `alias/aws/secretsmanager`, ...) but AWS resolves + returns\n// the concrete key ARN, which a string diff flags as drift.\n//\n// When `aliasTargets` (alias name -> target key id, from KMS ListAliases) is\n// provided AND the declared alias is in it, this does a STRICT comparison: the live\n// key ARN must resolve to that same managed key, else it is reported as real drift —\n// so a customer-managed key swapped in out of band (a security-relevant change the\n// shape-only check would hide) IS caught. When the alias can't be resolved (no\n// `aliasTargets`, or missing kms:ListAliases), it falls back to the conservative\n// shape-based match (any `alias/aws/*` vs any key ARN = equal): biased toward noise,\n// never a false positive.\nconst KMS_KEY_ARN_RE = /^arn:aws[a-z-]*:kms:[^:]*:\\d*:key\\//;\nconst keyIdOf = (s: string): string => s.slice(s.lastIndexOf('/') + 1);\nexport function isManagedKmsAliasMatch(\n desired: unknown,\n actual: unknown,\n aliasTargets?: Record<string, string>\n): boolean {\n if (\n typeof desired !== 'string' ||\n typeof actual !== 'string' ||\n !desired.startsWith('alias/aws/') ||\n !KMS_KEY_ARN_RE.test(actual)\n )\n return false;\n const target = aliasTargets?.[desired];\n if (target) {\n // strict: suppress only when the live key IS the alias's managed key\n return keyIdOf(actual) === keyIdOf(target);\n }\n // unresolved alias → conservative shape-based suppression (today's behavior)\n return true;\n}\n\n// A CloudWatch Logs log-group ARN carries a trailing `:*` wildcard segment\n// (`...:log-group:/my/group:*`) that scopes it to the group's log STREAMS. CDK's\n// `logGroup.logGroupArn` emits the ARN WITH that `:*`, so a template references it\n// that way — but several services store + return the SAME ARN with the `:*`\n// stripped (observed: API Gateway `AWS::ApiGateway::Stage`\n// AccessLogSetting.DestinationArn). A positional string diff then reports false\n// drift on a fresh deploy with nothing changed:\n// desired = \"arn:aws:logs:...:log-group:/aws/api-gateway/x:*\"\n// actual = \"arn:aws:logs:...:log-group:/aws/api-gateway/x\"\n//\n// Shape-based + value-only (NOT field-name-based, so no per-type table): suppress\n// ONLY when BOTH sides are well-formed log-group ARNs that are byte-identical after\n// dropping a single trailing `:*` from each. A different log group still differs\n// after the strip, so this never hides a real repoint.\nconst LOG_GROUP_ARN_RE = /^arn:aws[a-z-]*:logs:[^:]*:\\d*:log-group:/;\nconst stripLogGroupWildcard = (s: string): string => (s.endsWith(':*') ? s.slice(0, -2) : s);\nexport function isLogGroupArnWildcardMatch(desired: unknown, actual: unknown): boolean {\n if (\n typeof desired !== 'string' ||\n typeof actual !== 'string' ||\n !LOG_GROUP_ARN_RE.test(desired) ||\n !LOG_GROUP_ARN_RE.test(actual)\n )\n return false;\n return stripLogGroupWildcard(desired) === stripLogGroupWildcard(actual);\n}\n","// Copied from cdkd src/analyzer/cc-api-strip.ts (pure, generic, no per-type switch).\n// Strips AWS-managed / generated fields (timestamps, owner info, generated ids)\n// from a CC API GetResource response at any depth before drift comparison.\nconst ALWAYS_STRIPPED = new Set<string>([\n 'CreationDate',\n 'CreationTime',\n 'CreatedTime',\n 'CreatedDate',\n 'CreatedAt',\n 'LastModifiedDate',\n 'LastModifiedTime',\n 'LastModified',\n 'LastUpdatedTime',\n 'LastUpdatedDate',\n 'UpdatedAt',\n 'OwnerId',\n 'OwnerAccountId',\n 'CreatedBy',\n 'OwnerArn',\n 'RevisionId',\n 'LastUpdateStatus',\n 'LastUpdateStatusReason',\n 'LastUpdateStatusReasonCode',\n 'StackId',\n 'PhysicalResourceId',\n 'LogicalResourceId',\n]);\n\n// USER-controlled free-form `Map<String,String>` properties: their KEYS are arbitrary\n// user strings, so an `ALWAYS_STRIPPED` name appearing as a key here is the user's data,\n// NOT an AWS-managed field — stripping it hides a real out-of-band change (a Lambda env\n// var named `LastModified`, a Glue table Parameter named `OwnerId`, a user Tag named\n// `CreatedBy`, …). Inside these maps we do NOT strip by name. (The genuine managed\n// fields AWS adds at the TOP level — a function's own `LastModified`, a resource's\n// `CreationDate` — are not under one of these keys, so they are still stripped; the few\n// nested AWS-managed fields in STRUCTURED objects, e.g. StepFunctions\n// `LoggingConfiguration.CreatedAt`, are also not under these keys, so they still strip.)\nexport const FREE_FORM_MAP_PARENTS = new Set([\n 'Variables', // AWS::Lambda::Function Environment.Variables\n 'Parameters', // AWS::Glue::Table/Database TableInput/DatabaseInput.Parameters\n 'DefaultArguments', // AWS::Glue::Job\n 'DockerLabels', // AWS::ECS::TaskDefinition container definitions\n 'Labels', // generic label maps\n 'Tags', // map-shaped Tags (a user tag keyed like a managed field)\n]);\n\nexport function stripCcApiAwsManagedFields(\n awsProps: Record<string, unknown>\n): Record<string, unknown> {\n return stripWalk(awsProps, false) as Record<string, unknown>;\n}\n\n// `freeForm` = this subtree lives under a free-form USER map (Lambda env Variables, Glue\n// Parameters/DefaultArguments, DockerLabels, Labels, map-Tags) whose keys/values are user\n// data — never name-strip there. Sticky DOWN the subtree (matching the sticky free-form\n// flag in policy-canonical.ts, #182): the prior version recomputed the flag from the\n// immediate parent only, so a NESTED object value under a free-form map lost the\n// protection and a user key colliding with an ALWAYS_STRIPPED name (e.g. `CreatedBy`)\n// would be stripped one level down. No real type nests objects under these parents today,\n// so this is a defensive hardening to keep the two free-form guards consistent.\nfunction stripWalk(value: unknown, freeForm: boolean): unknown {\n if (value === null || value === undefined) return value;\n if (Array.isArray(value)) return value.map((v) => stripWalk(v, freeForm));\n if (typeof value === 'object') {\n const out: Record<string, unknown> = {};\n for (const [k, child] of Object.entries(value as Record<string, unknown>)) {\n if (!freeForm && ALWAYS_STRIPPED.has(k)) continue;\n out[k] = stripWalk(child, freeForm || FREE_FORM_MAP_PARENTS.has(k));\n }\n return out;\n }\n return value;\n}\n\nexport const STRIPPED_FIELDS_FOR_TEST: ReadonlySet<string> = ALWAYS_STRIPPED;\n","// Delete dotted property paths (with '*' wildcard for array elements / any key)\n// from an object IN PLACE. Used to strip schema readOnly/writeOnly paths at any\n// depth, e.g. \"LifecycleConfiguration.Rules.*.Transition\".\nexport function deepStripPaths(obj: Record<string, unknown>, paths: readonly string[]): void {\n for (const p of paths) stripPath(obj, p.split('.'));\n}\n\nfunction stripPath(node: unknown, segs: string[]): void {\n if (node === null || typeof node !== 'object') return;\n const [head, ...rest] = segs;\n if (head === undefined) return;\n const container = node as Record<string, unknown>;\n const keys =\n head === '*'\n ? Array.isArray(node)\n ? node.map((_, i) => String(i))\n : Object.keys(container)\n : [head];\n for (const k of keys) {\n if (rest.length === 0) {\n if (!Array.isArray(node)) delete container[k]; // deleting array elements by index left as no-op (rare for a leaf '*')\n } else {\n stripPath(container[k], rest);\n }\n }\n}\n","// Canonicalize IAM-style policy documents so semantically-equal policies compare\n// equal (cdkd lacks this — it raw-compares and tolerates false drift). Reused\n// across every policy-bearing type (IAM, S3 BucketPolicy, SQS, SNS, KMS, ...).\n//\n// Normalizations: URL-decode + JSON.parse strings; fill default Version;\n// scalar/array unify + sort for Action/Resource/Principal; sort statements.\n\nimport { FREE_FORM_MAP_PARENTS } from './cc-api-strip.js';\n\nfunction isObj(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction isPolicyDoc(v: unknown): v is Record<string, unknown> {\n if (!isObj(v) || !('Statement' in v)) return false;\n // Require `Statement` to actually look like IAM statements — an array of (or a\n // single) object carrying an `Effect` (Allow/Deny) — NOT just any value under a key\n // literally named \"Statement\". Otherwise a user free-form field named `Statement`\n // (a string, number, or arbitrary object) would be force-canonicalized into policy\n // shape: a scalar wrapped into a one-element array, sibling keys reordered, two\n // different values equated (the cc-api-strip free-form-map mangling class). Mirrors\n // isPolicyStatementArray in classify.ts.\n const looksLikeStatement = (el: unknown): boolean => isObj(el) && 'Effect' in el;\n const s = v.Statement;\n return Array.isArray(s) ? s.every(looksLikeStatement) : looksLikeStatement(s);\n}\n\n/** Parse a (possibly URL-encoded) JSON string into a policy doc, or null. */\nfunction parsePolicyString(s: string): Record<string, unknown> | null {\n for (const candidate of [s, safeDecode(s)]) {\n try {\n const parsed = JSON.parse(candidate);\n if (isPolicyDoc(parsed)) return parsed;\n } catch {\n /* not JSON */\n }\n }\n return null;\n}\nfunction safeDecode(s: string): string {\n try {\n return decodeURIComponent(s);\n } catch {\n return s;\n }\n}\n\n// scalar or array → sorted array (stable across single-vs-array CFn forms)\nfunction toSortedArray(v: unknown): unknown {\n const arr = Array.isArray(v) ? [...v] : [v];\n return arr.map((x) => (isObj(x) ? sortKeys(x) : x)).sort(byJson);\n}\nfunction byJson(a: unknown, b: unknown): number {\n const sa = JSON.stringify(a);\n const sb = JSON.stringify(b);\n return sa < sb ? -1 : sa > sb ? 1 : 0;\n}\nfunction sortKeys(o: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const k of Object.keys(o).sort()) out[k] = o[k];\n return out;\n}\n\nconst ARRAYISH_KEYS = new Set(['Action', 'NotAction', 'Resource', 'NotResource']);\n\n// An IAM `Condition` block is `{ <operator>: { <conditionKey>: <scalar|array> } }`.\n// A condition key's value is an UNORDERED SET of strings the operator matches\n// against, written either as a scalar (single value) or an array — IAM treats the\n// two forms identically and may store/return either, in any element order. Without\n// canonicalization a multi-value condition (`aws:SourceArn: [arnA, arnB]`) that AWS\n// echoes reordered, or a single-value condition the template declares as a scalar\n// while AWS stores it as a one-element array, both fire a false declared drift.\n// Mirror the Action/Resource treatment: unify scalar↔array and sort each value set,\n// on both sides, so a reordered-or-reshaped-but-equal condition compares equal while\n// a genuine value change still differs after the sort. Operator/condition-key ORDER\n// needs no sorting — deepEqual is key-order-insensitive.\nfunction canonicalizeCondition(v: unknown): unknown {\n if (!isObj(v)) return v;\n const out: Record<string, unknown> = {};\n for (const op of Object.keys(v)) {\n const body = v[op];\n if (!isObj(body)) {\n out[op] = body;\n continue;\n }\n const inner: Record<string, unknown> = {};\n for (const key of Object.keys(body)) inner[key] = toSortedArray(body[key]);\n out[op] = inner;\n }\n return out;\n}\n\nfunction canonicalizeStatement(s: unknown): unknown {\n if (!isObj(s)) return s;\n const out: Record<string, unknown> = {};\n for (const k of Object.keys(s).sort()) {\n const v = s[k];\n // A statement declared WITHOUT a Sid comes back from AWS (S3 BucketPolicy, SQS/SNS\n // policies, ...) with an auto-assigned sequential numeric string Sid (\"1\", \"2\", …).\n // The declared side has none → the statement's canonical JSON differs → false\n // declared drift on the whole Statement array PLUS a false undeclared `Statement[N].Sid`.\n // Drop a purely-numeric Sid on BOTH sides: it is never author-meaningful (a\n // deliberate label is a non-numeric string, preserved and still compared), and two\n // auto-assigned numeric Sids carry no drift signal. See policy-canonical tests.\n if (k === 'Sid' && typeof v === 'string' && /^\\d+$/.test(v)) continue;\n if (ARRAYISH_KEYS.has(k)) out[k] = toSortedArray(v);\n else if (k === 'Principal' || k === 'NotPrincipal') out[k] = canonicalizePrincipal(v);\n else if (k === 'Condition') out[k] = canonicalizeCondition(v);\n else out[k] = v;\n }\n return out;\n}\n\n// AWS's vended-log-delivery service (`delivery.logs.amazonaws.com`) APPENDS a statement\n// to a destination S3 bucket's policy when log delivery is enabled (CloudFront standard\n// logging v2, VPC flow logs, etc.) — Sid `AWSLogDeliveryWrite`/`AWSLogDeliveryAclCheck`.\n// It is AWS-managed and never in the template, so it fires a false declared drift on the\n// bucket policy's Statement array (an extra live-only statement). Recognized by the\n// `AWSLogDelivery` Sid prefix AND the delivery-logs service principal (both required, so a\n// user statement is never dropped), it is subtracted before compare — same philosophy as\n// stripping AWS-managed fields / aws:* tags. Symmetric: a user who declared the identical\n// statement still compares equal (both sides drop it).\nfunction isAwsManagedLogDeliveryStatement(s: unknown): boolean {\n if (!isObj(s)) return false;\n const sid = s.Sid;\n if (typeof sid !== 'string' || !/^AWSLogDelivery/.test(sid)) return false;\n const principal = s.Principal;\n if (!isObj(principal)) return false;\n const svc = principal.Service;\n const services = Array.isArray(svc) ? svc : [svc];\n return services.includes('delivery.logs.amazonaws.com');\n}\nfunction canonicalizePrincipal(v: unknown): unknown {\n if (isObj(v)) {\n const out: Record<string, unknown> = {};\n for (const k of Object.keys(v).sort()) {\n const arr = (Array.isArray(v[k]) ? v[k] : [v[k]]) as unknown[];\n out[k] = arr.map(normalizeAccountPrincipal).sort(byJson);\n }\n return out;\n }\n return v; // \"*\" or a scalar\n}\n\n// IAM treats a bare account id and its root ARN as equivalent principals.\nfunction normalizeAccountPrincipal(v: unknown): unknown {\n if (typeof v === 'string') {\n const m = /^arn:aws[a-z-]*:iam::(\\d{12}):root$/.exec(v);\n if (m) return m[1];\n }\n return v;\n}\n\nexport function canonicalizePolicy(doc: Record<string, unknown>): Record<string, unknown> {\n const rawStatements = Array.isArray(doc.Statement) ? doc.Statement : [doc.Statement];\n const statements = rawStatements.filter((s) => !isAwsManagedLogDeliveryStatement(s));\n // Preserve ALL top-level keys (only `Statement` is rewritten). A policy document\n // may carry a doc-level `Id` (IAM/S3 policy grammar) or other top-level fields; a\n // prior whitelist of just `Statement`/`Version` DROPPED them, so two policies that\n // differ ONLY in `Id` (or any sibling key) canon-equalled — hiding an out-of-band\n // `Id`/sibling change (a false negative).\n const out: Record<string, unknown> = {\n ...doc,\n Statement: statements.map(canonicalizeStatement).sort(byJson),\n };\n // Keep Version only if present. Filling a default would create a false\n // declared-drift when the template omits Version but AWS stored a literal\n // (e.g. legacy \"2008-10-17\"); under subset comparison an absent declared\n // Version simply isn't compared, which is the correct outcome.\n if (doc.Version === undefined) delete out.Version;\n return out;\n}\n\n// A CloudFront legacy Origin Access Identity (OAI) grant can be written two\n// equivalent ways in a resource policy principal:\n// declared (CDK `grantRead(oai)`): { CanonicalUser: <oai S3CanonicalUserId> }\n// live (S3 GetBucketPolicy / SNS / SQS read-back): AWS normalizes it to\n// { AWS: \"arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity <oaiId>\" }\n// The two carry DIFFERENT tokens — the S3 canonical-user-id hex vs the OAI id —\n// so a string diff fires a false declared drift on the bucket policy. We reconcile\n// them by rewriting the `cloudfront:user` ARN form to the CanonicalUser form, using\n// a resolved `oaiId -> S3CanonicalUserId` map (built in gather.ts from the stack's\n// own OAI resources' live attributes — no extra AWS call). Applied to BOTH sides so\n// either declaration style normalizes to the same canonical token; an empty/missing\n// map is a no-op (the false positive simply remains rather than hiding real drift).\n// An OAI id we cannot resolve is left as-is — never silently equated, so repointing\n// a bucket policy to a DIFFERENT, unknown OAI is still reported.\nconst OAI_USER_ARN_RE =\n /^arn:aws[a-z-]*:iam::cloudfront:user\\/CloudFront Origin Access Identity (.+)$/;\n\nfunction rewriteOaiPrincipal(\n principal: Record<string, unknown>,\n oaiCanonicalIds: Record<string, string>\n): Record<string, unknown> {\n const awsRaw = principal.AWS;\n if (awsRaw === undefined) return principal;\n const awsArr = Array.isArray(awsRaw) ? awsRaw : [awsRaw];\n const remainingAws: unknown[] = [];\n const resolvedCanonical: string[] = [];\n for (const entry of awsArr) {\n const oaiId = typeof entry === 'string' ? OAI_USER_ARN_RE.exec(entry)?.[1] : undefined;\n const canonical = oaiId ? oaiCanonicalIds[oaiId] : undefined;\n if (canonical) resolvedCanonical.push(canonical);\n else remainingAws.push(entry);\n }\n if (resolvedCanonical.length === 0) return principal; // nothing matched/resolved\n const out: Record<string, unknown> = { ...principal };\n if (remainingAws.length === 0) delete out.AWS;\n else out.AWS = remainingAws.length === 1 ? remainingAws[0] : remainingAws;\n const existing =\n out.CanonicalUser === undefined\n ? []\n : Array.isArray(out.CanonicalUser)\n ? out.CanonicalUser\n : [out.CanonicalUser];\n const merged = [...existing, ...resolvedCanonical];\n out.CanonicalUser = merged.length === 1 ? merged[0] : merged;\n return out;\n}\n\n/** Walk a value, rewriting every policy-statement `Principal`/`NotPrincipal` that\n * grants a CloudFront OAI via its `cloudfront:user` ARN into the equivalent\n * `CanonicalUser` form (see `rewriteOaiPrincipal`). No-op when the map is empty. */\nexport function rewriteOaiPrincipalsDeep(\n v: unknown,\n oaiCanonicalIds: Record<string, string>\n): unknown {\n if (oaiCanonicalIds === undefined || Object.keys(oaiCanonicalIds).length === 0) return v;\n if (Array.isArray(v)) return v.map((x) => rewriteOaiPrincipalsDeep(x, oaiCanonicalIds));\n if (isObj(v)) {\n const out: Record<string, unknown> = {};\n for (const [k, val] of Object.entries(v)) {\n if ((k === 'Principal' || k === 'NotPrincipal') && isObj(val)) {\n out[k] = rewriteOaiPrincipal(val, oaiCanonicalIds);\n } else {\n out[k] = rewriteOaiPrincipalsDeep(val, oaiCanonicalIds);\n }\n }\n return out;\n }\n return v;\n}\n\n// Canonicalize an embedded JSON string (e.g. ECR LifecyclePolicyText) so that\n// pretty-printed vs minified vs key-reordered forms compare equal.\nfunction canonicalizeJsonText(s: string): string {\n try {\n const parsed = JSON.parse(s);\n if (parsed && typeof parsed === 'object') return JSON.stringify(sortDeep(parsed));\n } catch {\n /* not JSON */\n }\n return s;\n}\nfunction sortDeep(v: unknown): unknown {\n if (Array.isArray(v)) return v.map(sortDeep);\n if (v && typeof v === 'object') {\n const out: Record<string, unknown> = {};\n for (const k of Object.keys(v as Record<string, unknown>).sort())\n out[k] = sortDeep((v as Record<string, unknown>)[k]);\n return out;\n }\n return v;\n}\n\n/**\n * Walk a value, replacing policy-document subtrees with their canonical form and\n * embedded JSON-text strings with a canonical (sorted, minified) form.\n */\nexport function normalizePoliciesDeep(v: unknown): unknown {\n return normWalk(v, false);\n}\n\n// `freeForm` = this subtree lives under a free-form USER map (Lambda env Variables,\n// Glue Parameters/DefaultArguments, DockerLabels, Labels, map-Tags). Those values are\n// opaque user data AWS stores VERBATIM (Map<String,String>), so re-serializing /\n// policy-canonicalizing a JSON-shaped value there would SUPPRESS a real out-of-band\n// key-order / statement edit by the user (a false negative) — the same R69 protection\n// cc-api-strip applies, extended to the policy/json-text canonicalizers that run after\n// it. Sticky down the subtree (everything under a user map is user data).\nfunction normWalk(v: unknown, freeForm: boolean): unknown {\n if (typeof v === 'string') {\n if (freeForm) return v; // opaque user data — never canonicalize\n const p = parsePolicyString(v);\n if (p) return canonicalizePolicy(p);\n return canonicalizeJsonText(v);\n }\n if (Array.isArray(v)) return v.map((el) => normWalk(el, freeForm));\n if (!freeForm && isPolicyDoc(v)) return canonicalizePolicy(v);\n if (isObj(v)) {\n const out: Record<string, unknown> = {};\n for (const [k, val] of Object.entries(v))\n out[k] = normWalk(val, freeForm || FREE_FORM_MAP_PARENTS.has(k));\n return out;\n }\n return v;\n}\n","// The shared value-canonicalization pipeline, used by BOTH the live/declared\n// comparison in classify.ts AND the baseline-value comparison in baseline-file.ts.\n// Keeping it in one place means a baseline recorded under an OLDER set of\n// canonicalization rules still compares equal to the same live value under the\n// CURRENT rules — so adding a normalizer (we have added four already) never makes a\n// cdkrd version bump alone produce false drift on existing baselines.\n//\n// Order matches classify.ts's live side exactly: policy canonicalization first\n// (Version / scalar-vs-array / statement order / account-id<->root-ARN), then tag\n// lists (unordered set -> sorted by Key), then AWS-id arrays (unordered set ->\n// sorted). It does NOT strip AWS-managed fields / aws:* tags / schema paths — those\n// are live-only concerns the caller applies before this.\nimport {\n canonicalizeIdArraysDeep,\n canonicalizeTagListsDeep,\n normalizeWafByteMatchDeep,\n ORDER_SIGNIFICANT_ARRAY_KEYS,\n} from './noise.js';\nimport { normalizePoliciesDeep } from './policy-canonical.js';\n\n// `resourceType` is optional: when given, identity-keyed object arrays the type marks\n// as ORDER-significant (ORDER_SIGNIFICANT_ARRAY_KEYS — e.g. CodePipeline Stages/Actions)\n// are NOT sorted, so both compare sides keep declared order and a finding's array index\n// stays aligned with the raw live model the revert patches. classify passes the type\n// for BOTH its live and declared sides; the type-less callers (baseline/writers) operate\n// on undeclared snapshot values, which never carry an order-significant declared array.\nexport function canonicalizeForCompare(v: unknown, resourceType?: string): unknown {\n const orderSig = resourceType ? ORDER_SIGNIFICANT_ARRAY_KEYS[resourceType] : undefined;\n const base = canonicalizeIdArraysDeep(\n canonicalizeTagListsDeep(normalizePoliciesDeep(v), orderSig)\n );\n // A WAFv2 WebACL's ByteMatchStatement search patterns read back base64-encoded; fold both\n // sides to the plain SearchString the template declares so a clean rule is not false drift.\n return resourceType === 'AWS::WAFv2::WebACL' ? normalizeWafByteMatchDeep(base) : base;\n}\n","// Copied from cdkd src/analyzer/drift-calculator.ts (pure function, no deps).\n// Walks keys present in `stateProperties` (the desired side) and reports where\n// `awsProperties` (actual) differs. Nested objects recurse with dotted paths;\n// arrays compare element-wise as a single parent-path drift.\nexport interface PropertyDrift {\n path: string;\n stateValue: unknown;\n awsValue: unknown;\n}\n\nexport function calculateResourceDrift(\n stateProperties: Record<string, unknown>,\n awsProperties: Record<string, unknown>,\n options?: { ignorePaths?: readonly string[] }\n): PropertyDrift[] {\n const drifts: PropertyDrift[] = [];\n const ignore = options?.ignorePaths ?? [];\n for (const key of Object.keys(stateProperties)) {\n if (isIgnoredPath(key, ignore)) continue;\n diffAt(key, stateProperties[key], awsProperties[key], drifts, ignore);\n }\n return drifts;\n}\n\nfunction isIgnoredPath(path: string, ignorePaths: readonly string[]): boolean {\n for (const entry of ignorePaths) {\n if (path === entry || path.startsWith(`${entry}.`)) return true;\n }\n return false;\n}\n\nfunction diffAt(\n path: string,\n sv: unknown,\n av: unknown,\n out: PropertyDrift[],\n ignorePaths: readonly string[]\n): void {\n if (deepEqual(sv, av)) return;\n if (isPlainObject(sv) && isPlainObject(av) && !Array.isArray(sv) && !Array.isArray(av)) {\n // A free-form map (DockerLabels, Tags, Glue Parameters, …) can hold USER keys that\n // contain the path grammar's separators — a Docker label `com.example.x`, a tag key\n // with a `.`, a key with `[`/`]`. Descending would build a child path like\n // `DockerLabels.com.example.x` that every downstream consumer (toPointer for the\n // revert JSON-pointer, the baseline `topSegment`, the ignore-rule glob) RE-SPLITS on\n // `.`/`[`, landing on the WRONG location — a misdirected revert write and a silently\n // ineffective ignore/baseline rule. When any key would corrupt the path, don't\n // descend: emit the whole map at the current (safe) path. The revert then rewrites\n // the map as a unit (correct) and the finding path carries no ambiguous segment.\n if (hasPathUnsafeKey(sv) || hasPathUnsafeKey(av)) {\n out.push({ path, stateValue: sv, awsValue: av });\n return;\n }\n // Mutually-exclusive / wholesale object swap: when the desired and live objects\n // share NO keys, the subset descent below (which walks only desired keys) would\n // emit the desired-only keys to ADD but never the live-only keys to REMOVE — so a\n // revert leaves BOTH and AWS rejects it (e.g. WAFv2 DefaultAction `{Allow:{}}` vs\n // live `{Block:{}}` → \"exactly one value\" for a one-of field; the live `Block` is\n // an empty `{}` so collectNestedUndeclared also suppresses it as trivial-empty,\n // leaving it entirely unreverted). Emit the WHOLE object at the parent path so the\n // revert REPLACES it wholesale. Gated on fully-disjoint keys, so every overlapping-\n // key case (the common partial-object drift) keeps the subset semantics unchanged.\n const svKeys = Object.keys(sv);\n if (svKeys.length > 0 && Object.keys(av).length > 0 && !svKeys.some((k) => k in av)) {\n out.push({ path, stateValue: sv, awsValue: av });\n return;\n }\n // Subset semantics: only walk keys present in the desired (state) side, so an\n // AWS-added nested key the template never set is not a DECLARED-side change here.\n // (R96: such live-only nested keys are instead caught by classify's\n // `collectNestedUndeclared` as nested UNDECLARED findings — folded, baseline-able.)\n for (const key of Object.keys(sv)) {\n const childPath = `${path}.${key}`;\n if (isIgnoredPath(childPath, ignorePaths)) continue;\n diffAt(childPath, sv[key], (av as Record<string, unknown>)[key], out, ignorePaths);\n }\n return;\n }\n // Same-length arrays of objects: compare element-wise with the same subset\n // semantics, so AWS enriching a declared array element with extra sub-fields\n // (e.g. S3 BucketEncryption.BucketKeyEnabled) is not false drift. A length\n // change is a genuine drift and falls through to the push below.\n if (\n Array.isArray(sv) &&\n Array.isArray(av) &&\n sv.length === av.length &&\n sv.every(isPlainObject) &&\n av.every(isPlainObject)\n ) {\n for (let i = 0; i < sv.length; i++) diffAt(`${path}.${i}`, sv[i], av[i], out, ignorePaths);\n return;\n }\n out.push({ path, stateValue: sv, awsValue: av });\n}\n\nexport function deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a === null || b === null || a === undefined || b === undefined) return a === b;\n if (typeof a !== typeof b) return false;\n if (typeof a !== 'object') return false;\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n return a.every((v, i) => deepEqual(v, b[i]));\n }\n const ao = a as Record<string, unknown>;\n const bo = b as Record<string, unknown>;\n const ak = Object.keys(ao);\n const bk = Object.keys(bo);\n if (ak.length !== bk.length) return false;\n for (const key of ak) {\n if (!Object.hasOwn(bo, key)) return false;\n if (!deepEqual(ao[key], bo[key])) return false;\n }\n return true;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n// A key that contains the path grammar's separators (`.`, `[`, `]`). Descending into\n// such a key would produce a finding path that downstream consumers re-split into the\n// wrong location — so an object holding one is emitted whole at its parent path.\nconst PATH_UNSAFE_KEY = /[.[\\]]/;\nfunction hasPathUnsafeKey(o: Record<string, unknown>): boolean {\n return Object.keys(o).some((k) => PATH_UNSAFE_KEY.test(k));\n}\n","// The heart of `check`: given a resource's resolved declared properties, its raw\n// live state, and its schema info, classify every difference into a tier:\n// declared — a declared property whose live value differs\n// undeclared — a live property not declared, after noise subtraction (the differentiator)\n// readGap — a declared property absent from the live read (CC-API can't read it back)\n// unresolved — a declared property whose intrinsics couldn't be resolved (GetAtt) → skip\n//\n// Pure: no AWS calls. liveRaw is the CC API GetResource model (un-stripped).\n\nimport {\n isArnNameMatch,\n isLogGroupArnWildcardMatch,\n isManagedKmsAliasMatch,\n} from '../normalize/arn-identity.js';\nimport { stripCcApiAwsManagedFields } from '../normalize/cc-api-strip.js';\nimport { hasUnresolved, UNRESOLVED } from '../normalize/intrinsic-resolver.js';\nimport {\n CASE_INSENSITIVE_ARRAY_PATHS,\n CASE_INSENSITIVE_KEY_PATHS,\n CASE_INSENSITIVE_PATHS,\n isAllAwsTags,\n identityField,\n isCaseInsensitiveEqualScalarSet,\n isCaseInsensitiveKeyMapEqual,\n isCaseInsensitiveScalarEqual,\n BOOLEAN_PARAM_MAP_PATHS,\n isBooleanTokenEquivalent,\n isCfnTemplateNonAsciiMask,\n isEqualUnorderedScalarSet,\n isEquivalentRateExpression,\n isJsonStringStructEqual,\n JSON_STRING_PROPS,\n JSON_STRING_DEFAULT_FILLS,\n isPemEqual,\n isAccessStringEqual,\n isPropertiesFileEqual,\n isSshPublicKeyEqual,\n ACCESS_STRING_PATHS,\n PROPERTIES_FILE_PATHS,\n SSH_PUBLIC_KEY_PATHS,\n isStringlyEqualScalar,\n isStringlyEqualScalarArray,\n isStringlyEqualDeep,\n isGeneratedName,\n isPhysicalIdSegment,\n isTrailingDotEqual,\n isTrailingSlashEqual,\n isTrivialEmpty,\n isVersionPrefixMatch,\n isLatestSentinelMatch,\n isIntelligentTieringMatch,\n INTELLIGENT_TIERING_PATHS,\n LATEST_SENTINEL_PATHS,\n TRAILING_DOT_PATHS,\n TRAILING_SLASH_PATHS,\n GENERATED_PATHS,\n CONTEXT_DEFAULTS,\n DEFAULT_MANAGED_NAME_PATHS,\n DESCEND_UNDECLARED_OBJECT_PATHS,\n ENGINE_DEFAULTS,\n GENERATED_LOGICALID_PREFIX_PATHS,\n GENERATED_NESTED_PATHS,\n GENERATED_TOPLEVEL_PATHS,\n isLogicalIdPrefixedGeneratedName,\n EPOCH_HOUR_PATHS,\n IDENTITY_KEYED_DEFAULT_ELEMENTS,\n isEpochHourEqual,\n KNOWN_DEFAULT_PATHS,\n KNOWN_DEFAULTS,\n ORDER_SIGNIFICANT_ARRAY_KEYS,\n READGAP_COLLECTION_PATHS,\n SCALAR_RETURNED_WHEN_SET,\n READ_NORMALIZED_DECLARED_PATHS,\n ELB_ATTRIBUTE_DEFAULTS,\n ELB_ATTRIBUTE_DEFAULTS_BY_LB_TYPE,\n NAME_VALUE_SUBSET_PATHS,\n alignNameValueSubset,\n RATE_EXPRESSION_PATHS,\n resolveGeneratedDefault,\n sortNestedObjectArrays,\n sortUnorderedObjectArray,\n stripAsymmetricIdentityFields,\n stripAwsTagsDeep,\n UNORDERED_ARRAY_PROPS,\n UNORDERED_NESTED_OBJECT_ARRAY_PATHS,\n UNORDERED_OBJECT_ARRAY_PROPS,\n VALUE_INDEPENDENT_DEFAULT_TOPLEVEL_PATHS,\n VERSION_PREFIX_PATHS,\n} from '../normalize/noise.js';\nimport { deepStripPaths } from '../normalize/path-strip.js';\nimport { canonicalizeForCompare } from '../normalize/pipeline.js';\nimport { rewriteOaiPrincipalsDeep } from '../normalize/policy-canonical.js';\nimport type { DesiredResource, Finding, SchemaInfo } from '../types.js';\nimport { calculateResourceDrift, deepEqual } from './drift-calculator.js';\n\n// R78: identity-keyed attribute bags whose declared drift must be reverted BY KEY\n// (the index-based Cloud Control patch misaligns against the full live bag and ELB\n// caps a modify at 20 attributes). Maps the resource type to its bag property; a\n// drift inside the bag emits one declared finding per changed Key (path stays at\n// the bag property, the Key rides on Finding.attributeKey for the SDK writer).\nconst ELB_ATTRIBUTE_BAGS: Record<string, string> = {\n 'AWS::ElasticLoadBalancingV2::LoadBalancer': 'LoadBalancerAttributes',\n 'AWS::ElasticLoadBalancingV2::TargetGroup': 'TargetGroupAttributes',\n 'AWS::ElasticLoadBalancingV2::Listener': 'ListenerAttributes',\n};\n\n// Identity-keyed object arrays where the template declares only a SUBSET of the elements\n// AWS always returns — keyed by the property -> the element's identity field. Cognito\n// UserPool `Schema` is the case: AWS returns all ~21 standard attributes (sub, email,\n// phone_number, …) plus any custom ones, every time, regardless of what the template\n// declares. Comparing the declared subset positionally against the full live array is a\n// length-mismatch whole-array FALSE positive on the first check of any pool that sets\n// `standardAttributes`/`customAttributes` (extremely common). The declared loop aligns\n// the declared elements to live BY this identity, compares them element-wise, and emits\n// the live-only elements as nested undeclared inventory (foldable, recordable) — so a\n// genuine out-of-band CUSTOM attribute addition still surfaces, but the standard-attribute\n// baseline no longer false-drifts. (Distinct from ELB bags, which are {Key,Value} and\n// revert by Key; these are rich objects compared by subset.)\ninterface SubsetArraySpec {\n idField: string;\n // normalize the identity before matching: Cognito stores a custom attribute the\n // template declares as `tier` under the live Name `custom:tier` (and a developer-only\n // one as `dev:tier`), so an exact-Name match would treat the declared attribute as\n // removed (a false declared drift). Strip those AWS-added prefixes on both sides.\n normalizeId?: (id: string) => string;\n}\nconst stripCognitoAttrPrefix = (id: string): string => id.replace(/^(custom|dev):/, '');\nconst IDENTITY_KEYED_SUBSET_ARRAYS: Record<string, Record<string, SubsetArraySpec>> = {\n 'AWS::Cognito::UserPool': { Schema: { idField: 'Name', normalizeId: stripCognitoAttrPrefix } },\n // An EC2 Instance's BlockDeviceMappings is a SET keyed by DeviceName, and the live\n // model is a SUPERSET of the template's in two ways: (1) the API enriches each declared\n // mapping's `Ebs` block with defaults the template never set (SnapshotId, the encrypting\n // KmsKeyId, the resolved Iops/Throughput); (2) a volume ATTACHED out of band — or via a\n // sibling AWS::EC2::VolumeAttachment — appears as an EXTRA mapping (e.g. `/dev/sdf`) the\n // Instance template never declared. A positional/whole-array compare then false-flags the\n // entire BlockDeviceMappings as declared drift on every fresh deploy. Aligning declared\n // mappings to live BY DeviceName lets each declared mapping subset-compare against its live\n // twin (the enriched Ebs keys are an undeclared superset, not a declared change) and emits\n // each live-only mapping as nested undeclared inventory. A genuinely removed declared\n // mapping (no live DeviceName match) still surfaces as declared drift. Observed live on a\n // fresh ec2-instance-rich deploy (a gp3 root volume + an attached data volume).\n // An EC2 Instance's `Volumes` (EBS volumes ATTACHED at launch, each {Device, VolumeId})\n // is the same superset shape as BlockDeviceMappings: the live model adds the AMI's ROOT\n // volume (e.g. `/dev/xvda`) — which the template never declares as an attachment — as an\n // EXTRA element, and AWS may interleave it among the declared attachments. A positional/\n // whole-array compare then false-flags the entire `Volumes` as declared drift on every\n // fresh deploy of an instance that attaches volumes. Aligning declared volumes to live BY\n // Device lets each declared attachment subset-compare against its live twin and emits the\n // live-only root volume as nested undeclared inventory (recordable). A genuinely detached\n // declared volume (no live Device match) still surfaces as declared drift. Observed live\n // on a fresh ec2-instance-sets deploy (two attached gp3 volumes + the AMI root). (The\n // sibling `NetworkInterfaces` set was tested in the SAME deploy declared non-sorted by\n // DeviceIndex and AWS PRESERVED its order — subset-clean, so it is NOT folded.)\n 'AWS::EC2::Instance': {\n BlockDeviceMappings: { idField: 'DeviceName' },\n Volumes: { idField: 'Device' },\n },\n // A Cognito UserPoolUser's UserAttributes is a SET keyed by Name where the live model\n // is a SUPERSET of the template's: AWS ALWAYS injects the server-generated immutable\n // `sub` (the user id), plus `email_verified`/`phone_number_verified` once those\n // attributes exist — none of which the template declares. A positional/whole-array\n // compare then false-flags the entire UserAttributes as declared drift on every fresh\n // deploy of a user that declares any attribute (e.g. just `email`). Aligning declared\n // attributes to live BY Name lets each declared attribute subset-compare against its\n // live twin and emits the live-only attributes (sub, *_verified) as nested undeclared\n // inventory (foldable, recordable). A genuinely changed declared attribute (e.g. a new\n // email) still surfaces. Exposed once UserPoolUser became CC-readable (router.ts adapter\n // above); observed live on a fresh cognito-userpooluser-rich deploy (sub injected).\n 'AWS::Cognito::UserPoolUser': { UserAttributes: { idField: 'Name' } },\n // A Route53Resolver ResolverEndpoint's `IpAddresses` is a SET keyed by SubnetId where\n // the template declares only `{SubnetId}` (letting AWS assign the IP) but the live model\n // is a SUPERSET: AWS fills in the assigned `Ip` (+ `IpId`/`Status`) per entry AND returns\n // the entries in a NON-deterministic order. A positional compare then false-flags each\n // shifted entry's `SubnetId` as declared drift on a freshly recorded endpoint — and the\n // resulting phantom revert FAILS (writing the SubnetId-only entry back makes AWS re-pick\n // an IP → `[RSLVR-00405] … not in subnet CIDR range or is reserved`). SubnetId is NOT one\n // of the global IDENTITY_FIELDS, so only this per-type key aligns it. Aligning declared\n // entries to live BY SubnetId neutralizes the reorder and subset-compares each declared\n // `{SubnetId}` against its live twin (the assigned Ip/IpId are undeclared inventory,\n // foldable/recordable); a genuinely changed subnet still surfaces. Assumes one IP per\n // subnet (the hybrid-DNS norm — one endpoint IP per AZ); multiple IPs in one subnet would\n // collapse on the key, an accepted edge case. Surfaced by the issue #467 --wait live-test.\n 'AWS::Route53Resolver::ResolverEndpoint': { IpAddresses: { idField: 'SubnetId' } },\n};\n// Nested object-arrays whose element identity is a NON-standard field (not Key/Id/\n// AttributeName/IndexName/Name). collectNestedUndeclared aligns identity-keyed arrays so a\n// live-only sub-key inside a declared element surfaces; without a known identity it skips\n// the array entirely (reorder-unsafe to descend by position) — silently HIDING such a\n// sub-key. Keyed by resourceType -> nested array path (brackets stripped) -> identity field.\n// - AWS::ApiGateway::Method Integration.IntegrationResponses is keyed by StatusCode, so an\n// out-of-band SelectionPattern / ContentHandling added to a declared response (the\n// \"HTTP error regex\" / \"content handling\" console knobs) is otherwise invisible.\nexport const NESTED_ARRAY_IDENTITY: Record<string, Record<string, string>> = {\n 'AWS::ApiGateway::Method': {\n 'Integration.IntegrationResponses': 'StatusCode',\n // MethodResponses is keyed by StatusCode too. AWS does NOT auto-materialize its\n // ResponseModels (a CFn-created method response declaring none reads back null —\n // proven live), so an out-of-band `responseModels` (e.g. the built-in \"Error\" model\n // attached in the console) surfaces as a genuine undeclared value, no FP.\n MethodResponses: 'StatusCode',\n },\n // A Backup plan's rules are keyed by RuleName. AWS MATERIALIZES defaults into each live\n // rule (CompletionWindowMinutes / StartWindowMinutes / ScheduleExpressionTimezone, plus\n // empty CopyActions/ScanActions/IndexActions/RecoveryPointTags) — folded via\n // KNOWN_DEFAULT_PATHS + isTrivialEmpty — so a clean plan stays clean, but an out-of-band\n // change to a compliance-relevant rule setting (e.g. a shortened CompletionWindowMinutes)\n // surfaces. Proven live.\n 'AWS::Backup::BackupPlan': { 'BackupPlan.BackupPlanRule': 'RuleName' },\n // A Route53 Resolver DNS-firewall rule group's rules are keyed by Priority. AWS\n // materializes defaults into each live rule (FirewallThreatProtectionId NOT_APPLICABLE,\n // FirewallDomainRedirectionAction INSPECT_REDIRECTION_DOMAIN) — folded via\n // KNOWN_DEFAULT_PATHS — so a security-relevant out-of-band change (a rule's Action /\n // BlockResponse flipped in the console) surfaces. Proven live.\n 'AWS::Route53Resolver::FirewallRuleGroup': { FirewallRules: 'Priority' },\n // A multi-region secret's replicas are keyed by Region. AWS materializes the default\n // AWS-managed KMS key (KmsKeyId `alias/aws/secretsmanager`) into each declared replica\n // that did not pin one — folded via KNOWN_DEFAULT_PATHS — so a replica re-keyed to a\n // different CMK out of band (a compliance-relevant change) surfaces. Proven live.\n 'AWS::SecretsManager::Secret': { ReplicaRegions: 'Region' },\n // A REST API stage's per-method settings are keyed by HttpMethod (the dominant CDK shape\n // is a single `*` deployment-wide default). AWS materializes the caching scalar default\n // into each declared method setting (CacheTtlInSeconds 300 — folded via\n // KNOWN_DEFAULT_PATHS; the sibling `false` defaults fold via isTrivialEmpty) — so an\n // out-of-band caching change on a declared method surfaces. Proven live.\n 'AWS::ApiGateway::Stage': { MethodSettings: 'HttpMethod' },\n};\n\n// Child resources whose live model ECHOES their parent's cluster-level configuration. An\n// Aurora DBInstance reports the DBCluster's encryption / engine version / backup / security\n// groups / subnet group / master user / log exports — settings the CDK `ClusterInstance`\n// never declares on the instance, so they flood a first run as undeclared inventory that\n// merely mirrors the cluster (which cdkrd classifies independently). classify drops an\n// UNDECLARED instance property whose value EQUALS the parent cluster's value for the same\n// key; `aliases` maps the few keys the two APIs spell differently. The parent's own property\n// still carries detection, so no out-of-band change is hidden — and an instance value that\n// DIVERGES from the cluster (its own maintenance window, its single AZ) still surfaces.\nconst CLUSTER_ECHO_CHILD: Record<string, { parentIdKey: string; aliases: Record<string, string> }> =\n {\n 'AWS::RDS::DBInstance': {\n parentIdKey: 'DBClusterIdentifier',\n // The two APIs spell a few shared settings differently: an instance's VPCSecurityGroups\n // is the cluster's VpcSecurityGroupIds; its EnablePerformanceInsights is the cluster's\n // PerformanceInsightsEnabled (Aurora manages PI cluster-wide, so the instance mirrors it).\n aliases: {\n VPCSecurityGroups: 'VpcSecurityGroupIds',\n EnablePerformanceInsights: 'PerformanceInsightsEnabled',\n },\n },\n };\n\nconst isKeyValueEntry = (t: unknown): t is { Key: string; Value: unknown } =>\n !!t &&\n typeof t === 'object' &&\n typeof (t as { Key?: unknown }).Key === 'string' &&\n 'Value' in (t as object);\n\n// Parent resources whose live model REFLECTS their separately-managed child resources\n// as an inline aggregate property (e.g. an SNS Topic's `Subscription` list mirrors every\n// AWS::SNS::Subscription pointing at it, including ones created out of band). cdkrd\n// already tracks those children independently — declared ones as their own resources,\n// out-of-band ones via the `added` enumerator (read/child-enumerators.ts) — so comparing\n// the reflection too would DOUBLE-REPORT one subscription as both a `Topic.Subscription`\n// undeclared drift AND an `added` Subscription resource. Drop the live reflection so the\n// child is reported ONCE (as the resource). Only when the template does NOT declare the\n// property inline: a stack that genuinely uses inline subscriptions keeps the compare\n// (fail-open — never hide a declared value). Same idea as the sibling-IAM-policy drop.\nconst REFLECTED_CHILD_PROPS: Record<string, string> = {\n 'AWS::SNS::Topic': 'Subscription',\n};\n\n// IAM principal types whose inline live `Policies` can be sibling-managed by a separate\n// AWS::IAM::Policy resource (the CDK `<Principal>DefaultPolicy` pattern). Used for the\n// revert-hazard guard when the sibling PolicyName was UNRESOLVED (see below).\nconst IAM_PRINCIPAL_POLICY_TYPES: ReadonlySet<string> = new Set([\n 'AWS::IAM::Role',\n 'AWS::IAM::User',\n 'AWS::IAM::Group',\n]);\n\n// AWS::EC2::SecurityGroup reflects, in its live SecurityGroupIngress / SecurityGroupEgress\n// arrays, the rules declared by SIBLING standalone AWS::EC2::SecurityGroupIngress /\n// ::SecurityGroupEgress resources that target it. CDK emits such a standalone rule resource\n// whenever a rule references a token it cannot safely inline — a self/peer SG reference, a\n// prefix list, an imported SG (`addIngressRule(otherSg, …)`, `Peer.prefixList(…)`, self-ref).\n// Those sibling rules are tracked + compared as their OWN resources, so leaving them in the\n// SG's live arrays double-counts them: the SG's DECLARED arrays hold only the INLINE rules, so\n// every sibling-reflected live rule reads as a false declared drift (a very common shape — a\n// self-referencing SG rule is the canonical ALB↔ASG / intra-cluster pattern). The fix mirrors\n// REFLECTED_CHILD_PROPS, but a SUBSET not the whole property: subtract each sibling-declared\n// rule from the live array, leaving the inline-declared rules (and any out-of-band rule, which\n// matches no sibling) to compare normally.\nconst SG_RULE_REFLECTION: Record<string, 'ingress' | 'egress'> = {\n SecurityGroupIngress: 'ingress',\n SecurityGroupEgress: 'egress',\n};\n\n// Match one sibling-declared rule field against the live element's value. The exact\n// deepEqual match is tried first (preserves every existing case), then two tolerances:\n// - typed<->string scalar coercion: a rule port declared as `Fn::GetAtt <Cluster>.\n// Endpoint.Port` resolves to the STRING \"3306\" (the DBCluster's live Endpoint.Port is\n// a string), while the SG's reflected live rule carries the NUMBER 3306, so a strict\n// deepEqual false-flags the whole declared ingress rule as undeclared drift on every\n// CDK Aurora stack (`cluster.connections.allowFrom(...)` is the canonical shape).\n// - UNRESOLVED wildcard: a declared field the intrinsic resolver could not evaluate is\n// unknowable, so it must not BLOCK the match — the CidrIp/protocol/description identity\n// still gates the subtraction. Consistent with the rest of the pipeline, which SKIPS an\n// unresolved declared value rather than false-drifting on it.\nfunction siblingRuleFieldMatches(liveVal: unknown, sibVal: unknown): boolean {\n if (sibVal === UNRESOLVED) return true;\n return deepEqual(liveVal, sibVal) || isStringlyEqualScalar(liveVal, sibVal);\n}\n\n// Remove from `arr` the first element each sibling rule is a SUBSET of (every sibling key\n// matches the live element's — the live element carries AWS-injected extras the sibling\n// resource never declared, e.g. SourceSecurityGroupOwnerId on a self/peer-ref rule, so an\n// exact equality compare would miss the match). One removal per sibling rule preserves a\n// duplicate inline rule that legitimately repeats the shape.\nfunction subtractSiblingSgRules(\n live: Record<string, unknown>,\n prop: string,\n siblingRules: unknown[]\n): void {\n const arr = live[prop];\n if (!Array.isArray(arr) || siblingRules.length === 0) return;\n for (const rule of siblingRules) {\n if (!rule || typeof rule !== 'object') continue;\n const sub = rule as Record<string, unknown>;\n const i = arr.findIndex(\n (el) =>\n el !== null &&\n typeof el === 'object' &&\n Object.entries(sub).every(([k, v]) =>\n siblingRuleFieldMatches((el as Record<string, unknown>)[k], v)\n )\n );\n if (i >= 0) arr.splice(i, 1);\n }\n if (arr.length === 0) delete live[prop]; // empty array == absent; don't introduce a []-vs-absent FP\n}\n\n// Cloud Control returns an ALTERNATIVE representation of a declared value as a separate\n// live-only field. Keyed resourceType -> { liveOnlyField: declaredSiblingField }: drop the\n// live-only field when its declared sibling is present (the template already pins the value\n// in the other form). AWS::EC2::Subnet is the case — declaring `AvailabilityZone`\n// (\"ap-northeast-1a\") makes CC also echo the resolved `AvailabilityZoneId` (\"apne1-az4\"), a\n// different form of the SAME AZ, on EVERY subnet. Symmetric, so declaring either form drops\n// the other.\nconst CC_ALT_REPRESENTATION: Record<string, Record<string, string>> = {\n 'AWS::EC2::Subnet': {\n AvailabilityZoneId: 'AvailabilityZone',\n AvailabilityZone: 'AvailabilityZoneId',\n },\n // An ALB reads back `SubnetMappings` (`[{SubnetId}]`) — the object-array echo of the\n // declared scalar `Subnets` list. Drop it when `Subnets` is declared so it is not\n // reported as a live-only property (the subnets ARE compared via `Subnets`).\n 'AWS::ElasticLoadBalancingV2::LoadBalancer': { SubnetMappings: 'Subnets' },\n};\n\n// Per-type attachment-list properties handled by tier rather than a positional compare.\n// AWS::IAM::ManagedPolicy's `Roles`/`Users`/`Groups` name the principals a managed\n// policy is attached to — but the same policy is commonly attached from SEVERAL places\n// (a role's own `ManagedPolicyArns`, a separate AWS::IAM::Policy/attachment resource,\n// another stack, the console), so the LIVE set is a UNION that legitimately exceeds any\n// one stack's intent. A symmetric compare would false-DRIFT on every shared policy (the\n// FP `cdk drift` raises). So each member is tiered by WHO declared it:\n// - a DECLARED member MISSING from live -> declared drift (an out-of-band DETACH —\n// security-relevant: a privilege the stack intends was removed). Revertable\n// (re-attach the one member). The real FN the old \"don't compare attachment lists\"\n// boundary missed.\n// - a live member NOT declared -> UNDECLARED inventory (recordable), NOT a\n// positional FP — the SAME treatment every other undeclared property + identity-\n// keyed subset array (ELB attribute bags, Cognito Schema) gets. So a known union\n// member is folded/recordable on a first run, and a NEW unexpected attachment\n// (a console/rogue grant of the policy's permissions to another principal) then\n// surfaces as drift vs the recorded baseline — detection cdk drift only matches by\n// ALSO false-drifting every legitimate union member. record-only (we never auto-\n// detach a member another owner added; --remove-unrecorded is the explicit opt-in).\n// Catches BOTH a removed declared attachment and an added unexpected one, without the\n// symmetric-compare false drift.\nconst IAM_ATTACHMENT_SUBSET: Record<string, ReadonlySet<string>> = {\n 'AWS::IAM::ManagedPolicy': new Set(['Roles', 'Users', 'Groups']),\n};\n\n// #493: identity-keyed object-array SUBSET folds where the identity is a COMPOSITE of\n// several fields AND live entries carry extra service-injected fields the template never\n// declares. This is a stricter cousin of noise.ts NAME_VALUE_SUBSET_PATHS (RDS OptionGroup\n// #480/#485) — that helper folds only PURE `{name,value}` pairs keyed by a single field, so\n// it disqualifies (returns null) the moment an element carries any other key. Elastic\n// Beanstalk's ConfigurationTemplate `OptionSettings` needs the composite variant:\n// - the template declares a SUBSET (~3 entries); once the composite-identifier adapter\n// (router.ts) makes the template CC-readable, CC returns the FULLY RESOLVED set (~58\n// entries) the service default-fills — a whole-array `declared` FP on every fresh deploy;\n// - each entry's identity is `Namespace` + `OptionName` together (neither alone is unique);\n// - live entries carry an extra `ResourceName` field the template never declares, which is\n// STRIPPED before the value compare (it is not part of the declared intent).\n// When every declared entry is present in live with an equal value (declared ⊆ live), the\n// whole-array `declared` diff is suppressed and the live-only (service-filled) entries surface\n// as nested undeclared inventory (recorded; a later change still surfaces). A genuine declared\n// entry change (missing key or differing value) returns null and the finding is kept.\ninterface CompositeSubsetSpec {\n re: RegExp;\n keyFields: string[];\n ignoreFields: ReadonlySet<string>;\n}\nconst COMPOSITE_KEY_SUBSET_PATHS: Record<string, CompositeSubsetSpec> = {\n 'AWS::ElasticBeanstalk::ConfigurationTemplate': {\n re: /(^|\\.)OptionSettings$/,\n keyFields: ['Namespace', 'OptionName'],\n ignoreFields: new Set(['ResourceName']),\n },\n};\n\n// Align a declared object array to a live one BY a composite identity key, ignoring the\n// spec's live-only fields in the value compare. Returns the live-only entries (server-\n// injected / out-of-band entries the template never declared) when every DECLARED entry is\n// present in live and deep-equal on its declared (non-ignored) fields (declared ⊆ live,\n// reorder-insensitive). Returns null when a declared entry is MISSING from live or a declared\n// field differs (a genuine declared drift the caller must keep), or when either side is not a\n// pure object array or an element is missing a key field (disqualify rather than risk muting).\nfunction alignCompositeKeySubset(\n declared: unknown,\n live: unknown,\n spec: CompositeSubsetSpec\n): unknown[] | null {\n if (!Array.isArray(declared) || !Array.isArray(live)) return null;\n const keyOf = (e: unknown): string | null => {\n if (!e || typeof e !== 'object' || Array.isArray(e)) return null;\n const r = e as Record<string, unknown>;\n const parts: string[] = [];\n for (const f of spec.keyFields) {\n if (typeof r[f] !== 'string') return null;\n parts.push(r[f] as string);\n }\n return JSON.stringify(parts);\n };\n // A declared entry deep-equals a live entry once BOTH sides drop the ignored (live-only)\n // fields — the declared side never carries them, but strip symmetrically to be safe.\n const stripIgnored = (e: Record<string, unknown>): Record<string, unknown> => {\n if (spec.ignoreFields.size === 0) return e;\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(e)) if (!spec.ignoreFields.has(k)) out[k] = v;\n return out;\n };\n const lm = new Map<string, unknown>();\n for (const e of live) {\n const k = keyOf(e);\n if (k === null) return null;\n lm.set(k, e);\n }\n const declaredKeys = new Set<string>();\n for (const d of declared) {\n const k = keyOf(d);\n if (k === null || !lm.has(k)) return null;\n if (\n !deepEqual(\n stripIgnored(d as Record<string, unknown>),\n stripIgnored(lm.get(k) as Record<string, unknown>)\n )\n )\n return null;\n declaredKeys.add(k);\n }\n return live.filter((e) => {\n const k = keyOf(e);\n return k !== null && !declaredKeys.has(k);\n });\n}\n\n// R96/R98: recurse the declared and live sides of a property and emit each LIVE-only\n// nested key — a sub-key present in live but never declared, at any depth.\n// - Plain objects (R96): walk every live key; recurse where declared, emit otherwise.\n// - Identity-keyed object arrays (R98: Tags/Origins/AttributeDefinitions/…): align\n// elements BY identity value (not position — canonicalization may sort the side\n// with an extra sub-key elsewhere) and recurse into each MATCHED pair, so a\n// live-only sub-field inside a declared element is caught (path `Prop[<id>].sub`).\n// A whole live-only ELEMENT (no declared match) is left to the declared compare,\n// not emitted here. Identity-LESS arrays (no shared Key/Id/AttributeName/IndexName,\n// e.g. SecurityGroup rules) are NOT descended — their elements can't be matched\n// reliably, so descending risks false positives.\n// Pure: the caller decides suppression and finding shape.\nconst isNestedObject = (x: unknown): x is Record<string, unknown> =>\n x !== null && typeof x === 'object' && !Array.isArray(x);\n\n// A CloudFormation AUTO-GENERATED physical name. When a resource declares no explicit name,\n// CFn mints `<stackName>-<logicalId>-<random>` (the stack name is the FIRST segment of the\n// CDK construct path). DELIBERATELY strict — it must start with this stack's name AND end\n// with CFn's ~12+ char alphanumeric random suffix — so a user-chosen name is not folded away\n// (that would hide a real undeclared value, defeating the differentiator). For SHORT-name\n// resource types (an ELBv2 load balancer / target group name is capped at 32 chars) CFn\n// TRUNCATES both segments — stack `CdkRealDriftIntegIotVpces` + logical id `NlbBC…` mints\n// `CdkRea-NlbBC-Rz5FCsQXIO7E` — so the full-prefix test misses and every auto-named\n// NLB/ALB/target group was first-run noise (observed live). The truncated branch stays\n// tightly gated: BOTH halves must be prefixes of this stack's name and this resource's own\n// logical id, with the stack half a STRICT prefix (truncation actually happened — the\n// untruncated form is the branch above) — a user-chosen name realistically never matches\n// all of that. Pure.\nconst CFN_RANDOM_SUFFIX = /-[0-9A-Za-z]{12,}$/;\n\n// #503: return a copy of a parsed JSON-string LIVE value with service-injected default\n// members subtracted, so the JSON_STRING_PROPS structural compare does not false-flag them.\n// A key is dropped from a live object only when it is a listed default, the DECLARED side\n// omits it, AND the live value equals the default (equality-gated — a member the template\n// set to a non-default value is kept and still compares). Runs per element when the parsed\n// value is a top-level array, at the root when it is an object; leaves anything else as-is.\nfunction stripInjectedJsonStringDefaults(\n declared: unknown,\n live: unknown,\n defaults: Record<string, unknown>\n): unknown {\n const stripObject = (d: unknown, l: unknown): unknown => {\n if (l === null || typeof l !== 'object' || Array.isArray(l)) return l;\n const dObj =\n d !== null && typeof d === 'object' && !Array.isArray(d)\n ? (d as Record<string, unknown>)\n : {};\n const out: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(l as Record<string, unknown>)) {\n if (key in defaults && !(key in dObj) && deepEqual(val, defaults[key])) continue;\n out[key] = val;\n }\n return out;\n };\n if (Array.isArray(live)) {\n const dArr = Array.isArray(declared) ? declared : [];\n return live.map((l, i) => stripObject(dArr[i], l));\n }\n return stripObject(declared, live);\n}\nfunction isCfnGeneratedName(\n value: unknown,\n constructPath: string | undefined,\n physicalId: string | undefined,\n logicalId?: string\n): boolean {\n // The bare physical-id echo (value === physicalId) is a STRUCTURAL drop handled separately\n // — never fold it into a `generated` finding here, or a resource whose physical id IS its\n // CFn-generated name gains a phantom finding.\n if (typeof value !== 'string' || !constructPath || value === physicalId) return false;\n // A bare LOGICAL-ID echo: for some types CloudFormation mints an auto-generated physical\n // name equal to the resource's LOGICAL ID verbatim — no `<stack>-` prefix, no extra random\n // suffix beyond the CDK hash already baked into the logical id (a BucketDeployment's\n // AwsCliLayer LayerName reads back \"CaDeployAwsCliLayer58606CDE\", its own logical id; #509).\n // The strict `<stack>-…-<suffix>` shapes below never match that form. A CDK logical id\n // already carries an 8-hex-char construct hash, so a user-chosen value coinciding is\n // effectively impossible — fold it. (aws-s3-deployment is a very common construct.)\n if (logicalId && value === logicalId) return true;\n const stackName = constructPath.split('/')[0];\n if (!stackName || !CFN_RANDOM_SUFFIX.test(value)) return false;\n if (value.startsWith(`${stackName}-`)) return true;\n if (!logicalId) return false;\n // Truncated short-name form: `<stackPrefix>-<logicalIdPrefix>-<random>`. Logical ids are\n // alphanumeric (never '-'), so the LAST '-' in the de-suffixed base splits the two halves\n // even when the stack name itself contains dashes.\n const base = value.replace(CFN_RANDOM_SUFFIX, '');\n const sep = base.lastIndexOf('-');\n if (sep <= 0) return false;\n const stackPart = base.slice(0, sep);\n const logicalPart = base.slice(sep + 1);\n return (\n stackPart.length < stackName.length &&\n stackName.startsWith(stackPart) &&\n logicalPart.length > 0 &&\n logicalId.startsWith(logicalPart)\n );\n}\n\n// A live-only OBJECT that is a SELF-IDENTITY ECHO WRAPPER: some CC read handlers\n// (AWS::Logs::DeliveryDestination's DeliveryDestinationPolicy) return\n// `{ <IdentityField>: <own physical id>, <Payload>: {} }` when the payload was never\n// set — semantically \"nothing configured\", but the id echo defeats the plain deep\n// trivially-empty drop. Ignore FIRST-LEVEL entries equal to the resource's own\n// physical id (at least one must match, so ordinary objects never take this path),\n// then apply the same deep trivially-empty test. A REAL payload (an actually\n// attached policy) is not trivially empty and still surfaces. Pure.\nfunction isSelfEchoTrivialEmpty(v: unknown, physicalId: string | undefined): boolean {\n if (physicalId === undefined || v === null || typeof v !== 'object' || Array.isArray(v))\n return false;\n const entries = Object.entries(v as Record<string, unknown>);\n const rest = entries.filter(([, val]) => val !== physicalId);\n return rest.length < entries.length && rest.every(([, val]) => isTrivialEmpty(val));\n}\n\n// A live-only policy DOCUMENT whose statements were ALL subtracted as AWS-managed\n// (canonicalizePolicy drops the delivery.logs `AWSLogDelivery*` statements a service\n// auto-attaches when vended logs are pointed at a log group — a CloudWatch Logs\n// Delivery, an APS Workspace LoggingConfiguration, VPC flow logs; issue #462 item 2,\n// APS instance per the #464 addendum). What survives is the bare policy-grammar\n// shell `{Version, Statement: []}` — Version is a non-empty constant string, so the\n// plain deep trivially-empty drop misses it and every vended-logs user saw one line\n// of first-run noise on the LOG GROUP. The shell carries no inventory value; drop it\n// as structural noise. Gated: `Statement` must be present and EMPTY (a doc with any\n// surviving statement — a real out-of-band policy, a foreign principal, a user grant\n// — is not a shell), and every other key must be the grammar boilerplate\n// (Version/Id strings). Pure.\nfunction isEmptyPolicyShell(v: unknown): boolean {\n if (v === null || typeof v !== 'object' || Array.isArray(v)) return false;\n const o = v as Record<string, unknown>;\n if (!Array.isArray(o.Statement) || o.Statement.length > 0) return false;\n return Object.entries(o).every(\n ([k, val]) => k === 'Statement' || ((k === 'Version' || k === 'Id') && typeof val === 'string')\n );\n}\n\n// structuredClone rejects the UNRESOLVED Symbol a declared value may carry, so deep-clone\n// the declared model symbol-safe (symbols/primitives pass through by reference/value). Used\n// to clone the declared side before stripAsymmetricIdentityFields mutates it.\nfunction cloneDeepWithSymbols(v: unknown): unknown {\n if (Array.isArray(v)) return v.map(cloneDeepWithSymbols);\n if (v !== null && typeof v === 'object') {\n const out: Record<string, unknown> = {};\n for (const [k, val] of Object.entries(v as Record<string, unknown>))\n out[k] = cloneDeepWithSymbols(val);\n return out;\n }\n return v;\n}\n\n// An IAM policy STATEMENT array (PolicyDocument.Statement, AssumeRolePolicyDocument\n// .Statement, inline Policies[].PolicyDocument.Statement, …). Recognized by the\n// `Effect` (Allow/Deny) key every statement carries — NOT by path, so it catches\n// statements at any depth. Statements are identity-LESS (no Key/Id/AttributeName/\n// IndexName), so the identity-keyed descent below skips them; this marker re-enables\n// a SAFE (subset-match) descent for exactly this shape, leaving other identity-less\n// arrays (SecurityGroup rules etc.) untouched.\nconst isPolicyStatementArray = (arr: unknown[]): boolean =>\n arr.length > 0 && arr.every((el) => isNestedObject(el) && 'Effect' in el);\n\n// An IAM inline-policy WRAPPER array — `Policies: [{ PolicyName, PolicyDocument }]` on\n// AWS::IAM::Role/User/Group, the dominant CDK inline-policy shape. The wrapper is\n// identity-LESS (PolicyName is not a generic IDENTITY_FIELD) and its elements are NOT\n// statements (no `Effect`), so neither descent above fires — leaving the wrapped\n// PolicyDocument.Statement unreached and a live-only sub-key added to a wrapped statement\n// (e.g. an out-of-band `Condition` narrowing/widening access) invisible, the same FN\n// #151 fixed for TOP-LEVEL documents. Recognized by `PolicyDocument` so the descent can\n// align by PolicyName and reach the statement subset-match for this shape too.\nconst isInlinePolicyArray = (arr: unknown[]): boolean =>\n arr.length > 0 && arr.every((el) => isNestedObject(el) && 'PolicyDocument' in el);\n\n// True when every key of `sub` is present in `sup` with an equal value (objects\n// recurse so a nested declared block must also be a subset; everything else is\n// deep-equal). Used to align a declared policy statement to the live statement it is\n// a subset of — robust to the statement re-sort canonicalization applies once a\n// sub-key is added (so positional alignment would break) and to extra live-only keys.\nfunction isPolicySubsetOf(sub: Record<string, unknown>, sup: Record<string, unknown>): boolean {\n for (const [k, v] of Object.entries(sub)) {\n if (!(k in sup)) return false;\n const sv = sup[k];\n if (isNestedObject(v) && isNestedObject(sv)) {\n if (!isPolicySubsetOf(v, sv)) return false;\n } else if (!deepEqual(v, sv)) return false;\n }\n return true;\n}\n\n// True when an undeclared live value matches a known AWS default — for the `atDefault`\n// fold (R86). A plain deepEqual is too strict for an OBJECT default whose sub-keys AWS\n// reports inconsistently: an EDGE RestApi reads back EndpointConfiguration as\n// `{Types:['EDGE']}` in some regions but `{IpAddressType:'ipv4',Types:['EDGE']}` in\n// others, so a strict compare against the fuller KNOWN_DEFAULTS object fails on the\n// omitted key and the whole undeclared object falls through as a false positive. Accept\n// the live value when it deep-equals the default OR is a SUB-OBJECT of it: every key it\n// carries matches the default and it carries no key absent from the default. Still\n// equality-gated per overlapping key — a sub-key set to a non-default value\n// (IpAddressType:'dualstack'), or an extra key the default doesn't list, breaks the\n// match and surfaces as real drift. Scalars/arrays fall back to deepEqual. Exported for\n// unit tests.\nexport function matchesKnownDefault(live: unknown, def: unknown): boolean {\n if (deepEqual(live, def)) return true;\n if (!isNestedObject(live) || !isNestedObject(def)) return false;\n // Trivially-empty live sub-keys the default does NOT list carry no inventory value (a\n // schema-strip residue husk — RedshiftServerless Workgroup's echo attribute reads back an\n // `Endpoint` that is only `{VpcEndpoints:[{NetworkInterfaces:[{},{}]}]}` after leaf\n // readOnly-stripping, #491). Skip only those, so the object still matches a default that\n // lists only the meaningful sub-keys (its `PricePerformanceTarget`) without pinning the\n // per-deploy ENI shape. A key the default DOES list must still deep-equal it — so a\n // trivially-empty live value that is the OPPOSITE of a non-empty default (VpcLattice\n // SharingConfig `{enabled:false}` vs default `{enabled:true}`, #483) never vacuously folds.\n return Object.entries(live).every(([k, v]) =>\n k in def ? deepEqual(v, def[k]) : isTrivialEmpty(v)\n );\n}\n\nfunction collectNestedUndeclared(\n declaredVal: unknown,\n liveVal: unknown,\n path: string,\n emit: (path: string, value: unknown) => void,\n // Per-type override: nested object-arrays whose element identity is a NON-standard field\n // (not one of IDENTITY_FIELDS), keyed by the array's path with brackets stripped. Without\n // it those arrays are identity-LESS to the generic check below and the descent is skipped —\n // hiding a live-only sub-key added to a declared element (a silent FN). See\n // NESTED_ARRAY_IDENTITY.\n nestedArrayIdentity?: Record<string, string>\n): void {\n if (Array.isArray(declaredVal) && Array.isArray(liveVal)) {\n if (declaredVal.length === 0 || liveVal.length === 0) return;\n // A registered identity field (e.g. ApiGateway Method Integration.IntegrationResponses\n // keyed by StatusCode) wins over the generic IDENTITY_FIELDS sniff; both sides share it.\n const regId = nestedArrayIdentity?.[path.replace(/\\[[^\\]]*\\]/g, '')];\n const idf = regId ?? identityField(declaredVal);\n if (idf && (regId !== undefined || identityField(liveVal) === idf)) {\n const liveById = new Map<string, Record<string, unknown>>();\n for (const el of liveVal) if (isNestedObject(el)) liveById.set(String(el[idf]), el);\n for (const dEl of declaredVal) {\n if (!isNestedObject(dEl)) continue;\n const match = liveById.get(String(dEl[idf]));\n if (match)\n collectNestedUndeclared(\n dEl,\n match,\n `${path}[${String(dEl[idf])}]`,\n emit,\n nestedArrayIdentity\n );\n }\n return;\n }\n // IAM policy STATEMENT arrays are identity-less, so the descent above is skipped —\n // which hid a live-only sub-key ADDED to a declared statement out of band (e.g. a\n // `Condition` narrowing/widening access, or an extra `Principal`): the product's\n // core \"a setting you never declared changed\" promise failing on a security-\n // relevant resource. Re-enable the descent for THIS shape only, aligning each\n // declared statement to the live statement it is a SUBSET of (content match,\n // greedy 1:1) so the live-only sub-keys surface. A declared statement with no\n // superset match genuinely changed → left to the declared compare. Other identity-\n // less arrays stay undescended (no `Effect` marker), preserving their FP safety.\n if (isPolicyStatementArray(declaredVal) && isPolicyStatementArray(liveVal)) {\n const used = new Set<number>();\n declaredVal.forEach((dEl, di) => {\n if (!isNestedObject(dEl)) return;\n for (let i = 0; i < liveVal.length; i++) {\n if (used.has(i)) continue;\n const lEl = liveVal[i];\n if (isNestedObject(lEl) && isPolicySubsetOf(dEl, lEl)) {\n used.add(i);\n collectNestedUndeclared(dEl, lEl, `${path}[${di}]`, emit, nestedArrayIdentity);\n break;\n }\n }\n });\n return;\n }\n // IAM inline-policy wrappers (Role/User/Group `Policies[]`) are identity-less and\n // their elements aren't statements, so neither descent above reaches the wrapped\n // PolicyDocument.Statement. Align by PolicyName and recurse into each matched pair so\n // the statement subset-descent (above) is reached for this dominant CDK shape too.\n if (isInlinePolicyArray(declaredVal) && isInlinePolicyArray(liveVal)) {\n const liveByName = new Map<string, Record<string, unknown>>();\n for (const el of liveVal)\n if (isNestedObject(el) && typeof el.PolicyName === 'string')\n liveByName.set(el.PolicyName, el);\n for (const dEl of declaredVal) {\n if (!isNestedObject(dEl) || typeof dEl.PolicyName !== 'string') continue;\n const match = liveByName.get(dEl.PolicyName);\n if (match)\n collectNestedUndeclared(\n dEl,\n match,\n `${path}[${dEl.PolicyName}]`,\n emit,\n nestedArrayIdentity\n );\n }\n }\n return;\n }\n if (!isNestedObject(declaredVal) || !isNestedObject(liveVal)) return;\n for (const [k, val] of Object.entries(liveVal)) {\n const childPath = `${path}.${k}`;\n if (k in declaredVal)\n collectNestedUndeclared(declaredVal[k], val, childPath, emit, nestedArrayIdentity);\n else emit(childPath, val);\n }\n}\n\n// Bring a raw Cloud Control live model into the SAME canonical, noise-subtracted form\n// classify's live side uses: strip AWS-managed fields + `aws:*` tags, reconcile OAI\n// principals (no-op without a resolved map), run the shared canonicalization pipeline\n// (policy docs + tag lists + id arrays), then drop schema readOnly + writeOnly paths.\n// Factored out of `classifyResource` so the `added` tier (read/child-enumerators.ts,\n// whole out-of-band resources with NO declared side to compare) can normalize the\n// child's full model IDENTICALLY before record/compare — otherwise a volatile readOnly\n// field (a timestamp, a revision id) would read as a false \"changed since record\" on\n// every check. Mutates a fresh object (the canonicalize step clones), so liveRaw is\n// untouched. Pure: no AWS calls.\n// Sort a resource's per-type UNORDERED-SET properties into a canonical order, in place.\n// canonicalizeForCompare is type-agnostic, so it can't apply these per-type opt-ins; the\n// DECLARED loop sorts them for its compare, but the UNDECLARED loop (and the recorded\n// baseline value + the `added` model) emitted them RAW — so a recorded SG ingress set or\n// Cognito OAuth list, re-read by AWS in a different order, false-flagged as \"changed since\n// record\" (baselineValueMatches re-canonicalizes without this step). Sorting them here, in\n// the shared live-model normalizer, makes every downstream consumer see one stable order.\nfunction sortUnorderedSetProps(\n model: Record<string, unknown>,\n resourceType: string,\n schemaObjectArrayKeys: readonly string[] = []\n): void {\n const objKeys = new Set([\n ...(UNORDERED_OBJECT_ARRAY_PROPS[resourceType] ?? []),\n ...schemaObjectArrayKeys,\n ]);\n // A key whose ORDER is semantically significant (a Logs Transformer processor pipeline)\n // must NOT be sorted even when the schema marks it insertionOrder:false — sorting the live\n // side alone would re-skew the finding index vs the raw model the revert patches (#529).\n const orderSig = ORDER_SIGNIFICANT_ARRAY_KEYS[resourceType];\n for (const k of objKeys)\n if (!orderSig?.has(k) && Array.isArray(model[k])) model[k] = sortUnorderedObjectArray(model[k]);\n for (const k of UNORDERED_ARRAY_PROPS[resourceType] ?? []) {\n const v = model[k];\n if (\n Array.isArray(v) &&\n v.every((e) => typeof e === 'string' || typeof e === 'number' || typeof e === 'boolean')\n )\n model[k] = [...v].sort((a, b) =>\n `${typeof a}:${String(a)}` < `${typeof b}:${String(b)}` ? -1 : 1\n );\n }\n}\n\nexport function normalizeLiveModel(\n liveRaw: Record<string, unknown>,\n schema: SchemaInfo,\n opts: { oaiCanonicalIds?: Record<string, string>; resourceType?: string } = {}\n): Record<string, unknown> {\n const oaiMap = opts.oaiCanonicalIds ?? {};\n const live = canonicalizeForCompare(\n rewriteOaiPrincipalsDeep(stripAwsTagsDeep(stripCcApiAwsManagedFields(liveRaw)), oaiMap),\n opts.resourceType\n ) as Record<string, unknown>;\n deepStripPaths(live, schema.readOnlyPaths);\n deepStripPaths(live, schema.writeOnlyPaths);\n if (opts.resourceType)\n sortUnorderedSetProps(\n live,\n opts.resourceType,\n // top-level keys only — nested (dotted) schema paths are handled per-key in the\n // declared loop, and the undeclared loop's nested inventory is emitted per-path.\n (schema.unorderedObjectArrayPaths ?? []).filter((p) => !p.includes('.'))\n );\n return live;\n}\n\nexport function classifyResource(\n resource: DesiredResource,\n liveRaw: Record<string, unknown>,\n schema: SchemaInfo,\n opts: {\n accountId?: string;\n region?: string;\n kmsAliasTargets?: Record<string, string>; // alias/aws/* -> target key id, for strict KMS match\n oaiCanonicalIds?: Record<string, string>; // OAI id -> S3CanonicalUserId, for CloudFront OAI principal match\n // Rules declared by SIBLING standalone AWS::EC2::SecurityGroupIngress/::SecurityGroupEgress\n // resources, keyed by the target SG's resolved GroupId (== the SG's physical id). Subtracted\n // from an AWS::EC2::SecurityGroup's reflected live rule arrays so they are not double-counted.\n siblingSgRules?: Record<string, { ingress: unknown[]; egress: unknown[] }>;\n // Bucket physical ids whose S3 notifications are managed by a Custom::S3BucketNotifications\n // custom resource (see buildBucketNotificationManaged): the live bucket reflects the\n // CR-applied NotificationConfiguration the bucket resource never declares, so it is dropped\n // rather than surfaced as false undeclared drift.\n bucketNotificationManaged?: Set<string>;\n // Per child physical id, the parent cluster's live model — for the CLUSTER_ECHO_CHILD\n // strip (an Aurora DBInstance echoing its DBCluster's cluster-level config).\n clusterEchoModel?: Record<string, Record<string, unknown>>;\n } = {}\n): Finding[] {\n const { logicalId, resourceType, physicalId, declared: declaredIn } = resource;\n const findings: Finding[] = [];\n\n // Normalize the LIVE model via the shared `normalizeLiveModel` — strip AWS-managed\n // fields + aws:* tags (live-only), reconcile CloudFront OAI principals (no-op without\n // a resolved map), run the shared canonicalization pipeline (policy docs + tag lists +\n // id arrays so reordering / scalar-vs-array / OAI principal-form is not false drift),\n // then drop schema readOnly (pure noise) + writeOnly (unreadable) paths at any depth.\n // The `added` tier uses the SAME helper, so the two live-normalization paths can never\n // silently diverge; the pipeline is shared with baseline-file.ts so baseline values\n // normalize identically (see pipeline.ts).\n const oaiMap = opts.oaiCanonicalIds ?? {};\n // AWS sometimes GENERATES an identity field the template omitted (S3\n // LifecycleConfiguration.Rules[].Id when `addLifecycleRule` is called without an `id`).\n // The live element then carries the field while the declared element does not, so the\n // per-side identity sort would key the LIVE array by the generated id and leave the\n // DECLARED array in template order — misaligning every element into false drift. Strip\n // such asymmetric identity fields from a clone of each side BEFORE canonicalization so\n // neither side is keyed by them (AWS preserves the array order). `declaredIn` can hold\n // the UNRESOLVED Symbol, which structuredClone rejects — clone it symbol-safe.\n const liveForCompare = structuredClone(liveRaw);\n const declaredForCompare = cloneDeepWithSymbols(declaredIn) as Record<string, unknown>;\n stripAsymmetricIdentityFields(declaredForCompare, liveForCompare);\n const live = normalizeLiveModel(liveForCompare, schema, {\n oaiCanonicalIds: oaiMap,\n resourceType,\n });\n const declared = canonicalizeForCompare(\n rewriteOaiPrincipalsDeep(declaredForCompare, oaiMap),\n resourceType\n ) as Record<string, unknown>;\n // Drop a parent's reflected child-aggregate property (e.g. SNS Topic.Subscription)\n // UNLESS the template declares it inline — cdkrd tracks those children as their own\n // resources (+ the `added` enumerator), so comparing the reflection would double-report\n // (see REFLECTED_CHILD_PROPS). Fail-open: a declared inline value is still compared.\n const reflected = REFLECTED_CHILD_PROPS[resourceType];\n if (reflected && !(reflected in declared)) delete live[reflected];\n // An ECS Cluster reflects the CapacityProviders / DefaultCapacityProviderStrategy declared by\n // its sibling AWS::ECS::ClusterCapacityProviderAssociations resource — the only CFn way to set\n // them (the Cluster's own schema carries neither). The association is tracked + compared as its\n // own resource, so leaving them on the cluster's live model reads as false undeclared drift. Drop\n // them ONLY when a sibling association references this cluster (hasSiblingCapacityProviders); a\n // cluster with capacity providers set purely out of band (no association resource) keeps them.\n if (resourceType === 'AWS::ECS::Cluster' && resource.hasSiblingCapacityProviders) {\n for (const p of ['CapacityProviders', 'DefaultCapacityProviderStrategy']) {\n if (!(p in declared)) delete live[p];\n }\n }\n // Drop declared scalar props AWS re-normalizes on read (SSM Document DocumentFormat:\n // any authored YAML/TEXT is stored + returned as JSON) from BOTH sides so the write-time\n // authoring hint is not a spurious declared drift (see READ_NORMALIZED_DECLARED_PATHS).\n for (const p of READ_NORMALIZED_DECLARED_PATHS[resourceType] ?? []) {\n delete declared[p];\n delete live[p];\n }\n // Subtract rules declared by sibling standalone SecurityGroupIngress/Egress resources from\n // an AWS::EC2::SecurityGroup's reflected live rule arrays (see SG_RULE_REFLECTION). Keyed by\n // the SG's resolved GroupId (== its physical id). The sibling rules are themselves compared\n // as their own resources, so this leaves only the inline-declared rules (plus any out-of-band\n // rule, which matches no sibling) to compare.\n if (resourceType === 'AWS::EC2::SecurityGroup') {\n const sib = physicalId ? opts.siblingSgRules?.[physicalId] : undefined;\n if (sib) {\n for (const [prop, side] of Object.entries(SG_RULE_REFLECTION)) {\n subtractSiblingSgRules(live, prop, sib[side]);\n }\n }\n }\n // A bucket whose notifications are managed by a Custom::S3BucketNotifications CR reflects\n // the CR-applied NotificationConfiguration it never declares itself (CDK renders\n // addEventNotification/enableEventBridgeNotification as that CR, which cdkrd skips). The\n // config is IaC-managed, not out of band — drop the reflected property so it is not false\n // undeclared drift. Only when the template does NOT declare it inline (a raw-CFn bucket that\n // sets NotificationConfiguration directly is compared normally).\n if (\n resourceType === 'AWS::S3::Bucket' &&\n physicalId &&\n opts.bucketNotificationManaged?.has(physicalId) &&\n !('NotificationConfiguration' in declared)\n ) {\n delete live.NotificationConfiguration;\n }\n // Drop an UNDECLARED property whose value ECHOES the parent cluster's value (an Aurora\n // DBInstance mirroring its DBCluster's cluster-level config — see CLUSTER_ECHO_CHILD).\n // Equality-gated: a declared property compares normally, and an instance value that\n // DIVERGES from the cluster still surfaces. The parent's own property carries detection.\n const echoSpec = CLUSTER_ECHO_CHILD[resourceType];\n const echoModel = echoSpec && physicalId ? opts.clusterEchoModel?.[physicalId] : undefined;\n if (echoSpec && echoModel) {\n for (const k of Object.keys(live)) {\n if (k in declared) continue;\n const parentKey = echoSpec.aliases[k] ?? k;\n if (!(parentKey in echoModel)) continue;\n const pv = echoModel[parentKey];\n if (deepEqual(live[k], pv) || isStringlyEqualDeep(live[k], pv)) delete live[k];\n }\n }\n // ManagedPolicy attachment lists (Roles/Users/Groups). A DECLARED list is handled\n // per-member in the declared loop below (declared-but-missing = detach; live-only =\n // undeclared inventory). A list the template does NOT declare at all is left in `live`\n // so it flows to the undeclared loop as ordinary undeclared inventory (recordable) —\n // NOT dropped: dropping it hid an unexpected attachment entirely (no record, no later\n // drift). It is inventory, never a positional FP, so it does not reintroduce the\n // cdk-drift union false positive.\n const attachmentProps = IAM_ATTACHMENT_SUBSET[resourceType];\n // R11: a declared TOP-LEVEL write-only key is about to be stripped from `declared`\n // (below). Surface it as ONE readGap finding FIRST so it is never silently dropped\n // — the informational tier exists precisely for \"declared but unreadable\" props.\n // Only top-level keys get this treatment; nested write-only path stripping stays\n // silent on purpose (too granular to report meaningfully per-path).\n for (const k of Object.keys(declared)) {\n if (schema.writeOnly.has(k)) {\n findings.push({\n tier: 'readGap',\n logicalId,\n resourceType,\n path: k,\n note: 'write-only — cannot be read back',\n });\n }\n }\n // writeOnly cannot be read back: strip it from the DECLARED side too so it is never\n // compared (the LIVE side was already stripped by normalizeLiveModel above).\n deepStripPaths(declared, schema.writeOnlyPaths);\n\n // Sibling-managed inline Policies (the CDK pattern: grants land in a sibling\n // AWS::IAM::Policy resource, which reflects into the role's live Policies). Drop\n // ONLY the live entries owned by a sibling — their content drift is the sibling\n // resource's own finding — so an out-of-band inline policy added to the role\n // still surfaces (as undeclared, or inside the declared compare).\n //\n // R111 fail-open: when a sibling PolicyName cannot be resolved statically (an\n // Fn::Sub/Fn::Join name, or none), `siblingPolicyNames` is 'unresolved' and we\n // do NOT filter at all. The old fallback DELETED the whole live Policies — which\n // also hid any out-of-band inline policy added directly to the role: a silent\n // false negative on a security-relevant resource (the dangerous DROP class, R95).\n // Now the unresolved role keeps its live Policies, so a rogue policy is NEVER\n // hidden; the sibling-managed entries surface as undeclared (baseline-able once).\n // We trade a one-time, VISIBLE false positive for never hiding a real change.\n const sibling = resource.siblingPolicyNames;\n if (sibling !== undefined && sibling !== 'unresolved' && Array.isArray(live.Policies)) {\n const names = new Set<unknown>(sibling);\n live.Policies = live.Policies.filter(\n (p) => !(p && typeof p === 'object' && names.has((p as Record<string, unknown>).PolicyName))\n );\n }\n\n // declared drift (A3: declared key absent in live = read gap, not drift).\n // NOTE: no `schema.writeOnly.has(k)` guard here — a top-level write-only key was\n // already emitted as a readGap above AND stripped from `declared` by writeOnlyPaths,\n // so it cannot reach this loop (the old guard was dead code for top-level keys).\n let knownDef = KNOWN_DEFAULTS[resourceType] ?? {};\n // A Redshift RA3 cluster is ALWAYS encrypted (RA3 mandates encryption — it can never be false)\n // and AWS enables AvailabilityZoneRelocation for it by default, so an RA3 cluster that declares\n // neither reads back Encrypted=true / AvailabilityZoneRelocationStatus=\"enabled\" — AWS-forced\n // initial values, not user intent. Fold them via a NodeType conditional (the reliable in-\n // template discriminator; a DC2 cluster keeps the false/absent default and is unaffected).\n // Equality-gated + live-verified on a fresh RA3 single-node deploy. A cluster that declares\n // either value explicitly is compared in the declared loop, never reaching here.\n if (\n resourceType === 'AWS::Redshift::Cluster' &&\n typeof declaredIn?.['NodeType'] === 'string' &&\n (declaredIn['NodeType'] as string).startsWith('ra3')\n ) {\n knownDef = { ...knownDef, Encrypted: true, AvailabilityZoneRelocationStatus: 'enabled' };\n }\n // AWS/CDK-generated values for THIS resource (its minted name, a default log group\n // derived from the physical id), with the live physical id substituted in — keyed\n // by property, consulted by the undeclared loop below. Empty when the type has no\n // template or the physical id is unknown.\n const genDef = resolveGeneratedDefault(resourceType, physicalId) ?? {};\n\n // --- Nested-undeclared fold setup + shared emit closure ---------------------------------\n // Used by BOTH the nested descent into DECLARED objects (R96, below) and the descent into a\n // fully-undeclared object listed in DESCEND_UNDECLARED_OBJECT_PATHS (#555). Defined here so\n // the fully-undeclared descend (which runs inside the top-level undeclared loop, earlier than\n // the declared-nested loop) can reuse the exact same leaf classification.\n // R108: KNOWN_DEFAULT_PATHS is the hand-coded twin for the nested service defaults the CFn\n // schema does NOT annotate (the nested analogue of KNOWN_DEFAULTS) — read through the SAME\n // wildcard lookup, equality-gated identically.\n let knownDefPaths = KNOWN_DEFAULT_PATHS[resourceType] ?? {};\n // A Lambda DURABLE FUNCTION (declares DurableConfig — enabling durable execution) runs on\n // AWS's durable/managed compute substrate, which emits structured JSON logs by default\n // (the Durable Execution SDK's default logger always emits JSON), NOT the plain-Text\n // default of a regular function. So a durable function that declares no explicit LogFormat\n // reads back \"JSON\", which the base `LoggingConfig.LogFormat: 'Text'` default cannot fold\n // and would surface as false undeclared drift. Override the LogFormat default to JSON when\n // DurableConfig is present (the reliable in-template discriminator; the paired\n // ApplicationLogLevel/SystemLogLevel INFO defaults already fold via the base table).\n // Equality-gated + value-independent proof: observed live that DurableConfig <=> JSON on a\n // 9-function stack (same nodejs24.x runtime) where only the durable function reads JSON. A\n // durable function that pins Text explicitly declares it and is compared, never reaching here.\n if (resourceType === 'AWS::Lambda::Function' && 'DurableConfig' in declared) {\n knownDefPaths = { ...knownDefPaths, 'LoggingConfig.LogFormat': 'JSON' };\n }\n // R140: nested paths that are always an AWS-assigned generated id (value-independent),\n // folded as `generated` like the top-level isGeneratedName/GENERATED_DEFAULTS cases.\n const generatedPaths = GENERATED_PATHS[resourceType] ?? [];\n const generatedNestedPaths = GENERATED_NESTED_PATHS[resourceType];\n // Schema-detected FREE-FORM MAP properties (Lambda Environment.Variables, Glue\n // Parameters): a live-only sub-key directly under one is user-authored data, not an\n // AWS-materialized nested default — so flag it `freeFormKey` to surface it in the report\n // (the generic nested fold would hide a console-added env var as first-run noise).\n const freeFormMapPaths = schema.freeFormMapPaths ?? [];\n const underFreeFormMap = (schemaPath: string): boolean =>\n freeFormMapPaths.some((ff) => schemaPath.startsWith(`${ff}.`));\n const emitNested = (path: string, value: unknown): void => {\n if (isAllAwsTags(value) || isTrivialEmpty(value)) return;\n const schemaPath = path.replace(/\\[[^\\]]*\\]/g, '.*');\n // Same subset-tolerant default match as the top-level atDefault compare: an\n // OBJECT-valued nested default (CloudFront GeoRestriction, Scheduler RetryPolicy,\n // Cognito SignInPolicy, …) that AWS returns with a sub-key omitted still folds,\n // while a sub-key changed away from the default — or an extra key — surfaces.\n // Falls back to deepEqual for scalars/arrays, so nothing else changes.\n const atDefault =\n (schemaPath in schema.defaultPaths &&\n matchesKnownDefault(value, schema.defaultPaths[schemaPath])) ||\n (schemaPath in knownDefPaths && matchesKnownDefault(value, knownDefPaths[schemaPath]));\n const tier = atDefault\n ? 'atDefault'\n : // R142: a GENERATED_PATHS value folds as `generated` ONLY when it echoes a\n // physical-id segment (the AWS default) — a custom value the user set surfaces.\n (generatedPaths.includes(schemaPath) && isPhysicalIdSegment(value, physicalId)) ||\n // Value-INDEPENDENT nested generated path (KMS KeyPolicy.Id): AWS/CFn-injected,\n // never derivable from the physical id — folded only in this live-only case.\n generatedNestedPaths?.has(schemaPath)\n ? 'generated'\n : 'undeclared';\n // A free-form map key surfaces (not folded), but only when it is a real undeclared\n // value — an atDefault/generated one stays informational like any other.\n const freeFormKey = tier === 'undeclared' && underFreeFormMap(schemaPath);\n findings.push({\n tier,\n logicalId,\n resourceType,\n path,\n actual: value,\n nested: true,\n ...(freeFormKey && { freeFormKey: true }),\n });\n };\n // ----------------------------------------------------------------------------------------\n\n for (const [k, v] of Object.entries(declared)) {\n if (v === UNRESOLVED || hasUnresolved(v)) {\n findings.push({ tier: 'unresolved', logicalId, resourceType, path: k });\n // Wholly unresolved, OR partially unresolved but not in live to compare against:\n // nothing more to do. Otherwise fall through to compare the RESOLVED sub-values —\n // a sibling sub-value's drift (e.g. a changed Environment.Variables entry next to a\n // GetAtt-valued one) must not be hidden just because a SIBLING leaf is unresolved.\n // The compare below skips any per-leaf record whose declared side is unresolved.\n if (v === UNRESOLVED || !(k in live)) continue;\n } else if (!(k in live)) {\n // A declared key absent from the live read. A declared NON-EMPTY COLLECTION\n // (object/array) absent from live means the whole config was emptied/removed out\n // of band — many services OMIT a sub-config entirely when empty but RETURN it\n // when set (SecurityGroup ingress/egress, IAM inline Policies, every S3 sub-config,\n // Lambda Environment, …). Treating that as an informational readGap was a SILENT\n // FALSE NEGATIVE (the removal reported CLEAN). So DETECT it by default — emit ONE\n // WHOLE-PROPERTY declared finding (revert then re-applies the entire config via a\n // single top-level `add`; a nested sub-path patch fails because the parent, e.g.\n // `/CorsConfiguration`, is absent in the live model). FP-safe: a populated\n // collection is always returned by AWS, so this only fires on a genuine removal.\n //\n // EXCEPTIONS stay readGap (informational, never false drift): a SCALAR (AWS may\n // legitimately not echo a scalar), an EMPTY declared collection (declared `{}`/`[]`\n // vs absent is not drift), and the curated READGAP_COLLECTION_PATHS denylist —\n // collections AWS genuinely never returns even when set (Batch Timeout, DynamoDB\n // SSESpecification, Budgets NotificationsWithSubscribers). A new genuine readGap\n // surfaces as a VISIBLE, denylist-able false positive, never a silent FN.\n const isNonEmptyCollection =\n (Array.isArray(v) && v.length > 0) ||\n (v !== null && typeof v === 'object' && Object.keys(v as object).length > 0);\n // #507: a declared SCALAR on a curated SCALAR_RETURNED_WHEN_SET path — proven to\n // be echoed by the live read when set — that is absent from live was cleared out\n // of band (replace-omit update semantics). Detect it like a removed collection\n // (whole-property `add` on revert). A non-empty string / boolean / number counts\n // as \"set\"; a declared empty string stays readGap (declared `\"\"` vs absent is not\n // drift).\n const isClearedAllowlistedScalar =\n SCALAR_RETURNED_WHEN_SET[resourceType]?.has(k) === true &&\n ((typeof v === 'string' && v.length > 0) ||\n typeof v === 'number' ||\n typeof v === 'boolean');\n if (\n (isNonEmptyCollection && !READGAP_COLLECTION_PATHS[resourceType]?.has(k)) ||\n isClearedAllowlistedScalar\n ) {\n findings.push({\n tier: 'declared',\n logicalId,\n resourceType,\n path: k,\n desired: v,\n actual: undefined,\n });\n } else {\n findings.push({\n tier: 'readGap',\n logicalId,\n resourceType,\n path: k,\n note: 'declared but not returned by live read',\n });\n }\n continue;\n }\n // #503: a JSON-STRING property into which the service INJECTS a constant default member\n // the template never sent (CE CostCategory `Rules` gets `\"Type\":\"REGULAR\"` per rule).\n // Both sides arrive as canonicalized JSON strings, so the plain string compare below\n // false-flags the injected member as permanent declared drift (and revert can never\n // converge — the re-read re-injects it). This prop is NOT in JSON_STRING_PROPS (its\n // revert works via a plain Cloud Control whole-prop replace), so fold it HERE: parse\n // both sides, subtract the service-injected defaults from live where the declared side\n // omits them and the value equals the default, and skip if the remainder matches. A\n // genuine change (a member set to a non-default value) does NOT match and falls through\n // to the normal compare below, reported with the full live state.\n const jsonFills = JSON_STRING_DEFAULT_FILLS[resourceType]?.[k];\n if (jsonFills !== undefined && typeof v === 'string' && typeof live[k] === 'string') {\n try {\n const dvParsed = JSON.parse(v) as unknown;\n const lvStripped = stripInjectedJsonStringDefaults(\n dvParsed,\n JSON.parse(live[k] as string),\n jsonFills\n );\n if (deepEqual(dvParsed, lvStripped) || isStringlyEqualDeep(dvParsed, lvStripped)) continue;\n } catch {\n /* not JSON on one side — fall through to the normal compare */\n }\n }\n // A CloudFormation JSON-STRING property (AWS::Config::ConfigRule InputParameters):\n // the schema types it as a string holding JSON, but CDK declares it as an object and\n // the live read returns it parsed. Compare and emit it as a WHOLE UNIT at the\n // top-level path — never descend — so the revert rewrites the whole property as a\n // compact JSON string (a sub-path RFC6902 patch makes Cloud Control re-serialize the\n // JSON in a shape the provider rejects; see JSON_STRING_PROPS). Fold a stringly-equal\n // value (declared `90` vs live `\"90\"`, the param-values-are-strings coercion) so a\n // clean deploy is not drift; a genuine value change is one declared finding at `k`.\n if (JSON_STRING_PROPS[resourceType]?.has(k)) {\n // Parse a side that arrives as a raw JSON string (some providers return the\n // property unparsed) so both forms compare structurally; then fold a stringly-equal\n // value (declared `90` vs live `\"90\"`). A genuine value change is one declared\n // finding at the whole property path.\n const parseJson = (x: unknown): unknown => {\n if (typeof x !== 'string') return x;\n try {\n return JSON.parse(x) as unknown;\n } catch {\n return x;\n }\n };\n const dv = parseJson(v);\n const lv = parseJson(live[k]);\n if (!deepEqual(dv, lv) && !isStringlyEqualDeep(dv, lv)) {\n findings.push({\n tier: 'declared',\n logicalId,\n resourceType,\n path: k,\n desired: v,\n actual: live[k],\n });\n }\n continue;\n }\n // ManagedPolicy attachment lists (Roles/Users/Groups): tier each member by WHO\n // declared it. A DECLARED member absent from the live (union) set is an out-of-band\n // DETACH — emit a declared finding per missing member, carrying the member on\n // `attributeKey` so revert re-attaches ONLY that one (never rewriting the whole\n // list, which would detach the union members another stack/role legitimately added).\n // A live member NOT declared is the union — emit it as nested UNDECLARED inventory\n // (recordable), NOT a positional FP: a known union member folds/records, and a NEW\n // unexpected attachment then surfaces as drift vs the baseline. An unresolved\n // declared member (an intrinsic the synth couldn't resolve) can't be compared —\n // skip it (the whole-property `unresolved` finding above already noted it).\n if (attachmentProps?.has(k) && Array.isArray(v) && Array.isArray(live[k])) {\n const liveArr = live[k] as unknown[];\n const liveSet = new Set(liveArr.map((m) => String(m)));\n const declaredSet = new Set<string>();\n for (const member of v) {\n if (member === UNRESOLVED || hasUnresolved(member)) continue;\n if (typeof member !== 'string' && typeof member !== 'number') continue;\n declaredSet.add(String(member));\n if (liveSet.has(String(member))) continue;\n findings.push({\n tier: 'declared',\n logicalId,\n resourceType,\n path: k,\n attributeKey: String(member),\n desired: member,\n actual: undefined,\n note: 'declared attachment not present in live (out-of-band detach)',\n });\n }\n for (const member of liveArr) {\n if (typeof member !== 'string' && typeof member !== 'number') continue;\n if (declaredSet.has(String(member))) continue;\n findings.push({\n tier: 'undeclared',\n logicalId,\n resourceType,\n path: `${k}[${String(member)}]`,\n actual: member,\n nested: true,\n });\n }\n continue;\n }\n // R78: ELB attribute bags compare BY KEY (the template declares a subset of\n // the keys AWS returns) and emit one declared finding per changed attribute\n // carrying its Key, so revert can send only that Key=Value. This is naturally\n // subset-aware, subsuming the R75 projection for these two types.\n if (k === ELB_ATTRIBUTE_BAGS[resourceType] && Array.isArray(v) && Array.isArray(live[k])) {\n const liveBag = live[k] as unknown[];\n for (const dEl of v) {\n if (!isKeyValueEntry(dEl)) continue;\n // an unresolved declared attribute value can't be compared (already noted at the\n // property level) — skip it rather than emit a false declared drift vs the symbol\n if (dEl.Value === UNRESOLVED || hasUnresolved(dEl.Value)) continue;\n const lEl = liveBag.find((e) => isKeyValueEntry(e) && e.Key === dEl.Key);\n const liveValue = lEl ? (lEl as { Value: unknown }).Value : undefined;\n if (deepEqual(dEl.Value, liveValue)) continue;\n if (isStringlyEqualScalar(dEl.Value, liveValue)) continue;\n findings.push({\n tier: 'declared',\n logicalId,\n resourceType,\n path: k,\n attributeKey: dEl.Key,\n desired: dEl.Value,\n actual: liveValue,\n });\n }\n // Fail-closed (R95): the live bag also carries attribute keys the template never\n // declared (the ~20 server-default LB/TG attributes, OR an out-of-band custom\n // attribute). The declared loop above compares ONLY declared keys, so without this\n // the undeclared keys reached NO dimension — not even `record` — making an\n // out-of-band change to an UNDECLARED attribute (routing.http2.enabled,\n // deletion_protection.enabled, access_logs.s3.enabled …) a permanent silent FN,\n // contradicting cdkrd's core undeclared-property promise. Emit each live-only key as\n // nested undeclared inventory — the same fail-closed treatment R95 gives every other\n // identity-keyed array: folded as informational on the first run, snapshotted by\n // `record`, and a later change vs the baseline then surfaces as real drift. A\n // live-only key whose value EQUALS its curated AWS default (ELB_ATTRIBUTE_DEFAULTS)\n // is instead surfaced in the `atDefault` tier: still inventory (never drift), but it\n // shrinks the first-run `[Potential Drift]` noise the ~15-20 server-default attributes\n // otherwise produce. This is a CURATED per-KEY equality-gated fold, NOT the wildcard\n // an earlier revision warned against — a key absent from the table, or present with a\n // non-default value, still classifies `undeclared` and is recorded, so a real\n // out-of-band change never hides.\n const declaredKeys = new Set(\n v.filter(isKeyValueEntry).map((e) => (e as { Key: string }).Key)\n );\n // A LoadBalancer's per-type defaults (NLB/GWLB cross_zone \"false\") override the\n // shared table — the live `Type` is authoritative (readable, createOnly), with\n // the omitted-Type default `application` as the fallback.\n const lbType =\n resourceType === 'AWS::ElasticLoadBalancingV2::LoadBalancer'\n ? String(live.Type ?? declared.Type ?? 'application')\n : undefined;\n const attrDefaults = {\n ...(ELB_ATTRIBUTE_DEFAULTS[resourceType] ?? {}),\n ...(lbType === undefined ? {} : (ELB_ATTRIBUTE_DEFAULTS_BY_LB_TYPE[lbType] ?? {})),\n };\n for (const lEl of liveBag) {\n if (!isKeyValueEntry(lEl)) continue;\n const key = (lEl as { Key: string }).Key;\n if (declaredKeys.has(key)) continue;\n const value = (lEl as { Value: unknown }).Value;\n if (isTrivialEmpty(value)) continue;\n // bag values are stringly; match an equal string directly, and also tolerate a\n // typed live scalar (boolean/number) echoed against the string default.\n const isDefault =\n key in attrDefaults &&\n (value === attrDefaults[key] || isStringlyEqualScalar(value, attrDefaults[key]));\n findings.push({\n tier: isDefault ? 'atDefault' : 'undeclared',\n logicalId,\n resourceType,\n path: `${k}[${key}]`,\n actual: value,\n nested: true,\n });\n }\n continue;\n }\n // Per-type identity-keyed SUBSET arrays (Cognito UserPool.Schema): the template\n // declares a SUBSET of the elements AWS always returns. Align the declared elements\n // to live BY identity so they compare element-wise (no whole-array length-mismatch\n // FALSE positive), and emit the live-only elements as nested undeclared inventory.\n const subsetSpec = IDENTITY_KEYED_SUBSET_ARRAYS[resourceType]?.[k];\n // Per-type unordered OBJECT-array sets (R88: EC2 SecurityGroup ingress/egress) —\n // rule objects with no single identity field that AWS returns reordered. Sort BOTH\n // sides by canonical JSON before the positional diff so a reorder is not false\n // drift; a genuine rule change still differs after the sort.\n // An ORDER-significant key (a Logs Transformer processor pipeline) is never sorted, even\n // when its schema marks it insertionOrder:false — the raw order must be preserved so the\n // finding index aligns with the live model the Cloud Control revert patches (#529).\n const orderSignificant = ORDER_SIGNIFICANT_ARRAY_KEYS[resourceType]?.has(k) ?? false;\n const unorderedObjArray =\n !orderSignificant &&\n (UNORDERED_OBJECT_ARRAY_PROPS[resourceType]?.has(k) ||\n // schema-driven twin (#459): the schema marks this OBJECT array insertionOrder:false\n // (and its items carry no identity field), so a reorder is never drift.\n (schema.unorderedObjectArrayPaths?.includes(k) ?? false));\n // Per-type NESTED unordered object-array paths under this key (Bedrock Guardrail\n // ContentPolicyConfig.FiltersConfig etc.): sort the reordered set on both sides so\n // a positional diff doesn't false-flag it.\n const nestedUnordered = UNORDERED_NESTED_OBJECT_ARRAY_PATHS[resourceType];\n const nestedSubPaths = [\n ...new Set(\n [...(nestedUnordered ?? []), ...(schema.unorderedObjectArrayPaths ?? [])]\n .filter((p) => p.startsWith(`${k}.`))\n .map((p) => p.slice(k.length + 1))\n ),\n ];\n let declaredVal: unknown = v;\n let liveVal: unknown = live[k];\n if (subsetSpec && Array.isArray(v) && Array.isArray(live[k])) {\n const { idField, normalizeId } = subsetSpec;\n const idOf = (e: unknown): string | undefined => {\n if (!isNestedObject(e) || typeof e[idField] !== 'string') return undefined;\n const raw = e[idField] as string;\n return normalizeId ? normalizeId(raw) : raw;\n };\n const liveById = new Map<string, unknown>();\n for (const el of live[k] as unknown[]) {\n const id = idOf(el);\n if (id !== undefined) liveById.set(id, el);\n }\n const declaredIds = new Set<string>();\n const declaredSorted: unknown[] = [];\n const liveAligned: unknown[] = [];\n // align each declared element to its live match by identity (undefined if the\n // declared attribute was removed from the pool -> a genuine declared drift). Set\n // the idField to the NORMALIZED id on both sides so the per-element compare below\n // doesn't false-flag the prefix difference itself (declared `tier` vs live\n // `custom:tier`) — the identity is already matched, the rest compares by value.\n for (const dEl of [...(v as unknown[])].sort((a, b) =>\n (idOf(a) ?? '') < (idOf(b) ?? '') ? -1 : 1\n )) {\n const id = idOf(dEl);\n if (id === undefined) continue;\n declaredIds.add(id);\n const match = liveById.get(id);\n declaredSorted.push(isNestedObject(dEl) ? { ...dEl, [idField]: id } : dEl);\n liveAligned.push(isNestedObject(match) ? { ...match, [idField]: id } : match);\n }\n // live-only elements (the always-present standard attributes, OR an out-of-band\n // custom attribute the template never declared) -> nested undeclared inventory.\n // A live-only element that deep-equals its curated default shape (Cognito's fixed,\n // immutable OIDC standard attributes) folds to `atDefault` instead — same equality-\n // gated treatment a top-level default value gets, so a never-customized pool stops\n // flooding the first run with ~20 standard-attribute entries.\n const defaultEls = IDENTITY_KEYED_DEFAULT_ELEMENTS[resourceType]?.[k];\n for (const lEl of live[k] as unknown[]) {\n const id = idOf(lEl);\n if (id !== undefined && !declaredIds.has(id)) {\n const atDefault = defaultEls && id in defaultEls && deepEqual(lEl, defaultEls[id]);\n findings.push({\n tier: atDefault ? 'atDefault' : 'undeclared',\n logicalId,\n resourceType,\n path: `${k}[${id}]`,\n actual: lEl,\n nested: true,\n });\n }\n }\n declaredVal = declaredSorted;\n liveVal = liveAligned;\n } else if (unorderedObjArray) {\n // A key in BOTH UNORDERED_OBJECT_ARRAY_PROPS and UNORDERED_NESTED_OBJECT_ARRAY_PATHS\n // (ELBv2 ListenerRule `Conditions`) needs both folds: sort each element's nested\n // unordered set FIRST (so its canonical JSON is normalized), THEN sort the object\n // array itself. Without the inner sort, the outer canonical-JSON sort sees a\n // reordered-but-equal nested set as a different element and the positional diff\n // still false-flags it.\n declaredVal = sortUnorderedObjectArray(\n nestedSubPaths.length > 0 ? sortNestedObjectArrays(v, nestedSubPaths) : v\n );\n liveVal = sortUnorderedObjectArray(\n nestedSubPaths.length > 0 ? sortNestedObjectArrays(live[k], nestedSubPaths) : live[k]\n );\n } else if (nestedSubPaths.length > 0) {\n declaredVal = sortNestedObjectArrays(v, nestedSubPaths);\n liveVal = sortNestedObjectArrays(live[k], nestedSubPaths);\n }\n // R95: the live side is compared in FULL — no subset projection. An R75\n // generic `projectLiveToDeclaredSubset` used to drop live elements whose\n // identity key was not declared, to mute the extra default attributes ELB\n // returns. But that ALSO silently dropped genuine out-of-band ADDITIONS to any\n // identity-keyed array — a console-added Tag, an extra CloudFront Origin — which\n // a drift tool must never hide (fail-closed: report, do not suppress). The ELB\n // attribute bags are handled above by ELB_ATTRIBUTE_BAGS (R78, compare BY KEY),\n // which subsumes the projection for the one type that needed it; the corpus\n // confirms no other type relied on it.\n for (const d of calculateResourceDrift({ [k]: declaredVal }, { [k]: liveVal })) {\n // a per-leaf record whose DECLARED side is (or contains) an unresolved value can't\n // be verified — already noted as `unresolved` at the property level above. Skip it\n // so the unresolvable leaf never becomes a false `declared` drift vs the symbol,\n // while its RESOLVED siblings still compare normally (the WAVE20-F1 fix).\n if (d.stateValue === UNRESOLVED || hasUnresolved(d.stateValue)) continue;\n // A NESTED declared trivially-EMPTY value (an empty sub-config `{}`, `[]`, or a\n // `false`/`\"\"` leaf) whose live counterpart is ABSENT or equally empty is not drift:\n // many services simply OMIT an empty optional sub-object on read (Scheduler\n // `Target.SqsParameters: {}` reads back undefined). This mirrors the top-level\n // `!(k in live)` branch's rule that a declared EMPTY collection vs absent is not drift,\n // applied to a sub-path the top-level branch can't reach (the parent IS present). Gated\n // on the DECLARED side being empty, so a declared empty value against a POPULATED live\n // value still differs and surfaces as real drift.\n if (isTrivialEmpty(d.stateValue) && (d.awsValue === undefined || isTrivialEmpty(d.awsValue)))\n continue;\n // A `[{<name>,<value>}]` pair set the service reorders + default-fills (Firehose\n // processor `Parameters`, RDS OptionGroup `OptionSettings`): when every declared\n // entry is present in live with an equal value (declared subset of live), the\n // whole-array `declared` diff is a false positive — suppress it and surface the\n // live-only (server-injected) entries as nested undeclared inventory (recorded; a\n // later change still surfaces). A genuine declared entry change returns null and\n // the finding is kept as real drift.\n const nvSubsetSpec = NAME_VALUE_SUBSET_PATHS[resourceType];\n if (nvSubsetSpec?.re.test(d.path)) {\n const liveOnly = alignNameValueSubset(d.stateValue, d.awsValue, nvSubsetSpec);\n if (liveOnly) {\n for (const lo of liveOnly) {\n findings.push({\n tier: 'undeclared',\n logicalId,\n resourceType,\n path: `${d.path}[${String((lo as Record<string, unknown>)[nvSubsetSpec.nameField])}]`,\n actual: lo,\n nested: true,\n });\n }\n continue;\n }\n }\n // #493: composite-identity object-array subset (ElasticBeanstalk ConfigurationTemplate\n // `OptionSettings`): the template declares ~3 entries but CC returns the fully resolved\n // ~58, keyed by Namespace+OptionName with a live-only ResourceName field. Same fold as\n // the name/value subset above but with a composite key + ignored live-only fields. When\n // every declared entry is a subset of live, suppress the whole-array `declared` FP and\n // surface the service-filled extras as nested undeclared inventory.\n const ckSubsetSpec = COMPOSITE_KEY_SUBSET_PATHS[resourceType];\n if (ckSubsetSpec?.re.test(d.path)) {\n const liveOnly = alignCompositeKeySubset(d.stateValue, d.awsValue, ckSubsetSpec);\n if (liveOnly) {\n for (const lo of liveOnly) {\n const r = lo as Record<string, unknown>;\n const key = ckSubsetSpec.keyFields.map((f) => String(r[f])).join('|');\n findings.push({\n tier: 'undeclared',\n logicalId,\n resourceType,\n path: `${d.path}[${key}]`,\n actual: lo,\n nested: true,\n });\n }\n continue;\n }\n }\n // a bare name declared for a field AWS returns as the full ARN is not drift\n // (account/region-scoped when opts are provided); likewise an AWS-managed-default\n // KMS alias vs its resolved key ARN\n if (isArnNameMatch(d.stateValue, d.awsValue, opts)) continue;\n if (isManagedKmsAliasMatch(d.stateValue, d.awsValue, opts.kmsAliasTargets)) continue;\n // a CloudWatch Logs log-group ARN whose only difference is the trailing `:*`\n // wildcard (CDK emits it; API Gateway AccessLogSetting strips it) is not drift\n if (isLogGroupArnWildcardMatch(d.stateValue, d.awsValue)) continue;\n // CFn stringly-typed scalar (Glue Parameters Map<String,String>, \"5432\" ports):\n // declared `true`/`5432` vs AWS `\"true\"`/`\"5432\"` is not drift.\n if (isStringlyEqualScalar(d.stateValue, d.awsValue)) continue;\n // CFn stringly-typed scalar ARRAY (R23): the drift-calculator emits the whole\n // array as one record, so the per-leaf check above can't see the elements of a\n // declared `[80, 443]` vs live `[\"80\", \"443\"]`. Same typed<->string collapse,\n // element-wise; a genuine element change still differs.\n if (isStringlyEqualScalarArray(d.stateValue, d.awsValue)) continue;\n // CFn free-form `Map<String,String>` (Glue Table Parameters, DockerLabels,\n // Lambda env Variables, map Tags) emitted WHOLE at its parent path because a\n // key holds a `.` — its values are all live STRINGS while CDK declares some\n // typed (boolean `projection.enabled`, numeric counts). Fold the whole-map\n // typed<->string coercion recursively; a real key add/remove or value change\n // still differs. Not Glue-specific — any whole-emitted free-form map.\n if (isStringlyEqualDeep(d.stateValue, d.awsValue)) continue;\n // A declared object whose live form is the same value as a JSON STRING\n // (R75: SSM Document.Content) — equal after parse, key-order-insensitive.\n if (isJsonStringStructEqual(d.stateValue, d.awsValue)) continue;\n // A PEM-armored value (R125: CloudFront PublicKey EncodedKey) that\n // round-trips with only surrounding-whitespace differences — AWS appends a\n // trailing newline after the END marker — is not drift.\n if (isPemEqual(d.stateValue, d.awsValue)) continue;\n // Per-type OpenSSH public-key paths (EC2 KeyPair PublicKeyMaterial — EC2\n // rewrites the comment field to the key pair name and appends a newline):\n // the same key material (type + base64) is not drift; a genuine key change\n // still differs.\n if (\n SSH_PUBLIC_KEY_PATHS[resourceType]?.has(d.path) &&\n isSshPublicKeyEqual(d.stateValue, d.awsValue)\n )\n continue;\n // Per-type Redis/Valkey ACL access-string paths (ElastiCache/MemoryDB User\n // AccessString via SDK_SUPPLEMENTS — #482): the service canonicalizes the\n // string on write by inserting a `-@all` baseline term, so the same ACL modulo\n // that term is not drift; a genuine grant/pattern change still differs.\n if (\n ACCESS_STRING_PATHS[resourceType]?.has(d.path) &&\n isAccessStringEqual(d.stateValue, d.awsValue)\n )\n continue;\n // Per-type Java `.properties` file paths (MSK Configuration ServerProperties via\n // SDK_SUPPLEMENTS — #508): line order / blank lines / comments / trailing newline are\n // cosmetic, so the same key=value set is not drift; a genuine key/value change differs.\n if (\n PROPERTIES_FILE_PATHS[resourceType]?.has(d.path) &&\n isPropertiesFileEqual(d.stateValue, d.awsValue)\n )\n continue;\n // RDS parameter-group Parameters map: a MySQL boolean system variable declared as\n // \"ON\"/\"OFF\" reads back as \"1\"/\"0\" (RDS canonicalizes on write). Fold only when both\n // sides are boolean tokens of the SAME truthiness — a genuine flip (ON vs 0) and a\n // non-boolean value still surface. Gated to the Parameters map's leaf paths.\n if (\n BOOLEAN_PARAM_MAP_PATHS[resourceType]?.has(d.path.split('.')[0] ?? '') &&\n d.path.includes('.') &&\n isBooleanTokenEquivalent(d.stateValue, d.awsValue)\n )\n continue;\n // CloudFormation's GetTemplate returns non-ASCII string literals with every\n // non-ASCII character replaced by `?` (a documented API limitation). The DECLARED\n // side (fetched via GetTemplate) is therefore corrupted while the LIVE side is\n // intact — a guaranteed false `declared` drift on every clean deploy (observed: an\n // SSM Parameter `Value: áéíóúABC` read back as desired `?????ABC`). When the\n // live value masked the same way equals the declared value, the declared value is\n // unknowable, so surface it as a readGap (declared-but-unverifiable) instead of a\n // false drift — same informational tier used for write-only declared props.\n if (isCfnTemplateNonAsciiMask(d.stateValue, d.awsValue)) {\n findings.push({\n tier: 'readGap',\n logicalId,\n resourceType,\n path: d.path,\n note: 'declared value unverifiable — CloudFormation GetTemplate masks non-ASCII characters as \"?\"',\n });\n continue;\n }\n // Per-type case-insensitive scalar paths (R75: Route53 AliasTarget.DNSName\n // — the ALB's generated DNS name is mixed-case declared, lowercase live). A `*`\n // in a table entry matches an array index: numeric path segments are normalized to\n // `*` before the lookup (e.g. `RedactedFields.0.SingleHeader.Name` -> `.*.`).\n if (\n (CASE_INSENSITIVE_PATHS[resourceType]?.has(d.path) ||\n CASE_INSENSITIVE_PATHS[resourceType]?.has(d.path.replace(/\\.\\d+(?=\\.|$)/g, '.*'))) &&\n isCaseInsensitiveScalarEqual(d.stateValue, d.awsValue)\n )\n continue;\n // Per-type case-insensitive HEADER-NAME array paths (apigwv2 CORS\n // AllowHeaders/ExposeHeaders — AWS lowercases header names): the same header\n // set modulo case/order is not drift; a genuine header add/remove still differs.\n if (\n CASE_INSENSITIVE_ARRAY_PATHS[resourceType]?.has(d.path) &&\n isCaseInsensitiveEqualScalarSet(d.stateValue, d.awsValue)\n )\n continue;\n // Per-type free-form map paths whose KEYS the Cloud Control read handler re-cases\n // (#494: DataBrew Recipe Steps[].Action.Parameters — the template + service carry\n // camelCase keys, but CC read remaps them onto the PascalCase RecipeParameters model):\n // the same map modulo key-case with equal values is not drift; a real key or value\n // change still differs. The table keys element segments with `[]`, so normalize the\n // drift path's numeric indices (`Steps.0.Action.Parameters`) to `[]` before the lookup.\n if (\n CASE_INSENSITIVE_KEY_PATHS[resourceType]?.has(d.path.replace(/\\.\\d+(?=\\.)/g, '[]')) &&\n isCaseInsensitiveKeyMapEqual(d.stateValue, d.awsValue)\n )\n continue;\n // Per-type rate() schedule-expression paths (Synthetics canary Schedule.Expression\n // — AWS rewrites `rate(60 minutes)` to `rate(1 hour)`): the same total duration is\n // not drift; a genuine interval change still differs.\n if (\n RATE_EXPRESSION_PATHS[resourceType]?.has(d.path) &&\n isEquivalentRateExpression(d.stateValue, d.awsValue)\n )\n continue;\n // Per-type epoch-seconds paths AWS rounds DOWN to the hour (AppSync ApiKey\n // Expires): the same hour is not drift; a change to a different hour still differs.\n if (EPOCH_HOUR_PATHS[resourceType]?.has(d.path) && isEpochHourEqual(d.stateValue, d.awsValue))\n continue;\n // Per-type DNS-FQDN paths whose trailing `.` is optional (Route53 HostedZone Name:\n // declared `example.com`, CC returns `example.com.`) — equal once stripped.\n if (\n TRAILING_DOT_PATHS[resourceType]?.has(d.path) &&\n isTrailingDotEqual(d.stateValue, d.awsValue)\n )\n continue;\n // Per-type paths whose trailing `/` is optional (ECR RepositoryCreationTemplate\n // Prefix: declared `cdkrd-hunt/`, service stores `cdkrd-hunt`) — equal once\n // stripped; a genuine prefix change still differs.\n if (\n TRAILING_SLASH_PATHS[resourceType]?.has(d.path) &&\n isTrailingSlashEqual(d.stateValue, d.awsValue)\n )\n continue;\n // Per-type version-track paths (R130: RDS DBInstance EngineVersion) — a declared\n // partial version (`\"8.0\"`) that AWS resolved to the full patch version it\n // provisioned (`\"8.0.45\"`) is not drift; a genuine track change still differs.\n if (\n VERSION_PREFIX_PATHS[resourceType]?.has(d.path) &&\n isVersionPrefixMatch(d.stateValue, d.awsValue)\n )\n continue;\n // Per-type `\"LATEST\"` sentinel paths (Fargate PlatformVersion) — a declared\n // `\"LATEST\"` that AWS resolved to the concrete current version is not drift; a\n // declared concrete version still compares so a genuine pin change differs.\n if (\n LATEST_SENTINEL_PATHS[resourceType]?.has(d.path) &&\n isLatestSentinelMatch(d.stateValue, d.awsValue)\n )\n continue;\n // Per-type Intelligent-Tiering paths (SSM Parameter Tier) — a declared\n // `\"Intelligent-Tiering\"` request that AWS resolved to the concrete tier it\n // provisioned (Standard/Advanced) is not drift; a real Standard↔Advanced change\n // still differs.\n if (\n INTELLIGENT_TIERING_PATHS[resourceType]?.has(d.path) &&\n isIntelligentTieringMatch(d.stateValue, d.awsValue)\n )\n continue;\n // Unordered scalar-array sets — same elements in the service's canonical order\n // is not drift; a genuine element change still differs after sorting. Two\n // sources: the per-type allowlist (R74: Cognito OAuth lists, and the many sets\n // AWS sorts that the schema marks insertionOrder:true) AND the schema-driven\n // `unorderedScalarPaths` (arrays AWS itself declares insertionOrder:false — no\n // table needed, FN-safe).\n if (\n (UNORDERED_ARRAY_PROPS[resourceType]?.has(d.path) ||\n // A `*` in a table entry matches an array index: numeric path segments are\n // normalized to `*` before the lookup (e.g. a CodePipeline trigger filter\n // `Triggers.0.GitConfiguration.Push.0.Branches.Includes` -> `Triggers.*.…Push.*.…`).\n UNORDERED_ARRAY_PROPS[resourceType]?.has(d.path.replace(/\\.\\d+(?=\\.|$)/g, '.*')) ||\n schema.unorderedScalarPaths?.includes(d.path)) &&\n isEqualUnorderedScalarSet(d.stateValue, d.awsValue)\n )\n continue;\n // A declared trivially-EMPTY value that the service materializes as its\n // documented default is not drift (R74: CDK Trail declares EventSelectors\n // [] and CloudTrail returns the default management selector). Equality-\n // gated on BOTH sides: the declared side must be empty (a real declared\n // value mismatch is never muted) and the live side must EQUAL the listed\n // default (any out-of-band change still surfaces).\n if (\n isTrivialEmpty(d.stateValue) &&\n d.path in knownDef &&\n deepEqual(d.awsValue, knownDef[d.path])\n )\n continue;\n findings.push({\n tier: 'declared',\n logicalId,\n resourceType,\n path: d.path,\n desired: d.stateValue,\n actual: d.awsValue,\n });\n }\n }\n\n // undeclared (A1/A2/A4 + identity suppression)\n for (const [k, v] of Object.entries(live)) {\n if (k in declared) continue;\n // A WHOLLY-undeclared ELB attribute bag (a Listener that declares no ListenerAttributes\n // reads back ~20 server-default attributes) — fold PER KEY like the declared-bag branch\n // above instead of emitting the whole array: an empty value is skipped, a value equal to\n // the curated AWS default folds `atDefault`, and anything else stays `undeclared` (so a\n // genuinely-set attribute still surfaces, fail-closed).\n if (k === ELB_ATTRIBUTE_BAGS[resourceType] && Array.isArray(v)) {\n // Same per-LB-type default resolution as the declared-bag branch above: an NLB/GWLB\n // whose LoadBalancerAttributes is WHOLLY undeclared reads back its type-specific\n // defaults (cross_zone \"false\", deletion_protection \"false\"), which the shared\n // application-oriented table does not carry — merge the BY_LB_TYPE overrides so they\n // fold `atDefault` instead of surfacing as false undeclared drift.\n const lbType =\n resourceType === 'AWS::ElasticLoadBalancingV2::LoadBalancer'\n ? String(live.Type ?? declared.Type ?? 'application')\n : undefined;\n const attrDefaults = {\n ...(ELB_ATTRIBUTE_DEFAULTS[resourceType] ?? {}),\n ...(lbType === undefined ? {} : (ELB_ATTRIBUTE_DEFAULTS_BY_LB_TYPE[lbType] ?? {})),\n };\n for (const lEl of v) {\n if (!isKeyValueEntry(lEl)) continue;\n const key = (lEl as { Key: string }).Key;\n const value = (lEl as { Value: unknown }).Value;\n if (isTrivialEmpty(value)) continue;\n const isDefault =\n key in attrDefaults &&\n (value === attrDefaults[key] || isStringlyEqualScalar(value, attrDefaults[key]));\n findings.push({\n tier: isDefault ? 'atDefault' : 'undeclared',\n logicalId,\n resourceType,\n path: `${k}[${key}]`,\n actual: value,\n nested: true,\n });\n }\n continue;\n }\n // NOTE: no `schema.writeOnly.has(k)` guard — a top-level write-only key was\n // already stripped from `live` by writeOnlyPaths above, so it cannot reach here\n // (the old guard was dead code for top-level keys).\n // A live value EQUAL to a known AWS default is the `atDefault` tier (R86): still\n // surfaced (folded, never dropped — the report shows the complete undeclared\n // count and --show-all/--verbose lists them), but informational, not drift, and\n // not recorded by record. The equality gate means an out-of-band change away from\n // the default no longer matches here and falls through to the `undeclared` tier.\n if (\n (k in schema.defaults && matchesKnownDefault(v, schema.defaults[k])) ||\n (k in knownDef && matchesKnownDefault(v, knownDef[k])) ||\n // A top-level key whose AWS default is NON-DETERMINISTIC (ECS\n // AvailabilityZoneRebalancing reads back ENABLED or DISABLED depending on the\n // service) — folded atDefault regardless of value: undeclared, so any value is\n // AWS's choice, not user intent.\n VALUE_INDEPENDENT_DEFAULT_TOPLEVEL_PATHS[resourceType]?.has(k)\n ) {\n findings.push({ tier: 'atDefault', logicalId, resourceType, path: k, actual: v });\n continue;\n }\n // A live value equal to its CONTEXT-DERIVED default — a default whose VALUE is\n // this resource's own read context (region), which a constant KNOWN_DEFAULTS\n // entry cannot express (a VPCEndpointService's SupportedRegions defaults to\n // [own region]). Equality-gated like every default fold; with no resolved\n // region it falls through to plain `undeclared` (recordable), never a wrong fold.\n const ctxKind = CONTEXT_DEFAULTS[resourceType]?.[k];\n if (ctxKind !== undefined && opts.region !== undefined) {\n const ctxDefault = ctxKind === 'region' ? opts.region : [opts.region];\n if (deepEqual(v, ctxDefault)) {\n findings.push({ tier: 'atDefault', logicalId, resourceType, path: k, actual: v });\n continue;\n }\n }\n // A live value EQUAL to its ENGINE-DERIVED default — an RDS default whose VALUE depends on\n // the resource's own live `Engine` (StorageType \"aurora\" for Aurora, Port 3306 for MySQL /\n // 5432 for Postgres, …), which a constant KNOWN_DEFAULTS entry cannot express. Equality-\n // gated with typed<->string coercion (a DBInstance echoes the port/storage as a string, a\n // DBCluster as a number); an engine with no single default, or a value that differs, falls\n // through to plain `undeclared` (recordable), never a wrong fold.\n const engineDefault = ENGINE_DEFAULTS[resourceType]?.[k];\n if (engineDefault !== undefined && typeof live.Engine === 'string') {\n const def = engineDefault(live.Engine);\n if (def !== undefined && (deepEqual(v, def) || isStringlyEqualScalar(v, def))) {\n findings.push({ tier: 'atDefault', logicalId, resourceType, path: k, actual: v });\n continue;\n }\n }\n // A live value that is an AWS-MANAGED default resource NAME, recognized by its reserved\n // `default.` / `default:` prefix (an RDS instance's default parameter/option group) rather\n // than a constant — a CUSTOM group name never carries the prefix, so it still surfaces.\n const namePattern = DEFAULT_MANAGED_NAME_PATHS[resourceType]?.[k];\n if (namePattern !== undefined && typeof v === 'string' && namePattern.test(v)) {\n findings.push({ tier: 'atDefault', logicalId, resourceType, path: k, actual: v });\n continue;\n }\n // A live value EQUAL to the AWS/CDK-generated value for this resource (its minted\n // physical name, a default-named log group) is the `generated` tier: folded\n // inventory like atDefault, never drift, never recorded. Equality-gated against\n // the physical-id-substituted template, so an out-of-band edit (a different\n // LogFormat, say) no longer matches and falls through to `undeclared` below.\n if (k in genDef && deepEqual(v, genDef[k])) {\n findings.push({ tier: 'generated', logicalId, resourceType, path: k, actual: v });\n continue;\n }\n // R107: a scalar value that IS this resource's generated NAME from an ARN physical\n // id (the ARN's name segment — a topic's TopicName, a state machine's\n // StateMachineName) is the same `generated` tier — folded, never drift, never\n // recorded — for ANY type, without a per-type GENERATED_DEFAULTS entry. The bare\n // physical-id echo (value === physicalId) is left to the structural drop below.\n if (isGeneratedName(v, physicalId)) {\n findings.push({ tier: 'generated', logicalId, resourceType, path: k, actual: v });\n continue;\n }\n // A CloudFormation AUTO-GENERATED physical name: when a resource declares no explicit\n // name, CFn mints `<stackName>-<logicalId>-<random>` (e.g. a Route53Resolver\n // FirewallDomainList's `Name` reads \"MyStack-DL-uaPlN2cdWoMb\" while its physical id is the\n // unrelated `rslvr-fdl-…`, so isGeneratedName above can't catch it). Fold it `generated`\n // so an auto-named resource is not first-run noise. Tightly gated to avoid hiding a REAL\n // undeclared value (the differentiator): the value must start with THIS stack's name AND\n // end with CFn's random suffix — a user-chosen name realistically never matches both.\n if (isCfnGeneratedName(v, resource.constructPath, physicalId, logicalId)) {\n findings.push({ tier: 'generated', logicalId, resourceType, path: k, actual: v });\n continue;\n }\n // A curated `<logicalId>-<random>` generated-name form (no `<stack>-` prefix) that the\n // isCfnGeneratedName branches miss — scoped by type+path to avoid over-folding a short\n // raw-CFn logical id's genuine undeclared names (GENERATED_LOGICALID_PREFIX_PATHS). Value-\n // dependent: an undeclared user-SET name (no logical-id prefix) still surfaces as drift.\n if (\n GENERATED_LOGICALID_PREFIX_PATHS[resourceType]?.has(k) &&\n isLogicalIdPrefixedGeneratedName(v, logicalId)\n ) {\n findings.push({ tier: 'generated', logicalId, resourceType, path: k, actual: v });\n continue;\n }\n // Cloud Control MIS-POPULATES a field by echoing a sibling: AWS::EC2::Route's\n // `VpcEndpointId` reflects the route's GATEWAY target (`igw-…`/`nat-…`/`tgw-…`) on a\n // NON-endpoint route — a value the template never set, duplicated from GatewayId. A REAL\n // VPC-endpoint route's VpcEndpointId is `vpce-…` (and declared). Drop the mis-echo so a\n // public-subnet route table is not first-run noise. (Proven live: an IGW default route\n // reads back VpcEndpointId === GatewayId === `igw-…`.)\n if (\n resourceType === 'AWS::EC2::Route' &&\n k === 'VpcEndpointId' &&\n typeof v === 'string' &&\n !v.startsWith('vpce-')\n )\n continue;\n // CC echoed an ALTERNATIVE representation of a declared value (e.g. a Subnet's\n // AvailabilityZoneId for the declared AvailabilityZone) — drop it (see CC_ALT_REPRESENTATION).\n const altSibling = CC_ALT_REPRESENTATION[resourceType]?.[k];\n if (altSibling !== undefined && altSibling in declared) continue;\n // A top-level key that is ALWAYS a service-minted generated id (value-independent):\n // the ApiGatewayV2 AutoDeploy Stage's DeploymentId, re-minted on every auto-deploy\n // and un-settable. Folded as `generated` (never drift, recorded, or reverted) so it\n // does not churn into false undeclared drift after any out-of-band API edit.\n if (GENERATED_TOPLEVEL_PATHS[resourceType]?.has(k)) {\n findings.push({ tier: 'generated', logicalId, resourceType, path: k, actual: v });\n continue;\n }\n // Pure structural noise (NOT a config value at default) — dropped outright: AWS\n // managed `aws:*` tags, the resource's own physical id echoed back as a property,\n // and trivially-empty {}/[]. These carry no inventory value, so they are not folded.\n if (isAllAwsTags(v)) continue;\n if (physicalId !== undefined && v === physicalId) continue;\n if (isTrivialEmpty(v) || isSelfEchoTrivialEmpty(v, physicalId) || isEmptyPolicyShell(v))\n continue;\n // #555: a FULLY-undeclared OBJECT listed in DESCEND_UNDECLARED_OBJECT_PATHS is descended\n // leaf-by-leaf (via the SAME emitNested classification the declared-nested loop uses)\n // instead of surfacing whole — its constant sub-keys fold (atDefault / generated /\n // trivially-empty) and only the non-default residue surfaces (nested, at `k.sub`). Curated\n // per (type, path) so objects with no foldable defaults are never fragmented into noise.\n if (isNestedObject(v) && DESCEND_UNDECLARED_OBJECT_PATHS[resourceType]?.has(k)) {\n collectNestedUndeclared({}, v, k, emitNested, NESTED_ARRAY_IDENTITY[resourceType]);\n continue;\n }\n findings.push({ tier: 'undeclared', logicalId, resourceType, path: k, actual: v });\n }\n\n // Nested undeclared (R96): the Cloud Control read returns the FULL live model, so a\n // live SUB-key inside a DECLARED object that the template never set is just as\n // undeclared as a top-level one — recurse the declared∩live objects and emit each\n // live-only nested key (dotted path). Same noise suppression as the top-level loop\n // (trivially-empty / aws:* tags). These flow through the usual undeclared→baseline\n // machinery, just `nested`-flagged so the report can fold them (the live model\n // carries many nested AWS defaults): folded inventory on a first run, recorded by\n // record, and a later out-of-band change to one surfaces as drift vs the baseline.\n // R103: a nested value EQUAL to the schema's `default` at that path is the\n // `atDefault` tier (mirrors the top-level atDefault), so config-dense types stop\n // drowning the report in materialized defaults. Live array-element paths carry the\n // element identity (`Prop[<id>].sub`); the schema keys it with a `*` wildcard, so\n // normalize `[<id>]` -> `.*` before the lookup. Equality-gated: a value changed\n // AWAY from its default no longer matches and falls back to `undeclared`. The leaf\n // classification lives in the shared `emitNested` closure (defined above, also used by\n // the fully-undeclared-object descend #555).\n for (const [k, dv] of Object.entries(declared)) {\n // Only skip a WHOLLY-unresolved property: collectNestedUndeclared descends to emit\n // LIVE-only keys, and an UNRESOLVED declared leaf is inert there (isNestedObject/\n // Array both false → no recursion, no emit). So a property that merely CONTAINS an\n // unresolved sub-value (e.g. Environment.Variables with one GetAtt) can still be\n // descended to surface a genuinely undeclared sibling sub-key — dropping the old\n // `hasUnresolved(dv)` guard, which hid that whole class (FP-safe: unresolved subtrees\n // simply aren't descended).\n if (dv === UNRESOLVED || !(k in live)) continue;\n // A JSON-string property (ConfigRule InputParameters) is compared and reported as a\n // WHOLE UNIT in the declared loop above — never descend into it for nested undeclared\n // sub-keys, which would emit a fragile dotted finding the revert can't target.\n if (JSON_STRING_PROPS[resourceType]?.has(k)) continue;\n collectNestedUndeclared(dv, live[k], k, emitNested, NESTED_ARRAY_IDENTITY[resourceType]);\n }\n\n // attach physicalId (for revert) + construct path (display) onto every finding\n const cp = resource.constructPath;\n const pid = resource.physicalId;\n // R111 fail-open carries a revert hazard: when the principal's sibling AWS::IAM::Policy\n // names were UNRESOLVED we did NOT filter the sibling-managed (DefaultPolicy)\n // entries out of the live Policies array (above), so a declared `Policies` diff\n // here lists own + sibling-managed entries together. The per-entry revert writer\n // deletes every prior entry the declared set drops — which would DELETE the\n // sibling-managed inline policy, removing real IAM grants. We cannot separate them,\n // so mark the Policies finding(s) so the revert plan refuses to act (a wrong-write to\n // live IAM is worse than an un-reverted FP). Applies to Role / User / Group alike.\n const unresolvedSibling =\n IAM_PRINCIPAL_POLICY_TYPES.has(resourceType) && resource.siblingPolicyNames === 'unresolved';\n return findings.map((f) => ({\n ...f,\n ...(pid !== undefined && { physicalId: pid }),\n ...(cp !== undefined && { constructPath: cp }),\n ...(unresolvedSibling && (f.path.split(/[.[]/)[0] ?? f.path) === 'Policies'\n ? { siblingPolicyNames: 'unresolved' as const }\n : {}),\n }));\n}\n","// Shared AWS SDK client retry config for cdkrd's READ path — applied to EVERY\n// read-side client: the Cloud Control / CloudFormation clients in gather.ts, all\n// SDK-override clients in overrides.ts, AND the KMS client in kms-aliases.ts.\n// `check` reads every resource in a stack with bounded concurrency (gather.ts POOL_SIZE), which on a\n// large stack (hundreds of resources) drives Cloud Control GetResource /\n// CloudFormation describe-type / the SDK-override APIs straight into\n// ThrottlingException. The SDK default (`standard` mode, maxAttempts=3) is not\n// enough headroom, so a throttled read was being reported as `skipped` — silent\n// coverage loss + noise. `adaptive` mode adds a client-side rate limiter (it backs\n// off the whole client when it sees throttling) and a higher attempt budget rides\n// out transient throttles. Reads are idempotent, so retrying is always safe.\nexport const READ_RETRY = {\n maxAttempts: 10,\n retryMode: 'adaptive' as const,\n};\n","// Resolve AWS-managed KMS aliases (`alias/aws/<service>`) to their concrete target\n// key id, so the classifier can tell a managed-default key (declared as the alias,\n// stored by AWS as the key ARN) apart from a customer-managed key swapped in out of\n// band — the latter is a real, security-relevant drift the shape-only check missed.\n// Listing aliases is account-wide, so one paginated ListAliases per region is enough;\n// cached per region. On any error (e.g. missing kms:ListAliases) returns `denied: true`\n// with empty targets so the classifier falls back to the conservative shape-based match\n// (noise, not false drift) — but the caller WARNS, because that fallback is blind to a\n// customer-key swap (it suppresses every `alias/aws/*` vs key-ARN pair). The result\n// (success OR denial) is cached so a denied region is not re-queried per stack.\nimport { KMSClient, ListAliasesCommand } from '@aws-sdk/client-kms';\nimport { READ_RETRY } from './client-config.js';\n\nexport interface ManagedAliasTargets {\n targets: Record<string, string>; // alias/aws/<svc> -> target key id\n denied: boolean; // true when ListAliases failed (e.g. missing kms:ListAliases)\n}\n\nconst cache = new Map<string, ManagedAliasTargets>();\n\nexport async function fetchManagedAliasTargets(region: string): Promise<ManagedAliasTargets> {\n const cached = cache.get(region);\n if (cached) return cached;\n const targets: Record<string, string> = {};\n let result: ManagedAliasTargets;\n try {\n const c = new KMSClient({ region, ...READ_RETRY });\n let marker: string | undefined;\n do {\n const r = await c.send(new ListAliasesCommand({ Marker: marker, Limit: 100 }));\n for (const a of r.Aliases ?? []) {\n if (a.AliasName?.startsWith('alias/aws/') && a.TargetKeyId)\n targets[a.AliasName] = a.TargetKeyId;\n }\n marker = r.Truncated ? r.NextMarker : undefined;\n } while (marker);\n result = { targets, denied: false };\n } catch {\n // no kms:ListAliases (or any error) → fall back to shape-based suppression\n result = { targets: {}, denied: true };\n }\n cache.set(region, result);\n return result;\n}\n\n/** The one-line warning emitted when ListAliases is denied but the stack declares an\n * AWS-managed alias: the managed-vs-customer key check degrades to shape-only, which\n * is BLIND to a customer-managed key swapped in for an `alias/aws/*` default. Pure +\n * exported so the wording is unit-tested. */\nexport function kmsListAliasesDeniedWarning(region: string): string {\n return (\n `warning: ${region}: kms:ListAliases denied — managed-KMS-alias drift detection is degraded. ` +\n `A customer-managed key swapped in for an AWS-managed default (alias/aws/*) will NOT be detected ` +\n `(every alias/aws/* is treated as matching any live key). Grant kms:ListAliases for full coverage.`\n );\n}\n\n/** True when any resolved declared value in the stack references an AWS-managed KMS\n * alias, i.e. a ListAliases prefetch is worth doing. */\nexport function usesManagedKmsAlias(v: unknown): boolean {\n if (typeof v === 'string') return v.startsWith('alias/aws/');\n if (Array.isArray(v)) return v.some(usesManagedKmsAlias);\n if (v && typeof v === 'object') return Object.values(v).some(usesManagedKmsAlias);\n return false;\n}\n","// Added-resource detection (the resource-granularity sibling of undeclared):\n// for a DECLARED \"parent\" resource, enumerate its LIVE child resources and flag any\n// that are NOT in the deployed template — a whole resource created out of band (e.g.\n// an API Gateway Method added on the root `/` via the console). The per-type code is\n// ONLY the child enumeration; the resulting `added` findings carry a Cloud Control\n// identifier so a later `revert` can DeleteResource them generically (no per-type\n// writer). Mirrors the SDK_OVERRIDES registry shape (one entry per parent type).\n//\n// Enumeration uses the SERVICE SDK, not Cloud Control ListResources: CC ListResources\n// is UnsupportedAction for AWS::ApiGateway::Resource/Method (verified live), so a\n// CC-based scan silently read back nothing. The same CC-gap reason SDK_OVERRIDES\n// exists for reads. CC GetResource/DeleteResource on these types DO work, so the\n// `identifier` stays the CC composite (`RestApiId|ResourceId[|HttpMethod]`) — that is\n// what revert's DeleteResource consumes.\nimport {\n APIGatewayClient,\n type Authorizer as ApiGwAuthorizer,\n type GatewayResponse as ApiGwGatewayResponse,\n GetAuthorizersCommand,\n GetGatewayResponsesCommand,\n GetModelsCommand,\n GetRequestValidatorsCommand,\n GetResourcesCommand,\n type Model as ApiGwModel,\n type RequestValidator as ApiGwRequestValidator,\n type Resource as ApiGwResource,\n} from '@aws-sdk/client-api-gateway';\nimport {\n AppConfigClient,\n type ConfigurationProfileSummary as AppConfigConfigurationProfile,\n type Environment as AppConfigEnvironment,\n ListConfigurationProfilesCommand,\n ListEnvironmentsCommand,\n} from '@aws-sdk/client-appconfig';\nimport {\n AppSyncClient,\n type DataSource as AppSyncDataSource,\n type FunctionConfiguration as AppSyncFunctionConfiguration,\n ListDataSourcesCommand,\n ListFunctionsCommand as ListAppSyncFunctionsCommand,\n ListResolversCommand,\n ListTypesCommand,\n type Resolver as AppSyncResolver,\n} from '@aws-sdk/client-appsync';\nimport {\n ApiGatewayV2Client,\n type Authorizer as ApiGwV2Authorizer,\n GetAuthorizersCommand as GetV2AuthorizersCommand,\n GetIntegrationsCommand,\n GetRoutesCommand,\n GetStagesCommand,\n type Integration as ApiGwV2Integration,\n type Route as ApiGwV2Route,\n type Stage as ApiGwV2Stage,\n} from '@aws-sdk/client-apigatewayv2';\nimport {\n CloudWatchLogsClient,\n DescribeMetricFiltersCommand,\n DescribeSubscriptionFiltersCommand,\n type MetricFilter as CwlMetricFilter,\n type SubscriptionFilter as CwlSubscriptionFilter,\n} from '@aws-sdk/client-cloudwatch-logs';\nimport {\n CognitoIdentityProviderClient,\n type GroupType,\n ListGroupsCommand,\n ListResourceServersCommand,\n ListUserPoolClientsCommand,\n type ResourceServerType,\n type UserPoolClientDescription,\n} from '@aws-sdk/client-cognito-identity-provider';\nimport {\n DescribeRouteTablesCommand,\n DescribeSubnetsCommand,\n EC2Client,\n type Route as Ec2Route,\n type Subnet as Ec2Subnet,\n} from '@aws-sdk/client-ec2';\nimport { ECSClient, ListServicesCommand } from '@aws-sdk/client-ecs';\nimport {\n DescribeMountTargetsCommand,\n EFSClient,\n type MountTargetDescription,\n} from '@aws-sdk/client-efs';\nimport {\n DescribeListenersCommand,\n DescribeRulesCommand,\n ElasticLoadBalancingV2Client,\n type Listener as Elbv2Listener,\n type Rule as Elbv2Rule,\n} from '@aws-sdk/client-elastic-load-balancing-v2';\nimport {\n EventBridgeClient,\n ListRulesCommand,\n type Rule as EventBridgeRule,\n} from '@aws-sdk/client-eventbridge';\nimport { type AliasListEntry, KMSClient, ListAliasesCommand } from '@aws-sdk/client-kms';\nimport {\n type AliasConfiguration as LambdaAliasConfiguration,\n type EventSourceMappingConfiguration,\n type FunctionConfiguration as LambdaVersionConfiguration,\n type FunctionUrlConfig,\n LambdaClient,\n ListAliasesCommand as ListLambdaAliasesCommand,\n ListEventSourceMappingsCommand,\n ListFunctionUrlConfigsCommand,\n ListVersionsByFunctionCommand,\n} from '@aws-sdk/client-lambda';\nimport {\n type DBInstance as RdsDBInstance,\n DescribeDBInstancesCommand,\n RDSClient,\n} from '@aws-sdk/client-rds';\nimport {\n ListSubscriptionsByTopicCommand,\n SNSClient,\n type Subscription as SnsSubscription,\n} from '@aws-sdk/client-sns';\nimport { READ_RETRY } from './client-config.js';\nimport type { Desired } from '../desired/template-adapter.js';\nimport type { DesiredResource } from '../types.js';\n\n// One out-of-band child resource: present live, absent from the template.\nexport interface AddedChild {\n resourceType: string; // CC TypeName of the child (e.g. AWS::ApiGateway::Method)\n identifier: string; // CC primaryIdentifier — feeds GetResource / DeleteResource (revert)\n label: string; // human display (e.g. 'ANY /', '/widgets')\n live: Record<string, unknown>; // live model snippet, for the report `actual`\n}\n\nexport interface EnumeratorContext {\n parent: DesiredResource; // the declared parent (its physicalId is the live parent id)\n desired: Desired; // full desired view — declared children + parent live attrs\n region: string;\n}\n\nexport type ChildEnumerator = (ctx: EnumeratorContext) => Promise<AddedChild[]>;\n\n// Registry: declared parent TYPE -> child enumerator. Grown one type at a time,\n// exactly like SDK_OVERRIDES. API Gateway REST APIs were the first member; API Gateway\n// V2 (HTTP / WebSocket) APIs the second; SNS Topics (subscriptions) the third; Lambda\n// Functions (event source mappings) the fourth; EventBridge event buses (rules) the fifth;\n// Cognito User Pools (clients) the sixth; AppSync GraphQL APIs (data sources) the seventh;\n// CloudWatch Logs log groups (metric filters) the eighth; Elastic Load Balancing v2 load\n// balancers (listeners) the ninth; EC2 VPCs (subnets) the tenth; EC2 route tables\n// (routes) the eleventh; ECS clusters (services) the twelfth; KMS keys (aliases) the\n// thirteenth; AppConfig applications (environments) the fourteenth; Elastic Load Balancing\n// v2 listeners (rules) the fifteenth; EFS file systems (mount targets) the sixteenth;\n// RDS DB clusters (DB instances) the seventeenth.\nexport const CHILD_ENUMERATORS: Record<string, ChildEnumerator> = {\n 'AWS::ApiGateway::RestApi': enumerateRestApiChildren,\n 'AWS::ApiGatewayV2::Api': enumerateHttpApiChildren,\n 'AWS::SNS::Topic': enumerateSnsTopicChildren,\n 'AWS::Lambda::Function': enumerateLambdaFunctionChildren,\n 'AWS::Events::EventBus': enumerateEventBusChildren,\n 'AWS::Cognito::UserPool': enumerateUserPoolChildren,\n 'AWS::AppSync::GraphQLApi': enumerateGraphQLApiChildren,\n 'AWS::Logs::LogGroup': enumerateLogGroupChildren,\n 'AWS::ElasticLoadBalancingV2::LoadBalancer': enumerateLoadBalancerChildren,\n 'AWS::ElasticLoadBalancingV2::Listener': enumerateListenerChildren,\n 'AWS::EC2::VPC': enumerateVpcChildren,\n 'AWS::EC2::RouteTable': enumerateRouteTableChildren,\n 'AWS::ECS::Cluster': enumerateEcsClusterChildren,\n 'AWS::KMS::Key': enumerateKmsKeyChildren,\n 'AWS::AppConfig::Application': enumerateAppConfigApplicationChildren,\n 'AWS::EFS::FileSystem': enumerateEfsFileSystemChildren,\n 'AWS::RDS::DBCluster': enumerateRdsClusterChildren,\n};\n\n// ── API Gateway ────────────────────────────────────────────────────────────\n// A RestApi owns Resources (paths), Methods, Authorizers, Models, and\n// RequestValidators. Each is a separate\n// CloudFormation resource, so the template lists every declared one; anything live\n// but undeclared is an out-of-band addition. The root resource `/` is implicit\n// (created with the RestApi) and so always counts as declared. A console / CLI\n// `create-authorizer` (someone wires a new TOKEN / REQUEST / COGNITO_USER_POOLS\n// authorizer onto the api out of band — a security-relevant change) is invisible to\n// cdk drift / CFn drift detection. The RestApi's own live model does NOT reflect its\n// authorizers inline, so there is no double-report to suppress. The CC\n// primaryIdentifier for AWS::ApiGateway::Authorizer is the composite\n// `[\"/properties/RestApiId\",\"/properties/AuthorizerId\"]`, so the `identifier` is the\n// composite `RestApiId|AuthorizerId` (RestApiId first) — that is what CC\n// GetResource / DeleteResource consume.\n\n// Pure diff: given the declared child sets and the live inventory, return the added\n// children. Separated from the SDK calls so the matching logic is unit-tested offline.\nexport interface ApiGatewayChildInput {\n apiId: string;\n rootResourceId?: string | undefined; // RestApi.RootResourceId (the `/` resource)\n declaredResourceIds: string[]; // physical ids of AWS::ApiGateway::Resource in the template\n declaredMethodKeys: string[]; // `${resourceId}|${httpMethod}` for each declared Method\n liveResources: { id: string; path?: string | undefined; live?: Record<string, unknown> }[];\n // resourceId -> live methods on it. Keyed so an added resource's methods are not\n // double-reported (we skip method scanning on a resource that is itself added).\n liveMethodsByResource: Record<string, { httpMethod: string; live?: Record<string, unknown> }[]>;\n}\n\nexport function diffApiGatewayChildren(input: ApiGatewayChildInput): AddedChild[] {\n const {\n apiId,\n rootResourceId,\n declaredResourceIds,\n declaredMethodKeys,\n liveResources,\n liveMethodsByResource,\n } = input;\n // Declared = template resources + the implicit root. The root `/` resource is ALWAYS\n // created with the RestApi and is never an \"added\" out-of-band resource. Identify it\n // by its LIVE path '/' (authoritative) IN ADDITION to rootResourceId — the latter\n // comes from the RestApi's CC read (liveAttrs), which may be skipped / throttled /\n // missing the attr, leaving rootResourceId undefined. Without the path fallback the\n // live root would then be flagged `added`, and a `revert` would issue DeleteResource\n // against the API's ROOT resource — a destructive false positive.\n const liveRootId = liveResources.find((r) => r.path === '/')?.id;\n const declaredResources = new Set(declaredResourceIds);\n if (rootResourceId) declaredResources.add(rootResourceId);\n if (liveRootId) declaredResources.add(liveRootId);\n const declaredMethods = new Set(declaredMethodKeys);\n\n const pathOf = new Map<string, string>();\n for (const r of liveResources) pathOf.set(r.id, r.path ?? r.id);\n if (rootResourceId && !pathOf.has(rootResourceId)) pathOf.set(rootResourceId, '/');\n\n const added: AddedChild[] = [];\n const addedResourceIds = new Set<string>();\n for (const r of liveResources) {\n if (declaredResources.has(r.id)) continue;\n addedResourceIds.add(r.id);\n added.push({\n resourceType: 'AWS::ApiGateway::Resource',\n identifier: `${apiId}|${r.id}`,\n label: pathOf.get(r.id) ?? r.id,\n live: r.live ?? {},\n });\n }\n\n // Methods: a method on a resource that is ITSELF added comes with that resource —\n // report only the resource. On every other (declared or root) resource, an\n // undeclared method is its own added finding.\n for (const [resourceId, methods] of Object.entries(liveMethodsByResource)) {\n if (addedResourceIds.has(resourceId)) continue;\n // When rootResourceId is unresolved (RestApi read incomplete), the template's\n // root-method ResourceId (Fn::GetAtt RootResourceId) couldn't resolve, so\n // declaredMethodKeys is missing the root's DECLARED methods — skip method-diffing\n // the live root to avoid falsely flagging a declared root method as added.\n if (!rootResourceId && resourceId === liveRootId) continue;\n for (const m of methods) {\n if (declaredMethods.has(`${resourceId}|${m.httpMethod}`)) continue;\n added.push({\n resourceType: 'AWS::ApiGateway::Method',\n identifier: `${apiId}|${resourceId}|${m.httpMethod}`,\n label: `${m.httpMethod} ${pathOf.get(resourceId) ?? resourceId}`,\n live: m.live ?? {},\n });\n }\n }\n return added;\n}\n\n// Page GetResources (embed=methods returns every resource AND its methods in one\n// paginated sweep — the root `/` resource included, so a method on root is caught).\nasync function getAllResources(client: APIGatewayClient, apiId: string): Promise<ApiGwResource[]> {\n const out: ApiGwResource[] = [];\n let position: string | undefined;\n do {\n const res = await client.send(\n new GetResourcesCommand({ restApiId: apiId, embed: ['methods'], limit: 500, position })\n );\n out.push(...(res.items ?? []));\n position = res.position;\n } while (position);\n return out;\n}\n\nasync function enumerateRestApiChildren(ctx: EnumeratorContext): Promise<AddedChild[]> {\n const { parent, desired, region } = ctx;\n const apiId = parent.physicalId;\n if (!apiId) return [];\n\n // RootResourceId is a readOnly attr already returned by the RestApi's CC read\n // (gather populated liveAttrs in pass 1); used to mark the `/` resource implicitly\n // declared even though GetResources also returns it.\n const restApiLive = desired.ctx.liveAttrs[parent.logicalId] ?? {};\n const rootResourceId =\n typeof restApiLive.RootResourceId === 'string' ? restApiLive.RootResourceId : undefined;\n\n // Declared children of THIS api (Ref/GetAtt already resolved to physical ids by gather).\n const declaredResourceIds: string[] = [];\n const declaredMethodKeys: string[] = [];\n for (const r of desired.resources) {\n if (r.declared.RestApiId !== apiId) continue;\n if (r.resourceType === 'AWS::ApiGateway::Resource' && r.physicalId) {\n declaredResourceIds.push(r.physicalId);\n } else if (r.resourceType === 'AWS::ApiGateway::Method') {\n const rid = r.declared.ResourceId;\n const hm = r.declared.HttpMethod;\n if (typeof rid === 'string' && typeof hm === 'string') {\n declaredMethodKeys.push(`${rid}|${hm}`);\n }\n }\n }\n\n // Declared authorizers of THIS api. An Authorizer's CFn physical id (Ref) IS its\n // AuthorizerId, and its declared RestApiId resolves (via gather) to the physical id.\n const declaredAuthorizerIds: string[] = [];\n // Declared models of THIS api. A Model's CFn physical id (Ref) IS its Name.\n const declaredModelNames: string[] = [];\n // Declared request validators of THIS api. A RequestValidator's CFn physical id (Ref)\n // IS its RequestValidatorId.\n const declaredValidatorIds: string[] = [];\n // Declared gateway responses of THIS api, matched by ResponseType.\n const declaredResponseTypes: string[] = [];\n for (const r of desired.resources) {\n if (\n r.resourceType === 'AWS::ApiGateway::Authorizer' &&\n r.declared.RestApiId === apiId &&\n r.physicalId\n ) {\n declaredAuthorizerIds.push(r.physicalId);\n } else if (r.resourceType === 'AWS::ApiGateway::Model' && r.declared.RestApiId === apiId) {\n const name = typeof r.declared.Name === 'string' ? r.declared.Name : r.physicalId;\n if (name) declaredModelNames.push(name);\n } else if (\n r.resourceType === 'AWS::ApiGateway::RequestValidator' &&\n r.declared.RestApiId === apiId &&\n r.physicalId\n ) {\n declaredValidatorIds.push(r.physicalId);\n } else if (\n r.resourceType === 'AWS::ApiGateway::GatewayResponse' &&\n r.declared.RestApiId === apiId &&\n typeof r.declared.ResponseType === 'string'\n ) {\n declaredResponseTypes.push(r.declared.ResponseType);\n }\n }\n\n const client = new APIGatewayClient({ region, ...READ_RETRY });\n const items = await getAllResources(client, apiId);\n const liveResources = items\n .filter((i): i is ApiGwResource & { id: string } => typeof i.id === 'string')\n .map((i) => ({ id: i.id, path: i.path, live: { Path: i.path, PathPart: i.pathPart } }));\n const liveMethodsByResource: Record<\n string,\n { httpMethod: string; live?: Record<string, unknown> }[]\n > = {};\n for (const i of items) {\n if (typeof i.id !== 'string') continue;\n liveMethodsByResource[i.id] = Object.keys(i.resourceMethods ?? {}).map((httpMethod) => ({\n httpMethod,\n live: { HttpMethod: httpMethod, ResourceId: i.id, Path: i.path },\n }));\n }\n\n const resourceAndMethodAdded = diffApiGatewayChildren({\n apiId,\n rootResourceId,\n declaredResourceIds,\n declaredMethodKeys,\n liveResources,\n liveMethodsByResource,\n });\n\n const authorizers = await getAllAuthorizers(client, apiId);\n const liveAuthorizers = authorizers\n .filter((a): a is ApiGwAuthorizer & { id: string } => typeof a.id === 'string')\n .map((a) => ({ id: a.id, label: a.name ?? a.id }));\n const authorizerAdded = diffApiGatewayAuthorizers({\n apiId,\n declaredAuthorizerIds,\n liveAuthorizers,\n });\n\n const models = await getAllModels(client, apiId);\n const liveModels = models\n .filter((m): m is ApiGwModel & { name: string } => typeof m.name === 'string')\n .map((m) => ({ name: m.name, label: m.name }));\n const modelAdded = diffApiGatewayModels({ apiId, declaredModelNames, liveModels });\n\n const validators = await getAllRequestValidators(client, apiId);\n const liveValidators = validators\n .filter((v): v is ApiGwRequestValidator & { id: string } => typeof v.id === 'string')\n .map((v) => ({ id: v.id, label: v.name ?? v.id }));\n const validatorAdded = diffApiGatewayRequestValidators({\n apiId,\n declaredValidatorIds,\n liveValidators,\n });\n\n const gatewayResponses = await getAllGatewayResponses(client, apiId);\n const liveResponseTypes = gatewayResponses\n .filter(\n (g): g is ApiGwGatewayResponse & { responseType: string } =>\n typeof g.responseType === 'string'\n )\n .map((g) => ({ type: g.responseType, label: g.responseType }));\n const gatewayResponseAdded = diffApiGatewayGatewayResponses({\n apiId,\n declaredResponseTypes,\n liveResponseTypes,\n });\n\n return [\n ...resourceAndMethodAdded,\n ...authorizerAdded,\n ...modelAdded,\n ...validatorAdded,\n ...gatewayResponseAdded,\n ];\n}\n\n// Pure diff: declared authorizer ids + live inventory -> the added authorizers.\n// Separated from the SDK calls so the matching logic is unit-tested offline.\nexport interface ApiGatewayAuthorizerInput {\n apiId: string;\n declaredAuthorizerIds: string[]; // physical ids (AuthorizerIds) of AWS::ApiGateway::Authorizer\n liveAuthorizers: { id: string; label?: string | undefined }[];\n}\n\nexport function diffApiGatewayAuthorizers(input: ApiGatewayAuthorizerInput): AddedChild[] {\n const { apiId, declaredAuthorizerIds, liveAuthorizers } = input;\n const declared = new Set(declaredAuthorizerIds);\n const added: AddedChild[] = [];\n for (const a of liveAuthorizers) {\n if (declared.has(a.id)) continue;\n added.push({\n resourceType: 'AWS::ApiGateway::Authorizer',\n identifier: `${apiId}|${a.id}`, // CC composite RestApiId|AuthorizerId\n label: a.label ?? a.id,\n live: { AuthorizerId: a.id, RestApiId: apiId },\n });\n }\n return added;\n}\n\n// Page GetAuthorizers (position-paginated like GetResources).\nasync function getAllAuthorizers(\n client: APIGatewayClient,\n apiId: string\n): Promise<ApiGwAuthorizer[]> {\n const out: ApiGwAuthorizer[] = [];\n let position: string | undefined;\n do {\n const res = await client.send(\n new GetAuthorizersCommand({ restApiId: apiId, limit: 500, position })\n );\n out.push(...(res.items ?? []));\n position = res.position;\n } while (position);\n return out;\n}\n\n// A RestApi also owns Models (request/response body schemas) and RequestValidators\n// (per-method body/parameter validation rules), each a separate CloudFormation resource.\n// A console / CLI `create-model` / `create-request-validator` (someone wires a new model\n// or validator onto an api out of band) is invisible to cdk drift / CFn drift detection.\n// The RestApi's own live model does NOT reflect its models or validators inline, so there\n// is no double-report to suppress. The CC primaryIdentifier for AWS::ApiGateway::Model is\n// the composite `[\"/properties/RestApiId\",\"/properties/Name\"]` (identifier `RestApiId|Name`)\n// and for AWS::ApiGateway::RequestValidator the composite\n// `[\"/properties/RestApiId\",\"/properties/RequestValidatorId\"]` (identifier\n// `RestApiId|RequestValidatorId`) — that is what CC GetResource / DeleteResource consume.\n// NOTE: every RestApi ships two built-in default models (`Empty`, `Error`) auto-created\n// by AWS with the api; they appear live on EVERY RestApi but are never template\n// resources, so a clean no-change deploy would otherwise surface them as `added` on\n// every run. Like the implicit root `/` resource, the GatewayResponse defaults\n// (`defaultResponse: true`), and the ELBv2 listener default rule (`IsDefault`), they\n// are AWS-generated built-ins and are filtered out below rather than left for `record`.\nconst BUILTIN_MODEL_NAMES = new Set(['Empty', 'Error']);\n\n// Pure diff: declared model names + live inventory -> the added models. A Model's CFn\n// physical id (Ref) IS its Name, so declared models are matched by Name.\nexport interface ApiGatewayModelInput {\n apiId: string;\n declaredModelNames: string[]; // Names of AWS::ApiGateway::Model declared on this api\n liveModels: { name: string; label?: string | undefined }[];\n}\n\nexport function diffApiGatewayModels(input: ApiGatewayModelInput): AddedChild[] {\n const { apiId, declaredModelNames, liveModels } = input;\n const declared = new Set(declaredModelNames);\n const added: AddedChild[] = [];\n for (const m of liveModels) {\n if (declared.has(m.name)) continue;\n // AWS auto-creates `Empty`/`Error` on every RestApi — never an out-of-band add.\n // (A user who explicitly declares one is matched by the `declared` check above.)\n if (BUILTIN_MODEL_NAMES.has(m.name)) continue;\n added.push({\n resourceType: 'AWS::ApiGateway::Model',\n identifier: `${apiId}|${m.name}`, // CC composite RestApiId|Name\n label: m.label ?? m.name,\n live: { Name: m.name, RestApiId: apiId },\n });\n }\n return added;\n}\n\n// Page GetModels (position-paginated like GetResources / GetAuthorizers).\nasync function getAllModels(client: APIGatewayClient, apiId: string): Promise<ApiGwModel[]> {\n const out: ApiGwModel[] = [];\n let position: string | undefined;\n do {\n const res = await client.send(new GetModelsCommand({ restApiId: apiId, limit: 500, position }));\n out.push(...(res.items ?? []));\n position = res.position;\n } while (position);\n return out;\n}\n\n// Pure diff: declared validator ids + live inventory -> the added request validators. A\n// RequestValidator's CFn physical id (Ref) IS its RequestValidatorId, so declared\n// validators are matched by RequestValidatorId.\nexport interface ApiGatewayRequestValidatorInput {\n apiId: string;\n declaredValidatorIds: string[]; // physical ids (RequestValidatorIds) of AWS::ApiGateway::RequestValidator\n liveValidators: { id: string; label?: string | undefined }[];\n}\n\nexport function diffApiGatewayRequestValidators(\n input: ApiGatewayRequestValidatorInput\n): AddedChild[] {\n const { apiId, declaredValidatorIds, liveValidators } = input;\n const declared = new Set(declaredValidatorIds);\n const added: AddedChild[] = [];\n for (const v of liveValidators) {\n if (declared.has(v.id)) continue;\n added.push({\n resourceType: 'AWS::ApiGateway::RequestValidator',\n identifier: `${apiId}|${v.id}`, // CC composite RestApiId|RequestValidatorId\n label: v.label ?? v.id,\n live: { RequestValidatorId: v.id, RestApiId: apiId },\n });\n }\n return added;\n}\n\n// Page GetRequestValidators (position-paginated like GetModels / GetAuthorizers).\nasync function getAllRequestValidators(\n client: APIGatewayClient,\n apiId: string\n): Promise<ApiGwRequestValidator[]> {\n const out: ApiGwRequestValidator[] = [];\n let position: string | undefined;\n do {\n const res = await client.send(\n new GetRequestValidatorsCommand({ restApiId: apiId, limit: 500, position })\n );\n out.push(...(res.items ?? []));\n position = res.position;\n } while (position);\n return out;\n}\n\n// A RestApi also owns GatewayResponses (per-response-type error customizations, e.g.\n// DEFAULT_4XX, UNAUTHORIZED), each a separate CloudFormation resource. A console / CLI\n// `put-gateway-response` (someone customizes a gateway response on an api out of band) is\n// invisible to cdk drift / CFn drift detection. The RestApi's own live model does NOT\n// reflect its gateway responses inline, so there is no double-report to suppress. The CC\n// primaryIdentifier for AWS::ApiGateway::GatewayResponse is the SINGLE `[\"/properties/Id\"]`,\n// whose runtime form is `${RestApiId}:${ResponseType}` (COLON-joined — verified live via CC\n// GetResource/ListResources; a `|`-joined composite is rejected as \"not valid for identifier\n// [/properties/Id]\"). So the `identifier` is `RestApiId:ResponseType` — that is what CC\n// GetResource / DeleteResource consume. NOTE: GetGatewayResponses returns ALL ~17 supported response\n// types, most as API Gateway-generated DEFAULTS (`defaultResponse: true`) that are NOT real\n// AWS::ApiGateway::GatewayResponse resources; the enumerator filters to the CUSTOMIZED ones\n// (`defaultResponse === false`) before diffing, so the un-customized defaults never flag.\n\n// Pure diff: declared response types + live (already filtered to customized) inventory ->\n// the added gateway responses. A GatewayResponse is matched by ResponseType.\nexport interface ApiGatewayGatewayResponseInput {\n apiId: string;\n declaredResponseTypes: string[]; // ResponseTypes of AWS::ApiGateway::GatewayResponse on this api\n liveResponseTypes: { type: string; label?: string | undefined }[];\n}\n\nexport function diffApiGatewayGatewayResponses(\n input: ApiGatewayGatewayResponseInput\n): AddedChild[] {\n const { apiId, declaredResponseTypes, liveResponseTypes } = input;\n const declared = new Set(declaredResponseTypes);\n const added: AddedChild[] = [];\n for (const r of liveResponseTypes) {\n if (declared.has(r.type)) continue;\n added.push({\n resourceType: 'AWS::ApiGateway::GatewayResponse',\n identifier: `${apiId}:${r.type}`, // CC single Id `RestApiId:ResponseType` (colon-joined)\n label: r.label ?? r.type,\n live: { ResponseType: r.type, RestApiId: apiId },\n });\n }\n return added;\n}\n\n// Page GetGatewayResponses (position-paginated for parity; the collection does not paginate).\n// Returns ONLY customized responses (`defaultResponse === false`) — the API\n// Gateway-generated defaults (`defaultResponse: true`) are not real resources.\nasync function getAllGatewayResponses(\n client: APIGatewayClient,\n apiId: string\n): Promise<ApiGwGatewayResponse[]> {\n const out: ApiGwGatewayResponse[] = [];\n let position: string | undefined;\n do {\n const res = await client.send(\n new GetGatewayResponsesCommand({ restApiId: apiId, limit: 500, position })\n );\n for (const g of res.items ?? []) {\n if (g.defaultResponse === false && typeof g.responseType === 'string') out.push(g);\n }\n position = res.position;\n } while (position);\n return out;\n}\n\n// ── API Gateway V2 (HTTP / WebSocket) ────────────────────────────────────────\n// An `AWS::ApiGatewayV2::Api` owns Routes, Integrations, Authorizers, and Stages, each a\n// SEPARATE CloudFormation resource — the direct V2 analogue of REST's Resources +\n// Methods + Stages. A console-added Route (e.g. `GET /admin`), Integration, Authorizer,\n// or Stage is invisible to `cdk drift` / CFn drift detection (they only compare\n// template-declared resources). Unlike REST there is no implicit \"root\" child to\n// special-case, and these children are siblings (not nested), so each is reported\n// independently. Both protocol types (HTTP and WebSocket) use the same Api type +\n// GetRoutes/GetIntegrations/GetAuthorizers/GetStages APIs, so one enumerator covers both.\n// The Api model does NOT reflect its authorizers/stages inline, so there is no\n// double-report to suppress. CC `GetResource`/`DeleteResource` consume the composite\n// identifier (`ApiId|RouteId` / `ApiId|IntegrationId` / `AuthorizerId|ApiId` /\n// `ApiId|StageName`), so revert deletes generically.\n\n// Pure diff: declared child id sets + live inventory -> the added children. Separated\n// from the SDK calls so the matching is unit-tested offline (mirrors REST).\nexport interface ApiGatewayV2ChildInput {\n apiId: string;\n declaredRouteIds: string[]; // physical ids of AWS::ApiGatewayV2::Route in the template\n declaredIntegrationIds: string[]; // physical ids of AWS::ApiGatewayV2::Integration\n liveRoutes: { id: string; key?: string | undefined }[];\n liveIntegrations: { id: string; label?: string | undefined }[];\n}\n\nexport function diffApiGatewayV2Children(input: ApiGatewayV2ChildInput): AddedChild[] {\n const { apiId, declaredRouteIds, declaredIntegrationIds, liveRoutes, liveIntegrations } = input;\n const declaredRoutes = new Set(declaredRouteIds);\n const declaredIntegrations = new Set(declaredIntegrationIds);\n const added: AddedChild[] = [];\n for (const r of liveRoutes) {\n if (declaredRoutes.has(r.id)) continue;\n added.push({\n resourceType: 'AWS::ApiGatewayV2::Route',\n identifier: `${apiId}|${r.id}`,\n label: r.key ?? r.id, // RouteKey is the human form, e.g. 'GET /items' / '$default'\n live: { RouteId: r.id, RouteKey: r.key },\n });\n }\n for (const i of liveIntegrations) {\n if (declaredIntegrations.has(i.id)) continue;\n added.push({\n resourceType: 'AWS::ApiGatewayV2::Integration',\n identifier: `${apiId}|${i.id}`,\n label: i.label ?? i.id,\n live: { IntegrationId: i.id },\n });\n }\n return added;\n}\n\n// A readable label for an out-of-band Integration (no RouteKey-style human key): the\n// integration type plus its target URI when present (e.g. 'AWS_PROXY arn:...:fn').\nfunction integrationLabel(i: ApiGwV2Integration): string | undefined {\n if (!i.IntegrationType) return undefined;\n return i.IntegrationUri ? `${i.IntegrationType} ${i.IntegrationUri}` : i.IntegrationType;\n}\n\nasync function pageRoutes(client: ApiGatewayV2Client, apiId: string): Promise<ApiGwV2Route[]> {\n const out: ApiGwV2Route[] = [];\n let next: string | undefined;\n do {\n const res = await client.send(new GetRoutesCommand({ ApiId: apiId, NextToken: next }));\n out.push(...(res.Items ?? []));\n next = res.NextToken;\n } while (next);\n return out;\n}\n\nasync function pageIntegrations(\n client: ApiGatewayV2Client,\n apiId: string\n): Promise<ApiGwV2Integration[]> {\n const out: ApiGwV2Integration[] = [];\n let next: string | undefined;\n do {\n const res = await client.send(new GetIntegrationsCommand({ ApiId: apiId, NextToken: next }));\n out.push(...(res.Items ?? []));\n next = res.NextToken;\n } while (next);\n return out;\n}\n\n// Pure diff: declared authorizer ids + live inventory -> the added authorizers. An\n// AWS::ApiGatewayV2::Authorizer's CFn physical id (Ref) IS its AuthorizerId, so declared\n// authorizers are matched by AuthorizerId. The CC primaryIdentifier is the composite\n// `[\"/properties/AuthorizerId\",\"/properties/ApiId\"]` (AuthorizerId FIRST), so the\n// `identifier` is `AuthorizerId|ApiId` — that is what CC GetResource / DeleteResource consume.\nexport function diffApiGatewayV2Authorizers(input: {\n apiId: string;\n declaredAuthorizerIds: string[]; // physical ids (AuthorizerIds) of AWS::ApiGatewayV2::Authorizer\n liveAuthorizers: { id: string; label?: string | undefined }[];\n}): AddedChild[] {\n const { apiId, declaredAuthorizerIds, liveAuthorizers } = input;\n const declared = new Set(declaredAuthorizerIds);\n const added: AddedChild[] = [];\n for (const a of liveAuthorizers) {\n if (declared.has(a.id)) continue;\n added.push({\n resourceType: 'AWS::ApiGatewayV2::Authorizer',\n identifier: `${a.id}|${apiId}`, // CC composite AuthorizerId|ApiId (AuthorizerId first)\n label: a.label ?? a.id,\n live: { AuthorizerId: a.id, ApiId: apiId },\n });\n }\n return added;\n}\n\nasync function pageV2Authorizers(\n client: ApiGatewayV2Client,\n apiId: string\n): Promise<ApiGwV2Authorizer[]> {\n const out: ApiGwV2Authorizer[] = [];\n let next: string | undefined;\n do {\n const res = await client.send(new GetV2AuthorizersCommand({ ApiId: apiId, NextToken: next }));\n out.push(...(res.Items ?? []));\n next = res.NextToken;\n } while (next);\n return out;\n}\n\n// Pure diff: declared stage names + live inventory -> the added stages. An\n// AWS::ApiGatewayV2::Stage's CFn physical id (Ref) IS its StageName, so declared stages\n// are matched by StageName. The CC primaryIdentifier is the composite\n// `[\"/properties/ApiId\",\"/properties/StageName\"]`, so the `identifier` is\n// `ApiId|StageName` — that is what CC GetResource / DeleteResource consume.\nexport function diffApiGatewayV2Stages(input: {\n apiId: string;\n declaredStageNames: string[]; // physical ids (StageNames) of AWS::ApiGatewayV2::Stage\n liveStages: { name: string; label?: string | undefined }[];\n}): AddedChild[] {\n const { apiId, declaredStageNames, liveStages } = input;\n const declared = new Set(declaredStageNames);\n const added: AddedChild[] = [];\n for (const s of liveStages) {\n if (declared.has(s.name)) continue;\n added.push({\n resourceType: 'AWS::ApiGatewayV2::Stage',\n identifier: `${apiId}|${s.name}`, // CC composite ApiId|StageName\n label: s.label ?? s.name,\n live: { StageName: s.name, ApiId: apiId },\n });\n }\n return added;\n}\n\nasync function pageV2Stages(client: ApiGatewayV2Client, apiId: string): Promise<ApiGwV2Stage[]> {\n const out: ApiGwV2Stage[] = [];\n let next: string | undefined;\n do {\n const res = await client.send(new GetStagesCommand({ ApiId: apiId, NextToken: next }));\n out.push(...(res.Items ?? []));\n next = res.NextToken;\n } while (next);\n return out;\n}\n\nasync function enumerateHttpApiChildren(ctx: EnumeratorContext): Promise<AddedChild[]> {\n const { parent, desired, region } = ctx;\n const apiId = parent.physicalId;\n if (!apiId) return [];\n\n // Declared children of THIS api (Ref/GetAtt ApiId already resolved to the physical id\n // by gather). Route/Integration physical ids ARE the RouteId/IntegrationId.\n const declaredRouteIds: string[] = [];\n const declaredIntegrationIds: string[] = [];\n // Declared authorizers of THIS api. An Authorizer's physical id (Ref) IS its AuthorizerId.\n const declaredAuthorizerIds: string[] = [];\n // Declared stages of THIS api. A Stage's physical id (Ref) IS its StageName.\n const declaredStageNames: string[] = [];\n for (const r of desired.resources) {\n if (r.declared.ApiId !== apiId) continue;\n if (r.resourceType === 'AWS::ApiGatewayV2::Route' && r.physicalId) {\n declaredRouteIds.push(r.physicalId);\n } else if (r.resourceType === 'AWS::ApiGatewayV2::Integration' && r.physicalId) {\n declaredIntegrationIds.push(r.physicalId);\n } else if (r.resourceType === 'AWS::ApiGatewayV2::Authorizer' && r.physicalId) {\n declaredAuthorizerIds.push(r.physicalId);\n } else if (r.resourceType === 'AWS::ApiGatewayV2::Stage') {\n const name = r.physicalId ?? (r.declared.StageName as string | undefined);\n if (name) declaredStageNames.push(name);\n }\n }\n\n const client = new ApiGatewayV2Client({ region, ...READ_RETRY });\n const [routes, integrations, authorizers, stages] = await Promise.all([\n pageRoutes(client, apiId),\n pageIntegrations(client, apiId),\n pageV2Authorizers(client, apiId),\n pageV2Stages(client, apiId),\n ]);\n const liveRoutes = routes\n .filter((r): r is ApiGwV2Route & { RouteId: string } => typeof r.RouteId === 'string')\n .map((r) => ({ id: r.RouteId, key: r.RouteKey }));\n const liveIntegrations = integrations\n .filter(\n (i): i is ApiGwV2Integration & { IntegrationId: string } =>\n typeof i.IntegrationId === 'string'\n )\n .map((i) => ({ id: i.IntegrationId, label: integrationLabel(i) }));\n const liveAuthorizers = authorizers\n .filter(\n (a): a is ApiGwV2Authorizer & { AuthorizerId: string } => typeof a.AuthorizerId === 'string'\n )\n .map((a) => ({ id: a.AuthorizerId, label: a.Name ?? a.AuthorizerId }));\n const liveStages = stages\n .filter((s): s is ApiGwV2Stage & { StageName: string } => typeof s.StageName === 'string')\n .map((s) => ({ name: s.StageName }));\n\n const added = diffApiGatewayV2Children({\n apiId,\n declaredRouteIds,\n declaredIntegrationIds,\n liveRoutes,\n liveIntegrations,\n });\n const authorizerAdded = diffApiGatewayV2Authorizers({\n apiId,\n declaredAuthorizerIds,\n liveAuthorizers,\n });\n const stageAdded = diffApiGatewayV2Stages({\n apiId,\n declaredStageNames,\n liveStages,\n });\n return added.concat(authorizerAdded, stageAdded);\n}\n\n// ── SNS ──────────────────────────────────────────────────────────────────────\n// An `AWS::SNS::Topic` owns Subscriptions, each a separate CloudFormation resource.\n// A console-added subscription (someone wires an email / SQS / Lambda endpoint to a\n// topic out of band) is invisible to `cdk drift` / CFn drift detection. The CC\n// primaryIdentifier for AWS::SNS::Subscription is the bare SubscriptionArn (not a\n// composite), which CC GetResource / DeleteResource consume.\n//\n// ONE implicit child must be special-cased: AWS Chatbot (the Slack / Teams / Chime\n// channel configs behind `AWS::Chatbot::SlackChannelConfiguration`, and the Amazon Q\n// Developer console) AUTO-subscribes its fixed global endpoint to every SNS topic a\n// channel config points at — so a stack that declares a SlackChannelConfiguration +\n// alarm topic always grows an `https` subscription to that endpoint that is NOT in the\n// template. It is an AWS-managed side effect of the declared config, not a user's\n// out-of-band change, so reporting it as an `added` resource is a false positive. The\n// endpoint is a constant AWS-owned host; any subscription to it is Chatbot-managed, so\n// folding it can never mask a genuine out-of-band subscription.\nconst CHATBOT_SUBSCRIPTION_ENDPOINT = 'https://global.sns-api.chatbot.amazonaws.com';\n\n// Pure diff: declared subscription arns + live inventory -> the added subscriptions.\nexport interface SnsTopicChildInput {\n declaredSubscriptionArns: string[]; // physical ids of AWS::SNS::Subscription in the template\n liveSubscriptions: { arn: string; label?: string | undefined; endpoint?: string | undefined }[];\n}\n\nexport function diffSnsTopicChildren(input: SnsTopicChildInput): AddedChild[] {\n const declared = new Set(input.declaredSubscriptionArns);\n const added: AddedChild[] = [];\n for (const s of input.liveSubscriptions) {\n if (declared.has(s.arn)) continue;\n if (s.endpoint === CHATBOT_SUBSCRIPTION_ENDPOINT) continue; // AWS Chatbot auto-managed\n added.push({\n resourceType: 'AWS::SNS::Subscription',\n identifier: s.arn, // SubscriptionArn IS the CC primaryIdentifier\n label: s.label ?? s.arn,\n live: { SubscriptionArn: s.arn },\n });\n }\n return added;\n}\n\nasync function pageSubscriptions(client: SNSClient, topicArn: string): Promise<SnsSubscription[]> {\n const out: SnsSubscription[] = [];\n let next: string | undefined;\n do {\n const res = await client.send(\n new ListSubscriptionsByTopicCommand({ TopicArn: topicArn, NextToken: next })\n );\n out.push(...(res.Subscriptions ?? []));\n next = res.NextToken;\n } while (next);\n return out;\n}\n\nasync function enumerateSnsTopicChildren(ctx: EnumeratorContext): Promise<AddedChild[]> {\n const { parent, desired, region } = ctx;\n const topicArn = parent.physicalId; // the Topic's physical id IS its ARN\n if (!topicArn) return [];\n\n // Declared subscriptions of THIS topic (Ref/GetAtt TopicArn already resolved by gather).\n // A subscription's physical id IS its SubscriptionArn.\n const declaredSubscriptionArns: string[] = [];\n for (const r of desired.resources) {\n if (\n r.resourceType === 'AWS::SNS::Subscription' &&\n r.declared.TopicArn === topicArn &&\n r.physicalId\n ) {\n declaredSubscriptionArns.push(r.physicalId);\n }\n }\n\n const client = new SNSClient({ region, ...READ_RETRY });\n const subs = await pageSubscriptions(client, topicArn);\n const liveSubscriptions = subs\n // Skip subscriptions with no real ARN: a pending-confirmation email/http sub reports\n // `PendingConfirmation` (and a just-deleted one `Deleted`) as its arn — neither is a\n // CC-addressable resource, so it cannot be recorded or reverted; not yet a real child.\n .filter(\n (s): s is SnsSubscription & { SubscriptionArn: string } =>\n typeof s.SubscriptionArn === 'string' && s.SubscriptionArn.startsWith('arn:')\n )\n .map((s) => ({\n arn: s.SubscriptionArn,\n label: s.Protocol ? `${s.Protocol} ${s.Endpoint ?? ''}`.trim() : s.SubscriptionArn,\n endpoint: s.Endpoint,\n }));\n\n return diffSnsTopicChildren({ declaredSubscriptionArns, liveSubscriptions });\n}\n\n// ── Lambda ───────────────────────────────────────────────────────────────────\n// A Lambda Function owns Event Source Mappings (the SQS / DynamoDB-stream / Kinesis /\n// MSK poller wiring), each a separate CloudFormation resource. A console / CLI\n// `create-event-source-mapping` (someone wires a new trigger to a function out of band)\n// is invisible to cdk drift / CFn drift detection. The Function's own live model does\n// NOT reflect its mappings, so there is no double-report to suppress. The CC\n// primaryIdentifier for AWS::Lambda::EventSourceMapping is the bare mapping UUID (Id),\n// which CC GetResource / DeleteResource consume.\n//\n// A Function ALSO owns at most one Function URL per qualifier (AWS::Lambda::Url). A\n// console / CLI `create-function-url-config` (someone exposes a public HTTPS endpoint\n// out of band — a security-relevant change, especially `AuthType: NONE`) is invisible\n// to cdk drift / CFn drift detection, and the Function's own live model does NOT reflect\n// its URL inline, so there is no double-report to suppress. The CC primaryIdentifier for\n// AWS::Lambda::Url is the bare FunctionArn of the URL config, which CC GetResource /\n// DeleteResource consume.\n//\n// A Function ALSO owns Aliases (AWS::Lambda::Alias) — named pointers to a published\n// version (e.g. `prod`, `live`). A console / CLI `create-alias` (someone wires a new\n// alias to a function out of band) is invisible to cdk drift / CFn drift detection, and\n// the Function's own live model does NOT reflect its aliases inline, so there is no\n// double-report to suppress. The CC primaryIdentifier for AWS::Lambda::Alias is the bare\n// AliasArn, which CC GetResource / DeleteResource consume.\n//\n// A Function ALSO owns published Versions (AWS::Lambda::Version) — immutable snapshots of\n// the function's code + config. A console / CLI `publish-version` (someone publishes a new\n// version out of band) is invisible to cdk drift / CFn drift detection, and the Function's\n// own live model does NOT reflect its versions inline, so there is no double-report to\n// suppress. The `$LATEST` pseudo-version is NOT a real AWS::Lambda::Version resource and is\n// skipped. The CC primaryIdentifier for AWS::Lambda::Version is the bare versioned\n// FunctionArn (e.g. `arn:...:function:fn:2`), which CC GetResource / DeleteResource consume.\n\n// Pure diff: declared mapping ids + live inventory -> the added mappings.\nexport interface LambdaFunctionChildInput {\n declaredMappingIds: string[]; // physical ids (UUIDs) of AWS::Lambda::EventSourceMapping\n liveMappings: { id: string; label?: string | undefined }[];\n}\n\nexport function diffLambdaFunctionChildren(input: LambdaFunctionChildInput): AddedChild[] {\n const declared = new Set(input.declaredMappingIds);\n const added: AddedChild[] = [];\n for (const m of input.liveMappings) {\n if (declared.has(m.id)) continue;\n added.push({\n resourceType: 'AWS::Lambda::EventSourceMapping',\n identifier: m.id, // the mapping UUID IS the CC primaryIdentifier\n label: m.label ?? m.id,\n live: { Id: m.id },\n });\n }\n return added;\n}\n\nasync function pageEventSourceMappings(\n client: LambdaClient,\n functionName: string\n): Promise<EventSourceMappingConfiguration[]> {\n const out: EventSourceMappingConfiguration[] = [];\n let marker: string | undefined;\n do {\n const res = await client.send(\n new ListEventSourceMappingsCommand({ FunctionName: functionName, Marker: marker })\n );\n out.push(...(res.EventSourceMappings ?? []));\n marker = res.NextMarker;\n } while (marker);\n return out;\n}\n\n// Pure diff: declared URL FunctionArns + live inventory -> the added function URLs.\nexport function diffLambdaFunctionUrls(input: {\n declaredUrlArns: string[];\n liveUrls: { arn: string; label?: string | undefined }[];\n}): AddedChild[] {\n const declared = new Set(input.declaredUrlArns);\n const added: AddedChild[] = [];\n for (const u of input.liveUrls) {\n if (declared.has(u.arn)) continue;\n added.push({\n resourceType: 'AWS::Lambda::Url',\n identifier: u.arn, // the URL config's FunctionArn IS the CC primaryIdentifier\n label: u.label ?? u.arn,\n live: { FunctionArn: u.arn },\n });\n }\n return added;\n}\n\nasync function pageFunctionUrlConfigs(\n client: LambdaClient,\n functionName: string\n): Promise<FunctionUrlConfig[]> {\n const out: FunctionUrlConfig[] = [];\n let marker: string | undefined;\n do {\n const res = await client.send(\n new ListFunctionUrlConfigsCommand({ FunctionName: functionName, Marker: marker })\n );\n out.push(...(res.FunctionUrlConfigs ?? []));\n marker = res.NextMarker;\n } while (marker);\n return out;\n}\n\n// Pure diff: declared alias arns + live inventory -> the added aliases.\nexport function diffLambdaFunctionAliases(input: {\n declaredAliasArns: string[];\n liveAliases: { arn: string; label?: string | undefined }[];\n}): AddedChild[] {\n const declared = new Set(input.declaredAliasArns);\n const added: AddedChild[] = [];\n for (const a of input.liveAliases) {\n if (declared.has(a.arn)) continue;\n added.push({\n resourceType: 'AWS::Lambda::Alias',\n identifier: a.arn, // the AliasArn IS the CC primaryIdentifier\n label: a.label ?? a.arn,\n live: { AliasArn: a.arn },\n });\n }\n return added;\n}\n\nasync function pageLambdaAliases(\n client: LambdaClient,\n functionName: string\n): Promise<LambdaAliasConfiguration[]> {\n const out: LambdaAliasConfiguration[] = [];\n let marker: string | undefined;\n do {\n const res = await client.send(\n new ListLambdaAliasesCommand({ FunctionName: functionName, Marker: marker })\n );\n out.push(...(res.Aliases ?? []));\n marker = res.NextMarker;\n } while (marker);\n return out;\n}\n\n// Pure diff: declared version arns + live inventory -> the added versions.\nexport function diffLambdaFunctionVersions(input: {\n declaredVersionArns: string[];\n liveVersions: { arn: string; label?: string | undefined }[];\n}): AddedChild[] {\n const declared = new Set(input.declaredVersionArns);\n const added: AddedChild[] = [];\n for (const v of input.liveVersions) {\n if (declared.has(v.arn)) continue;\n added.push({\n resourceType: 'AWS::Lambda::Version',\n identifier: v.arn, // the versioned FunctionArn IS the CC primaryIdentifier\n label: v.label ?? v.arn,\n live: { FunctionArn: v.arn },\n });\n }\n return added;\n}\n\nasync function pageLambdaVersions(\n client: LambdaClient,\n functionName: string\n): Promise<LambdaVersionConfiguration[]> {\n const out: LambdaVersionConfiguration[] = [];\n let marker: string | undefined;\n do {\n const res = await client.send(\n new ListVersionsByFunctionCommand({ FunctionName: functionName, Marker: marker })\n );\n out.push(...(res.Versions ?? []));\n marker = res.NextMarker;\n } while (marker);\n return out;\n}\n\nasync function enumerateLambdaFunctionChildren(ctx: EnumeratorContext): Promise<AddedChild[]> {\n const { parent, desired, region } = ctx;\n const functionName = parent.physicalId; // the Function's physical id is its name\n if (!functionName) return [];\n\n // Declared mappings targeting THIS function. An EventSourceMapping's FunctionName is\n // often a Ref/GetAtt (already resolved by gather), and its physical id IS the mapping\n // UUID. Match on the function name resolving to either the bare name or its ARN.\n const fnArnRaw = desired.ctx.liveAttrs[parent.logicalId]?.Arn;\n const fnArn = typeof fnArnRaw === 'string' ? fnArnRaw : undefined;\n const declaredMappingIds: string[] = [];\n for (const r of desired.resources) {\n if (r.resourceType !== 'AWS::Lambda::EventSourceMapping' || !r.physicalId) continue;\n const fn = r.declared.FunctionName;\n if (fn === functionName || (fnArn !== undefined && fn === fnArn)) {\n declaredMappingIds.push(r.physicalId);\n }\n }\n\n // Declared function URLs targeting THIS function. An AWS::Lambda::Url's physical id\n // (Ref) IS the URL config's FunctionArn; its TargetFunctionArn resolves to the function\n // name or ARN. Match by physicalId (the FunctionArn), and also tolerate matching by the\n // target function (a URL whose TargetFunctionArn resolves to this function's name/arn),\n // falling back to physicalId.\n const declaredUrlArns: string[] = [];\n for (const r of desired.resources) {\n if (r.resourceType !== 'AWS::Lambda::Url') continue;\n const target = r.declared.TargetFunctionArn;\n const targetsThis = target === functionName || (fnArn !== undefined && target === fnArn);\n if (targetsThis) {\n // The URL's FunctionArn (its primaryIdentifier) is the function's bare ARN for an\n // unqualified URL; prefer the resolved live function ARN, else the declared physicalId.\n if (fnArn !== undefined) declaredUrlArns.push(fnArn);\n if (r.physicalId) declaredUrlArns.push(r.physicalId);\n } else if (r.physicalId) {\n declaredUrlArns.push(r.physicalId);\n }\n }\n\n // Declared aliases targeting THIS function. An AWS::Lambda::Alias's CFn physical id\n // (Ref) IS its AliasArn; its FunctionName resolves (via gather) to the function name or\n // ARN. Prefer matching on the FunctionName targeting this function; fall back to\n // including any alias whose FunctionName did not resolve (undefined) so a resolved-id\n // mismatch never causes a declared alias to be flagged added.\n const declaredAliasArns: string[] = [];\n for (const r of desired.resources) {\n if (r.resourceType !== 'AWS::Lambda::Alias' || !r.physicalId) continue;\n const fn = r.declared.FunctionName;\n const targetsThis = fn === functionName || (fnArn !== undefined && fn === fnArn);\n if (targetsThis || fn === undefined) {\n declaredAliasArns.push(r.physicalId);\n }\n }\n\n // Declared versions targeting THIS function. An AWS::Lambda::Version's CFn physical id\n // (Ref) IS its versioned FunctionArn; its FunctionName resolves (via gather) to the\n // function name or ARN. Prefer matching on the FunctionName targeting this function; fall\n // back to including any version whose FunctionName did not resolve (undefined) so a\n // resolved-id mismatch never causes a declared version to be flagged added.\n const declaredVersionArns: string[] = [];\n for (const r of desired.resources) {\n if (r.resourceType !== 'AWS::Lambda::Version' || !r.physicalId) continue;\n const fn = r.declared.FunctionName;\n const targetsThis = fn === functionName || (fnArn !== undefined && fn === fnArn);\n if (targetsThis || fn === undefined) {\n declaredVersionArns.push(r.physicalId);\n }\n }\n\n const client = new LambdaClient({ region, ...READ_RETRY });\n const mappings = await pageEventSourceMappings(client, functionName);\n const liveMappings = mappings\n .filter(\n (m): m is EventSourceMappingConfiguration & { UUID: string } => typeof m.UUID === 'string'\n )\n .map((m) => ({ id: m.UUID, label: m.EventSourceArn ?? m.UUID }));\n\n const esmAdded = diffLambdaFunctionChildren({ declaredMappingIds, liveMappings });\n\n const urlConfigs = await pageFunctionUrlConfigs(client, functionName);\n const liveUrls = urlConfigs\n .filter(\n (u): u is FunctionUrlConfig & { FunctionArn: string } => typeof u.FunctionArn === 'string'\n )\n .map((u) => ({\n arn: u.FunctionArn,\n label: u.AuthType ? `${u.AuthType} ${u.FunctionArn}` : u.FunctionArn,\n }));\n\n const urlAdded = diffLambdaFunctionUrls({ declaredUrlArns, liveUrls });\n\n const aliases = await pageLambdaAliases(client, functionName);\n const liveAliases = aliases\n .filter(\n (a): a is LambdaAliasConfiguration & { AliasArn: string } => typeof a.AliasArn === 'string'\n )\n .map((a) => ({ arn: a.AliasArn, label: a.Name ? `${a.Name} ${a.AliasArn}` : a.AliasArn }));\n\n const aliasAdded = diffLambdaFunctionAliases({ declaredAliasArns, liveAliases });\n\n const versions = await pageLambdaVersions(client, functionName);\n const liveVersions = versions\n .filter(\n (v): v is LambdaVersionConfiguration & { FunctionArn: string } =>\n typeof v.FunctionArn === 'string' && v.Version !== '$LATEST' // skip the $LATEST pseudo-version\n )\n .map((v) => ({\n arn: v.FunctionArn,\n label: v.Version ? `v${v.Version}` : v.FunctionArn,\n }));\n\n const versionAdded = diffLambdaFunctionVersions({ declaredVersionArns, liveVersions });\n\n return [...esmAdded, ...urlAdded, ...aliasAdded, ...versionAdded];\n}\n\n// ── EventBridge ────────────────────────────────────────────────────────────────\n// An `AWS::Events::EventBus` owns Rules, each a separate CloudFormation resource. A\n// console / CLI `put-rule` (someone wires a new rule on a custom bus out of band) is\n// invisible to cdk drift / CFn drift detection. Only DECLARED custom buses are scanned,\n// so the AWS-default bus (never a template resource) is never swept — its many\n// AWS-created rules are out of scope. AWS service-managed rules (ManagedBy set) are\n// skipped: they are owned by another service, not an out-of-band human change. The\n// EventBus model does NOT reflect its rules, so there is no double-report to suppress.\n// The CC primaryIdentifier for AWS::Events::Rule is the bare rule Arn, which CC\n// GetResource / DeleteResource consume.\n\n// Pure diff: declared rule names + live inventory -> the added rules.\nexport interface EventBusChildInput {\n declaredRuleNames: string[]; // bare Names of AWS::Events::Rule declared on this bus\n liveRules: { name: string; arn: string; label?: string | undefined }[];\n}\n\nexport function diffEventBusChildren(input: EventBusChildInput): AddedChild[] {\n const declared = new Set(input.declaredRuleNames);\n const added: AddedChild[] = [];\n for (const r of input.liveRules) {\n if (declared.has(r.name)) continue;\n added.push({\n resourceType: 'AWS::Events::Rule',\n identifier: r.arn, // the rule Arn IS the CC primaryIdentifier\n label: r.label ?? r.name,\n live: { Name: r.name, Arn: r.arn },\n });\n }\n return added;\n}\n\nasync function pageRules(client: EventBridgeClient, busName: string): Promise<EventBridgeRule[]> {\n const out: EventBridgeRule[] = [];\n let next: string | undefined;\n do {\n const res = await client.send(new ListRulesCommand({ EventBusName: busName, NextToken: next }));\n out.push(...(res.Rules ?? []));\n next = res.NextToken;\n } while (next);\n return out;\n}\n\nasync function enumerateEventBusChildren(ctx: EnumeratorContext): Promise<AddedChild[]> {\n const { parent, desired, region } = ctx;\n const busName = parent.physicalId; // an EventBus's physical id is its name\n if (!busName) return [];\n const busArnRaw = desired.ctx.liveAttrs[parent.logicalId]?.Arn;\n const busArn = typeof busArnRaw === 'string' ? busArnRaw : undefined;\n\n // Declared rules on THIS bus. EventBusName resolves (via gather) to either the bus name\n // or its ARN. A rule's physical id (Ref) is its name — but for a custom bus that can be\n // a `<busName>|<ruleName>` composite, so take the trailing segment; ListRules returns\n // the bare name. Fall back to a literal declared Name.\n const declaredRuleNames: string[] = [];\n for (const r of desired.resources) {\n if (r.resourceType !== 'AWS::Events::Rule') continue;\n const bus = r.declared.EventBusName;\n if (bus !== busName && !(busArn !== undefined && bus === busArn)) continue;\n const raw = r.physicalId ?? (typeof r.declared.Name === 'string' ? r.declared.Name : undefined);\n if (raw) declaredRuleNames.push(raw.includes('|') ? raw.slice(raw.lastIndexOf('|') + 1) : raw);\n }\n\n const client = new EventBridgeClient({ region, ...READ_RETRY });\n const rules = await pageRules(client, busName);\n const liveRules = rules\n // Skip AWS service-managed rules (ManagedBy set): owned by another AWS service, not an\n // out-of-band human change, and not user-revertable.\n .filter(\n (r): r is EventBridgeRule & { Name: string; Arn: string } =>\n typeof r.Name === 'string' && typeof r.Arn === 'string' && !r.ManagedBy\n )\n .map((r) => ({ name: r.Name, arn: r.Arn, label: r.Name }));\n\n return diffEventBusChildren({ declaredRuleNames, liveRules });\n}\n\n// ── Cognito ──────────────────────────────────────────────────────────────────\n// An `AWS::Cognito::UserPool` owns UserPoolClients (app clients), each a separate\n// CloudFormation resource. A console / CLI `create-user-pool-client` (someone wires a\n// new app client to a pool out of band) is invisible to cdk drift / CFn drift detection\n// (they only compare template-declared resources). The UserPool's own live model does\n// NOT reflect its clients, so there is no double-report to suppress. The CC\n// primaryIdentifier for AWS::Cognito::UserPoolClient is the composite\n// `[\"/properties/UserPoolId\",\"/properties/ClientId\"]`, so the `identifier` is the\n// composite `UserPoolId|ClientId` — that is what CC GetResource / DeleteResource consume.\n\n// Pure diff: declared client ids + live inventory -> the added clients.\nexport interface UserPoolChildInput {\n userPoolId: string;\n declaredClientIds: string[]; // physical ids (ClientIds) of AWS::Cognito::UserPoolClient\n liveClients: { id: string; label?: string | undefined }[];\n}\n\nexport function diffUserPoolChildren(input: UserPoolChildInput): AddedChild[] {\n const { userPoolId, declaredClientIds, liveClients } = input;\n const declared = new Set(declaredClientIds);\n const added: AddedChild[] = [];\n for (const c of liveClients) {\n if (declared.has(c.id)) continue;\n added.push({\n resourceType: 'AWS::Cognito::UserPoolClient',\n identifier: `${userPoolId}|${c.id}`, // CC composite UserPoolId|ClientId\n label: c.label ?? c.id,\n live: { ClientId: c.id },\n });\n }\n return added;\n}\n\nasync function pageUserPoolClients(\n client: CognitoIdentityProviderClient,\n userPoolId: string\n): Promise<UserPoolClientDescription[]> {\n const out: UserPoolClientDescription[] = [];\n let next: string | undefined;\n do {\n const res = await client.send(\n new ListUserPoolClientsCommand({ UserPoolId: userPoolId, NextToken: next, MaxResults: 60 })\n );\n out.push(...(res.UserPoolClients ?? []));\n next = res.NextToken;\n } while (next);\n return out;\n}\n\n// A UserPool also owns UserPoolGroups, each a separate CloudFormation resource. A\n// console / CLI `create-group` (someone wires a new group onto a pool out of band) is\n// invisible to cdk drift / CFn drift detection. The UserPool model does NOT reflect its\n// groups inline, so there is no double-report to suppress. The CC primaryIdentifier for\n// AWS::Cognito::UserPoolGroup is the composite `[\"/properties/UserPoolId\",\"/properties/GroupName\"]`,\n// so the `identifier` is the composite `UserPoolId|GroupName` — that is what CC\n// GetResource / DeleteResource consume. A group's CFn physical id (Ref) IS its GroupName.\n\n// Pure diff: declared group names + live inventory -> the added groups.\nexport interface UserPoolGroupInput {\n userPoolId: string;\n declaredGroupNames: string[]; // physical ids (GroupNames) of AWS::Cognito::UserPoolGroup\n liveGroups: { name: string; label?: string | undefined }[];\n}\n\nexport function diffUserPoolGroups(input: UserPoolGroupInput): AddedChild[] {\n const { userPoolId, declaredGroupNames, liveGroups } = input;\n const declared = new Set(declaredGroupNames);\n const added: AddedChild[] = [];\n for (const g of liveGroups) {\n if (declared.has(g.name)) continue;\n added.push({\n resourceType: 'AWS::Cognito::UserPoolGroup',\n identifier: `${userPoolId}|${g.name}`, // CC composite UserPoolId|GroupName\n label: g.label ?? g.name,\n live: { GroupName: g.name, UserPoolId: userPoolId },\n });\n }\n return added;\n}\n\nasync function pageUserPoolGroups(\n client: CognitoIdentityProviderClient,\n userPoolId: string\n): Promise<GroupType[]> {\n const out: GroupType[] = [];\n let next: string | undefined;\n do {\n const res = await client.send(\n new ListGroupsCommand({ UserPoolId: userPoolId, NextToken: next, Limit: 60 })\n );\n out.push(...(res.Groups ?? []));\n next = res.NextToken;\n } while (next);\n return out;\n}\n\n// A UserPool also owns UserPoolResourceServers, each a separate CloudFormation resource. A\n// console / CLI `create-resource-server` (someone wires a new OAuth resource server onto a\n// pool out of band) is invisible to cdk drift / CFn drift detection. The UserPool model does\n// NOT reflect its resource servers inline, so there is no double-report to suppress. The CC\n// primaryIdentifier for AWS::Cognito::UserPoolResourceServer is the composite\n// `[\"/properties/UserPoolId\",\"/properties/Identifier\"]`, so the `identifier` is the composite\n// `UserPoolId|Identifier` — that is what CC GetResource / DeleteResource consume.\n\n// Pure diff: declared resource server identifiers + live inventory -> the added resource servers.\nexport interface UserPoolResourceServerInput {\n userPoolId: string;\n declaredIdentifiers: string[]; // Identifier values of AWS::Cognito::UserPoolResourceServer\n liveResourceServers: { identifier: string; label?: string | undefined }[];\n}\n\nexport function diffUserPoolResourceServers(input: UserPoolResourceServerInput): AddedChild[] {\n const { userPoolId, declaredIdentifiers, liveResourceServers } = input;\n const declared = new Set(declaredIdentifiers);\n const added: AddedChild[] = [];\n for (const rs of liveResourceServers) {\n if (declared.has(rs.identifier)) continue;\n added.push({\n resourceType: 'AWS::Cognito::UserPoolResourceServer',\n identifier: `${userPoolId}|${rs.identifier}`, // CC composite UserPoolId|Identifier\n label: rs.label ?? rs.identifier,\n live: { Identifier: rs.identifier, UserPoolId: userPoolId },\n });\n }\n return added;\n}\n\nasync function pageUserPoolResourceServers(\n client: CognitoIdentityProviderClient,\n userPoolId: string\n): Promise<ResourceServerType[]> {\n const out: ResourceServerType[] = [];\n let next: string | undefined;\n do {\n const res = await client.send(\n new ListResourceServersCommand({ UserPoolId: userPoolId, NextToken: next, MaxResults: 50 })\n );\n out.push(...(res.ResourceServers ?? []));\n next = res.NextToken;\n } while (next);\n return out;\n}\n\nasync function enumerateUserPoolChildren(ctx: EnumeratorContext): Promise<AddedChild[]> {\n const { parent, desired, region } = ctx;\n const userPoolId = parent.physicalId; // a UserPool's physical id IS its UserPoolId\n if (!userPoolId) return [];\n\n // Declared clients of THIS pool (Ref/GetAtt UserPoolId already resolved to the physical\n // id by gather). A client's physical id IS its ClientId.\n const declaredClientIds: string[] = [];\n // Declared groups of THIS pool. A group's physical id IS its GroupName.\n const declaredGroupNames: string[] = [];\n // Declared resource servers of THIS pool. Matched by the Identifier value.\n const declaredResourceServerIdentifiers: string[] = [];\n for (const r of desired.resources) {\n if (\n r.resourceType === 'AWS::Cognito::UserPoolClient' &&\n r.declared.UserPoolId === userPoolId &&\n r.physicalId\n ) {\n declaredClientIds.push(r.physicalId);\n } else if (\n r.resourceType === 'AWS::Cognito::UserPoolGroup' &&\n r.declared.UserPoolId === userPoolId\n ) {\n const name = typeof r.declared.GroupName === 'string' ? r.declared.GroupName : r.physicalId;\n if (name) declaredGroupNames.push(name);\n } else if (\n r.resourceType === 'AWS::Cognito::UserPoolResourceServer' &&\n r.declared.UserPoolId === userPoolId\n ) {\n const identifier =\n typeof r.declared.Identifier === 'string' ? r.declared.Identifier : r.physicalId;\n if (identifier) declaredResourceServerIdentifiers.push(identifier);\n }\n }\n\n const client = new CognitoIdentityProviderClient({ region, ...READ_RETRY });\n\n const clients = await pageUserPoolClients(client, userPoolId);\n const liveClients = clients\n .filter(\n (c): c is UserPoolClientDescription & { ClientId: string } => typeof c.ClientId === 'string'\n )\n .map((c) => ({ id: c.ClientId, label: c.ClientName ?? c.ClientId }));\n const clientAdded = diffUserPoolChildren({ userPoolId, declaredClientIds, liveClients });\n\n const groups = await pageUserPoolGroups(client, userPoolId);\n const liveGroups = groups\n .filter((g): g is GroupType & { GroupName: string } => typeof g.GroupName === 'string')\n .map((g) => ({ name: g.GroupName }));\n const groupAdded = diffUserPoolGroups({ userPoolId, declaredGroupNames, liveGroups });\n\n const resourceServers = await pageUserPoolResourceServers(client, userPoolId);\n const liveResourceServers = resourceServers\n .filter(\n (rs): rs is ResourceServerType & { Identifier: string } => typeof rs.Identifier === 'string'\n )\n .map((rs) => ({ identifier: rs.Identifier, label: rs.Name ?? rs.Identifier }));\n const resourceServerAdded = diffUserPoolResourceServers({\n userPoolId,\n declaredIdentifiers: declaredResourceServerIdentifiers,\n liveResourceServers,\n });\n\n return [...clientAdded, ...groupAdded, ...resourceServerAdded];\n}\n\n// ── AppSync ──────────────────────────────────────────────────────────────────\n// An `AWS::AppSync::GraphQLApi` owns DataSources (the DynamoDB / Lambda / HTTP / NONE\n// resolver backings), Resolvers (per type/field attachments), AND Functions (the\n// pipeline functions composed into a pipeline resolver), each a separate\n// CloudFormation resource. A console / CLI `create-data-source` / `create-resolver` /\n// `create-function` (someone wires a new backing, resolver, or function onto an api\n// out of band) is invisible to cdk drift / CFn drift detection. The GraphQLApi model\n// does NOT reflect its datasources, resolvers, or functions inline, so there is no\n// double-report to suppress. The CC primaryIdentifier for AWS::AppSync::DataSource is\n// the bare DataSourceArn, for AWS::AppSync::Resolver the bare ResolverArn, and for\n// AWS::AppSync::FunctionConfiguration the bare FunctionArn, which CC GetResource /\n// DeleteResource consume.\n\n// Pure diff: declared datasource names + live inventory -> the added datasources.\nexport interface GraphQLApiChildInput {\n declaredDataSourceNames: string[]; // Names of AWS::AppSync::DataSource declared on this api\n liveDataSources: { name: string; arn: string; label?: string | undefined }[];\n}\n\nexport function diffGraphQLApiChildren(input: GraphQLApiChildInput): AddedChild[] {\n const declared = new Set(input.declaredDataSourceNames);\n const added: AddedChild[] = [];\n for (const ds of input.liveDataSources) {\n if (declared.has(ds.name)) continue;\n added.push({\n resourceType: 'AWS::AppSync::DataSource',\n identifier: ds.arn, // DataSourceArn IS the CC primaryIdentifier\n label: ds.label ?? ds.name,\n live: { Name: ds.name, DataSourceArn: ds.arn },\n });\n }\n return added;\n}\n\nasync function pageDataSources(client: AppSyncClient, apiId: string): Promise<AppSyncDataSource[]> {\n const out: AppSyncDataSource[] = [];\n let next: string | undefined;\n do {\n const res = await client.send(new ListDataSourcesCommand({ apiId, nextToken: next }));\n out.push(...(res.dataSources ?? []));\n next = res.nextToken;\n } while (next);\n return out;\n}\n\n// Pure diff: declared resolver keys (`${typeName}|${fieldName}`) + live inventory ->\n// the added resolvers. Declared resolvers are matched by their typeName|fieldName key\n// (the physical-id form is unreliable); an added resolver's identifier is its live\n// ResolverArn (the CC primaryIdentifier).\nexport interface GraphQLApiResolverInput {\n declaredResolverKeys: string[]; // `${typeName}|${fieldName}` of declared AWS::AppSync::Resolver\n liveResolvers: { key: string; arn: string; label?: string | undefined }[];\n}\n\nexport function diffGraphQLApiResolvers(input: GraphQLApiResolverInput): AddedChild[] {\n const declared = new Set(input.declaredResolverKeys);\n const added: AddedChild[] = [];\n for (const r of input.liveResolvers) {\n if (declared.has(r.key)) continue;\n added.push({\n resourceType: 'AWS::AppSync::Resolver',\n identifier: r.arn, // ResolverArn IS the CC primaryIdentifier\n label: r.label ?? r.key,\n live: { ResolverArn: r.arn },\n });\n }\n return added;\n}\n\nasync function pageTypes(client: AppSyncClient, apiId: string): Promise<string[]> {\n const out: string[] = [];\n let next: string | undefined;\n do {\n const res = await client.send(new ListTypesCommand({ apiId, format: 'SDL', nextToken: next }));\n for (const t of res.types ?? []) {\n if (typeof t.name === 'string') out.push(t.name);\n }\n next = res.nextToken;\n } while (next);\n return out;\n}\n\nasync function pageResolvers(\n client: AppSyncClient,\n apiId: string,\n typeName: string\n): Promise<AppSyncResolver[]> {\n const out: AppSyncResolver[] = [];\n let next: string | undefined;\n do {\n const res = await client.send(new ListResolversCommand({ apiId, typeName, nextToken: next }));\n out.push(...(res.resolvers ?? []));\n next = res.nextToken;\n } while (next);\n return out;\n}\n\n// Pure diff: declared function arns + live inventory -> the added functions. A declared\n// AWS::AppSync::FunctionConfiguration's CFn physical id (Ref) IS its FunctionArn, so\n// declared functions are matched by FunctionArn; an added function's identifier is its\n// live FunctionArn (the CC primaryIdentifier).\nexport interface GraphQLApiFunctionInput {\n declaredFunctionArns: string[]; // physical ids (FunctionArns) of AWS::AppSync::FunctionConfiguration\n liveFunctions: { arn: string; label?: string | undefined }[];\n}\n\nexport function diffGraphQLApiFunctions(input: GraphQLApiFunctionInput): AddedChild[] {\n const declared = new Set(input.declaredFunctionArns);\n const added: AddedChild[] = [];\n for (const f of input.liveFunctions) {\n if (declared.has(f.arn)) continue;\n added.push({\n resourceType: 'AWS::AppSync::FunctionConfiguration',\n identifier: f.arn, // FunctionArn IS the CC primaryIdentifier\n label: f.label ?? f.arn,\n live: { FunctionArn: f.arn },\n });\n }\n return added;\n}\n\nasync function pageAppSyncFunctions(\n client: AppSyncClient,\n apiId: string\n): Promise<AppSyncFunctionConfiguration[]> {\n const out: AppSyncFunctionConfiguration[] = [];\n let next: string | undefined;\n do {\n const res = await client.send(new ListAppSyncFunctionsCommand({ apiId, nextToken: next }));\n out.push(...(res.functions ?? []));\n next = res.nextToken;\n } while (next);\n return out;\n}\n\n// A GraphQLApi's CFn physical id is its ARN (`arn:...:apis/<apiId>`), but `ListDataSources`\n// and a DataSource's declared `ApiId` (`Fn::GetAtt ApiId`) both use the BARE api id. Take\n// the trailing `apis/<id>` segment when the physical id is an ARN; otherwise it already IS\n// the bare id (the CC primaryIdentifier form).\nfunction bareApiId(physicalId: string): string {\n return physicalId.includes('/') ? physicalId.slice(physicalId.lastIndexOf('/') + 1) : physicalId;\n}\n\nasync function enumerateGraphQLApiChildren(ctx: EnumeratorContext): Promise<AddedChild[]> {\n const { parent, desired, region } = ctx;\n if (!parent.physicalId) return [];\n const apiId = bareApiId(parent.physicalId); // the BARE ApiId (ListDataSources / declared ApiId form)\n\n // Declared datasources on THIS api. Datasource names are unique per api, and the\n // Ref/physical-id form is unreliable, so match DECLARED datasources by Name. A declared\n // DataSource's ApiId (Fn::GetAtt ApiId, resolved by gather) is the bare api id; tolerate\n // an ARN form too in case gather resolved it differently.\n const declaredDataSourceNames: string[] = [];\n for (const r of desired.resources) {\n if (r.resourceType !== 'AWS::AppSync::DataSource' || typeof r.declared.Name !== 'string') {\n continue;\n }\n const declaredApiId = r.declared.ApiId;\n if (typeof declaredApiId !== 'string') continue;\n if (bareApiId(declaredApiId) !== apiId) continue;\n declaredDataSourceNames.push(r.declared.Name);\n }\n\n // Declared resolvers on THIS api. Resolvers are attached per (type, field); match\n // DECLARED resolvers by the `${typeName}|${fieldName}` key (the physical-id form is\n // unreliable). A declared Resolver's ApiId (Fn::GetAtt ApiId) is the bare api id;\n // tolerate an ARN form too in case gather resolved it differently.\n const declaredResolverKeys: string[] = [];\n for (const r of desired.resources) {\n if (r.resourceType !== 'AWS::AppSync::Resolver') continue;\n const declaredApiId = r.declared.ApiId;\n if (typeof declaredApiId !== 'string') continue;\n if (bareApiId(declaredApiId) !== apiId) continue;\n const { TypeName, FieldName } = r.declared;\n if (typeof TypeName !== 'string' || typeof FieldName !== 'string') continue;\n declaredResolverKeys.push(`${TypeName}|${FieldName}`);\n }\n\n // Declared functions on THIS api. An AWS::AppSync::FunctionConfiguration's CFn physical\n // id (Ref) IS its FunctionArn, so match DECLARED functions by FunctionArn (= physicalId).\n // A declared Function's ApiId (Fn::GetAtt ApiId, resolved by gather) is the bare api id;\n // tolerate an ARN form too in case gather resolved it differently.\n const declaredFunctionArns: string[] = [];\n for (const r of desired.resources) {\n if (r.resourceType !== 'AWS::AppSync::FunctionConfiguration' || !r.physicalId) continue;\n const declaredApiId = r.declared.ApiId;\n if (typeof declaredApiId !== 'string') continue;\n if (bareApiId(declaredApiId) !== apiId) continue;\n declaredFunctionArns.push(r.physicalId);\n }\n\n const client = new AppSyncClient({ region, ...READ_RETRY });\n const dataSources = await pageDataSources(client, apiId);\n const liveDataSources = dataSources\n .filter(\n (ds): ds is AppSyncDataSource & { name: string; dataSourceArn: string } =>\n typeof ds.name === 'string' && typeof ds.dataSourceArn === 'string'\n )\n .map((ds) => ({\n name: ds.name,\n arn: ds.dataSourceArn,\n label: ds.type ? `${ds.type} ${ds.name}` : ds.name,\n }));\n const datasourceAdded = diffGraphQLApiChildren({ declaredDataSourceNames, liveDataSources });\n\n // Resolvers are scoped per type: list all types, then list resolvers per type.\n const types = await pageTypes(client, apiId);\n const liveResolvers: { key: string; arn: string; label?: string | undefined }[] = [];\n for (const typeName of types) {\n for (const r of await pageResolvers(client, apiId, typeName)) {\n if (typeof r.resolverArn !== 'string') continue;\n if (typeof r.typeName !== 'string' || typeof r.fieldName !== 'string') continue;\n liveResolvers.push({\n key: `${r.typeName}|${r.fieldName}`,\n arn: r.resolverArn,\n label: `${r.typeName}.${r.fieldName}`,\n });\n }\n }\n const resolverAdded = diffGraphQLApiResolvers({ declaredResolverKeys, liveResolvers });\n\n // Functions are listed per api (not per type).\n const functions = await pageAppSyncFunctions(client, apiId);\n const liveFunctions = functions\n .filter(\n (f): f is AppSyncFunctionConfiguration & { functionArn: string } =>\n typeof f.functionArn === 'string'\n )\n .map((f) => ({ arn: f.functionArn, label: f.name ?? f.functionArn }));\n const functionAdded = diffGraphQLApiFunctions({ declaredFunctionArns, liveFunctions });\n\n return [...datasourceAdded, ...resolverAdded, ...functionAdded];\n}\n\n// ── CloudWatch Logs ────────────────────────────────────────────────────────────\n// An `AWS::Logs::LogGroup` owns MetricFilters AND SubscriptionFilters, each a separate\n// CloudFormation resource. A console / CLI `put-metric-filter` / `put-subscription-filter`\n// (someone wires a new metric filter, or — security-relevant — a new SUBSCRIPTION filter\n// streaming the log group's events to an out-of-band Lambda/Kinesis/Firehose destination)\n// is invisible to cdk drift / CFn drift detection (they only compare template-declared\n// resources). The LogGroup's own live model does NOT reflect either inline, so there is no\n// double-report to suppress. The CC primaryIdentifier for BOTH AWS::Logs::MetricFilter and\n// AWS::Logs::SubscriptionFilter is the composite `[\"/properties/LogGroupName\",\n// \"/properties/FilterName\"]`, so the `identifier` is `LogGroupName|FilterName`\n// (LogGroupName first) — what CC GetResource / DeleteResource consume.\n\n// Pure diff: declared filter names + live inventory -> the added filters, tagged with the\n// given CFn resourceType (MetricFilter or SubscriptionFilter). Metric- and subscription-\n// filter names are independent namespaces, so each is diffed against its OWN declared set.\n// `identifierOf` builds the CC composite identifier — the two types ORDER it DIFFERENTLY:\n// AWS::Logs::MetricFilter is `[\"/properties/LogGroupName\",\"/properties/FilterName\"]`\n// (LogGroupName|FilterName), AWS::Logs::SubscriptionFilter is the REVERSE\n// `[\"/properties/FilterName\",\"/properties/LogGroupName\"]` (FilterName|LogGroupName) — using\n// the wrong order makes CC GetResource/DeleteResource throw a ValidationException.\nfunction diffLogGroupFilters(\n logGroupName: string,\n resourceType: string,\n declaredFilterNames: string[],\n liveFilters: { name: string; label?: string | undefined }[],\n identifierOf: (filterName: string) => string\n): AddedChild[] {\n const declared = new Set(declaredFilterNames);\n const added: AddedChild[] = [];\n for (const f of liveFilters) {\n if (declared.has(f.name)) continue;\n added.push({\n resourceType,\n identifier: identifierOf(f.name),\n label: f.label ?? f.name,\n live: { FilterName: f.name, LogGroupName: logGroupName },\n });\n }\n return added;\n}\n\n// Pure diff: declared metric-filter names + live inventory -> the added metric filters.\nexport interface LogGroupChildInput {\n logGroupName: string;\n declaredFilterNames: string[]; // names of AWS::Logs::MetricFilter declared on this log group\n liveFilters: { name: string; label?: string | undefined }[];\n}\n\nexport function diffLogGroupChildren(input: LogGroupChildInput): AddedChild[] {\n return diffLogGroupFilters(\n input.logGroupName,\n 'AWS::Logs::MetricFilter',\n input.declaredFilterNames,\n input.liveFilters,\n (name) => `${input.logGroupName}|${name}` // CC composite LogGroupName|FilterName\n );\n}\n\n// Pure diff: declared subscription-filter names + live inventory -> the added ones.\nexport interface LogGroupSubscriptionInput {\n logGroupName: string;\n declaredFilterNames: string[]; // names of AWS::Logs::SubscriptionFilter declared on this log group\n liveFilters: { name: string; label?: string | undefined }[];\n}\n\nexport function diffLogGroupSubscriptionFilters(input: LogGroupSubscriptionInput): AddedChild[] {\n return diffLogGroupFilters(\n input.logGroupName,\n 'AWS::Logs::SubscriptionFilter',\n input.declaredFilterNames,\n input.liveFilters,\n // CC composite FilterName|LogGroupName (the REVERSE of MetricFilter — verified live)\n (name) => `${name}|${input.logGroupName}`\n );\n}\n\nasync function pageMetricFilters(\n client: CloudWatchLogsClient,\n logGroupName: string\n): Promise<CwlMetricFilter[]> {\n const out: CwlMetricFilter[] = [];\n let next: string | undefined;\n do {\n const res = await client.send(\n new DescribeMetricFiltersCommand({ logGroupName, nextToken: next })\n );\n out.push(...(res.metricFilters ?? []));\n next = res.nextToken;\n } while (next);\n return out;\n}\n\nasync function pageSubscriptionFilters(\n client: CloudWatchLogsClient,\n logGroupName: string\n): Promise<CwlSubscriptionFilter[]> {\n const out: CwlSubscriptionFilter[] = [];\n let next: string | undefined;\n do {\n const res = await client.send(\n new DescribeSubscriptionFiltersCommand({ logGroupName, nextToken: next })\n );\n out.push(...(res.subscriptionFilters ?? []));\n next = res.nextToken;\n } while (next);\n return out;\n}\n\nasync function enumerateLogGroupChildren(ctx: EnumeratorContext): Promise<AddedChild[]> {\n const { parent, desired, region } = ctx;\n const logGroupName = parent.physicalId; // a LogGroup's physical id IS its LogGroupName\n if (!logGroupName) return [];\n\n // Declared metric filters on THIS log group (Ref/GetAtt LogGroupName already resolved to\n // the physical id by gather). A filter's physical id (Ref) is its FilterName, but prefer a\n // literal declared FilterName when present.\n const declaredFilterNames: string[] = [];\n for (const r of desired.resources) {\n if (r.resourceType !== 'AWS::Logs::MetricFilter' || r.declared.LogGroupName !== logGroupName) {\n continue;\n }\n const name = typeof r.declared.FilterName === 'string' ? r.declared.FilterName : r.physicalId;\n if (name) declaredFilterNames.push(name);\n }\n\n // Declared subscription filters on THIS log group (separate name namespace from metric\n // filters). A SubscriptionFilter's physical id (Ref) is its FilterName.\n const declaredSubscriptionNames: string[] = [];\n for (const r of desired.resources) {\n if (\n r.resourceType !== 'AWS::Logs::SubscriptionFilter' ||\n r.declared.LogGroupName !== logGroupName\n ) {\n continue;\n }\n const name = typeof r.declared.FilterName === 'string' ? r.declared.FilterName : r.physicalId;\n if (name) declaredSubscriptionNames.push(name);\n }\n\n const client = new CloudWatchLogsClient({ region, ...READ_RETRY });\n const filters = await pageMetricFilters(client, logGroupName);\n const liveFilters = filters\n .filter((f): f is CwlMetricFilter & { filterName: string } => typeof f.filterName === 'string')\n .map((f) => ({ name: f.filterName }));\n const subs = await pageSubscriptionFilters(client, logGroupName);\n const liveSubs = subs\n .filter(\n (f): f is CwlSubscriptionFilter & { filterName: string } => typeof f.filterName === 'string'\n )\n .map((f) => ({ name: f.filterName }));\n\n return [\n ...diffLogGroupChildren({ logGroupName, declaredFilterNames, liveFilters }),\n ...diffLogGroupSubscriptionFilters({\n logGroupName,\n declaredFilterNames: declaredSubscriptionNames,\n liveFilters: liveSubs,\n }),\n ];\n}\n\n// ── Elastic Load Balancing v2 ──────────────────────────────────────────────────\n// An `AWS::ElasticLoadBalancingV2::LoadBalancer` owns Listeners, each a separate\n// CloudFormation resource. A console / CLI `create-listener` (someone wires a new\n// listener onto a load balancer out of band) is invisible to cdk drift / CFn drift\n// detection (they only compare template-declared resources). The LoadBalancer's own\n// live model does NOT reflect its listeners inline, so there is no double-report to\n// suppress. The CC primaryIdentifier for AWS::ElasticLoadBalancingV2::Listener is the\n// bare ListenerArn, which CC GetResource / DeleteResource consume.\n\n// Pure diff: declared listener arns + live inventory -> the added listeners.\nexport interface LoadBalancerChildInput {\n declaredListenerArns: string[]; // physical ids of AWS::ElasticLoadBalancingV2::Listener\n liveListeners: { arn: string; label?: string | undefined }[];\n}\n\nexport function diffLoadBalancerChildren(input: LoadBalancerChildInput): AddedChild[] {\n const declared = new Set(input.declaredListenerArns);\n const added: AddedChild[] = [];\n for (const l of input.liveListeners) {\n if (declared.has(l.arn)) continue;\n added.push({\n resourceType: 'AWS::ElasticLoadBalancingV2::Listener',\n identifier: l.arn, // ListenerArn IS the CC primaryIdentifier\n label: l.label ?? l.arn,\n live: { ListenerArn: l.arn },\n });\n }\n return added;\n}\n\nasync function pageListeners(\n client: ElasticLoadBalancingV2Client,\n loadBalancerArn: string\n): Promise<Elbv2Listener[]> {\n const out: Elbv2Listener[] = [];\n let marker: string | undefined;\n do {\n const res = await client.send(\n new DescribeListenersCommand({ LoadBalancerArn: loadBalancerArn, Marker: marker })\n );\n out.push(...(res.Listeners ?? []));\n marker = res.NextMarker;\n } while (marker);\n return out;\n}\n\nasync function enumerateLoadBalancerChildren(ctx: EnumeratorContext): Promise<AddedChild[]> {\n const { parent, desired, region } = ctx;\n const lbArn = parent.physicalId; // a LoadBalancer's physical id IS its LoadBalancerArn\n if (!lbArn) return [];\n\n // Declared listeners of THIS load balancer (Ref/GetAtt LoadBalancerArn already resolved\n // to the physical id by gather). A listener's physical id IS its ListenerArn.\n const declaredListenerArns: string[] = [];\n for (const r of desired.resources) {\n if (\n r.resourceType === 'AWS::ElasticLoadBalancingV2::Listener' &&\n r.declared.LoadBalancerArn === lbArn &&\n r.physicalId\n ) {\n declaredListenerArns.push(r.physicalId);\n }\n }\n\n const client = new ElasticLoadBalancingV2Client({ region, ...READ_RETRY });\n const listeners = await pageListeners(client, lbArn);\n const liveListeners = listeners\n .filter((l): l is Elbv2Listener & { ListenerArn: string } => typeof l.ListenerArn === 'string')\n .map((l) => ({ arn: l.ListenerArn, label: `${l.Protocol}:${l.Port}` }));\n\n return diffLoadBalancerChildren({ declaredListenerArns, liveListeners });\n}\n\n// A Listener (itself a declared template resource, AND enumerated as a child of its\n// LoadBalancer) owns ListenerRules, each a separate CloudFormation resource. A console /\n// CLI `create-rule` (someone wires a new routing rule onto a listener out of band) is\n// invisible to cdk drift / CFn drift detection (they only compare template-declared\n// resources). Every listener has an AWS-auto-created DEFAULT rule (`IsDefault`) that is\n// not a template resource and is never an out-of-band addition, so it is skipped. The\n// Listener's own live model does NOT reflect its rules inline, so there is no\n// double-report to suppress. The CC primaryIdentifier for\n// AWS::ElasticLoadBalancingV2::ListenerRule is the bare RuleArn, which CC GetResource /\n// DeleteResource consume.\n\n// Pure diff: declared rule arns + live inventory -> the added rules.\nexport interface ListenerChildInput {\n declaredRuleArns: string[]; // physical ids of AWS::ElasticLoadBalancingV2::ListenerRule\n liveRules: { arn: string; label?: string | undefined }[];\n}\n\nexport function diffListenerChildren(input: ListenerChildInput): AddedChild[] {\n const declared = new Set(input.declaredRuleArns);\n const added: AddedChild[] = [];\n for (const r of input.liveRules) {\n if (declared.has(r.arn)) continue;\n added.push({\n resourceType: 'AWS::ElasticLoadBalancingV2::ListenerRule',\n identifier: r.arn, // RuleArn IS the CC primaryIdentifier\n label: r.label ?? r.arn,\n live: { RuleArn: r.arn },\n });\n }\n return added;\n}\n\nasync function pageListenerRules(\n client: ElasticLoadBalancingV2Client,\n listenerArn: string\n): Promise<Elbv2Rule[]> {\n const out: Elbv2Rule[] = [];\n let marker: string | undefined;\n do {\n const res = await client.send(\n new DescribeRulesCommand({ ListenerArn: listenerArn, Marker: marker })\n );\n out.push(...(res.Rules ?? []));\n marker = res.NextMarker;\n } while (marker);\n return out;\n}\n\nasync function enumerateListenerChildren(ctx: EnumeratorContext): Promise<AddedChild[]> {\n const { parent, desired, region } = ctx;\n const listenerArn = parent.physicalId; // a Listener's physical id IS its ListenerArn\n if (!listenerArn) return [];\n\n // Declared rules of THIS listener (Ref/GetAtt ListenerArn already resolved to the\n // physical id by gather). A rule's physical id IS its RuleArn.\n const declaredRuleArns: string[] = [];\n for (const r of desired.resources) {\n if (\n r.resourceType === 'AWS::ElasticLoadBalancingV2::ListenerRule' &&\n r.declared.ListenerArn === listenerArn &&\n r.physicalId\n ) {\n declaredRuleArns.push(r.physicalId);\n }\n }\n\n const client = new ElasticLoadBalancingV2Client({ region, ...READ_RETRY });\n const rules = await pageListenerRules(client, listenerArn);\n const liveRules = rules\n // Skip the auto-created default rule: it is created with the listener, not a template\n // resource, and is never an out-of-band addition.\n .filter(\n (r): r is Elbv2Rule & { RuleArn: string } =>\n typeof r.RuleArn === 'string' && r.IsDefault !== true\n )\n .map((r) => ({ arn: r.RuleArn, label: r.Priority ? `priority ${r.Priority}` : r.RuleArn }));\n\n return diffListenerChildren({ declaredRuleArns, liveRules });\n}\n\n// ── EC2 (VPC) ──────────────────────────────────────────────────────────────────\n// An `AWS::EC2::VPC` owns Subnets, each a separate CloudFormation resource. A console\n// / CLI `create-subnet` (someone carves a new subnet into a VPC out of band) is\n// invisible to cdk drift / CFn drift detection (they only compare template-declared\n// resources). The VPC's own live model does NOT reflect its subnets inline, so there is\n// no double-report to suppress. The CC primaryIdentifier for AWS::EC2::Subnet is the\n// bare SubnetId, which CC GetResource / DeleteResource consume.\n\n// Pure diff: declared subnet ids + live inventory -> the added subnets.\nexport interface VpcChildInput {\n declaredSubnetIds: string[]; // physical ids (SubnetIds) of AWS::EC2::Subnet on this VPC\n liveSubnets: { id: string; label?: string | undefined }[];\n}\n\nexport function diffVpcChildren(input: VpcChildInput): AddedChild[] {\n const declared = new Set(input.declaredSubnetIds);\n const added: AddedChild[] = [];\n for (const s of input.liveSubnets) {\n if (declared.has(s.id)) continue;\n added.push({\n resourceType: 'AWS::EC2::Subnet',\n identifier: s.id, // SubnetId IS the CC primaryIdentifier\n label: s.label ?? s.id,\n live: { SubnetId: s.id },\n });\n }\n return added;\n}\n\nasync function pageSubnets(client: EC2Client, vpcId: string): Promise<Ec2Subnet[]> {\n const out: Ec2Subnet[] = [];\n let next: string | undefined;\n do {\n const res = await client.send(\n new DescribeSubnetsCommand({\n Filters: [{ Name: 'vpc-id', Values: [vpcId] }],\n NextToken: next,\n })\n );\n out.push(...(res.Subnets ?? []));\n next = res.NextToken;\n } while (next);\n return out;\n}\n\nasync function enumerateVpcChildren(ctx: EnumeratorContext): Promise<AddedChild[]> {\n const { parent, desired, region } = ctx;\n const vpcId = parent.physicalId; // a VPC's physical id IS its VpcId\n if (!vpcId) return [];\n\n // Declared subnets of THIS VPC (Ref/GetAtt VpcId already resolved to the physical id by\n // gather). A subnet's physical id IS its SubnetId.\n const declaredSubnetIds: string[] = [];\n for (const r of desired.resources) {\n if (r.resourceType === 'AWS::EC2::Subnet' && r.declared.VpcId === vpcId && r.physicalId) {\n declaredSubnetIds.push(r.physicalId);\n }\n }\n\n const client = new EC2Client({ region, ...READ_RETRY });\n const subnets = await pageSubnets(client, vpcId);\n const liveSubnets = subnets\n .filter((s): s is Ec2Subnet & { SubnetId: string } => typeof s.SubnetId === 'string')\n .map((s) => ({ id: s.SubnetId, label: s.CidrBlock ? `${s.CidrBlock}` : s.SubnetId }));\n\n return diffVpcChildren({ declaredSubnetIds, liveSubnets });\n}\n\n// ── EC2 (RouteTable) ────────────────────────────────────────────────────────────\n// An `AWS::EC2::RouteTable` owns Routes, each a separate CloudFormation resource. A\n// console / CLI `create-route` (someone adds a route to a route table out of band) is\n// invisible to cdk drift / CFn drift detection (they only compare template-declared\n// resources). The RouteTable's own live model does NOT reflect its routes inline (it\n// carries only RouteTableId / VpcId / Tags), so there is no double-report to suppress.\n// Non-declarable routes are skipped by `isEnumerableRoute`: the auto-created VPC-CIDR\n// LOCAL route (`Origin CreateRouteTable` / `GatewayId local`) and VGW-PROPAGATED routes\n// (`Origin EnableVgwRoutePropagation` — BGP/propagated, not declarable `AWS::EC2::Route`\n// resources). Only IPv4 routes (those with a DestinationCidrBlock) are handled, since the\n// CC identifier keys on CidrBlock. The CC primaryIdentifier for AWS::EC2::Route is the\n// composite `[\"/properties/RouteTableId\",\"/properties/CidrBlock\"]`, so the `identifier`\n// is the composite `RouteTableId|CidrBlock` (RouteTableId first) — that is what CC\n// GetResource / DeleteResource consume.\n\n// Pure diff: declared cidrs + live inventory -> the added routes.\nexport interface RouteTableChildInput {\n routeTableId: string;\n declaredCidrs: string[]; // DestinationCidrBlocks of AWS::EC2::Route declared on this table\n liveRoutes: { cidr: string }[];\n}\n\nexport function diffRouteTableChildren(input: RouteTableChildInput): AddedChild[] {\n const { routeTableId, declaredCidrs, liveRoutes } = input;\n const declared = new Set(declaredCidrs);\n const added: AddedChild[] = [];\n for (const route of liveRoutes) {\n if (declared.has(route.cidr)) continue;\n added.push({\n resourceType: 'AWS::EC2::Route',\n identifier: `${routeTableId}|${route.cidr}`, // CC composite RouteTableId|CidrBlock\n label: route.cidr,\n live: { RouteTableId: routeTableId, CidrBlock: route.cidr },\n });\n }\n return added;\n}\n\nasync function describeRouteTable(client: EC2Client, routeTableId: string): Promise<Ec2Route[]> {\n const res = await client.send(new DescribeRouteTablesCommand({ RouteTableIds: [routeTableId] }));\n return res.RouteTables?.[0]?.Routes ?? [];\n}\n\n// A live route is an enumerable out-of-band `AWS::EC2::Route` only if it is one a user\n// could have declared. EXCLUDED:\n// - the auto-created VPC-CIDR LOCAL route (Origin CreateRouteTable / GatewayId local);\n// - an IPv6-only route (no DestinationCidrBlock — the CC identifier keys on CidrBlock);\n// - a route inserted by VGW route PROPAGATION (Origin EnableVgwRoutePropagation): these\n// are BGP/propagated, not declarable `AWS::EC2::Route` resources, and AWS re-creates\n// them — flagging one as `added` is a false positive, and a `revert` DeleteResource\n// would either churn (AWS re-propagates) or fail. Pure + exported for unit tests.\nexport function isEnumerableRoute(\n route: Ec2Route\n): route is Ec2Route & { DestinationCidrBlock: string } {\n return (\n typeof route.DestinationCidrBlock === 'string' &&\n route.Origin !== 'CreateRouteTable' &&\n route.Origin !== 'EnableVgwRoutePropagation' &&\n route.GatewayId !== 'local'\n );\n}\n\nasync function enumerateRouteTableChildren(ctx: EnumeratorContext): Promise<AddedChild[]> {\n const { parent, desired, region } = ctx;\n const routeTableId = parent.physicalId; // a RouteTable's physical id IS its RouteTableId\n if (!routeTableId) return [];\n\n // Declared routes on THIS route table (Ref/GetAtt RouteTableId already resolved to the\n // physical id by gather). A route's CFn physical id is a generated token, so MATCH\n // declared routes by DestinationCidrBlock (the route's identity within the table).\n const declaredCidrs: string[] = [];\n for (const r of desired.resources) {\n if (\n r.resourceType === 'AWS::EC2::Route' &&\n r.declared.RouteTableId === routeTableId &&\n typeof r.declared.DestinationCidrBlock === 'string'\n ) {\n declaredCidrs.push(r.declared.DestinationCidrBlock);\n }\n }\n\n const client = new EC2Client({ region, ...READ_RETRY });\n const routes = await describeRouteTable(client, routeTableId);\n const liveRoutes = routes\n .filter(isEnumerableRoute)\n .map((route) => ({ cidr: route.DestinationCidrBlock }));\n\n return diffRouteTableChildren({ routeTableId, declaredCidrs, liveRoutes });\n}\n\n// ── ECS ──────────────────────────────────────────────────────────────────────\n// An `AWS::ECS::Cluster` owns Services, each a separate CloudFormation resource. A\n// console / CLI `create-service` (someone launches a new service onto a cluster out of\n// band) is invisible to cdk drift / CFn drift detection (they only compare\n// template-declared resources). The Cluster's own live model does NOT reflect its\n// services inline, so there is no double-report to suppress. The CC primaryIdentifier for\n// AWS::ECS::Service is the composite `[\"/properties/ServiceArn\",\"/properties/Cluster\"]`,\n// so the `identifier` is the composite `ServiceArn|Cluster` (ServiceArn first) — that is\n// what CC GetResource / DeleteResource consume.\n\n// Pure diff: declared service arns + live inventory -> the added services.\nexport interface EcsClusterChildInput {\n cluster: string; // the cluster name (the Cluster half of the composite identifier)\n declaredServiceArns: string[]; // physical ids (ServiceArns) of AWS::ECS::Service on this cluster\n liveServices: { arn: string; label?: string | undefined }[];\n}\n\nexport function diffEcsClusterChildren(input: EcsClusterChildInput): AddedChild[] {\n const { cluster, declaredServiceArns, liveServices } = input;\n const declared = new Set(declaredServiceArns);\n const added: AddedChild[] = [];\n for (const svc of liveServices) {\n if (declared.has(svc.arn)) continue;\n added.push({\n resourceType: 'AWS::ECS::Service',\n identifier: `${svc.arn}|${cluster}`, // CC composite ServiceArn|Cluster\n label: svc.label ?? svc.arn,\n live: { ServiceArn: svc.arn },\n });\n }\n return added;\n}\n\nasync function pageServices(client: ECSClient, cluster: string): Promise<string[]> {\n const out: string[] = [];\n let next: string | undefined;\n do {\n const res = await client.send(new ListServicesCommand({ cluster, nextToken: next }));\n for (const arn of res.serviceArns ?? []) {\n if (typeof arn === 'string') out.push(arn);\n }\n next = res.nextToken;\n } while (next);\n return out;\n}\n\nasync function enumerateEcsClusterChildren(ctx: EnumeratorContext): Promise<AddedChild[]> {\n const { parent, desired, region } = ctx;\n const cluster = parent.physicalId; // a Cluster's physical id IS its cluster name\n if (!cluster) return [];\n\n // The cluster ARN, for matching a declared service whose `Cluster` was resolved to the\n // ARN form (gather may resolve Ref/GetAtt to either the name or the ARN).\n const clusterArnRaw = desired.ctx.liveAttrs[parent.logicalId]?.Arn;\n const clusterArn = typeof clusterArnRaw === 'string' ? clusterArnRaw : undefined;\n\n // Declared services of THIS cluster (Ref/GetAtt Cluster already resolved by gather). A\n // service's physical id (Ref) IS its ServiceArn. Match services to this cluster by the\n // declared `Cluster` resolving to either the cluster name or its ARN.\n const declaredServiceArns: string[] = [];\n for (const r of desired.resources) {\n if (r.resourceType !== 'AWS::ECS::Service' || !r.physicalId) continue;\n const decl = r.declared.Cluster;\n if (decl === cluster || (clusterArn !== undefined && decl === clusterArn)) {\n declaredServiceArns.push(r.physicalId);\n }\n }\n\n const client = new ECSClient({ region, ...READ_RETRY });\n const arns = await pageServices(client, cluster);\n const liveServices = arns.map((arn) => ({ arn, label: arn.split('/').pop() }));\n\n return diffEcsClusterChildren({ cluster, declaredServiceArns, liveServices });\n}\n\n// ── KMS ──────────────────────────────────────────────────────────────────────\n// An `AWS::KMS::Key` owns Aliases, each a separate CloudFormation resource. A\n// console / CLI `create-alias` (someone points a new alias at a key out of band) is\n// invisible to cdk drift / CFn drift detection (they only compare template-declared\n// resources). The Key's own live model does NOT reflect its aliases inline, so there\n// is no double-report to suppress. The CC primaryIdentifier for AWS::KMS::Alias is the\n// bare AliasName (e.g. `alias/foo`), which CC GetResource / DeleteResource consume.\n\n// Pure diff: declared alias names + live inventory -> the added aliases.\nexport interface KmsKeyChildInput {\n declaredAliasNames: string[]; // AliasNames of AWS::KMS::Alias declared on this key\n liveAliases: { name: string; label?: string | undefined }[];\n}\n\nexport function diffKmsKeyChildren(input: KmsKeyChildInput): AddedChild[] {\n const declared = new Set(input.declaredAliasNames);\n const added: AddedChild[] = [];\n for (const alias of input.liveAliases) {\n if (declared.has(alias.name)) continue;\n added.push({\n resourceType: 'AWS::KMS::Alias',\n identifier: alias.name, // AliasName IS the CC primaryIdentifier\n label: alias.label ?? alias.name,\n live: { AliasName: alias.name },\n });\n }\n return added;\n}\n\nasync function pageAliases(client: KMSClient, keyId: string): Promise<AliasListEntry[]> {\n const out: AliasListEntry[] = [];\n let marker: string | undefined;\n do {\n const res = await client.send(new ListAliasesCommand({ KeyId: keyId, Marker: marker }));\n out.push(...(res.Aliases ?? []));\n marker = res.NextMarker;\n } while (marker);\n return out;\n}\n\nasync function enumerateKmsKeyChildren(ctx: EnumeratorContext): Promise<AddedChild[]> {\n const { parent, desired, region } = ctx;\n const keyId = parent.physicalId; // a Key's physical id IS its KeyId (UUID)\n if (!keyId) return [];\n\n // Declared aliases targeting THIS key. An alias's TargetKeyId (resolved by gather) is\n // either the bare KeyId or the key ARN; tolerate both. An alias's CFn physical id (Ref)\n // IS its AliasName, so fall back to the physical id when AliasName is not a literal.\n const keyArnRaw = desired.ctx.liveAttrs[parent.logicalId]?.Arn;\n const keyArn = typeof keyArnRaw === 'string' ? keyArnRaw : undefined;\n const declaredAliasNames: string[] = [];\n for (const r of desired.resources) {\n if (r.resourceType !== 'AWS::KMS::Alias') continue;\n const target = r.declared.TargetKeyId;\n if (target !== keyId && !(keyArn !== undefined && target === keyArn)) continue;\n const name = typeof r.declared.AliasName === 'string' ? r.declared.AliasName : r.physicalId;\n if (name) declaredAliasNames.push(name);\n }\n\n const client = new KMSClient({ region, ...READ_RETRY });\n const aliases = await pageAliases(client, keyId);\n const liveAliases = aliases\n .filter((a): a is AliasListEntry & { AliasName: string } => typeof a.AliasName === 'string')\n .map((a) => ({ name: a.AliasName }));\n\n return diffKmsKeyChildren({ declaredAliasNames, liveAliases });\n}\n\n// ── AppConfig ──────────────────────────────────────────────────────────────────\n// An `AWS::AppConfig::Application` owns Environments AND ConfigurationProfiles, each a\n// separate CloudFormation resource. A console / CLI `create-environment` /\n// `create-configuration-profile` (someone adds a new environment or configuration profile\n// to an application out of band) is invisible to cdk drift / CFn drift detection (they only\n// compare template-declared resources). The Application's own live model does NOT reflect\n// its environments or profiles inline, so there is no double-report to suppress. The CC\n// primaryIdentifier for AWS::AppConfig::Environment is the composite\n// `[\"/properties/ApplicationId\",\"/properties/EnvironmentId\"]` and for\n// AWS::AppConfig::ConfigurationProfile the composite\n// `[\"/properties/ApplicationId\",\"/properties/ConfigurationProfileId\"]`, so the `identifier`\n// is the composite `ApplicationId|EnvironmentId` / `ApplicationId|ConfigurationProfileId`\n// (ApplicationId first) — that is what CC GetResource / DeleteResource consume.\n\n// Pure diff: declared environment ids + live inventory -> the added environments.\nexport interface AppConfigApplicationChildInput {\n applicationId: string;\n declaredEnvironmentIds: string[]; // physical ids (EnvironmentIds) of AWS::AppConfig::Environment\n liveEnvironments: { id: string; label?: string | undefined }[];\n}\n\nexport function diffAppConfigApplicationChildren(\n input: AppConfigApplicationChildInput\n): AddedChild[] {\n const { applicationId, declaredEnvironmentIds, liveEnvironments } = input;\n const declared = new Set(declaredEnvironmentIds);\n const added: AddedChild[] = [];\n for (const e of liveEnvironments) {\n if (declared.has(e.id)) continue;\n added.push({\n resourceType: 'AWS::AppConfig::Environment',\n identifier: `${applicationId}|${e.id}`, // CC composite ApplicationId|EnvironmentId\n label: e.label ?? e.id,\n live: { EnvironmentId: e.id, ApplicationId: applicationId },\n });\n }\n return added;\n}\n\nasync function pageAppConfigEnvironments(\n client: AppConfigClient,\n applicationId: string\n): Promise<AppConfigEnvironment[]> {\n const out: AppConfigEnvironment[] = [];\n let next: string | undefined;\n do {\n const res = await client.send(\n new ListEnvironmentsCommand({ ApplicationId: applicationId, NextToken: next })\n );\n out.push(...(res.Items ?? []));\n next = res.NextToken;\n } while (next);\n return out;\n}\n\n// Pure diff: declared configuration-profile ids + live inventory -> the added profiles.\nexport interface AppConfigProfilesInput {\n applicationId: string;\n declaredProfileIds: string[]; // physical ids (ConfigurationProfileIds) of the declared profiles\n liveProfiles: { id: string; label?: string | undefined }[];\n}\n\nexport function diffAppConfigProfiles(input: AppConfigProfilesInput): AddedChild[] {\n const { applicationId, declaredProfileIds, liveProfiles } = input;\n const declared = new Set(declaredProfileIds);\n const added: AddedChild[] = [];\n for (const p of liveProfiles) {\n if (declared.has(p.id)) continue;\n added.push({\n resourceType: 'AWS::AppConfig::ConfigurationProfile',\n identifier: `${applicationId}|${p.id}`, // CC composite ApplicationId|ConfigurationProfileId\n label: p.label ?? p.id,\n live: { ConfigurationProfileId: p.id, ApplicationId: applicationId },\n });\n }\n return added;\n}\n\nasync function pageAppConfigProfiles(\n client: AppConfigClient,\n applicationId: string\n): Promise<AppConfigConfigurationProfile[]> {\n const out: AppConfigConfigurationProfile[] = [];\n let next: string | undefined;\n do {\n const res = await client.send(\n new ListConfigurationProfilesCommand({ ApplicationId: applicationId, NextToken: next })\n );\n out.push(...(res.Items ?? []));\n next = res.NextToken;\n } while (next);\n return out;\n}\n\nasync function enumerateAppConfigApplicationChildren(\n ctx: EnumeratorContext\n): Promise<AddedChild[]> {\n const { parent, desired, region } = ctx;\n const applicationId = parent.physicalId; // an Application's physical id IS its ApplicationId\n if (!applicationId) return [];\n\n // Declared environments of THIS application (Ref/GetAtt ApplicationId already resolved to\n // the physical id by gather). An environment's CFn physical id (Ref) IS its EnvironmentId.\n const declaredEnvironmentIds: string[] = [];\n // Declared configuration profiles of THIS application. A profile's CFn physical id (Ref)\n // IS its ConfigurationProfileId.\n const declaredProfileIds: string[] = [];\n for (const r of desired.resources) {\n if (\n r.resourceType === 'AWS::AppConfig::Environment' &&\n r.declared.ApplicationId === applicationId &&\n r.physicalId\n ) {\n declaredEnvironmentIds.push(r.physicalId);\n } else if (\n r.resourceType === 'AWS::AppConfig::ConfigurationProfile' &&\n r.declared.ApplicationId === applicationId &&\n r.physicalId\n ) {\n declaredProfileIds.push(r.physicalId);\n }\n }\n\n const client = new AppConfigClient({ region, ...READ_RETRY });\n\n const environments = await pageAppConfigEnvironments(client, applicationId);\n const liveEnvironments = environments\n .filter((e): e is AppConfigEnvironment & { Id: string } => typeof e.Id === 'string')\n .map((e) => ({ id: e.Id, label: e.Name ?? e.Id }));\n const environmentAdded = diffAppConfigApplicationChildren({\n applicationId,\n declaredEnvironmentIds,\n liveEnvironments,\n });\n\n const profiles = await pageAppConfigProfiles(client, applicationId);\n const liveProfiles = profiles\n .filter((p): p is AppConfigConfigurationProfile & { Id: string } => typeof p.Id === 'string')\n .map((p) => ({ id: p.Id, label: p.Name ?? p.Id }));\n const profileAdded = diffAppConfigProfiles({\n applicationId,\n declaredProfileIds,\n liveProfiles,\n });\n\n return [...environmentAdded, ...profileAdded];\n}\n\n// ── EFS ──────────────────────────────────────────────────────────────────────\n// An `AWS::EFS::FileSystem` owns MountTargets, each a separate CloudFormation resource.\n// A console / CLI `create-mount-target` (someone attaches a new mount target to a file\n// system in an out-of-band subnet) is invisible to cdk drift / CFn drift detection (they\n// only compare template-declared resources). The FileSystem's own live model does NOT\n// reflect its mount targets inline, so there is no double-report to suppress. The CC\n// primaryIdentifier for AWS::EFS::MountTarget is the bare mount-target Id (fsmt-...),\n// which CC GetResource / DeleteResource consume.\n\n// Pure diff: declared mount-target ids + live inventory -> the added mount targets.\nexport interface EfsFileSystemChildInput {\n declaredMountTargetIds: string[]; // physical ids (MountTargetIds) of AWS::EFS::MountTarget\n liveMountTargets: { id: string; label?: string | undefined }[];\n}\n\nexport function diffEfsFileSystemChildren(input: EfsFileSystemChildInput): AddedChild[] {\n const declared = new Set(input.declaredMountTargetIds);\n const added: AddedChild[] = [];\n for (const mt of input.liveMountTargets) {\n if (declared.has(mt.id)) continue;\n added.push({\n resourceType: 'AWS::EFS::MountTarget',\n identifier: mt.id, // the mount-target Id IS the CC primaryIdentifier\n label: mt.label ?? mt.id,\n live: { Id: mt.id },\n });\n }\n return added;\n}\n\nasync function pageMountTargets(\n client: EFSClient,\n fileSystemId: string\n): Promise<MountTargetDescription[]> {\n const out: MountTargetDescription[] = [];\n let marker: string | undefined;\n do {\n const res = await client.send(\n new DescribeMountTargetsCommand({ FileSystemId: fileSystemId, Marker: marker })\n );\n out.push(...(res.MountTargets ?? []));\n marker = res.NextMarker;\n } while (marker);\n return out;\n}\n\nasync function enumerateEfsFileSystemChildren(ctx: EnumeratorContext): Promise<AddedChild[]> {\n const { parent, desired, region } = ctx;\n const fileSystemId = parent.physicalId; // a FileSystem's physical id IS its FileSystemId\n if (!fileSystemId) return [];\n\n // Declared mount targets of THIS file system (Ref/GetAtt FileSystemId already resolved to\n // the physical id by gather). A mount target's CFn physical id (Ref) IS its MountTargetId.\n const declaredMountTargetIds: string[] = [];\n for (const r of desired.resources) {\n if (\n r.resourceType === 'AWS::EFS::MountTarget' &&\n r.declared.FileSystemId === fileSystemId &&\n r.physicalId\n ) {\n declaredMountTargetIds.push(r.physicalId);\n }\n }\n\n const client = new EFSClient({ region, ...READ_RETRY });\n const mountTargets = await pageMountTargets(client, fileSystemId);\n const liveMountTargets = mountTargets\n .filter(\n (mt): mt is MountTargetDescription & { MountTargetId: string } =>\n typeof mt.MountTargetId === 'string'\n )\n .map((mt) => ({\n id: mt.MountTargetId,\n label: mt.SubnetId ? `${mt.MountTargetId} (${mt.SubnetId})` : mt.MountTargetId,\n }));\n\n return diffEfsFileSystemChildren({ declaredMountTargetIds, liveMountTargets });\n}\n\n// ── RDS ────────────────────────────────────────────────────────────────────────\n// An `AWS::RDS::DBCluster` owns DBInstances (the cluster's writer / reader members),\n// each a separate CloudFormation resource. A console / CLI `create-db-instance`\n// (someone adds a new reader instance to a cluster out of band) is invisible to cdk\n// drift / CFn drift detection (they only compare template-declared resources). The\n// DBCluster's own live model does NOT reflect its instances inline, so there is no\n// double-report to suppress. The CC primaryIdentifier for AWS::RDS::DBInstance is the\n// bare DBInstanceIdentifier, which CC GetResource / DeleteResource consume.\n\n// Pure diff: declared instance ids + live inventory -> the added DB instances.\nexport interface RdsClusterChildInput {\n declaredInstanceIds: string[]; // physical ids (DBInstanceIdentifiers) of AWS::RDS::DBInstance\n liveInstances: { id: string; label?: string | undefined }[];\n}\n\nexport function diffRdsClusterChildren(input: RdsClusterChildInput): AddedChild[] {\n const declared = new Set(input.declaredInstanceIds);\n const added: AddedChild[] = [];\n for (const i of input.liveInstances) {\n if (declared.has(i.id)) continue;\n added.push({\n resourceType: 'AWS::RDS::DBInstance',\n identifier: i.id, // DBInstanceIdentifier IS the CC primaryIdentifier\n label: i.label ?? i.id,\n live: { DBInstanceIdentifier: i.id },\n });\n }\n return added;\n}\n\nasync function pageDbInstances(client: RDSClient, clusterId: string): Promise<RdsDBInstance[]> {\n const out: RdsDBInstance[] = [];\n let marker: string | undefined;\n do {\n const res = await client.send(\n new DescribeDBInstancesCommand({\n Filters: [{ Name: 'db-cluster-id', Values: [clusterId] }],\n Marker: marker,\n })\n );\n out.push(...(res.DBInstances ?? []));\n marker = res.Marker;\n } while (marker);\n return out;\n}\n\nasync function enumerateRdsClusterChildren(ctx: EnumeratorContext): Promise<AddedChild[]> {\n const { parent, desired, region } = ctx;\n const clusterId = parent.physicalId; // a DBCluster's physical id IS its DBClusterIdentifier\n if (!clusterId) return [];\n\n // Declared instances of THIS cluster (Ref/GetAtt DBClusterIdentifier already resolved to\n // the physical id by gather). A DBInstance's CFn physical id (Ref) IS its DBInstanceIdentifier.\n const declaredInstanceIds: string[] = [];\n for (const r of desired.resources) {\n if (\n r.resourceType === 'AWS::RDS::DBInstance' &&\n r.declared.DBClusterIdentifier === clusterId &&\n r.physicalId\n ) {\n declaredInstanceIds.push(r.physicalId);\n }\n }\n\n const client = new RDSClient({ region, ...READ_RETRY });\n const instances = await pageDbInstances(client, clusterId);\n const liveInstances = instances\n .filter(\n (i): i is RdsDBInstance & { DBInstanceIdentifier: string } =>\n typeof i.DBInstanceIdentifier === 'string'\n )\n .map((i) => ({ id: i.DBInstanceIdentifier, label: i.DBInstanceIdentifier }));\n\n return diffRdsClusterChildren({ declaredInstanceIds, liveInstances });\n}\n","import { createHash } from 'node:crypto';\n\n// A stable, order- and whitespace-insensitive digest of a PEM CA-certificate BUNDLE — the\n// integrity signal cdkrd records for an ELBv2 TrustStore, whose CA bundle location is\n// writeOnly (unreadable) but whose live CONTENT is reachable via a presigned S3 URL\n// (issue #505). A TrustStore's trust anchors are a SET, so the certificates are canonicalized\n// (base64 body only, all whitespace stripped) and SORTED before hashing — reordering or\n// re-wrapping the same anchors yields the same hash, while adding / removing / swapping any\n// anchor changes it. Returns undefined when the text contains no CERTIFICATE block (e.g. a\n// failed fetch returned HTML), so a bogus hash is never recorded.\nexport function hashCaBundle(pem: unknown): string | undefined {\n if (typeof pem !== 'string') return undefined;\n const bodies: string[] = [];\n const re = /-----BEGIN CERTIFICATE-----([\\s\\S]*?)-----END CERTIFICATE-----/g;\n for (let m = re.exec(pem); m !== null; m = re.exec(pem)) {\n const body = (m[1] ?? '').replace(/\\s+/g, '');\n if (body.length > 0) bodies.push(body);\n }\n if (bodies.length === 0) return undefined;\n bodies.sort();\n return createHash('sha256').update(bodies.join('\\n')).digest('hex');\n}\n","// SDK-override readers for common CFn types that Cloud Control API cannot read\n// (GetResource → UnsupportedActionException). Read logic mirrors cdkd's SDK\n// providers, but keyed off the resolved DECLARED properties (Bucket / Topics /\n// Queues / Roles / FunctionName / policy ARN) — NOT the CloudFormation physical\n// id, because CFn assigns these policy-attachment resources physical ids that\n// differ from the underlying target. Returns CFn-shaped properties for the\n// classifier; undefined when the target can't be resolved/read (→ skipped).\n\nimport { AppSyncClient, ListApiKeysCommand } from '@aws-sdk/client-appsync';\nimport { BudgetsClient, DescribeBudgetCommand } from '@aws-sdk/client-budgets';\nimport { CloudControlClient, GetResourceCommand } from '@aws-sdk/client-cloudcontrol';\nimport { CognitoSyncClient, GetCognitoEventsCommand } from '@aws-sdk/client-cognito-sync';\nimport {\n BatchGetProjectsCommand,\n BatchGetReportGroupsCommand,\n CodeBuildClient,\n} from '@aws-sdk/client-codebuild';\nimport { DescribeServicesCommand, ECSClient } from '@aws-sdk/client-ecs';\nimport {\n DescribeDBClustersCommand,\n DescribeDBInstancesCommand,\n DocDBClient,\n} from '@aws-sdk/client-docdb';\nimport {\n CloudWatchLogsClient,\n DescribeMetricFiltersCommand,\n type MetricFilter,\n} from '@aws-sdk/client-cloudwatch-logs';\nimport {\n DescribeAddressesCommand,\n DescribeClientVpnAuthorizationRulesCommand,\n DescribeClientVpnEndpointsCommand,\n DescribeClientVpnTargetNetworksCommand,\n DescribeLaunchTemplateVersionsCommand,\n DescribeNetworkAclsCommand,\n EC2Client,\n} from '@aws-sdk/client-ec2';\nimport {\n DAXClient,\n DescribeClustersCommand,\n DescribeParameterGroupsCommand,\n DescribeParametersCommand as DescribeDaxParametersCommand,\n DescribeSubnetGroupsCommand,\n} from '@aws-sdk/client-dax';\nimport {\n GetClassifierCommand,\n GetConnectionCommand,\n GetTableCommand,\n GetWorkflowCommand,\n GlueClient,\n} from '@aws-sdk/client-glue';\nimport {\n ListResourceRecordSetsCommand,\n type ListResourceRecordSetsCommandOutput,\n type ResourceRecordSet,\n type RRType,\n Route53Client,\n} from '@aws-sdk/client-route-53';\nimport {\n GetGroupPolicyCommand,\n GetPolicyCommand,\n GetPolicyVersionCommand,\n GetRolePolicyCommand,\n GetUserPolicyCommand,\n IAMClient,\n ListEntitiesForPolicyCommand,\n} from '@aws-sdk/client-iam';\nimport { LambdaClient, GetPolicyCommand as LambdaGetPolicyCommand } from '@aws-sdk/client-lambda';\nimport { GetBucketPolicyCommand, S3Client } from '@aws-sdk/client-s3';\nimport {\n DescribeCacheClustersCommand,\n DescribeReplicationGroupsCommand,\n DescribeUsersCommand as DescribeCacheUsersCommand,\n ElastiCacheClient,\n} from '@aws-sdk/client-elasticache';\nimport {\n DescribeUsersCommand as DescribeMemoryDbUsersCommand,\n MemoryDBClient,\n} from '@aws-sdk/client-memorydb';\nimport {\n type AnomalyDetector,\n CloudWatchClient,\n DescribeAnomalyDetectorsCommand,\n} from '@aws-sdk/client-cloudwatch';\nimport { DLMClient, GetLifecyclePolicyCommand } from '@aws-sdk/client-dlm';\nimport {\n DatabaseMigrationServiceClient,\n DescribeEndpointsCommand,\n DescribeReplicationSubnetGroupsCommand,\n} from '@aws-sdk/client-database-migration-service';\nimport {\n GetJobTemplateCommand,\n GetQueueCommand,\n MediaConvertClient,\n} from '@aws-sdk/client-mediaconvert';\nimport {\n ElasticLoadBalancingV2Client,\n GetTrustStoreCaCertificatesBundleCommand,\n} from '@aws-sdk/client-elastic-load-balancing-v2';\nimport {\n DescribeConfigurationCommand,\n DescribeConfigurationRevisionCommand,\n KafkaClient,\n} from '@aws-sdk/client-kafka';\nimport { GetWorkgroupCommand, RedshiftServerlessClient } from '@aws-sdk/client-redshift-serverless';\nimport {\n DescribeBotLocaleCommand,\n DescribeIntentCommand,\n DescribeSlotCommand,\n DescribeSlotTypeCommand,\n LexModelsV2Client,\n ListBotLocalesCommand,\n ListIntentsCommand,\n ListSlotsCommand,\n ListSlotTypesCommand,\n} from '@aws-sdk/client-lex-models-v2';\nimport { GetScheduleCommand, SchedulerClient } from '@aws-sdk/client-scheduler';\nimport {\n DescribeReceiptRuleCommand,\n DescribeReceiptRuleSetCommand,\n ListReceiptFiltersCommand,\n type ReceiptRule,\n SESClient,\n} from '@aws-sdk/client-ses';\nimport { DescribeParametersCommand, SSMClient } from '@aws-sdk/client-ssm';\nimport {\n GetNamespaceCommand,\n GetServiceCommand,\n ServiceDiscoveryClient,\n} from '@aws-sdk/client-servicediscovery';\nimport { GetTopicAttributesCommand, SNSClient } from '@aws-sdk/client-sns';\nimport { GetQueueAttributesCommand, SQSClient } from '@aws-sdk/client-sqs';\nimport { ResourceGoneError } from '../aws-errors.js';\nimport { READ_RETRY } from './client-config.js';\nimport { hashCaBundle } from './pem.js';\n\nexport interface OverrideCtx {\n physicalId: string;\n declared: Record<string, unknown>;\n region: string;\n accountId: string;\n // The resource's CloudFormation type — set on the REVERT (SdkWriter) path so a\n // type-agnostic writer (the Cloud Control index-revert for nested array-element values)\n // can GetResource/UpdateResource it. Unused by the read (OverrideReader) path.\n resourceType?: string;\n // The Cloud Control identifier — the composite the READ path resolves via\n // CC_IDENTIFIER_ADAPTERS (e.g. AWS::ApiGateway::Stage = `RestApiId|StageName`), set on the\n // REVERT (SdkWriter) path. A Cloud-Control-routed writer (writeCloudControlIndexNested)\n // MUST address the resource by this, not the bare CFn physical id, or GetResource /\n // UpdateResource ValidationException. Falls back to `physicalId` when no adapter applies.\n identifier?: string;\n}\nexport type OverrideReader = (ctx: OverrideCtx) => Promise<Record<string, unknown> | undefined>;\n\nconst str = (v: unknown): string | undefined =>\n typeof v === 'string' && v.length > 0 ? v : undefined;\nconst firstStr = (v: unknown): string | undefined => (Array.isArray(v) ? str(v[0]) : str(v));\nfunction parsePolicy(s: string | undefined): unknown {\n if (!s) return undefined;\n for (const c of [s, safeDecode(s)]) {\n try {\n return JSON.parse(c);\n } catch {\n /* keep trying */\n }\n }\n return s;\n}\nfunction safeDecode(s: string): string {\n try {\n return decodeURIComponent(s);\n } catch {\n return s;\n }\n}\n\nconst readS3BucketPolicy: OverrideReader = async ({ declared, region }) => {\n const bucket = str(declared.Bucket);\n if (!bucket) return undefined;\n const c = new S3Client({ region, ...READ_RETRY });\n const r = await c.send(new GetBucketPolicyCommand({ Bucket: bucket }));\n return { Bucket: bucket, PolicyDocument: parsePolicy(r.Policy) };\n};\n\nconst readSnsTopicPolicy: OverrideReader = async ({ declared, region }) => {\n const topic = firstStr(declared.Topics);\n if (!topic) return undefined;\n const c = new SNSClient({ region, ...READ_RETRY });\n const r = await c.send(new GetTopicAttributesCommand({ TopicArn: topic }));\n return { Topics: declared.Topics, PolicyDocument: parsePolicy(r.Attributes?.Policy) };\n};\n\nconst readSqsQueuePolicy: OverrideReader = async ({ declared, region }) => {\n const queue = firstStr(declared.Queues);\n if (!queue) return undefined;\n const c = new SQSClient({ region, ...READ_RETRY });\n const r = await c.send(\n new GetQueueAttributesCommand({ QueueUrl: queue, AttributeNames: ['Policy'] })\n );\n return { Queues: declared.Queues, PolicyDocument: parsePolicy(r.Attributes?.Policy) };\n};\n\nconst readIamPolicy: OverrideReader = async ({ declared, region }) => {\n const name = str(declared.PolicyName);\n if (!name) return undefined;\n const c = new IAMClient({ region, ...READ_RETRY });\n const role = firstStr(declared.Roles);\n const user = firstStr(declared.Users);\n const group = firstStr(declared.Groups);\n let doc: string | undefined;\n if (role)\n doc = (await c.send(new GetRolePolicyCommand({ RoleName: role, PolicyName: name })))\n .PolicyDocument;\n else if (user)\n doc = (await c.send(new GetUserPolicyCommand({ UserName: user, PolicyName: name })))\n .PolicyDocument;\n else if (group)\n doc = (await c.send(new GetGroupPolicyCommand({ GroupName: group, PolicyName: name })))\n .PolicyDocument;\n else return undefined;\n return {\n PolicyName: name,\n PolicyDocument: parsePolicy(doc),\n ...(role\n ? { Roles: declared.Roles }\n : user\n ? { Users: declared.Users }\n : { Groups: declared.Groups }),\n };\n};\n\nconst readIamManagedPolicy: OverrideReader = async ({ physicalId, region }) => {\n // CFn physical id for a managed policy IS its ARN.\n if (!physicalId.startsWith('arn:')) return undefined;\n const c = new IAMClient({ region, ...READ_RETRY });\n const p = (await c.send(new GetPolicyCommand({ PolicyArn: physicalId }))).Policy;\n if (!p) return undefined;\n const ver = (\n await c.send(\n new GetPolicyVersionCommand({ PolicyArn: physicalId, VersionId: p.DefaultVersionId })\n )\n ).PolicyVersion;\n // Live attachment lists (the Roles/Users/Groups this policy is attached to). Read\n // them so classify can detect an out-of-band DETACH of a member the template\n // DECLARES — but the comparison is ASYMMETRIC (declared∖live only): the live set is\n // a UNION that legitimately exceeds any one stack's intent (a role's\n // `ManagedPolicyArns`, another stack, the console), so live-only members are never\n // a finding (see IAM_ATTACHMENT_SUBSET in diff/classify.ts). Names, not ARNs —\n // matching the CFn `Roles`/`Users`/`Groups` property shape (a Ref to a role\n // resolves to the role NAME). Paginated: a popular managed policy can be attached\n // to far more than one page of entities.\n const roles: string[] = [];\n const users: string[] = [];\n const groups: string[] = [];\n let marker: string | undefined;\n do {\n const e = await c.send(\n new ListEntitiesForPolicyCommand({ PolicyArn: physicalId, Marker: marker })\n );\n for (const r of e?.PolicyRoles ?? []) if (r.RoleName) roles.push(r.RoleName);\n for (const u of e?.PolicyUsers ?? []) if (u.UserName) users.push(u.UserName);\n for (const g of e?.PolicyGroups ?? []) if (g.GroupName) groups.push(g.GroupName);\n marker = e?.IsTruncated ? e.Marker : undefined;\n } while (marker);\n // GetPolicy OMITS Description when it is empty, while CDK templates declare\n // `Description: \"\"` — an undefined-valued key here read as `desired=\"\" actual=\n // undefined` false declared drift (first live policies integ run, R69). An\n // absent live description IS the empty description.\n return {\n PolicyDocument: parsePolicy(ver?.Document),\n Path: p.Path,\n Description: p.Description ?? '',\n Roles: roles,\n Users: users,\n Groups: groups,\n };\n};\n\nconst readLambdaPermission: OverrideReader = async ({ declared, physicalId, region }) => {\n const fn = str(declared.FunctionName);\n if (!fn) return undefined;\n const c = new LambdaClient({ region, ...READ_RETRY });\n // GetPolicy throws ResourceNotFoundException when the function has NO resource\n // policy at all — i.e. the permission was deleted out of band. Let it propagate\n // so the router maps it to `deleted` rather than swallowing it as skipped.\n const policy = parsePolicy(\n (await c.send(new LambdaGetPolicyCommand({ FunctionName: fn }))).Policy\n );\n const stmts = (policy as { Statement?: Array<Record<string, unknown>> })?.Statement ?? [];\n // The CFn physical id of an AWS::Lambda::Permission IS its statement `Sid` — match on\n // it FIRST so the correct statement is read back unambiguously. This matters when one\n // function carries SEVERAL permissions that share Action + Principal: the CDK API\n // Gateway integration emits two (the deployment-stage permission and a parallel\n // `test-invoke-stage` one), both `lambda:InvokeFunction` for `apigateway.amazonaws.com`,\n // differing ONLY in SourceArn. The Action+Principal fallback below returns the FIRST\n // match for BOTH, so the deployment-stage permission read back the `test-invoke-stage`\n // SourceArn — a false `declared` drift on every clean deploy.\n const byId = physicalId ? stmts.find((s) => s.Sid === physicalId) : undefined;\n // best-effort fallback match by Action + Principal against the declared permission\n // (a permission whose physical id is not the live Sid, or a renamed statement).\n const want = { action: str(declared.Action), principal: str(declared.Principal) };\n const m =\n byId ??\n stmts.find(\n (s) =>\n (!want.action || s.Action === want.action) &&\n (!want.principal || JSON.stringify(s.Principal).includes(String(want.principal)))\n );\n // No match while the policy itself exists = the specific statement was removed out\n // of band (but other statements remain). Return undefined → router maps it to\n // `skipped` (target not resolvable), NOT `deleted`: safely asserting THIS statement\n // is gone needs its StatementId, which the best-effort Action+Principal match lacks.\n // A wholly-deleted resource policy throws ResourceNotFoundException above → `deleted`.\n if (!m) return undefined;\n // Return the MATCHED statement's REAL fields — never echo the declared template\n // (an echoed Principal makes a Principal drift structurally undetectable).\n // Normalize the statement Principal to CFn shape: {Service:\"x\"}/{AWS:\"x\"} -> \"x\",\n // a plain string stays as-is.\n const cond = m.Condition as\n | { ArnLike?: Record<string, unknown>; StringEquals?: Record<string, unknown> }\n | undefined;\n const sourceArn = str(cond?.ArnLike?.['AWS:SourceArn']);\n const sourceAccount = str(cond?.StringEquals?.['AWS:SourceAccount']);\n // Security-scoping conditions that were NOT projected, so an out-of-band widening\n // was invisible: PrincipalOrgID restricts invocation to an AWS Organization\n // (dropping it opens the function to any matching principal), and\n // FunctionUrlAuthType gates a function-URL permission (a flip from AWS_IAM to NONE\n // makes the URL public). Both are stored under the verbatim global/service\n // condition keys (lowercase `aws:`/`lambda:`, unlike Lambda's own capitalized\n // `AWS:Source*`). Absent unless the permission uses them → omitted, no noise.\n const principalOrgId = str(cond?.StringEquals?.['aws:PrincipalOrgID']);\n const functionUrlAuthType = str(cond?.StringEquals?.['lambda:FunctionUrlAuthType']);\n return {\n FunctionName: fn,\n Action: m.Action,\n Principal: normalizeLambdaPrincipal(m.Principal),\n // omit SourceArn/SourceAccount when absent (→ readGap, honest; never fabricate)\n ...(sourceArn !== undefined && { SourceArn: sourceArn }),\n ...(sourceAccount !== undefined && { SourceAccount: sourceAccount }),\n ...(principalOrgId !== undefined && { PrincipalOrgID: principalOrgId }),\n ...(functionUrlAuthType !== undefined && { FunctionUrlAuthType: functionUrlAuthType }),\n };\n};\n\n// Lambda resource-policy Principal -> CFn Principal shape. AWS stores it as\n// {Service:\"x\"} or {AWS:\"x\"}; CFn declares the bare string. A plain string (or\n// anything else) is returned unchanged.\nfunction normalizeLambdaPrincipal(p: unknown): unknown {\n if (p && typeof p === 'object') {\n const o = p as Record<string, unknown>;\n if (typeof o.Service === 'string') return o.Service;\n if (typeof o.AWS === 'string') return o.AWS;\n }\n return p;\n}\n\nconst readBudget: OverrideReader = async ({ physicalId, declared, accountId, region }) => {\n // The CFn physical id of AWS::Budgets::Budget IS the budget name — and unlike\n // declared.Budget.BudgetName it is always present, including the common case\n // where the template declares no name and CFn generates one\n // (`<logicalId>-<region>-<ts>-...`). Resolving by declared name only skipped\n // exactly those budgets whole-resource (dogfood, R65); declared name stays as\n // the fallback for safety.\n const budget = declared.Budget as Record<string, unknown> | undefined;\n const name = str(physicalId) || str(budget?.BudgetName);\n if (!name || !accountId) return undefined;\n const c = new BudgetsClient({ region, ...READ_RETRY });\n const r = await c.send(new DescribeBudgetCommand({ AccountId: accountId, BudgetName: name }));\n const b = r.Budget;\n if (!b) return undefined;\n // BudgetLimit is in the projection (R67): once R65 made budgets readable, a\n // declared BudgetLimit compared against a projection WITHOUT it reported\n // `desired={...} actual=undefined` false drift. The live Amount is a string\n // (\"5.0\") vs the declared number (5) — isStringlyEqualScalar's numeric arm folds that.\n //\n // CostFilters is the budget's SCOPE — which services/accounts/tags it watches.\n // Omitting it made an out-of-band scope change (e.g. narrowing a budget from all\n // services to one) undetectable: a declared CostFilters became a `readGap` (not\n // compared) and an undeclared one was wholly invisible. FP-safe to add: DescribeBudget\n // returns `{}` (or omits it) for an unfiltered budget, which `isTrivialEmpty`\n // suppresses, so a budget that declares no filters stays CLEAN; a declared filter set\n // is compared, and one added out of band surfaces. The projection still stays thin\n // where it must: COMPUTED fields (CalculatedSpend) and AWS-defaulted blobs (TimePeriod's\n // 2087 end date, the full CostTypes default set) are deliberately NOT offered — they\n // would be live-only noise.\n // PlannedBudgetLimits — a time-phased budget's per-period limits. Omitting it made an\n // out-of-band change to a future month's limit invisible (a declared one became a\n // readGap; an undeclared one wholly invisible). FP-safe: DescribeBudget returns it ONLY\n // for a budget created WITH planned limits (SDK-documented absent-when-unused), so a\n // plain fixed budget stays CLEAN; the inner Spend.Amount string (\"40.0\") vs the declared\n // number is folded by isStringlyEqualScalar, exactly like BudgetLimit.\n //\n // AutoAdjustData — switching a budget to auto-adjusting (or changing its look-back) was\n // undetectable. Projected THIN: only the user-settable AutoAdjustType + HistoricalOptions\n // .BudgetAdjustmentPeriod. The COMPUTED fields (LastAutoAdjustTime, the auto-calculated\n // HistoricalOptions.LookBackAvailablePeriods) are deliberately NOT offered — they would\n // be live-only noise. Absent for a fixed budget, so no first-run noise there.\n const aad = b.AutoAdjustData;\n return {\n Budget: {\n BudgetName: b.BudgetName,\n BudgetType: b.BudgetType,\n TimeUnit: b.TimeUnit,\n ...(b.BudgetLimit !== undefined && { BudgetLimit: b.BudgetLimit }),\n ...(b.PlannedBudgetLimits !== undefined && { PlannedBudgetLimits: b.PlannedBudgetLimits }),\n ...(b.CostFilters !== undefined && { CostFilters: b.CostFilters }),\n ...(aad && {\n AutoAdjustData: {\n ...(aad.AutoAdjustType !== undefined && { AutoAdjustType: aad.AutoAdjustType }),\n ...(aad.HistoricalOptions?.BudgetAdjustmentPeriod !== undefined && {\n HistoricalOptions: {\n BudgetAdjustmentPeriod: aad.HistoricalOptions.BudgetAdjustmentPeriod,\n },\n }),\n },\n }),\n },\n };\n};\n\n// AWS::EC2::EIP — Cloud Control API GetResource throws ValidationException for\n// this type, so read it via EC2 DescribeAddresses. The CFn physical id is the\n// allocation id (eipalloc-...) for VPC EIPs, or the public IP for classic EIPs.\nconst readEc2Eip: OverrideReader = async ({ physicalId, region }) => {\n const id = str(physicalId);\n if (!id) return undefined;\n const c = new EC2Client({ region, ...READ_RETRY });\n const input = id.startsWith('eipalloc-') ? { AllocationIds: [id] } : { PublicIps: [id] };\n // Not-found surfaces as InvalidAddress.NotFound / InvalidAllocationID.NotFound;\n // let it propagate so the router maps it to `deleted` (the EIP was released out\n // of band) instead of being silently swallowed as an empty model.\n const r = await c.send(new DescribeAddressesCommand(input));\n const addr = r.Addresses?.[0];\n if (!addr) return undefined;\n const tags = Array.isArray(addr.Tags)\n ? addr.Tags.filter((t) => str(t.Key) !== undefined).map((t) => ({\n Key: t.Key as string,\n Value: t.Value ?? '',\n }))\n : undefined;\n const model: Record<string, unknown> = {};\n if (str(addr.Domain)) model.Domain = addr.Domain;\n if (str(addr.NetworkBorderGroup)) model.NetworkBorderGroup = addr.NetworkBorderGroup;\n if (str(addr.PublicIp)) model.PublicIp = addr.PublicIp;\n if (str(addr.InstanceId)) model.InstanceId = addr.InstanceId;\n // NOTE: NetworkInterfaceId is NOT projected — it is not a declarable CFn property of\n // AWS::EC2::EIP (verified against the registry schema: the property set has no\n // NetworkInterfaceId), so it is neither readOnly-stripped nor a known default. AWS\n // populates it for any EIP associated with an ENI, so projecting it false-flagged an\n // `undeclared` drift on EVERY associated EIP on the first check.\n if (str(addr.PublicIpv4Pool)) model.PublicIpv4Pool = addr.PublicIpv4Pool; // declarable; absent for AWS-pool EIPs (FP-safe)\n if (tags && tags.length > 0) model.Tags = tags;\n return model;\n};\n\n// AWS::EC2::NetworkAclEntry — Cloud Control has no read handler for this type\n// (GetResource throws UnsupportedActionException), so every NACL entry was silently\n// `skipped`: a NACL rule changed out of band (a CidrBlock widened, an action flipped\n// allow->deny) was invisible. Read the parent NACL via EC2 DescribeNetworkAcls and pick\n// the entry by its identity (RuleNumber + Egress — a NACL holds at most one entry per\n// (RuleNumber, Egress) pair). The EC2 entry shape mirrors the CFn property shape, except\n// Protocol comes back as a STRING (\"6\") while CFn declares it as an INTEGER (6) — coerce\n// it to a number so a tcp/udp/icmp rule does not false-drift on a typed-vs-string Protocol.\n// AWS::CloudWatch::AnomalyDetector — NON_PROVISIONABLE in the registry (no Cloud\n// Control read handler), so every declared anomaly detector was a silent `skipped`\n// read-gap (issue #461) despite being a standard CloudWatch pattern. The CFn physical\n// id is an opaque generated id no CloudWatch API accepts, so identity comes from the\n// DECLARED model. Two declaration styles exist (a nested SingleMetricAnomalyDetector /\n// MetricMathAnomalyDetector, or the legacy top-level Namespace/MetricName/Stat/\n// Dimensions); the live model is emitted in the SAME style the template used so the\n// compare is shape-stable. Field mapping: the CW API spells the timezone\n// `MetricTimezone` while CFn spells it `MetricTimeZone`; ExcludedTimeRanges come back\n// as Date objects and are projected in the CFn Range pattern — the registry schema\n// enforces `YYYY-MM-DDTHH:MM:SS` (zone-less UTC; a trailing `Z` is REJECTED at deploy,\n// live-proven), so a full-ISO projection would false-flag every declared range\n// (`desired=\"…T00:00:00\" actual=\"…T00:00:00.000Z\"`). Only projected when present\n// (FP-safe: an unset Configuration stays absent on both sides).\nconst dimSetEqual = (a: unknown, b: unknown): boolean => {\n const norm = (v: unknown): string =>\n JSON.stringify(\n (Array.isArray(v) ? (v as { Name?: unknown; Value?: unknown }[]) : [])\n .map((d) => [str(d.Name) ?? '', str(d.Value) ?? ''])\n .sort()\n );\n return norm(a) === norm(b);\n};\n// CFn Range pattern: `YYYY-MM-DDTHH:MM:SS` in UTC (the schema rejects a zone suffix).\nconst cfnRangeTime = (v: unknown): unknown =>\n v instanceof Date ? v.toISOString().slice(0, 19) : v;\nconst readCloudWatchAnomalyDetector: OverrideReader = async ({ declared, region }) => {\n const singleDecl = declared.SingleMetricAnomalyDetector as Record<string, unknown> | undefined;\n const mathDecl = declared.MetricMathAnomalyDetector as Record<string, unknown> | undefined;\n const ns = str(singleDecl?.Namespace) ?? str(declared.Namespace);\n const metric = str(singleDecl?.MetricName) ?? str(declared.MetricName);\n const stat = str(singleDecl?.Stat) ?? str(declared.Stat);\n const dims = singleDecl?.Dimensions ?? declared.Dimensions;\n if (!mathDecl && (!ns || !metric || !stat)) return undefined; // unresolved identity -> skipped\n\n const c = new CloudWatchClient({ region, ...READ_RETRY });\n // Namespace/MetricName filters match only single-metric detectors. A math\n // detector MUST request AnomalyDetectorTypes=METRIC_MATH explicitly: the API\n // DEFAULTS to SINGLE_METRIC when the field is omitted, so an \"unfiltered\"\n // listing never returns math detectors — every metric-math detector then\n // false-reported \"deleted out of band\" on a fresh stack (live-caught; the\n // unit-test mock returned detectors regardless of the filter, masking it).\n const filters = mathDecl\n ? { AnomalyDetectorTypes: ['METRIC_MATH' as const] }\n : { Namespace: ns, MetricName: metric };\n const detectors: AnomalyDetector[] = [];\n let nextToken: string | undefined;\n do {\n const r = await c.send(\n new DescribeAnomalyDetectorsCommand({ ...filters, NextToken: nextToken })\n );\n detectors.push(...(r.AnomalyDetectors ?? []));\n nextToken = r.NextToken;\n } while (nextToken);\n\n const found = detectors.find((d) => {\n if (mathDecl) {\n const q = d.MetricMathAnomalyDetector?.MetricDataQueries;\n const declQ = mathDecl.MetricDataQueries;\n const ids = (v: unknown): string =>\n JSON.stringify(\n (Array.isArray(v) ? (v as { Id?: unknown }[]) : []).map((x) => str(x.Id) ?? '').sort()\n );\n return q !== undefined && ids(q) === ids(declQ);\n }\n const s = d.SingleMetricAnomalyDetector;\n const dNs = s?.Namespace ?? d.Namespace;\n const dMetric = s?.MetricName ?? d.MetricName;\n const dStat = s?.Stat ?? d.Stat;\n const dDims = s?.Dimensions ?? d.Dimensions;\n return dNs === ns && dMetric === metric && dStat === stat && dimSetEqual(dDims, dims ?? []);\n });\n if (!found) throw new ResourceGoneError(`AnomalyDetector ${ns ?? 'math'}/${metric ?? ''} absent`);\n\n const model: Record<string, unknown> = {};\n if (mathDecl) {\n model.MetricMathAnomalyDetector = found.MetricMathAnomalyDetector;\n } else if (singleDecl) {\n const s = found.SingleMetricAnomalyDetector;\n model.SingleMetricAnomalyDetector = {\n // AccountId is projected ONLY when the template declares it (cross-account\n // monitoring): the API echoes the OWN account id on every detector, which would\n // otherwise surface as undeclared first-run noise.\n ...(str(singleDecl.AccountId) !== undefined &&\n str(s?.AccountId) !== undefined && { AccountId: s?.AccountId }),\n Namespace: s?.Namespace ?? found.Namespace,\n MetricName: s?.MetricName ?? found.MetricName,\n Stat: s?.Stat ?? found.Stat,\n ...((s?.Dimensions ?? found.Dimensions ?? []).length > 0 && {\n Dimensions: s?.Dimensions ?? found.Dimensions,\n }),\n };\n } else {\n model.Namespace = found.SingleMetricAnomalyDetector?.Namespace ?? found.Namespace;\n model.MetricName = found.SingleMetricAnomalyDetector?.MetricName ?? found.MetricName;\n model.Stat = found.SingleMetricAnomalyDetector?.Stat ?? found.Stat;\n const legacyDims = found.SingleMetricAnomalyDetector?.Dimensions ?? found.Dimensions;\n if ((legacyDims ?? []).length > 0) model.Dimensions = legacyDims;\n }\n const cfg = found.Configuration;\n if (cfg !== undefined) {\n const out: Record<string, unknown> = {};\n if (str(cfg.MetricTimezone)) out.MetricTimeZone = cfg.MetricTimezone;\n if ((cfg.ExcludedTimeRanges ?? []).length > 0)\n out.ExcludedTimeRanges = (cfg.ExcludedTimeRanges ?? []).map((rng) => ({\n StartTime: cfnRangeTime(rng.StartTime),\n EndTime: cfnRangeTime(rng.EndTime),\n }));\n if (Object.keys(out).length > 0) model.Configuration = out;\n }\n if (found.MetricCharacteristics !== undefined)\n model.MetricCharacteristics = found.MetricCharacteristics;\n return model;\n};\n\n// AWS::DLM::LifecyclePolicy — NON_PROVISIONABLE in the registry (no Cloud Control read\n// handler; issue #468), so every Data Lifecycle Manager policy — a common EBS snapshot /\n// AMI backup-schedule staple — came back a silent `skipped` read-gap. The CFn physical id\n// IS the DLM policy id (`policy-0abc…`), which dlm:GetLifecyclePolicy accepts directly. The\n// DLM API models the policy in the SAME PascalCase shape the CFn registry uses\n// (PolicyDetails / Schedules / CreateRule / RetainRule / CrossRegionCopyRules / …), so the\n// live PolicyDetails is emitted verbatim for the classifier (like the Glue family — a\n// whole-object read). Two declaration styles exist: a full custom policy (declared\n// PolicyDetails) and the default-policy shorthand (top-level CreateInterval / RetainInterval\n// / CopyTags / …, which the API folds INTO PolicyDetails); the live model is emitted in the\n// SAME style the template used so the compare is shape-stable. Tags are a `{k: v}` map on\n// the API but a `[{Key,Value}]` list in CFn, so they are not projected here (the shape\n// mismatch would false-drift; `aws:*` tag noise is handled elsewhere). A deleted policy\n// throws ResourceNotFoundException → the router maps it to `deleted`.\nexport const DLM_DEFAULT_POLICY_SHORTHAND = [\n 'CreateInterval',\n 'RetainInterval',\n 'CopyTags',\n 'ExtendDeletion',\n 'CrossRegionCopyTargets',\n 'Exclusions',\n] as const;\nconst readDlmLifecyclePolicy: OverrideReader = async ({ physicalId, declared, region }) => {\n const id = str(physicalId);\n if (!id) return undefined;\n const c = new DLMClient({ region, ...READ_RETRY });\n // Not-found (ResourceNotFoundException) propagates so the router maps a deleted policy\n // to `deleted` rather than an empty model.\n const p = (await c.send(new GetLifecyclePolicyCommand({ PolicyId: id }))).Policy;\n if (!p) throw new ResourceGoneError(`DLM LifecyclePolicy ${id} absent`);\n const model: Record<string, unknown> = {};\n if (str(p.Description) !== undefined) model.Description = p.Description;\n if (str(p.State) !== undefined) model.State = p.State;\n if (str(p.ExecutionRoleArn) !== undefined) model.ExecutionRoleArn = p.ExecutionRoleArn;\n const details = (p.PolicyDetails ?? {}) as Record<string, unknown>;\n // Emit in the template's style. The default-policy shorthand declares the schedule\n // knobs at the TOP level and no PolicyDetails; the API folds them into PolicyDetails, so\n // project just those keys back up. Every other case is a custom policy → PolicyDetails.\n const usesShorthand =\n declared.PolicyDetails === undefined &&\n DLM_DEFAULT_POLICY_SHORTHAND.some((k) => declared[k] !== undefined);\n if (usesShorthand) {\n for (const k of DLM_DEFAULT_POLICY_SHORTHAND)\n if (details[k] !== undefined) model[k] = details[k];\n } else if (Object.keys(details).length > 0) {\n model.PolicyDetails = details;\n }\n return model;\n};\n\n// AWS::DMS::Endpoint — NON_PROVISIONABLE in the registry (no Cloud Control read handler;\n// issue #497), so every DMS endpoint — 2 of which every migration/CDC pipeline declares —\n// was a silent `skipped` read-gap. Connection attributes people tweak in the console\n// (ExtraConnectionAttributes, ServerName, Port, engine settings) were invisible. The CFn\n// physical id (Ref → `Id`) IS the EndpointArn, which DMS DescribeEndpoints filters on via\n// `endpoint-arn`; a bare identifier (older stacks / imports) filters on `endpoint-id`. The\n// DMS API models the endpoint in the SAME PascalCase shape the CFn registry uses, so the\n// CFn-declarable scalars are projected 1:1. The per-engine *Settings blobs\n// (S3Settings/KinesisSettings/…) are NOT projected: the SDK returns them under DIFFERENT key\n// casing than the CFn schema (e.g. CFn MongoDbSettings vs API MongoDbSettings sub-field\n// drift) and AWS default-fills them, so a passthrough would false-flag; scalar coverage is\n// the deliverable. Read-ONLY: a ModifyEndpoint writer is deferred to a follow-up (revert of\n// connection settings needs per-engine care). A deleted endpoint surfaces as\n// ResourceNotFoundException → the router maps it to `deleted`.\nconst readDmsEndpoint: OverrideReader = async ({ physicalId, region }) => {\n const id = str(physicalId);\n if (!id) return undefined;\n const c = new DatabaseMigrationServiceClient({ region, ...READ_RETRY });\n const filterName = id.startsWith('arn:') ? 'endpoint-arn' : 'endpoint-id';\n // ResourceNotFoundException propagates so a deleted endpoint maps to `deleted`.\n const r = await c.send(\n new DescribeEndpointsCommand({ Filters: [{ Name: filterName, Values: [id] }] })\n );\n const e = r.Endpoints?.[0];\n if (!e) throw new ResourceGoneError(`DMS Endpoint ${id} absent`);\n const model: Record<string, unknown> = {};\n if (str(e.EndpointIdentifier)) model.EndpointIdentifier = e.EndpointIdentifier;\n if (str(e.EndpointType)) model.EndpointType = e.EndpointType;\n if (str(e.EngineName)) model.EngineName = e.EngineName;\n if (str(e.Username)) model.Username = e.Username;\n if (str(e.ServerName)) model.ServerName = e.ServerName;\n if (typeof e.Port === 'number') model.Port = e.Port;\n if (str(e.DatabaseName)) model.DatabaseName = e.DatabaseName;\n if (str(e.ExtraConnectionAttributes))\n model.ExtraConnectionAttributes = e.ExtraConnectionAttributes;\n if (str(e.KmsKeyId)) model.KmsKeyId = e.KmsKeyId;\n if (str(e.CertificateArn)) model.CertificateArn = e.CertificateArn;\n if (str(e.SslMode)) model.SslMode = e.SslMode;\n return model;\n};\n\n// AWS::DMS::ReplicationSubnetGroup — NON_PROVISIONABLE (no Cloud Control read handler; issue\n// #497), paired with the endpoints above in every migration pipeline. The CFn physical id\n// (Ref → `Id`) IS the ReplicationSubnetGroupIdentifier, which DMS\n// DescribeReplicationSubnetGroups filters on via `replication-subnet-group-id`. The API\n// returns Subnets as a list of `{SubnetIdentifier}` objects, while CFn declares a flat\n// `SubnetIds` string list — project the SubnetIdentifier values (SORTED, so a live-vs-declared\n// order difference is not false drift; DMS does not preserve the declared order). Read-ONLY\n// (ModifyReplicationSubnetGroup deferred). AWS lowercases the identifier, and CFn's Ref\n// resolves to that lowercased form, so the identity round-trips.\nconst readDmsReplicationSubnetGroup: OverrideReader = async ({ physicalId, region }) => {\n const id = str(physicalId);\n if (!id) return undefined;\n const c = new DatabaseMigrationServiceClient({ region, ...READ_RETRY });\n const r = await c.send(\n new DescribeReplicationSubnetGroupsCommand({\n Filters: [{ Name: 'replication-subnet-group-id', Values: [id] }],\n })\n );\n const g = r.ReplicationSubnetGroups?.[0];\n if (!g) throw new ResourceGoneError(`DMS ReplicationSubnetGroup ${id} absent`);\n const model: Record<string, unknown> = {};\n if (str(g.ReplicationSubnetGroupIdentifier))\n model.ReplicationSubnetGroupIdentifier = g.ReplicationSubnetGroupIdentifier;\n if (str(g.ReplicationSubnetGroupDescription))\n model.ReplicationSubnetGroupDescription = g.ReplicationSubnetGroupDescription;\n const subnetIds = (g.Subnets ?? [])\n .map((s) => str(s.SubnetIdentifier))\n .filter((v): v is string => v !== undefined)\n .sort();\n if (subnetIds.length > 0) model.SubnetIds = subnetIds;\n return model;\n};\n\n// AWS::MediaConvert::Queue — NON_PROVISIONABLE (no Cloud Control read handler; issue #497), a\n// video-pipeline staple whose `Status` (ACTIVE/PAUSED) is a classic console-toggled prop that\n// was invisible. The CFn physical id (Ref → `Id`) IS the queue Name, which mc:GetQueue accepts\n// directly. Project the CFn-declarable scalars (Name/Description/PricingPlan/Status). The\n// computed/reserved fields (Arn/CreatedAt/LastUpdated/ConcurrentJobs/MaximumConcurrentFeeds/\n// ReservationPlan/*JobsCount/ServiceOverrides/Type) are dropped — not user-declarable scalars,\n// pure noise. Read-ONLY (UpdateQueue deferred). A deleted queue surfaces as\n// NotFoundException → the router maps it to `deleted`.\nconst readMediaConvertQueue: OverrideReader = async ({ physicalId, region }) => {\n const name = str(physicalId);\n if (!name) return undefined;\n const c = new MediaConvertClient({ region, ...READ_RETRY });\n const q = (await c.send(new GetQueueCommand({ Name: name }))).Queue;\n if (!q) throw new ResourceGoneError(`MediaConvert Queue ${name} absent`);\n const model: Record<string, unknown> = {};\n if (str(q.Name)) model.Name = q.Name;\n if (str(q.Description)) model.Description = q.Description;\n if (str(q.PricingPlan)) model.PricingPlan = q.PricingPlan;\n if (str(q.Status)) model.Status = q.Status;\n return model;\n};\n\n// AWS::MediaConvert::JobTemplate — NON_PROVISIONABLE (no Cloud Control read handler; issue\n// #497). The CFn physical id (Ref → `Id`) IS the template Name, which mc:GetJobTemplate accepts\n// directly. Project the CFn-declarable props; `SettingsJson` is a large free-form JSON blob\n// that CFn declares as an opaque object and the API returns as the structured `Settings` object\n// — read it back FAITHFULLY (verbatim passthrough) so an out-of-band settings change surfaces.\n// AccelerationSettings/HopDestinations/StatusUpdateInterval/Category/Queue/Priority mirror the\n// CFn shape 1:1. Computed/managed fields (Arn/CreatedAt/LastUpdated/Type) are dropped. Read-ONLY\n// (UpdateJobTemplate deferred). A deleted template surfaces as NotFoundException → `deleted`.\nconst readMediaConvertJobTemplate: OverrideReader = async ({ physicalId, region }) => {\n const name = str(physicalId);\n if (!name) return undefined;\n const c = new MediaConvertClient({ region, ...READ_RETRY });\n const t = (await c.send(new GetJobTemplateCommand({ Name: name }))).JobTemplate;\n if (!t) throw new ResourceGoneError(`MediaConvert JobTemplate ${name} absent`);\n const model: Record<string, unknown> = {};\n if (str(t.Name)) model.Name = t.Name;\n if (str(t.Description)) model.Description = t.Description;\n if (str(t.Category)) model.Category = t.Category;\n if (str(t.Queue)) model.Queue = t.Queue;\n if (typeof t.Priority === 'number') model.Priority = t.Priority;\n if (str(t.StatusUpdateInterval)) model.StatusUpdateInterval = t.StatusUpdateInterval;\n if (t.AccelerationSettings !== undefined) model.AccelerationSettings = t.AccelerationSettings;\n if (Array.isArray(t.HopDestinations) && t.HopDestinations.length > 0)\n model.HopDestinations = t.HopDestinations;\n // SettingsJson: CFn declares it as an opaque JSON object; the API returns the structured\n // `Settings` object. Faithful passthrough so a console-side transcode-settings change is\n // detectable.\n if (t.Settings !== undefined) model.SettingsJson = t.Settings;\n return model;\n};\n\n// AWS::CodeBuild::ReportGroup — NON_PROVISIONABLE (no Cloud Control read handler; issue #530).\n// Any CI stack that publishes test/coverage reports carries one, so an out-of-band ExportConfig\n// (S3 destination / packaging / encryption) or Tags change was silently invisible. The CFn\n// physical id (Ref) IS the report-group ARN, which codebuild:BatchGetReportGroups accepts\n// directly (single call). Project the CFn-declarable surface (Name/Type/ExportConfig/Tags),\n// camelCase→PascalCase; the SDK's read-only/computed fields (Arn/Created/LastModified/Status)\n// are dropped. Read-ONLY (UpdateReportGroup writer deferred). A deleted group returns an empty\n// list → ResourceGoneError → the router maps it to `deleted`.\nconst readCodeBuildReportGroup: OverrideReader = async ({ physicalId, region }) => {\n const arn = str(physicalId);\n if (!arn) return undefined;\n const c = new CodeBuildClient({ region, ...READ_RETRY });\n const rg = (await c.send(new BatchGetReportGroupsCommand({ reportGroupArns: [arn] })))\n .reportGroups?.[0];\n if (!rg) throw new ResourceGoneError(`CodeBuild ReportGroup ${arn} absent`);\n const model: Record<string, unknown> = {};\n if (str(rg.name)) model.Name = rg.name;\n if (str(rg.type)) model.Type = rg.type;\n const ec = rg.exportConfig;\n if (ec) {\n const exp: Record<string, unknown> = {};\n if (str(ec.exportConfigType)) exp.ExportConfigType = ec.exportConfigType;\n const s3 = ec.s3Destination;\n if (s3) {\n const dest: Record<string, unknown> = {};\n if (str(s3.bucket)) dest.Bucket = s3.bucket;\n if (str(s3.path)) dest.Path = s3.path;\n if (str(s3.packaging)) dest.Packaging = s3.packaging;\n if (str(s3.encryptionKey)) dest.EncryptionKey = s3.encryptionKey;\n if (typeof s3.encryptionDisabled === 'boolean')\n dest.EncryptionDisabled = s3.encryptionDisabled;\n if (Object.keys(dest).length > 0) exp.S3Destination = dest;\n }\n if (Object.keys(exp).length > 0) model.ExportConfig = exp;\n }\n if (Array.isArray(rg.tags) && rg.tags.length > 0)\n model.Tags = rg.tags.map((t) => ({ Key: t.key, Value: t.value }));\n return model;\n};\n\nconst readEc2NetworkAclEntry: OverrideReader = async ({ declared, region }) => {\n const naclId = str(declared.NetworkAclId);\n const ruleNumber = declared.RuleNumber;\n const egress = declared.Egress;\n // RuleNumber + Egress are required identity; an unresolved NetworkAclId (Symbol) or a\n // missing identity field -> skipped (fail-open, never a false read).\n if (!naclId || typeof ruleNumber !== 'number' || typeof egress !== 'boolean') return undefined;\n\n const c = new EC2Client({ region, ...READ_RETRY });\n // InvalidNetworkAclID.NotFound surfaces if the NACL itself was deleted out of band —\n // let it propagate so the router maps it to `deleted`.\n const r = await c.send(new DescribeNetworkAclsCommand({ NetworkAclIds: [naclId] }));\n const nacl = r.NetworkAcls?.[0];\n if (!nacl) return undefined;\n const entry = nacl.Entries?.find((e) => e.RuleNumber === ruleNumber && e.Egress === egress);\n if (!entry)\n throw new ResourceGoneError(\n `NetworkAclEntry rule=${ruleNumber} egress=${egress} absent from NACL ${naclId}`\n );\n\n const model: Record<string, unknown> = {\n NetworkAclId: naclId,\n RuleNumber: entry.RuleNumber,\n Egress: entry.Egress,\n RuleAction: entry.RuleAction,\n };\n // Protocol: EC2 returns a numeric STRING; CFn declares an integer.\n if (entry.Protocol !== undefined && entry.Protocol !== null)\n model.Protocol = Number(entry.Protocol);\n if (str(entry.CidrBlock)) model.CidrBlock = entry.CidrBlock;\n if (str(entry.Ipv6CidrBlock)) model.Ipv6CidrBlock = entry.Ipv6CidrBlock;\n // PortRange (TCP/UDP) and Icmp (ICMP/ICMPv6) are mutually exclusive and protocol-derived;\n // project each only when AWS returns it so a non-port / non-icmp rule stays absent (FP-safe).\n if (entry.PortRange) model.PortRange = { From: entry.PortRange.From, To: entry.PortRange.To };\n // EC2 names the ICMP field IcmpTypeCode; the CFn property is Icmp (same {Code, Type}).\n if (entry.IcmpTypeCode)\n model.Icmp = { Code: entry.IcmpTypeCode.Code, Type: entry.IcmpTypeCode.Type };\n return model;\n};\n\n// AWS::EC2::LaunchTemplate — Cloud Control reads the resource but its entire\n// `LaunchTemplateData` body is writeOnly in the registry schema, so CC returns only\n// ids/version numbers and the data was a permanent `readGap` (declared but\n// unverifiable). Read the DEFAULT version's data via EC2\n// DescribeLaunchTemplateVersions — the CFn physical id IS the LaunchTemplateId — and\n// project `LaunchTemplateData` so cdkrd can finally detect drift on it (e.g. a new\n// default version someone published out of band with a changed InstanceType / block\n// device / metadata option). The EC2 `ResponseLaunchTemplateData` shape mirrors the\n// CFn `LaunchTemplateData` shape (same PascalCase keys, same nesting) and AWS returns\n// it FAITHFULLY — it does NOT inject defaults (a probe confirmed a minimal template\n// reads back exactly as declared), so this is essentially a pass-through with low FP\n// risk. `schema-strip.ts` exempts `LaunchTemplateData` from the writeOnly strip for\n// this type (OVERRIDE_READABLE_WRITEONLY) so the projected value is actually compared.\n// LaunchTemplateName (createOnly, readable) is projected too; VersionDescription and\n// the top-level resource TagSpecifications stay writeOnly readGaps (not projected).\nconst readEc2LaunchTemplate: OverrideReader = async ({ physicalId, region }) => {\n const id = str(physicalId);\n if (!id) return undefined;\n const c = new EC2Client({ region, ...READ_RETRY });\n // Not-found (InvalidLaunchTemplateId.NotFound) propagates so the router maps a\n // deleted launch template to `deleted` rather than an empty model.\n const r = await c.send(\n new DescribeLaunchTemplateVersionsCommand({ LaunchTemplateId: id, Versions: ['$Default'] })\n );\n const v = r.LaunchTemplateVersions?.[0];\n if (!v) return undefined;\n const model: Record<string, unknown> = {};\n if (str(v.LaunchTemplateName)) model.LaunchTemplateName = v.LaunchTemplateName;\n if (v.LaunchTemplateData !== undefined)\n model.LaunchTemplateData = v.LaunchTemplateData as Record<string, unknown>;\n return model;\n};\n\n// AWS::EC2::ClientVpnEndpoint — NON_PROVISIONABLE (no Cloud Control read handler; issue #534).\n// The CFn physical id (Ref) IS the ClientVpnEndpointId, which\n// ec2:DescribeClientVpnEndpoints accepts directly. Project the CFn-declarable props; drop the\n// computed/managed fields (Status/CreationTime/DeletionTime/DnsName/VpnProtocol/\n// AssociatedTargetNetworks/ClientConnectOptions/ClientLoginBannerOptions/\n// ClientRouteEnforcementOptions/EndpointIpAddressType/Tags). Read-ONLY. A deleted endpoint\n// yields an empty result -> ResourceGoneError so the router maps it to `deleted`.\nconst readEc2ClientVpnEndpoint: OverrideReader = async ({ physicalId, region }) => {\n const id = str(physicalId);\n if (!id) return undefined;\n const c = new EC2Client({ region, ...READ_RETRY });\n const r = await c.send(new DescribeClientVpnEndpointsCommand({ ClientVpnEndpointIds: [id] }));\n const e = r.ClientVpnEndpoints?.[0];\n if (!e) throw new ResourceGoneError(`ClientVpnEndpoint ${id} absent`);\n const model: Record<string, unknown> = {};\n if (str(e.Description)) model.Description = e.Description;\n if (str(e.ClientCidrBlock)) model.ClientCidrBlock = e.ClientCidrBlock;\n const dnsServers = (e.DnsServers ?? []).filter((v): v is string => str(v) !== undefined);\n if (dnsServers.length > 0) model.DnsServers = dnsServers;\n if (typeof e.SplitTunnel === 'boolean') model.SplitTunnel = e.SplitTunnel;\n if (str(e.TransportProtocol)) model.TransportProtocol = e.TransportProtocol;\n if (typeof e.VpnPort === 'number') model.VpnPort = e.VpnPort;\n if (str(e.ServerCertificateArn)) model.ServerCertificateArn = e.ServerCertificateArn;\n const securityGroupIds = (e.SecurityGroupIds ?? []).filter(\n (v): v is string => str(v) !== undefined\n );\n if (securityGroupIds.length > 0) model.SecurityGroupIds = securityGroupIds;\n if (str(e.VpcId)) model.VpcId = e.VpcId;\n if (typeof e.SessionTimeoutHours === 'number') model.SessionTimeoutHours = e.SessionTimeoutHours;\n if (typeof e.DisconnectOnSessionTimeout === 'boolean')\n model.DisconnectOnSessionTimeout = e.DisconnectOnSessionTimeout;\n // SelfServicePortal is NOT projected: the API returns a `SelfServicePortalUrl` for EVERY\n // endpoint regardless of whether the CFn `SelfServicePortal` is enabled or disabled\n // (live-verified: an endpoint that declares no SelfServicePortal — i.e. the \"disabled\"\n // default — still returns a URL). So URL presence cannot distinguish enabled from disabled,\n // and deriving \"enabled\" from it would false-drift against a declared \"disabled\". There is\n // no reliable read-back signal, so the field is left unread (a declared value becomes a\n // readGap — honest — rather than a false positive).\n // ConnectionLogOptions: API ConnectionLogResponseOptions carries the SAME CFn field names\n // (Enabled/CloudwatchLogGroup/CloudwatchLogStream). Project the sub-fields that are present.\n if (e.ConnectionLogOptions) {\n const clo: Record<string, unknown> = {};\n if (typeof e.ConnectionLogOptions.Enabled === 'boolean')\n clo.Enabled = e.ConnectionLogOptions.Enabled;\n if (str(e.ConnectionLogOptions.CloudwatchLogGroup))\n clo.CloudwatchLogGroup = e.ConnectionLogOptions.CloudwatchLogGroup;\n if (str(e.ConnectionLogOptions.CloudwatchLogStream))\n clo.CloudwatchLogStream = e.ConnectionLogOptions.CloudwatchLogStream;\n if (Object.keys(clo).length > 0) model.ConnectionLogOptions = clo;\n }\n // AuthenticationOptions: API ClientVpnAuthentication[] -> CFn ClientAuthenticationRequest[].\n // The CFn sub-field names DIFFER from the API: MutualAuthentication.ClientRootCertificateChain\n // (API) -> ClientRootCertificateChainArn (CFn); FederatedAuthentication.SamlProviderArn (API)\n // -> SAMLProviderArn (CFn); SelfServiceSamlProviderArn (API) -> SelfServiceSAMLProviderArn\n // (CFn). These CFn names are validated live. Project each sub-object only when present.\n if (Array.isArray(e.AuthenticationOptions) && e.AuthenticationOptions.length > 0) {\n const auth = e.AuthenticationOptions.map((a) => {\n const item: Record<string, unknown> = {};\n if (str(a.Type)) item.Type = a.Type;\n if (a.ActiveDirectory && str(a.ActiveDirectory.DirectoryId))\n item.ActiveDirectory = { DirectoryId: a.ActiveDirectory.DirectoryId };\n if (a.MutualAuthentication && str(a.MutualAuthentication.ClientRootCertificateChain))\n item.MutualAuthentication = {\n ClientRootCertificateChainArn: a.MutualAuthentication.ClientRootCertificateChain,\n };\n if (a.FederatedAuthentication) {\n const fed: Record<string, unknown> = {};\n if (str(a.FederatedAuthentication.SamlProviderArn))\n fed.SAMLProviderArn = a.FederatedAuthentication.SamlProviderArn;\n if (str(a.FederatedAuthentication.SelfServiceSamlProviderArn))\n fed.SelfServiceSAMLProviderArn = a.FederatedAuthentication.SelfServiceSamlProviderArn;\n if (Object.keys(fed).length > 0) item.FederatedAuthentication = fed;\n }\n return item;\n });\n model.AuthenticationOptions = auth;\n }\n return model;\n};\n\n// AWS::EC2::ClientVpnAuthorizationRule — NON_PROVISIONABLE (issue #534). The CFn Ref is an\n// opaque generated id, so the reader resolves the PARENT ClientVpnEndpointId from the declared\n// props and MATCHES the specific rule by its declared identity (TargetNetworkCidr === live\n// DestinationCidr, and — when declared — AccessGroupId === live GroupId). Read-ONLY. No matching\n// rule -> ResourceGoneError (deleted out of band); unresolved parent -> undefined (skipped).\nconst readEc2ClientVpnAuthorizationRule: OverrideReader = async ({ declared, region }) => {\n const endpointId = str(declared.ClientVpnEndpointId);\n if (!endpointId) return undefined;\n const cidr = str(declared.TargetNetworkCidr);\n const groupId = str(declared.AccessGroupId);\n const c = new EC2Client({ region, ...READ_RETRY });\n const r = await c.send(\n new DescribeClientVpnAuthorizationRulesCommand({ ClientVpnEndpointId: endpointId })\n );\n const rule = (r.AuthorizationRules ?? []).find(\n (a) =>\n (cidr === undefined || a.DestinationCidr === cidr) &&\n (groupId === undefined || a.GroupId === groupId)\n );\n if (!rule)\n throw new ResourceGoneError(\n `ClientVpnAuthorizationRule cidr=${cidr} group=${groupId} absent from endpoint ${endpointId}`\n );\n const model: Record<string, unknown> = {};\n // Echo the parent endpoint id (the declared, resolved value) so a declared\n // ClientVpnEndpointId compares rather than read-gapping (the describe call is scoped\n // to it, so it is authoritative).\n model.ClientVpnEndpointId = endpointId;\n if (str(rule.DestinationCidr)) model.TargetNetworkCidr = rule.DestinationCidr;\n if (str(rule.GroupId)) model.AccessGroupId = rule.GroupId;\n if (str(rule.Description)) model.Description = rule.Description;\n if (typeof rule.AccessAll === 'boolean') model.AuthorizeAllGroups = rule.AccessAll;\n return model;\n};\n\n// AWS::EC2::ClientVpnTargetNetworkAssociation — NON_PROVISIONABLE (issue #534). The CFn physical\n// id (Ref) IS the AssociationId; ec2:DescribeClientVpnTargetNetworks requires the parent\n// ClientVpnEndpointId (resolved from declared) plus the AssociationId. Read-ONLY. Empty result ->\n// ResourceGoneError (deleted out of band); unresolved parent -> undefined (skipped).\nconst readEc2ClientVpnTargetNetworkAssociation: OverrideReader = async ({\n physicalId,\n declared,\n region,\n}) => {\n const id = str(physicalId);\n const endpointId = str(declared.ClientVpnEndpointId);\n if (!endpointId || !id) return undefined;\n const c = new EC2Client({ region, ...READ_RETRY });\n const r = await c.send(\n new DescribeClientVpnTargetNetworksCommand({\n ClientVpnEndpointId: endpointId,\n AssociationIds: [id],\n })\n );\n const n = r.ClientVpnTargetNetworks?.[0];\n if (!n) throw new ResourceGoneError(`ClientVpnTargetNetworkAssociation ${id} absent`);\n const model: Record<string, unknown> = {};\n if (str(n.ClientVpnEndpointId)) model.ClientVpnEndpointId = n.ClientVpnEndpointId;\n if (str(n.TargetNetworkId)) model.SubnetId = n.TargetNetworkId;\n return model;\n};\n\n// AWS::DAX::Cluster — NON_PROVISIONABLE (no Cloud Control read handler; issue #534). The CFn\n// physical id (Ref) IS the ClusterName, which dax:DescribeClusters accepts via ClusterNames.\n// Project the CFn-declarable props; drop the computed/managed fields (ClusterArn/TotalNodes/\n// ActiveNodes/Status/ClusterDiscoveryEndpoint/NodeIdsToRemove/Nodes/NetworkType). Note the CFn\n// casing IAMRoleARN (from API IamRoleArn) and the nested field extractions (SubnetGroupName from\n// SubnetGroup, SecurityGroupIds from SecurityGroups[].SecurityGroupIdentifier, ParameterGroupName\n// from ParameterGroup.ParameterGroupName, NotificationTopicARN from\n// NotificationConfiguration.TopicArn, SSESpecification from SSEDescription.Status). Read-ONLY.\n// Empty result -> ResourceGoneError so the router maps it to `deleted`.\nconst readDaxCluster: OverrideReader = async ({ physicalId, region }) => {\n const name = str(physicalId);\n if (!name) return undefined;\n const c = new DAXClient({ region, ...READ_RETRY });\n const cl = (await c.send(new DescribeClustersCommand({ ClusterNames: [name] }))).Clusters?.[0];\n if (!cl) throw new ResourceGoneError(`DAX Cluster ${name} absent`);\n const model: Record<string, unknown> = {};\n if (str(cl.ClusterName)) model.ClusterName = cl.ClusterName;\n if (str(cl.Description)) model.Description = cl.Description;\n if (str(cl.NodeType)) model.NodeType = cl.NodeType;\n if (str(cl.IamRoleArn)) model.IAMRoleARN = cl.IamRoleArn;\n if (str(cl.PreferredMaintenanceWindow))\n model.PreferredMaintenanceWindow = cl.PreferredMaintenanceWindow;\n if (str(cl.SubnetGroup)) model.SubnetGroupName = cl.SubnetGroup;\n if (str(cl.ClusterEndpointEncryptionType))\n model.ClusterEndpointEncryptionType = cl.ClusterEndpointEncryptionType;\n const securityGroupIds = (cl.SecurityGroups ?? [])\n .map((s) => str(s.SecurityGroupIdentifier))\n .filter((v): v is string => v !== undefined);\n if (securityGroupIds.length > 0) model.SecurityGroupIds = securityGroupIds;\n if (cl.ParameterGroup && str(cl.ParameterGroup.ParameterGroupName))\n model.ParameterGroupName = cl.ParameterGroup.ParameterGroupName;\n if (cl.NotificationConfiguration && str(cl.NotificationConfiguration.TopicArn))\n model.NotificationTopicARN = cl.NotificationConfiguration.TopicArn;\n if (cl.SSEDescription?.Status === 'ENABLED') model.SSESpecification = { SSEEnabled: true };\n return model;\n};\n\n// AWS::DAX::ParameterGroup — NON_PROVISIONABLE (issue #534). The CFn physical id (Ref) IS the\n// ParameterGroupName. DescribeParameterGroups yields the name + description;\n// DescribeParameters yields the parameter values, projected as the CFn free-form map\n// ParameterNameValues { name -> value }. Only user-settable parameters (IsModifiable !== 'FALSE')\n// are projected — DAX returns many system-fixed defaults that the user never declared. Read-ONLY.\n// Empty result -> ResourceGoneError so the router maps it to `deleted`.\nconst readDaxParameterGroup: OverrideReader = async ({ physicalId, region }) => {\n const name = str(physicalId);\n if (!name) return undefined;\n const c = new DAXClient({ region, ...READ_RETRY });\n const g = (await c.send(new DescribeParameterGroupsCommand({ ParameterGroupNames: [name] })))\n .ParameterGroups?.[0];\n if (!g) throw new ResourceGoneError(`DAX ParameterGroup ${name} absent`);\n const model: Record<string, unknown> = {};\n if (str(g.ParameterGroupName)) model.ParameterGroupName = g.ParameterGroupName;\n if (str(g.Description)) model.Description = g.Description;\n const p = await c.send(new DescribeDaxParametersCommand({ ParameterGroupName: name }));\n const values: Record<string, string> = {};\n for (const param of p.Parameters ?? []) {\n // Skip system-fixed parameters (IsModifiable === 'FALSE') — they are not user-declarable.\n if (param.IsModifiable === 'FALSE') continue;\n const pName = str(param.ParameterName);\n const pValue = param.ParameterValue;\n if (pName !== undefined && typeof pValue === 'string') values[pName] = pValue;\n }\n if (Object.keys(values).length > 0) model.ParameterNameValues = values;\n return model;\n};\n\n// AWS::DAX::SubnetGroup — NON_PROVISIONABLE (issue #534). The CFn physical id (Ref) IS the\n// SubnetGroupName. Project SubnetGroupName/Description and flatten Subnets[].SubnetIdentifier to\n// the CFn SubnetIds list. Drop the computed/managed fields (VpcId/SupportedNetworkTypes).\n// Read-ONLY. Empty result -> ResourceGoneError so the router maps it to `deleted`.\nconst readDaxSubnetGroup: OverrideReader = async ({ physicalId, region }) => {\n const name = str(physicalId);\n if (!name) return undefined;\n const c = new DAXClient({ region, ...READ_RETRY });\n const g = (await c.send(new DescribeSubnetGroupsCommand({ SubnetGroupNames: [name] })))\n .SubnetGroups?.[0];\n if (!g) throw new ResourceGoneError(`DAX SubnetGroup ${name} absent`);\n const model: Record<string, unknown> = {};\n if (str(g.SubnetGroupName)) model.SubnetGroupName = g.SubnetGroupName;\n if (str(g.Description)) model.Description = g.Description;\n const subnetIds = (g.Subnets ?? [])\n .map((s) => str(s.SubnetIdentifier))\n .filter((v): v is string => v !== undefined);\n if (subnetIds.length > 0) model.SubnetIds = subnetIds;\n return model;\n};\n\n// Align a live DNS value's trailing dot to the declared value's style, so AWS's\n// always-trailing-dot form (\"x.cloudfront.net.\") is not false drift against a\n// declared value without the dot (a GetAtt-resolved DomainName has no dot). Real\n// drift to a different name still differs.\nconst alignTrailingDot = (live: string | undefined, declared: unknown): string | undefined => {\n if (live === undefined) return undefined;\n const declHasDot = typeof declared === 'string' && declared.endsWith('.');\n return declHasDot ? (live.endsWith('.') ? live : `${live}.`) : live.replace(/\\.$/, '');\n};\n\n// Route53 stores/returns special characters in a record name as octal escapes\n// (`\\ooo`): a wildcard `*.example.net` comes back as `\\052.example.net.`, and space\n// → `\\040`, etc. The declared/template name uses the literal character, so a\n// verbatim compare misreads the wildcard record as absent — throwing ResourceGoneError\n// → a FALSE `deleted` finding (and leaving the record's returned Name as false\n// declared drift). Unescape before matching AND in the returned model so both the\n// existence check and the value compare see the literal form. See\n// https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DomainNameFormat.html\nconst unescapeRoute53Name = (s: string): string =>\n s.replace(/\\\\(\\d{3})/g, (_m, oct: string) => String.fromCharCode(Number.parseInt(oct, 8)));\n\n// AWS::Route53::RecordSet — CC API GetResource throws UnsupportedActionException.\n// Read via Route53 ListResourceRecordSets (the CFn physical id is\n// `<HostedZoneId>_<Name>_<Type>`; declared values are preferred, id is the fallback).\nconst readRoute53RecordSet: OverrideReader = async ({ physicalId, declared, region }) => {\n const parts = physicalId.split('_');\n const hasIdParts = parts.length >= 3;\n const hostedZoneId = str(declared.HostedZoneId) ?? (hasIdParts ? parts[0] : undefined);\n const name = str(declared.Name) ?? (hasIdParts ? parts[1] : undefined);\n const type = str(declared.Type) ?? (hasIdParts ? parts[parts.length - 1] : undefined);\n if (!hostedZoneId || !name || !type) return undefined;\n // A name+type can have MANY records that differ only by SetIdentifier (weighted,\n // latency, failover, geolocation, multivalue routing — an L1 CfnRecordSet pattern).\n // MaxItems:1 returned only the FIRST one at the cursor, so the declared variant was\n // either read as the WRONG record (false positive/negative against the wrong values)\n // or missed entirely. Drop the cap (Route53's default page is 100 records from the\n // StartRecord cursor, which holds all variants of one name+type consecutively) and\n // disambiguate by SetIdentifier below.\n const c = new Route53Client({ region, ...READ_RETRY });\n const canon = (s: string): string => unescapeRoute53Name(s).replace(/\\.$/, '').toLowerCase();\n // Match the declared SetIdentifier too: a simple record declares none and AWS\n // returns none (undefined === undefined), while a weighted/latency variant matches\n // its specific identifier instead of whichever sibling happened to come first.\n const declSetId = str(declared.SetIdentifier);\n const isOurNameType = (x: ResourceRecordSet): boolean =>\n x.Type === type && !!x.Name && canon(x.Name) === canon(name);\n const isExact = (x: ResourceRecordSet): boolean =>\n isOurNameType(x) && (x.SetIdentifier ?? undefined) === declSetId;\n // PAGINATE: a name+type with many SetIdentifier variants (weighted/latency/geo/failover/\n // multivalue), or a name that sorts past the default ~300-record page, can land the\n // declared record on a LATER page. Reading only page 1 would misread a PRESENT record as\n // absent and throw ResourceGoneError → a FALSE `deleted` (and revert would then recreate\n // an existing record). Page from the name+type cursor until the exact record is found.\n // Early-stop once our name+type's records are exhausted: Route53 returns records sorted,\n // so all variants of one name+type are contiguous — once we've seen them and a page has\n // none, the declared SetIdentifier is genuinely absent.\n let rec: ResourceRecordSet | undefined;\n let sawOurNameType = false;\n let startName: string | undefined = name;\n let startType: RRType | undefined = type as RRType;\n let startId: string | undefined;\n for (;;) {\n const r: ListResourceRecordSetsCommandOutput = await c.send(\n new ListResourceRecordSetsCommand({\n HostedZoneId: hostedZoneId,\n StartRecordName: startName,\n StartRecordType: startType,\n ...(startId !== undefined && { StartRecordIdentifier: startId }),\n })\n );\n const page = r.ResourceRecordSets ?? [];\n rec = page.find(isExact);\n if (rec) break;\n const pageHasOurNameType = page.some(isOurNameType);\n if (pageHasOurNameType) sawOurNameType = true;\n // exhausted our name+type's contiguous run, or the whole listing -> genuinely absent\n if ((sawOurNameType && !pageHasOurNameType) || !r.IsTruncated) break;\n startName = r.NextRecordName;\n startType = r.NextRecordType as RRType | undefined;\n startId = r.NextRecordIdentifier;\n }\n // The zone was listed successfully (every page) but the declared name+type(+SetIdentifier)\n // record is absent — it was deleted out of band. Distinct from the \"couldn't resolve the\n // target\" guard above (returns undefined → skipped): here we KNOW it is gone.\n if (!rec)\n throw new ResourceGoneError(\n `Route53 RecordSet ${name} ${type} absent from zone ${hostedZoneId}`\n );\n const model: Record<string, unknown> = {\n Name: alignTrailingDot(\n rec.Name === undefined ? undefined : unescapeRoute53Name(rec.Name),\n declared.Name\n ),\n Type: rec.Type,\n HostedZoneId: hostedZoneId,\n };\n if (rec.TTL !== undefined) model.TTL = String(rec.TTL); // CFn TTL is a string\n const records = rec.ResourceRecords?.map((rr) => rr.Value).filter((v): v is string => !!v);\n if (records && records.length > 0) model.ResourceRecords = records;\n if (rec.AliasTarget) {\n const declAlias = declared.AliasTarget as Record<string, unknown> | undefined;\n model.AliasTarget = {\n DNSName: alignTrailingDot(rec.AliasTarget.DNSName, declAlias?.DNSName),\n HostedZoneId: rec.AliasTarget.HostedZoneId,\n EvaluateTargetHealth: rec.AliasTarget.EvaluateTargetHealth ?? false,\n };\n }\n // Routing-policy fields — projected away before, so a console change to a weight /\n // failover role / health check was invisible. All absent for a simple record (the\n // common case) so they add no noise; present only on the routing variant the user\n // declared, which is now matched correctly via SetIdentifier above.\n if (rec.SetIdentifier !== undefined) model.SetIdentifier = rec.SetIdentifier;\n if (rec.Weight !== undefined) model.Weight = rec.Weight;\n if (rec.Region !== undefined) model.Region = rec.Region;\n if (rec.Failover !== undefined) model.Failover = rec.Failover;\n if (rec.MultiValueAnswer !== undefined) model.MultiValueAnswer = rec.MultiValueAnswer;\n if (rec.HealthCheckId !== undefined) model.HealthCheckId = rec.HealthCheckId;\n const geo = rec.GeoLocation;\n if (geo)\n model.GeoLocation = {\n ...(geo.ContinentCode !== undefined && { ContinentCode: geo.ContinentCode }),\n ...(geo.CountryCode !== undefined && { CountryCode: geo.CountryCode }),\n ...(geo.SubdivisionCode !== undefined && { SubdivisionCode: geo.SubdivisionCode }),\n };\n // Geoproximity + CIDR routing-policy fields — the two newer routing variants, projected\n // away before so an out-of-band change to a geoproximity Bias/region or a CIDR\n // collection/location was invisible. Both objects exist ONLY on a record using that\n // routing policy (absent on a simple/weighted/latency/geo/failover record), so they add\n // no noise to the common case. Bias defaults to 0 when omitted — folded via\n // KNOWN_DEFAULT_PATHS so a record declaring only AWSRegion stays CLEAN.\n const geoProx = rec.GeoProximityLocation;\n if (geoProx)\n model.GeoProximityLocation = {\n ...(geoProx.AWSRegion !== undefined && { AWSRegion: geoProx.AWSRegion }),\n ...(geoProx.LocalZoneGroup !== undefined && { LocalZoneGroup: geoProx.LocalZoneGroup }),\n ...(geoProx.Coordinates !== undefined && {\n Coordinates: {\n ...(geoProx.Coordinates.Latitude !== undefined && {\n Latitude: geoProx.Coordinates.Latitude,\n }),\n ...(geoProx.Coordinates.Longitude !== undefined && {\n Longitude: geoProx.Coordinates.Longitude,\n }),\n },\n }),\n ...(geoProx.Bias !== undefined && { Bias: geoProx.Bias }),\n };\n const cidr = rec.CidrRoutingConfig;\n if (cidr)\n model.CidrRoutingConfig = {\n ...(cidr.CollectionId !== undefined && { CollectionId: cidr.CollectionId }),\n ...(cidr.LocationName !== undefined && { LocationName: cidr.LocationName }),\n };\n return model;\n};\n\n// AWS::Glue::Table — CC API GetResource throws UnsupportedActionException. Read via\n// Glue GetTable. Maps the live Table back to the CFn `{ CatalogId?, DatabaseName,\n// TableInput }` shape, returning ONLY the TableInput sub-fields CFn models —\n// AWS-managed fields (CreateTime / UpdateTime / CreatedBy / VersionId /\n// IsRegisteredWithLakeFormation / DatabaseName / CatalogId inside Table) are dropped\n// as they are not declarable and would be pure noise.\nconst readGlueTable: OverrideReader = async ({ physicalId, declared, region }) => {\n const idParts = physicalId.split('|');\n const dbName = str(declared.DatabaseName) ?? (idParts.length >= 2 ? idParts[0] : undefined);\n const tableInput = declared.TableInput as Record<string, unknown> | undefined;\n const name =\n str(tableInput?.Name) ?? (idParts.length >= 2 ? idParts[idParts.length - 1] : undefined);\n if (!dbName || !name) return undefined;\n const catalogId = str(declared.CatalogId);\n const c = new GlueClient({ region, ...READ_RETRY });\n const r = await c.send(\n new GetTableCommand({\n DatabaseName: dbName,\n Name: name,\n ...(catalogId && { CatalogId: catalogId }),\n })\n );\n const t = r.Table;\n if (!t) return undefined;\n const ti: Record<string, unknown> = { Name: t.Name };\n const copy = <K extends keyof typeof t>(k: K, as: string): void => {\n if (t[k] !== undefined) ti[as] = t[k];\n };\n copy('Description', 'Description');\n copy('Owner', 'Owner');\n copy('Retention', 'Retention');\n copy('TableType', 'TableType');\n copy('Parameters', 'Parameters');\n copy('PartitionKeys', 'PartitionKeys');\n copy('StorageDescriptor', 'StorageDescriptor');\n copy('ViewOriginalText', 'ViewOriginalText');\n copy('ViewExpandedText', 'ViewExpandedText');\n // TargetTable — a Glue resource-link table points at another catalog/db/table; it\n // was the one CFn-modeled TableInput field the projection omitted, so an out-of-band\n // repoint was undetectable. Absent for a normal (non-link) table, so adding it is\n // inert there (no FP) and only the resource-link case gains coverage.\n copy('TargetTable', 'TargetTable');\n const model: Record<string, unknown> = { DatabaseName: dbName, TableInput: ti };\n if (catalogId) model.CatalogId = catalogId;\n return model;\n};\n\n// AWS::Glue::Classifier — CC API GetResource throws UnsupportedActionException, so the\n// classifier was silently `skipped` and any out-of-band change to it (a delimiter, a grok\n// pattern, a JSON path) was invisible. Read via Glue GetClassifier. The CFn physical id is\n// the classifier name; the live `Classifier` is a one-of union ({CsvClassifier |\n// GrokClassifier | JsonClassifier | XMLClassifier}) that mirrors the CFn shape — project\n// the present member, dropping the AWS-managed Version / CreationTime / LastUpdated fields\n// (not CFn-declarable, pure noise).\n// `Serde` is a CsvClassifier field GetClassifier returns as \"None\" by default but the CFn\n// schema does NOT model (verified live — it surfaced as a bogus [Potential Drift] value); a\n// user can never declare it, so projecting it would be a permanent undeclared false\n// inventory. Dropped alongside the AWS-managed Version / CreationTime / LastUpdated.\nconst GLUE_CLASSIFIER_MANAGED = new Set(['Version', 'CreationTime', 'LastUpdated', 'Serde']);\nconst readGlueClassifier: OverrideReader = async ({ physicalId, declared, region }) => {\n const declMember = (declared.CsvClassifier ??\n declared.GrokClassifier ??\n declared.JsonClassifier ??\n declared.XMLClassifier) as Record<string, unknown> | undefined;\n const name = str(physicalId) ?? str(declMember?.Name);\n if (!name) return undefined;\n const c = new GlueClient({ region, ...READ_RETRY });\n const r = await c.send(new GetClassifierCommand({ Name: name }));\n const cl = r.Classifier;\n if (!cl) return undefined;\n const project = (o: object): Record<string, unknown> =>\n Object.fromEntries(\n Object.entries(o as Record<string, unknown>).filter(([k]) => !GLUE_CLASSIFIER_MANAGED.has(k))\n );\n const out: Record<string, unknown> = {};\n if (cl.CsvClassifier) out.CsvClassifier = project(cl.CsvClassifier);\n if (cl.GrokClassifier) out.GrokClassifier = project(cl.GrokClassifier);\n if (cl.JsonClassifier) out.JsonClassifier = project(cl.JsonClassifier);\n if (cl.XMLClassifier) out.XMLClassifier = project(cl.XMLClassifier);\n return out;\n};\n\n// AWS::Glue::Workflow — CC API GetResource throws UnsupportedActionException, so the\n// workflow was silently `skipped` and an out-of-band change to its Description /\n// DefaultRunProperties / MaxConcurrentRuns was invisible. Read via Glue GetWorkflow. The\n// CFn physical id is the workflow name; project the CFn-modeled scalar/map props, dropping\n// AWS-managed run/graph state (CreatedOn / LastModifiedOn / LastRun / Graph) and `Tags`\n// (handled by the shared aws:* tag strip). MaxConcurrentRuns is a number CFn declares.\nconst readGlueWorkflow: OverrideReader = async ({ physicalId, declared, region }) => {\n const name = str(physicalId) ?? str(declared.Name);\n if (!name) return undefined;\n const c = new GlueClient({ region, ...READ_RETRY });\n const r = await c.send(new GetWorkflowCommand({ Name: name }));\n const w = r.Workflow;\n if (!w) return undefined;\n const out: Record<string, unknown> = { Name: w.Name };\n if (w.Description !== undefined) out.Description = w.Description;\n if (w.DefaultRunProperties !== undefined) out.DefaultRunProperties = w.DefaultRunProperties;\n if (w.MaxConcurrentRuns !== undefined) out.MaxConcurrentRuns = w.MaxConcurrentRuns;\n return out;\n};\n\n// AWS::Glue::Connection — CC API GetResource throws UnsupportedActionException, so the\n// connection was silently `skipped` and an out-of-band change to its network/JDBC settings\n// (ConnectionType, PhysicalConnectionRequirements [subnet/SG/AZ], ConnectionProperties,\n// Description) was invisible — a security-relevant FN on a common ETL data-source resource.\n// Read via Glue GetConnection with HidePassword:true so NO credential ever enters the\n// baseline. Project the CFn `ConnectionInput` shape, dropping AWS-managed status/timestamps.\n// SECRET note: any returned ConnectionProperties.*PASSWORD key is dropped (HidePassword\n// returns the encrypted blob on some paths, and a secret must never land in the .cdkrd\n// baseline). `SECRET_ID` is KEPT — it is a Secrets Manager ARN (config, not a secret), so\n// an out-of-band repoint to a different secret stays detectable. The modern SECRET_ID /\n// NETWORK pattern carries no inline password, so this is FP-clean there; a legacy\n// inline-PASSWORD connection's password just stays a readGap. Read-ONLY (no SDK writer):\n// closing the FN [detection] is the value; a revert that omitted an un-read credential\n// could clear a JDBC password, so it is deferred.\nconst GLUE_CONNECTION_MANAGED = new Set([\n 'CreationTime',\n 'LastUpdatedTime',\n 'LastUpdatedBy',\n 'Status',\n 'StatusReason',\n 'LastConnectionValidationTime',\n 'ConnectionSchemaVersion',\n]);\nconst GLUE_CONNECTION_SECRET_KEYS = /PASSWORD/i;\nconst readGlueConnection: OverrideReader = async ({ physicalId, declared, region }) => {\n const declInput = declared.ConnectionInput as Record<string, unknown> | undefined;\n const name = str(physicalId) ?? str(declInput?.Name);\n if (!name) return undefined;\n const catalogId = str(declared.CatalogId);\n const c = new GlueClient({ region, ...READ_RETRY });\n const r = await c.send(\n new GetConnectionCommand({\n Name: name,\n HidePassword: true,\n ...(catalogId && { CatalogId: catalogId }),\n })\n );\n const conn = r.Connection;\n if (!conn) return undefined;\n const ci: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(conn)) {\n if (GLUE_CONNECTION_MANAGED.has(k) || k === 'Name') continue;\n ci[k] = v;\n }\n ci.Name = conn.Name;\n // never let a credential into the baseline, regardless of HidePassword behaviour\n if (ci.ConnectionProperties && typeof ci.ConnectionProperties === 'object') {\n ci.ConnectionProperties = Object.fromEntries(\n Object.entries(ci.ConnectionProperties as Record<string, unknown>).filter(\n ([k]) => !GLUE_CONNECTION_SECRET_KEYS.test(k)\n )\n );\n }\n const out: Record<string, unknown> = { ConnectionInput: ci };\n if (catalogId) out.CatalogId = catalogId;\n return out;\n};\n\n// AWS::Logs::MetricFilter — CC API GetResource throws ValidationException. Read via\n// CloudWatch Logs DescribeMetricFilters. The CFn physical id IS the filter name;\n// the log group comes from the declared (GetAtt-resolved) LogGroupName.\nconst readMetricFilter: OverrideReader = async ({ physicalId, declared, region }) => {\n const logGroup = str(declared.LogGroupName);\n const filterName = str(physicalId) ?? str(declared.FilterName);\n if (!logGroup || !filterName) return undefined;\n const c = new CloudWatchLogsClient({ region, ...READ_RETRY });\n // `filterNamePrefix: filterName` narrows each page to filters that START WITH this\n // name — but when many filters share the prefix (a name that is also a prefix of\n // others), the EXACT-named one can be paginated past the first page. Follow\n // nextToken until it is found, so a present filter is never misread as deleted (a\n // false negative). Stops as soon as the exact match appears.\n let mf: MetricFilter | undefined;\n let nextToken: string | undefined;\n do {\n const r = await c.send(\n new DescribeMetricFiltersCommand({\n logGroupName: logGroup,\n filterNamePrefix: filterName,\n ...(nextToken && { nextToken }),\n })\n );\n mf = r.metricFilters?.find((m) => m.filterName === filterName);\n nextToken = r.nextToken;\n } while (!mf && nextToken);\n // The log group was described successfully (every page) but the exact-named filter is\n // absent — it was deleted out of band. (A deleted LOG GROUP instead throws\n // ResourceNotFoundException above → also `deleted`; an unresolvable target returned\n // undefined → skipped before the describe.)\n if (!mf)\n throw new ResourceGoneError(`MetricFilter ${filterName} absent from log group ${logGroup}`);\n return {\n LogGroupName: logGroup,\n FilterName: filterName,\n FilterPattern: mf.filterPattern ?? '',\n MetricTransformations: (mf.metricTransformations ?? []).map((t) => ({\n MetricName: t.metricName,\n MetricNamespace: t.metricNamespace,\n MetricValue: t.metricValue,\n ...(t.defaultValue !== undefined && { DefaultValue: t.defaultValue }),\n ...(t.unit !== undefined && { Unit: t.unit }),\n ...(t.dimensions !== undefined && { Dimensions: t.dimensions }),\n })),\n // ApplyOnTransformedLogs (CFn AWS::Logs::MetricFilter prop) controls whether the\n // filter evaluates the TRANSFORMED log events instead of the originals — toggling it\n // out of band silently changes what the metric counts. It was omitted, so that change\n // was invisible. FP-safe: projected only when present; a live false is a top-level\n // undeclared value that isTrivialEmpty drops, so a never-set filter stays CLEAN and\n // only an out-of-band flip to true surfaces.\n ...(mf.applyOnTransformedLogs !== undefined && {\n ApplyOnTransformedLogs: mf.applyOnTransformedLogs,\n }),\n };\n};\n\n// AWS::Scheduler::Schedule — Cloud Control CAN read this type, but its\n// primaryIdentifier is the bare Name and the read handler only looks in the\n// DEFAULT schedule group: a schedule in any other group reads as not-found and\n// falsely reports DELETED (proven live on the harvest3 fixture, R74 — Name-only,\n// \"group/name\", \"group|name\", and the full ARN were all tried against CC).\n// Read via Scheduler GetSchedule with the declared GroupName instead. The CFn\n// physical id IS the schedule name.\nconst readSchedulerSchedule: OverrideReader = async ({ physicalId, declared, region }) => {\n const name = str(physicalId) ?? str(declared.Name);\n if (!name) return undefined;\n const group = str(declared.GroupName); // omitted -> service default group\n const c = new SchedulerClient({ region, ...READ_RETRY });\n // Not-found propagates so the router maps a genuinely deleted schedule to `deleted`.\n const s = await c.send(\n new GetScheduleCommand({ Name: name, ...(group && { GroupName: group }) })\n );\n // Project ONLY CFn-modeled props — Arn/CreationDate/LastModificationDate are\n // AWS-managed noise the classifier should never see from an SDK reader.\n return {\n Name: s.Name,\n ...(s.GroupName !== undefined && { GroupName: s.GroupName }),\n ...(s.ScheduleExpression !== undefined && { ScheduleExpression: s.ScheduleExpression }),\n ...(s.ScheduleExpressionTimezone !== undefined && {\n ScheduleExpressionTimezone: s.ScheduleExpressionTimezone,\n }),\n ...(s.FlexibleTimeWindow !== undefined && { FlexibleTimeWindow: s.FlexibleTimeWindow }),\n ...(s.State !== undefined && { State: s.State }),\n ...(s.Description !== undefined && { Description: s.Description }),\n ...(s.KmsKeyArn !== undefined && { KmsKeyArn: s.KmsKeyArn }),\n ...(s.ActionAfterCompletion !== undefined && {\n ActionAfterCompletion: s.ActionAfterCompletion,\n }),\n ...(s.StartDate !== undefined && { StartDate: s.StartDate.toISOString() }),\n ...(s.EndDate !== undefined && { EndDate: s.EndDate.toISOString() }),\n ...(s.Target !== undefined && { Target: s.Target }),\n };\n};\n\n// AWS::CodeBuild::Project — Cloud Control GetResource throws\n// UnsupportedActionException (R84/R85, observed live on the harvest6 fixture).\n// Read via CodeBuild BatchGetProjects — the CFn physical id IS the project name.\n// Maps the camelCase SDK Project back to the CFn PascalCase shape, projecting\n// ONLY CFn-modeled props (Arn / Created / LastModified / Badge URL are\n// AWS-managed noise). The declared compare is subset-based, so nested fields the\n// template never set are ignored; an absent project returns undefined (-> skip).\nconst readCodeBuildProject: OverrideReader = async ({ physicalId, declared, region }) => {\n const name = str(physicalId) ?? str(declared.Name);\n if (!name) return undefined;\n const c = new CodeBuildClient({ region, ...READ_RETRY });\n const r = await c.send(new BatchGetProjectsCommand({ names: [name] }));\n const p = r.projects?.[0];\n if (!p) return undefined;\n const model: Record<string, unknown> = { Name: p.name };\n if (p.serviceRole !== undefined) model.ServiceRole = p.serviceRole;\n if (p.description !== undefined) model.Description = p.description;\n if (p.timeoutInMinutes !== undefined) model.TimeoutInMinutes = p.timeoutInMinutes;\n if (p.queuedTimeoutInMinutes !== undefined)\n model.QueuedTimeoutInMinutes = p.queuedTimeoutInMinutes;\n if (p.encryptionKey !== undefined) model.EncryptionKey = p.encryptionKey;\n const src = p.source;\n if (src)\n model.Source = {\n ...(src.type !== undefined && { Type: src.type }),\n ...(src.location !== undefined && { Location: src.location }),\n ...(src.buildspec !== undefined && { BuildSpec: src.buildspec }),\n ...(src.gitCloneDepth !== undefined && { GitCloneDepth: src.gitCloneDepth }),\n // Security-relevant source flags omitted before, so an out-of-band flip was\n // invisible: InsecureSsl disables TLS verification when cloning the source;\n // ReportBuildStatus posts build status back to the source provider. Both default\n // false and are projected only when present; a live false folds via isTrivialEmpty\n // (nested undeclared), so a never-set project stays CLEAN and only a flip to true\n // surfaces.\n ...(src.insecureSsl !== undefined && { InsecureSsl: src.insecureSsl }),\n ...(src.reportBuildStatus !== undefined && { ReportBuildStatus: src.reportBuildStatus }),\n };\n const art = p.artifacts;\n if (art)\n model.Artifacts = {\n ...(art.type !== undefined && { Type: art.type }),\n ...(art.location !== undefined && { Location: art.location }),\n // The remaining CFn-declarable S3-artifact fields. They were omitted, so for an\n // S3-artifacts project the template's declared Name / NamespaceType / Packaging /\n // Path / ArtifactIdentifier had NO live counterpart → a false declared drift\n // (actual=undefined), live-caught here. AWS echoes exactly the declared values, so\n // projecting them makes the declared compare match; absent (CODEPIPELINE/NO_ARTIFACTS)\n // → skipped, so no new noise. OverrideArtifactName is a boolean that folds via\n // isTrivialEmpty when false.\n ...(art.name !== undefined && { Name: art.name }),\n ...(art.namespaceType !== undefined && { NamespaceType: art.namespaceType }),\n ...(art.packaging !== undefined && { Packaging: art.packaging }),\n ...(art.path !== undefined && { Path: art.path }),\n ...(art.artifactIdentifier !== undefined && { ArtifactIdentifier: art.artifactIdentifier }),\n ...(art.overrideArtifactName !== undefined && {\n OverrideArtifactName: art.overrideArtifactName,\n }),\n // EncryptionDisabled turns OFF artifact encryption (security-relevant); omitted\n // before, so disabling encryption out of band was undetectable. Same FP-safe shape\n // as S3Logs.EncryptionDisabled below: a live false folds via isTrivialEmpty, true\n // surfaces.\n ...(art.encryptionDisabled !== undefined && { EncryptionDisabled: art.encryptionDisabled }),\n };\n const env = p.environment;\n if (env)\n model.Environment = {\n ...(env.type !== undefined && { Type: env.type }),\n ...(env.computeType !== undefined && { ComputeType: env.computeType }),\n ...(env.image !== undefined && { Image: env.image }),\n ...(env.privilegedMode !== undefined && { PrivilegedMode: env.privilegedMode }),\n ...(env.imagePullCredentialsType !== undefined && {\n ImagePullCredentialsType: env.imagePullCredentialsType,\n }),\n ...(env.environmentVariables !== undefined && {\n EnvironmentVariables: env.environmentVariables.map((v) => ({\n Name: v.name,\n Value: v.value,\n ...(v.type !== undefined && { Type: v.type }),\n })),\n }),\n };\n // R(this) — these CFn-modeled props were OMITTED from the projection, so an\n // out-of-band change to them was undetectable (a declared one became a benign\n // readGap; an undeclared one was invisible). All FP-safe to add:\n // Visibility — PRIVATE/PUBLIC_READ; security-relevant (a project flipped to\n // PUBLIC_READ exposes build logs/artifacts). Always present; the\n // PRIVATE default is folded via KNOWN_DEFAULTS so it is atDefault,\n // not first-run noise.\n // VpcConfig — absent unless the project runs in a VPC → no noise when unused.\n // ConcurrentBuildLimit / SourceVersion — absent unless set → no noise.\n if (p.projectVisibility !== undefined) model.Visibility = p.projectVisibility;\n if (p.concurrentBuildLimit !== undefined) model.ConcurrentBuildLimit = p.concurrentBuildLimit;\n if (p.sourceVersion !== undefined) model.SourceVersion = p.sourceVersion;\n // ResourceAccessRole — the role CodeBuild assumes for batch builds / report groups;\n // absent unless set, so no noise. FileSystemLocations — EFS mounts into the build\n // (Identifier/Type/Location/MountPoint/MountOptions are all USER-specified, no server\n // default), absent unless the project mounts a file system. Both were omitted, so an\n // out-of-band change was invisible. (secondarySources / secondaryArtifacts /\n // buildBatchConfig / autoRetryLimit are deliberately NOT projected yet: the read shapes\n // diverge from the declared CFn shapes [secondaryArtifacts reads as BuildArtifacts —\n // missing Type/Name/NamespaceType/Packaging], carry server defaults [autoRetryLimit=0,\n // batch nested defaults], or are order-sensitive arrays — each needs its own FP-safe\n // handling, added when a real gap surfaces per the \"widen coverage as gaps surface\" rule.)\n if (p.resourceAccessRole !== undefined) model.ResourceAccessRole = p.resourceAccessRole;\n if (p.fileSystemLocations !== undefined && p.fileSystemLocations.length > 0)\n model.FileSystemLocations = p.fileSystemLocations.map((f) => ({\n ...(f.type !== undefined && { Type: f.type }),\n ...(f.location !== undefined && { Location: f.location }),\n ...(f.mountPoint !== undefined && { MountPoint: f.mountPoint }),\n ...(f.identifier !== undefined && { Identifier: f.identifier }),\n ...(f.mountOptions !== undefined && { MountOptions: f.mountOptions }),\n }));\n // LogsConfig — CloudWatch/S3 build-log destinations. Security/observability\n // relevant (enabling S3 logs writes build output to a bucket; a custom CloudWatch\n // group/stream redirects audit data) and commonly toggled in the console, yet it\n // was projected away entirely, so an out-of-band logging change was undetectable.\n // FP-safe: BatchGetProjects returns logsConfig=null (absent) when the project was\n // never configured with logging, and otherwise echoes EXACTLY the configured shape\n // with NO server-added siblings (verified live: setting only cloudWatchLogs does\n // not materialize an s3Logs default, and vice versa). So a never-configured project\n // emits nothing and a declared one matches its template. The lone always-present\n // extra is s3Logs.encryptionDisabled=false, which isTrivialEmpty suppresses — no\n // KNOWN_DEFAULTS entry needed.\n const logs = p.logsConfig;\n if (logs) {\n const cw = logs.cloudWatchLogs;\n const s3 = logs.s3Logs;\n model.LogsConfig = {\n ...(cw && {\n CloudWatchLogs: {\n ...(cw.status !== undefined && { Status: cw.status }),\n ...(cw.groupName !== undefined && { GroupName: cw.groupName }),\n ...(cw.streamName !== undefined && { StreamName: cw.streamName }),\n },\n }),\n ...(s3 && {\n S3Logs: {\n ...(s3.status !== undefined && { Status: s3.status }),\n ...(s3.location !== undefined && { Location: s3.location }),\n ...(s3.encryptionDisabled !== undefined && { EncryptionDisabled: s3.encryptionDisabled }),\n },\n }),\n };\n }\n // BadgeEnabled — a public build-status badge exposes build state; console-toggleable.\n // badge.badgeEnabled is false when off → isTrivialEmpty suppresses it (no first-run\n // noise); flipping it true surfaces. badge.badgeRequestUrl is a read-only computed\n // URL, deliberately not projected.\n if (p.badge?.badgeEnabled !== undefined) model.BadgeEnabled = p.badge.badgeEnabled;\n const vpc = p.vpcConfig;\n if (vpc && (vpc.vpcId || vpc.subnets?.length || vpc.securityGroupIds?.length))\n model.VpcConfig = {\n ...(vpc.vpcId !== undefined && { VpcId: vpc.vpcId }),\n ...(vpc.subnets !== undefined && { Subnets: vpc.subnets }),\n ...(vpc.securityGroupIds !== undefined && { SecurityGroupIds: vpc.securityGroupIds }),\n };\n // Cache — was omitted, so an out-of-band switch to/from S3 caching (a cost + a\n // cross-project cache-sharing surface) was undetectable. BatchGetProjects ALWAYS\n // returns cache (default `{type:'NO_CACHE'}`), so the never-configured case is\n // folded to atDefault via KNOWN_DEFAULTS (`Cache: {Type:'NO_CACHE'}`); a declared\n // S3/LOCAL cache projects its real shape and matches the template. Modes/Location\n // are projected only when present so the NO_CACHE default is exactly `{Type:'NO_CACHE'}`\n // (else it would not fold). A declared cache change still surfaces.\n const cache = p.cache;\n if (cache)\n model.Cache = {\n ...(cache.type !== undefined && { Type: cache.type }),\n ...(cache.location !== undefined && { Location: cache.location }),\n ...(cache.modes?.length && { Modes: cache.modes }),\n };\n return model;\n};\n\n// AWS::ServiceDiscovery::HttpNamespace / ::PrivateDnsNamespace / ::PublicDnsNamespace —\n// the whole ServiceDiscovery family is a CC read gap (GetResource UnsupportedActionException,\n// confirmed live). Read via Cloud Map GetNamespace — the CFn physical id IS the namespace\n// Id (ns-xxxx). Project the CFn-modeled Name / Description AND the readOnly `Arn` / `Id`:\n// Arn and Id are schema-stripped from the COMPARISON (so they never false-flag) but kept in\n// `liveAttrs`, which is what an `Fn::GetAtt [<ns>, Arn]` resolves against. An ECS Service's\n// `ServiceConnectConfiguration.Namespace` is declared as that GetAtt (for ANY namespace\n// type), so without the namespace's Arn in liveAttrs the whole ServiceConnect config\n// resolves to UNRESOLVED and its drift is never detected. (ServiceCount / CreateDate /\n// Properties / a DNS namespace's Vpc stay readGaps — not projected.)\nconst readServiceDiscoveryNamespace: OverrideReader = async ({ physicalId, region }) => {\n const id = str(physicalId);\n if (!id) return undefined;\n const c = new ServiceDiscoveryClient({ region, ...READ_RETRY });\n const r = await c.send(new GetNamespaceCommand({ Id: id }));\n const ns = r.Namespace;\n if (!ns) return undefined;\n const model: Record<string, unknown> = {};\n if (ns.Name !== undefined) model.Name = ns.Name;\n if (ns.Description !== undefined) model.Description = ns.Description;\n if (ns.Arn !== undefined) model.Arn = ns.Arn; // readOnly: stripped from compare, kept for GetAtt\n if (ns.Id !== undefined) model.Id = ns.Id; // readOnly: ditto (a GetAtt [ns, Id] consumer)\n return model;\n};\n\n// AWS::ServiceDiscovery::Service — same CC read gap. Read via Cloud Map GetService;\n// the CFn physical id IS the service Id (srv-xxxx). Project the CFn-modeled props,\n// mapping the SDK shapes back to CFn PascalCase. DnsConfig.NamespaceId is a\n// deprecated/read-only echo, deliberately not projected (a service in an HTTP\n// namespace has no DnsConfig at all). HealthCheck* are projected only when present\n// so an HTTP service stays CLEAN. Id / Arn / InstanceCount / CreateDate are noise.\nconst readServiceDiscoveryService: OverrideReader = async ({ physicalId, region }) => {\n const id = str(physicalId);\n if (!id) return undefined;\n const c = new ServiceDiscoveryClient({ region, ...READ_RETRY });\n const r = await c.send(new GetServiceCommand({ Id: id }));\n const s = r.Service;\n if (!s) return undefined;\n const model: Record<string, unknown> = {};\n if (s.Name !== undefined) model.Name = s.Name;\n if (s.Description !== undefined) model.Description = s.Description;\n if (s.NamespaceId !== undefined) model.NamespaceId = s.NamespaceId;\n if (s.Type !== undefined) model.Type = s.Type;\n if (s.DnsConfig)\n model.DnsConfig = {\n ...(s.DnsConfig.RoutingPolicy !== undefined && { RoutingPolicy: s.DnsConfig.RoutingPolicy }),\n ...(s.DnsConfig.DnsRecords !== undefined && {\n DnsRecords: s.DnsConfig.DnsRecords.map((d) => ({ Type: d.Type, TTL: d.TTL })),\n }),\n };\n if (s.HealthCheckConfig)\n model.HealthCheckConfig = {\n ...(s.HealthCheckConfig.Type !== undefined && { Type: s.HealthCheckConfig.Type }),\n ...(s.HealthCheckConfig.ResourcePath !== undefined && {\n ResourcePath: s.HealthCheckConfig.ResourcePath,\n }),\n ...(s.HealthCheckConfig.FailureThreshold !== undefined && {\n FailureThreshold: s.HealthCheckConfig.FailureThreshold,\n }),\n };\n if (s.HealthCheckCustomConfig)\n model.HealthCheckCustomConfig = {\n ...(s.HealthCheckCustomConfig.FailureThreshold !== undefined && {\n FailureThreshold: s.HealthCheckCustomConfig.FailureThreshold,\n }),\n };\n return model;\n};\n\n// AWS::DocDB::DBCluster — Cloud Control GetResource throws\n// UnsupportedActionException (the DocumentDB family is a CC read gap, confirmed\n// live; before this the cluster + its props were `skipped`). Read via DocDB\n// DescribeDBClusters — the CFn physical id IS the DBClusterIdentifier. Project the\n// CFn-modeled props, mapping the SDK names back to CFn (EnabledCloudwatchLogsExports\n// -> EnableCloudwatchLogsExports, DBClusterParameterGroup -> DBClusterParameterGroupName,\n// VpcSecurityGroups[].VpcSecurityGroupId -> VpcSecurityGroupIds). Endpoint / Status /\n// ClusterCreateTime / DBClusterArn etc. are AWS-managed noise. AvailabilityZones is\n// deliberately NOT projected — it is create-only and AWS may reorder it, an FP surface\n// with no detection benefit (same rule as Subnet AZ). An absent cluster returns\n// undefined (-> skipped; a genuinely deleted one throws DBClusterNotFoundFault -> deleted).\nconst readDocDbCluster: OverrideReader = async ({ physicalId, declared, region }) => {\n const id = str(physicalId) ?? str(declared.DBClusterIdentifier);\n if (!id) return undefined;\n const c = new DocDBClient({ region, ...READ_RETRY });\n const r = await c.send(new DescribeDBClustersCommand({ DBClusterIdentifier: id }));\n const cl = r.DBClusters?.[0];\n if (!cl) return undefined;\n const model: Record<string, unknown> = {};\n if (cl.DBClusterIdentifier !== undefined) model.DBClusterIdentifier = cl.DBClusterIdentifier;\n if (cl.BackupRetentionPeriod !== undefined)\n model.BackupRetentionPeriod = cl.BackupRetentionPeriod;\n if (cl.Port !== undefined) model.Port = cl.Port;\n if (cl.EngineVersion !== undefined) model.EngineVersion = cl.EngineVersion;\n if (cl.MasterUsername !== undefined) model.MasterUsername = cl.MasterUsername;\n if (cl.PreferredBackupWindow !== undefined)\n model.PreferredBackupWindow = cl.PreferredBackupWindow;\n if (cl.PreferredMaintenanceWindow !== undefined)\n model.PreferredMaintenanceWindow = cl.PreferredMaintenanceWindow;\n if (cl.StorageEncrypted !== undefined) model.StorageEncrypted = cl.StorageEncrypted;\n if (cl.KmsKeyId !== undefined) model.KmsKeyId = cl.KmsKeyId;\n if (cl.DeletionProtection !== undefined) model.DeletionProtection = cl.DeletionProtection;\n if (cl.EnabledCloudwatchLogsExports !== undefined)\n model.EnableCloudwatchLogsExports = cl.EnabledCloudwatchLogsExports;\n if (cl.DBClusterParameterGroup !== undefined)\n model.DBClusterParameterGroupName = cl.DBClusterParameterGroup;\n const sgs = (cl.VpcSecurityGroups ?? [])\n .map((g) => g.VpcSecurityGroupId)\n .filter((s): s is string => s !== undefined);\n if (sgs.length > 0) model.VpcSecurityGroupIds = sgs;\n return model;\n};\n\n// AWS::DocDB::DBInstance — same CC read gap. Read via DescribeDBInstances; the CFn\n// physical id IS the DBInstanceIdentifier. Project the CFn-modeled props, mapping\n// PerformanceInsightsEnabled -> EnablePerformanceInsights. AvailabilityZone is\n// create-only and not projected. Endpoint / Status / InstanceCreateTime are noise.\nconst readDocDbInstance: OverrideReader = async ({ physicalId, declared, region }) => {\n const id = str(physicalId) ?? str(declared.DBInstanceIdentifier);\n if (!id) return undefined;\n const c = new DocDBClient({ region, ...READ_RETRY });\n const r = await c.send(new DescribeDBInstancesCommand({ DBInstanceIdentifier: id }));\n const inst = r.DBInstances?.[0];\n if (!inst) return undefined;\n const model: Record<string, unknown> = {};\n if (inst.DBInstanceIdentifier !== undefined)\n model.DBInstanceIdentifier = inst.DBInstanceIdentifier;\n if (inst.DBInstanceClass !== undefined) model.DBInstanceClass = inst.DBInstanceClass;\n if (inst.DBClusterIdentifier !== undefined) model.DBClusterIdentifier = inst.DBClusterIdentifier;\n if (inst.AutoMinorVersionUpgrade !== undefined)\n model.AutoMinorVersionUpgrade = inst.AutoMinorVersionUpgrade;\n if (inst.PreferredMaintenanceWindow !== undefined)\n model.PreferredMaintenanceWindow = inst.PreferredMaintenanceWindow;\n if (inst.CACertificateIdentifier !== undefined)\n model.CACertificateIdentifier = inst.CACertificateIdentifier;\n if (inst.PerformanceInsightsEnabled !== undefined)\n model.EnablePerformanceInsights = inst.PerformanceInsightsEnabled;\n return model;\n};\n\n// AWS::AppSync::ApiKey — Cloud Control GetResource throws UnsupportedActionException\n// (NON_PROVISIONABLE; confirmed live), so a declared API key was `skipped`. Read via\n// AppSync ListApiKeys. The CFn physical id is the ARN\n// `arn:aws:appsync:<region>:<acct>:apis/<apiId>/apikeys/<keyId>` — parse BOTH ids from\n// it (fall back to declared.ApiId). Project the CFn-modeled props: ApiId, Description,\n// Expires (epoch seconds). Description is omitted when AWS returns none/\"\" so a\n// no-description key stays CLEAN; Expires is undeclared in the common auto-key case\n// (-> recorded, not a declared FP).\nconst readAppSyncApiKey: OverrideReader = async ({ physicalId, declared, region }) => {\n const m = /apis\\/([^/]+)\\/apikeys\\/([^/]+)/.exec(str(physicalId) ?? '');\n const apiId = m?.[1] ?? str(declared.ApiId);\n const keyId = m?.[2];\n if (!apiId) return undefined;\n const c = new AppSyncClient({ region, ...READ_RETRY });\n const keys = (await c.send(new ListApiKeysCommand({ apiId }))).apiKeys ?? [];\n const k = keyId ? keys.find((x) => x.id === keyId) : keys[0];\n if (!k) return undefined; // key deleted out of band -> router maps undefined to skipped\n const model: Record<string, unknown> = { ApiId: apiId };\n if (k.description !== undefined && k.description !== '') model.Description = k.description;\n if (k.expires !== undefined) model.Expires = k.expires;\n return model;\n};\n\n// AWS::Cognito::IdentityPool — Cloud Control reads every property EXCEPT the three\n// writeOnly ones (CognitoEvents / PushSync / CognitoStreams), so an out-of-band\n// \"Cognito Events\" Sync trigger (a Lambda wired to the pool) is a silent read-gap that\n// `check` cannot see. CC has no GetResource gap for the base model, so read the base via\n// CC unchanged (low FP risk — identical to the default path) and ENRICH only with\n// CognitoEvents from the (deprecated but live) cognito-sync API. PushSync/CognitoStreams\n// stay writeOnly readGaps — they are not projected, so they can never false-positive.\n// (CognitoEvents is exempted from the writeOnly strip via OVERRIDE_READABLE_WRITEONLY so\n// the projected value is actually compared.)\nconst readCognitoIdentityPool: OverrideReader = async ({ physicalId, region }) => {\n const id = str(physicalId);\n if (!id) return undefined;\n const cc = new CloudControlClient({ region, ...READ_RETRY });\n // A deleted pool throws ResourceNotFound here, which the router maps to `deleted`.\n const g = await cc.send(\n new GetResourceCommand({ TypeName: 'AWS::Cognito::IdentityPool', Identifier: id })\n );\n const model = JSON.parse(g.ResourceDescription?.Properties ?? '{}') as Record<string, unknown>;\n try {\n const ev = await new CognitoSyncClient({ region, ...READ_RETRY }).send(\n new GetCognitoEventsCommand({ IdentityPoolId: id })\n );\n // Only project a NON-EMPTY event map: a pool with no Sync trigger reads back `{}`,\n // which must stay absent (declared) so a clean pool never reports false drift.\n if (ev.Events && Object.keys(ev.Events).length > 0) model.CognitoEvents = ev.Events;\n } catch {\n /* cognito-sync unavailable/disabled in the region -> leave CognitoEvents a readGap */\n }\n return model;\n};\n\n// The SES inbound receipt-rule family (ReceiptRuleSet / ReceiptRule / ReceiptFilter)\n// has NO Cloud Control handlers (GetResource throws UnsupportedActionException), so each\n// was silently `skipped` — zero drift coverage. Read them via the SES v1 API. NOTE: SES\n// inbound receipt rules exist only in us-east-1 / us-west-2 / eu-west-1; in any other\n// region these resources cannot exist, so the override naturally reads not-found there.\n\n// AWS::SES::ReceiptRuleSet — the only declarable property is RuleSetName, and the CFn\n// physical id IS the rule-set name. Read via SES DescribeReceiptRuleSet; project just\n// RuleSetName (Metadata.Name). A deleted set throws RuleSetDoesNotExistException →\n// mapped to `deleted` by the router.\nconst readSesReceiptRuleSet: OverrideReader = async ({ physicalId, declared, region }) => {\n const name = str(physicalId) ?? str(declared.RuleSetName);\n if (!name) return undefined;\n const c = new SESClient({ region, ...READ_RETRY });\n const r = await c.send(new DescribeReceiptRuleSetCommand({ RuleSetName: name }));\n const liveName = str(r.Metadata?.Name);\n if (!liveName) return undefined;\n return { RuleSetName: liveName };\n};\n\n// AWS::SES::ReceiptRule — its CFn physical id is the bare rule name; the parent\n// RuleSetName (createOnly) comes from the resolved declared property. Read via SES\n// DescribeReceiptRule({ RuleSetName, RuleName }). The SDK `ReceiptRule` shape mirrors the\n// CFn `Rule` shape 1:1 (same PascalCase keys, same Action union members\n// S3Action/BounceAction/LambdaAction/SNSAction/StopAction/WorkmailAction/AddHeaderAction/\n// ConnectAction — verified against the registry schema), and Actions is an ordered list\n// AWS preserves (actions execute sequentially), so it is projected verbatim. Project only\n// present fields: the boolean defaults (Enabled / ScanEnabled = false) fold via\n// isTrivialEmpty when undeclared, and TlsPolicy's \"Optional\" default is folded via\n// KNOWN_DEFAULT_PATHS. The CFn `After` placement hint is not readable (DescribeReceiptRule\n// never returns it) — a declared `After` stays an informational readGap (scalar). A\n// deleted rule throws RuleDoesNotExistException → mapped to `deleted` by the router.\nconst readSesReceiptRule: OverrideReader = async ({ physicalId, declared, region }) => {\n const ruleSetName = str(declared.RuleSetName);\n const declRule = declared.Rule as Record<string, unknown> | undefined;\n const ruleName = str(physicalId) ?? str(declRule?.Name);\n if (!ruleSetName || !ruleName) return undefined;\n const c = new SESClient({ region, ...READ_RETRY });\n const r = await c.send(\n new DescribeReceiptRuleCommand({ RuleSetName: ruleSetName, RuleName: ruleName })\n );\n const live = r.Rule;\n if (!live) return undefined;\n const rule: Record<string, unknown> = { Name: live.Name };\n const copy = <K extends keyof ReceiptRule>(k: K): void => {\n if (live[k] !== undefined) rule[k] = live[k];\n };\n copy('Enabled');\n copy('TlsPolicy');\n copy('ScanEnabled');\n if (live.Recipients && live.Recipients.length > 0) rule.Recipients = live.Recipients;\n if (live.Actions && live.Actions.length > 0) rule.Actions = live.Actions;\n return { RuleSetName: ruleSetName, Rule: rule };\n};\n\n// AWS::SES::ReceiptFilter — there is no single-get API, so read the whole list via SES\n// ListReceiptFilters and pick the entry by name (the CFn physical id is the filter name;\n// declared Filter.Name is the fallback). Project the CFn `Filter` shape ({ Name, IpFilter:\n// { Policy, Cidr } }) verbatim — the SDK ReceiptFilter mirrors it 1:1. The container list\n// is always readable, so an absent named filter means it was deleted out of band →\n// ResourceGoneError (mapped to `deleted`).\nconst readSesReceiptFilter: OverrideReader = async ({ physicalId, declared, region }) => {\n const declFilter = declared.Filter as Record<string, unknown> | undefined;\n const name = str(physicalId) ?? str(declFilter?.Name);\n if (!name) return undefined;\n const c = new SESClient({ region, ...READ_RETRY });\n const r = await c.send(new ListReceiptFiltersCommand({}));\n const f = (r.Filters ?? []).find((x) => x.Name === name);\n if (!f)\n throw new ResourceGoneError(`SES ReceiptFilter ${name} absent from the account's filter list`);\n const ipFilter = f.IpFilter;\n return {\n Filter: {\n Name: f.Name,\n ...(ipFilter && {\n IpFilter: {\n ...(ipFilter.Policy !== undefined && { Policy: ipFilter.Policy }),\n ...(ipFilter.Cidr !== undefined && { Cidr: ipFilter.Cidr }),\n },\n }),\n },\n };\n};\n\nexport const SDK_OVERRIDES: Record<string, OverrideReader> = {\n 'AWS::SES::ReceiptRuleSet': readSesReceiptRuleSet,\n 'AWS::SES::ReceiptRule': readSesReceiptRule,\n 'AWS::SES::ReceiptFilter': readSesReceiptFilter,\n 'AWS::Cognito::IdentityPool': readCognitoIdentityPool,\n 'AWS::AppSync::ApiKey': readAppSyncApiKey,\n 'AWS::ServiceDiscovery::HttpNamespace': readServiceDiscoveryNamespace,\n 'AWS::ServiceDiscovery::PrivateDnsNamespace': readServiceDiscoveryNamespace,\n 'AWS::ServiceDiscovery::PublicDnsNamespace': readServiceDiscoveryNamespace,\n 'AWS::ServiceDiscovery::Service': readServiceDiscoveryService,\n 'AWS::DocDB::DBCluster': readDocDbCluster,\n 'AWS::DocDB::DBInstance': readDocDbInstance,\n 'AWS::CodeBuild::Project': readCodeBuildProject,\n 'AWS::S3::BucketPolicy': readS3BucketPolicy,\n 'AWS::SNS::TopicPolicy': readSnsTopicPolicy,\n 'AWS::SQS::QueuePolicy': readSqsQueuePolicy,\n 'AWS::IAM::Policy': readIamPolicy,\n 'AWS::IAM::ManagedPolicy': readIamManagedPolicy,\n 'AWS::Lambda::Permission': readLambdaPermission,\n 'AWS::Budgets::Budget': readBudget,\n 'AWS::EC2::EIP': readEc2Eip,\n 'AWS::EC2::LaunchTemplate': readEc2LaunchTemplate,\n 'AWS::EC2::NetworkAclEntry': readEc2NetworkAclEntry,\n 'AWS::EC2::ClientVpnEndpoint': readEc2ClientVpnEndpoint,\n 'AWS::EC2::ClientVpnAuthorizationRule': readEc2ClientVpnAuthorizationRule,\n 'AWS::EC2::ClientVpnTargetNetworkAssociation': readEc2ClientVpnTargetNetworkAssociation,\n 'AWS::DAX::Cluster': readDaxCluster,\n 'AWS::DAX::ParameterGroup': readDaxParameterGroup,\n 'AWS::DAX::SubnetGroup': readDaxSubnetGroup,\n 'AWS::CloudWatch::AnomalyDetector': readCloudWatchAnomalyDetector,\n 'AWS::CodeBuild::ReportGroup': readCodeBuildReportGroup,\n 'AWS::DLM::LifecyclePolicy': readDlmLifecyclePolicy,\n 'AWS::DMS::Endpoint': readDmsEndpoint,\n 'AWS::DMS::ReplicationSubnetGroup': readDmsReplicationSubnetGroup,\n 'AWS::MediaConvert::Queue': readMediaConvertQueue,\n 'AWS::MediaConvert::JobTemplate': readMediaConvertJobTemplate,\n 'AWS::Route53::RecordSet': readRoute53RecordSet,\n 'AWS::Glue::Table': readGlueTable,\n 'AWS::Glue::Classifier': readGlueClassifier,\n 'AWS::Glue::Workflow': readGlueWorkflow,\n 'AWS::Glue::Connection': readGlueConnection,\n 'AWS::Logs::MetricFilter': readMetricFilter,\n 'AWS::Scheduler::Schedule': readSchedulerSchedule,\n};\n\n// ---------------------------------------------------------------------------\n// SDK supplements (SDK_SUPPLEMENTS)\n//\n// Unlike SDK_OVERRIDES (which REPLACE the Cloud Control read for a CC-gap type),\n// a supplement runs AFTER a successful CC GetResource and shallow-merges a few\n// EXTRA top-level fields onto the CC live model. The motivating case: a property\n// the CFn registry marks `writeOnlyProperties` is never returned by Cloud Control\n// (CC only echoes readable props), so the classify pipeline strips it from BOTH\n// sides and an out-of-band change to it is silently invisible — even though a\n// plain SDK Describe/Get API CAN read the value back. The supplement fetches just\n// those values; `schema-strip.ts` exempts the same props from the writeOnly strip\n// (OVERRIDE_READABLE_WRITEONLY) so they are actually compared.\n//\n// A supplement returns ONLY the extra keys (or undefined / {} when it has nothing\n// to add). It must be FP-safe: project a key only when AWS actually returns it, so\n// an unset optional prop stays absent on both sides rather than false-flagging.\nexport type SupplementReader = (ctx: OverrideCtx) => Promise<Record<string, unknown> | undefined>;\n\n// AWS::SSM::Parameter — `Description`/`AllowedPattern`/`Tier` (and `Policies`) are\n// writeOnly in the registry schema, so Cloud Control returns only Type/Value/\n// DataType/Name and a console edit to them was undetectable. Only SSM\n// `DescribeParameters` returns these (GetParameter does NOT). Project `Description`\n// and `AllowedPattern` (returned ONLY when explicitly set, so an unset value stays\n// absent on both sides — FP-safe) and `Tier` (always present; AWS auto-assigns\n// \"Standard\" when undeclared, folded via KNOWN_DEFAULTS, and resolves a requested\n// \"Intelligent-Tiering\" to the actual Standard/Advanced tier, folded by the\n// INTELLIGENT_TIERING equivalence in classify — declared \"Intelligent-Tiering\"\n// matches a live Standard/Advanced, while a real Standard↔Advanced change still\n// surfaces). `Policies` reads back as expanded policy objects with a runtime\n// PolicyStatus (shape differs from the CFn JSON-string input), so it stays a\n// writeOnly readGap.\nconst supplementSsmParameter: SupplementReader = async ({ physicalId, declared, region }) => {\n const name = str(declared.Name) ?? str(physicalId);\n if (!name) return undefined;\n const c = new SSMClient({ region, ...READ_RETRY });\n const r = await c.send(\n new DescribeParametersCommand({\n ParameterFilters: [{ Key: 'Name', Option: 'Equals', Values: [name] }],\n })\n );\n const p = r.Parameters?.[0];\n const extra: Record<string, unknown> = {};\n const desc = str(p?.Description);\n if (desc !== undefined) extra.Description = desc;\n const pattern = str(p?.AllowedPattern);\n if (pattern !== undefined) extra.AllowedPattern = pattern;\n const tier = str(p?.Tier);\n if (tier !== undefined) extra.Tier = tier;\n return Object.keys(extra).length > 0 ? extra : undefined;\n};\n\n// NOTE — AWS::Cognito::UserPool `EnabledMfas` (writeOnly; CC echoes MfaConfiguration\n// but never the enabled-method list) was evaluated as a supplement and DEFERRED:\n// it cannot be reliably reconstructed from the read APIs. GetUserPoolMfaConfig keeps\n// returning the full `SmsMfaConfiguration` block (the SNS caller config persists at\n// the pool level) even after SMS is no longer an enabled MFA factor — live-proven\n// (states \"SMS+TOTP\" and \"TOTP-only\" returned an identical SmsMfaConfiguration). So\n// presence-based SMS detection would both miss an SMS removal (FN) and false-flag a\n// pool that configures SMS for verification only (FP). describe-user-pool omits\n// EnabledMfas too. Deferred until a reliable per-factor enabled signal exists.\n\n// AWS::ElastiCache::ReplicationGroup — `PreferredMaintenanceWindow`,\n// `NotificationTopicArn` and `EngineVersion` are writeOnly on the RG in the registry\n// schema, so Cloud Control echoes the RG's other props but NEVER these three; an\n// out-of-band change to the maintenance window or the notification topic was\n// invisible. They are not stored on the RG object — they live on its MEMBER cache\n// clusters — so read MemberClusters[0] via DescribeCacheClusters and project them\n// VERBATIM (live-proven: \"sun:05:00-sun:06:00\" / the topic ARN / \"7.1.0\" read back\n// exactly as set). `NotificationConfiguration.TopicArn` maps to the CFn\n// `NotificationTopicArn`; only project it when a topic is configured (FP-safe).\n// EngineVersion carries the usual ElastiCache prefix quirk (declared \"7.1\" reads\n// \"7.1.0\"), folded by VERSION_PREFIX_PATHS. PreferredMaintenanceWindow is always\n// present (AWS auto-assigns one when undeclared) — when undeclared it surfaces as an\n// undeclared/recorded value, not drift; when declared it is compared verbatim.\nconst supplementElastiCacheReplicationGroup: SupplementReader = async ({ physicalId, region }) => {\n const id = str(physicalId);\n if (!id) return undefined;\n const c = new ElastiCacheClient({ region, ...READ_RETRY });\n const rg = await c.send(new DescribeReplicationGroupsCommand({ ReplicationGroupId: id }));\n const member = firstStr(rg.ReplicationGroups?.[0]?.MemberClusters);\n if (!member) return undefined;\n const cc = await c.send(\n new DescribeCacheClustersCommand({ CacheClusterId: member, ShowCacheNodeInfo: false })\n );\n const cluster = cc.CacheClusters?.[0];\n if (!cluster) return undefined;\n const extra: Record<string, unknown> = {};\n const window = str(cluster.PreferredMaintenanceWindow);\n if (window !== undefined) extra.PreferredMaintenanceWindow = window;\n const topic = str(cluster.NotificationConfiguration?.TopicArn);\n if (topic !== undefined) extra.NotificationTopicArn = topic;\n const version = str(cluster.EngineVersion);\n if (version !== undefined) extra.EngineVersion = version;\n return Object.keys(extra).length > 0 ? extra : undefined;\n};\n\n// Recursively upper-case the first letter of every object key (the SDK returns the\n// ECS ServiceConnect config in camelCase; the CFn `ServiceConnectConfiguration` shape\n// is PascalCase). Verified to map the whole shape 1:1 — Enabled/Namespace/Services/\n// PortName/DiscoveryName/ClientAliases/Port/DnsName/IngressPortOverride/Timeout/Tls/\n// LogConfiguration all differ only by the leading-letter case (no acronym surprises).\nfunction pascalKeysDeep(v: unknown): unknown {\n if (Array.isArray(v)) return v.map(pascalKeysDeep);\n if (v && typeof v === 'object') {\n const out: Record<string, unknown> = {};\n for (const [k, val] of Object.entries(v)) {\n out[k.charAt(0).toUpperCase() + k.slice(1)] = pascalKeysDeep(val);\n }\n return out;\n }\n return v;\n}\n\n// AWS::ECS::Service — `ServiceConnectConfiguration` is writeOnly in the registry\n// schema, so Cloud Control echoes the service's other props but NEVER the Service\n// Connect config (it lives on the service's deployments). An out-of-band change to\n// the Service Connect wiring (the namespace, a client alias / DNS name / port, or\n// disabling it) was therefore invisible. Read it from the PRIMARY deployment via\n// ecs:DescribeServices and PascalCase it to the CFn shape. The namespace reads back\n// in the SAME form it was declared (declared ARN → reads ARN; declared name → reads\n// name — live-proven), so no normalization is needed. AWS defaults a service's\n// `DiscoveryName` to its `PortName` when undeclared, so drop a DiscoveryName that\n// equals PortName (the implicit default) to stay FP-safe.\n//\n// `VolumeConfigurations` (managed EBS volumes attached at deploy) is ALSO writeOnly and\n// ALSO on the PRIMARY deployment — projected the same way. AWS injects exactly ONE\n// default into `ManagedEBSVolume`: `FilesystemType` = \"xfs\" (live-proven — volumeType /\n// sizeInGiB / roleArn / encrypted / iops / throughput all read back verbatim or stay\n// absent when undeclared), so dropping a FilesystemType that equals \"xfs\" keeps it\n// FP-safe, mirroring the DiscoveryName fold.\nconst supplementEcsService: SupplementReader = async ({ physicalId, declared, region }) => {\n const serviceArn = str(physicalId);\n const cluster = str(declared.Cluster);\n if (!serviceArn || !cluster) return undefined;\n const c = new ECSClient({ region, ...READ_RETRY });\n const r = await c.send(new DescribeServicesCommand({ cluster, services: [serviceArn] }));\n const primary = r.services?.[0]?.deployments?.find((d) => d.status === 'PRIMARY');\n if (!primary) return undefined;\n const extra: Record<string, unknown> = {};\n\n const sc = primary.serviceConnectConfiguration;\n if (sc) {\n const config = pascalKeysDeep(sc) as Record<string, unknown>;\n const services = config.Services;\n if (Array.isArray(services)) {\n for (const s of services) {\n // AWS fills DiscoveryName with PortName when it is not declared — drop the\n // implicit default so a service that declares only PortName stays FP-clean.\n if (\n s &&\n typeof s === 'object' &&\n (s as Record<string, unknown>).DiscoveryName === (s as Record<string, unknown>).PortName\n ) {\n delete (s as Record<string, unknown>).DiscoveryName;\n }\n }\n }\n extra.ServiceConnectConfiguration = config;\n }\n\n const vols = primary.volumeConfigurations;\n if (Array.isArray(vols) && vols.length > 0) {\n const volumeConfigurations = pascalKeysDeep(vols) as Record<string, unknown>[];\n for (const v of volumeConfigurations) {\n const ebs = v?.ManagedEBSVolume as Record<string, unknown> | undefined;\n // FilesystemType defaults to \"xfs\" — drop the implicit default so a config that\n // does not declare it stays FP-clean (the only field AWS injects, live-proven).\n if (ebs && ebs.FilesystemType === 'xfs') delete ebs.FilesystemType;\n }\n extra.VolumeConfigurations = volumeConfigurations;\n }\n\n return Object.keys(extra).length > 0 ? extra : undefined;\n};\n\n// AWS::ElastiCache::User / AWS::MemoryDB::User — `AccessString` (the Redis/Valkey ACL:\n// WHAT the user may do) is writeOnly in both registry schemas, so Cloud Control never\n// returns it and an out-of-band ACL grant (e.g. adding +@write in the console) was\n// silently invisible — a security-relevant FN (#482). Both plain DescribeUsers APIs\n// return the live AccessString, so project it (always present on an active user;\n// FP-safe: projected only when returned). NOTE the service CANONICALIZES the string on\n// write (declared `on ~app:* +@read` reads back `on ~app:* -@all +@read`), so the\n// declared compare goes through isAccessStringEqual (ACCESS_STRING_PATHS in noise.ts)\n// instead of raw string equality. AuthenticationMode stays a writeOnly readGap: its\n// read shape ({Type, PasswordCount}) differs from the CFn input ({Type, Passwords}).\nconst supplementElastiCacheUser: SupplementReader = async ({ physicalId, declared, region }) => {\n const userId = str(declared.UserId) ?? str(physicalId);\n if (!userId) return undefined;\n const c = new ElastiCacheClient({ region, ...READ_RETRY });\n const r = await c.send(new DescribeCacheUsersCommand({ UserId: userId }));\n const access = str(r.Users?.[0]?.AccessString);\n return access !== undefined ? { AccessString: access } : undefined;\n};\n\nconst supplementMemoryDbUser: SupplementReader = async ({ physicalId, declared, region }) => {\n const userName = str(declared.UserName) ?? str(physicalId);\n if (!userName) return undefined;\n const c = new MemoryDBClient({ region, ...READ_RETRY });\n const r = await c.send(new DescribeMemoryDbUsersCommand({ UserName: userName }));\n const access = str(r.Users?.[0]?.AccessString);\n return access !== undefined ? { AccessString: access } : undefined;\n};\n\n// AWS::RedshiftServerless::Workgroup — ConfigParameters / SecurityGroupIds / SubnetIds are\n// writeOnly in the registry schema and, unlike the hunt's harvested corpus suggested, the\n// Cloud Control GetResource does NOT return them at the top level (they live only inside the\n// read-only `Workgroup` echo attribute), so an out-of-band change to a declared value — e.g.\n// a SecurityGroupIds swap (security-relevant) or a ConfigParameters flip — was a silent FN\n// (#490). GetWorkgroup returns all three; project them (SDK camelCase -> CFn PascalCase) so\n// the classify pipeline compares them (schema-strip OVERRIDE_READABLE_WRITEONLY exempts the\n// same three from the writeOnly strip). ConfigParameters is the ~9-element resolved default\n// set, folded to a ParameterKey-keyed subset by NAME_VALUE_SUBSET_PATHS; SecurityGroupIds /\n// SubnetIds are id-like sets (reorder folded by canonicalizeIdArraysDeep). FP-safe: each key\n// is projected only when GetWorkgroup actually returns it.\nconst supplementRedshiftServerlessWorkgroup: SupplementReader = async ({\n physicalId,\n declared,\n region,\n}) => {\n const workgroupName = str(declared.WorkgroupName) ?? str(physicalId);\n if (!workgroupName) return undefined;\n const c = new RedshiftServerlessClient({ region, ...READ_RETRY });\n const r = await c.send(new GetWorkgroupCommand({ workgroupName }));\n const wg = r.workgroup;\n if (!wg) return undefined;\n const extra: Record<string, unknown> = {};\n if (Array.isArray(wg.configParameters)) {\n extra.ConfigParameters = wg.configParameters.map((p) => ({\n ParameterKey: p.parameterKey,\n ParameterValue: p.parameterValue,\n }));\n }\n if (Array.isArray(wg.securityGroupIds)) extra.SecurityGroupIds = wg.securityGroupIds;\n if (Array.isArray(wg.subnetIds)) extra.SubnetIds = wg.subnetIds;\n return Object.keys(extra).length > 0 ? extra : undefined;\n};\n\n// AWS::MSK::Configuration — `ServerProperties` (the Kafka server.properties blob) is\n// writeOnly in the registry schema, so Cloud Control echoes only Arn/Name/Description/\n// LatestRevision and an out-of-band `kafka update-configuration` (a new revision flipping\n// e.g. auto.create.topics.enable or slashing log.retention.hours) was a silent FN (#508).\n// It IS SDK-readable: DescribeConfiguration returns LatestRevision.Revision and\n// DescribeConfigurationRevision returns the properties blob (the JS SDK decodes the base64\n// to bytes). Project the decoded text as `ServerProperties`; the compare goes through\n// isPropertiesFileEqual (PROPERTIES_FILE_PATHS in noise.ts — key=value equality, order /\n// comment / blank-line / trailing-newline insensitive) so formatting is not false drift.\n// KafkaVersionsList/Name are createOnly, so this supplement closes the type completely.\nconst supplementMskConfiguration: SupplementReader = async ({ physicalId, region }) => {\n const arn = str(physicalId);\n if (!arn || !arn.startsWith('arn:')) return undefined;\n const c = new KafkaClient({ region, ...READ_RETRY });\n const cfg = await c.send(new DescribeConfigurationCommand({ Arn: arn }));\n const revision = cfg.LatestRevision?.Revision;\n if (revision === undefined) return undefined;\n const rev = await c.send(\n new DescribeConfigurationRevisionCommand({ Arn: arn, Revision: revision })\n );\n const props = rev.ServerProperties;\n if (props === undefined) return undefined;\n const text =\n typeof props === 'string' ? props : Buffer.from(props as Uint8Array).toString('utf-8');\n return text.length > 0 ? { ServerProperties: text } : undefined;\n};\n\n// AWS::ElasticLoadBalancingV2::TrustStore — the mTLS CA bundle LOCATION\n// (CaCertificatesBundleS3Bucket/Key) is writeOnly AND unreadable by any Describe API, so an\n// out-of-band CA-bundle SWAP (the trust anchors — the most security-sensitive thing a\n// TrustStore has) was completely invisible: every `check` stayed CLEAN even after\n// modify-trust-store replaced the bundle (#505). The bundle LOCATION cannot be read, but its\n// CONTENT is reachable via elbv2:GetTrustStoreCaCertificatesBundle (a presigned S3 URL).\n// Project a stable, order/whitespace-insensitive SHA-256 of the live PEM set as the SYNTHETIC\n// field `CaCertificatesBundleSha256`. It is not a CFn property, so it surfaces as an\n// UNDECLARED integrity signal that `record` snapshots into the baseline; a later same-key (or\n// any) bundle swap changes the hash and re-surfaces as undeclared drift — the common rotation\n// pattern the writeOnly location can never catch. Non-fatal: any failure (GetBundle denied,\n// fetch failure, non-PEM body) skips the field (keep the CC model) rather than false-flag. A\n// computed digest has no write target, so revert reports it not-revertable (SYNTHETIC_READ_\n// SIGNAL_PATHS in plan.ts). Requires the extra `elbv2:GetTrustStoreCaCertificatesBundle`\n// permission plus an outbound fetch of the presigned URL — the only content read path AWS\n// offers.\nconst supplementTrustStore: SupplementReader = async ({ physicalId, region }) => {\n const arn = str(physicalId);\n if (!arn || !arn.startsWith('arn:')) return undefined;\n const c = new ElasticLoadBalancingV2Client({ region, ...READ_RETRY });\n const r = await c.send(new GetTrustStoreCaCertificatesBundleCommand({ TrustStoreArn: arn }));\n const url = str(r.Location);\n if (!url) return undefined;\n const resp = await fetch(url);\n if (!resp.ok) return undefined;\n const hash = hashCaBundle(await resp.text());\n return hash !== undefined ? { CaCertificatesBundleSha256: hash } : undefined;\n};\n\n// AWS::Lex::Bot — `BotLocales` (the ENTIRE conversational model: every locale, its\n// intents, sample utterances, slots, slot types, and prompts) is writeOnly in the\n// registry schema, so Cloud Control echoes only the bot's top-level props (Name /\n// Description / RoleArn / DataPrivacy / IdleSessionTTLInSeconds) and NEVER the model.\n// An out-of-band console edit to an utterance, a slot, or a whole intent was therefore\n// a completely silent false negative (#527). CC cannot read it, but the lexv2-models\n// API CAN — there is no single \"get the model\" call, so this supplement RECONSTRUCTS\n// the CFn `BotLocales` array by walking the tree: ListBotLocales → per locale\n// DescribeBotLocale + (ListSlotTypes → DescribeSlotType) + (ListIntents →\n// DescribeIntent → ListSlots → DescribeSlot), always at botVersion \"DRAFT\" (the CFn\n// working copy). The physical id is the Bot Id (e.g. \"I3PRF2VKMG\"). This is the\n// DEEPEST reader in cdkrd. REVERTABLE (update-only) via the SDK_NESTED_WRITERS\n// `writeLexBotLocales` (#553): an out-of-band edit to an EXISTING node reverts by\n// re-supplying the declared model through the lexv2-models Update* APIs + BuildBotLocale;\n// a STRUCTURAL add/delete of a whole node is refused (not-revertable), deferred.\n//\n// FP-safe: project a CFn field ONLY when the API returns it (so an unset optional prop\n// stays absent on BOTH sides). API field names verified against the lex-models-v2 model\n// types. Built-in slot types (AMAZON.* — a Describe on their signature errors and they\n// carry no user-authored values) are skipped: an intent Slot that points at a built-in\n// keeps its slotTypeId AS the SlotTypeName (built-in signatures ARE the CFn name), and a\n// built-in slot type never appears in the reconstructed SlotTypes array (CFn declares\n// only custom slot types). Non-fatal: ANY thrown error aborts the whole reconstruction\n// and returns undefined (keep the CC model) rather than a partial/false model.\ntype Rec = Record<string, unknown>;\nfunction projectLexPrompt(p: unknown): Rec | undefined {\n const ps = p as {\n maxRetries?: number;\n allowInterrupt?: boolean;\n messageGroups?: { message?: { plainTextMessage?: { value?: string } } }[];\n } | null;\n if (!ps || typeof ps !== 'object') return undefined;\n const out: Rec = {};\n if (typeof ps.maxRetries === 'number') out.MaxRetries = ps.maxRetries;\n if (Array.isArray(ps.messageGroups)) {\n out.MessageGroupsList = ps.messageGroups.map((g) => {\n const msg: Rec = {};\n const value = g?.message?.plainTextMessage?.value;\n if (typeof value === 'string') msg.PlainTextMessage = { Value: value };\n return { Message: msg };\n });\n }\n if (typeof ps.allowInterrupt === 'boolean') out.AllowInterrupt = ps.allowInterrupt;\n return out;\n}\n// lexv2 API SlotValueResolutionStrategy (PascalCase) -> CFn ResolutionStrategy (SCREAMING_SNAKE).\nconst LEX_RESOLUTION_STRATEGY_TO_CFN: Record<string, string> = {\n OriginalValue: 'ORIGINAL_VALUE',\n TopResolution: 'TOP_RESOLUTION',\n Concatenation: 'CONCATENATION',\n};\nconst supplementLexBot: SupplementReader = async ({ physicalId, region }) => {\n const botId = str(physicalId);\n if (!botId) return undefined;\n const botVersion = 'DRAFT';\n const c = new LexModelsV2Client({ region, ...READ_RETRY });\n try {\n const locales = await c.send(new ListBotLocalesCommand({ botId, botVersion }));\n const localeSummaries = locales.botLocaleSummaries ?? [];\n const botLocales: Rec[] = [];\n for (const ls of localeSummaries) {\n const localeId = str(ls.localeId);\n if (!localeId) continue;\n\n const loc = await c.send(new DescribeBotLocaleCommand({ botId, botVersion, localeId }));\n const cfnLocale: Rec = { LocaleId: localeId };\n const desc = str(loc.description);\n if (desc !== undefined) cfnLocale.Description = desc;\n if (typeof loc.nluIntentConfidenceThreshold === 'number') {\n cfnLocale.NluConfidenceThreshold = loc.nluIntentConfidenceThreshold;\n }\n const voiceId = str(loc.voiceSettings?.voiceId);\n if (voiceId !== undefined) {\n const vs: Rec = { VoiceId: voiceId };\n const engine = str(loc.voiceSettings?.engine);\n if (engine !== undefined) vs.Engine = engine;\n cfnLocale.VoiceSettings = vs;\n }\n\n // SlotTypes — custom slot types only; build id→name for slot resolution.\n const slotTypeNames = new Map<string, string>();\n const slotTypes = await c.send(new ListSlotTypesCommand({ botId, botVersion, localeId }));\n const cfnSlotTypes: Rec[] = [];\n for (const sts of slotTypes.slotTypeSummaries ?? []) {\n const slotTypeId = str(sts.slotTypeId);\n if (!slotTypeId) continue;\n // Built-in slot types (AMAZON.*) carry no describe-able user model; skip them.\n if (slotTypeId.startsWith('AMAZON.')) {\n slotTypeNames.set(slotTypeId, slotTypeId);\n continue;\n }\n const st = await c.send(\n new DescribeSlotTypeCommand({ botId, botVersion, localeId, slotTypeId })\n );\n const name = str(st.slotTypeName);\n if (name !== undefined) slotTypeNames.set(slotTypeId, name);\n const cfnSt: Rec = {};\n if (name !== undefined) cfnSt.Name = name;\n const stDesc = str(st.description);\n if (stDesc !== undefined) cfnSt.Description = stDesc;\n if (Array.isArray(st.slotTypeValues)) {\n cfnSt.SlotTypeValues = st.slotTypeValues.map((v) => {\n const entry: Rec = {};\n const sv = str(v.sampleValue?.value);\n if (sv !== undefined) entry.SampleValue = { Value: sv };\n if (Array.isArray(v.synonyms)) {\n const syns = v.synonyms\n .map((s) => str(s.value))\n .filter((x): x is string => x !== undefined)\n .map((x) => ({ Value: x }));\n if (syns.length > 0) entry.Synonyms = syns;\n }\n return entry;\n });\n }\n // The lexv2 API enum is PascalCase (OriginalValue/TopResolution/Concatenation) while\n // CFn's ResolutionStrategy is SCREAMING_SNAKE (ORIGINAL_VALUE/TOP_RESOLUTION/\n // CONCATENATION) — translate, else EVERY custom slot type false-drifts. Fall back to the\n // raw value for any future enum member so an unknown value surfaces rather than mangles.\n const strategy = str(st.valueSelectionSetting?.resolutionStrategy);\n if (strategy !== undefined) {\n cfnSt.ValueSelectionSetting = {\n ResolutionStrategy: LEX_RESOLUTION_STRATEGY_TO_CFN[strategy] ?? strategy,\n };\n }\n cfnSlotTypes.push(cfnSt);\n }\n\n // Intents — with their slots + slot-priority name resolution.\n const intents = await c.send(new ListIntentsCommand({ botId, botVersion, localeId }));\n const cfnIntents: Rec[] = [];\n for (const is of intents.intentSummaries ?? []) {\n const intentId = str(is.intentId);\n if (!intentId) continue;\n const intent = await c.send(\n new DescribeIntentCommand({ botId, botVersion, localeId, intentId })\n );\n const cfnIntent: Rec = {};\n const iName = str(intent.intentName);\n if (iName !== undefined) cfnIntent.Name = iName;\n const iDesc = str(intent.description);\n if (iDesc !== undefined) cfnIntent.Description = iDesc;\n const parentSig = str(intent.parentIntentSignature);\n if (parentSig !== undefined) cfnIntent.ParentIntentSignature = parentSig;\n if (Array.isArray(intent.sampleUtterances)) {\n const utterances = intent.sampleUtterances\n .map((u) => str(u.utterance))\n .filter((x): x is string => x !== undefined)\n .map((x) => ({ Utterance: x }));\n if (utterances.length > 0) cfnIntent.SampleUtterances = utterances;\n }\n\n // Slots — build id→name for the SlotPriorities resolution.\n const slotNames = new Map<string, string>();\n const cfnSlots: Rec[] = [];\n const slots = await c.send(new ListSlotsCommand({ botId, botVersion, localeId, intentId }));\n for (const ss of slots.slotSummaries ?? []) {\n const slotId = str(ss.slotId);\n if (!slotId) continue;\n const slot = await c.send(\n new DescribeSlotCommand({ botId, botVersion, localeId, intentId, slotId })\n );\n const slotName = str(slot.slotName);\n if (slotName !== undefined) slotNames.set(slotId, slotName);\n const cfnSlot: Rec = {};\n if (slotName !== undefined) cfnSlot.Name = slotName;\n const slotTypeId = str(slot.slotTypeId);\n if (slotTypeId !== undefined) {\n // Built-in slotTypeIds (AMAZON.*) map to themselves; custom ones resolve via\n // the slot-type name map (fall back to the raw id if unresolved).\n cfnSlot.SlotTypeName = slotTypeNames.get(slotTypeId) ?? slotTypeId;\n }\n const elic = slot.valueElicitationSetting;\n if (elic && typeof elic === 'object') {\n const cfnElic: Rec = {};\n const constraint = str(elic.slotConstraint);\n if (constraint !== undefined) cfnElic.SlotConstraint = constraint;\n const prompt = projectLexPrompt(elic.promptSpecification);\n if (prompt !== undefined) cfnElic.PromptSpecification = prompt;\n if (Object.keys(cfnElic).length > 0) cfnSlot.ValueElicitationSetting = cfnElic;\n }\n cfnSlots.push(cfnSlot);\n }\n\n if (Array.isArray(intent.slotPriorities)) {\n const priorities = intent.slotPriorities\n .map((p) => {\n const slotName = str(p.slotId) ? slotNames.get(str(p.slotId) as string) : undefined;\n if (typeof p.priority !== 'number' || slotName === undefined) return undefined;\n return { Priority: p.priority, SlotName: slotName };\n })\n .filter((x): x is { Priority: number; SlotName: string } => x !== undefined);\n if (priorities.length > 0) cfnIntent.SlotPriorities = priorities;\n }\n if (cfnSlots.length > 0) cfnIntent.Slots = cfnSlots;\n cfnIntents.push(cfnIntent);\n }\n\n if (cfnSlotTypes.length > 0) cfnLocale.SlotTypes = cfnSlotTypes;\n if (cfnIntents.length > 0) cfnLocale.Intents = cfnIntents;\n botLocales.push(cfnLocale);\n }\n return botLocales.length > 0 ? { BotLocales: botLocales } : undefined;\n } catch {\n // Non-fatal: any failure (a describe on a built-in, a transient, a missing DRAFT\n // version) keeps the CC model rather than emitting a partial/false BotLocales.\n return undefined;\n }\n};\n\nexport const SDK_SUPPLEMENTS: Record<string, SupplementReader> = {\n 'AWS::Lex::Bot': supplementLexBot,\n 'AWS::MSK::Configuration': supplementMskConfiguration,\n 'AWS::ElasticLoadBalancingV2::TrustStore': supplementTrustStore,\n 'AWS::SSM::Parameter': supplementSsmParameter,\n 'AWS::ElastiCache::ReplicationGroup': supplementElastiCacheReplicationGroup,\n 'AWS::ECS::Service': supplementEcsService,\n 'AWS::ElastiCache::User': supplementElastiCacheUser,\n 'AWS::MemoryDB::User': supplementMemoryDbUser,\n 'AWS::RedshiftServerless::Workgroup': supplementRedshiftServerlessWorkgroup,\n};\n","// Read source router (per resource TYPE):\n// SDK override (for common types Cloud Control API can't read) → CC API\n// GetResource → skip + log. Declared/undeclared labeling happens later.\nimport { type CloudControlClient, GetResourceCommand } from '@aws-sdk/client-cloudcontrol';\nimport { isResourceNotFoundError } from '../aws-errors.js';\nimport type { DesiredResource } from '../types.js';\nimport { SDK_OVERRIDES, SDK_SUPPLEMENTS } from './overrides.js';\n\nexport interface ReadResult {\n live?: Record<string, unknown>; // un-stripped property model\n skippedReason?: string;\n deleted?: boolean; // the resource was deleted out of band (read returned not-found)\n}\n\n// Cloud Control identifier adapters (R74): for most types the CFn physical id IS\n// the CC primaryIdentifier, but not for all — passing the raw physical id then\n// reads as not-found and falsely reports the resource DELETED (found live on the\n// harvest3 fixture). Each adapter derives the CC identifier; returning undefined\n// falls back to the physical id unchanged.\nexport const CC_IDENTIFIER_ADAPTERS: Record<\n string,\n (physicalId: string, declared: Record<string, unknown>) => string | undefined\n> = {\n // physical id = the API ARN (arn:...:apis/<apiId>); CC wants the bare ApiId.\n 'AWS::AppSync::GraphQLApi': (pid) => (pid.startsWith('arn:') ? pid.split('/').pop() : pid),\n // Batch JobDefinition: the CFn physical id is the full ARN\n // (arn:...:job-definition/<name>:<revision>), but CC's primaryIdentifier is the\n // bare JobDefinitionName — no ARN wrapper and no `:<revision>` suffix. Verified\n // live (batch-rich fixture): both the ARN and `<name>:<revision>` return\n // InvalidRequestException (\"Invalid identifier provided\"); only the bare name\n // reads. Without this the JobDefinition is silently `skipped` on every check\n // (read-gap), so undeclared drift on it is invisible. Job-definition names cannot\n // contain a colon, so stripping the trailing `:<revision>` is unambiguous; the\n // bare name resolves to the active revision, which is the one the template\n // reflects.\n 'AWS::Batch::JobDefinition': (pid) => {\n const tail = pid.startsWith('arn:') ? (pid.split('/').pop() ?? pid) : pid;\n return tail.replace(/:\\d+$/, '');\n },\n // ECR RepositoryCreationTemplate: the primaryIdentifier is the Prefix, but the\n // service NORMALIZES a trailing `/` away (`cdkrd-hunt/` is stored as `cdkrd-hunt`)\n // while CloudFormation keeps the user's declared form (with the slash) as the\n // physical id. So CC GetResource on `cdkrd-hunt/` returns NotFound and the template\n // is falsely reported `deleted` out of band (masking every declared prop on it, and\n // a revert would plan a re-CREATE of a template that already exists). Strip the\n // trailing slash to match the stored id. Verified live (misc0cov4 fixture,\n // 2026-07-03): `cdkrd-hunt/` NotFounds, `cdkrd-hunt` reads. The literal `ROOT`\n // prefix has no slash, so it passes through untouched. The residual declared\n // `Prefix` diff (`cdkrd-hunt/` vs `cdkrd-hunt`) is folded by TRAILING_SLASH_PATHS.\n 'AWS::ECR::RepositoryCreationTemplate': (pid) => pid.replace(/\\/$/, ''),\n // The rest are `[<parent ref>, <child id>]` composites: the CFn physical id is\n // only the child id; the parent id comes from the resolved declared Ref. CC's\n // composite-identifier separator is `|` (verified live — R74 Cognito, R76\n // ApiGatewayV2, R77 AppConfig). An unresolved parent → fall back to the bare\n // physical id (CC then reports an honest ValidationException skip).\n 'AWS::Cognito::UserPoolClient': compositeWith('UserPoolId'),\n 'AWS::Cognito::UserPoolGroup': compositeWith('UserPoolId'),\n // UserPoolIdentityProvider primaryIdentifier is [UserPoolId, ProviderName]; the CFn\n // physical id is the bare ProviderName, so without the composite it ValidationExceptions\n // and the IdP is silently `skipped` (read-gap). Same UserPoolId|<child> shape as its\n // siblings — verified live (cognito-idp-rich fixture).\n 'AWS::Cognito::UserPoolIdentityProvider': compositeWith('UserPoolId'),\n // UserPoolUser primaryIdentifier is [UserPoolId, Username] — parent-first. The CFn\n // physical id (Ref) is the bare Username, so without the composite CC GetResource\n // ValidationException-skips and the user is silently `skipped` (read-gap: undeclared\n // drift on the user is invisible). Same UserPoolId|<child> shape as its UserPoolClient\n // / UserPoolGroup / UserPoolDomain siblings. Verified live (cognito-userpooluser-rich):\n // `UserPoolId|Username` reads; the reverse order returns NotFound.\n 'AWS::Cognito::UserPoolUser': compositeWith('UserPoolId'),\n 'AWS::ApiGatewayV2::Stage': compositeWith('ApiId'),\n 'AWS::ApiGatewayV2::Route': compositeWith('ApiId'),\n 'AWS::ApiGatewayV2::Integration': compositeWith('ApiId'),\n // ApiGatewayV2::Authorizer primaryIdentifier is [AuthorizerId, ApiId] — CHILD\n // first, the REVERSE of its v2 siblings (Stage/Route/Integration are [ApiId,\n // <child>] parent-first). The CFn physical id is the bare AuthorizerId; ApiId comes\n // from the resolved declared Ref. Verified live (httpapi-authorizer-rich): the bare\n // id ValidationException-skips until paired as `AuthorizerId|ApiId`. Child-first like\n // ECS Service, so not `compositeWith` (that is parent-first).\n 'AWS::ApiGatewayV2::Authorizer': (pid, declared) => {\n if (pid.includes('|')) return pid;\n const apiId = declared.ApiId;\n return typeof apiId === 'string' && apiId.length > 0 ? `${pid}|${apiId}` : undefined;\n },\n 'AWS::AppConfig::Environment': compositeWith('ApplicationId'),\n 'AWS::AppConfig::ConfigurationProfile': compositeWith('ApplicationId'),\n // AppConfig HostedConfigurationVersion + Deployment are 3-SEGMENT composites whose\n // CFn physical id is only the LAST segment (the VersionNumber / DeploymentNumber), so\n // the bare id is a CC ValidationException skip (read-gap) until paired with both\n // parents from the resolved declared Refs — in primaryIdentifier order. Verified live\n // (appconfig-deployment-readgap): HostedConfigurationVersion reads as\n // `ApplicationId|ConfigurationProfileId|VersionNumber`; Deployment reads as\n // `ApplicationId|EnvironmentId|DeploymentNumber`. An unresolved parent → fall back to\n // the bare physical id (honest skip).\n 'AWS::AppConfig::HostedConfigurationVersion': (pid, declared) => {\n if (pid.includes('|')) return pid;\n const appId = declared.ApplicationId;\n const profileId = declared.ConfigurationProfileId;\n return typeof appId === 'string' &&\n appId.length > 0 &&\n typeof profileId === 'string' &&\n profileId.length > 0\n ? `${appId}|${profileId}|${pid}`\n : undefined;\n },\n 'AWS::AppConfig::Deployment': (pid, declared) => {\n if (pid.includes('|')) return pid;\n const appId = declared.ApplicationId;\n const envId = declared.EnvironmentId;\n return typeof appId === 'string' &&\n appId.length > 0 &&\n typeof envId === 'string' &&\n envId.length > 0\n ? `${appId}|${envId}|${pid}`\n : undefined;\n },\n // ApiGateway v1 (REST) parent-first composites `[RestApiId, <child>]` and Cognito\n // `[UserPoolId, <child>]` — same parent-first `|` shape as above. The CFn physical\n // id is only the child (Model→Name, RequestValidator→RequestValidatorId,\n // Resource→ResourceId, Stage→StageName, UserPoolDomain→Domain,\n // UserPoolResourceServer→Identifier); the parent comes from the resolved declared\n // Ref. All verified live (R129): the bare child id reads as a ValidationException /\n // not-found skip until paired with its parent. (ApiGateway::Method needs NO adapter\n // — its CFn physical id is ALREADY the full `RestApiId|ResourceId|HttpMethod`.)\n 'AWS::ApiGateway::Model': compositeWith('RestApiId'),\n 'AWS::ApiGateway::RequestValidator': compositeWith('RestApiId'),\n 'AWS::ApiGateway::Resource': compositeWith('RestApiId'),\n 'AWS::ApiGateway::Stage': compositeWith('RestApiId'),\n // Authorizer primaryIdentifier is [RestApiId, AuthorizerId] — parent-first like the\n // rest of the v1 family. The CFn physical id is the bare AuthorizerId; without this\n // a DECLARED Lambda/Cognito authorizer ValidationException-skips (read-gap). Verified\n // live (restapi-authorizer-rich).\n 'AWS::ApiGateway::Authorizer': compositeWith('RestApiId'),\n 'AWS::Cognito::UserPoolDomain': compositeWith('UserPoolId'),\n 'AWS::Cognito::UserPoolResourceServer': compositeWith('UserPoolId'),\n // AutoScaling LifecycleHook primaryIdentifier is [AutoScalingGroupName,\n // LifecycleHookName] — parent-first. The CFn physical id is the bare\n // LifecycleHookName; the ASG name comes from the resolved declared Ref. Without this\n // a declared hook ValidationException-skips (read-gap). Verified live\n // (autoscaling-lifecyclehook-rich).\n 'AWS::AutoScaling::LifecycleHook': compositeWith('AutoScalingGroupName'),\n // CodeDeploy DeploymentGroup primaryIdentifier is [ApplicationName,\n // DeploymentGroupName] — parent-first. The CFn physical id (Ref) is the bare\n // DeploymentGroupName; the ApplicationName comes from the resolved declared Ref.\n // Without this a declared deployment group is a CC ValidationException skip on every\n // check (read-gap), so both undeclared drift on it AND an out-of-band change to a\n // declared property (DeploymentConfigName, AlarmConfiguration, …) are invisible.\n // Verified live (codedeploy-deploymentgroup-readgap): `ApplicationName|DeploymentGroupName`\n // reads; the reverse order returns NotFound (\"No application found for name\").\n 'AWS::CodeDeploy::DeploymentGroup': compositeWith('ApplicationName'),\n // ElasticBeanstalk ConfigurationTemplate primaryIdentifier is [ApplicationName,\n // TemplateName] — parent-first. The CFn physical id is the bare TemplateName; the\n // ApplicationName comes from the resolved declared Ref. Without this a declared\n // configuration template is a CC ValidationException skip on every check (read-gap),\n // so both undeclared drift on it AND an out-of-band change to a declared property\n // (OptionSettings, SolutionStackName, …) are invisible. Verified live (#493,\n // CdkRealDriftHuntEbElbVpn, us-east-1): `ApplicationName|TemplateName` reads; the\n // reverse order (`TemplateName|ApplicationName`) returns NotFound.\n 'AWS::ElasticBeanstalk::ConfigurationTemplate': compositeWith('ApplicationName'),\n // ElasticBeanstalk ApplicationVersion primaryIdentifier is [ApplicationName, Id] —\n // parent-first, the same shape as its ConfigurationTemplate sibling above. The CFn\n // physical id is the bare version label; the ApplicationName comes from the resolved\n // declared Ref, so it almost certainly shares the same composite read-gap. Added\n // BY ANALOGY with the live-proven ConfigurationTemplate (#493) — not separately\n // live-verified this round.\n 'AWS::ElasticBeanstalk::ApplicationVersion': compositeWith('ApplicationName'),\n // AutoScaling ScheduledAction primaryIdentifier is [ScheduledActionName,\n // AutoScalingGroupName] — CHILD-first, the REVERSE of its sibling LifecycleHook\n // (parent-first). The CFn physical id is the bare ScheduledActionName; the ASG name\n // comes from the resolved declared Ref. Without this a declared scheduled action\n // ValidationException-skips (read-gap). Verified live (autoscaling-scheduledaction-rich).\n 'AWS::AutoScaling::ScheduledAction': (pid, declared) => {\n if (pid.includes('|')) return pid;\n const asg = declared.AutoScalingGroupName;\n return typeof asg === 'string' && asg.length > 0 ? `${pid}|${asg}` : undefined;\n },\n // ApiGateway::Deployment is the odd one out: its primaryIdentifier is\n // `[DeploymentId, RestApiId]` — CHILD first (verified live R129: `RestApiId|DeploymentId`\n // returns not-found; only `DeploymentId|RestApiId` reads). The CFn physical id is the\n // DeploymentId; RestApiId comes from the resolved declared Ref. Not `compositeWith`\n // (parent-first); this is child-first like ECS Service.\n 'AWS::ApiGateway::Deployment': (pid, declared) => {\n if (pid.includes('|')) return pid;\n const restApiId = declared.RestApiId;\n return typeof restApiId === 'string' && restApiId.length > 0\n ? `${pid}|${restApiId}`\n : undefined;\n },\n // ApiGateway::DocumentationPart is child-first like Deployment: its primaryIdentifier\n // is `[DocumentationPartId, RestApiId]` (verified live — `RestApiId|DocumentationPartId`\n // returns NotFound; only `DocumentationPartId|RestApiId` reads). The CFn physical id is\n // the bare DocumentationPartId; RestApiId comes from the resolved declared Ref. Without\n // this a declared documentation part is a CC ValidationException skip on every check\n // (read-gap), so undeclared drift on it is invisible. (RequestValidator/Model are\n // parent-first and already adapted above.)\n 'AWS::ApiGateway::DocumentationPart': (pid, declared) => {\n if (pid.includes('|')) return pid;\n const restApiId = declared.RestApiId;\n return typeof restApiId === 'string' && restApiId.length > 0\n ? `${pid}|${restApiId}`\n : undefined;\n },\n // ApplicationAutoScaling ScalingPolicy: primaryIdentifier is [Arn,\n // ScalableDimension]. The CFn physical id IS the PolicyARN, but ScalableDimension\n // is not a direct ScalingPolicy property — it rides on the resolved\n // `ScalingTargetId` (= the ScalableTarget physical id, formatted\n // `resourceId|scalableDimension|serviceNamespace`). Verified live (R79): the\n // PolicyARN was a CC ValidationException skip until paired with its dimension.\n 'AWS::ApplicationAutoScaling::ScalingPolicy': scalingPolicyComposite,\n // ECS Service primaryIdentifier is [ServiceArn, Cluster] — the SERVICE arn FIRST,\n // then the cluster (verified live R102: either the cluster name OR arn is recorded\n // for the second segment; the reverse order is rejected). The CFn physical id is\n // the service ARN; the cluster comes from the resolved declared `Cluster` ref. Not\n // `compositeWith` (that is parent-first); ECS is child(service)-first.\n 'AWS::ECS::Service': (pid, declared) => {\n if (pid.includes('|')) return pid;\n const cluster = declared.Cluster;\n return typeof cluster === 'string' && cluster.length > 0 ? `${pid}|${cluster}` : undefined;\n },\n // Logs SubscriptionFilter primaryIdentifier is [FilterName, LogGroupName] — CHILD\n // first (the FilterName, then the parent LogGroupName), the same child-first shape\n // as ECS Service. The CFn physical id is the bare FilterName; the LogGroupName comes\n // from the resolved declared Ref. Without this a declared subscription filter is a CC\n // ValidationException skip on every check (read-gap), so both undeclared drift on it\n // AND an out-of-band FilterPattern change are invisible. Verified live\n // (logs-subscriptionfilter-rich): `FilterName|LogGroupName` reads; the reverse order\n // 404s (\"The specified log group does not exist\").\n 'AWS::Logs::SubscriptionFilter': (pid, declared) => {\n if (pid.includes('|')) return pid;\n const lg = declared.LogGroupName;\n return typeof lg === 'string' && lg.length > 0 ? `${pid}|${lg}` : undefined;\n },\n // Logs LogStream primaryIdentifier is [LogGroupName, LogStreamName] — PARENT first\n // (LogGroupName, then LogStreamName), unlike the child-first SubscriptionFilter. The\n // CFn physical id (Ref) is the bare LogStreamName; the LogGroupName comes from the\n // resolved declared Ref. Without this a declared log stream is a CC ValidationException\n // skip on every check (read-gap, surfaced by the dogfood-data-pipeline Firehose error\n // log stream). Verified live: `<LogGroupName>|<LogStreamName>` reads, the reverse\n // ResourceNotFoundExceptions.\n 'AWS::Logs::LogStream': compositeWith('LogGroupName'),\n // SSM MaintenanceWindowTarget / MaintenanceWindowTask primaryIdentifier is\n // [WindowId, WindowTargetId] / [WindowId, WindowTaskId] (parent-first), but the CFn\n // physical id (Ref) is the bare child UUID — so CC GetResource ValidationException-skips\n // both on every check (silent read-gap on any patch-window automation). WindowId is a\n // required create prop (a Ref to the window) so it is always a resolved declared value.\n // Verified live (opsmisc-rich): `<WindowId>|<childId>` reads both; the bare child id is\n // rejected. (The sibling Athena PreparedStatement needs NO adapter — its CFn Ref is\n // already the `<StatementName>|<WorkGroup>` composite.)\n 'AWS::SSM::MaintenanceWindowTarget': compositeWith('WindowId'),\n 'AWS::SSM::MaintenanceWindowTask': compositeWith('WindowId'),\n // TransitGatewayRouteTablePropagation primaryIdentifier is [TransitGatewayRouteTableId,\n // TransitGatewayAttachmentId], but its CFn physical id (Ref) is the AWS console id\n // format `${attachmentId}_${routeTableId}` (underscore, ATTACHMENT first) — NOT the CC\n // composite, so CC GetResource ValidationException-skips it (read-gap). Unlike the\n // child-first adapters, BOTH composite segments are declared props, so build the\n // pipe composite directly from the resolved declared Refs (route-table FIRST, matching\n // the primaryIdentifier order). Verified live (tgw-routetable-readgap): `rtb|attach`\n // reads, the reverse and the underscore physical id both fail. (The sibling\n // RouteTableAssociation and TransitGatewayRoute need NO adapter — their CFn Ref is\n // ALREADY the full `rtb|attach` / `rtb|cidr` pipe composite.)\n 'AWS::EC2::TransitGatewayRouteTablePropagation': (pid, declared) => {\n if (pid.includes('|')) return pid;\n const rtb = declared.TransitGatewayRouteTableId;\n const att = declared.TransitGatewayAttachmentId;\n return typeof rtb === 'string' && rtb.length > 0 && typeof att === 'string' && att.length > 0\n ? `${rtb}|${att}`\n : undefined;\n },\n};\n\n// `${PolicyARN}|${ScalableDimension}` for a ScalingPolicy, extracting the\n// dimension from the resolved ScalingTargetId (`resourceId|dimension|namespace`).\n// undefined when the target ref did not resolve (→ honest skip).\nfunction scalingPolicyComposite(\n pid: string,\n declared: Record<string, unknown>\n): string | undefined {\n if (pid.includes('|')) return pid; // already composite — never double-suffix\n const targetId = declared.ScalingTargetId;\n if (typeof targetId !== 'string') return undefined;\n const dimension = targetId.split('|')[1];\n return dimension ? `${pid}|${dimension}` : undefined;\n}\n\n// Build a `${declared[parentKey]}|${physicalId}` composite CC identifier, or\n// undefined when the parent ref did not resolve (→ honest skip). Never\n// double-prefixes an id that is already composite.\nfunction compositeWith(\n parentKey: string\n): (pid: string, declared: Record<string, unknown>) => string | undefined {\n return (pid, declared) => {\n if (pid.includes('|')) return pid;\n const parent = declared[parentKey];\n return typeof parent === 'string' && parent.length > 0 ? `${parent}|${pid}` : undefined;\n };\n}\n\nexport async function readLive(\n cc: CloudControlClient,\n resource: DesiredResource,\n region: string,\n accountId: string\n): Promise<ReadResult> {\n const { resourceType, physicalId, declared } = resource;\n // Custom resources are backed by a user Lambda; there is NO Cloud Control type to\n // read, so calling GetResource just wastes an API round-trip (+ retries) and\n // returns a misleading \"ValidationException\". Short-circuit to a clear skip.\n if (resourceType.startsWith('Custom::') || resourceType === 'AWS::CloudFormation::CustomResource')\n return { skippedReason: 'custom resource — no cloud-side model to read' };\n const override = SDK_OVERRIDES[resourceType];\n if (override) {\n try {\n const live = await override({ physicalId: physicalId ?? '', declared, region, accountId });\n return live\n ? { live }\n : { skippedReason: 'SDK override: target not resolvable from template' };\n } catch (e) {\n if (isResourceNotFoundError(e)) return { deleted: true };\n return { skippedReason: `SDK override (${resourceType}): ${(e as Error).name}` };\n }\n }\n try {\n const identifier =\n CC_IDENTIFIER_ADAPTERS[resourceType]?.(physicalId ?? '', declared) ?? physicalId ?? '';\n const g = await cc.send(\n new GetResourceCommand({ TypeName: resourceType, Identifier: identifier })\n );\n const live = JSON.parse(g.ResourceDescription?.Properties ?? '{}') as Record<string, unknown>;\n // Supplement the CC model with writeOnly-but-SDK-readable props (e.g. SSM\n // Parameter Description) that Cloud Control never echoes. A supplement failure\n // is non-fatal: keep the CC model rather than dropping the whole read.\n const supplement = SDK_SUPPLEMENTS[resourceType];\n if (supplement) {\n try {\n const extra = await supplement({\n physicalId: physicalId ?? '',\n declared,\n region,\n accountId,\n });\n if (extra) Object.assign(live, extra);\n } catch {\n /* keep the CC model; the supplement prop stays an (unavoidable) readGap */\n }\n }\n return { live };\n } catch (e) {\n if (isResourceNotFoundError(e)) return { deleted: true };\n return { skippedReason: `CC API: ${(e as Error).name}` };\n }\n}\n","// Fetch a CloudFormation resource schema via describe-type and derive the\n// readOnly / writeOnly / default sets used for noise suppression — both as\n// top-level name sets (fast checks) and as full dotted paths (nested strip).\nimport { type CloudFormationClient, DescribeTypeCommand } from '@aws-sdk/client-cloudformation';\nimport type { SchemaInfo } from '../types.js';\n\nconst cache = new Map<string, SchemaInfo>();\nconst EMPTY: SchemaInfo = {\n readOnly: new Set(),\n writeOnly: new Set(),\n createOnly: new Set(),\n readOnlyPaths: [],\n writeOnlyPaths: [],\n createOnlyPaths: [],\n defaults: {},\n defaultPaths: {},\n unorderedScalarPaths: [],\n unorderedObjectArrayPaths: [],\n freeFormMapPaths: [],\n};\n\nexport async function getSchemaInfo(\n client: CloudFormationClient,\n resourceType: string\n): Promise<SchemaInfo> {\n const cached = cache.get(resourceType);\n if (cached) return cached;\n const info = await fetch(client, resourceType);\n cache.set(resourceType, info);\n return info;\n}\n\n// Top-level writeOnly properties that an SDK_OVERRIDES reader (read/overrides.ts) CAN\n// actually read back, so they must NOT be writeOnly-stripped / readGap'd for these types\n// — the override populates them and they should be compared like any readable property.\n// Kept in sync with SDK_OVERRIDES: AWS::EC2::LaunchTemplate `LaunchTemplateData` is\n// writeOnly in the registry schema (CC returns only ids/versions), but readEc2LaunchTemplate\n// reads the default version's data via DescribeLaunchTemplateVersions. (VersionDescription\n// and the top-level TagSpecifications stay writeOnly — the override does not project them.)\nexport const OVERRIDE_READABLE_WRITEONLY: Record<string, readonly string[]> = {\n 'AWS::EC2::LaunchTemplate': ['LaunchTemplateData'],\n // AWS::MSK::Configuration `ServerProperties` is writeOnly (CC never echoes the\n // server.properties blob); the SDK_SUPPLEMENTS reader fetches the latest revision's\n // decoded properties via kafka:DescribeConfigurationRevision, so compare it (through\n // isPropertiesFileEqual — PROPERTIES_FILE_PATHS), not readGap.\n 'AWS::MSK::Configuration': ['ServerProperties'],\n // CognitoEvents is writeOnly in the registry schema (CC GetResource never returns it),\n // but readCognitoIdentityPool projects it from the cognito-sync API, so compare it.\n // PushSync / CognitoStreams stay writeOnly readGaps (the override does not project them).\n 'AWS::Cognito::IdentityPool': ['CognitoEvents'],\n // AWS::SSM::Parameter `Description`/`AllowedPattern`/`Tier` are writeOnly (CC never\n // echoes them), but the SDK_SUPPLEMENTS reader fetches them via ssm:DescribeParameters\n // — so they must NOT be writeOnly-stripped/readGap'd, they should be compared like any\n // readable prop. Tier folds the undeclared \"Standard\" default (KNOWN_DEFAULTS) and the\n // declared \"Intelligent-Tiering\"→Standard/Advanced resolution (INTELLIGENT_TIERING_PATHS).\n // (Policies stays writeOnly: the supplement does not project it — its read shape with a\n // runtime PolicyStatus differs from the CFn JSON-string input.)\n 'AWS::SSM::Parameter': ['Description', 'AllowedPattern', 'Tier'],\n // AWS::ElastiCache::ReplicationGroup PreferredMaintenanceWindow / NotificationTopicArn\n // / EngineVersion are writeOnly on the RG (CC never echoes them); the SDK_SUPPLEMENTS\n // reader fetches them VERBATIM from the member cache cluster, so compare, not readGap.\n 'AWS::ElastiCache::ReplicationGroup': [\n 'PreferredMaintenanceWindow',\n 'NotificationTopicArn',\n 'EngineVersion',\n ],\n // AWS::ECS::Service `ServiceConnectConfiguration` / `VolumeConfigurations` are writeOnly\n // (CC never echoes them — they live on the service's deployments); the SDK_SUPPLEMENTS\n // reader reconstructs both from the PRIMARY deployment, so compare them, don't readGap.\n 'AWS::ECS::Service': ['ServiceConnectConfiguration', 'VolumeConfigurations'],\n // AWS::ElastiCache::User / AWS::MemoryDB::User `AccessString` (the Redis/Valkey ACL)\n // is writeOnly in both schemas, so an out-of-band ACL grant was silently invisible\n // (#482 — a security-relevant FN); the SDK_SUPPLEMENTS readers fetch it via each\n // service's DescribeUsers, so compare it (through isAccessStringEqual — the service\n // canonicalizes the string on write), don't readGap. AuthenticationMode/Passwords/\n // NoPasswordRequired stay writeOnly readGaps (read shape differs from CFn input).\n 'AWS::ElastiCache::User': ['AccessString'],\n 'AWS::MemoryDB::User': ['AccessString'],\n // AWS::RedshiftServerless::Workgroup ConfigParameters / SecurityGroupIds / SubnetIds\n // are writeOnly in the registry schema, so cdkrd filed them under the write-only readGap\n // bucket and an out-of-band change was silently invisible (#490 — a security-relevant FN\n // for an out-of-band SecurityGroupIds swap; live-proven on a ConfigParameters flip). But\n // UNLIKE the entries above, no SDK override is needed: the Cloud Control read ALREADY\n // returns all three at the TOP LEVEL of the same GetResource response cdkrd has (not just\n // inside the read-only `Workgroup` echo attribute), so exempting the writeOnly strip makes\n // cdkrd compare the value it already holds — no extra API call. ConfigParameters meets the\n // default-fill shape (declared 1, live echoes the full ~9-element default set), so it is\n // folded as a ParameterKey-keyed subset via NAME_VALUE_SUBSET_PATHS (noise.ts);\n // SecurityGroupIds / SubnetIds are id-like sets folded for reorder by canonicalizeIdArraysDeep.\n 'AWS::RedshiftServerless::Workgroup': ['ConfigParameters', 'SecurityGroupIds', 'SubnetIds'],\n // AWS::Lex::Bot `BotLocales` (the entire conversational model — intents, utterances,\n // slots, slot types, prompts) is writeOnly in the registry schema, so Cloud Control\n // never echoes it and an out-of-band console edit to the model was a silent FN (#527).\n // The SDK_SUPPLEMENTS reader RECONSTRUCTS it from the lexv2-models API tree walk, so\n // compare it, don't readGap. The other writeOnly Bot props (AutoBuildBotLocales,\n // BotFileS3Location, Replication, TestBotAliasSettings, TestBotAliasTags) stay\n // writeOnly readGaps — the supplement does not project them.\n 'AWS::Lex::Bot': ['BotLocales'],\n};\n\n// Curated readOnly SUPPLEMENTS: JSON-pointer property paths a type's CloudFormation\n// schema FORGETS to mark `readOnly`, so the readOnly strip leaves them in the live model\n// and they surface as first-run Potential Drift. This is the MIRROR of SDK_SUPPLEMENTS\n// (which patches writeOnly gaps the other direction, #482): here we patch a readOnly gap.\n// Applied on top of the fetched schema's readOnlyProperties BEFORE the strip runs, so the\n// property is stripped for EVERY tier (first-run noise, baseline, revert planning) — the\n// right treatment for a lifecycle/status attribute that can never be user intent and flaps\n// between values (so an equality-gated KNOWN_DEFAULTS fold would be wrong).\n//\n// AWS::NetworkManager::GlobalNetwork forgets readOnly on its lifecycle `State`\n// (AVAILABLE/UPDATING/DELETING) and `CreatedAt` timestamp — provably an AWS oversight:\n// the sibling AWS::NetworkManager::Site marks the SAME pair readOnly\n// (readOnlyProperties = [SiteId, SiteArn, State, CreatedAt]). GlobalNetwork's schema has\n// readOnly = [Id, Arn] only (#495). Keep this table CURATED/minimal — the corpus scan\n// found no other currently-leaking type, so do NOT add speculative entries.\nexport const SCHEMA_READONLY_SUPPLEMENTS: Record<string, readonly string[]> = {\n 'AWS::NetworkManager::GlobalNetwork': ['/properties/State', '/properties/CreatedAt'],\n};\n\n// Merge a type's readOnly supplement paths into readOnly (top-level set) + readOnlyPaths\n// (nested strip), so the schema-strip layer removes them exactly as if the registry schema\n// had listed them in readOnlyProperties. Exported for unit testing without an AWS call.\nexport function supplementReadOnly(info: SchemaInfo, resourceType: string): SchemaInfo {\n const supplements = SCHEMA_READONLY_SUPPLEMENTS[resourceType];\n if (!supplements?.length) return info;\n const dotted = supplements.map(pointerToDotted);\n const readOnlyPaths = [...new Set([...info.readOnlyPaths, ...dotted])];\n return {\n ...info,\n readOnly: new Set([...info.readOnly, ...dotted.filter((p) => !p.includes('.'))]),\n readOnlyPaths,\n };\n}\n\n// The MIRROR of OVERRIDE_READABLE_WRITEONLY: nested paths an SDK_OVERRIDES reader\n// CANNOT read back even though the registry schema does not mark them writeOnly —\n// the type's Describe API simply never returns them. Appended to `writeOnlyPaths`\n// so BOTH sides strip the path (readGap semantics): without this, a declared value\n// at such a path false-flags as declared drift against the reader's live model\n// (found live on AnomalyDetector: DescribeAnomalyDetectors never echoes a metric-math\n// query's cosmetic `Label`, so a declared label reported `desired=\"…\" actual=undefined`).\nexport const SDK_READER_GAP_PATHS: Record<string, readonly string[]> = {\n 'AWS::CloudWatch::AnomalyDetector': ['MetricMathAnomalyDetector.MetricDataQueries.*.Label'],\n};\n\n// Append a type's SDK-reader gap paths to writeOnlyPaths (strip from both sides).\n// Exported for unit testing without an AWS call.\nexport function injectReaderGaps(info: SchemaInfo, resourceType: string): SchemaInfo {\n const gaps = SDK_READER_GAP_PATHS[resourceType];\n if (!gaps?.length) return info;\n return { ...info, writeOnlyPaths: [...info.writeOnlyPaths, ...gaps] };\n}\n\n// Remove the override-readable writeOnly props from a type's writeOnly sets so the\n// classify pipeline compares (not strips/readGaps) the value the override now supplies.\n// Exported for unit testing without an AWS call.\nexport function exemptOverrideReadable(info: SchemaInfo, resourceType: string): SchemaInfo {\n const exempt = OVERRIDE_READABLE_WRITEONLY[resourceType];\n if (!exempt?.length) return info;\n const isExempt = (p: string): boolean => exempt.some((e) => p === e || p.startsWith(`${e}.`));\n return {\n ...info,\n writeOnly: new Set([...info.writeOnly].filter((k) => !exempt.includes(k))),\n writeOnlyPaths: info.writeOnlyPaths.filter((p) => !isExempt(p)),\n };\n}\n\nasync function fetch(client: CloudFormationClient, resourceType: string): Promise<SchemaInfo> {\n try {\n const r = await client.send(\n new DescribeTypeCommand({ Type: 'RESOURCE', TypeName: resourceType })\n );\n return injectReaderGaps(\n exemptOverrideReadable(\n supplementReadOnly(parseSchema(r.Schema ?? '{}'), resourceType),\n resourceType\n ),\n resourceType\n );\n } catch {\n return EMPTY;\n }\n}\n\n// JSON pointer \"/properties/A/B/*/C\" -> dotted \"A.B.*.C\"\nfunction pointerToDotted(p: string): string {\n // A JSON-pointer property path is `/properties/Foo/Bar`. Some CFn registry schemas\n // (e.g. OpenSearch `conditionalCreateOnlyProperties`) emit an INTERIOR or TRAILING\n // `/properties/` segment — `/properties/EncryptionAtRestOptions/properties` (the\n // block itself) or `/properties/AdvancedSecurityOptions/properties/Enabled`. Strip\n // the leading one, collapse any interior `/properties/` to the real nesting boundary,\n // and drop a trailing `/properties`, so the dotted path matches the actual model key\n // (`EncryptionAtRestOptions`, `AdvancedSecurityOptions.Enabled`) instead of keeping a\n // literal `properties` segment that matches nothing.\n return p\n .replace(/^\\/properties\\//, '')\n .replace(/\\/properties\\//g, '/')\n .replace(/\\/properties$/, '')\n .replace(/\\//g, '.');\n}\n\n// Unlike readOnly/writeOnly/createOnly (CFn pre-flattens those into pointer\n// arrays), nested `default` annotations live inline on the property schemas\n// (incl. inside `definitions`, reached via `$ref`). Walk the schema resolving\n// local `#/definitions/...` refs and collect every `default` keyed by its dotted\n// path — array `items` contribute a `*` segment, matching the readOnlyPaths\n// convention and the `[id]`->`*`-normalized live finding paths. The per-branch\n// `seen` ref-set breaks recursive definitions (a $ref cannot expand inside its\n// own descent). Best-effort: only `properties` + `items` are descended (not\n// oneOf/anyOf/allOf), so a missed default just stays `undeclared` — never a false\n// positive.\ntype SchemaNode = {\n $ref?: string;\n default?: unknown;\n type?: string;\n insertionOrder?: boolean;\n enum?: unknown[];\n properties?: Record<string, SchemaNode>;\n items?: SchemaNode;\n patternProperties?: Record<string, SchemaNode>;\n additionalProperties?: boolean | SchemaNode;\n};\nfunction collectDefaultPaths(\n definitions: Record<string, SchemaNode>,\n properties: Record<string, SchemaNode>\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n const walk = (node: SchemaNode | undefined, path: string, seen: ReadonlySet<string>): void => {\n if (!node || typeof node !== 'object') return;\n if (node.$ref) {\n const name = node.$ref.replace('#/definitions/', '');\n if (seen.has(name)) return; // recursive definition — stop\n walk(definitions[name], path, new Set(seen).add(name));\n return;\n }\n if ('default' in node && path) out[path] = node.default;\n if (node.properties)\n for (const [k, child] of Object.entries(node.properties))\n walk(child, path ? `${path}.${k}` : k, seen);\n if (node.items) walk(node.items, path ? `${path}.*` : '*', seen);\n };\n for (const [k, child] of Object.entries(properties)) walk(child, k, new Set());\n return out;\n}\n\n// Collect the dotted paths of arrays the schema marks `insertionOrder: false` (AWS\n// declaring the array UNORDERED), split by item shape — a reorder of either is never\n// drift (AWS may echo the set in its own canonical order), so classify folds them\n// WITHOUT a per-type table:\n// - `scalar`: items resolve to a SCALAR type — classify folds a same-multiset\n// difference at one of these paths (isEqualUnorderedScalarSet).\n// - `object`: items are OBJECTS with NO identity field (Key/Id/AttributeName/\n// IndexName/Name) — classify sorts BOTH sides by canonical JSON before the\n// positional diff, the schema-driven twin of UNORDERED_OBJECT_ARRAY_PROPS (#459;\n// found live on AccessAnalyzer ArchiveRules, whose RuleName is not an identity\n// field). Identity-keyed object arrays (Tags et al.) are EXCLUDED: they are\n// already deterministically aligned by canonicalizeTagListsDeep, and a second\n// canonical-JSON sort would churn that established order for zero gain.\n// Paths reached THROUGH an array element (which would carry a `*` segment) are\n// skipped — classify matches an exact dotted drift path, and those rarer\n// nested-under-array sets stay on the per-type allowlists. Same $ref-resolving,\n// recursion-guarded walk as collectDefaultPaths; best-effort (a missed array just\n// stays on the manual table — never a false positive).\nconst SCALAR_TYPES = new Set(['string', 'number', 'integer', 'boolean']);\n// Mirrors noise.ts IDENTITY_FIELDS (the keys canonicalizeTagListsDeep aligns on).\nconst ITEM_IDENTITY_FIELDS = ['Key', 'Id', 'AttributeName', 'IndexName', 'Name'];\nfunction collectUnorderedArrayPaths(\n definitions: Record<string, SchemaNode>,\n properties: Record<string, SchemaNode>\n): { scalar: string[]; object: string[] } {\n const scalar: string[] = [];\n const object: string[] = [];\n const resolve = (\n node: SchemaNode | undefined,\n seen: ReadonlySet<string>\n ): SchemaNode | undefined => {\n let n = node;\n const s = new Set(seen);\n while (n?.$ref) {\n const name = n.$ref.replace('#/definitions/', '');\n if (s.has(name)) return undefined; // recursive — stop\n s.add(name);\n n = definitions[name];\n }\n return n;\n };\n const isScalarItems = (it: SchemaNode | undefined): boolean => {\n if (!it) return false;\n if (it.properties) return false; // object items\n if (Array.isArray(it.enum) && it.enum.every((v) => typeof v !== 'object')) return true;\n return typeof it.type === 'string' && SCALAR_TYPES.has(it.type);\n };\n const isNonIdentityObjectItems = (it: SchemaNode | undefined): boolean => {\n if (!it) return false;\n const propKeys = Object.keys(it.properties ?? {});\n if (propKeys.length === 0) return false; // scalar or free-form — not a structured object set\n return !propKeys.some((k) => ITEM_IDENTITY_FIELDS.includes(k));\n };\n const walk = (node: SchemaNode | undefined, path: string, seen: ReadonlySet<string>): void => {\n const n = resolve(node, seen);\n if (!n) return;\n const nextSeen = node?.$ref ? new Set(seen).add(node.$ref.replace('#/definitions/', '')) : seen;\n if (n.type === 'array') {\n if (n.insertionOrder === false && path && !path.includes('*')) {\n const it = resolve(n.items, nextSeen);\n if (isScalarItems(it)) scalar.push(path);\n else if (isNonIdentityObjectItems(it)) object.push(path);\n }\n if (n.items) walk(n.items, path ? `${path}.*` : '*', nextSeen); // descend (only finds '*' paths, skipped above)\n }\n if (n.properties)\n for (const [k, child] of Object.entries(n.properties))\n walk(child, path ? `${path}.${k}` : k, nextSeen);\n };\n for (const [k, child] of Object.entries(properties)) walk(child, k, new Set());\n return { scalar: [...new Set(scalar)].sort(), object: [...new Set(object)].sort() };\n}\n\n// Collect the dotted paths of FREE-FORM MAP properties: a `type: object` schema node with\n// NO fixed `properties` whose contents are open — declared via `patternProperties` (regex\n// keys, e.g. Lambda Environment.Variables `[a-zA-Z][a-zA-Z0-9_]+`) or an object-valued\n// `additionalProperties` (Glue Parameters, ECS DockerLabels). Every key under such a node\n// is user-authored data, never an AWS-materialized nested default, so classify surfaces a\n// live-only sub-key there instead of folding it (R96 `undeclared-subkey`). A node with\n// fixed `properties` (a structured object) is NOT a free-form map even if it also allows\n// additionalProperties. Same $ref-resolving, recursion-guarded walk as the collectors\n// above; best-effort (a missed map just keeps folding — never a false positive). A map\n// NESTED UNDER AN ARRAY ELEMENT is KEPT (its path carries a `*` segment — ECS\n// ContainerDefinitions.*.DockerLabels / .LogConfiguration.Options, Volumes.*\n// .DockerVolumeConfiguration.Labels): classify matches via `startsWith` on the live\n// `[id]`->`*`-normalized path, so the `*` aligns (unlike the EXACT-match collectors above,\n// which skip `*`). Such a key is still surfaced (visibility); revert stays barred for it\n// because its live path carries the array bracket (isUnrevertableNested). A `Tags` bag is\n// EXCLUDED even when map-shaped — see the inline note (tags fold consistently with the\n// dominant LIST-shaped Tags, so map-tagged resources are not noisier on the first run).\nfunction collectFreeFormMapPaths(\n definitions: Record<string, SchemaNode>,\n properties: Record<string, SchemaNode>\n): string[] {\n const out: string[] = [];\n const isObjectSchema = (v: boolean | SchemaNode | undefined): v is SchemaNode =>\n typeof v === 'object' && v !== null;\n const walk = (node: SchemaNode | undefined, path: string, seen: ReadonlySet<string>): void => {\n if (!node || typeof node !== 'object') return;\n if (node.$ref) {\n const name = node.$ref.replace('#/definitions/', '');\n if (seen.has(name)) return; // recursive — stop\n walk(definitions[name], path, new Set(seen).add(name));\n return;\n }\n const hasFixedProps = node.properties && Object.keys(node.properties).length > 0;\n const isMap =\n node.type === 'object' &&\n !hasFixedProps &&\n ((node.patternProperties && Object.keys(node.patternProperties).length > 0) ||\n isObjectSchema(node.additionalProperties));\n // A `Tags` bag is EXCLUDED even when MAP-shaped (AWS::SSM::Parameter et al. model\n // Tags as a patternProperties map, while most types use a {Key,Value}[] LIST). Tags\n // are a special low-signal category the pipeline already handles separately\n // (canonicalizeTagLists / stripAwsTagsDeep / tagPreservingOps); surfacing an undeclared\n // map-tag key as freeFormKey would make map-tagged resources noisier on the first run\n // than LIST-tagged ones (whose nested `Tags[<id>]` keys fold) — an inconsistency users\n // can't see the cause of. So a map-tag key FOLDS like a list-tag key (still recorded by\n // record; a change after record surfaces as drift; still revertable via path shape).\n const lastSeg = path.split('.').at(-1);\n if (isMap && path && lastSeg !== 'Tags') out.push(path);\n if (node.properties)\n for (const [k, child] of Object.entries(node.properties))\n walk(child, path ? `${path}.${k}` : k, seen);\n if (node.items) walk(node.items, path ? `${path}.*` : '*', seen);\n };\n for (const [k, child] of Object.entries(properties)) walk(child, k, new Set());\n return [...new Set(out)].sort();\n}\n\n/** Exported for unit testing without an AWS call. */\nexport function parseSchema(schemaJson: string): SchemaInfo {\n const schema = JSON.parse(schemaJson) as {\n readOnlyProperties?: string[];\n writeOnlyProperties?: string[];\n createOnlyProperties?: string[];\n conditionalCreateOnlyProperties?: string[];\n properties?: Record<string, SchemaNode>;\n definitions?: Record<string, SchemaNode>;\n };\n const dotted = (arr: string[] | undefined): string[] => (arr ?? []).map(pointerToDotted);\n const topLevel = (paths: string[]): Set<string> => new Set(paths.filter((p) => !p.includes('.')));\n const readOnlyPaths = dotted(schema.readOnlyProperties);\n const writeOnlyPaths = dotted(schema.writeOnlyProperties);\n // Only HARD `createOnlyProperties` bar a revert. `conditionalCreateOnlyProperties`\n // are create-only ONLY in specific cases (e.g. an RDS read replica) — in the common\n // case they are MUTABLE in place (RDS BackupRetentionPeriod / MultiAZ / StorageType /\n // PreferredMaintenanceWindow / AutoMinorVersionUpgrade are all modifiable via\n // ModifyDBInstance). Merging them in barred revert of these everyday props with a\n // misleading \"create-only — requires replacement\" (a revert false-negative on a very\n // common resource). They are NOT barred now: a revert attempts the in-place change\n // and, if a specific change truly needs replacement, Cloud Control UpdateResource\n // rejects it cleanly (it never silently replaces) — an honest failure beats a silent\n // bar. (Live-confirmed on AWS::RDS::DBInstance BackupRetentionPeriod.)\n const createOnlyPaths = dotted(schema.createOnlyProperties);\n const defaults: Record<string, unknown> = {};\n for (const [k, def] of Object.entries(schema.properties ?? {})) {\n if (def && typeof def === 'object' && 'default' in def) defaults[k] = def.default;\n }\n const defaultPaths = collectDefaultPaths(schema.definitions ?? {}, schema.properties ?? {});\n const unorderedArrayPaths = collectUnorderedArrayPaths(\n schema.definitions ?? {},\n schema.properties ?? {}\n );\n const freeFormMapPaths = collectFreeFormMapPaths(\n schema.definitions ?? {},\n schema.properties ?? {}\n );\n return {\n readOnly: topLevel(readOnlyPaths),\n writeOnly: topLevel(writeOnlyPaths),\n createOnly: topLevel(createOnlyPaths),\n readOnlyPaths,\n writeOnlyPaths,\n createOnlyPaths,\n defaults,\n defaultPaths,\n unorderedScalarPaths: unorderedArrayPaths.scalar,\n unorderedObjectArrayPaths: unorderedArrayPaths.object,\n freeFormMapPaths,\n };\n}\n","// Shared read+classify pipeline used by both `check` and `record`.\n\nimport { CloudControlClient, GetResourceCommand } from '@aws-sdk/client-cloudcontrol';\nimport { CloudFormationClient } from '@aws-sdk/client-cloudformation';\nimport { buildCorpusCase, CORPUS_DIR_ENV, recordCorpusCase } from '../corpus/record.js';\nimport { type Desired, loadDesired } from '../desired/template-adapter.js';\nimport { classifyResource, normalizeLiveModel } from '../diff/classify.js';\nimport { resolveProperties } from '../normalize/intrinsic-resolver.js';\nimport { READ_RETRY } from '../read/client-config.js';\nimport {\n fetchManagedAliasTargets,\n kmsListAliasesDeniedWarning,\n usesManagedKmsAlias,\n} from '../read/kms-aliases.js';\nimport { type AddedChild, CHILD_ENUMERATORS } from '../read/child-enumerators.js';\nimport { SDK_OVERRIDES } from '../read/overrides.js';\nimport { CC_IDENTIFIER_ADAPTERS, readLive, type ReadResult } from '../read/router.js';\nimport { getSchemaInfo } from '../schema/schema-strip.js';\nimport type { DesiredResource, Finding, SchemaInfo } from '../types.js';\n\nexport interface GatherResult {\n desired: Desired;\n findings: Finding[];\n schemas: Map<string, SchemaInfo>; // resourceType -> schema (so revert can honor createOnly)\n // logicalId -> the UN-stripped live model (CC GetResource / SDK override read), kept so\n // the revert write path can see live-only data the compare-side strips — notably the\n // `aws:*` managed tags `stripAwsTagsDeep` removes, which a Tags revert must preserve on\n // the WRITE side (tagPreservingOps). Resources with no readable live model are absent.\n liveByLogical: Map<string, Record<string, unknown>>;\n}\n\n// Project the per-resource live reads into the logicalId -> live-model map carried on\n// GatherResult (only the resources that actually read back a model).\nfunction liveModelMap(reads: Map<string, ReadResult>): Map<string, Record<string, unknown>> {\n const out = new Map<string, Record<string, unknown>>();\n for (const [logicalId, read] of reads) if (read.live) out.set(logicalId, read.live);\n return out;\n}\n\n// Regions already warned about a denied kms:ListAliases — the warning is one-per-region\n// (a multi-stack run in the same region should not repeat it). Process-lifetime (matches\n// the per-region alias cache in kms-aliases.ts).\nconst kmsDeniedWarned = new Set<string>();\n\n// Bounded-concurrency live-read pool (pull-next-when-free): serial reads cost\n// ~300ms each, so 200+ resources took >1min; the SDK's adaptive retry handles\n// any throttling. Stores each read in `reads` and feeds ctx.liveAttrs so\n// Fn::GetAtt can resolve against real attributes.\nconst POOL_SIZE = 6;\nasync function readAll(\n cc: CloudControlClient,\n targets: DesiredResource[],\n region: string,\n desired: Desired,\n reads: Map<string, ReadResult>\n): Promise<void> {\n let cursor = 0;\n const worker = async (): Promise<void> => {\n while (cursor < targets.length) {\n const r = targets[cursor++]!;\n const read = await readLive(cc, r, region, desired.accountId);\n reads.set(r.logicalId, read);\n if (read.live) desired.ctx.liveAttrs[r.logicalId] = read.live;\n }\n };\n await Promise.all(Array.from({ length: Math.min(POOL_SIZE, targets.length) }, () => worker()));\n}\n\n// Turn an enumerated out-of-band child into an `added` finding. logicalId is\n// synthesized (the child is not in the template, so it has none) from the parent's\n// logical id + the CC identifier — stable and unique. physicalId carries the CC\n// identifier so revert can DeleteResource it; constructPath gives the report a\n// readable label even when the parent has no CDK construct path.\n//\n// `actual` is the child's FULL, normalized live model (PR4): `added` is now\n// record-able (the resource-level analog of recording an undeclared property), so the\n// baseline snapshots this value and a later out-of-band CHANGE to the child surfaces\n// as drift. The model is normalized identically to classify's live side\n// (normalizeLiveModel) so a volatile readOnly field never reads as a false \"changed\n// since record\". Falls back to the enumerator's identity-only snippet when the CC\n// GetResource fails (so the resource is still reported, just not change-watchable).\nfunction addedFinding(\n parent: DesiredResource,\n c: AddedChild,\n read: { model: Record<string, unknown>; ok: boolean }\n): Finding {\n return {\n tier: 'added',\n logicalId: `${parent.logicalId}/${c.identifier}`,\n physicalId: c.identifier,\n constructPath: `${parent.constructPath ?? parent.logicalId} ▸ ${c.label}`,\n resourceType: c.resourceType,\n path: '',\n actual: read.model,\n note: read.ok\n ? 'created out of band — not in your CloudFormation template'\n : 'created out of band — not in your CloudFormation template; live model unreadable this run',\n // a degraded read carries only the identity snippet — not change-watchable this run\n ...(read.ok ? {} : { modelReadFailed: true }),\n };\n}\n\n// Read the added child's FULL live model via Cloud Control GetResource (its\n// `identifier` is the CC composite, the same one revert's DeleteResource consumes) and\n// normalize it for record/compare. On any read/parse error return the enumerator's\n// identity-only `live` snippet with `ok: false` — the resource is still REPORTED as\n// added, but the finding is flagged `modelReadFailed` so record skips snapshotting the\n// partial model and applyBaseline never false-flags it as \"changed\" (a degraded snippet\n// vs a recorded full model would otherwise differ). `cfn` fetches the child type's schema\n// (readOnly/writeOnly strip); `schemas` is the shared cache.\nasync function readAddedModel(\n cc: CloudControlClient,\n cfn: CloudFormationClient,\n c: AddedChild,\n schemas: Map<string, SchemaInfo>,\n oaiCanonicalIds: Record<string, string>\n): Promise<{ model: Record<string, unknown>; ok: boolean }> {\n try {\n const g = await cc.send(\n new GetResourceCommand({ TypeName: c.resourceType, Identifier: c.identifier })\n );\n const raw = JSON.parse(g.ResourceDescription?.Properties ?? '{}') as Record<string, unknown>;\n const schema = schemas.get(c.resourceType) ?? (await getSchemaInfo(cfn, c.resourceType));\n schemas.set(c.resourceType, schema);\n return {\n model: normalizeLiveModel(raw, schema, { oaiCanonicalIds, resourceType: c.resourceType }),\n ok: true,\n };\n } catch {\n return { model: c.live, ok: false };\n }\n}\n\ninterface ClassifyOpts {\n accountId: string;\n region: string;\n kmsAliasTargets: Record<string, string>;\n oaiCanonicalIds: Record<string, string>;\n siblingSgRules: Record<string, { ingress: unknown[]; egress: unknown[] }>;\n bucketNotificationManaged: Set<string>;\n clusterEchoModel: Record<string, Record<string, unknown>>;\n}\n\n// Rules declared by standalone AWS::EC2::SecurityGroupIngress / ::SecurityGroupEgress\n// resources, keyed by the target SG's resolved GroupId (== the SG's physical id). CDK emits\n// such a resource whenever a rule references a token it cannot inline (self/peer SG ref,\n// prefix list, imported SG). The live SecurityGroup REFLECTS these rules in its own ingress/\n// egress arrays, so classify subtracts them to avoid double-counting (see SG_RULE_REFLECTION\n// in diff/classify.ts). Fail-open: a rule whose GroupId did not resolve to a concrete sg-id\n// is skipped (the SG keeps the reflected rule -> a one-time visible FP, never a hidden change).\nconst SG_RULE_RESOURCE_SIDE: Record<string, 'ingress' | 'egress'> = {\n 'AWS::EC2::SecurityGroupIngress': 'ingress',\n 'AWS::EC2::SecurityGroupEgress': 'egress',\n};\nexport function buildSiblingSgRules(\n desired: Desired\n): Record<string, { ingress: unknown[]; egress: unknown[] }> {\n const map: Record<string, { ingress: unknown[]; egress: unknown[] }> = {};\n for (const r of desired.resources) {\n const side = SG_RULE_RESOURCE_SIDE[r.resourceType];\n if (!side) continue;\n const decl = r.declared;\n if (!decl || typeof decl !== 'object') continue;\n const groupId = (decl as Record<string, unknown>).GroupId;\n if (typeof groupId !== 'string' || !groupId) continue; // unresolved intrinsic -> skip\n const rule = { ...(decl as Record<string, unknown>) };\n delete rule.GroupId;\n // A same-account SG-to-SG reference reads back a SourceSecurityGroupOwnerId AWS injects\n // (the account that owns the referenced SG) that the template never declares. Fill it in\n // with the stack's own account so (a) the classify subset-match still matches the live\n // reflected rule and (b) a revert's whole-array CC replacement re-sends the rule in its\n // EXACT live form — otherwise CC treats the owner-less rule as different and replaces it,\n // orphaning the sibling resource (observed live). A cross-account peer DECLARES the owner\n // id (CDK requires it), so it is already present and not overwritten.\n if (\n typeof rule.SourceSecurityGroupId === 'string' &&\n rule.SourceSecurityGroupOwnerId === undefined &&\n desired.accountId\n ) {\n rule.SourceSecurityGroupOwnerId = desired.accountId;\n }\n (map[groupId] ??= { ingress: [], egress: [] })[side].push(rule);\n }\n return map;\n}\n\n// Bucket physical ids (== bucket names) whose S3 notifications are managed by a\n// Custom::S3BucketNotifications custom resource. CDK renders `bucket.addEventNotification()`\n// / `enableEventBridgeNotification()` as this CR (which cdkrd cannot read/verify, so it is\n// `skipped`), NOT as the bucket's own NotificationConfiguration property — so the live\n// bucket REFLECTS the CR-applied config while its template resource declares nothing,\n// surfacing the whole NotificationConfiguration as false undeclared drift on every such\n// bucket. The config is IaC-managed (by the CR), not out of band; classify drops the\n// reflected property for these buckets (see classifyResource). Fail-open: a CR whose\n// BucketName did not resolve to a concrete name is skipped (the bucket keeps the reflected\n// config -> a one-time visible FP, never a hidden change).\nconst S3_NOTIFICATIONS_CR_TYPE = 'Custom::S3BucketNotifications';\nexport function buildBucketNotificationManaged(desired: Desired): Set<string> {\n const byLogicalId = new Map<string, string>();\n for (const r of desired.resources) if (r.physicalId) byLogicalId.set(r.logicalId, r.physicalId);\n const managed = new Set<string>();\n for (const r of desired.resources) {\n if (r.resourceType !== S3_NOTIFICATIONS_CR_TYPE) continue;\n const decl = r.declared;\n if (!decl || typeof decl !== 'object') continue;\n const bucketName = (decl as Record<string, unknown>).BucketName;\n if (typeof bucketName === 'string' && bucketName) {\n managed.add(bucketName); // already resolved to the concrete bucket name (== physical id)\n } else if (bucketName && typeof bucketName === 'object' && 'Ref' in bucketName) {\n const phys = byLogicalId.get((bucketName as { Ref: string }).Ref);\n if (phys) managed.add(phys);\n }\n }\n return managed;\n}\n\n// Per Aurora DBInstance physical id, the parent DBCluster's live model — the source for the\n// CLUSTER_ECHO_CHILD strip in classify (an instance's undeclared property that echoes its\n// cluster's cluster-level config). Resolved via the instance's declared DBClusterIdentifier\n// (a Ref that resolves to the cluster's physical id). Fail-open: an instance whose parent\n// cannot be resolved is simply not stripped (its echoes stay a one-time visible inventory,\n// never a hidden change).\nexport function buildClusterEchoModels(desired: Desired): Record<string, Record<string, unknown>> {\n const clusterByPhys: Record<string, Record<string, unknown>> = {};\n for (const r of desired.resources) {\n if (r.resourceType !== 'AWS::RDS::DBCluster' || !r.physicalId) continue;\n const live = desired.ctx.liveAttrs[r.logicalId];\n if (live && typeof live === 'object')\n clusterByPhys[r.physicalId] = live as Record<string, unknown>;\n }\n const map: Record<string, Record<string, unknown>> = {};\n for (const r of desired.resources) {\n if (r.resourceType !== 'AWS::RDS::DBInstance' || !r.physicalId) continue;\n const clusterId = (r.declared as Record<string, unknown> | undefined)?.DBClusterIdentifier;\n if (typeof clusterId !== 'string') continue;\n const clusterLive = clusterByPhys[clusterId];\n if (clusterLive) map[r.physicalId] = clusterLive;\n }\n return map;\n}\n\n// CloudFront legacy OAI id -> S3CanonicalUserId, harvested from the stack's own\n// OAI resources' live attributes (both are readOnly attrs the CC-API read already\n// returned — no extra AWS call). Lets classify reconcile the two equivalent OAI\n// principal forms in a resource policy (see rewriteOaiPrincipalsDeep). Empty when\n// the stack declares no OAI.\nconst OAI_TYPE = 'AWS::CloudFront::CloudFrontOriginAccessIdentity';\nfunction buildOaiCanonicalIds(desired: Desired): Record<string, string> {\n const map: Record<string, string> = {};\n for (const r of desired.resources) {\n if (r.resourceType !== OAI_TYPE) continue;\n const live = desired.ctx.liveAttrs[r.logicalId];\n const id = live?.Id;\n const canonical = live?.S3CanonicalUserId;\n if (typeof id === 'string' && id && typeof canonical === 'string' && canonical) {\n map[id] = canonical;\n }\n }\n return map;\n}\n\n// Turn ONE resource's read into findings: no-physical-id / deleted / skipped\n// short-circuits, else schema-strip + classify. Shared by gather's pass 2 and\n// the scoped post-revert re-check (regatherTouched).\nasync function classifyRead(\n cfn: CloudFormationClient,\n r: DesiredResource,\n read: ReadResult | undefined,\n schemas: Map<string, SchemaInfo>,\n classifyOpts: ClassifyOpts\n): Promise<Finding[]> {\n if (!r.physicalId) {\n return [\n {\n tier: 'skipped',\n logicalId: r.logicalId,\n resourceType: r.resourceType,\n path: '',\n note: 'no physical id',\n },\n ];\n }\n if (read?.deleted) {\n return [\n {\n tier: 'deleted',\n logicalId: r.logicalId,\n physicalId: r.physicalId,\n constructPath: r.constructPath,\n resourceType: r.resourceType,\n path: '',\n note: 'resource deleted out of band',\n },\n ];\n }\n if (!read || read.skippedReason || !read.live) {\n return [\n {\n tier: 'skipped',\n logicalId: r.logicalId,\n resourceType: r.resourceType,\n path: '',\n note: read?.skippedReason ?? 'not readable',\n },\n ];\n }\n const schema = schemas.get(r.resourceType) ?? (await getSchemaInfo(cfn, r.resourceType));\n schemas.set(r.resourceType, schema);\n return classifyResource(r, read.live, schema, classifyOpts);\n}\n\nexport async function gatherFindings(\n stackName: string,\n region: string,\n // --pre-deploy: use the LOCAL synth template as the declared source instead of\n // the deployed template, so check reports the declared drift the next deploy\n // would overwrite. physIds + live reads still come from the deployed stack.\n templateOverride?: Record<string, unknown>,\n // the LOCAL synth template, passed through to loadDesired to recover GetTemplate's\n // `?`-masked non-ASCII literals (mask-gated). Distinct from templateOverride: it does\n // not replace the declared source, only patches corrupted leaves.\n recoveryTemplate?: Record<string, unknown>\n): Promise<GatherResult> {\n const cfn = new CloudFormationClient({ region, ...READ_RETRY });\n const cc = new CloudControlClient({ region, ...READ_RETRY });\n\n const desired = await loadDesired(cfn, stackName, region, templateOverride, recoveryTemplate);\n const findings: Finding[] = [];\n const schemas = new Map<string, SchemaInfo>();\n\n // Pass 1: read every resource's live model first, so Fn::GetAtt in any\n // resource's declared props can be resolved against the referenced resource's\n // real attributes (populates ctx.liveAttrs) instead of falling to UNRESOLVED.\n // Pass-2 ordering stays deterministic (iterates desired.resources).\n const reads = new Map<string, ReadResult>();\n const targets = desired.resources.filter((r) => r.physicalId);\n await readAll(cc, targets, region, desired, reads);\n\n // Re-resolve EVERY resource's declared now that pass 1 populated all live\n // attributes, so Fn::GetAtt resolves. Hoisted out of pass 2 because pass 1.5\n // (below) needs the resolved declared. Mutated in place so downstream consumers\n // (revert / record) see the resolved view.\n for (const r of desired.resources) {\n if (r.declaredRaw) r.declared = resolveProperties(r.declaredRaw, desired.ctx);\n }\n\n // Pass 1.5: declared-dependent reads key off props that are frequently Fn::GetAtt\n // and so were UNRESOLVED during pass 1 (liveAttrs was still being filled) — the\n // resource is structurally readable, we just asked too early. Two shapes hit this:\n // - SDK overrides whose target prop is a GetAtt (Lambda Permission.FunctionName =\n // GetAtt[fn,Arn]) → pass 1 returned `skippedReason` (\"target not resolvable\").\n // - CC composite-id types whose PARENT key is a GetAtt (ApiGatewayV2 Route.ApiId =\n // GetAtt[Api,ApiId], ECS Service.Cluster = GetAtt[Cluster,Arn]): the composite\n // identifier couldn't be built, so CC was queried with the BARE child id — which\n // fails as `skippedReason` (ValidationException) OR, worse, `deleted`\n // (ResourceNotFound) → a FALSE \"deleted out of band\". (Ref-sourced parents\n // resolve in pass 1 via physIds, so only the GetAtt form is affected.)\n // Re-read ONCE, concurrently, both shapes when the earlier result was a skip OR a\n // deleted — now that liveAttrs is populated the parent resolves. A genuinely deleted\n // resource just reads not-found again, so re-reading the `deleted` set is safe.\n const retryTargets = desired.resources.filter((r) => {\n const prev = reads.get(r.logicalId);\n return (\n r.physicalId &&\n r.declaredRaw &&\n (SDK_OVERRIDES[r.resourceType] || CC_IDENTIFIER_ADAPTERS[r.resourceType]) &&\n (prev?.skippedReason || prev?.deleted)\n );\n });\n await readAll(cc, retryTargets, region, desired, reads);\n\n // Re-resolve once MORE when pass 1.5 actually read something: it populated liveAttrs\n // for the composite-id / SDK-override types it just read, so a CONSUMER whose declared\n // Fn::GetAtt targets one of those (e.g. a prop = GetAtt[<an ECS Service / Permission>,\n // attr]) was still UNRESOLVED after the first re-resolution above (which ran BEFORE\n // pass 1.5) — its property would be classified `unresolved` and skipped = a missed\n // drift. Monotonic and FP-safe: liveAttrs only grew, so this can only turn an\n // UNRESOLVED into a concrete value, never change an already-resolved one. Cheap:\n // retryTargets is empty for the common stack, so this loop is skipped entirely.\n if (retryTargets.length > 0) {\n for (const r of desired.resources) {\n if (r.declaredRaw) r.declared = resolveProperties(r.declaredRaw, desired.ctx);\n }\n }\n\n // OAI canonical-id map (CloudFront legacy OAI principal reconciliation) — harvested\n // from already-read liveAttrs, so it is ready before pass 1.6 normalizes added child\n // models AND reused for pass 2's classifyOpts below. Empty unless the stack declares\n // an OAI; for API Gateway children it is simply a no-op.\n const oaiCanonicalIds = buildOaiCanonicalIds(desired);\n\n // Pass 1.6: added-resource detection. For each declared PARENT type with a child\n // enumerator (read/child-enumerators.ts), list its live child resources and flag any\n // not in the template — a whole resource created out of band (e.g. an API Gateway\n // Method on `/`). The resource-granularity sibling of undeclared; not a per-property\n // compare, so it runs OUTSIDE classify. Each added child is then read in FULL (CC\n // GetResource) and normalized so `record` can snapshot it and a later change surfaces\n // as drift (PR4). An enumeration failure is a coverage gap, not drift — surfaced as a\n // `skipped` finding on the parent so it is never silently lost.\n for (const r of desired.resources) {\n const enumerate = CHILD_ENUMERATORS[r.resourceType];\n if (!enumerate || !r.physicalId) continue;\n // Only enumerate children of a parent we actually READ this run. The enumerators\n // match DECLARED children against the parent's live attributes (e.g. a Lambda\n // Function / EventBus matches its declared ESMs / Rules by the parent's `Arn`), and\n // those attrs are absent when the parent's own read failed transiently — Lambda\n // Function and Events::EventBus are in neither SDK_OVERRIDES nor\n // CC_IDENTIFIER_ADAPTERS, so pass 1.5 never retries them. With the parent unread,\n // every declared child would fail to match and false-flag as `added` — and `revert`\n // would then offer to DeleteResource a legitimately declared resource. The parent's\n // own skipped/deleted finding already carries that coverage gap, so skip enumeration.\n if (!reads.get(r.logicalId)?.live) continue;\n try {\n const children = await enumerate({ parent: r, desired, region });\n for (const c of children) {\n const read = await readAddedModel(cc, cfn, c, schemas, oaiCanonicalIds);\n findings.push(addedFinding(r, c, read));\n }\n } catch (e) {\n findings.push({\n tier: 'skipped',\n logicalId: r.logicalId,\n resourceType: r.resourceType,\n path: '',\n note: `added-resource scan: ${(e as Error).name}`,\n });\n }\n }\n\n // KMS managed-alias resolution (R9): only if the stack declares any `alias/aws/*`,\n // fetch alias -> target key id once so classify can tell a managed-default key from\n // a customer-managed key swapped in out of band. Missing kms:ListAliases -> empty +\n // denied (the classifier falls back to the conservative shape-based match) — and we\n // WARN once per region, because that fallback is BLIND to a customer-key swap (R115).\n let kmsAliasTargets: Record<string, string> = {};\n if (desired.resources.some((r) => usesManagedKmsAlias(r.declared))) {\n const resolved = await fetchManagedAliasTargets(region);\n kmsAliasTargets = resolved.targets;\n if (resolved.denied && !kmsDeniedWarned.has(region)) {\n kmsDeniedWarned.add(region);\n console.error(kmsListAliasesDeniedWarning(region));\n }\n }\n const classifyOpts = {\n accountId: desired.accountId,\n region,\n kmsAliasTargets,\n oaiCanonicalIds,\n siblingSgRules: buildSiblingSgRules(desired),\n bucketNotificationManaged: buildBucketNotificationManaged(desired),\n clusterEchoModel: buildClusterEchoModels(desired),\n };\n\n // Pass 2: classify (declared already re-resolved + override retries applied above).\n // CDKRD_CORPUS_DIR records every readable resource as a golden-corpus case\n // (the pure pipeline inputs + the findings they produced) for offline replay —\n // see src/corpus/record.ts (R63). Account ids are sanitized at record time.\n const corpusDir = process.env[CORPUS_DIR_ENV];\n for (const r of desired.resources) {\n const resourceFindings = await classifyRead(\n cfn,\n r,\n reads.get(r.logicalId),\n schemas,\n classifyOpts\n );\n findings.push(...resourceFindings);\n const live = reads.get(r.logicalId)?.live;\n const schema = schemas.get(r.resourceType);\n if (corpusDir && live && schema) {\n await recordCorpusCase(\n corpusDir,\n buildCorpusCase(r, live, schema, classifyOpts, resourceFindings)\n );\n }\n }\n return { desired, findings, schemas, liveByLogical: liveModelMap(reads) };\n}\n\n/**\n * Scoped re-gather for the post-revert convergence check (R44): re-read and\n * re-classify ONLY the `touched` resources, carrying every other resource's\n * findings forward from the original gather unchanged. The deployed template\n * cannot have changed (revert writes live state, not CloudFormation), so\n * `gathered.desired` and `gathered.schemas` stay valid — this turns a\n * whole-stack re-gather (template fetch + a live read per resource) into a\n * handful of reads, which is what made `revert` hang silently after the last\n * `reverted:` line. Out-of-band changes to UNTOUCHED resources during the\n * revert are deliberately not picked up — that is `check`'s job, and the old\n * full re-gather could even contradict the plan the user just confirmed by\n * blaming unrelated new drift on the revert.\n *\n * Returned findings are unordered across resources (untouched first, then the\n * fresh ones) — the convergence check only counts drift, it never renders them.\n * Mutates `gathered` the same way gatherFindings does (ctx.liveAttrs, resolved\n * declared, schemas cache).\n */\nexport async function regatherTouched(\n gathered: GatherResult,\n touched: Set<string>,\n region: string\n): Promise<Finding[]> {\n const cfn = new CloudFormationClient({ region, ...READ_RETRY });\n const cc = new CloudControlClient({ region, ...READ_RETRY });\n const { desired, schemas } = gathered;\n const targets = desired.resources.filter((r) => touched.has(r.logicalId));\n\n const reads = new Map<string, ReadResult>();\n await readAll(\n cc,\n targets.filter((r) => r.physicalId),\n region,\n desired,\n reads\n );\n // Re-resolve declared against the refreshed liveAttrs (mirrors gather's hoisted\n // re-resolve) — GetAtt targets among the touched resources may have moved.\n for (const r of targets) {\n if (r.declaredRaw) r.declared = resolveProperties(r.declaredRaw, desired.ctx);\n }\n // Re-check path (revert convergence): reuse the cached targets; the denial warning,\n // if any, already fired in the primary gather, so just take the resolved map.\n const kmsAliasTargets = targets.some((r) => usesManagedKmsAlias(r.declared))\n ? (await fetchManagedAliasTargets(region)).targets\n : {};\n // Built from desired.ctx.liveAttrs (populated by the original gather), so the OAI\n // map is complete even though regather only re-reads the touched resources.\n const oaiCanonicalIds = buildOaiCanonicalIds(desired);\n const classifyOpts = {\n accountId: desired.accountId,\n region,\n kmsAliasTargets,\n oaiCanonicalIds,\n siblingSgRules: buildSiblingSgRules(desired),\n bucketNotificationManaged: buildBucketNotificationManaged(desired),\n clusterEchoModel: buildClusterEchoModels(desired),\n };\n\n const fresh: Finding[] = [];\n for (const r of targets) {\n fresh.push(...(await classifyRead(cfn, r, reads.get(r.logicalId), schemas, classifyOpts)));\n }\n // Refresh the live-model map for the re-read resources (so a follow-up tag-preserving\n // revert sees the post-revert managed-tag set), mirroring the findings carry-forward.\n for (const [logicalId, read] of reads)\n if (read.live) gathered.liveByLogical.set(logicalId, read.live);\n return [...gathered.findings.filter((f) => !touched.has(f.logicalId)), ...fresh];\n}\n","// Shared gather-phase progress spinner for the four verbs (check / record / ignore /\n// revert). Each of them reads a stack's full live state + computes the diff via\n// `gatherFindings`, which runs SILENTLY and can take many seconds on a large stack —\n// long enough that a run looks frozen before the first output, and (in a multi-stack\n// run) in the gap between one stack's interactive prompt and the next stack's turn,\n// where the user has no cue anything is happening. Show a spinner while it runs so it is\n// clear cdkrd is working, not hung.\nimport { spinner } from '@clack/prompts';\n\n// TTY + text mode only: a spinner would corrupt --json's machine stdout and is noise in\n// a non-TTY / CI pipe, so callers pass `show=false` there and this is a plain\n// pass-through. Stopped on BOTH success (`stop`) and error (`error`, which renders the\n// failure symbol) so a throw still tears the animation down before the caller's catch\n// prints its message. Generic in the gather result so every verb (which unpacks the\n// result differently) can wrap its own `gatherFindings` call unchanged.\nexport async function gatherWithProgress<T>(\n show: boolean,\n label: string,\n run: () => Promise<T>\n): Promise<T> {\n if (!show) return run();\n const s = spinner();\n s.start(`${label}: reading live AWS state & computing drift…`);\n try {\n const gathered = await run();\n s.stop(`${label}: live state read`);\n return gathered;\n } catch (e) {\n s.error(`${label}: read failed`);\n throw e;\n }\n}\n\n// The `[2/3] ` position cue shared by the spinner label, the report header, and the\n// interactive resolve prompt (issue #539) so all three agree on \"which stack of how\n// many\". Empty for a lone stack (a bare `[1/1]` is noise). `idx` is the 0-based\n// position, `total` the number of stacks being processed. Pure + exported for tests.\nexport function positionPrefix(idx: number, total: number): string {\n return total > 1 ? `[${idx + 1}/${total}] ` : '';\n}\n\n// The per-stack spinner label: `[2/3] Stack (region)` in a multi-stack run, or just\n// `Stack (region)` for a lone stack. `idx` is the 0-based position, `total` the number\n// of stacks being processed.\nexport function progressLabel(\n idx: number,\n total: number,\n stackName: string,\n region: string\n): string {\n return `${positionPrefix(idx, total)}${stackName} (${region})`;\n}\n\n// The up-front \"checking N stacks\" announcement (issue #539): emitted once before the\n// per-stack loop so the user knows the total (and which stacks) at the start, not only\n// embedded inside the scrolled-away `[i/N]` spinner line. Only meaningful with >1 stack\n// — a lone stack returns null (consistent with the `[1/1]`-is-noise rule). Pure +\n// exported for tests; the caller gates on `--json` (stderr must not pollute JSON stdout).\nexport function stackCountAnnouncement(stackNames: string[]): string | null {\n if (stackNames.length <= 1) return null;\n return `note: checking ${stackNames.length} stack(s): ${stackNames.join(', ')}`;\n}\n","// Git-committed baseline file: .cdkrd/baselines/<stack>.<accountId>.<region>.json\n// Stores the RECORDED undeclared property values (the only thing with no other\n// source of truth — declared desired comes live from GetTemplate).\n//\n// Lives under the `baselines/` subdirectory (not flat in `.cdkrd/`) so the machine-\n// generated baselines stay visually separated from the hand-edited `.cdkrd/ignore.yaml`\n// policy file — the directory name labels the role, and a multi-env tree of baselines\n// stays tidy. JSON, not YAML (unlike ignore.yaml): a baseline is wholesale-rewritten\n// machine data with no comment expectation, so deterministic JSON is the right fit.\n//\n// Undeclared classification is PER ENTRY, not per file (R62): an undeclared\n// finding with a matching entry is suppressed; with an entry whose value differs\n// it is drift; with NO entry it is drift only if its resource is listed in\n// `completeResources` (the record snapshot covered that whole resource, so the\n// value APPEARED since) — otherwise the user never decided on it and it is\n// UNRECORDED, not drift. File existence alone decides nothing: a cherry-pick\n// record of one value must not flip the other hundred from unrecorded to drift.\n//\n// The accountId is in the FILENAME (not just a field) so the same stack name\n// deployed to multiple accounts (the common `env: { account: PERSONAL || SHARED }`\n// CDK pattern) gets one baseline file PER account — they never collide, and a\n// personal-account run is not blocked by the shared-account baseline. The accountId\n// is only known after a gather (DescribeStackResources), so `loadBaseline` must be\n// called after the desired model is resolved.\n\nimport { createHash } from 'node:crypto';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { deepEqual } from '../diff/drift-calculator.js';\nimport { canonicalizeForCompare } from '../normalize/pipeline.js';\nimport type { ArrayDelta, Finding } from '../types.js';\n\nexport interface RecordedEntry {\n logicalId: string;\n resourceType: string;\n path: string;\n value: unknown;\n}\n\nexport interface BaselineFile {\n schemaVersion: 1 | 2; // v1 files load fine; completeResources is absent (= nothing complete)\n stackName: string;\n region: string;\n accountId: string; // the AWS account the baseline was captured in (per-account guard)\n capturedAt: string;\n templateHash: string;\n recorded: RecordedEntry[];\n // v2 (R62): logicalIds whose undeclared snapshot was COMPLETE at record time —\n // every undeclared value the resource then had is in `recorded` (a resource with\n // zero undeclared values is trivially complete). An entry-less undeclared value\n // on a complete resource APPEARED since record = drift; on any other resource it\n // is UNRECORDED (never decided). Monotonic: once complete, a resource stays\n // complete (declining to record a new appeared value must not demote it back).\n completeResources?: string[];\n}\n\nexport function baselinePath(stackName: string, accountId: string, region: string): string {\n return `.cdkrd/baselines/${stackName}.${accountId}.${region}.json`;\n}\n\nexport function hashTemplate(rawTemplate: string): string {\n return 'sha256:' + createHash('sha256').update(rawTemplate).digest('hex');\n}\n\nexport async function loadBaseline(\n stackName: string,\n accountId: string,\n region: string\n): Promise<BaselineFile | undefined> {\n let raw: string;\n try {\n raw = await readFile(baselinePath(stackName, accountId, region), 'utf8');\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === 'ENOENT') return undefined;\n throw e;\n }\n const path = baselinePath(stackName, accountId, region);\n let parsed: BaselineFile & { accepted?: RecordedEntry[] };\n try {\n parsed = JSON.parse(raw) as BaselineFile & { accepted?: RecordedEntry[] };\n } catch {\n throw new Error(`baseline file ${path} is not valid JSON (corrupt or partially written)`);\n }\n if (parsed === null || typeof parsed !== 'object')\n throw new Error(`baseline file ${path} is malformed: root is not an object`);\n // Back-compat: baselines written before `accept` was renamed to `record` stored the\n // entries under `accepted`; the field is now `recorded`. Read the old key so a\n // committed baseline keeps loading — the next `record` rewrites it under `recorded`.\n if (parsed.recorded === undefined && parsed.accepted !== undefined)\n parsed.recorded = parsed.accepted;\n delete parsed.accepted;\n // Fail-safe validation (a baseline is a git-committed, hand-editable, cross-version\n // artifact): a newer schemaVersion must error CLEARLY rather than be silently\n // mis-applied as v2, and a missing/non-array `recorded` must error here rather than\n // crash later with an opaque TypeError inside applyBaseline (`recorded.find`).\n if (typeof parsed.schemaVersion === 'number' && parsed.schemaVersion > 2)\n throw new Error(\n `baseline file ${path} was written by a newer cdkrd (schemaVersion ${parsed.schemaVersion}); upgrade cdkrd`\n );\n if (!Array.isArray(parsed.recorded))\n throw new Error(`baseline file ${path} is malformed: \\`recorded\\` is missing or not an array`);\n return parsed;\n}\n\n/** Deterministic order for `recorded` entries: lexicographic by (logicalId, path).\n * The single point where order is imposed — read/compare logic is order-independent,\n * so this only affects the bytes on disk. Without it the entries inherit findings\n * order (= template Resources order), so a pure CDK refactor that reorders construct\n * definitions would produce a whole-file reordering diff on the next `record` even\n * though no recorded VALUE changed — breaking \"the baseline PR diff = a review of the\n * real state we record\". A non-locale comparator keeps it byte-stable across machines. */\nfunction sortRecorded(recorded: RecordedEntry[]): RecordedEntry[] {\n return [...recorded].sort(\n (a, b) =>\n (a.logicalId < b.logicalId ? -1 : a.logicalId > b.logicalId ? 1 : 0) ||\n (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)\n );\n}\n\nexport async function writeBaselineFile(b: BaselineFile): Promise<string> {\n const p = baselinePath(b.stackName, b.accountId, b.region);\n await mkdir(dirname(p), { recursive: true });\n // sort at the write point (not per entry-generation path) so every caller — record,\n // selective record, check's first-run offer — lands the same deterministic order.\n const stable: BaselineFile = {\n ...b,\n recorded: sortRecorded(b.recorded),\n ...(b.completeResources ? { completeResources: [...b.completeResources].sort() } : {}),\n };\n await writeFile(p, JSON.stringify(stable, null, 2) + '\\n', 'utf8'); // pretty + stable for clean PR diffs\n return p;\n}\n\n/**\n * Which resources the record snapshot covered COMPLETELY (R62): every undeclared\n * finding of the resource is in `recorded` (zero undeclared findings = trivially\n * complete), and the resource was actually observed — a `skipped` (unread) or\n * `deleted` resource cannot be snapshot. Ignored-tier values do not block\n * completeness: they were visible and deliberately ruled out.\n * Monotonic via `previousComplete`: once complete, a resource stays complete\n * (declining to record an appeared-since-record value keeps it drift, instead of\n * demoting it back to unrecorded) — pruned to ids still in the template.\n */\nexport function computeCompleteResources(\n allLogicalIds: string[],\n findings: Finding[],\n recorded: RecordedEntry[],\n previousComplete: string[] = []\n): string[] {\n const recordedKeys = new Set(recorded.map(recordedKey));\n const blocked = new Set<string>();\n for (const f of findings) {\n if (f.tier === 'skipped' || f.tier === 'deleted') blocked.add(f.logicalId);\n if (f.tier === 'undeclared' && !recordedKeys.has(recordedKey(f))) blocked.add(f.logicalId);\n }\n const all = new Set(allLogicalIds);\n const complete = new Set(previousComplete.filter((id) => all.has(id)));\n for (const id of allLogicalIds) if (!blocked.has(id)) complete.add(id);\n return [...complete].sort();\n}\n\n/** Write a baseline for a stack from a check run's findings + raw template.\n * Shared by `record` and `check`'s first-run interactive offer. Pass `recorded`\n * to record a pre-filtered subset (selective record); omit it to record ALL\n * undeclared findings (the default — same as `buildRecorded(findings)`).\n * `opts.allLogicalIds` (the template's full resource list) feeds the\n * completeResources computation — without it, resources with no findings at all\n * (read clean) would be invisible here; `opts.previous` keeps completeness\n * monotonic across re-records. */\nexport async function writeBaseline(\n stackName: string,\n region: string,\n accountId: string,\n findings: Finding[],\n rawTemplate: string,\n recorded: RecordedEntry[] = buildRecorded(findings),\n opts: { allLogicalIds?: string[] | undefined; previous?: BaselineFile | undefined } = {}\n): Promise<{ path: string; count: number }> {\n const allIds = opts.allLogicalIds ?? [\n ...new Set([...findings.map((f) => f.logicalId), ...recorded.map((a) => a.logicalId)]),\n ];\n const path = await writeBaselineFile({\n schemaVersion: 2,\n stackName,\n region,\n accountId,\n capturedAt: new Date().toISOString(),\n templateHash: hashTemplate(rawTemplate),\n recorded,\n completeResources: computeCompleteResources(\n allIds,\n findings,\n recorded,\n opts.previous?.completeResources ?? []\n ),\n });\n return { path, count: recorded.length };\n}\n\n/**\n * Per-account guard (secondary defense). The baseline filename now embeds the\n * accountId, so a correctly-named file always matches; this guard catches a file\n * that was hand-copied or renamed to the wrong account's path (its `accountId`\n * field would then disagree with the filename it was loaded from). On a mismatch\n * this throws (caller surfaces exit 2). A pre-release file with no accountId field\n * only warns; the next `record` stamps it.\n */\nexport function checkBaselineAccount(\n baseline: BaselineFile,\n currentAccountId: string,\n stackName: string,\n warn: (s: string) => void = console.error\n): void {\n if (!baseline.accountId) {\n warn(\n `note: ${stackName}: baseline has no accountId (older file) — it will be stamped on the next \\`cdkrd record\\`.`\n );\n return;\n }\n if (currentAccountId && baseline.accountId !== currentAccountId) {\n throw new Error(\n `baseline file for ${stackName} was captured in account ${baseline.accountId}, but the current account is ${currentAccountId} ` +\n '(the file was likely copied or renamed to the wrong account path). Baselines are per-account — ' +\n \"run `cdkrd record` to write this account's own baseline file, or restore the correct file from git.\"\n );\n }\n}\n\n/** Build the recorded set from a check run's findings: undeclared PROPERTIES plus\n * out-of-band `added` RESOURCES (PR4 — `added` is the resource-granularity sibling of\n * undeclared, so `record` snapshots its full live model and a later change to it\n * surfaces as drift). An `added` entry has the synthesized child logicalId and an\n * empty `path` (the whole resource is the value); `recordedKey` keeps it unique. */\nexport function buildRecorded(findings: Finding[]): RecordedEntry[] {\n return (\n findings\n .filter((f) => f.tier === 'undeclared' || f.tier === 'added')\n // PR4: never snapshot an `added` resource whose full model could not be read this\n // run (`modelReadFailed`) — its `actual` is only the identity snippet, and recording\n // that would false-flag \"changed since record\" on the next clean (full-model) read.\n .filter((f) => !f.modelReadFailed)\n .map((f) => ({\n logicalId: f.logicalId,\n resourceType: f.resourceType,\n path: f.path,\n value: f.actual,\n }))\n );\n}\n\n/** Stable key uniquely identifying an undeclared finding / recorded entry, for\n * selective record (the multiselect maps its picks to these keys). */\nexport function recordedKey(e: { logicalId: string; path: string }): string {\n return `${e.logicalId}::${e.path}`;\n}\n\n/**\n * Carry forward previously-recorded entries for resources that this run could NOT\n * read, so a re-`record` does not silently SHRINK the (git-committed) baseline.\n *\n * `buildRecorded` only emits entries for resources observed this run (a `skipped`\n * resource produces no undeclared finding; an `added` resource whose full model\n * failed to read is filtered by `modelReadFailed`). Because `writeBaseline` writes\n * the `recorded` array as the COMPLETE new baseline (full replace, not a merge),\n * an entry absent from this run is permanently dropped — even when the resource was\n * merely unread, not actually changed-to-default. That loses a real recorded value:\n * a later out-of-band change to that property/resource can then no longer be\n * compared against it (it re-reads as unrecorded inventory, not \"changed\").\n *\n * The READ side (`applyBaseline`) already makes this exact distinction — it refuses\n * to surface a false \"removed since record\" for `skipped`/`modelReadFailed`\n * resources (unread ≠ gone). This is its symmetric WRITE-side guard: preserve the\n * existing baseline entries for resources unread this run (`skipped`, or a\n * `modelReadFailed` `added` finding). A resource read clean whose undeclared value\n * legitimately returned to its default is NOT unread, so it is correctly dropped; a\n * `deleted` resource is genuinely gone, so it is dropped too.\n */\nexport function carryForwardUnreadable(\n recorded: RecordedEntry[],\n existing: BaselineFile | undefined,\n findings: Finding[]\n): RecordedEntry[] {\n const prior = existing?.recorded;\n if (!prior || prior.length === 0) return recorded;\n const unreadable = new Set(\n findings.filter((f) => f.tier === 'skipped' || f.modelReadFailed).map((f) => f.logicalId)\n );\n if (unreadable.size === 0) return recorded;\n const present = new Set(recorded.map(recordedKey));\n const preserved = prior.filter(\n (e) => unreadable.has(e.logicalId) && !present.has(recordedKey(e))\n );\n return preserved.length === 0 ? recorded : [...recorded, ...preserved];\n}\n\n/**\n * The single source of truth for \"is this baseline value equal to the current\n * value?\". `applyBaseline` (suppress vs surface) and `splitRecordedByBaseline`\n * (unchanged vs changed) MUST share this exact predicate. The baseline value is\n * re-canonicalized through the CURRENT pipeline so a baseline written under older\n * normalization rules still matches today's canonical live value (R6) — the\n * `currentCanonicalValue` side is expected to be already canonical.\n */\nexport function baselineValueMatches(\n baselineValue: unknown,\n currentCanonicalValue: unknown\n): boolean {\n return deepEqual(canonicalizeForCompare(baselineValue), currentCanonicalValue);\n}\n\n// Identity fields for the ELEMENT-LEVEL DELTA display only (R128) — deliberately\n// broader than classify's `IDENTITY_FIELDS` (which gate canonicalization + the R98\n// nested descent and so must stay corpus-validated). This set is consulted ONLY to\n// align a recorded-but-CHANGED undeclared array's elements for the report; the\n// finding is already drift either way, so a wider identity set here can only sharpen\n// what is shown and can NEVER create a false positive. `PolicyName` is the IAM Role\n// inline-Policies case the user hit; `Name` covers the common named-element array.\nconst DELTA_IDENTITY_FIELDS = ['Key', 'Id', 'AttributeName', 'IndexName', 'PolicyName', 'Name'];\n\nconst isPlainObjectArray = (arr: unknown[]): boolean =>\n arr.length > 0 && arr.every((x) => x !== null && typeof x === 'object' && !Array.isArray(x));\n\n// Pick the first identity field that EVERY element on BOTH sides carries as a string\n// AND that is UNIQUE within each side. Uniqueness matters: a non-unique key would\n// collapse two distinct elements into one map entry and mis-describe the delta — so\n// fall back to the whole-array display (undefined) rather than show a wrong delta.\nfunction deltaIdentityField(a: unknown[], b: unknown[]): string | undefined {\n if (!isPlainObjectArray(a) || !isPlainObjectArray(b)) return undefined;\n return DELTA_IDENTITY_FIELDS.find((f) => {\n const idsOf = (arr: unknown[]): string[] =>\n arr\n .map((x) => (x as Record<string, unknown>)[f])\n .filter((v): v is string => typeof v === 'string');\n const ia = idsOf(a);\n const ib = idsOf(b);\n return (\n ia.length === a.length &&\n ib.length === b.length &&\n new Set(ia).size === ia.length &&\n new Set(ib).size === ib.length\n );\n });\n}\n\n/**\n * Element-level delta of a recorded-but-CHANGED undeclared identity-keyed object\n * array (R128) — e.g. an IAM Role's inline Policies keyed by `PolicyName`. Computed\n * for the REPORT only: the finding stays at the whole-array path, so `record` still\n * snapshots the whole array (the property never un-records) and revert is unaffected;\n * this just says WHICH element(s) differ so the report shows the delta instead of\n * dumping the full array. Aligns by a unique identity field present on both sides,\n * then deep-compares matched pairs (so a same-name-but-changed-document element IS\n * still surfaced as `changed`, never missed). Returns undefined when the two sides\n * are not both unique-identity-keyed object arrays, or when nothing actually differs\n * after alignment (e.g. a pure reorder) — the caller then falls back to whole-array\n * display.\n */\nexport function identityArrayDelta(recordedVal: unknown, liveVal: unknown): ArrayDelta | undefined {\n if (!Array.isArray(recordedVal) || !Array.isArray(liveVal)) return undefined;\n const idf = deltaIdentityField(recordedVal, liveVal);\n if (!idf) return undefined;\n const byId = (arr: unknown[]): Map<string, unknown> =>\n new Map(arr.map((x) => [String((x as Record<string, unknown>)[idf]), x]));\n const rec = byId(recordedVal);\n const live = byId(liveVal);\n const added: ArrayDelta['added'] = [];\n const changed: ArrayDelta['changed'] = [];\n const removed: ArrayDelta['removed'] = [];\n for (const [id, v] of live) {\n if (!rec.has(id)) added.push({ id, value: v });\n else if (!deepEqual(rec.get(id), v)) changed.push({ id, recorded: rec.get(id), actual: v });\n }\n for (const [id, v] of rec) if (!live.has(id)) removed.push({ id, value: v });\n if (added.length === 0 && changed.length === 0 && removed.length === 0) return undefined;\n return { identityField: idf, added, removed, changed };\n}\n\n/**\n * Split a freshly-built recorded set against the existing baseline into the values\n * a human must decide on (`changed` = new path OR value differs) and the values\n * already recorded and unchanged (`unchanged` = same logicalId+path AND value\n * matches by `baselineValueMatches`). With no baseline EVERYTHING is `changed`\n * (the true first record). Entries are matched against `entry.value` which comes\n * from `buildRecorded` (already canonical), so the predicate compares\n * canonical-vs-canonical, exactly like `applyBaseline`.\n */\nexport function splitRecordedByBaseline(\n recorded: RecordedEntry[],\n baseline: BaselineFile | undefined\n): { unchanged: RecordedEntry[]; changed: RecordedEntry[] } {\n if (!baseline) return { unchanged: [], changed: [...recorded] };\n const unchanged: RecordedEntry[] = [];\n const changed: RecordedEntry[] = [];\n for (const entry of recorded) {\n const baselineEntry = baseline.recorded.find(\n (a) => a.logicalId === entry.logicalId && a.path === entry.path\n );\n if (baselineEntry && baselineValueMatches(baselineEntry.value, entry.value))\n unchanged.push(entry);\n else changed.push(entry);\n }\n return { unchanged, changed };\n}\n\n/** Selective record: build the recorded set from only the findings whose key is in\n * `selectedKeys`. Empty set -> []; all keys -> equals buildRecorded(findings). */\nexport function selectRecorded(findings: Finding[], selectedKeys: Set<string>): RecordedEntry[] {\n return buildRecorded(findings).filter((e) => selectedKeys.has(recordedKey(e)));\n}\n\nexport interface ApplyBaselineOptions {\n // logicalId -> set of currently-declared top-level keys. An recorded entry whose\n // path is now DECLARED in the template is the recommended \"promote undeclared\n // drift into code\" workflow, NOT a removal — suppress the false removal finding.\n declaredByLogical?: Map<string, Set<string>>;\n // logicalId -> CDK construct path. Used to restore constructPath onto the synthetic\n // \"baseline value removed since record\" finding so a constructPath-form ignore rule\n // matches it (a RecordedEntry carries no constructPath of its own).\n constructPathByLogical?: Map<string, string>;\n // logicalId -> live physical id. Used to restore physicalId onto the synthetic\n // \"baseline value removed since record\" finding. A RecordedEntry stores no physical\n // id, and unlike a LIVE finding (which classifyResource stamps with\n // resource.physicalId) this one is synthesized here — so without this it reaches\n // `revert` with NO physical id and buildRevertPlan rejects it (\"no physical id\"),\n // making a recorded value removed out of band UN-revertable (a real revert FN: the\n // value the user chose to keep disappeared, yet `revert` refuses to restore it).\n physicalIdByLogical?: Map<string, string>;\n warn?: (s: string) => void; // stderr note channel for the promotion case\n}\n\nconst topSegment = (p: string): string => p.split('.')[0] ?? p;\n\n/**\n * Reconcile undeclared findings against the recorded baseline (per ENTRY, R62):\n * - an undeclared finding matching an recorded entry (same value) is suppressed;\n * - an entry whose value changed survives as drift (the recorded contract was\n * violated);\n * - a finding with NO entry is drift only when its resource is snapshot-complete\n * (`completeResources`) — the value APPEARED since record; on any other\n * resource the user never decided on it, so it is tagged `unrecorded` (an\n * inventory item, not drift — excluded from the verdict/exit downstream);\n * - with NO baseline at all, every undeclared finding is unrecorded;\n * - an recorded entry with NO corresponding current undeclared value is reported as\n * a removal (drift in the other direction — something recorded disappeared),\n * UNLESS that path has since been DECLARED in the template (promotion to code —\n * the workflow we recommend — which is noted, not flagged as drift).\n * Non-undeclared findings pass through untouched.\n */\nexport function applyBaseline(\n findings: Finding[],\n baseline: BaselineFile | undefined,\n opts: ApplyBaselineOptions = {}\n): Finding[] {\n // PR4 (option B): an out-of-band `added` resource is the resource-level sibling of an\n // undeclared property — with NO recorded intent (CFn template OR baseline) about it,\n // there is no contract to violate, so an UNRECORDED added resource is inventory, not\n // drift, exactly like an undeclared property with no entry. With no baseline at all,\n // every undeclared value AND every added resource is unrecorded.\n if (!baseline)\n return findings.map((f) =>\n f.tier === 'undeclared' || f.tier === 'added' ? { ...f, unrecorded: true } : f\n );\n const recorded = baseline.recorded;\n const complete = new Set(baseline.completeResources ?? []); // v1 file: nothing complete\n const kept: Finding[] = [];\n for (const f of findings) {\n // PR4: reconcile `added` against the baseline as a full mirror of undeclared — but on\n // the WHOLE resource (path ''), not a property. A matching entry whose value is equal\n // is suppressed; a recorded value that CHANGED stays `added` drift with a \"changed\n // since record\" note + the baseline value on `desired` (so the report shows it); a\n // resource with NO entry is unrecorded inventory (not drift). The completeResources /\n // \"appeared since record\" mechanism is undeclared-only (it is keyed per template\n // resource, and an added child has a synthesized id that never enters allLogicalIds),\n // so a newly-appeared added resource is simply unrecorded until the user records it.\n if (f.tier === 'added') {\n const entry = recorded.find((a) => a.logicalId === f.logicalId && a.path === f.path);\n // PR4: the full model could not be read this run — `actual` is only the identity\n // snippet, so we CANNOT decide changed-vs-unchanged. Never false-flag \"changed\": a\n // recorded resource is suppressed (it was verified before; re-checked next clean\n // run, like a transiently-skipped resource), an un-recorded one stays Not-Recorded.\n if (f.modelReadFailed) {\n if (entry) continue;\n kept.push({ ...f, unrecorded: true });\n continue;\n }\n if (entry && baselineValueMatches(entry.value, f.actual)) continue; // recorded, unchanged\n if (entry) {\n kept.push({\n ...f,\n desired: canonicalizeForCompare(entry.value),\n note: f.note ? `${f.note}; changed since record` : 'changed since record',\n });\n continue;\n }\n kept.push({ ...f, unrecorded: true }); // never decided -> not drift\n continue;\n }\n // atDefault AND generated are reconciled alongside undeclared (R86): a value the\n // user already recorded is suppressed whichever undeclared-side tier it lands in\n // today, so a baseline entry whose live value is now classified at-default OR\n // generated does NOT read as \"removed\" — and a recorded value CHANGED to one of\n // those forms still surfaces as drift (handled below), not folded away. (The three\n // tiers here mirror the `currentPaths` filter at the bottom of this function.)\n if (f.tier !== 'undeclared' && f.tier !== 'atDefault' && f.tier !== 'generated') {\n kept.push(f);\n continue;\n }\n const entry = recorded.find((a) => a.logicalId === f.logicalId && a.path === f.path);\n // re-canonicalize the baseline value through the CURRENT pipeline before comparing\n // (f.actual is already canonical from classify): a baseline recorded under older\n // normalization rules still matches today's live, so a cdkrd version bump alone\n // never resurfaces a suppressed value as false drift.\n if (entry && baselineValueMatches(entry.value, f.actual)) continue; // recorded, unchanged\n if (entry) {\n // recorded value CHANGED -> drift. This takes PRIORITY over the at-default fold\n // below: a recorded NON-default value reset out of band to the AWS default is a\n // real out-of-band change (e.g. an undeclared MaxSessionDuration recorded at 7200,\n // reset to the 3600 default), so it must surface as drift, not be folded away as\n // inventory. classify tagged today's at-default value `atDefault`, which is NOT a\n // drift tier — force `undeclared` so the changed-from-baseline value is counted as\n // drift. For an identity-keyed object array (IAM inline Policies, …) attach the\n // element-level delta so the report shows WHICH element changed (R128, display-only;\n // the finding still names the whole-array path, so record/revert are unaffected).\n const delta = identityArrayDelta(canonicalizeForCompare(entry.value), f.actual);\n kept.push({ ...f, tier: 'undeclared', ...(delta && { arrayDelta: delta }) });\n continue;\n }\n if (f.tier === 'atDefault' || f.tier === 'generated') {\n // No recorded entry and the value equals a known AWS default / an AWS-generated\n // form (the equality gate proved it): folded inventory — never drift, never\n // unrecorded. A genuine change AWAY from it would not match and arrives as tier\n // 'undeclared', handled below; a recorded value changed TO it is the entry branch\n // above (drift).\n kept.push(f);\n continue;\n }\n if (complete.has(f.logicalId)) {\n // the record snapshot covered this whole resource, so this value is new\n kept.push({\n ...f,\n note: f.note ? `${f.note}; appeared since record` : 'appeared since record',\n });\n } else {\n kept.push({ ...f, unrecorded: true }); // never decided -> not drift\n }\n }\n // removed: recorded entries whose path is no longer present in any current\n // undeclared / at-default / generated finding (R86: a recorded value reclassified to\n // any of those undeclared-side tiers is still PRESENT — reconciled above as either\n // suppressed-unchanged or drift — not \"removed\"). Must match the reconciliation tier\n // set at the top of the loop, else a recorded value changed to a generated/at-default\n // form would be both surfaced as drift AND double-reported here as removed.\n const currentPaths = new Set(\n findings\n .filter((f) => f.tier === 'undeclared' || f.tier === 'atDefault' || f.tier === 'generated')\n .map((f) => `${f.logicalId}.${f.path}`)\n );\n // R134: baseline entries promoted into the template since record are a \"clean up your\n // baseline\" nudge, NOT drift — but emitting one note PER entry floods the output (a\n // config-dense stack can have dozens, e.g. every Lambda's LoggingConfig.* once CDK\n // starts declaring them). Collect them and emit ONE folded summary line (the `info:`\n // footer pattern), so a `revert` touching a single op no longer prints 20+ unrelated\n // lines. The fix is the same for every caller: re-run `record` to re-snapshot.\n // A resource that was SKIPPED this run (CC-API gap / transient read error / no\n // physical id — gather emits a `skipped` finding) was NOT observed, so its baseline\n // values are unknown, NOT removed. Excluding it prevents a transient skip from\n // flooding the report with false \"baseline value removed since record\" drift (its\n // values still exist; we just couldn't read them this run).\n //\n // A resource DELETED out of band already surfaces as a single resource-level\n // `deleted` finding (gather.ts), which SUBSUMES every recorded baseline value it\n // had — the whole resource is gone, so of course each of its values is too. Emitting\n // an extra per-property \"baseline value removed\" undeclared finding for each is\n // redundant noise that also inflates the drift COUNT (one deletion would read as\n // 1 + N drifts) and, for `revert`, yields un-actionable ops against a resource that\n // no longer exists. Suppress them too; the `deleted` finding carries the drift. (Gated\n // on an actual `deleted` finding, so a removal NOT already reported still surfaces.)\n const skippedLogical = new Set(\n findings.filter((f) => f.tier === 'skipped').map((f) => f.logicalId)\n );\n const deletedLogical = new Set(\n findings.filter((f) => f.tier === 'deleted').map((f) => f.logicalId)\n );\n // A recorded nested undeclared value whose DECLARED parent property is itself\n // drifting this run is subsumed by that `declared` finding: the parent array/object\n // changed (e.g. CloudFront `DistributionConfig.Origins` -> []), so the nested value's\n // disappearance is the SAME real change, not a separate \"baseline value removed\".\n // Emitting both double-counts the drift and yields an un-actionable revert op against\n // a nested path that no longer exists — the exact class already suppressed for\n // `deleted`/`skipped`. Suppress when a current `declared` finding's path is a prefix\n // of the recorded path (so a sibling NOT under the drifting parent still surfaces).\n const declaredDriftByLogical = new Map<string, string[]>();\n for (const f of findings) {\n if (f.tier !== 'declared') continue;\n const arr = declaredDriftByLogical.get(f.logicalId) ?? [];\n arr.push(f.path);\n declaredDriftByLogical.set(f.logicalId, arr);\n }\n const underDeclaredDrift = (logicalId: string, path: string): boolean =>\n (declaredDriftByLogical.get(logicalId) ?? []).some(\n (p) => path === p || path.startsWith(`${p}.`) || path.startsWith(`${p}[`)\n );\n const promotedStale: string[] = [];\n for (const a of recorded) {\n // PR4: an `added`-resource entry has an empty path (the whole resource is the value)\n // and is reconciled in the loop above, never here. If its live resource is gone the\n // out-of-band addition was simply removed — nothing to \"restore\", so skip it (a\n // property-removal note against a synthesized child id would be meaningless).\n if (a.path === '') continue;\n if (currentPaths.has(`${a.logicalId}.${a.path}`)) continue;\n if (skippedLogical.has(a.logicalId)) continue; // unread this run -> not \"removed\"\n if (deletedLogical.has(a.logicalId)) continue; // subsumed by the `deleted` finding\n if (underDeclaredDrift(a.logicalId, a.path)) continue; // subsumed by parent declared drift\n // promoted into the template since record → not a removal, just stale baseline\n if (opts.declaredByLogical?.get(a.logicalId)?.has(topSegment(a.path))) {\n promotedStale.push(`${a.logicalId}.${a.path}`);\n continue;\n }\n kept.push({\n tier: 'undeclared',\n logicalId: a.logicalId,\n resourceType: a.resourceType,\n // Restore the construct path that every LIVE finding for this resource carries\n // (a RecordedEntry doesn't store it). Without it, a constructPath-form ignore\n // rule — the form `cdkrd ignore` writes by preference — would NOT match this\n // synthetic \"removed since record\" finding (applyIgnores keys on constructPath\n // when present), so the removal would re-surface despite the ignore.\n ...(opts.constructPathByLogical?.get(a.logicalId) !== undefined && {\n constructPath: opts.constructPathByLogical.get(a.logicalId),\n }),\n // physical id so `revert` can act on it (a synthesized finding has no\n // resource.physicalId source — without this it is rejected as \"no physical id\").\n ...(opts.physicalIdByLogical?.get(a.logicalId) !== undefined && {\n physicalId: opts.physicalIdByLogical.get(a.logicalId),\n }),\n path: a.path,\n desired: a.value,\n actual: undefined,\n note: 'baseline value removed since record',\n });\n }\n if (promotedStale.length > 0) opts.warn?.(formatPromotedStaleNote(promotedStale));\n return kept;\n}\n\n/**\n * The folded one-line note for baseline entries now declared in the template (R134). One\n * line with a count instead of one line per entry; `record` re-snapshots to clear them.\n * Pure + exported for unit tests.\n */\nexport function formatPromotedStaleNote(paths: string[]): string {\n const n = paths.length;\n const subject = n === 1 ? `baseline entry (${paths[0]}) is` : `${n} baseline entries are`;\n const them = n === 1 ? 'it' : 'them';\n return `note: ${subject} now declared in the template — re-run \\`cdkrd record\\` to clean ${them} up.`;\n}\n\n/** logicalId -> set of declared top-level keys, for applyBaseline's promotion check. */\nexport function declaredKeysByLogical(\n resources: { logicalId: string; declared: Record<string, unknown> }[]\n): Map<string, Set<string>> {\n return new Map(resources.map((r) => [r.logicalId, new Set(Object.keys(r.declared))]));\n}\n\n// logicalId -> construct path, for resources that carry one. Feeds\n// ApplyBaselineOptions.constructPathByLogical so the synthetic removed-since-record\n// finding can be matched by a constructPath-form ignore rule.\nexport function constructPathsByLogical(\n resources: { logicalId: string; constructPath?: string | undefined }[]\n): Map<string, string> {\n const m = new Map<string, string>();\n for (const r of resources) if (r.constructPath !== undefined) m.set(r.logicalId, r.constructPath);\n return m;\n}\n\n// logicalId -> live physical id, for resources that resolved one. Feeds\n// ApplyBaselineOptions.physicalIdByLogical so the synthetic removed-since-record\n// finding carries a physical id and `revert` can restore the removed value.\nexport function physicalIdsByLogical(\n resources: { logicalId: string; physicalId?: string | undefined }[]\n): Map<string, string> {\n const m = new Map<string, string>();\n for (const r of resources) if (r.physicalId !== undefined) m.set(r.logicalId, r.physicalId);\n return m;\n}\n\n/**\n * Warn (never error) when the baseline predates snapshot tracking (schema v1, no\n * `completeResources`): nothing is snapshot-complete, so values that appeared\n * since record read as UNRECORDED instead of drift until the next `record`\n * upgrades the file (R62).\n */\nexport function warnBaselineSchemaV1(\n baseline: BaselineFile,\n stackName: string,\n warn: (s: string) => void = console.error\n): void {\n if (baseline.completeResources === undefined) {\n warn(\n `note: ${stackName}: baseline predates snapshot tracking — new out-of-band values read as unrecorded, not drift; re-run \\`cdkrd record\\` to upgrade it.`\n );\n }\n}\n\n/**\n * Warn (never error) when the baseline was captured against a different template\n * version than the one now deployed — the recorded set may be stale. Skipped in\n * --pre-deploy mode (the synth template legitimately differs from the deployed one).\n */\nexport function warnTemplateHashDrift(\n baseline: BaselineFile,\n rawTemplate: string,\n stackName: string,\n warn: (s: string) => void = console.error\n): void {\n if (!baseline.templateHash) return;\n if (baseline.templateHash !== hashTemplate(rawTemplate)) {\n warn(\n `note: ${stackName}: baseline was captured against a different template version — consider re-running \\`cdkrd record\\`.`\n );\n }\n}\n","// Semantic color helpers for human-facing output (R43). Call sites say WHAT a\n// thing is (a drift verdict, an info footer), not what color it is.\n//\n// Colors are enabled ONLY when stdout is a real terminal and NO_COLOR is unset:\n// piped / CI / --json output stays byte-identical plain text, so the\n// CI-greppable invariant (`grep '^result:'`) and the `--json` contract are\n// untouched. FORCE_COLOR is deliberately ignored — test runners set it for\n// their own reporters, and honoring it would make committed-test output\n// environment-dependent.\nimport pc from 'picocolors';\n\nexport interface Style {\n header: (s: string) => string; // === check/revert: ... === banners\n resultLabel: (s: string) => string; // the `result:` prefix — the conclusion anchor\n driftTier: (s: string) => string; // deleted / declared section titles\n undeclaredTier: (s: string) => string; // the differentiator tier title\n // Secondary UI chrome you're NOT meant to read closely: picker key-hints, the skip\n // chip, aborted/retry status lines. Dim (SGR 2) is correct HERE — it recedes.\n infoTier: (s: string) => string;\n // Explanatory prose you ARE meant to read: tier notes, origin hints (↳), the info:\n // footer. Terminal DEFAULT foreground — legible on any theme (dim was unreadable on\n // dark terminals and wrongly wore the \"don't read me\" style of the picker chrome).\n note: (s: string) => string;\n clean: (s: string) => string; // result: CLEAN / CLEAN after revert. / no drift\n drift: (s: string) => string; // result: N drift(s) / N drift(s) remain.\n desired: (s: string) => string; // desired= value (what it should be)\n actual: (s: string) => string; // actual = value (what it really is)\n ok: (s: string) => string; // reverted: / baseline written:\n fail: (s: string) => string; // FAILED:\n cursor: (s: string) => string; // the focused row in an interactive multiselect\n}\n\n/** Build the palette on top of a picocolors instance (identity when disabled). */\nexport function makeStyle(c: ReturnType<typeof pc.createColors>): Style {\n return {\n header: c.bold,\n resultLabel: c.bold,\n driftTier: (s) => c.bold(c.red(s)),\n undeclaredTier: (s) => c.bold(c.yellow(s)),\n infoTier: c.dim,\n // Terminal default foreground (identity) — no dim, no fixed color, so it stays\n // legible whatever the terminal theme. Structure (parentheses, `↳`, the `info:`\n // prefix, indentation) carries the \"this is secondary\" cue instead of color.\n note: (s) => s,\n clean: (s) => c.bold(c.green(s)),\n drift: (s) => c.bold(c.red(s)),\n desired: c.green,\n actual: c.red,\n ok: c.green,\n fail: (s) => c.bold(c.red(s)),\n cursor: c.cyan,\n };\n}\n\nexport const colorEnabled = process.stdout.isTTY === true && process.env['NO_COLOR'] === undefined;\n\nexport const style: Style = makeStyle(pc.createColors(colorEnabled));\n","// Interactive multi-select with BULK keys, shared by record + revert (R116).\n//\n// The high-level `@clack/prompts` multiselect only exposes `a` (toggle all) / `i`\n// (invert) for bulk selection, hidden behind a dim hint and easy to miss. Mirroring\n// `cdk-local`'s target picker, this builds on `@clack/core`'s low-level\n// `MultiSelectPrompt` so it can bind the keys users reach for first:\n// space = toggle the cursor row · → = select all · ← = clear all · enter = confirm\n// `MultiSelectPrompt` ALSO maps Left/Right onto the cursor (as Up/Down) and that fires\n// before our handler, so after a bulk change we pin the cursor to the top for a stable\n// position. Selection lives in `this.value`, so the handlers set it directly — the same\n// mechanism the built-in `toggleAll` uses.\nimport { MultiSelectPrompt } from '@clack/core';\nimport {\n isCancel,\n S_BAR,\n S_BAR_END,\n S_BAR_START,\n S_CHECKBOX_INACTIVE,\n S_CHECKBOX_SELECTED,\n} from '@clack/prompts';\nimport { style } from '../report/style.js';\n\nexport interface BulkOption {\n value: string;\n label: string;\n selected: boolean; // initial selection state (RESTORE pre-selected, REMOVE not, etc.)\n}\n\n/** The selected-value array after a bulk action — `all` selects every option, `none`\n * clears it. Pure (no prompt state) so the →/← wiring is unit-testable without a TTY. */\nexport function bulkSelectValues(options: { value: string }[], action: 'all' | 'none'): string[] {\n return action === 'all' ? options.map((o) => o.value) : [];\n}\n\n/** The key-hint line shown under the message (readable — style.note, not dim: it is\n * meant to be read). Pure + exported for unit tests.\n * `esc = cancel` is listed last (R130): Esc aborts the prompt — in check's interactive\n * flow that returns to the action menu, in a standalone `record`/`ignore` it cancels\n * the command; either way the selection is discarded, so `cancel` is accurate in both. */\nexport function bulkSelectHint(): string {\n return 'space = toggle · → = all · ← = none · enter = confirm · esc = cancel';\n}\n\ntype Opt = { value: string; label: string };\n\n/**\n * One rendered row. The cursor row MUST be visually distinct or up/down navigation\n * looks dead (R116 regression: `S_CHECKBOX_ACTIVE` and `S_CHECKBOX_INACTIVE` are the\n * SAME glyph in clack — only colour told them apart — and a selected row always showed\n * the filled box regardless of focus, so the cursor was invisible). A leading `❯`\n * pointer marks the focused row even with NO_COLOR; with colour it is also cyan. Pure +\n * exported so the \"focused row differs from the rest\" invariant is unit-tested. R118.\n */\nexport function formatRow(label: string, state: { active: boolean; selected: boolean }): string {\n const pointer = state.active ? '❯' : ' ';\n const box = state.selected ? S_CHECKBOX_SELECTED : S_CHECKBOX_INACTIVE;\n const cell = `${pointer} ${box} ${label}`;\n if (state.active) return style.cursor(cell);\n return state.selected ? `${pointer} ${style.ok(box)} ${style.ok(label)}` : cell;\n}\n\n/**\n * Show the multi-select and return the picked values, or `undefined` on cancel\n * (Ctrl+C / Esc). `message` is the prompt header; the hint line is appended for you.\n */\nexport async function bulkMultiselect(\n message: string,\n options: BulkOption[]\n): Promise<string[] | undefined> {\n const prompt = new MultiSelectPrompt<Opt>({\n options: options.map((o) => ({ value: o.value, label: o.label })),\n initialValues: options.filter((o) => o.selected).map((o) => o.value),\n required: false,\n render() {\n if (this.state === 'submit' || this.state === 'cancel') {\n return `${S_BAR_START} ${message}\\n${S_BAR} ${(this.value ?? []).length} selected`;\n }\n const header = `${S_BAR_START} ${message}\\n${S_BAR} ${style.note(bulkSelectHint())}`;\n const selected = new Set(this.value ?? []);\n const rows = this.options.map(\n (opt, i) =>\n `${S_BAR} ${formatRow(opt.label, { active: i === this.cursor, selected: selected.has(opt.value) })}`\n );\n return `${header}\\n${rows.join('\\n')}\\n${S_BAR_END}`;\n },\n });\n prompt.on('key', (_char, info) => {\n if (info?.name !== 'right' && info?.name !== 'left') return;\n prompt.value = bulkSelectValues(options, info.name === 'right' ? 'all' : 'none');\n prompt.cursor = 0;\n });\n const picked = await prompt.prompt();\n if (isCancel(picked)) return undefined;\n return (picked as string[] | undefined) ?? [];\n}\n","// Apply RFC6902-ish add/remove ops (as produced by the revert plan) onto a copy\n// of a resource model, by JSON pointer. Used by the SDK writers to reconstruct\n// the DESIRED full property value before a whole-property SDK write (e.g. set the\n// full bucket policy), so sub-path drifts revert correctly too.\nimport type { PatchOp } from './plan.js';\n\nfunction unescape(seg: string): string {\n return seg.replace(/~1/g, '/').replace(/~0/g, '~');\n}\n\nexport function applyOps(\n model: Record<string, unknown>,\n ops: readonly PatchOp[]\n): Record<string, unknown> {\n const out = structuredClone(model);\n for (const op of ops) {\n const segs = op.path.split('/').slice(1).map(unescape);\n if (op.op === 'add') setAt(out, segs, op.value);\n else removeAt(out, segs);\n }\n return out;\n}\n\nfunction setAt(root: unknown, segs: string[], value: unknown): void {\n let node = root as Record<string, unknown>;\n for (let i = 0; i < segs.length - 1; i++) {\n const k = segs[i]!;\n if (node[k] === null || typeof node[k] !== 'object') node[k] = {};\n node = node[k] as Record<string, unknown>;\n }\n node[segs[segs.length - 1]!] = value;\n}\n\nfunction removeAt(root: unknown, segs: string[]): void {\n let node = root as Record<string, unknown>;\n for (let i = 0; i < segs.length - 1; i++) {\n const k = segs[i]!;\n if (node[k] === null || typeof node[k] !== 'object') return;\n node = node[k] as Record<string, unknown>;\n }\n delete node[segs[segs.length - 1]!];\n}\n","// Type-specific SDK writers for revert of Cloud-Control-unwritable types. Each\n// reads the current model (reusing the override READER), applies the revert ops to\n// reconstruct the DESIRED full value, then writes it back with the resource's own\n// SDK. Covers the policy-document types (the common revert) plus IAM ManagedPolicy\n// (revert the default version's document).\n//\n// Still not-revertable by design (no SDK writer here):\n// - AWS::Lambda::Permission: an ADD/REMOVE statement model keyed by StatementId\n// (AddPermission/RemovePermission), NOT a settable whole-document property. A\n// generic ops-based revert would have to diff the resource policy statements\n// and add/remove each individually; the override READER only returns a thin\n// best-effort match (FunctionName/Action/Principal, no StatementId / SourceArn\n// / SourceAccount / EventSourceToken), so we cannot reconstruct the exact\n// statement to re-add nor safely identify the one to remove. Reverting it\n// blindly risks dropping or duplicating unrelated grants -> left not-revertable.\n// - AWS::Budgets::Budget: UpdateBudget requires a FULL NewBudget object\n// (BudgetLimit/PlannedBudgetLimits + BudgetName + TimeUnit + BudgetType, and it\n// overwrites CostFilters / CostTypes / notifications wholesale). The override\n// READER returns only the scalar identity subset (BudgetName / BudgetType /\n// TimeUnit) — no BudgetLimit / CostFilters / CostTypes — so a desiredModel\n// reconstruction would be missing the required limit and would wipe the cost\n// filters/types on write. Too divergent from the reader to revert safely ->\n// left not-revertable.\nimport {\n APIGatewayClient,\n type PatchOperation,\n UpdateIntegrationCommand,\n UpdateIntegrationResponseCommand,\n UpdateMethodResponseCommand,\n} from '@aws-sdk/client-api-gateway';\nimport { CloudWatchClient, PutAnomalyDetectorCommand } from '@aws-sdk/client-cloudwatch';\nimport {\n DLMClient,\n GetLifecyclePolicyCommand,\n type SettablePolicyStateValues,\n UpdateLifecyclePolicyCommand,\n} from '@aws-sdk/client-dlm';\nimport {\n CloudControlClient,\n GetResourceCommand,\n UpdateResourceCommand,\n} from '@aws-sdk/client-cloudcontrol';\nimport {\n CloudFrontClient,\n GetDistributionConfigCommand,\n UpdateDistributionCommand,\n} from '@aws-sdk/client-cloudfront';\nimport {\n CloudWatchLogsClient,\n PutBearerTokenAuthenticationCommand,\n PutMetricFilterCommand,\n} from '@aws-sdk/client-cloudwatch-logs';\nimport {\n DocDBClient,\n ModifyDBClusterCommand,\n ModifyDBInstanceCommand,\n} from '@aws-sdk/client-docdb';\nimport {\n DescribeDomainConfigCommand,\n OpenSearchClient,\n UpdateDomainConfigCommand,\n} from '@aws-sdk/client-opensearch';\nimport {\n GetJobCommand,\n GlueClient,\n UpdateClassifierCommand,\n UpdateConnectionCommand,\n UpdateJobCommand,\n UpdateTableCommand,\n UpdateWorkflowCommand,\n} from '@aws-sdk/client-glue';\nimport {\n GetWebACLCommand,\n type Scope,\n UpdateWebACLCommand,\n WAFV2Client,\n} from '@aws-sdk/client-wafv2';\nimport { type ReceiptRule, SESClient, UpdateReceiptRuleCommand } from '@aws-sdk/client-ses';\nimport {\n ElasticLoadBalancingV2Client,\n ModifyLoadBalancerAttributesCommand,\n ModifyTargetGroupAttributesCommand,\n} from '@aws-sdk/client-elastic-load-balancing-v2';\nimport {\n AttachGroupPolicyCommand,\n AttachRolePolicyCommand,\n AttachUserPolicyCommand,\n CreatePolicyVersionCommand,\n DetachGroupPolicyCommand,\n DetachRolePolicyCommand,\n DetachUserPolicyCommand,\n DeletePolicyVersionCommand,\n DeleteRolePolicyCommand,\n IAMClient,\n ListPolicyVersionsCommand,\n PutGroupPolicyCommand,\n PutRolePolicyCommand,\n PutUserPolicyCommand,\n} from '@aws-sdk/client-iam';\nimport {\n ConfigServiceClient,\n DescribeConfigRulesCommand,\n PutConfigRuleCommand,\n} from '@aws-sdk/client-config-service';\nimport { KafkaClient, UpdateConfigurationCommand } from '@aws-sdk/client-kafka';\nimport {\n CodeBuildClient,\n type ReportExportConfig,\n type Tag as CodeBuildTag,\n UpdateReportGroupCommand,\n} from '@aws-sdk/client-codebuild';\nimport {\n DAXClient,\n UpdateClusterCommand,\n UpdateParameterGroupCommand as UpdateDaxParameterGroupCommand,\n} from '@aws-sdk/client-dax';\nimport { EC2Client, ModifyClientVpnEndpointCommand } from '@aws-sdk/client-ec2';\nimport {\n DescribeEventBusCommand,\n EventBridgeClient,\n PutPermissionCommand,\n} from '@aws-sdk/client-eventbridge';\nimport {\n CognitoSyncClient,\n GetCognitoEventsCommand,\n SetCognitoEventsCommand,\n} from '@aws-sdk/client-cognito-sync';\nimport {\n ECSClient,\n type ServiceConnectConfiguration,\n type ServiceVolumeConfiguration,\n UpdateServiceCommand,\n} from '@aws-sdk/client-ecs';\nimport {\n BuildBotLocaleCommand,\n CreateIntentCommand,\n type CreateIntentCommandInput,\n CreateSlotCommand,\n type CreateSlotCommandInput,\n CreateSlotTypeCommand,\n type CreateSlotTypeCommandInput,\n DeleteIntentCommand,\n DeleteSlotCommand,\n DeleteSlotTypeCommand,\n DescribeBotLocaleCommand,\n DescribeIntentCommand,\n DescribeSlotCommand,\n DescribeSlotTypeCommand,\n LexModelsV2Client,\n ListIntentsCommand,\n ListSlotsCommand,\n ListSlotTypesCommand,\n type SlotValueElicitationSetting,\n UpdateBotLocaleCommand,\n type UpdateBotLocaleCommandInput,\n UpdateIntentCommand,\n UpdateSlotCommand,\n UpdateSlotTypeCommand,\n type UpdateSlotTypeCommandInput,\n type VoiceSettings,\n} from '@aws-sdk/client-lex-models-v2';\nimport { ChangeResourceRecordSetsCommand, Route53Client } from '@aws-sdk/client-route-53';\nimport { DeleteBucketPolicyCommand, PutBucketPolicyCommand, S3Client } from '@aws-sdk/client-s3';\nimport {\n ServiceDiscoveryClient,\n UpdateHttpNamespaceCommand,\n} from '@aws-sdk/client-servicediscovery';\nimport { SetTopicAttributesCommand, SNSClient } from '@aws-sdk/client-sns';\nimport { SetQueueAttributesCommand, SQSClient } from '@aws-sdk/client-sqs';\nimport { NESTED_ARRAY_IDENTITY } from '../diff/classify.js';\nimport { identityField } from '../normalize/noise.js';\nimport { canonicalizeForCompare } from '../normalize/pipeline.js';\nimport {\n DLM_DEFAULT_POLICY_SHORTHAND,\n type OverrideCtx,\n SDK_OVERRIDES,\n} from '../read/overrides.js';\nimport { applyOps } from './apply-ops.js';\nimport type { PatchOp } from './plan.js';\n\nexport type SdkWriter = (ctx: OverrideCtx, ops: PatchOp[]) => Promise<void>;\n\nconst str = (v: unknown): string | undefined =>\n typeof v === 'string' && v.length > 0 ? v : undefined;\n// Every non-empty string in v (an array of targets, or a single scalar). A policy\n// resource can attach to MORE THAN ONE target (an AWS::IAM::Policy on several Roles,\n// an SNS TopicPolicy spanning several Topics) — revert must write to ALL of them, or\n// the drift silently persists on every target after the first while the run reports\n// \"reverted\".\nconst strList = (v: unknown): string[] =>\n (Array.isArray(v) ? v : [v]).map(str).filter((s): s is string => s !== undefined);\n\n// reconstruct the desired full model = current (read back) with revert ops applied\nasync function desiredModel(\n type: string,\n ctx: OverrideCtx,\n ops: PatchOp[]\n): Promise<Record<string, unknown>> {\n const reader = SDK_OVERRIDES[type];\n const current = (reader && (await reader(ctx))) ?? {};\n // A revert op path indexes the model classify COMPARED — which is canonicalized\n // (canonicalizePolicy SORTS the Statement array, reshapes Action/Resource, …). But the\n // override reader returns the RAW live document, whose statement order can differ. An\n // op like `…/Statement/1/Resource` would then land on a DIFFERENT statement than the\n // one classify found drifted — corrupting an unrelated statement and leaving the real\n // drift unreverted (a security-relevant wrong write). Canonicalize the current\n // PolicyDocument the same way so an indexed op hits the SAME statement; the written\n // doc is the canonical (statement-sorted, AWS-equivalent) form of the declared intent.\n const aligned =\n current.PolicyDocument === undefined\n ? current\n : { ...current, PolicyDocument: canonicalizeForCompare(current.PolicyDocument) };\n return applyOps(aligned, ops);\n}\nconst policyJson = (m: Record<string, unknown>): string | undefined =>\n m.PolicyDocument === undefined ? undefined : JSON.stringify(m.PolicyDocument);\n\nconst writeS3BucketPolicy: SdkWriter = async (ctx, ops) => {\n const bucket = str(ctx.declared['Bucket']);\n if (!bucket) throw new Error('cannot resolve bucket for revert');\n const desired = policyJson(await desiredModel('AWS::S3::BucketPolicy', ctx, ops));\n const c = new S3Client({ region: ctx.region });\n if (desired === undefined) await c.send(new DeleteBucketPolicyCommand({ Bucket: bucket }));\n else await c.send(new PutBucketPolicyCommand({ Bucket: bucket, Policy: desired }));\n};\n\nconst writeSnsTopicPolicy: SdkWriter = async (ctx, ops) => {\n const topics = strList(ctx.declared['Topics']);\n if (topics.length === 0) throw new Error('cannot resolve topic for revert');\n const desired = policyJson(await desiredModel('AWS::SNS::TopicPolicy', ctx, ops)) ?? '';\n const c = new SNSClient({ region: ctx.region });\n // A TopicPolicy can attach to several Topics — set the policy on every one.\n for (const topic of topics) {\n await c.send(\n new SetTopicAttributesCommand({\n TopicArn: topic,\n AttributeName: 'Policy',\n AttributeValue: desired,\n })\n );\n }\n};\n\nconst writeSqsQueuePolicy: SdkWriter = async (ctx, ops) => {\n const queues = strList(ctx.declared['Queues']);\n if (queues.length === 0) throw new Error('cannot resolve queue for revert');\n const desired = policyJson(await desiredModel('AWS::SQS::QueuePolicy', ctx, ops)) ?? '';\n const c = new SQSClient({ region: ctx.region });\n // A QueuePolicy can attach to several Queues — set the policy on every one.\n for (const queue of queues) {\n await c.send(\n new SetQueueAttributesCommand({ QueueUrl: queue, Attributes: { Policy: desired } })\n );\n }\n};\n\n// AWS::Events::EventBusPolicy is a resource-policy STATEMENT on an event bus — the\n// same class as SNS TopicPolicy / SQS QueuePolicy / S3 BucketPolicy, all of which\n// revert via their native SDK because a Cloud Control RFC6902 patch is wrong for a\n// policy here: the live `Statement` comes back as a SINGULAR object while classify\n// canonicalizes it to a one-element array, so an indexed op (`/Statement/0/Action`)\n// targets a path the raw model lacks (`noSuchPath`) and the CC revert FAILS. We write\n// the desired statement directly via PutPermission, MERGING by StatementId into the\n// bus's current aggregate policy so a sibling statement (another EventBusPolicy\n// resource, or one added out of band) is preserved rather than wiped.\nconst writeEventBusPolicy: SdkWriter = async (ctx) => {\n const eventBusName = str(ctx.declared['EventBusName']) ?? 'default';\n const statementId = str(ctx.declared['StatementId']);\n if (!statementId) throw new Error('cannot resolve StatementId for EventBusPolicy revert');\n const c = new EventBridgeClient({ region: ctx.region });\n\n // Desired statement = the declared (template) intent. Modern templates declare a full\n // `Statement` object; the legacy CfnEventBusPolicy form declares Action+Principal.\n const declaredStmt = ctx.declared['Statement'];\n let desiredStatement: Record<string, unknown>;\n if (declaredStmt && typeof declaredStmt === 'object' && !Array.isArray(declaredStmt)) {\n desiredStatement = { Sid: statementId, ...(declaredStmt as Record<string, unknown>) };\n } else {\n const action = ctx.declared['Action'];\n const principal = str(ctx.declared['Principal']);\n if (action === undefined || principal === undefined)\n throw new Error('EventBusPolicy revert needs a Statement (or Action + Principal)');\n desiredStatement = {\n Sid: statementId,\n Effect: 'Allow',\n Principal: principal === '*' ? '*' : { AWS: `arn:aws:iam::${principal}:root` },\n Action: action,\n Resource: `arn:aws:events:${ctx.region}:${ctx.accountId}:event-bus/${eventBusName}`,\n ...(ctx.declared['Condition'] !== undefined ? { Condition: ctx.declared['Condition'] } : {}),\n };\n }\n\n const bus = await c.send(new DescribeEventBusCommand({ Name: eventBusName }));\n const policy =\n bus.Policy && bus.Policy.length > 0\n ? (JSON.parse(bus.Policy) as { Version?: string; Statement?: unknown })\n : { Version: '2012-10-17', Statement: [] as unknown };\n const statements: Record<string, unknown>[] = Array.isArray(policy.Statement)\n ? (policy.Statement as Record<string, unknown>[])\n : policy.Statement\n ? [policy.Statement as Record<string, unknown>]\n : [];\n const idx = statements.findIndex((s) => s?.['Sid'] === statementId);\n if (idx >= 0) statements[idx] = desiredStatement;\n else statements.push(desiredStatement);\n await c.send(\n new PutPermissionCommand({\n EventBusName: eventBusName,\n Policy: JSON.stringify({ Version: policy.Version ?? '2012-10-17', Statement: statements }),\n })\n );\n};\n\nconst writeIamPolicy: SdkWriter = async (ctx, ops) => {\n const name = str(ctx.declared['PolicyName']);\n if (!name) throw new Error('cannot resolve policy name for revert');\n const desired = policyJson(await desiredModel('AWS::IAM::Policy', ctx, ops));\n if (desired === undefined) throw new Error('cannot revert an IAM inline policy to absent');\n const c = new IAMClient({ region: ctx.region });\n // An AWS::IAM::Policy can attach to ANY combination of Roles, Users and Groups, and\n // to several of each — the same inline policy is put on every one. Reverting only the\n // first target (the old behavior) left the drift in place on every other attachment\n // while reporting success.\n const roles = strList(ctx.declared['Roles']);\n const users = strList(ctx.declared['Users']);\n const groups = strList(ctx.declared['Groups']);\n if (roles.length + users.length + groups.length === 0)\n throw new Error('IAM policy has no role/user/group target');\n for (const role of roles)\n await c.send(\n new PutRolePolicyCommand({ RoleName: role, PolicyName: name, PolicyDocument: desired })\n );\n for (const user of users)\n await c.send(\n new PutUserPolicyCommand({ UserName: user, PolicyName: name, PolicyDocument: desired })\n );\n for (const group of groups)\n await c.send(\n new PutGroupPolicyCommand({ GroupName: group, PolicyName: name, PolicyDocument: desired })\n );\n};\n\n// IAM managed policies are versioned: a \"settable\" PolicyDocument lives in the\n// default version, and a policy can hold at most 5 versions. To revert we create a\n// NEW version (SetAsDefault) carrying the desired document; if 5 already exist we\n// first delete the oldest NON-default version to make room.\nconst isArn = (v: unknown): string | undefined => {\n const s = str(v);\n return s && s.startsWith('arn:') ? s : undefined;\n};\n// Top JSON-pointer segment of an op path (`/Roles/0` -> `Roles`, `/Roles` -> `Roles`).\nconst topSeg = (path: string): string => path.split('/').filter(Boolean)[0] ?? '';\nconst ATTACHMENT_PROPS = new Set(['Roles', 'Users', 'Groups']);\n// Resolve an op into a ManagedPolicy attachment (prop + member) from EITHER encoding the\n// revert plan emits: a declared DETACH revert (re-attach) arrives as path `Roles` with\n// the member on `attributeKey`; an unexpected-attach removal (--remove-unrecorded) of a\n// live-only member arrives as the nested path `Roles[member]`. Returns undefined for a\n// document op (PolicyDocument/Path/Description), which routes to the version path below.\nconst parseAttachmentOp = (o: PatchOp): { prop: string; member: string } | undefined => {\n const seg = topSeg(o.path);\n if (ATTACHMENT_PROPS.has(seg)) {\n const member = o.attributeKey ?? (typeof o.value === 'string' ? o.value : undefined);\n return member !== undefined ? { prop: seg, member: String(member) } : undefined;\n }\n const m = /^(Roles|Users|Groups)\\[(.+)\\]$/.exec(seg);\n return m ? { prop: m[1] as string, member: m[2] as string } : undefined;\n};\n\nconst writeIamManagedPolicy: SdkWriter = async (ctx, ops) => {\n // CFn physical id for a managed policy IS its arn; fall back to the declared\n // ManagedPolicyArn when the physical id isn't (yet) the arn shape.\n const arn = isArn(ctx.physicalId) ?? isArn(ctx.declared['ManagedPolicyArn']);\n if (!arn) throw new Error('cannot resolve managed policy arn for revert');\n const c = new IAMClient({ region: ctx.region });\n\n // Attachment-list reverts (Roles/Users/Groups), per member — never by rewriting the\n // whole list (that would touch the union members another stack/role/console\n // legitimately added):\n // - an `add` op re-ATTACHES a declared member detached out of band (AttachXPolicy);\n // - a `remove` op DETACHES a live-only (unexpected) member the user chose to remove\n // via --remove-unrecorded (DetachXPolicy).\n // AttachXPolicy on an already-attached member is a no-op, so a partial prior revert\n // re-runs safely.\n for (const o of ops) {\n const parsed = parseAttachmentOp(o);\n if (!parsed) continue;\n const { prop, member } = parsed;\n const detach = o.op === 'remove';\n if (prop === 'Roles')\n await c.send(\n detach\n ? new DetachRolePolicyCommand({ PolicyArn: arn, RoleName: member })\n : new AttachRolePolicyCommand({ PolicyArn: arn, RoleName: member })\n );\n else if (prop === 'Users')\n await c.send(\n detach\n ? new DetachUserPolicyCommand({ PolicyArn: arn, UserName: member })\n : new AttachUserPolicyCommand({ PolicyArn: arn, UserName: member })\n );\n else if (prop === 'Groups')\n await c.send(\n detach\n ? new DetachGroupPolicyCommand({ PolicyArn: arn, GroupName: member })\n : new AttachGroupPolicyCommand({ PolicyArn: arn, GroupName: member })\n );\n }\n\n // Document/Path/Description reverts go through a new default policy version. Skip it\n // entirely when only attachment ops were present, so a detach-only revert does not\n // burn a (capped at 5) policy version re-writing the unchanged document.\n const docOps = ops.filter((o) => parseAttachmentOp(o) === undefined);\n if (docOps.length === 0) return;\n const desired = policyJson(await desiredModel('AWS::IAM::ManagedPolicy', ctx, docOps));\n if (desired === undefined)\n throw new Error('cannot revert a managed policy to an absent document');\n\n const versions = (await c.send(new ListPolicyVersionsCommand({ PolicyArn: arn }))).Versions ?? [];\n if (versions.length >= 5) {\n const oldest = versions\n .filter((v) => !v.IsDefaultVersion && v.VersionId)\n .sort((a, b) => (a.CreateDate?.getTime() ?? 0) - (b.CreateDate?.getTime() ?? 0))[0];\n if (oldest?.VersionId)\n await c.send(new DeletePolicyVersionCommand({ PolicyArn: arn, VersionId: oldest.VersionId }));\n }\n await c.send(\n new CreatePolicyVersionCommand({ PolicyArn: arn, PolicyDocument: desired, SetAsDefault: true })\n );\n};\n\n// Inline Policies on an IAM Role, reverted PER ENTRY (PutRolePolicy /\n// DeleteRolePolicy by PolicyName) instead of a whole-property Cloud Control patch:\n// a CC `remove /Policies` would also wipe the sibling-AWS::IAM::Policy entries\n// (the CDK DefaultPolicy) that classify filtered OUT of the finding. Each op\n// carries the finding's current live subset in `prior` (set by plan.ts); the\n// desired subset is `value` for an add (baseline restore), empty for a remove.\n// Entries in prior but not desired are deleted; every desired entry is (re)put.\ninterface InlinePolicy {\n PolicyName: string;\n PolicyDocument: unknown;\n}\nconst asInlinePolicies = (v: unknown): InlinePolicy[] =>\n Array.isArray(v)\n ? v.filter(\n (p): p is InlinePolicy =>\n !!p && typeof p === 'object' && typeof (p as InlinePolicy).PolicyName === 'string'\n )\n : [];\n\nconst writeIamRoleInlinePolicies: SdkWriter = async (ctx, ops) => {\n const role = str(ctx.physicalId); // an AWS::IAM::Role physical id IS the role name\n if (!role) throw new Error('cannot resolve role name for revert');\n const c = new IAMClient({ region: ctx.region });\n for (const op of ops) {\n if (op.path !== '/Policies')\n throw new Error(`unsupported inline-policy revert path: ${op.path}`);\n const desired = op.op === 'add' ? asInlinePolicies(op.value) : [];\n const keep = new Set(desired.map((p) => p.PolicyName));\n for (const p of asInlinePolicies(op.prior)) {\n if (!keep.has(p.PolicyName))\n await c.send(new DeleteRolePolicyCommand({ RoleName: role, PolicyName: p.PolicyName }));\n }\n for (const p of desired) {\n await c.send(\n new PutRolePolicyCommand({\n RoleName: role,\n PolicyName: p.PolicyName,\n PolicyDocument: JSON.stringify(p.PolicyDocument),\n })\n );\n }\n }\n};\n\n// ELB attribute bags (LoadBalancerAttributes / TargetGroupAttributes), reverted\n// PER ATTRIBUTE via Modify*AttributesCommand instead of a whole-property Cloud\n// Control patch (R78): the CC index patch misaligns against the full live bag\n// (~23 entries) and ELB rejects a modify carrying >20 attributes. Each op carries\n// the changed attribute's Key (op.attributeKey) and the desired Value (op.value),\n// so we send ONLY the declared attributes — a partial, merge-style update that\n// leaves every other live attribute untouched. The ELB physical id IS the ARN.\nconst elbAttributeOps = (ops: PatchOp[]): { Key: string; Value: string }[] =>\n ops\n .filter((o) => o.attributeKey !== undefined)\n .map((o) => ({ Key: o.attributeKey as string, Value: String(o.value) }));\n\nconst writeElbLoadBalancerAttributes: SdkWriter = async (ctx, ops) => {\n const arn = str(ctx.physicalId);\n if (!arn) throw new Error('cannot resolve load balancer arn for revert');\n const attrs = elbAttributeOps(ops);\n if (attrs.length === 0) return;\n await new ElasticLoadBalancingV2Client({ region: ctx.region }).send(\n new ModifyLoadBalancerAttributesCommand({ LoadBalancerArn: arn, Attributes: attrs })\n );\n};\n\nconst writeElbTargetGroupAttributes: SdkWriter = async (ctx, ops) => {\n const arn = str(ctx.physicalId);\n if (!arn) throw new Error('cannot resolve target group arn for revert');\n const attrs = elbAttributeOps(ops);\n if (attrs.length === 0) return;\n await new ElasticLoadBalancingV2Client({ region: ctx.region }).send(\n new ModifyTargetGroupAttributesCommand({ TargetGroupArn: arn, Attributes: attrs })\n );\n};\n\n// AWS::ServiceDiscovery::HttpNamespace — Cloud Control cannot read OR write this\n// type (UnsupportedActionException), so revert goes through Cloud Map's own\n// UpdateHttpNamespace, whose ONLY mutable field is Description (Name is immutable).\n// Reconstruct the desired model (current read + revert ops) and write its Description\n// back. (Sibling AWS::ServiceDiscovery::Service is intentionally NOT revertable: a\n// service in an HTTP/API-only namespace cannot be updated at all — UpdateService\n// throws InvalidInput \"Service in API-only namespace cannot be updated\" — so there is\n// nothing to revert; a DNS-namespace service writer can be added if a real gap surfaces.)\nconst writeServiceDiscoveryHttpNamespace: SdkWriter = async (ctx, ops) => {\n const id = str(ctx.physicalId);\n if (!id) throw new Error('cannot resolve namespace id for revert');\n const m = await desiredModel('AWS::ServiceDiscovery::HttpNamespace', ctx, ops);\n await new ServiceDiscoveryClient({ region: ctx.region }).send(\n new UpdateHttpNamespaceCommand({\n Id: id,\n Namespace: { Description: (str(m.Description) ?? '') as string },\n })\n );\n};\n\n// AWS::DocDB::DBCluster — Cloud Control cannot read OR write this type\n// (UnsupportedActionException), so revert goes through DocDB's own ModifyDBCluster.\n// ModifyDBCluster is a PARTIAL update (only the supplied fields change), so we send\n// ONLY the drifted top-level props that are in the safe-to-modify allowlist below —\n// re-asserting unchanged props would be a no-op but is avoided to keep the call\n// minimal. ApplyImmediately so the revert converges on the next read. EngineVersion is\n// intentionally NOT in the allowlist (a version write can trigger an upgrade); a\n// declared EngineVersion drift stays not-revertable rather than risk a major upgrade.\n// (The sibling AWS::DocDB::DBInstance has its own ModifyDBInstance writer below.)\nconst DOCDB_CLUSTER_MODIFY_PARAMS = new Set([\n 'BackupRetentionPeriod',\n 'PreferredBackupWindow',\n 'PreferredMaintenanceWindow',\n 'Port',\n 'DeletionProtection',\n]);\nconst writeDocDbCluster: SdkWriter = async (ctx, ops) => {\n const id = str(ctx.physicalId) ?? str(ctx.declared['DBClusterIdentifier']);\n if (!id) throw new Error('cannot resolve DB cluster identifier for revert');\n const desired = await desiredModel('AWS::DocDB::DBCluster', ctx, ops);\n const input: { DBClusterIdentifier: string; ApplyImmediately: boolean; [k: string]: unknown } = {\n DBClusterIdentifier: id,\n ApplyImmediately: true,\n };\n let any = false;\n for (const op of ops) {\n const top = op.path.replace(/^\\//, '').split('/')[0];\n if (top && DOCDB_CLUSTER_MODIFY_PARAMS.has(top) && desired[top] !== undefined) {\n input[top] = desired[top];\n any = true;\n }\n }\n if (!any) return;\n await new DocDBClient({ region: ctx.region }).send(new ModifyDBClusterCommand(input));\n};\n\n// AWS::DocDB::DBInstance — Cloud Control cannot read OR write the DocDB family, so it is\n// read via DescribeDBInstances and had no writer (the sibling cluster had one). Revert\n// goes through DocDB's own ModifyDBInstance (a PARTIAL update, like ModifyDBCluster), so\n// send ONLY the drifted top-level props in the safe-to-modify allowlist. ApplyImmediately\n// so the revert converges on the next read. The mirror of the cluster writer.\n// EXCLUDED: DBClusterIdentifier (create-only) and AutoMinorVersionUpgrade — the latter is\n// a CLUSTER-level setting on DocumentDB (ModifyDBInstance rejects it: \"AutoMinorVersionUpgrade\n// is a cluster setting for DocumentDB clusters. Use ModifyDBCluster\"), so even though the\n// reader echoes the cluster's value on the instance read, it is not instance-modifiable —\n// a change surfaces/reverts at the cluster, not here.\nconst DOCDB_INSTANCE_MODIFY_PARAMS = new Set([\n 'DBInstanceClass',\n 'PreferredMaintenanceWindow',\n 'CACertificateIdentifier',\n 'EnablePerformanceInsights',\n]);\nconst writeDocDbInstance: SdkWriter = async (ctx, ops) => {\n const id = str(ctx.physicalId) ?? str(ctx.declared['DBInstanceIdentifier']);\n if (!id) throw new Error('cannot resolve DB instance identifier for revert');\n const desired = await desiredModel('AWS::DocDB::DBInstance', ctx, ops);\n const input: { DBInstanceIdentifier: string; ApplyImmediately: boolean; [k: string]: unknown } = {\n DBInstanceIdentifier: id,\n ApplyImmediately: true,\n };\n let any = false;\n for (const op of ops) {\n const top = op.path.replace(/^\\//, '').split('/')[0];\n if (top && DOCDB_INSTANCE_MODIFY_PARAMS.has(top) && desired[top] !== undefined) {\n input[top] = desired[top];\n any = true;\n }\n }\n if (!any) return;\n await new DocDBClient({ region: ctx.region }).send(new ModifyDBInstanceCommand(input));\n};\n\n// AWS::CloudFront::Distribution — Cloud Control CAN read this type, but its\n// UpdateResource REJECTS even a minimal single-property patch: applying the patch\n// re-validates the WHOLE distribution and the default ViewerCertificate\n// representation trips \"IamCertificateId or AcmCertificateArn can be specified only\n// if SslSupportMethod must also be specified and vice-versa\" (proven live — EVERY\n// CloudFront revert failed). Route revert through CloudFront's own GetDistributionConfig\n// -> apply ops -> UpdateDistribution(IfMatch=ETag) instead: a full-config round-trip\n// re-submits AWS's own ViewerCertificate verbatim, so it validates. The revert ops are\n// CFn-pointer paths (`/DistributionConfig/<prop>`); applying a SCALAR op to the freshly\n// read SDK config touches only that property, so the CFn-vs-SDK array-shape difference\n// (Origins as `[...]` vs `{Quantity,Items}`) is irrelevant for the common scalar drifts\n// (Comment / DefaultRootObject / Enabled / PriceClass / HttpVersion / WebACLId / …).\nconst writeCloudFrontDistribution: SdkWriter = async (ctx, ops) => {\n const id = str(ctx.physicalId);\n if (!id) throw new Error('cannot resolve distribution id for revert');\n const c = new CloudFrontClient({ region: ctx.region });\n const cur = await c.send(new GetDistributionConfigCommand({ Id: id }));\n if (!cur.DistributionConfig || !cur.ETag)\n throw new Error('could not read current distribution config for revert');\n const reverted = applyOps({ DistributionConfig: cur.DistributionConfig }, ops) as {\n DistributionConfig: Record<string, unknown>;\n };\n await c.send(\n new UpdateDistributionCommand({\n Id: id,\n IfMatch: cur.ETag,\n // the SDK DistributionConfig shape is preserved verbatim except for the scalar\n // properties the revert ops set, so it round-trips validly.\n DistributionConfig: reverted.DistributionConfig as never,\n })\n );\n};\n\n// AWS::WAFv2::WebACL — Cloud Control CAN read this type, but its UpdateResource\n// REJECTS a property patch: applying the patch re-validates the WHOLE WebACL against\n// the CFn schema, and AWS's own live `Description: \"\"` (empty when none was set) fails\n// the schema's Description pattern constraint — \"#/Description: failed validation\n// constraint for keyword [pattern]\" (proven live; the same CC re-validation class as\n// CloudFront). Route revert through WAFv2's own GetWebACL -> apply ops -> UpdateWebACL\n// (Name|Id|Scope physical id + LockToken). update-web-acl accepts the absence of\n// Description, so OMIT an empty/invalid one; every other updatable field is re-sent\n// verbatim so nothing is dropped.\nconst WAF_UPDATABLE_PASSTHROUGH = [\n 'Rules',\n 'CustomResponseBodies',\n 'CaptchaConfig',\n 'ChallengeConfig',\n 'TokenDomains',\n 'AssociationConfig',\n 'DataProtectionConfig',\n 'OnSourceDDoSProtectionConfig',\n 'ApplicationConfig',\n 'MonetizationConfig',\n] as const;\nconst writeWafv2WebAcl: SdkWriter = async (ctx, ops) => {\n const [name, id, scope] = (str(ctx.physicalId) ?? '').split('|');\n if (!name || !id || !scope) throw new Error('cannot resolve WebACL Name|Id|Scope for revert');\n const c = new WAFV2Client({ region: ctx.region });\n const cur = await c.send(new GetWebACLCommand({ Name: name, Id: id, Scope: scope as Scope }));\n if (!cur.WebACL || !cur.LockToken) throw new Error('could not read current WebACL for revert');\n // A revert op path indexes the model classify COMPARED, which is canonicalized: every\n // WebACL Rule carries a `Name`, so canonicalizeForCompare SORTS the `Rules` array by it\n // (the same identity-keyed sort that aligns Tags/Origins). But GetWebACL returns Rules in\n // their RAW configured order, which a user who declared rules out of Name order returns in\n // a DIFFERENT order than the sorted finding index. An op like `…/Rules/1/…` would then\n // land on a DIFFERENT rule than the one classify found drifted — patching an unrelated\n // (security-relevant) rule and leaving the real drift unreverted (the #180 / #275 index-\n // misalignment class, here on the SDK-writer path). Canonicalize the current model the\n // same way so an indexed op hits the SAME rule; Rule order is not significant to WAFv2\n // (Priority governs evaluation), so re-sending the sorted array changes no behavior.\n const m = applyOps(\n canonicalizeForCompare(cur.WebACL as unknown as Record<string, unknown>) as Record<\n string,\n unknown\n >,\n ops\n );\n const desc = m.Description;\n await c.send(\n new UpdateWebACLCommand({\n Name: name,\n Id: id,\n Scope: scope as Scope,\n LockToken: cur.LockToken,\n DefaultAction: m.DefaultAction as never,\n VisibilityConfig: m.VisibilityConfig as never,\n // OMIT an empty Description — AWS returns \"\" but the schema pattern rejects it.\n ...(typeof desc === 'string' && desc.length > 0 ? { Description: desc } : {}),\n ...Object.fromEntries(\n WAF_UPDATABLE_PASSTHROUGH.filter((k) => m[k] !== undefined).map((k) => [k, m[k]])\n ),\n } as never)\n );\n};\n\n// AWS::Glue::Job — Cloud Control CAN read this type, but its UpdateResource REJECTS a\n// property patch when the job uses WorkerType + NumberOfWorkers: AWS ALSO returns a\n// computed `MaxCapacity` (and the deprecated `AllocatedCapacity`) on read, and\n// re-submitting BOTH MaxCapacity and WorkerType fails \"Please do not set Max Capacity\n// if using Worker Type and Number of Workers\" (proven live; the same CC-revalidation\n// class as CloudFront/WAFv2). Route revert through Glue's own GetJob -> apply ops ->\n// UpdateJob, OMITTING MaxCapacity/AllocatedCapacity when WorkerType is set (update-job\n// accepts their absence). Read-only fields (CreatedOn / LastModifiedOn / Name) are not\n// part of JobUpdate and are dropped by the explicit field copy.\nconst GLUE_JOB_UPDATE_FIELDS = [\n 'JobMode',\n 'JobRunQueuingEnabled',\n 'Description',\n 'LogUri',\n 'Role',\n 'ExecutionProperty',\n 'Command',\n 'DefaultArguments',\n 'NonOverridableArguments',\n 'Connections',\n 'MaxRetries',\n 'Timeout',\n 'WorkerType',\n 'NumberOfWorkers',\n 'SecurityConfiguration',\n 'NotificationProperty',\n 'GlueVersion',\n 'CodeGenConfigurationNodes',\n 'ExecutionClass',\n 'SourceControlDetails',\n 'MaintenanceWindow',\n] as const;\nconst writeGlueJob: SdkWriter = async (ctx, ops) => {\n const name = str(ctx.physicalId) ?? str(ctx.declared['Name']);\n if (!name) throw new Error('cannot resolve Glue job name for revert');\n const c = new GlueClient({ region: ctx.region });\n const got = await c.send(new GetJobCommand({ JobName: name }));\n if (!got.Job) throw new Error('could not read current Glue job for revert');\n const m = applyOps(got.Job as unknown as Record<string, unknown>, ops);\n const update: Record<string, unknown> = {};\n for (const k of GLUE_JOB_UPDATE_FIELDS) if (m[k] !== undefined) update[k] = m[k];\n // MaxCapacity / AllocatedCapacity are mutually exclusive with WorkerType — include\n // them ONLY for a non-WorkerType job (else update-job rejects sending both).\n if (m.WorkerType === undefined) {\n if (m.MaxCapacity !== undefined) update.MaxCapacity = m.MaxCapacity;\n if (m.AllocatedCapacity !== undefined) update.AllocatedCapacity = m.AllocatedCapacity;\n }\n await c.send(new UpdateJobCommand({ JobName: name, JobUpdate: update as never }));\n};\n\n// AWS::Glue::Table — Cloud Control GetResource throws UnsupportedActionException for the\n// whole Glue family, so it is read via the Glue GetTable override and was not revertable.\n// Glue UpdateTable is a WHOLE-TableInput overwrite, and the override reader already\n// returns the full CFn-modeled TableInput (Name/Description/Owner/Retention/TableType/\n// Parameters/PartitionKeys/StorageDescriptor/…), so reconstruct the desired TableInput\n// (current + revert ops) and write it back. Mirrors the sibling writeGlueJob (GetJob →\n// UpdateJob). The reverted TableInput is complete, so the overwrite is safe.\nconst writeGlueTable: SdkWriter = async (ctx, ops) => {\n const m = await desiredModel('AWS::Glue::Table', ctx, ops);\n const dbName = str(m.DatabaseName) ?? str(ctx.declared['DatabaseName']);\n const tableInput = m.TableInput as Record<string, unknown> | undefined;\n if (!dbName || !tableInput || !str(tableInput.Name))\n throw new Error('cannot resolve Glue table target for revert');\n const catalogId = str(m.CatalogId) ?? str(ctx.declared['CatalogId']);\n await new GlueClient({ region: ctx.region }).send(\n new UpdateTableCommand({\n DatabaseName: dbName,\n TableInput: tableInput as never,\n ...(catalogId && { CatalogId: catalogId }),\n })\n );\n};\n\n// AWS::Glue::Classifier — read via the GetClassifier override (CC UnsupportedActionException),\n// so it was not revertable. Glue UpdateClassifier is a WHOLE one-of overwrite ({CsvClassifier\n// | GrokClassifier | JsonClassifier | XMLClassifier}); the override reader returns the full\n// CFn-modeled member, so reconstruct the desired member (current + revert ops) and write it\n// back. Mirrors writeGlueTable (GetTable → UpdateTable). Covers the common drifts — an\n// out-of-band Delimiter / GrokPattern / JsonPath edit.\nconst writeGlueClassifier: SdkWriter = async (ctx, ops) => {\n const m = await desiredModel('AWS::Glue::Classifier', ctx, ops);\n const input: Record<string, unknown> = {};\n for (const k of ['CsvClassifier', 'GrokClassifier', 'JsonClassifier', 'XMLClassifier']) {\n const member = m[k];\n // require a Name — UpdateClassifier targets the classifier by it, and it guards against\n // a partial member an op might fabricate when the live read returned nothing.\n if (member && typeof member === 'object' && str((member as Record<string, unknown>).Name)) {\n input[k] = member;\n break;\n }\n }\n if (Object.keys(input).length === 0)\n throw new Error('cannot resolve Glue classifier target for revert');\n await new GlueClient({ region: ctx.region }).send(new UpdateClassifierCommand(input as never));\n};\n\n// AWS::Glue::Workflow — read via the GetWorkflow override (CC UnsupportedActionException),\n// so it was not revertable. Glue UpdateWorkflow takes the mutable props (Description /\n// DefaultRunProperties / MaxConcurrentRuns); reconstruct the desired model (current + revert\n// ops) and write the present ones back, targeting by the declared/physical Name.\nconst writeGlueWorkflow: SdkWriter = async (ctx, ops) => {\n const m = await desiredModel('AWS::Glue::Workflow', ctx, ops);\n const name = str(m.Name) ?? str(ctx.physicalId) ?? str(ctx.declared['Name']);\n if (!name) throw new Error('cannot resolve Glue workflow target for revert');\n await new GlueClient({ region: ctx.region }).send(\n new UpdateWorkflowCommand({\n Name: name,\n ...(m.Description !== undefined && { Description: str(m.Description) }),\n ...(m.DefaultRunProperties !== undefined && {\n DefaultRunProperties: m.DefaultRunProperties as Record<string, string>,\n }),\n ...(m.MaxConcurrentRuns !== undefined && { MaxConcurrentRuns: Number(m.MaxConcurrentRuns) }),\n })\n );\n};\n\n// AWS::Glue::Connection — read via the GetConnection override (the whole Glue family is a\n// CC read gap; UnsupportedActionException), so it was detect-only. Glue UpdateConnection is\n// a WHOLE-ConnectionInput overwrite, and the reader returns the full CFn `ConnectionInput`\n// (ConnectionType / Description / MatchCriteria / ConnectionProperties [SECRET_ID kept] /\n// PhysicalConnectionRequirements / AuthenticationConfiguration), so reconstruct the desired\n// model (current + revert ops) and write the whole ConnectionInput back — covering a\n// network / Description / JDBC-setting drift.\n//\n// CREDENTIAL SAFETY: the reader runs GetConnection with HidePassword and DROPS every\n// `*PASSWORD` ConnectionProperties key, so the desired ConnectionInput carries NO inline\n// password. Re-supplying it on a connection that DECLARES an inline password would CLEAR\n// that un-read credential (silent data loss). Refuse such a revert up front (a thrown error\n// the revert loop reports as a per-resource failure — never a clobber): only the modern\n// SECRET_ID / NETWORK / no-inline-credential pattern is safe to overwrite. The guard reads\n// the DECLARED ConnectionProperties (no extra API call); a SECRET_ID connection has no\n// password key and reverts fine.\nconst GLUE_CONNECTION_PASSWORD_KEY = /PASSWORD/i;\nconst writeGlueConnection: SdkWriter = async (ctx, ops) => {\n const declInput = ctx.declared['ConnectionInput'] as Record<string, unknown> | undefined;\n const declProps = declInput?.ConnectionProperties as Record<string, unknown> | undefined;\n if (declProps && Object.keys(declProps).some((k) => GLUE_CONNECTION_PASSWORD_KEY.test(k)))\n throw new Error(\n 'Glue Connection declares an inline PASSWORD — not revertable (a revert would clear the un-read credential); use a SECRET_ID connection or update it manually'\n );\n const m = await desiredModel('AWS::Glue::Connection', ctx, ops);\n const ci = m.ConnectionInput as Record<string, unknown> | undefined;\n const name = str(ci?.Name) ?? str(ctx.physicalId) ?? str(declInput?.Name);\n if (!ci || !name) throw new Error('cannot resolve Glue connection target for revert');\n const catalogId = str(m.CatalogId) ?? str(ctx.declared['CatalogId']);\n await new GlueClient({ region: ctx.region }).send(\n new UpdateConnectionCommand({\n Name: name,\n ...(catalogId && { CatalogId: catalogId }),\n // ConnectionProperties is required by the API; a NETWORK connection has none -> {}.\n ConnectionInput: { ...ci, Name: name, ConnectionProperties: ci.ConnectionProperties ?? {} },\n } as never)\n );\n};\n\n// AWS::SES::ReceiptRule — read via the DescribeReceiptRule override (the SES inbound\n// receipt-rule family has no Cloud Control handlers), so it was detect-only. SES\n// UpdateReceiptRule REPLACES the whole rule in place (without changing its position), and\n// the override reader returns the full CFn `Rule` (whose shape mirrors the SDK ReceiptRule\n// 1:1), so reconstruct the desired model (current live + revert ops) and write the whole\n// Rule back — covering any drift on Enabled / TlsPolicy / Recipients / Actions / ScanEnabled.\n// The parent RuleSetName (createOnly) targets the rule; sending the WHOLE live Rule (not just\n// the drifted field) means a never-declared Enabled/ScanEnabled is preserved rather than\n// reset to the SES create-default. (RuleSetName / ReceiptFilter have only createOnly props,\n// so they have no SDK writer — detect-only.)\nconst writeSesReceiptRule: SdkWriter = async (ctx, ops) => {\n const m = await desiredModel('AWS::SES::ReceiptRule', ctx, ops);\n const ruleSetName = str(m.RuleSetName) ?? str(ctx.declared['RuleSetName']);\n const rule = m.Rule as ReceiptRule | undefined;\n if (!ruleSetName || !rule || !str(rule.Name))\n throw new Error('cannot resolve SES receipt rule target for revert');\n await new SESClient({ region: ctx.region }).send(\n new UpdateReceiptRuleCommand({ RuleSetName: ruleSetName, Rule: rule })\n );\n};\n\n// AWS::CloudWatch::AnomalyDetector — read via the DescribeAnomalyDetectors override\n// (NON_PROVISIONABLE, no Cloud Control handlers), so it was detect-only. Every\n// identity property (Namespace/MetricName/Stat/Dimensions or the nested\n// SingleMetric/MetricMath detector) is createOnly — the one mutable property is\n// `Configuration` (MetricTimeZone + ExcludedTimeRanges), and cloudwatch\n// PutAnomalyDetector is an UPSERT keyed on the detector identity: re-supply the\n// identity from the desired model plus the desired Configuration and the config is\n// overwritten in place. Field mapping mirrors the reader (CFn MetricTimeZone -> API\n// MetricTimezone; ISO strings -> Dates). A desired model with NO Configuration sends\n// an empty {} — proven live to clear an out-of-band timezone back to the default.\nconst writeCloudWatchAnomalyDetector: SdkWriter = async (ctx, ops) => {\n const m = await desiredModel('AWS::CloudWatch::AnomalyDetector', ctx, ops);\n const single = m.SingleMetricAnomalyDetector as Record<string, unknown> | undefined;\n const math = m.MetricMathAnomalyDetector as Record<string, unknown> | undefined;\n const legacyNs = str(m.Namespace);\n if (!single && !math && !legacyNs)\n throw new Error('cannot resolve anomaly-detector identity for revert');\n const cfg = m.Configuration as\n | {\n MetricTimeZone?: unknown;\n ExcludedTimeRanges?: { StartTime?: unknown; EndTime?: unknown }[];\n }\n | undefined;\n // The CFn Range pattern is ZONE-LESS UTC (`YYYY-MM-DDTHH:MM:SS`) — a bare\n // `new Date(s)` would parse that as LOCAL time and shift every range by the\n // machine's UTC offset on revert. Pin zone-less strings to UTC explicitly.\n const toDate = (v: unknown): Date | undefined =>\n typeof v === 'string'\n ? new Date(/Z$|[+-]\\d\\d:\\d\\d$/.test(v) ? v : `${v}Z`)\n : v instanceof Date\n ? v\n : undefined;\n const configuration = {\n ...(str(cfg?.MetricTimeZone) && { MetricTimezone: cfg?.MetricTimeZone as string }),\n ...((cfg?.ExcludedTimeRanges ?? []).length > 0 && {\n ExcludedTimeRanges: (cfg?.ExcludedTimeRanges ?? []).map((r) => ({\n StartTime: toDate(r.StartTime),\n EndTime: toDate(r.EndTime),\n })),\n }),\n };\n await new CloudWatchClient({ region: ctx.region }).send(\n new PutAnomalyDetectorCommand({\n ...(single && { SingleMetricAnomalyDetector: single as never }),\n ...(math && { MetricMathAnomalyDetector: math as never }),\n ...(!single &&\n !math && {\n SingleMetricAnomalyDetector: {\n Namespace: legacyNs,\n MetricName: str(m.MetricName),\n Stat: str(m.Stat),\n ...(Array.isArray(m.Dimensions) &&\n m.Dimensions.length > 0 && { Dimensions: m.Dimensions as never }),\n },\n }),\n Configuration: configuration,\n })\n );\n};\n\n// AWS::DLM::LifecyclePolicy — read via the GetLifecyclePolicy override (NON_PROVISIONABLE,\n// no Cloud Control handlers), so it was detect-only. dlm:UpdateLifecyclePolicy takes the\n// SAME shape as the read (PolicyId + the mutable Description / State / ExecutionRoleArn /\n// PolicyDetails — PolicyType and ResourceType are the only immutable bits and are re-sent\n// unchanged inside PolicyDetails), so reconstruct the desired model (current + revert ops)\n// and write it back. Covers the common drifts: an out-of-band State flip (ENABLED↔DISABLED),\n// a changed schedule retain count / interval, an ExecutionRoleArn swap. The default-policy\n// shorthand emits the schedule knobs at the top level, which Update does NOT accept, so\n// re-fetch the live PolicyDetails and overlay the desired shorthand keys into it.\nconst writeDlmLifecyclePolicy: SdkWriter = async (ctx, ops) => {\n const id = str(ctx.physicalId);\n if (!id) throw new Error('cannot resolve DLM lifecycle policy id for revert');\n const c = new DLMClient({ region: ctx.region });\n const m = await desiredModel('AWS::DLM::LifecyclePolicy', ctx, ops);\n let details = m.PolicyDetails as Record<string, unknown> | undefined;\n if (details === undefined && DLM_DEFAULT_POLICY_SHORTHAND.some((k) => m[k] !== undefined)) {\n // Shorthand style: Update only accepts a full PolicyDetails, so start from the live\n // PolicyDetails (carries the immutable PolicyType/ResourceType the API folded in) and\n // overlay the desired shorthand values.\n const live = (await c.send(new GetLifecyclePolicyCommand({ PolicyId: id }))).Policy\n ?.PolicyDetails as Record<string, unknown> | undefined;\n details = { ...(live ?? {}) };\n for (const k of DLM_DEFAULT_POLICY_SHORTHAND) if (m[k] !== undefined) details[k] = m[k];\n }\n await c.send(\n new UpdateLifecyclePolicyCommand({\n PolicyId: id,\n ...(str(m.Description) !== undefined && { Description: str(m.Description) }),\n ...(str(m.State) !== undefined && { State: str(m.State) as SettablePolicyStateValues }),\n ...(str(m.ExecutionRoleArn) !== undefined && { ExecutionRoleArn: str(m.ExecutionRoleArn) }),\n ...(details !== undefined && { PolicyDetails: details as never }),\n })\n );\n};\n\n// AWS::Logs::MetricFilter — Cloud Control GetResource throws ValidationException (its\n// composite id), so it is read via DescribeMetricFilters and was not revertable.\n// CloudWatch Logs PutMetricFilter is an UPSERT of the whole filter, and the override\n// reader returns the full CFn model (FilterPattern + MetricTransformations [+\n// ApplyOnTransformedLogs]), so reconstruct the desired model (current + revert ops) and\n// PUT it back. Covers the common drifts: an out-of-band FilterPattern edit or a changed\n// MetricTransformation value.\nconst writeMetricFilter: SdkWriter = async (ctx, ops) => {\n const m = await desiredModel('AWS::Logs::MetricFilter', ctx, ops);\n const logGroup = str(m.LogGroupName) ?? str(ctx.declared['LogGroupName']);\n const filterName = str(m.FilterName) ?? str(ctx.physicalId) ?? str(ctx.declared['FilterName']);\n if (!logGroup || !filterName) throw new Error('cannot resolve metric filter target for revert');\n const transforms = ((m.MetricTransformations as Record<string, unknown>[]) ?? []).map((t) => ({\n metricName: str(t.MetricName),\n metricNamespace: str(t.MetricNamespace),\n metricValue: str(t.MetricValue),\n ...(t.DefaultValue !== undefined && { defaultValue: Number(t.DefaultValue) }),\n ...(t.Unit !== undefined && { unit: t.Unit as string }),\n ...(t.Dimensions !== undefined && { dimensions: t.Dimensions as Record<string, string> }),\n }));\n await new CloudWatchLogsClient({ region: ctx.region }).send(\n new PutMetricFilterCommand({\n logGroupName: logGroup,\n filterName,\n filterPattern: str(m.FilterPattern) ?? '',\n metricTransformations: transforms as never,\n ...(m.ApplyOnTransformedLogs !== undefined && {\n applyOnTransformedLogs: m.ApplyOnTransformedLogs as boolean,\n }),\n })\n );\n};\n\n// AWS::Route53::RecordSet — Cloud Control cannot read this type (read via the\n// ListResourceRecordSets override) and it had no writer, so a console edit to a record\n// (TTL / values / weight / failover / alias target / health check) was detected but not\n// revertable. Route53 ChangeResourceRecordSets with Action UPSERT replaces the record\n// with the supplied ResourceRecordSet, and the override reader returns the FULL CFn\n// projection (Name/Type/TTL/ResourceRecords + AliasTarget + all routing-policy fields),\n// so reconstruct the desired RRSet (current + revert ops) and UPSERT it. A simple record\n// carries Name/Type/TTL/ResourceRecords; alias/weighted/latency/failover/geo/cidr\n// variants carry their extra fields, all already in the desired model.\nconst RR_ROUTING_FIELDS = [\n 'SetIdentifier',\n 'Weight',\n 'Region',\n 'Failover',\n 'MultiValueAnswer',\n 'HealthCheckId',\n 'GeoLocation',\n 'GeoProximityLocation',\n 'CidrRoutingConfig',\n] as const;\nconst writeRoute53RecordSet: SdkWriter = async (ctx, ops) => {\n const m = await desiredModel('AWS::Route53::RecordSet', ctx, ops);\n const zone = str(m.HostedZoneId) ?? str(ctx.declared['HostedZoneId']);\n const name = str(m.Name) ?? str(ctx.declared['Name']);\n const type = str(m.Type) ?? str(ctx.declared['Type']);\n if (!zone || !name || !type) throw new Error('cannot resolve Route53 record target for revert');\n const rrset: Record<string, unknown> = { Name: name, Type: type };\n if (m.TTL !== undefined) rrset.TTL = Number(m.TTL); // CFn TTL is a string; the API wants a number\n if (Array.isArray(m.ResourceRecords))\n rrset.ResourceRecords = (m.ResourceRecords as string[]).map((v) => ({ Value: v }));\n if (m.AliasTarget !== undefined) rrset.AliasTarget = m.AliasTarget;\n for (const k of RR_ROUTING_FIELDS) if (m[k] !== undefined) rrset[k] = m[k];\n await new Route53Client({ region: ctx.region }).send(\n new ChangeResourceRecordSetsCommand({\n HostedZoneId: zone,\n ChangeBatch: { Changes: [{ Action: 'UPSERT', ResourceRecordSet: rrset as never }] },\n })\n );\n};\n\n// AWS::Config::ConfigRule `InputParameters` — Config stores it as a single JSON STRING.\n// Cloud Control CAN read it (returned parsed as an object) but CANNOT revert it: a CC\n// UpdateResource re-serializes the JSON into Config's string field WITH SPACES, which the\n// PutConfigRule provider rejects (\"Blank spaces are not acceptable for input parameter\")\n// — proven live, the same CC-revalidation class as OpenSearch/CloudFront. So revert this\n// property via PutConfigRule directly, writing the declared value as a COMPACT JSON string\n// (no spaces). PutConfigRule is a whole-rule UPSERT, so re-read the current rule and\n// overwrite only InputParameters, preserving Source/Scope/MaximumExecutionFrequency/etc.\n// Config stores InputParameters as a JSON string whose param VALUES are themselves\n// strings (a managed rule's `maxAccessKeyAge` is `\"90\"`, not `90`). CDK declares them\n// typed (`90`), and CloudFormation coerces them to strings on deploy — cdkrd treats\n// `90` and `\"90\"` as equal (stringly). The revert must write the SAME string-valued form\n// CloudFormation produced, or PutConfigRule rejects the numeric value with the misleading\n// \"Blank spaces are not acceptable for input parameter\" error (proven live). So serialize\n// the declared object with each scalar param value coerced to a string; objects/arrays\n// (a rare structured param) are left as-is for JSON to render.\nconst configInputParametersString = (v: unknown): string => {\n let model: unknown = v;\n if (typeof v === 'string') {\n try {\n model = JSON.parse(v);\n } catch {\n return v; // already a string we can't parse — pass through verbatim\n }\n }\n if (model !== null && typeof model === 'object' && !Array.isArray(model)) {\n const coerced: Record<string, unknown> = {};\n for (const [k, val] of Object.entries(model as Record<string, unknown>)) {\n coerced[k] = typeof val === 'number' || typeof val === 'boolean' ? String(val) : val;\n }\n return JSON.stringify(coerced);\n }\n return JSON.stringify(model);\n};\nconst writeConfigRuleInputParameters: SdkWriter = async (ctx, ops) => {\n const name = str(ctx.physicalId) ?? str(ctx.declared['ConfigRuleName']);\n if (!name) throw new Error('cannot resolve Config rule name for revert');\n const op = ops.find((o) => o.path === '/InputParameters');\n if (op?.op !== 'add') throw new Error('Config rule InputParameters revert: unexpected op');\n const client = new ConfigServiceClient({ region: ctx.region });\n const got = await client.send(new DescribeConfigRulesCommand({ ConfigRuleNames: [name] }));\n const rule = got.ConfigRules?.[0];\n if (!rule) throw new Error(`Config rule not found for revert: ${name}`);\n // Re-PUT the rule with only InputParameters overwritten. Drop the server-populated\n // fields PutConfigRule rejects (ConfigRuleArn/Id/State, CreatedBy, and a newer\n // RuleEvaluationVisibility — proven live: \"AWS Config populates the\n // RuleEvaluationVisibility field ... Try again without populating [it]\"); keep the rest\n // (Source/Scope/Description/MaximumExecutionFrequency/EvaluationModes). The rule is\n // matched by the preserved ConfigRuleName.\n const {\n ConfigRuleArn,\n ConfigRuleId,\n ConfigRuleState,\n CreatedBy,\n RuleEvaluationVisibility,\n ...rest\n } = rule;\n void ConfigRuleArn;\n void ConfigRuleId;\n void ConfigRuleState;\n void CreatedBy;\n void RuleEvaluationVisibility;\n await client.send(\n new PutConfigRuleCommand({\n ConfigRule: { ...rest, InputParameters: configInputParametersString(op.value) },\n })\n );\n};\n\n// AWS::OpenSearchService::Domain — Cloud Control CAN read this type, but its\n// UpdateResource REJECTS a property patch: it re-submits the full model and AWS's own\n// legacy `override_main_response_version` AdvancedOption (returned on read) is rejected\n// as \"Unrecognized advanced option\" (proven live; the same CC-revalidation class as\n// CloudFront/WAFv2/Glue). UpdateDomainConfig is a PARTIAL API, so route revert through\n// it sending ONLY the top-level option properties the revert ops actually touch — the\n// untouched AdvancedOptions are never re-submitted. (If AdvancedOptions itself is the\n// drift, the AWS-managed override_main_response_version key is dropped before the call.)\nconst OS_UPDATABLE_OPTIONS = new Set([\n 'ClusterConfig',\n 'EBSOptions',\n 'SnapshotOptions',\n 'VPCOptions',\n 'CognitoOptions',\n 'AdvancedOptions',\n 'AccessPolicies',\n 'IPAddressType',\n 'LogPublishingOptions',\n 'EncryptionAtRestOptions',\n 'DomainEndpointOptions',\n 'NodeToNodeEncryptionOptions',\n 'AdvancedSecurityOptions',\n 'AutoTuneOptions',\n 'OffPeakWindowOptions',\n 'SoftwareUpdateOptions',\n]);\nconst writeOpenSearchDomain: SdkWriter = async (ctx, ops) => {\n const name = str(ctx.physicalId) ?? str(ctx.declared['DomainName']);\n if (!name) throw new Error('cannot resolve OpenSearch domain name for revert');\n const touched = new Set(\n ops.map((o) => o.path.replace(/^\\//, '').split('/')[0]).filter((p): p is string => !!p)\n );\n const c = new OpenSearchClient({ region: ctx.region });\n const cfg = (await c.send(new DescribeDomainConfigCommand({ DomainName: name }))).DomainConfig as\n | Record<string, { Options?: unknown }>\n | undefined;\n // build a model of ONLY the touched option properties from the current live config,\n // apply the revert ops, then send each touched updatable property on its own.\n const model: Record<string, unknown> = {};\n for (const p of touched) if (cfg?.[p]?.Options !== undefined) model[p] = cfg[p].Options;\n const reverted = applyOps(model, ops);\n const input: Record<string, unknown> = { DomainName: name };\n for (const p of touched) {\n if (!OS_UPDATABLE_OPTIONS.has(p) || reverted[p] === undefined) continue;\n if (p === 'AdvancedOptions' && reverted[p] && typeof reverted[p] === 'object') {\n // drop the AWS-managed legacy key UpdateDomainConfig rejects on re-submit.\n const { override_main_response_version: _drop, ...rest } = reverted[p] as Record<\n string,\n unknown\n >;\n input[p] = rest;\n } else {\n input[p] = reverted[p];\n }\n }\n await c.send(new UpdateDomainConfigCommand(input as never));\n};\n\n// AWS::Logs::LogGroup.BearerTokenAuthenticationEnabled — Cloud Control CAN read this\n// type, but its UpdateResource FAILS on this (newer) boolean: the CC LogGroup update\n// handler's downstream CloudWatch Logs call errors with \"The security token included in\n// the request is invalid\" (proven live; the property has a dedicated control-plane API\n// the generic UpdateLogGroup path does not drive). CloudWatch Logs exposes\n// PutBearerTokenAuthentication for exactly this toggle, so route the revert through it.\n// The op is the BearerTokenAuthenticationEnabled toggle: a `remove` (undeclared, not in\n// baseline) reverts to the schema default of DISABLED; an `add` carries the desired\n// boolean (declared drift / recorded baseline value). The LogGroup physical id IS its\n// name, which PutBearerTokenAuthentication accepts as logGroupIdentifier.\nconst writeLogGroupBearerTokenAuth: SdkWriter = async (ctx, ops) => {\n const lg = str(ctx.physicalId) ?? str(ctx.declared['LogGroupName']);\n if (!lg) throw new Error('cannot resolve log group name for revert');\n const c = new CloudWatchLogsClient({ region: ctx.region });\n for (const op of ops) {\n // plan.ts groups this prop-scoped item to the single BearerTokenAuthenticationEnabled\n // path, so there is one op; a `remove` means \"back to default (disabled)\".\n const enabled = op.op === 'add' ? op.value === true : false;\n await c.send(\n new PutBearerTokenAuthenticationCommand({\n logGroupIdentifier: lg,\n bearerTokenAuthenticationEnabled: enabled,\n })\n );\n }\n};\n\n// AWS::Cognito::IdentityPool `CognitoEvents` (the writeOnly \"Cognito Events\" Sync\n// trigger) cannot be patched through Cloud Control — it is set via the cognito-sync\n// SetCognitoEvents API. Reconstruct the DESIRED event map (current live + revert ops)\n// then write it whole. Two cognito-sync quirks (both live-proven): SetCognitoEvents\n// REJECTS an empty map (\"Missing required parameter EventsMap\"), and a key simply OMITTED\n// from the map is NOT cleared — to remove an event you must set its value to an EMPTY\n// STRING. So re-add every current key the desired map drops, valued \"\" (clear); and when\n// there is nothing to set AND nothing to clear, skip the (rejected) empty call. The\n// IdentityPool physical id is the pool id SetCognitoEvents expects.\nconst writeCognitoIdentityPoolEvents: SdkWriter = async (ctx, ops) => {\n const id = str(ctx.physicalId) ?? str(ctx.declared['Id']);\n if (!id) throw new Error('cannot resolve identity pool id for CognitoEvents revert');\n const c = new CognitoSyncClient({ region: ctx.region });\n const cur = (await c.send(new GetCognitoEventsCommand({ IdentityPoolId: id }))).Events ?? {};\n const desired =\n (applyOps({ CognitoEvents: { ...cur } }, ops) as { CognitoEvents?: Record<string, string> })\n .CognitoEvents ?? {};\n const events: Record<string, string> = { ...desired };\n for (const k of Object.keys(cur)) if (!(k in events)) events[k] = ''; // clear dropped keys\n if (Object.keys(events).length === 0) return; // nothing to set or clear -> no-op\n await c.send(new SetCognitoEventsCommand({ IdentityPoolId: id, Events: events }));\n};\n\n// An ApiGateway Method's nested knobs live under a NESTED path Cloud Control cannot patch\n// reliably: the array-element ones (Integration.IntegrationResponses[<sc>].*,\n// MethodResponses[<sc>].*) are unaddressable by a flat RFC6902 pointer (the `[sc]` bracket\n// survives as a literal key, the same reason R78 abandoned index array patches), and CC's\n// whole-Method read-modify-write is fiddly for these sub-objects. API Gateway's native\n// granular patch API targets each knob exactly, so route these specific paths here. Mirrors\n// isManagedPolicyAttachmentMember: a nested undeclared value WITH a precise flat SDK op is\n// exempt from the record-only bar.\n// - Integration-level: Integration.{PassthroughBehavior,ContentHandling,TimeoutInMillis}\n// - IntegrationResponse: Integration.IntegrationResponses[<sc>].{SelectionPattern,ContentHandling}\n// - MethodResponse: MethodResponses[<sc>].ResponseModels (the whole live-only map —\n// classify emits a live-only sub-OBJECT whole, so the media keys ride the op's value)\nconst APIGW_METHOD_KNOB =\n /^Integration\\.(PassthroughBehavior|ContentHandling|TimeoutInMillis)$|^Integration\\.IntegrationResponses\\[[^\\]]+\\]\\.(SelectionPattern|ContentHandling)$|^MethodResponses\\[[^\\]]+\\]\\.ResponseModels$/;\nexport const isApiGatewayMethodKnobPath = (path: string): boolean => APIGW_METHOD_KNOB.test(path);\n\n// Per-knob revert target: the API Gateway patch path + the value to RESET to when the knob\n// was undeclared. API Gateway REJECTS `op: remove` for these INTEGRATION knobs (`Invalid\n// patch path /selectionPattern` — proven live), so the reset is always a `replace`:\n// - PassthroughBehavior / TimeoutInMillis -> their AWS default (WHEN_NO_MATCH / 29000).\n// - ContentHandling / SelectionPattern -> the EMPTY STRING, which is the cleared state:\n// `replace /contentHandling \"\"` makes CC read it ABSENT, and `replace /selectionPattern\n// \"\"` leaves a \"\" the compare folds as trivially-empty (both proven live).\n// (MethodResponses ResponseModels is the EXCEPTION — UpdateMethodResponse DOES accept\n// `op: remove /responseModels/<media>`, proven live — handled separately below.)\n// A declared-drift revert (`add` op) replaces with the desired template value instead.\nconst APIGW_KNOB_RESET: Record<string, { patchPath: string; resetTo: string }> = {\n PassthroughBehavior: { patchPath: '/passthroughBehavior', resetTo: 'WHEN_NO_MATCH' },\n TimeoutInMillis: { patchPath: '/timeoutInMillis', resetTo: '29000' },\n ContentHandling: { patchPath: '/contentHandling', resetTo: '' },\n SelectionPattern: { patchPath: '/selectionPattern', resetTo: '' },\n};\n\nconst ptrEscape = (s: string): string => s.replace(/~/g, '~0').replace(/\\//g, '~1');\n\ntype ApiGwPatch =\n | { kind: 'integration'; patch: PatchOperation }\n | { kind: 'integrationResponse'; statusCode: string; patch: PatchOperation }\n | { kind: 'methodResponse'; statusCode: string; patch: PatchOperation };\n\nconst asRecord = (v: unknown): Record<string, unknown> =>\n v !== null && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {};\n\n// Translate a revert op (RFC6902 pointer into the Method model) into the matching API Gateway\n// PatchOperation(s) + which sub-resource call applies each. ResponseModels yields ONE patch\n// per media key (the finding is the whole map); the others yield a single patch.\nfunction apigwKnobPatches(op: PatchOp): ApiGwPatch[] {\n const segs = op.path\n .split('/')\n .slice(1)\n .map((s) => s.replace(/~1/g, '/').replace(/~0/g, '~'));\n // MethodResponses[<sc>].ResponseModels -> UpdateMethodResponse, one patch per media key.\n // UpdateMethodResponse ACCEPTS op:remove for a responseModels entry (proven live), so an\n // undeclared map is removed key-by-key (its keys ride op.prior); a declared one is restored\n // with op:add from op.value.\n const mr = segs[0]?.match(/^MethodResponses\\[(.+)\\]$/);\n if (mr && segs[1] === 'ResponseModels') {\n const statusCode = mr[1] ?? '';\n const media = op.op === 'add' ? asRecord(op.value) : asRecord(op.prior);\n return Object.keys(media).map((k) => ({\n kind: 'methodResponse' as const,\n statusCode,\n patch:\n op.op === 'add'\n ? { op: 'add', path: `/responseModels/${ptrEscape(k)}`, value: String(media[k]) }\n : { op: 'remove', path: `/responseModels/${ptrEscape(k)}` },\n }));\n }\n const ir = segs[1]?.match(/^IntegrationResponses\\[(.+)\\]$/);\n const field = (ir ? segs[2] : segs[1]) ?? '';\n const knob = APIGW_KNOB_RESET[field];\n if (!knob) throw new Error(`unsupported ApiGateway method knob: ${op.path}`);\n const value = op.op === 'add' ? String(op.value) : knob.resetTo;\n const patch: PatchOperation = { op: 'replace', path: knob.patchPath, value };\n return [\n ir\n ? { kind: 'integrationResponse', statusCode: ir[1] ?? '', patch }\n : { kind: 'integration', patch },\n ];\n}\n\nconst pushByKey = (m: Map<string, PatchOperation[]>, k: string, p: PatchOperation): void => {\n const arr = m.get(k);\n if (arr) arr.push(p);\n else m.set(k, [p]);\n};\n\n// Revert an ApiGateway Method's nested knobs (see isApiGatewayMethodKnobPath) via API\n// Gateway's native granular patch API: integration-level ops batch into one UpdateIntegration;\n// per-statusCode integration-response ops into UpdateIntegrationResponse; per-statusCode\n// method-response ops into UpdateMethodResponse.\nconst writeApiGatewayMethod: SdkWriter = async (ctx, ops) => {\n const [restApiId, resourceId, httpMethod] = ctx.physicalId.split('|');\n if (!restApiId || !resourceId || !httpMethod)\n throw new Error(\n `cannot parse ApiGateway Method id \"${ctx.physicalId}\" (RestApiId|ResourceId|HttpMethod)`\n );\n const integrationPatches: PatchOperation[] = [];\n const integrationRespPatches = new Map<string, PatchOperation[]>();\n const methodRespPatches = new Map<string, PatchOperation[]>();\n for (const op of ops)\n for (const p of apigwKnobPatches(op)) {\n if (p.kind === 'integration') integrationPatches.push(p.patch);\n else if (p.kind === 'integrationResponse')\n pushByKey(integrationRespPatches, p.statusCode, p.patch);\n else pushByKey(methodRespPatches, p.statusCode, p.patch);\n }\n const c = new APIGatewayClient({ region: ctx.region });\n if (integrationPatches.length > 0)\n await c.send(\n new UpdateIntegrationCommand({\n restApiId,\n resourceId,\n httpMethod,\n patchOperations: integrationPatches,\n })\n );\n for (const [statusCode, patchOperations] of integrationRespPatches)\n await c.send(\n new UpdateIntegrationResponseCommand({\n restApiId,\n resourceId,\n httpMethod,\n statusCode,\n patchOperations,\n })\n );\n for (const [statusCode, patchOperations] of methodRespPatches)\n await c.send(\n new UpdateMethodResponseCommand({\n restApiId,\n resourceId,\n httpMethod,\n statusCode,\n patchOperations,\n })\n );\n};\n\n// Recursively lower-case the first letter of every object key (the inverse of the\n// reader's pascalKeysDeep): the declared CFn `ServiceConnectConfiguration` is PascalCase,\n// the ecs:UpdateService input is camelCase.\nfunction camelKeysDeep(v: unknown): unknown {\n if (Array.isArray(v)) return v.map(camelKeysDeep);\n if (v && typeof v === 'object') {\n const out: Record<string, unknown> = {};\n for (const [k, val] of Object.entries(v)) {\n out[k.charAt(0).toLowerCase() + k.slice(1)] = camelKeysDeep(val);\n }\n return out;\n }\n return v;\n}\n\n// AWS::ECS::Service ServiceConnectConfiguration / VolumeConfigurations — both writeOnly,\n// so Cloud Control cannot sub-path patch them; revert re-supplies the WHOLE declared\n// prop via ecs:UpdateService (the only API that sets them). The whole config comes from\n// `ctx.declared` (the resolved template intent), NOT the nested op value, so any drift\n// under either prop reverts to the declared whole. CamelCased back to the SDK shape;\n// UpdateService re-defaults DiscoveryName→PortName / FilesystemType→\"xfs\", which the\n// reader folds, so the stack converges clean. ONLY the prop(s) the ops touch are sent\n// (UpdateService leaves untouched fields alone), and a service whose declared Service\n// Connect config is gone sends `enabled: false` to turn it off.\nconst writeEcsServiceWriteOnlyProps: SdkWriter = async (ctx, ops) => {\n const cluster = str(ctx.declared['Cluster']);\n const service = str(ctx.physicalId);\n if (!cluster || !service) return;\n const input: { cluster: string; service: string } & Record<string, unknown> = {\n cluster,\n service,\n };\n if (ops.some((o) => o.path.startsWith('/ServiceConnectConfiguration'))) {\n const declared = ctx.declared['ServiceConnectConfiguration'];\n input.serviceConnectConfiguration =\n declared && typeof declared === 'object'\n ? (camelKeysDeep(declared) as ServiceConnectConfiguration)\n : { enabled: false };\n }\n if (ops.some((o) => o.path.startsWith('/VolumeConfigurations'))) {\n const declared = ctx.declared['VolumeConfigurations'];\n input.volumeConfigurations = Array.isArray(declared)\n ? (camelKeysDeep(declared) as ServiceVolumeConfiguration[])\n : [];\n }\n const c = new ECSClient({ region: ctx.region });\n await c.send(new UpdateServiceCommand(input));\n};\n\n// AWS::MSK::Configuration `ServerProperties` is writeOnly, so Cloud Control cannot patch it\n// (it can't read it); a \"revert\" is APPEND-ONLY — kafka:UpdateConfiguration creates the NEXT\n// revision carrying the desired properties (the only mechanism MSK offers), which becomes the\n// LatestRevision the SDK_SUPPLEMENTS reader then reads back. The op value is the desired\n// plaintext server.properties blob (CFn accepts plaintext; the API takes bytes). #508.\nconst writeMskConfiguration: SdkWriter = async (ctx, ops) => {\n const arn = str(ctx.physicalId);\n if (!arn) throw new Error('cannot resolve MSK Configuration ARN for revert');\n const op = ops.find((o) => o.path === '/ServerProperties');\n if (op === undefined || op.op === 'remove' || typeof op.value !== 'string')\n throw new Error('MSK Configuration ServerProperties revert: unexpected op');\n const client = new KafkaClient({ region: ctx.region });\n await client.send(\n new UpdateConfigurationCommand({\n Arn: arn,\n ServerProperties: new TextEncoder().encode(op.value),\n })\n );\n};\n\n// AWS::CodeBuild::ReportGroup — NON_PROVISIONABLE (read via BatchGetReportGroups; #530).\n// codebuild:UpdateReportGroup re-supplies the two mutable props (exportConfig / tags) WHOLESALE\n// — the reader's projected shape maps back 1:1 (PascalCase CFn → camelCase API). Always send both\n// desired sub-objects so reverting a Tags-only drift never wipes the ExportConfig and vice-versa;\n// they reflect the intended (declared-or-current) full state (desiredModel = live + revert ops).\n// Type is create-only (not modifiable), so it never reaches here. #552.\nconst writeCodeBuildReportGroup: SdkWriter = async (ctx, ops) => {\n const arn = str(ctx.physicalId);\n if (!arn) throw new Error('cannot resolve CodeBuild ReportGroup ARN for revert');\n const desired = await desiredModel('AWS::CodeBuild::ReportGroup', ctx, ops);\n const input: { arn: string; exportConfig?: ReportExportConfig; tags?: CodeBuildTag[] } = { arn };\n const ec = desired.ExportConfig as Record<string, unknown> | undefined;\n if (ec) {\n const s3 = ec.S3Destination as Record<string, unknown> | undefined;\n input.exportConfig = {\n exportConfigType: ec.ExportConfigType as ReportExportConfig['exportConfigType'],\n ...(s3\n ? {\n s3Destination: {\n bucket: str(s3.Bucket),\n path: str(s3.Path),\n packaging: str(s3.Packaging) as\n | NonNullable<ReportExportConfig['s3Destination']>['packaging']\n | undefined,\n encryptionKey: str(s3.EncryptionKey),\n encryptionDisabled:\n typeof s3.EncryptionDisabled === 'boolean' ? s3.EncryptionDisabled : undefined,\n },\n }\n : {}),\n };\n }\n const tags = desired.Tags as { Key?: unknown; Value?: unknown }[] | undefined;\n // Always send tags (empty list clears them) so a removed/edited tag reverts; omitting it would\n // leave AWS's current tags untouched (UpdateReportGroup replaces the tag set wholesale).\n input.tags = Array.isArray(tags)\n ? tags.map((t) => ({ key: str(t.Key), value: str(t.Value) }))\n : [];\n await new CodeBuildClient({ region: ctx.region }).send(new UpdateReportGroupCommand(input));\n};\n\n// AWS::DAX::Cluster — NON_PROVISIONABLE (read via DescribeClusters; #534). dax:UpdateCluster is a\n// PARTIAL modify (like ModifyDBCluster): send ONLY the drifted top-level props in the mutable\n// allowlist, mapped CFn→API (NotificationTopicARN → NotificationTopicArn). NodeType/ClusterName/\n// SubnetGroupName/IAMRoleARN/ClusterEndpointEncryptionType are create-only → never in the\n// allowlist. #552.\nconst DAX_CLUSTER_MODIFY_PARAMS: Record<string, string> = {\n Description: 'Description',\n PreferredMaintenanceWindow: 'PreferredMaintenanceWindow',\n NotificationTopicARN: 'NotificationTopicArn',\n ParameterGroupName: 'ParameterGroupName',\n SecurityGroupIds: 'SecurityGroupIds',\n};\nconst writeDaxCluster: SdkWriter = async (ctx, ops) => {\n const name = str(ctx.physicalId) ?? str(ctx.declared['ClusterName']);\n if (!name) throw new Error('cannot resolve DAX cluster name for revert');\n const desired = await desiredModel('AWS::DAX::Cluster', ctx, ops);\n const input: { ClusterName: string; [k: string]: unknown } = { ClusterName: name };\n let any = false;\n for (const op of ops) {\n const top = op.path.replace(/^\\//, '').split('/')[0] ?? '';\n const apiKey = DAX_CLUSTER_MODIFY_PARAMS[top];\n if (!apiKey) continue;\n // A revert that CLEARS a value (op removed it, e.g. NotificationTopicARN back to none) sends\n // the empty string DAX accepts to detach the topic; otherwise send the desired value.\n const val = desired[top] ?? (apiKey === 'NotificationTopicArn' ? '' : undefined);\n if (val !== undefined) {\n input[apiKey] = val;\n any = true;\n }\n }\n if (!any) return;\n await new DAXClient({ region: ctx.region }).send(new UpdateClusterCommand(input));\n};\n\n// AWS::DAX::ParameterGroup — NON_PROVISIONABLE (read via DescribeParameters; #534).\n// dax:UpdateParameterGroup updates ONLY the parameters passed (others untouched), so re-assert\n// each DRIFTED parameter to its desired value. The CFn `ParameterNameValues` is a { name → value }\n// map; the API takes a [{ ParameterName, ParameterValue }] list. #552.\nconst writeDaxParameterGroup: SdkWriter = async (ctx, ops) => {\n const name = str(ctx.physicalId) ?? str(ctx.declared['ParameterGroupName']);\n if (!name) throw new Error('cannot resolve DAX parameter-group name for revert');\n const desired = await desiredModel('AWS::DAX::ParameterGroup', ctx, ops);\n const desiredValues = (desired.ParameterNameValues as Record<string, unknown> | undefined) ?? {};\n // Collect the parameter keys the revert ops touch (path `/ParameterNameValues/<key>`), plus a\n // whole-map op (`/ParameterNameValues`). Re-send each from the desired map.\n const keys = new Set<string>();\n for (const op of ops) {\n const segs = op.path.replace(/^\\//, '').split('/');\n if (segs[0] !== 'ParameterNameValues') continue;\n if (segs[1] !== undefined) keys.add(segs[1].replace(/~1/g, '/').replace(/~0/g, '~'));\n else for (const k of Object.keys(desiredValues)) keys.add(k);\n }\n const values = [...keys]\n .filter((k) => typeof desiredValues[k] === 'string')\n .map((k) => ({ ParameterName: k, ParameterValue: desiredValues[k] as string }));\n if (values.length === 0) return;\n await new DAXClient({ region: ctx.region }).send(\n new UpdateDaxParameterGroupCommand({ ParameterGroupName: name, ParameterNameValues: values })\n );\n};\n\n// AWS::EC2::ClientVpnEndpoint — NON_PROVISIONABLE (read via DescribeClientVpnEndpoints; #534).\n// ec2:ModifyClientVpnEndpoint is a PARTIAL modify: send ONLY the drifted top-level props in the\n// mutable allowlist. Two props need reshaping vs the reader's projection: DnsServers (the read is\n// a plain string[]; modify takes a DnsServersOptionsModifyStructure { CustomDnsServers, Enabled }),\n// and SecurityGroupIds (the API requires VpcId alongside it). ServerCertificateArn/ClientCidrBlock/\n// TransportProtocol/VpcId are create-only → not in the allowlist. #552.\nconst CLIENT_VPN_SCALAR_PARAMS = new Set([\n 'Description',\n 'SplitTunnel',\n 'VpnPort',\n 'SessionTimeoutHours',\n 'DisconnectOnSessionTimeout',\n]);\nconst writeEc2ClientVpnEndpoint: SdkWriter = async (ctx, ops) => {\n const id = str(ctx.physicalId);\n if (!id) throw new Error('cannot resolve Client VPN endpoint id for revert');\n const desired = await desiredModel('AWS::EC2::ClientVpnEndpoint', ctx, ops);\n const input: { ClientVpnEndpointId: string; [k: string]: unknown } = { ClientVpnEndpointId: id };\n let any = false;\n const tops = new Set(ops.map((op) => op.path.replace(/^\\//, '').split('/')[0] ?? ''));\n for (const top of tops) {\n if (CLIENT_VPN_SCALAR_PARAMS.has(top) && desired[top] !== undefined) {\n input[top] = desired[top];\n any = true;\n } else if (top === 'ConnectionLogOptions' && desired.ConnectionLogOptions !== undefined) {\n input.ConnectionLogOptions = desired.ConnectionLogOptions;\n any = true;\n } else if (top === 'DnsServers') {\n const list = desired.DnsServers as string[] | undefined;\n input.DnsServers =\n Array.isArray(list) && list.length > 0\n ? { CustomDnsServers: list, Enabled: true }\n : { Enabled: false };\n any = true;\n } else if (top === 'SecurityGroupIds') {\n const list = desired.SecurityGroupIds as string[] | undefined;\n const vpcId = str(desired.VpcId) ?? str(ctx.declared['VpcId']);\n if (Array.isArray(list) && list.length > 0 && vpcId) {\n input.SecurityGroupIds = list;\n input.VpcId = vpcId;\n any = true;\n }\n }\n }\n if (!any) return;\n await new EC2Client({ region: ctx.region }).send(new ModifyClientVpnEndpointCommand(input));\n};\n\n// AWS::Lex::Bot `BotLocales` is the ENTIRE conversational model (locales → intents → slots +\n// slot types), writeOnly in the registry schema and read back by supplementLexBot walking the\n// lexv2-models DRAFT tree. Cloud Control cannot write it, so revert re-supplies the DECLARED\n// model through the lexv2-models write APIs (#553). It converges each EXISTING node (locale\n// settings / slot type / intent / slot) to its declared value via a read-modify-write (Describe\n// → overlay the declared-projected fields → Update, preserving any un-projected setting), and\n// FULLY REBUILDS the structure when the declared and live node-NAME sets differ (#564): a\n// declared node missing from live is CREATED (CreateSlotType / CreateIntent / CreateSlot,\n// resolving SlotTypeName→id and SlotPriorities after the slots exist) and a live node not in the\n// declared set is DELETED (DeleteSlot / DeleteIntent / DeleteSlotType — never the auto-managed\n// built-in FallbackIntent). Order: slot types → intents → slots for create (so references\n// resolve) and the reverse for delete, then one BuildBotLocale per touched locale. This makes a\n// revert able to rebuild the whole conversational model, not just update in place.\nconst LEX_CFN_TO_LEX_RESOLUTION_STRATEGY: Record<string, string> = {\n ORIGINAL_VALUE: 'OriginalValue',\n TOP_RESOLUTION: 'TopResolution',\n CONCATENATION: 'Concatenation',\n};\ntype LexRec = Record<string, unknown>;\nconst lexStr = (v: unknown): string | undefined =>\n typeof v === 'string' && v.length > 0 ? v : undefined;\n// Map a declared CFn SlotType's SlotTypeValues to the lexv2 slotTypeValues shape (used by both\n// the create and update paths). Returns undefined when the property is not a declared array.\nconst lexMapSlotTypeValues = (dst: LexRec): { sampleValue: { value: string } }[] | undefined =>\n Array.isArray(dst.SlotTypeValues)\n ? (dst.SlotTypeValues as LexRec[]).map((v) => {\n const sv = (v.SampleValue as LexRec | undefined)?.Value;\n const syns = Array.isArray(v.Synonyms)\n ? (v.Synonyms as LexRec[])\n .map((s) => lexStr(s.Value))\n .filter((x): x is string => x !== undefined)\n .map((x) => ({ value: x }))\n : undefined;\n return {\n sampleValue: { value: lexStr(sv) ?? '' },\n ...(syns && syns.length > 0 ? { synonyms: syns } : {}),\n };\n })\n : undefined;\n// The lexv2 valueSelectionSetting.resolutionStrategy for a declared SlotType (mapped from the\n// CFn enum), or undefined when none is declared.\nconst lexResolutionStrategy = (dst: LexRec): string | undefined => {\n const strat = lexStr((dst.ValueSelectionSetting as LexRec | undefined)?.ResolutionStrategy);\n return strat === undefined ? undefined : (LEX_CFN_TO_LEX_RESOLUTION_STRATEGY[strat] ?? strat);\n};\n// Map a declared CFn intent's SampleUtterances to the lexv2 sampleUtterances shape, or undefined.\nconst lexMapUtterances = (di: LexRec): { utterance: string }[] | undefined =>\n Array.isArray(di.SampleUtterances)\n ? (di.SampleUtterances as LexRec[])\n .map((u) => lexStr(u.Utterance))\n .filter((x): x is string => x !== undefined)\n .map((utterance) => ({ utterance }))\n : undefined;\n// Build the lexv2 promptSpecification from a declared CFn PromptSpecification (inverse of the\n// reader's projectLexPrompt). Only the fields the reader projects are set.\nconst lexBuildPrompt = (declared: unknown): LexRec | undefined => {\n if (!declared || typeof declared !== 'object') return undefined;\n const d = declared as LexRec;\n const out: LexRec = {};\n if (typeof d.MaxRetries === 'number') out.maxRetries = d.MaxRetries;\n if (typeof d.AllowInterrupt === 'boolean') out.allowInterrupt = d.AllowInterrupt;\n if (Array.isArray(d.MessageGroupsList)) {\n out.messageGroups = d.MessageGroupsList.map((g) => {\n const value = (g as LexRec)?.Message as LexRec | undefined;\n const plain = value?.PlainTextMessage as LexRec | undefined;\n return { message: { plainTextMessage: { value: lexStr(plain?.Value) ?? '' } } };\n });\n }\n return out;\n};\nconst writeLexBotLocales: SdkWriter = async (ctx, ops) => {\n const botId = str(ctx.physicalId);\n if (!botId) throw new Error('cannot resolve Lex Bot id for revert');\n const declaredLocales = ctx.declared['BotLocales'];\n if (!Array.isArray(declaredLocales))\n throw new Error('Lex BotLocales revert: declared BotLocales is not an array');\n void ops; // reconcile the WHOLE declared model (declared IS the desired target); ops only route.\n const c = new LexModelsV2Client({ region: ctx.region });\n const botVersion = 'DRAFT';\n\n for (const rawLocale of declaredLocales) {\n if (!rawLocale || typeof rawLocale !== 'object') continue;\n const loc = rawLocale as LexRec;\n const localeId = lexStr(loc.LocaleId);\n if (!localeId) throw new Error('Lex BotLocales revert: a declared locale has no LocaleId');\n\n // --- slot types: name<->id (custom only; AMAZON.* are built-in), create missing / update ---\n const liveSlotTypes = await c.send(new ListSlotTypesCommand({ botId, botVersion, localeId }));\n const slotTypeNameToId = new Map<string, string>();\n for (const s of liveSlotTypes.slotTypeSummaries ?? []) {\n const id = lexStr(s.slotTypeId);\n const name = lexStr(s.slotTypeName);\n if (id && name && !id.startsWith('AMAZON.')) slotTypeNameToId.set(name, id);\n }\n const declaredSlotTypes = Array.isArray(loc.SlotTypes) ? (loc.SlotTypes as LexRec[]) : [];\n const declaredStNames = new Set(\n declaredSlotTypes.map((s) => lexStr(s.Name)).filter((n): n is string => n !== undefined)\n );\n // Live custom slot types NOT in the declared set are out-of-band additions — deleted AFTER\n // every referencing slot/intent is reconciled (a slot type in use cannot be deleted), so the\n // names are captured now (before create-missing mutates the map) and DeleteSlotType runs last.\n const extraSlotTypeNames = [...slotTypeNameToId.keys()].filter((n) => !declaredStNames.has(n));\n // A declared custom slot type missing from live was deleted out of band — recreate it first\n // (slots resolve SlotTypeName→id against this map). CreateSlotType needs a valueSelectionSetting\n // when it carries values; the update loop below then converges the full declared content.\n for (const dst of declaredSlotTypes) {\n const name = lexStr(dst.Name);\n if (!name || slotTypeNameToId.has(name)) continue;\n const created = await c.send(\n new CreateSlotTypeCommand({\n botId,\n botVersion,\n localeId,\n slotTypeName: name,\n description: lexStr(dst.Description),\n slotTypeValues: lexMapSlotTypeValues(dst),\n valueSelectionSetting: {\n resolutionStrategy: lexResolutionStrategy(dst) ?? 'OriginalValue',\n },\n } as unknown as CreateSlotTypeCommandInput)\n );\n const newId = lexStr(created.slotTypeId);\n if (newId) slotTypeNameToId.set(name, newId);\n }\n // resolve a declared SlotTypeName to a live slotTypeId (built-ins map to themselves)\n const resolveSlotTypeId = (name: string | undefined): string | undefined =>\n name === undefined\n ? undefined\n : name.startsWith('AMAZON.')\n ? name\n : slotTypeNameToId.get(name);\n\n for (const dst of declaredSlotTypes) {\n const name = lexStr(dst.Name);\n const slotTypeId = name ? slotTypeNameToId.get(name) : undefined;\n if (!slotTypeId || !name) continue;\n const live = await c.send(\n new DescribeSlotTypeCommand({ botId, botVersion, localeId, slotTypeId })\n );\n const input: LexRec = {\n botId,\n botVersion,\n localeId,\n slotTypeId,\n slotTypeName: name,\n parentSlotTypeSignature: live.parentSlotTypeSignature,\n externalSourceSetting: live.externalSourceSetting,\n compositeSlotTypeSetting: live.compositeSlotTypeSetting,\n description: lexStr(dst.Description),\n slotTypeValues: lexMapSlotTypeValues(dst) ?? live.slotTypeValues,\n };\n const strat = lexResolutionStrategy(dst);\n if (strat !== undefined)\n input.valueSelectionSetting = {\n ...(live.valueSelectionSetting ?? {}),\n resolutionStrategy: strat,\n };\n else input.valueSelectionSetting = live.valueSelectionSetting;\n await c.send(new UpdateSlotTypeCommand(input as unknown as UpdateSlotTypeCommandInput));\n }\n\n // --- intents: name<->id, create missing / delete extra (skip AMAZON.FallbackIntent-style\n // built-ins), then update each ---\n const liveIntents = await c.send(new ListIntentsCommand({ botId, botVersion, localeId }));\n const intentNameToId = new Map<string, string>();\n for (const i of liveIntents.intentSummaries ?? []) {\n const id = lexStr(i.intentId);\n const name = lexStr(i.intentName);\n if (id && name) intentNameToId.set(name, id);\n }\n const declaredIntents = Array.isArray(loc.Intents) ? (loc.Intents as LexRec[]) : [];\n // The built-in FallbackIntent is auto-created/managed by Lex — it is always present live and\n // its declaration is optional, so it is NOT a user-authored node that can be added/removed\n // out of band. Exclude it (and any AMAZON.* signature intent) from the structural check on\n // BOTH sides, and skip re-writing it below (reverting the auto-managed fallback is not a\n // target case). Compare only the USER intents.\n const isBuiltinIntent = (n: string): boolean =>\n n === 'FallbackIntent' || n.startsWith('AMAZON.');\n const declaredIntentNames = new Set(\n declaredIntents.map((i) => lexStr(i.Name)).filter((n): n is string => n !== undefined)\n );\n const liveUserIntents = [...intentNameToId.keys()].filter((n) => !isBuiltinIntent(n));\n // Live USER intents not in the declared set are out-of-band additions — deleted after the\n // per-intent loop (captured now, before create-missing mutates the map). The built-in\n // FallbackIntent is excluded on both sides, so it is never created or deleted.\n const extraIntentNames = liveUserIntents.filter((n) => !declaredIntentNames.has(n));\n // A declared USER intent missing from live was deleted out of band — recreate it before its\n // slots (CreateSlot needs the intent id). SlotPriorities are resolved in the UpdateIntent\n // below, once the slots exist.\n for (const di of declaredIntents) {\n const name = lexStr(di.Name);\n if (!name || isBuiltinIntent(name) || intentNameToId.has(name)) continue;\n const created = await c.send(\n new CreateIntentCommand({\n botId,\n botVersion,\n localeId,\n intentName: name,\n description: lexStr(di.Description),\n parentIntentSignature: lexStr(di.ParentIntentSignature),\n sampleUtterances: lexMapUtterances(di),\n } satisfies CreateIntentCommandInput)\n );\n const newId = lexStr(created.intentId);\n if (newId) intentNameToId.set(name, newId);\n }\n\n for (const di of declaredIntents) {\n const iName = lexStr(di.Name);\n const intentId = iName ? intentNameToId.get(iName) : undefined;\n if (!intentId || !iName || isBuiltinIntent(iName)) continue;\n\n // slots for this intent: name<->id, create missing / delete extra, then update each\n const liveSlots = await c.send(\n new ListSlotsCommand({ botId, botVersion, localeId, intentId })\n );\n const slotNameToId = new Map<string, string>();\n for (const s of liveSlots.slotSummaries ?? []) {\n const id = lexStr(s.slotId);\n const name = lexStr(s.slotName);\n if (id && name) slotNameToId.set(name, id);\n }\n const declaredSlots = Array.isArray(di.Slots) ? (di.Slots as LexRec[]) : [];\n const declaredSlotNames = new Set(\n declaredSlots.map((s) => lexStr(s.Name)).filter((n): n is string => n !== undefined)\n );\n // A declared slot missing from live was deleted out of band — recreate it (a slot always\n // has a valueElicitationSetting with a SlotConstraint; default to Optional when the declared\n // model omits it). The update loop below then converges the full declared content, and the\n // UpdateIntent resolves SlotPriorities against the now-complete slot map.\n for (const ds of declaredSlots) {\n const sName = lexStr(ds.Name);\n if (!sName || slotNameToId.has(sName)) continue;\n const declaredElic = ds.ValueElicitationSetting as LexRec | undefined;\n const elic: LexRec = { slotConstraint: lexStr(declaredElic?.SlotConstraint) ?? 'Optional' };\n const prompt = lexBuildPrompt(declaredElic?.PromptSpecification);\n if (prompt !== undefined) elic.promptSpecification = prompt;\n const created = await c.send(\n new CreateSlotCommand({\n botId,\n botVersion,\n localeId,\n intentId,\n slotName: sName,\n slotTypeId: resolveSlotTypeId(lexStr(ds.SlotTypeName)),\n description: lexStr(ds.Description),\n valueElicitationSetting: elic as unknown as SlotValueElicitationSetting,\n } satisfies CreateSlotCommandInput)\n );\n const newId = lexStr(created.slotId);\n if (newId) slotNameToId.set(sName, newId);\n }\n // Live slots not in the declared set are out-of-band additions — delete them (their intent\n // is kept, so they must be removed individually before the locale is rebuilt).\n for (const [name, slotId] of slotNameToId) {\n if (declaredSlotNames.has(name)) continue;\n await c.send(new DeleteSlotCommand({ botId, botVersion, localeId, intentId, slotId }));\n slotNameToId.delete(name);\n }\n\n for (const ds of declaredSlots) {\n const sName = lexStr(ds.Name);\n const slotId = sName ? slotNameToId.get(sName) : undefined;\n if (!slotId || !sName) continue;\n const live = await c.send(\n new DescribeSlotCommand({ botId, botVersion, localeId, intentId, slotId })\n );\n const declaredElic = ds.ValueElicitationSetting as LexRec | undefined;\n const liveElic = (live.valueElicitationSetting ?? {}) as LexRec;\n const elic: LexRec = { ...liveElic };\n if (declaredElic) {\n const constraint = lexStr(declaredElic.SlotConstraint);\n if (constraint !== undefined) elic.slotConstraint = constraint;\n const prompt = lexBuildPrompt(declaredElic.PromptSpecification);\n if (prompt !== undefined) elic.promptSpecification = prompt;\n }\n await c.send(\n new UpdateSlotCommand({\n botId,\n botVersion,\n localeId,\n intentId,\n slotId,\n slotName: sName,\n slotTypeId: resolveSlotTypeId(lexStr(ds.SlotTypeName)) ?? live.slotTypeId,\n description: lexStr(ds.Description) ?? live.description,\n obfuscationSetting: live.obfuscationSetting,\n multipleValuesSetting: live.multipleValuesSetting,\n subSlotSetting: live.subSlotSetting,\n // valueElicitationSetting is REQUIRED; a slot always has one (SlotConstraint).\n valueElicitationSetting: elic as unknown as SlotValueElicitationSetting,\n })\n );\n }\n\n // intent itself: overlay declared fields onto the live intent, resolve SlotPriorities.\n const live = await c.send(\n new DescribeIntentCommand({ botId, botVersion, localeId, intentId })\n );\n const slotPriorities = Array.isArray(di.SlotPriorities)\n ? (di.SlotPriorities as LexRec[])\n .map((p) => {\n const sid = slotNameToId.get(lexStr(p.SlotName) ?? '');\n return typeof p.Priority === 'number' && sid\n ? { priority: p.Priority, slotId: sid }\n : undefined;\n })\n .filter((x): x is { priority: number; slotId: string } => x !== undefined)\n : live.slotPriorities;\n await c.send(\n new UpdateIntentCommand({\n botId,\n botVersion,\n localeId,\n intentId,\n intentName: iName,\n description: lexStr(di.Description) ?? live.description,\n parentIntentSignature: lexStr(di.ParentIntentSignature) ?? live.parentIntentSignature,\n sampleUtterances: Array.isArray(di.SampleUtterances)\n ? (di.SampleUtterances as LexRec[])\n .map((u) => lexStr(u.Utterance))\n .filter((x): x is string => x !== undefined)\n .map((utterance) => ({ utterance }))\n : live.sampleUtterances,\n slotPriorities,\n // preserve un-projected live settings (code hooks, confirmation, contexts, …)\n dialogCodeHook: live.dialogCodeHook,\n fulfillmentCodeHook: live.fulfillmentCodeHook,\n intentConfirmationSetting: live.intentConfirmationSetting,\n intentClosingSetting: live.intentClosingSetting,\n inputContexts: live.inputContexts,\n outputContexts: live.outputContexts,\n kendraConfiguration: live.kendraConfiguration,\n initialResponseSetting: live.initialResponseSetting,\n })\n );\n }\n\n // --- deletes (reverse of create order so references resolve): extra USER intents first\n // (DeleteIntent cascades their slots), then the now-unreferenced extra custom slot types. ---\n for (const name of extraIntentNames) {\n const intentId = intentNameToId.get(name);\n if (intentId)\n await c.send(new DeleteIntentCommand({ botId, botVersion, localeId, intentId }));\n }\n for (const name of extraSlotTypeNames) {\n const slotTypeId = slotTypeNameToId.get(name);\n if (slotTypeId)\n await c.send(new DeleteSlotTypeCommand({ botId, botVersion, localeId, slotTypeId }));\n }\n\n // --- locale-level settings (Description / NluConfidenceThreshold / VoiceSettings) ---\n const liveLocale = await c.send(new DescribeBotLocaleCommand({ botId, botVersion, localeId }));\n const voice = loc.VoiceSettings as LexRec | undefined;\n await c.send(\n new UpdateBotLocaleCommand({\n botId,\n botVersion,\n localeId,\n description: lexStr(loc.Description) ?? liveLocale.description,\n // nluIntentConfidenceThreshold is REQUIRED; fall back to the live value.\n nluIntentConfidenceThreshold:\n typeof loc.NluConfidenceThreshold === 'number'\n ? loc.NluConfidenceThreshold\n : liveLocale.nluIntentConfidenceThreshold,\n voiceSettings: voice\n ? ({\n voiceId: lexStr(voice.VoiceId) ?? '',\n engine: lexStr(voice.Engine),\n } as VoiceSettings)\n : liveLocale.voiceSettings,\n } satisfies UpdateBotLocaleCommandInput)\n );\n\n // Rebuild the DRAFT locale so the reverted model is consistent (best-effort, bounded wait).\n await c.send(new BuildBotLocaleCommand({ botId, botVersion, localeId }));\n for (let i = 0; i < 30; i++) {\n const s = await c.send(new DescribeBotLocaleCommand({ botId, botVersion, localeId }));\n if (s.botLocaleStatus !== 'Building' && s.botLocaleStatus !== 'Processing') break;\n await new Promise((r) => setTimeout(r, 2000));\n }\n }\n};\n\nexport const SDK_WRITERS: Record<string, SdkWriter> = {\n 'AWS::CodeBuild::ReportGroup': writeCodeBuildReportGroup,\n 'AWS::DAX::Cluster': writeDaxCluster,\n 'AWS::DAX::ParameterGroup': writeDaxParameterGroup,\n 'AWS::EC2::ClientVpnEndpoint': writeEc2ClientVpnEndpoint,\n 'AWS::OpenSearchService::Domain': writeOpenSearchDomain,\n 'AWS::CloudFront::Distribution': writeCloudFrontDistribution,\n 'AWS::WAFv2::WebACL': writeWafv2WebAcl,\n 'AWS::Glue::Job': writeGlueJob,\n 'AWS::Glue::Table': writeGlueTable,\n 'AWS::Glue::Classifier': writeGlueClassifier,\n 'AWS::Glue::Workflow': writeGlueWorkflow,\n 'AWS::Glue::Connection': writeGlueConnection,\n 'AWS::SES::ReceiptRule': writeSesReceiptRule,\n 'AWS::CloudWatch::AnomalyDetector': writeCloudWatchAnomalyDetector,\n 'AWS::DLM::LifecyclePolicy': writeDlmLifecyclePolicy,\n 'AWS::Logs::MetricFilter': writeMetricFilter,\n 'AWS::Route53::RecordSet': writeRoute53RecordSet,\n 'AWS::DocDB::DBCluster': writeDocDbCluster,\n 'AWS::DocDB::DBInstance': writeDocDbInstance,\n 'AWS::ServiceDiscovery::HttpNamespace': writeServiceDiscoveryHttpNamespace,\n 'AWS::S3::BucketPolicy': writeS3BucketPolicy,\n 'AWS::SNS::TopicPolicy': writeSnsTopicPolicy,\n 'AWS::SQS::QueuePolicy': writeSqsQueuePolicy,\n 'AWS::Events::EventBusPolicy': writeEventBusPolicy,\n 'AWS::IAM::Policy': writeIamPolicy,\n 'AWS::IAM::ManagedPolicy': writeIamManagedPolicy,\n};\n\n// Property-scoped SDK writers: CC-writable types where ONE property must be\n// reverted via the type's own SDK instead of a Cloud Control patch. Keyed by\n// resource type -> EXACT top-level finding path. Deeper paths (e.g. a declared\n// drift at Policies.0...) still go through Cloud Control as before.\nexport const SDK_PROP_WRITERS: Record<string, Record<string, SdkWriter>> = {\n 'AWS::Cognito::IdentityPool': { CognitoEvents: writeCognitoIdentityPoolEvents },\n 'AWS::Config::ConfigRule': { InputParameters: writeConfigRuleInputParameters },\n 'AWS::MSK::Configuration': { ServerProperties: writeMskConfiguration },\n 'AWS::IAM::Role': { Policies: writeIamRoleInlinePolicies },\n 'AWS::Logs::LogGroup': { BearerTokenAuthenticationEnabled: writeLogGroupBearerTokenAuth },\n 'AWS::ElasticLoadBalancingV2::LoadBalancer': {\n LoadBalancerAttributes: writeElbLoadBalancerAttributes,\n },\n 'AWS::ElasticLoadBalancingV2::TargetGroup': {\n TargetGroupAttributes: writeElbTargetGroupAttributes,\n },\n};\n\n// Re-point an RFC6902 pointer's IDENTITY-bracket array segments (`/Prop[<id>]/sub`, which\n// Cloud Control would read as a literal key named `Prop[<id>]`) to the matching LIVE-array\n// INDEX (`/Prop/<index>/sub`, a valid pointer CC applies read-modify-write). The index is\n// located by the array's identity field (NESTED_ARRAY_IDENTITY override, else the generic\n// identityField) against the live model — the SAME model CC will read-modify-write, so the\n// index aligns. This is why an array-element nested value IS revertable via CC after all\n// (R78 abandoned index patches against the DECLARED subset, whose indices differ from live;\n// here we index the LIVE array). Throws if a segment can't be located → an honest revert\n// failure, never a wrong write.\nfunction reindexNestedPointer(\n pointer: string,\n live: Record<string, unknown>,\n resourceType: string\n): string {\n const out: string[] = [];\n let node: unknown = live;\n let dotted = '';\n for (const raw of pointer.split('/').slice(1)) {\n const seg = raw.replace(/~1/g, '/').replace(/~0/g, '~');\n const m = seg.match(/^(.+)\\[(.+)\\]$/);\n if (m) {\n const prop = m[1] as string;\n const id = m[2] as string;\n const arrPath = dotted ? `${dotted}.${prop}` : prop;\n const arr =\n node && typeof node === 'object' ? (node as Record<string, unknown>)[prop] : undefined;\n if (!Array.isArray(arr)) throw new Error(`cannot resolve array \"${arrPath}\" for ${pointer}`);\n const idField = NESTED_ARRAY_IDENTITY[resourceType]?.[arrPath] ?? identityField(arr);\n const idx = idField\n ? arr.findIndex(\n (el) =>\n el &&\n typeof el === 'object' &&\n String((el as Record<string, unknown>)[idField]) === id\n )\n : -1;\n if (idx < 0) throw new Error(`cannot locate ${arrPath}[${id}] in live ${resourceType}`);\n out.push(ptrEscape(prop), String(idx));\n node = arr[idx];\n dotted = arrPath;\n } else {\n out.push(ptrEscape(seg));\n node = node && typeof node === 'object' ? (node as Record<string, unknown>)[seg] : undefined;\n dotted = dotted ? `${dotted}.${seg}` : seg;\n }\n }\n return `/${out.join('/')}`;\n}\n\n// Revert an array-element nested value (e.g. Backup BackupPlanRule[<RuleName>].window,\n// Route53Resolver FirewallRules[<Priority>].setting) via Cloud Control: GetResource for the\n// live model, re-point each op's identity-bracket to the live-array index (reindexNestedPointer),\n// then one UpdateResource. CC-mutable types only (Backup / Route53Resolver) — proven live.\nconst writeCloudControlIndexNested: SdkWriter = async (ctx, ops) => {\n const type = ctx.resourceType;\n if (!type) throw new Error('writeCloudControlIndexNested: resourceType missing on ctx');\n // Address the resource by the resolved Cloud Control identifier (the composite the READ\n // path builds via CC_IDENTIFIER_ADAPTERS — e.g. AWS::ApiGateway::Stage `RestApiId|\n // StageName`), not the bare CFn physical id, or CC ValidationExceptions. Falls back to the\n // physical id when no adapter applies (single-segment types: Backup plan, Route53 group).\n const identifier = ctx.identifier ?? ctx.physicalId;\n const cc = new CloudControlClient({ region: ctx.region });\n const got = await cc.send(new GetResourceCommand({ TypeName: type, Identifier: identifier }));\n const live = JSON.parse(got.ResourceDescription?.Properties ?? '{}') as Record<string, unknown>;\n const patch = ops.map((op) => {\n const path = reindexNestedPointer(op.path, live, type);\n return op.op === 'remove' ? { op: op.op, path } : { op: op.op, path, value: op.value };\n });\n await cc.send(\n new UpdateResourceCommand({\n TypeName: type,\n Identifier: identifier,\n PatchDocument: JSON.stringify(patch),\n })\n );\n};\n\n// SDK writers for NESTED finding paths (a sub-key inside a declared object — dotted or\n// array-element). Unlike SDK_PROP_WRITERS, which keys on an EXACT top-level finding path,\n// these match by PREDICATE because the targetable knob is deep (e.g. an ApiGateway Method's\n// Integration.IntegrationResponses[<statusCode>].SelectionPattern). A matching nested path is\n// (a) exempt from the \"nested undeclared is record-only\" revert bar (plan.ts) and (b) routed\n// to the writer, which translates each op to the type's native granular API.\nexport interface NestedWriterSpec {\n match: (path: string) => boolean;\n writer: SdkWriter;\n}\nexport const SDK_NESTED_WRITERS: Record<string, NestedWriterSpec> = {\n 'AWS::ApiGateway::Method': {\n match: isApiGatewayMethodKnobPath,\n writer: writeApiGatewayMethod,\n },\n // Any drift UNDER the writeOnly ServiceConnectConfiguration / VolumeConfigurations\n // re-supplies the whole declared prop via ecs:UpdateService (CC cannot sub-path patch\n // a writeOnly prop).\n 'AWS::ECS::Service': {\n match: (p) =>\n p === 'ServiceConnectConfiguration' ||\n p.startsWith('ServiceConnectConfiguration.') ||\n p === 'VolumeConfigurations' ||\n p.startsWith('VolumeConfigurations.') ||\n p.startsWith('VolumeConfigurations['),\n writer: writeEcsServiceWriteOnlyProps,\n },\n // Array-element nested rule settings (keyed by RuleName / Priority — descended via\n // NESTED_ARRAY_IDENTITY). CC-mutable, so revert via the generic Cloud Control index-revert:\n // the identity bracket is re-pointed to the live-array index, which CC applies. Proven live.\n 'AWS::Backup::BackupPlan': {\n match: (p) => p.startsWith('BackupPlan.BackupPlanRule['),\n writer: writeCloudControlIndexNested,\n },\n 'AWS::Route53Resolver::FirewallRuleGroup': {\n match: (p) => p.startsWith('FirewallRules['),\n writer: writeCloudControlIndexNested,\n },\n // A multi-region secret's replica KmsKeyId (keyed by Region — descended via\n // NESTED_ARRAY_IDENTITY). CC-mutable, so revert re-points the identity bracket to the\n // live-array index. Proven live.\n 'AWS::SecretsManager::Secret': {\n match: (p) => p.startsWith('ReplicaRegions['),\n writer: writeCloudControlIndexNested,\n },\n // A REST API stage's per-method caching/metrics knobs (keyed by HttpMethod — descended\n // via NESTED_ARRAY_IDENTITY). CC-mutable, so revert re-points the identity bracket to the\n // live-array index. Proven live.\n 'AWS::ApiGateway::Stage': {\n match: (p) => p.startsWith('MethodSettings['),\n writer: writeCloudControlIndexNested,\n },\n // Any drift UNDER the writeOnly BotLocales (an utterance / slot / slot-type / prompt edit, OR a\n // whole intent / slot / slot type added or removed out of band) re-supplies the DECLARED\n // conversational model via the lexv2-models write APIs — CC cannot write the writeOnly prop. It\n // updates existing nodes and creates/deletes structurally-diverged ones (see writeLexBotLocales).\n // #553 (update-only) + #564 (structural create/delete).\n 'AWS::Lex::Bot': {\n match: (p) => p === 'BotLocales' || p.startsWith('BotLocales.') || p.startsWith('BotLocales['),\n writer: writeLexBotLocales,\n },\n};\n\n// dotted finding path for a revert op's RFC6902 pointer (`/A/B[x]/c` -> `A.B[x].c`).\nfunction pointerToDotted(pointer: string): string {\n return pointer\n .split('/')\n .slice(1)\n .map((s) => s.replace(/~1/g, '/').replace(/~0/g, '~'))\n .join('.');\n}\n\n/** Resolve the SDK writer for a kind='sdk' revert item: the whole-type writer, the\n * property-scoped writer matching the item's ops (all ops in a prop-scoped item share one\n * top-level pointer — plan.ts groups by exact finding path), or a nested-path writer whose\n * predicate matches the ops' (deep) finding path. */\nexport function resolveSdkWriter(resourceType: string, ops: PatchOp[]): SdkWriter | undefined {\n const whole = SDK_WRITERS[resourceType];\n if (whole) return whole;\n const byProp = SDK_PROP_WRITERS[resourceType];\n const top = ops[0]?.path.split('/')[1]?.replace(/~1/g, '/').replace(/~0/g, '~');\n if (byProp && top && byProp[top]) return byProp[top];\n const nested = SDK_NESTED_WRITERS[resourceType];\n if (nested && ops[0] && nested.match(pointerToDotted(ops[0].path))) return nested.writer;\n return undefined;\n}\n","// Build a revert plan from drift findings (pure — no AWS). Revert writes the\n// DESIRED value back to AWS:\n// declared drift -> the deployed-template value (finding.desired)\n// undeclared drift -> the baseline value if recorded before (restore), else\n// REMOVE (the value appeared since a snapshot-complete record)\n// removed-undeclared (baseline value gone) -> re-add the baseline value\n// UNRECORDED values (R62: no baseline entry, resource never snapshot-complete)\n// are not drift and have no revert target — notRevertable unless\n// --remove-unrecorded explicitly turns them into REMOVE ops.\n// Not revertable: readGap / unresolved / skipped, and (v1) the SDK-override\n// CC-gap types (revert for those is a follow-up).\nimport type { BaselineFile } from '../baseline/baseline-file.js';\nimport { withinStackPath } from '../construct-path.js';\nimport { hasUnresolved, UNRESOLVED } from '../normalize/intrinsic-resolver.js';\nimport {\n awsManagedTags,\n JSON_STRING_PROPS,\n KNOWN_DEFAULT_PATHS,\n KNOWN_DEFAULTS,\n} from '../normalize/noise.js';\nimport { SDK_OVERRIDES } from '../read/overrides.js';\nimport type { Finding, SchemaInfo } from '../types.js';\nimport { SDK_NESTED_WRITERS, SDK_PROP_WRITERS, SDK_WRITERS } from './writers.js';\n\n// Per type, the writeOnly props that an SDK_SUPPLEMENTS reader makes COMPARABLE\n// (detection works) but Cloud Control still cannot revert via a nested sub-path patch\n// (CC can't navigate into a writeOnly prop it can't read) AND no type-specific SDK\n// writer covers yet. Findings under these paths are reported not-revertable instead of\n// emitting a CC patch that always fails. (ECS `ServiceConnectConfiguration` GRADUATED\n// out of this table — it now reverts via the `SDK_NESTED_WRITERS` UpdateService writer.\n// ECS `VolumeConfigurations` will populate it once that prop is projected.)\n// (AWS::MSK::Configuration `ServerProperties` GRADUATED out of this table — it now reverts\n// via the `SDK_PROP_WRITERS` kafka:UpdateConfiguration writer, which creates the next\n// revision carrying the desired properties.)\nconst WRITEONLY_NESTED_NO_CC_REVERT: Record<string, readonly string[]> = {};\n\n// Per type, SYNTHETIC top-level fields an SDK_SUPPLEMENTS reader COMPUTES (not real AWS\n// properties) as an integrity signal for a value that is otherwise unreadable — currently\n// AWS::ElasticLoadBalancingV2::TrustStore `CaCertificatesBundleSha256`, a digest of the live\n// CA bundle content (#505). They surface as undeclared drift that `record` snapshots (so a\n// later content swap re-surfaces), but they have no write target, so a revert on one is\n// reported not-revertable rather than emitting a `remove` that always fails.\nconst SYNTHETIC_READ_SIGNAL_PATHS: Record<string, readonly string[]> = {\n 'AWS::ElasticLoadBalancingV2::TrustStore': ['CaCertificatesBundleSha256'],\n};\n\n// SDK-override types that are nonetheless Cloud Control FULLY_MUTABLE — their override\n// exists only to work around a READ quirk, NOT because CC cannot UPDATE them, so a CC\n// UpdateResource revert is valid and they are EXEMPT from the \"read-override => not\n// revertable\" rule below. AWS::Scheduler::Schedule is the case: its CC read handler\n// only looks in the DEFAULT schedule group (the override reads via Scheduler\n// GetSchedule with the declared GroupName), but CC can update it fine. Verified live —\n// a schedule State revert via CC succeeds for the common default-group case. (A\n// non-default-group schedule would fail at apply with a clear AWS error, not silently.)\n// AWS::Cognito::IdentityPool: the override exists only to ENRICH the CC read with the\n// writeOnly CognitoEvents (CC reads/updates every base property — AllowClassicFlow,\n// providers, … — fine). So base-property reverts route through CC UpdateResource as\n// normal; only the CognitoEvents path takes its dedicated SDK_PROP_WRITER.\nconst CC_REVERTABLE_DESPITE_READ_OVERRIDE = new Set<string>([\n 'AWS::Scheduler::Schedule',\n 'AWS::Cognito::IdentityPool',\n]);\n\n// Properties whose undeclared \"appeared since record\" revert must EXPLICITLY write the\n// AWS default value (an `add` of KNOWN_DEFAULTS[type][path]) instead of an RFC6902\n// `remove`. The default revert for such a value is `remove`, which for most types makes\n// the provider clear the property (IAM Role Description -> \"\", Tags -> untagged) or\n// delete a sub-config that AWS then re-defaults (S3 DeleteBucketOwnershipControls,\n// VersioningConfiguration -> Suspended). But a handful of providers leave the property\n// UNCHANGED when it is simply absent from the desired model — so `remove` is a SILENT\n// no-op (Cloud Control reports SUCCESS yet the live value persists). IAM's UpdateRole is\n// the proven case: it ignores a missing MaxSessionDuration, so reverting an out-of-band\n// 7200 back toward the 3600 default never converged. For these, write the known default\n// explicitly. Keyed `${resourceType}\\0${propertyPath}`; the value comes from the same\n// KNOWN_DEFAULTS table (single source of truth), so an entry here without a matching\n// KNOWN_DEFAULTS default falls through to `remove`. Curated rather than \"every\n// KNOWN_DEFAULTS entry\" on purpose: KNOWN_DEFAULTS holds read-side COMPARE shapes (some\n// projected/normalized, not valid CC write inputs), and most entries already converge\n// via `remove` — broadening blindly would regress them and risk writing an unwritable\n// shape. Add a property here only once a `remove` no-op is observed for it.\n// - AWS::Lambda::Alias Description: UpdateAlias ignores an OMITTED description (keeps\n// the existing value), so a bare `remove` is a silent no-op — Cloud Control reports\n// SUCCESS yet the live description persists. Writing the empty-string default (an\n// `add /Description \"\"`) clears it. Both behaviours proven live.\nconst REVERT_SET_DEFAULT_PATHS = new Set<string>([\n 'AWS::IAM::Role\\0MaxSessionDuration',\n 'AWS::Lambda::Alias\\0Description',\n // Cognito UpdateIdentityPool ignores an omitted AllowClassicFlow (live-observed: a\n // `remove` revert of an out-of-band `true` is a silent no-op), so write the `false`\n // default explicitly.\n 'AWS::Cognito::IdentityPool\\0AllowClassicFlow',\n]);\n\n/**\n * A nested undeclared value (a live sub-key inside a declared object, R96/R98) — a dotted\n * path (`Conf.Destination`) or an identity-keyed array element (`Prop[<id>].sub`). Pure +\n * exported. Detected by PATH SHAPE, not just `Finding.nested`: a baseline value removed\n * since record is reconstructed without the flag but keeps its nested path. A top-level\n * undeclared path is a single key (no '.'/'[').\n */\nexport function isNestedUndeclared(f: Finding): boolean {\n return (\n f.tier === 'undeclared' && (Boolean(f.nested) || f.path.includes('.') || f.path.includes('['))\n );\n}\n\n/**\n * Of the nested undeclared values, the ones revert genuinely CANNOT target: an ARRAY\n * ELEMENT path (it contains a `[<id>]`/`[<index>]` bracket). `toPointer` builds an RFC6902\n * pointer by splitting on '.', so a bracket survives as a literal segment (`/Prop[<id>]/sub`)\n * that addresses a key named `Prop[<id>]`, not the array element — the patch is malformed\n * (the same reason R78 abandoned index-based array patches). A PURE-DOTTED nested path\n * (`Environment.Variables.<key>` free-form map keys, or a sub-field of a declared object)\n * IS a valid pointer that Cloud Control applies read-modify-write — proven live removing an\n * out-of-band Lambda env var — so it stays revertable. That INCLUDES a MAP-shaped tag key\n * (`Tags.<key>`, e.g. AWS::SSM::Parameter): a single-key `remove /Tags/<key>` is proven live\n * to succeed AND leave the live `aws:*` managed tags untouched (Cloud Control's read-modify-\n * write keeps every other key, so the provider never untags the managed ones — no rewrite\n * needed). A LIST-shaped tag element (`Tags[<id>].sub`) stays barred by the bracket rule.\n * Pure + exported so the action picker offers `revert` exactly where revert can run.\n */\nexport function isUnrevertableNested(f: Finding): boolean {\n return isNestedUndeclared(f) && f.path.includes('[');\n}\n\n// An out-of-band ManagedPolicy attachment member (a live-only `Roles[x]`/`Users[x]`/\n// `Groups[x]` — the union, surfaced as nested undeclared). Unlike a generic nested\n// undeclared value, this one HAS a precise, flat SDK op to undo it (DetachX-Policy by\n// member), so writeIamManagedPolicy can revert it exactly — it is NOT subject to the\n// \"nested undeclared is record-only\" bar (which exists because a flat patch can't\n// safely target a deep sub-field). Removal still requires --remove-unrecorded like any\n// unrecorded undeclared value (the unrecorded guard below), so it never auto-detaches.\nexport function isManagedPolicyAttachmentMember(f: Finding): boolean {\n return (\n f.tier === 'undeclared' &&\n f.resourceType === 'AWS::IAM::ManagedPolicy' &&\n /^(Roles|Users|Groups)\\[.+\\]$/.test(f.path)\n );\n}\n\n// A nested finding path a type-specific SDK writer can revert PRECISELY (SDK_NESTED_WRITERS) —\n// e.g. an ApiGateway Method's Integration.IntegrationResponses[<sc>].SelectionPattern. Like\n// isManagedPolicyAttachmentMember, it lifts the path off the \"nested undeclared is\n// record-only\" bar (which exists only because a flat RFC6902 patch can't target a deep\n// sub-field) and routes it to the writer instead of Cloud Control.\nexport function isNestedSdkWritable(f: Finding): boolean {\n return SDK_NESTED_WRITERS[f.resourceType]?.match(f.path) ?? false;\n}\n\nexport interface PatchOp {\n op: 'add' | 'remove';\n path: string; // RFC6902 JSON pointer into the resource Properties model\n value?: unknown;\n // the finding's CURRENT live value, for property-scoped SDK writers that revert\n // per entry (e.g. IAM Role inline Policies). Never serialized to Cloud Control\n // (toPatchDocument picks op/path/value only).\n prior?: unknown;\n // R78: the Key of a changed attribute inside an ELB attribute bag. Set only for\n // attribute-bag findings; the SDK writer sends `{Key, Value: value}` via\n // ModifyLoadBalancerAttributes. Never serialized to Cloud Control.\n attributeKey?: string;\n human: string; // one-line description for the plan display\n}\n\nexport interface RevertItem {\n logicalId: string;\n displayId: string; // construct path or logical id\n resourceType: string;\n physicalId: string;\n // cc = Cloud Control UpdateResource; sdk = type-specific SDK writer;\n // delete = Cloud Control DeleteResource (revert of an `added` out-of-band resource).\n kind: 'cc' | 'sdk' | 'delete';\n ops: PatchOp[]; // for `delete`: a single pseudo-op carrying the human label (never serialized)\n}\n\nexport interface NotRevertable {\n displayId: string;\n resourceType: string;\n path: string;\n reason: string;\n}\n\nexport interface RevertPlan {\n items: RevertItem[];\n notRevertable: NotRevertable[];\n}\n\n// dotted finding path (\"A.B.0.C\") -> RFC6902 JSON pointer (\"/A/B/0/C\")\nfunction toPointer(dotted: string): string {\n return (\n '/' +\n dotted\n .split('.')\n .map((s) => s.replace(/~/g, '~0').replace(/\\//g, '~1'))\n .join('/')\n );\n}\n\nconst DRIFT_TIERS = new Set(['declared', 'undeclared']);\n\n// SecurityGroup rule property -> the buildSiblingSgRules side key, for the sibling-rule\n// merge below (see RevertOptions.siblingSgRules).\nconst SG_REVERT_SIDE: Record<string, 'ingress' | 'egress'> = {\n SecurityGroupIngress: 'ingress',\n SecurityGroupEgress: 'egress',\n};\n\nexport interface RevertOptions {\n // UNRECORDED undeclared values are removed only if this is set. Without it they\n // are reported as notRevertable (a bulk REMOVE of every undecided value that\n // slipped through noise subtraction would be destructive — fail-safe instead).\n removeUnrecorded?: boolean;\n // resourceType -> schema, so create-only property drift is reported as\n // notRevertable up front (an in-place patch would fail at apply time).\n schemas?: Map<string, SchemaInfo>;\n // The stack name — used to strip the stack/Stage prefix off each finding's construct path\n // for display (`withinStackPath`), matching what `cdkrd check` shows. Absent (unit calls) =\n // no strip, the full construct path.\n stackName?: string;\n // Rules declared by sibling standalone SecurityGroupIngress/Egress resources, keyed by the\n // SG's physical id. Reverting an AWS::EC2::SecurityGroup's SecurityGroupIngress/Egress is a\n // whole-array Cloud Control replacement; the live SG REFLECTS these sibling-declared rules,\n // so a revert built from only the inline declared rules would DELETE them (silent data loss\n // — a self-ref / peer / prefix-list rule wiped). Merge them back into the revert value so\n // CC preserves them. Same shape classify uses to subtract them (buildSiblingSgRules).\n siblingSgRules?: Record<string, { ingress: unknown[]; egress: unknown[] }>;\n}\n\n// True when a finding path is AT or UNDER any create-only schema path. The schema's\n// `createOnlyPaths` are full dotted paths with `*` wildcards (e.g. `EncryptionConfiguration\n// .KmsKey`, `PosixUser.*`, `Foo.*.Bar`); a finding's array-index segments (`[id]` or a\n// numeric `.0`) align with those `*`. Segment-wise PREFIX membership, so a NESTED\n// create-only property (parent mutable) is caught — the previous top-level-only check\n// (`createOnly.has(firstSegment)`) missed those, and a `revert` then built an in-place\n// patch that AWS rejects only at apply time (e.g. ECR `EncryptionConfiguration.KmsKey`,\n// EFS AccessPoint `PosixUser.*`).\nfunction pathSegments(path: string): string[] {\n return path\n .replace(/\\[[^\\]]*\\]/g, '.*')\n .split('.')\n .filter((s) => s.length > 0);\n}\nfunction isUnderCreateOnly(findingPath: string, createOnlyPaths: readonly string[]): boolean {\n const f = pathSegments(findingPath);\n for (const co of createOnlyPaths) {\n const c = co.split('.');\n // Block when EITHER path is a prefix of the other (segment-wise; a `*` on either\n // side is a wildcard):\n // - create-only path ⊆ finding path: the finding IS, or is nested under, a\n // create-only property — an in-place patch on it is rejected (the nested\n // create-only fix);\n // - finding path ⊆ create-only path: the finding is a PARENT of a create-only\n // property. drift-calculator emits a finding at the PARENT path for a\n // length-/shape-changed array or object, so reverting it rewrites the whole\n // subtree — INCLUDING the create-only descendant — which AWS also rejects as a\n // replacement. Without this the revert proceeded and failed only at apply time\n // (e.g. a length change in an object array whose elements carry a create-only\n // sub-field, like EFS AccessPoint PosixUser under a replaced parent).\n const common = Math.min(c.length, f.length);\n let match = true;\n for (let i = 0; i < common; i++) {\n if (c[i] !== '*' && f[i] !== '*' && c[i] !== f[i]) {\n match = false;\n break;\n }\n }\n if (match) return true;\n }\n return false;\n}\n\nexport function buildRevertPlan(\n findings: Finding[],\n baseline: BaselineFile | undefined,\n opts: RevertOptions = {}\n): RevertPlan {\n const itemsByLogical = new Map<string, RevertItem>();\n const notRevertable: NotRevertable[] = [];\n const recorded = baseline?.recorded ?? [];\n\n for (const f of findings) {\n // Show the construct path WITHIN the stack (stack/Stage prefix stripped), the same as the\n // check report — the revert banner already names the stack. Full path when unstripped.\n const displayId = f.constructPath\n ? withinStackPath(f.constructPath, opts.stackName ?? '')\n : f.logicalId;\n if (f.tier === 'deleted') {\n // a resource deleted out of band cannot be patched back — it must be\n // recreated by re-deploying the stack.\n notRevertable.push({\n displayId,\n resourceType: f.resourceType,\n path: f.path,\n reason: 'deleted — recreate via cdk deploy',\n });\n continue;\n }\n if (f.tier === 'added') {\n // PR4: an UNRECORDED added resource (no baseline entry — the user has not decided\n // on it) is excluded from the default plan, exactly like an unrecorded undeclared\n // value: a default revert would DELETE it (the destructive mirror of the\n // subtractive model). Refuse unless --remove-unrecorded; the fork is the same —\n // record it if the live resource should stay, --remove-unrecorded to delete it.\n if (f.unrecorded && !opts.removeUnrecorded) {\n notRevertable.push({\n displayId,\n resourceType: f.resourceType,\n path: f.path,\n reason:\n 'unrecorded — record it if the live resource is right, or --remove-unrecorded to delete it',\n });\n continue;\n }\n // an out-of-band resource (not in the template) is reverted by DELETING it via\n // Cloud Control DeleteResource. f.physicalId is the CC identifier (the composite\n // `RestApiId|ResourceId[|HttpMethod]`). Modeled as a `delete`-kind item carrying a\n // single pseudo-op so the picker / count / filter machinery (which is op-based)\n // works unchanged; the apply path branches on kind and never serializes the op.\n if (!f.physicalId) {\n notRevertable.push({\n displayId,\n resourceType: f.resourceType,\n path: f.path,\n reason: 'no physical id',\n });\n continue;\n }\n itemsByLogical.set(f.logicalId, {\n logicalId: f.logicalId,\n displayId,\n resourceType: f.resourceType,\n physicalId: f.physicalId,\n kind: 'delete',\n ops: [\n {\n op: 'remove',\n path: '',\n human: `DELETE out-of-band ${f.resourceType} (not in your template)`,\n },\n ],\n });\n continue;\n }\n // A nested undeclared value whose path addresses an ARRAY ELEMENT (`Prop[<id>].sub`)\n // is detect/record-only, NOT revertable: `toPointer` builds a flat RFC6902 pointer by\n // splitting on '.', so the bracket survives as a literal segment (`/Prop[<id>]/sub`)\n // that targets a key named `Prop[<id>]`, not the array element — a malformed patch (the\n // same reason R78 abandoned index-based array patches). A PURE-DOTTED nested path\n // (`Environment.Variables.<key>` free-form map keys, or a sub-field of a declared\n // object) IS a valid pointer that Cloud Control applies read-modify-write (proven live\n // removing an out-of-band Lambda env var), so it falls through to the normal revert\n // below. Detect by PATH SHAPE, not Finding.nested: a baseline value REMOVED since\n // record is reconstructed (baseline-file.ts) WITHOUT the flag, but keeps its nested\n // path. A top-level undeclared path is a single key (never contains '.'/'['), and\n // declared drift is a different tier — so this never blocks a top-level revert.\n if (isUnrevertableNested(f) && !isManagedPolicyAttachmentMember(f) && !isNestedSdkWritable(f)) {\n notRevertable.push({\n displayId,\n resourceType: f.resourceType,\n path: f.path,\n reason: 'nested undeclared array-element value — detect/record only, not revertable',\n });\n continue;\n }\n if (!DRIFT_TIERS.has(f.tier)) continue; // only declared/undeclared are drift to revert\n // A SYNTHETIC integrity signal an SDK_SUPPLEMENTS reader computes (ELBv2 TrustStore\n // `CaCertificatesBundleSha256`, a digest of the live CA bundle content — #505) is not a\n // real AWS property, so it has no write target: a `remove` would fail. It exists only to\n // re-surface an out-of-band content swap as recordable undeclared drift; report it\n // detect/record-only.\n if (SYNTHETIC_READ_SIGNAL_PATHS[f.resourceType]?.includes(f.path)) {\n notRevertable.push({\n displayId,\n resourceType: f.resourceType,\n path: f.path,\n reason: 'read-only integrity signal — detect/record only, not revertable',\n });\n continue;\n }\n if (!f.physicalId) {\n notRevertable.push({\n displayId,\n resourceType: f.resourceType,\n path: f.path,\n reason: 'no physical id',\n });\n continue;\n }\n // CC-gap types are revertable only when we have a type-specific SDK writer — UNLESS\n // the override is a mere READ workaround on a CC-mutable type (see the set above),\n // in which case a CC UpdateResource revert is valid and we fall through to it.\n if (\n SDK_OVERRIDES[f.resourceType] &&\n !SDK_WRITERS[f.resourceType] &&\n !CC_REVERTABLE_DESPITE_READ_OVERRIDE.has(f.resourceType)\n ) {\n notRevertable.push({\n displayId,\n resourceType: f.resourceType,\n path: f.path,\n reason: 'type not revertable yet',\n });\n continue;\n }\n // UNRECORDED values (R62): the user never decided on them, so a default plan\n // would otherwise REMOVE every such value (the subtractive model's failure\n // mode is \"check is noisy\", but the revert mirror of that is destructive).\n // Refuse unless --remove-unrecorded. Evaluated BEFORE the create-only guard\n // (R35): the fundamental blocker is \"no revert target exists\".\n // The reason wording is a FORK, not a sequence (R55): \"record first, then\n // revert\" reads as if record were a step toward reverting THESE values, but\n // recording them endorses them (they leave the report entirely) — record is\n // for values that are RIGHT; --remove-unrecorded is for values that are WRONG.\n if (f.tier === 'undeclared' && f.unrecorded && !opts.removeUnrecorded) {\n notRevertable.push({\n displayId,\n resourceType: f.resourceType,\n path: f.path,\n reason:\n 'unrecorded — record it if the live value is right, or --remove-unrecorded to remove it',\n });\n continue;\n }\n // create-only property: an in-place UpdateResource patch would be rejected (the\n // change needs a replacement) — report it now instead of failing at apply time.\n const schema = opts.schemas?.get(f.resourceType);\n if (schema && isUnderCreateOnly(f.path, schema.createOnlyPaths)) {\n notRevertable.push({\n displayId,\n resourceType: f.resourceType,\n path: f.path,\n reason: 'create-only property — change requires resource replacement',\n });\n continue;\n }\n // AWS::SSM::Parameter Tier: AWS forbids an advanced->standard downgrade via\n // PutParameter (\"You can't downgrade a parameter from the advanced-parameter tier\n // to the standard-parameter tier\" — live-proven), so reverting an out-of-band Tier\n // UPGRADE (the common case) would always fail at apply. Report it not-revertable\n // instead. The reverse (declared Advanced, restore an upgrade) is allowed and stays\n // revertable. Detection still works.\n if (\n f.resourceType === 'AWS::SSM::Parameter' &&\n f.path === 'Tier' &&\n f.actual === 'Advanced' &&\n f.desired !== 'Advanced'\n ) {\n notRevertable.push({\n displayId,\n resourceType: f.resourceType,\n path: f.path,\n reason:\n 'SSM advanced-tier parameter cannot be downgraded to standard via update — delete and recreate it',\n });\n continue;\n }\n // R111: an IAM Role whose sibling AWS::IAM::Policy names could NOT be resolved\n // statically keeps the sibling-managed (DefaultPolicy) entries in its live\n // Policies array — classify could not separate them, and marked this finding\n // accordingly. The per-entry writer (writeIamRoleInlinePolicies) deletes every\n // prior entry the declared set drops, so reverting here would DELETE a managed\n // inline policy, removing real IAM grants. Refuse rather than wrong-write.\n if (f.siblingPolicyNames === 'unresolved') {\n notRevertable.push({\n displayId,\n resourceType: f.resourceType,\n path: f.path,\n reason:\n 'inline policies are managed by a sibling AWS::IAM::Policy whose name could not be resolved — reverting could delete a managed policy',\n });\n continue;\n }\n // property-scoped SDK writers match the EXACT top-level finding path only\n // (deeper paths keep going through Cloud Control); a resource can therefore\n // split into one cc item and one sdk item per scoped path — key the grouping\n // by kind (+ path when prop-scoped) so each item resolves to ONE writer.\n const propScoped =\n !SDK_WRITERS[f.resourceType] && SDK_PROP_WRITERS[f.resourceType]?.[f.path] !== undefined;\n // A nested-path SDK writer (SDK_NESTED_WRITERS) reverts a DEEP sub-field its predicate\n // matches (e.g. ApiGateway Method integration knobs). Unlike propScoped, every matching\n // nested op of one resource batches into ONE sdk item (no path suffix in the key below) —\n // the writer translates them to the type's native granular API in one or few calls.\n const nestedScoped = !SDK_WRITERS[f.resourceType] && !propScoped && isNestedSdkWritable(f);\n // A JSON-string property (JSON_STRING_PROPS) can NEVER be reverted via Cloud Control:\n // CC re-serializes the JSON it stores into the provider's string field with spaces,\n // which the provider rejects (Config: \"Blank spaces are not acceptable\") — proven live.\n // So it MUST route to an SDK writer that writes the compact JSON string directly; if no\n // writer covers it, refuse rather than emit a CC patch that always fails at apply.\n if (\n JSON_STRING_PROPS[f.resourceType]?.has(f.path) &&\n !propScoped &&\n !SDK_WRITERS[f.resourceType]\n ) {\n notRevertable.push({\n displayId,\n resourceType: f.resourceType,\n path: f.path,\n reason:\n 'JSON-string property — revert needs a type-specific SDK writer (not available yet)',\n });\n continue;\n }\n // A writeOnly property an SDK_SUPPLEMENTS reader makes COMPARABLE (so drift on it is\n // detected) but that Cloud Control still cannot sub-path patch: CC cannot navigate\n // INTO a writeOnly prop it can't read, so an `add` at a nested path (e.g. ECS\n // ServiceConnectConfiguration.Services.0.ClientAliases.0.DnsName) is rejected (\"can\n // only be updated using 'add' operation\") — only re-supplying the WHOLE top-level\n // prop works, which needs the full declared value threaded to a type-specific SDK\n // writer. Until that writer exists, report it not-revertable rather than emit a CC\n // patch that always fails at apply. Detection still works.\n if (\n WRITEONLY_NESTED_NO_CC_REVERT[f.resourceType]?.some(\n (p) => f.path === p || f.path.startsWith(`${p}.`)\n ) &&\n !SDK_WRITERS[f.resourceType] &&\n !propScoped &&\n !nestedScoped\n ) {\n notRevertable.push({\n displayId,\n resourceType: f.resourceType,\n path: f.path,\n reason:\n 'writeOnly nested property — Cloud Control cannot patch a sub-path; revert needs a type-specific SDK writer (not available yet)',\n });\n continue;\n }\n const kind: RevertItem['kind'] =\n SDK_WRITERS[f.resourceType] || propScoped || nestedScoped ? 'sdk' : 'cc';\n\n // Reverting an SG's reflected SecurityGroupIngress/Egress is a whole-array CC replacement;\n // merge back the rules declared by sibling standalone SG-rule resources (which the live SG\n // reflects but the inline declared value omits) so the replacement does not DELETE them.\n let toRevert = f;\n const sgSide =\n f.tier === 'declared' && f.resourceType === 'AWS::EC2::SecurityGroup'\n ? SG_REVERT_SIDE[f.path]\n : undefined;\n if (sgSide && Array.isArray(f.desired) && f.physicalId) {\n const sib = opts.siblingSgRules?.[f.physicalId]?.[sgSide] ?? [];\n if (sib.length > 0) toRevert = { ...f, desired: [...(f.desired as unknown[]), ...sib] };\n }\n const op = revertOp(toRevert, recorded);\n const key = `${f.logicalId} ${kind}${propScoped ? ` ${f.path}` : ''}`;\n const item =\n itemsByLogical.get(key) ??\n ({\n logicalId: f.logicalId,\n displayId,\n resourceType: f.resourceType,\n physicalId: f.physicalId,\n kind,\n ops: [],\n } as RevertItem);\n item.ops.push(op);\n itemsByLogical.set(key, item);\n }\n\n // Order DELETE items LAST. A `delete` (out-of-band `added` resource) can be REFERENCED\n // by an undeclared property on another resource in the SAME plan — e.g. an ApiGateway\n // Method's undeclared `RequestValidatorId` points at the out-of-band RequestValidator the\n // plan also deletes. The provider rejects deleting a still-referenced resource, so the\n // dereference (property remove/revert via cc/sdk) MUST run before the delete. Apply order\n // == plan order (stack-actions iterates plan.items), so fix it here once: a STABLE\n // partition keeps every property write ahead of every delete while preserving the\n // relative order within each group (so the picker / dry-run preview match apply order).\n const ordered = [...itemsByLogical.values()];\n const items = [\n ...ordered.filter((i) => i.kind !== 'delete'),\n ...ordered.filter((i) => i.kind === 'delete'),\n ];\n return { items, notRevertable };\n}\n\nfunction revertOp(f: Finding, recorded: BaselineFile['recorded']): PatchOp {\n const pointer = toPointer(f.path);\n if (f.tier === 'declared') {\n return {\n op: 'add',\n path: pointer,\n value: f.desired,\n // Carry the current live value as `prior`, exactly like the undeclared branches\n // below. A property-scoped SDK writer that reverts PER ENTRY needs it:\n // `writeIamRoleInlinePolicies` deletes every inline policy present in `prior`\n // that the declared `value` no longer keeps. Without `prior` a declared\n // `/Policies` drift (a rogue inline policy added out of band → whole-array drift)\n // would re-PUT the declared policies but NEVER delete the rogue one — a silent,\n // security-relevant incomplete revert. Cloud Control serialization ignores\n // `prior`, and the ELB attribute-bag writers key off `attributeKey`, so this is\n // inert for them.\n prior: f.actual,\n ...(f.attributeKey !== undefined && { attributeKey: f.attributeKey }),\n human: `${f.path}${f.attributeKey ? `[${f.attributeKey}]` : ''} -> deployed-template value`,\n };\n }\n // undeclared: recorded before? restore that value; else it is a new addition -> remove.\n // `prior` carries the finding's current live value for property-scoped SDK\n // writers (per-entry revert); Cloud Control serialization ignores it.\n const wasRecorded = recorded.find((a) => a.logicalId === f.logicalId && a.path === f.path);\n if (f.actual === undefined && f.desired !== undefined) {\n // removed-undeclared finding: re-add the baseline value\n return {\n op: 'add',\n path: pointer,\n value: f.desired,\n human: `${f.path} -> restore baseline value`,\n };\n }\n if (wasRecorded) {\n return {\n op: 'add',\n path: pointer,\n value: wasRecorded.value,\n prior: f.actual,\n human: `${f.path} -> baseline value`,\n };\n }\n // A property the provider won't reset on absence (REVERT_SET_DEFAULT_PATHS): write the\n // known AWS default explicitly instead of a no-op `remove` (e.g. IAM Role\n // MaxSessionDuration). The value is the same KNOWN_DEFAULTS default that mutes an\n // at-default first sighting; if it is somehow absent we fall through to `remove`.\n const knownDefault = KNOWN_DEFAULTS[f.resourceType]?.[f.path];\n if (knownDefault !== undefined && REVERT_SET_DEFAULT_PATHS.has(`${f.resourceType}\\0${f.path}`)) {\n return {\n op: 'add',\n path: pointer,\n value: knownDefault,\n prior: f.actual,\n human: `${f.path} -> AWS default (undeclared, not in baseline)`,\n };\n }\n // A NESTED value AWS materializes as a default (KNOWN_DEFAULT_PATHS, descended via\n // NESTED_ARRAY_IDENTITY): SET that default rather than `remove` it. Some providers keep\n // the existing value when a field is merely absent from the patch, so a bare `remove` is a\n // silent no-op (Route53Resolver FirewallDomainRedirectionAction — proven live). The\n // schemaPath normalizes the identity bracket to the `.*` the table is keyed by.\n const nestedDefault = KNOWN_DEFAULT_PATHS[f.resourceType]?.[f.path.replace(/\\[[^\\]]*\\]/g, '.*')];\n if (nestedDefault !== undefined) {\n return {\n op: 'add',\n path: pointer,\n value: nestedDefault,\n prior: f.actual,\n human: `${f.path} -> AWS default (undeclared, not in baseline)`,\n };\n }\n return {\n op: 'remove',\n path: pointer,\n prior: f.actual,\n human: `${f.path} -> remove (undeclared, not in baseline)`,\n };\n}\n\n// Cloud Control applies an UpdateResource patch read-modify-write: it reads the\n// current model, applies the patch, and hands the result to the provider's update\n// handler. Read handlers CANNOT return write-only properties, so any write-only\n// property absent from the patch vanishes from the desired state on every CC-routed\n// update (cdkd #812). For most types the loss is silent; some hard-fail — e.g.\n// reverting any property on an AWS::ECS::Service with a managed EBS volume drops the\n// write-only `VolumeConfigurations` and UpdateService rejects with \"Task definition\n// has configuredAtLaunch volume but no volume configuration provided at runtime\".\n//\n// Re-include every TOP-LEVEL write-only property present (and fully resolved) in the\n// declared model that the patch does not already touch — restoring the CC\n// read-modify-write contract. Only `cc`-kind items need this (SDK writers don't\n// read-modify-write through Cloud Control). An UNRESOLVED declared value is skipped\n// (we cannot send a sentinel); the patch then omits it exactly as before, so this\n// never makes a borderline revert WORSE than today.\n// Navigate a dotted path (e.g. `LoginProfile.Password`) in a declared model; returns\n// undefined if any segment is missing or non-object. Used to re-include a NESTED\n// write-only value from the template's intent.\nfunction valueAtDottedPath(model: Record<string, unknown>, path: string): unknown {\n let node: unknown = model;\n for (const seg of path.split('.')) {\n if (node === null || typeof node !== 'object' || Array.isArray(node)) return undefined;\n node = (node as Record<string, unknown>)[seg];\n }\n return node;\n}\n\nexport function writeOnlyReincludeOps(\n declared: Record<string, unknown> | undefined,\n schema: SchemaInfo | undefined,\n existingOps: PatchOp[]\n): PatchOp[] {\n if (!declared || !schema || schema.writeOnlyPaths.length === 0) return [];\n const touched = new Set(existingOps.map((o) => o.path));\n const ops: PatchOp[] = [];\n // Iterate the FULL write-only paths, not just the top-level set: a NESTED write-only\n // property (AWS::IAM::User LoginProfile.Password, AWS::Amplify::App\n // BasicAuthConfig.Password) is never a top-level key, so the old top-level-only loop\n // re-included nothing — and a cc revert touching another property sent the parent\n // object (e.g. LoginProfile, which CC returns WITHOUT the write-only Password) to\n // UpdateResource, which RESET the credential. Re-include each resolved write-only value\n // present in the declared model from its template intent.\n for (const path of schema.writeOnlyPaths) {\n if (path.includes('*')) continue; // a wildcard (array-element) write-only — no single value to re-include\n // A property that is write-only AND create-only must NEVER enter an update patch:\n // Cloud Control hard-rejects any op on a create-only path (\"createOnlyProperties\n // [...] cannot be updated\"), failing the WHOLE revert at apply time — even though\n // the op only re-includes the property to satisfy the read-modify-write contract.\n // Omitting it is also safe: a create-only property is fixed at creation, so the\n // provider's update handler preserves it regardless of whether the patch carries it\n // (unlike a mutable write-only prop, it cannot silently vanish). Live-proven by an\n // AWS::ElastiCache::ReplicationGroup revert: CacheSubnetGroupName is both write-only\n // and create-only, so re-including it made every revert fail \"createOnlyProperties\n // [/properties/CacheSubnetGroupName] cannot be updated\".\n if (isUnderCreateOnly(path, schema.createOnlyPaths)) continue;\n const value = valueAtDottedPath(declared, path);\n if (value === undefined || value === UNRESOLVED || hasUnresolved(value)) continue;\n const pointer = toPointer(path);\n if (touched.has(pointer)) continue;\n ops.push({\n op: 'add',\n path: pointer,\n value,\n human: `${path} -> re-include write-only (Cloud Control read-modify-write contract)`,\n });\n }\n return ops;\n}\n\n// Cloud Control applies a `/Tags` patch read-modify-write: it reads the live model\n// (which AWS augments with `aws:cloudformation:*` / `aws:*` managed tags), applies the\n// patch, then hands the result to the provider's update handler. The handler diffs the\n// resulting tag set against the live set and UNtags whatever is gone — so a bare\n// `remove /Tags` (or an `add /Tags` whose value omits the managed tags) tells the\n// provider to drop the `aws:*` tags too, which AWS hard-rejects: \"aws: prefixed tag key\n// names are not allowed for external use\" (reproduced live reverting an out-of-band tag\n// on an AWS::SNS::Topic). cdkrd strips `aws:*` tags from the COMPARE side\n// (stripAwsTagsDeep), so the finding value never carries them; the revert must re-attach\n// them on the WRITE side. For any cc-kind op on the top-level `/Tags` pointer, rewrite it\n// to an `add /Tags` whose value is the intended user tags MERGED WITH the live `aws:*`\n// tags — so the provider leaves the managed tags untouched and only the user tag changes.\n// A `remove` becomes `add []`-of-managed-only; an `add` keeps its value plus the managed\n// tags. With no managed tags present (or no live model) the op is returned unchanged, so\n// this never alters a tag revert that wasn't at risk. Only the top-level `/Tags` pointer is\n// rewritten here (LIST-shaped, the {Key,Value}[] shape awsManagedTags understands). A NESTED\n// map-tag key op (`/Tags/<key>`, e.g. AWS::SSM::Parameter) does NOT need this rewrite and\n// passes through unchanged: a single-key `remove`/`add` leaves every OTHER key — including\n// the live `aws:*` managed ones — in Cloud Control's read-modify-write model, so the\n// provider never untags the managed keys (proven live on an SSM Parameter).\nconst TAGS_POINTER = '/Tags';\nfunction asTagList(v: unknown): unknown[] {\n return Array.isArray(v) ? v : [];\n}\nexport function tagPreservingOps(\n ops: PatchOp[],\n liveRaw: Record<string, unknown> | undefined\n): PatchOp[] {\n const liveTags = liveRaw?.['Tags'];\n // MAP-shaped Tags (key->value, e.g. AWS::SSM::Parameter): the managed tags are aws:*\n // KEYS. awsManagedTags only understood the {Key,Value}[] list shape, so a map-shaped\n // /Tags revert dropped the aws:* keys -> AWS rejects (\"aws: prefixed tag key names are\n // not allowed for external use\"). Mirror stripTagsWalk/isAllAwsTags and preserve them.\n if (liveTags !== null && typeof liveTags === 'object' && !Array.isArray(liveTags)) {\n const managedMap = Object.fromEntries(\n Object.entries(liveTags).filter(([k]) => k.startsWith('aws:'))\n );\n if (Object.keys(managedMap).length === 0) return ops;\n return ops.map((op) => {\n if (op.path !== TAGS_POINTER) return op;\n const userMap =\n op.op === 'add' &&\n op.value !== null &&\n typeof op.value === 'object' &&\n !Array.isArray(op.value)\n ? Object.fromEntries(\n Object.entries(op.value as Record<string, unknown>).filter(\n ([k]) => !k.startsWith('aws:')\n )\n )\n : {};\n return {\n op: 'add',\n path: TAGS_POINTER,\n value: { ...userMap, ...managedMap },\n ...(op.prior !== undefined && { prior: op.prior }),\n human: `${op.human} (preserving aws:* managed tags)`,\n };\n });\n }\n const managed = awsManagedTags(liveTags);\n if (managed.length === 0) return ops; // nothing managed to protect — leave ops as-is\n return ops.map((op) => {\n if (op.path !== TAGS_POINTER) return op;\n // user (non-managed) tags the revert wants to KEEP: an `add` keeps its value's\n // tags, a `remove` keeps none — either way, drop any aws:* entry from the value\n // (it should never carry one, but be defensive — same per-element predicate as\n // awsManagedTags) and re-attach the live managed set.\n const userTags =\n op.op === 'add' ? asTagList(op.value).filter((t) => awsManagedTags([t]).length === 0) : [];\n return {\n op: 'add',\n path: TAGS_POINTER,\n value: [...userTags, ...managed],\n ...(op.prior !== undefined && { prior: op.prior }),\n human: `${op.human} (preserving aws:* managed tags)`,\n };\n });\n}\n\n// Service-echoed EMPTY sub-arrays that the service itself REJECTS when a Cloud Control\n// UpdateResource re-sends them (#481): the CC read of a VpcLattice Rule echoes\n// `Match.HttpMatch.HeaderMatches: []` for a rule declared with only a path match (the\n// common shape), and the CC update handler folds its own read-back state into\n// `UpdateRule` — which requires headerMatches to have >= 1 members. So ANY patch on such\n// a rule, even a Priority-only revert, failed with \"Value '[]' at\n// 'match.httpMatch.headerMatches' failed to satisfy constraint\" (reproduced live). The\n// CFn schema does not annotate the constraint (no minItems on HeaderMatches), so the\n// pointers are curated per type. An appended `remove` op drops the echoed empty array\n// from the handler's desired state; the service treats an absent headerMatches as \"no\n// header matches\", which is exactly what the empty echo meant.\n// A pointer segment may be `*` — an ARRAY WILDCARD matching every index — so a husk that\n// sits INSIDE an array element is reachable (#506: ImageBuilder DistributionConfiguration\n// echoes `TargetAccountIds: []` inside EACH Distributions[i].AmiDistributionConfiguration,\n// out of reach of a static object-only pointer). Each `*` fans the pointer out to one\n// concrete pointer per live index.\nexport const CC_UPDATE_REJECTED_EMPTY_PATHS: Record<string, readonly string[]> = {\n 'AWS::VpcLattice::Rule': ['/Match/HttpMatch/HeaderMatches'],\n // ImageBuilder folds its own read-back state into UpdateDistributionConfiguration, and\n // the handler rejects the echoed `targetAccountIds: []` inside every distribution's\n // amiDistributionConfiguration — so ANY patch (even a Description-only revert) failed\n // with \"The value supplied for parameter 'distributions[0].amiDistributionConfiguration.\n // targetAccountIds' is not valid\" (reproduced live, 2026-07-03). Dropping the echoed\n // empty array lets the handler treat it as absent (no cross-account distribution), which\n // is what the empty echo meant. The CC read echoes the sibling FastLaunchConfigurations /\n // LaunchTemplateConfigurations arrays as `[]` too (corpus-observed), and they carry the\n // same \"must be non-empty when present\" shape — so they are included pre-emptively.\n // Stripping is a safe no-op regardless: the fail-safe gate only drops a live value that is\n // ALREADY an empty array (a populated array is real data and never touched), and an absent\n // array means \"no config\", exactly what the echoed `[]` meant. TargetAccountIds is the\n // live-proven rejection; the siblings guard against the same wall on a distribution that\n // sets one of them.\n 'AWS::ImageBuilder::DistributionConfiguration': [\n '/Distributions/*/AmiDistributionConfiguration/TargetAccountIds',\n '/Distributions/*/FastLaunchConfigurations',\n '/Distributions/*/LaunchTemplateConfigurations',\n ],\n};\n// Expand a JSON pointer that MAY contain `*` array-wildcard segments into a {pointer, value}\n// pair for every matching live node. A `*` matches each index of an array node; a normal\n// segment indexes an object. A wildcard-free pointer yields one pair (or none if a segment\n// is absent). Pure.\nfunction expandPointer(model: unknown, pointer: string): { pointer: string; value: unknown }[] {\n let frontier: { path: string[]; node: unknown }[] = [{ path: [], node: model }];\n for (const seg of pointer.split('/').slice(1)) {\n const next: { path: string[]; node: unknown }[] = [];\n for (const { path, node } of frontier) {\n if (seg === '*') {\n if (Array.isArray(node))\n node.forEach((el, i) => next.push({ path: [...path, String(i)], node: el }));\n } else if (node !== null && typeof node === 'object' && !Array.isArray(node)) {\n next.push({ path: [...path, seg], node: (node as Record<string, unknown>)[seg] });\n }\n }\n frontier = next;\n }\n return frontier.map(({ path, node }) => ({ pointer: `/${path.join('/')}`, value: node }));\n}\n// Extra `remove` ops for a cc-kind item on a type in the table above. Fail-safe gates:\n// the LIVE model must carry the pointer as an EMPTY array (a populated array is real\n// data and is never dropped; an absent pointer needs no strip and a `remove` on it\n// would itself fail), and no planned op may already rewrite the pointer or an ANCESTOR\n// of it (such a rewrite replaces what lives there, so a trailing remove would target a\n// path the patch may have just dropped).\nexport function rejectedEmptyStripOps(\n resourceType: string,\n ops: PatchOp[],\n liveRaw: Record<string, unknown> | undefined\n): PatchOp[] {\n const pointers = CC_UPDATE_REJECTED_EMPTY_PATHS[resourceType];\n if (!pointers || !liveRaw || ops.length === 0) return [];\n const out: PatchOp[] = [];\n for (const pointer of pointers) {\n for (const { pointer: concrete, value } of expandPointer(liveRaw, pointer)) {\n if (!Array.isArray(value) || value.length > 0) continue;\n const covered = ops.some((o) => concrete === o.path || concrete.startsWith(`${o.path}/`));\n if (covered) continue;\n out.push({\n op: 'remove',\n path: concrete,\n human: `${concrete.slice(1).replaceAll('/', '.')} -> drop service-echoed empty array (service rejects [] on update)`,\n });\n }\n }\n return out;\n}\n\n/** Serialize a RevertItem's ops to an RFC6902 PatchDocument string for Cloud Control. */\nexport function toPatchDocument(item: RevertItem): string {\n return JSON.stringify(\n item.ops.map(({ op, path, value }) => (op === 'remove' ? { op, path } : { op, path, value }))\n );\n}\n","// Apply a revert via Cloud Control API — UpdateResource (RFC6902 patch) for a\n// property revert, or DeleteResource for an `added` out-of-band resource — polling the\n// async request to completion. This is the only AWS-MUTATING path in cdkrd.\nimport {\n type CloudControlClient,\n DeleteResourceCommand,\n GetResourceRequestStatusCommand,\n type ProgressEvent,\n UpdateResourceCommand,\n} from '@aws-sdk/client-cloudcontrol';\nimport { type RevertItem, toPatchDocument } from './plan.js';\nimport { errorText, type RetryOptions, retryTransient } from './transient.js';\n\nexport interface ApplyResult {\n ok: boolean;\n error?: string;\n // Set when the FINAL failure (after bounded retries) is a transient \"resource is\n // mid-update\" class — carries a targeted hint for the report layer (issue #467).\n transient?: boolean;\n hint?: string;\n}\n\nconst POLL_INTERVAL_MS = 2000;\n// Generous ceiling: Cloud Control operations on stateful resources legitimately take\n// many minutes (e.g. deleting an RDS DBInstance is ~5-10 min). pollToCompletion returns\n// as soon as the operation reaches a terminal state, so a high ceiling never slows the\n// common case — it only bounds how long we wait on an operation that never terminates.\nconst TIMEOUT_MS = 15 * 60 * 1000;\n\n// A DELETE whose target is ALREADY absent is the goal state, not a failure. Two ways\n// this happens for an `added`-resource revert: (1) deleting an API Gateway Resource\n// CASCADE-deletes its child Resources/Methods — and each added child is an independent\n// finding applied in unspecified order, so a later DeleteResource on a child can race\n// the cascade; (2) the user removed it between `check` and `revert`. Cloud Control\n// surfaces an absent target as ResourceNotFoundException (thrown) or a FAILED event\n// whose message says not-found. Treat both as success so a revert that REACHES the\n// goal state isn't reported as FAILED (which would also wrongly bump the exit code).\nexport function isAlreadyGone(e: unknown): boolean {\n const o = (e ?? {}) as { name?: unknown; message?: unknown };\n const name = typeof o.name === 'string' ? o.name : '';\n if (name === 'ResourceNotFoundException' || name === 'NotFoundException') return true;\n const m = (typeof o.message === 'string' ? o.message : '').toLowerCase();\n return m.includes('not found') || m.includes('does not exist') || m.includes('notfound');\n}\n\nconst sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));\n\n// Poll a Cloud Control ProgressEvent (Update or Delete) to a terminal state.\nasync function pollToCompletion(\n cc: CloudControlClient,\n first: ProgressEvent | undefined\n): Promise<ApplyResult> {\n let event = first;\n const token = event?.RequestToken;\n if (!token) return { ok: false, error: 'no request token returned' };\n const deadline = Date.now() + TIMEOUT_MS;\n while (Date.now() < deadline) {\n const status = event?.OperationStatus;\n if (status === 'SUCCESS') return { ok: true };\n if (status === 'FAILED' || status === 'CANCEL_COMPLETE') {\n // StatusMessage carries the service code (e.g. RSLVR-00705) for transient\n // classification; ErrorCode is a coarser CC enum, appended when present.\n const msg = event?.StatusMessage ?? status;\n const code = event?.ErrorCode;\n return { ok: false, error: code && !msg.includes(code) ? `${code}: ${msg}` : msg };\n }\n await sleep(POLL_INTERVAL_MS);\n const polled = await cc.send(new GetResourceRequestStatusCommand({ RequestToken: token }));\n event = polled.ProgressEvent;\n }\n return { ok: false, error: 'timed out waiting for Cloud Control request' };\n}\n\nexport async function applyRevertItem(\n cc: CloudControlClient,\n item: RevertItem,\n // The Cloud Control resource identifier. Defaults to the CFn physical id, but\n // composite-identifier types (e.g. AWS::ECS::Service = `${ServiceArn}|${Cluster}`)\n // need the same adapted identifier the READ path uses — the caller resolves it via\n // CC_IDENTIFIER_ADAPTERS and passes it here, else UpdateResource ValidationExceptions.\n identifier: string = item.physicalId,\n // Bounded-backoff retry knobs (issue #467) — tests inject a no-op sleep.\n retry: RetryOptions = {}\n): Promise<ApplyResult> {\n // Retry ONLY transient \"resource is mid-update\" failures (RSLVR-00705 & friends);\n // a terminal ValidationException returns on the first attempt.\n return retryTransient(async () => {\n try {\n const res = await cc.send(\n new UpdateResourceCommand({\n TypeName: item.resourceType,\n Identifier: identifier,\n PatchDocument: toPatchDocument(item),\n })\n );\n return await pollToCompletion(cc, res.ProgressEvent);\n } catch (e) {\n return { ok: false, error: errorText(e) };\n }\n }, retry);\n}\n\n// DELETE an `added` (out-of-band) resource via Cloud Control DeleteResource. The\n// identifier is the resource's CC primaryIdentifier (for API Gateway children, the\n// `RestApiId|ResourceId[|HttpMethod]` composite already carried on the finding).\nexport async function applyRevertDelete(\n cc: CloudControlClient,\n item: RevertItem,\n identifier: string = item.physicalId,\n retry: RetryOptions = {}\n): Promise<ApplyResult> {\n // Same transient-retry wrapper as the update path: a DeleteResource can also hit a\n // \"resource is currently updating / in use\" window and settle on a retry.\n return retryTransient(async () => {\n try {\n const res = await cc.send(\n new DeleteResourceCommand({ TypeName: item.resourceType, Identifier: identifier })\n );\n const result = await pollToCompletion(cc, res.ProgressEvent);\n // already-gone surfaced as a FAILED event (vs a thrown error, handled below)\n if (!result.ok && isAlreadyGone({ message: result.error })) return { ok: true };\n return result;\n } catch (e) {\n const err = e as { name?: string; message?: string };\n if (isAlreadyGone(err)) return { ok: true };\n return { ok: false, error: errorText(e) };\n }\n }, retry);\n}\n","// Per-stack record / revert actions, shared by the standalone `record` / `revert`\n// commands AND `check`'s interactive after-drift prompt (R28). Extracting them keeps\n// the interactive flow and the single-verb commands behaviourally identical: both go\n// through exactly the same record / plan / apply / converge code.\nimport { CloudControlClient } from '@aws-sdk/client-cloudcontrol';\nimport { confirm, isCancel } from '@clack/prompts';\nimport {\n recordedKey,\n applyBaseline,\n type BaselineFile,\n buildRecorded,\n carryForwardUnreadable,\n constructPathsByLogical,\n declaredKeysByLogical,\n loadBaseline,\n physicalIdsByLogical,\n selectRecorded,\n splitRecordedByBaseline,\n writeBaseline,\n} from '../baseline/baseline-file.js';\nimport {\n addIgnoreRules,\n applyIgnores,\n type CdkrdConfig,\n ignoreRuleFor,\n} from '../config/config-file.js';\nimport { withinStackPath } from '../construct-path.js';\nimport { style } from '../report/style.js';\nimport { bulkMultiselect } from './bulk-multiselect.js';\nimport { CC_IDENTIFIER_ADAPTERS } from '../read/router.js';\nimport { applyRevertDelete, applyRevertItem } from '../revert/apply.js';\nimport {\n buildRevertPlan,\n rejectedEmptyStripOps,\n type RevertItem,\n type RevertPlan,\n tagPreservingOps,\n writeOnlyReincludeOps,\n} from '../revert/plan.js';\nimport { errorText, type RetryOptions, retryTransient } from '../revert/transient.js';\nimport { resolveSdkWriter } from '../revert/writers.js';\nimport type { Finding, SchemaInfo } from '../types.js';\nimport { type Desired } from '../desired/template-adapter.js';\nimport { buildSiblingSgRules, type GatherResult, regatherTouched } from './gather.js';\n\n// unrecorded values (R62) are awaiting a decision, not drift — they never count\n// toward \"drift(s) remain\" messaging or the convergence check.\nconst isDrift = (f: Finding): boolean =>\n (f.tier === 'deleted' ||\n f.tier === 'added' ||\n f.tier === 'declared' ||\n f.tier === 'undeclared') &&\n !f.unrecorded;\nconst driftCount = (findings: Finding[]): number => findings.filter(isDrift).length;\nconst unrecordedCount = (findings: Finding[]): number =>\n findings.filter((f) => f.unrecorded === true).length;\n\nconst sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));\n\n/**\n * The revert confirm message (R52). When NOT-revertable findings exist (e.g. a\n * no-baseline first check with one declared drift and 100+ undeclared values),\n * users read \"This WRITES to AWS\" as \"everything I just saw gets written\" —\n * state explicitly that ONLY the listed op(s) are written and the rest is\n * untouched. Pure + exported so the wording is unit-tested.\n */\nexport function revertConfirmMessage(\n stackName: string,\n opCount: number,\n notRevertableCount: number\n): string {\n const scope =\n notRevertableCount > 0\n ? ` Only the ${opCount} selected op(s) are written — the ${notRevertableCount} NOT-revertable finding(s) are untouched.`\n : '';\n return `Apply ${opCount} revert op(s) to ${stackName}? This WRITES to AWS.${scope}`;\n}\n\n/**\n * The post-revert surviving-drift pointer list (R46), capped (R52): after a\n * partial revert on a no-baseline stack, every unrecorded undeclared value\n * \"survives\" — re-listing 100+ lines the user just saw in the report is noise.\n * Show up to `cap` entries, then a one-line fold. Pure + exported for tests.\n */\nexport function formatSurvivingDrift(remaining: Finding[], stackName = '', cap = 10): string[] {\n const idOf = (f: Finding): string =>\n f.constructPath ? withinStackPath(f.constructPath, stackName) : f.logicalId;\n const lines = remaining\n .slice(0, cap)\n .map((f) => ` - ${idOf(f)}${f.path ? `.${f.path}` : ''} (${f.tier})`);\n if (remaining.length > cap)\n lines.push(` ... and ${remaining.length - cap} more — run \\`cdkrd check\\` for the full list`);\n return lines;\n}\n\n/**\n * Header for record's multiselect (R49, R116). The key hints (space / → / ← / enter)\n * are rendered by `bulkMultiselect` itself, so this is just the one-line prompt. When\n * `foldedCount` > 0 it DISCLOSES that those nested sub-keys are recorded too — the picker\n * lists only the standout rows, so without this the user could see (say) one row and not\n * realise enter also records the folded values. The folded values are NOT individually\n * deselectable here: \"record only the standout, keep the folded reported\" has no use case\n * (the folded would just nag forever), whereas deselecting a standout to \"record the rest\"\n * IS useful — so standouts toggle, the folded always record. Pure + exported.\n */\nexport function recordSelectMessage(stackName: string, foldedCount = 0): string {\n const fold =\n foldedCount > 0\n ? `; +${foldedCount} folded sub-key(s) ALWAYS recorded too (--verbose to itemize)`\n : '';\n return `${stackName}: select undeclared value(s) to record (unselected stay reported)${fold}`;\n}\n\n/**\n * Split the to-record delta into STANDOUT (itemized in the record multiselect) and FOLDED\n * (nested live-only sub-keys — the `undeclared-subkey` mass the report folds, R96). Folded\n * entries are auto-recorded as a summarized count instead of dozens of rows. `expandNested`\n * (--verbose) turns the fold off so every nested value is itemized. An entry is folded when\n * its matching gather finding is a `nested` undeclared value — EXCEPT a free-form map key\n * (freeFormKey), which the report shows in full, so the picker itemizes it too. Pure + exported.\n */\nexport function splitFoldedNested<T extends { logicalId: string; path: string }>(\n changed: T[],\n findings: Finding[],\n expandNested: boolean | undefined\n): { standout: T[]; folded: T[] } {\n if (expandNested) return { standout: changed, folded: [] };\n const nestedKeys = new Set(\n findings\n .filter((f) => f.nested === true && f.tier === 'undeclared' && !f.freeFormKey)\n .map((f) => `${f.logicalId}::${f.path}`)\n );\n const isFolded = (e: T): boolean => nestedKeys.has(`${e.logicalId}::${e.path}`);\n return { standout: changed.filter((e) => !isFolded(e)), folded: changed.filter(isFolded) };\n}\n\n/**\n * Post-record scope note (or undefined). `record` snapshots UNDECLARED state and (PR4)\n * out-of-band `added` resources into the baseline — but it CANNOT silence DECLARED or\n * DELETED drift, which is divergence from your template intent a baseline does not\n * govern (`buildRecorded` keeps only undeclared + added). Users read \"record\" as\n * \"approve EVERYTHING I just saw\", so when declared/deleted drift is present say plainly\n * that it was NOT approved and still stands. Resolution: revert it, `cdkrd ignore` it\n * (declared — stop reporting), or `cdk deploy`. Pure + exported (emitted by both `cdkrd\n * record` and check's interactive record, so the scope is stated wherever record runs —\n * previously only check's path warned). R117.\n */\nexport function recordScopeNote(stackName: string, findings: Finding[]): string | undefined {\n const n = findings.filter((f) => f.tier === 'declared' || f.tier === 'deleted').length;\n if (n === 0) return undefined;\n return `note: ${stackName}: record snapshotted undeclared + added state into the baseline only — ${n} declared/deleted drift NOT approved (it still reports as drift; resolve with cdkrd revert, cdkrd ignore, or cdk deploy).`;\n}\n\n/**\n * The success line after a record writes the baseline. Three outcomes (R142):\n * - refreshed: nothing new to decide, the already-recorded unchanged set was re-snapshotted;\n * - initialized: the FIRST baseline on a CLEAN stack (no prior file, zero recorded entries)\n * — a day-1 INITIALIZATION, not a no-op, so it states what it established (the stack is now\n * tracked → a later out-of-band undeclared value reports as drift) rather than the cold\n * \"(0 recorded entry(ies))\" that read as \"nothing happened\";\n * - written: the normal case, N recorded entries.\n * Pure + exported so the wording is unit-tested. `count` is undeclared values + (PR4)\n * out-of-band added resources — \"recorded entry(ies)\" covers both.\n */\nexport function recordOutcomeMessage(\n stackName: string,\n path: string,\n count: number,\n refreshedOnly: boolean,\n hadPriorBaseline: boolean\n): string {\n if (refreshedOnly)\n return `${stackName}: nothing new to record — baseline refreshed (${count} unchanged value(s))`;\n if (!hadPriorBaseline && count === 0)\n return `${stackName}: baseline initialized — ${path} (no undeclared values to record; this stack is now tracked — future out-of-band changes report as drift)`;\n return `baseline written: ${path} (${count} recorded entry(ies))`;\n}\n\n/**\n * Build the interactive revert multiselect options from a plan (R57). Revert is\n * now symmetric with record: choosing Revert lets you pick WHICH op(s) to write\n * — \"select the things to revert\" is the user's natural reading of the flow.\n * EVERY op starts UNSELECTED (R137): revert is the one AWS-mutating verb, so nothing\n * is pre-armed — the user opts in to each write explicitly (→ selects all at once).\n * Pre-selecting RESTORE ops but not REMOVE ops was a confusing asymmetry: a console\n * change to a declared property would be silently primed for write-back while an\n * undeclared one was not. REMOVE ops still carry a (REMOVE) label so a destructive\n * delete is visible. Pure + exported.\n */\nexport function revertSelectOptions(\n plan: RevertPlan\n): { value: string; label: string; selected: boolean }[] {\n const options: { value: string; label: string; selected: boolean }[] = [];\n for (const item of plan.items) {\n for (const op of item.ops) {\n // `delete` items delete a whole out-of-band resource — the loudest destructive\n // action, marked (DELETE); a property REMOVE keeps its (REMOVE) marker.\n const marker = item.kind === 'delete' ? ' (DELETE)' : op.op === 'remove' ? ' (REMOVE)' : '';\n options.push({\n value: revertOpKey(item, op),\n label: `${item.displayId}: ${op.human}${marker}`,\n selected: false,\n });\n }\n }\n return options;\n}\n\nfunction revertOpKey(item: RevertItem, op: RevertItem['ops'][number]): string {\n // Include attributeKey: ELB attribute-bag ops all share one op.path\n // (/LoadBalancerAttributes) and differ only by attributeKey, so without it every\n // bag attribute collapses to one multiselect row and toggles as a unit. Non-bag\n // ops have no attributeKey, so their key is unchanged.\n const attr = op.attributeKey !== undefined ? `${op.attributeKey}` : '';\n return `${item.logicalId}${item.kind}${op.path}${attr}`;\n}\n\n/** Keep only the selected ops; items left with no ops drop out. Pure + exported. */\nexport function filterRevertPlan(plan: RevertPlan, picked: Set<string>): RevertPlan {\n const items = plan.items\n .map((item) => ({ ...item, ops: item.ops.filter((op) => picked.has(revertOpKey(item, op))) }))\n .filter((item) => item.ops.length > 0);\n return { items, notRevertable: plan.notRevertable };\n}\n\nexport function revertSelectMessage(stackName: string): string {\n return `${stackName}: select the op(s) to revert (unselected are not written)`;\n}\n\n// ---- record ----\n\nexport interface RecordStackParams {\n stackName: string;\n region: string;\n desired: Desired;\n findings: Finding[]; // the gather's findings (undeclared still present, pre-baseline)\n yes: boolean;\n interactive: boolean; // whether the multiselect decision prompt may be shown (TTY only)\n // check's \"Decide per finding\" path (R121): the user already chose WHICH undeclared\n // values to record in the action picker, so recordStack skips its own multiselect and\n // records exactly these (keyed by recordedKey). Already-recorded unchanged values are\n // still auto-kept, so this never drops the rest of the baseline.\n preselectedKeys?: Set<string>;\n // Mirror the report's R96 fold: by default the record multiselect itemizes only the\n // STANDOUT (non-nested) undeclared values and auto-records the nested live-only sub-keys\n // (the `undeclared-subkey` mass the report folds) as a summarized count, instead of\n // listing dozens of nested rows. `--verbose` sets this true to itemize every nested\n // value individually (mirrors the report's --verbose fold-expansion; --show-all is the\n // separate inventory mode and suppresses the interactive prompt, so it never reaches here).\n expandNested?: boolean;\n}\n\n/**\n * Outcome of a per-stack record.\n * - `wrote`: a baseline file was written.\n * - `refused`: true ONLY when a decision was required (undeclared values to record)\n * but the run is non-interactive and `--yes` was not passed — record refuses\n * rather than recording everything by default (R38). A user-cancelled multiselect\n * is `{ wrote:false, refused:false }`, not a refusal.\n */\nexport interface RecordResult {\n wrote: boolean;\n refused: boolean;\n}\n\n/**\n * Record the current undeclared state into the baseline file. In an interactive run\n * (no --yes) the user picks WHICH undeclared values to record (selective record, R14).\n * When an existing baseline is present the multiselect shows only the DELTA from it\n * (new/changed); already-recorded unchanged values are auto-kept and surfaced with a\n * note (R39). An empty FINAL set is confirmed first (R19). Non-interactively\n * (non-TTY: CI/cron/pipes), the multiselect is a required DECISION: with\n * undeclared values present and no --yes, record refuses (exit 2) instead of recording\n * all (R38). When there is nothing to decide (no undeclared values) the baseline is\n * written regardless. (Same flow whether reached via `cdkrd record` or check's\n * interactive prompt — neither re-gathers.)\n */\nexport async function recordStack(p: RecordStackParams): Promise<RecordResult> {\n const { stackName, region, desired, findings, yes, interactive, preselectedKeys, expandNested } =\n p;\n const existing = await loadBaseline(stackName, desired.accountId, region);\n if (!yes && existing)\n console.error(\n `note: ${stackName}: will overwrite the existing baseline file on confirm (nothing written yet; it is git-tracked — review the diff afterwards). Pass --yes to silence.`\n );\n // Seed with this run's observed entries, then carry forward any prior baseline\n // entries for resources this run could NOT read (skipped / model-read-failed) so a\n // re-record never silently shrinks the committed baseline (writeBaseline full-replaces).\n let recorded = carryForwardUnreadable(buildRecorded(findings), existing, findings);\n let refreshedOnly = false; // true when only unchanged values remained (no delta to decide)\n if (!yes && recorded.length > 0) {\n // A decision is required (which undeclared values to record). Non-interactively\n // we refuse rather than implicitly record ALL of them (R38).\n if (!interactive) {\n console.error(\n `error: record needs a decision — pass --yes to record ALL undeclared values, or run interactively`\n );\n return { wrote: false, refused: true };\n }\n // Only make the human decide on the DELTA from the existing baseline: already-recorded\n // unchanged values are auto-kept (re-confirming a 50-item snapshot every time is wrong,\n // R39). With no baseline the split returns everything as `changed` (the true first record).\n const { unchanged, changed } = splitRecordedByBaseline(recorded, existing);\n if (unchanged.length > 0)\n console.error(\n `note: ${stackName}: keeping ${unchanged.length} already-recorded unchanged value(s)`\n );\n if (changed.length === 0) {\n // Nothing new to decide — just refresh the baseline (re-snapshot the unchanged set).\n recorded = unchanged;\n refreshedOnly = true;\n } else {\n // Per-finding path: the action picker already chose the keys, so take them\n // directly (no second prompt). Otherwise show the record multiselect.\n let picked: string[];\n if (preselectedKeys) {\n picked = changed.map((e) => recordedKey(e)).filter((k) => preselectedKeys.has(k));\n } else {\n // Mirror the report's R96 fold: itemize only the STANDOUT (non-nested) values; the\n // folded nested sub-keys (the `undeclared-subkey` mass) are ALWAYS recorded and the\n // header discloses the count. They are deliberately NOT individually deselectable —\n // \"record only the standout, keep the folded reported\" has no use case (the folded\n // would just nag forever), while deselecting a standout to \"record the rest\" stays\n // possible (the folded still record). To record nothing, cancel (esc). `--verbose`\n // (expandNested) itemizes every nested value as its own row instead (`--show-all` is\n // the separate inventory mode — it suppresses this prompt, so it can't itemize here).\n const { standout, folded } = splitFoldedNested(changed, findings, expandNested);\n if (standout.length === 0) {\n // Nothing to itemize (every changed value is a folded nested sub-key — the common\n // all-nested first run). A Yes/No commit replaces the empty multiselect.\n const proceed = await confirm({\n message: `${stackName}: record ${folded.length} undeclared sub-key value(s)? (--verbose to itemize each)`,\n initialValue: true,\n });\n if (isCancel(proceed) || !proceed) {\n console.error(`note: ${stackName}: record cancelled — baseline unchanged`);\n return { wrote: false, refused: false };\n }\n picked = changed.map((e) => recordedKey(e));\n } else {\n const fromPrompt = await bulkMultiselect(\n recordSelectMessage(stackName, folded.length),\n // default = all selected (→/← bulk-toggle from there)\n standout.map((e) => ({\n value: recordedKey(e),\n // an `added`-resource entry (PR4) has an empty path — the whole resource is\n // the value — so omit the trailing dot and tag it as a resource snapshot.\n label: e.path ? `${e.logicalId}.${e.path}` : `${e.logicalId} (added resource)`,\n selected: true,\n }))\n );\n if (fromPrompt === undefined) {\n console.error(`note: ${stackName}: record cancelled — baseline unchanged`);\n return { wrote: false, refused: false };\n }\n // the folded nested values are always recorded alongside the picked standouts\n picked = [...fromPrompt, ...folded.map((e) => recordedKey(e))];\n }\n }\n const selectedChanged = selectRecorded(findings, new Set(picked));\n recorded = [...unchanged, ...selectedChanged]; // auto-kept unchanged + the user's picks\n // The FINAL written set being empty (no unchanged + nothing picked) writes an EMPTY\n // baseline. Since R62 that no longer arms revert removal (unrecorded values stay\n // guarded per entry) — it just records \"I decided nothing\", so the values keep\n // being reported as unrecorded. Still confirm: writing a file that changes nothing\n // is more likely a mis-keyed multiselect than an intent (R19, defanged by R62).\n // Skipped on the per-finding path: the picker is the decision, no extra confirm.\n if (recorded.length === 0 && !preselectedKeys) {\n const proceed = await confirm({\n message: `${stackName}: record nothing? This writes an EMPTY baseline — every undeclared value stays reported as unrecorded.`,\n initialValue: false,\n });\n if (isCancel(proceed) || !proceed) {\n console.error(`note: ${stackName}: record cancelled — baseline unchanged`);\n return { wrote: false, refused: false };\n }\n }\n }\n }\n const { path, count } = await writeBaseline(\n stackName,\n region,\n desired.accountId,\n findings,\n desired.rawTemplate,\n recorded,\n // full resource list (read-clean resources are snapshot-complete too) +\n // previous baseline so completeness stays monotonic across re-records (R62)\n { allLogicalIds: desired.resources.map((r) => r.logicalId), previous: existing }\n );\n console.log(style.ok(recordOutcomeMessage(stackName, path, count, refreshedOnly, !!existing)));\n // record's scope excludes declared/deleted: if such drift is present, say so —\n // it was NOT approved by this record and still stands (R117).\n const scopeNote = recordScopeNote(stackName, findings);\n if (scopeNote) console.error(scopeNote);\n return { wrote: true, refused: false };\n}\n\n// ---- ignore ----\n\nexport interface IgnoreStackParams {\n stackName: string;\n // baseline-reconciled findings — ignore targets the declared + undeclared tiers\n // (the same set applyIgnores can re-tag). Already-ignored findings are tier\n // `ignored`, so they never re-appear here.\n findings: Finding[];\n yes: boolean;\n interactive: boolean; // whether the multiselect decision prompt may be shown (TTY only)\n}\n\n/**\n * Outcome of a per-stack ignore.\n * - `wrote`: at least one NEW rule was appended to `.cdkrd/ignore.yaml`.\n * - `refused`: true ONLY when a decision was required (ignorable findings present)\n * but the run is non-interactive and `--yes` was not passed — like record, ignore\n * refuses rather than ignoring everything by default.\n * - `added`: how many new rules were written (0 when all were already present, or on\n * a cancel/refusal).\n */\nexport interface IgnoreResult {\n wrote: boolean;\n refused: boolean;\n added: number;\n}\n\n/** Header for ignore's multiselect. The key hints are rendered by `bulkMultiselect`\n * itself, so this is just the one-line prompt. Pure + exported for unit tests. */\nexport function ignoreSelectMessage(stackName: string): string {\n return `${stackName}: select drift to ignore — stops reporting it (writes .cdkrd/ignore.yaml)`;\n}\n\n// Unique per-finding key for the multiselect (logicalId+path is unique within a stack;\n// the WRITTEN rule is ignoreRuleFor, which may instead use the friendlier constructPath).\nconst ignoreFindingKey = (f: Finding): string => `${f.logicalId}::${f.path}`;\n\n/**\n * The ignore multiselect rows. EVERY row starts UNSELECTED (→ selects all) — mirroring\n * revert's picker (R137): ignore STOPS watching permanently, and check's interactive flow\n * can route folded undeclared inventory here, so a default-all selection would let an\n * Enter ignore values the user never saw in the report. Opt-in, not opt-out. Pure +\n * exported so the \"starts unselected\" invariant is unit-tested without a TTY.\n */\nexport function ignoreSelectOptions(\n ignorable: Finding[],\n stackName = ''\n): { value: string; label: string; selected: boolean }[] {\n return ignorable.map((f) => {\n const id = f.constructPath ? withinStackPath(f.constructPath, stackName) : f.logicalId;\n return {\n value: ignoreFindingKey(f),\n label: `${id}${f.path ? `.${f.path}` : ''} (${f.tier})`,\n selected: false,\n };\n });\n}\n\n/**\n * Write `ignore` rules into `.cdkrd/ignore.yaml` for the chosen declared/undeclared\n * findings — they stop being reported entirely (re-tagged `ignored` on the next check),\n * the \"stop watching\" counterpart to record's \"keep watching\". Interactive runs pick\n * WHICH findings to ignore (default NONE selected — → selects all, R137); `--yes`\n * ignores all shown.\n * Non-interactively without `--yes` it refuses (a required decision, like record, R38).\n * Idempotent: rules already in the file are reported, not duplicated. Shared by `cdkrd\n * ignore` and (PR-B2) check's interactive flow, so both write rules identically.\n */\nexport async function ignoreStack(p: IgnoreStackParams): Promise<IgnoreResult> {\n const { stackName, findings, yes, interactive } = p;\n // ignore is symmetric with revert (declared + undeclared + added), unlike record\n // (undeclared only) — it fills the gap of accepting a DECLARED or out-of-band ADDED\n // drift in-tool.\n const ignorable = findings.filter(\n (f) => f.tier === 'declared' || f.tier === 'undeclared' || f.tier === 'added'\n );\n if (ignorable.length === 0) {\n console.log(style.clean(`${stackName}: no ignorable drift to ignore.`));\n return { wrote: false, refused: false, added: 0 };\n }\n let chosen = ignorable;\n if (!yes) {\n if (!interactive) {\n console.error(\n `error: ignore needs a decision — pass --yes to ignore ALL shown drift, or run interactively`\n );\n return { wrote: false, refused: true, added: 0 };\n }\n const picked = await bulkMultiselect(\n ignoreSelectMessage(stackName),\n ignoreSelectOptions(ignorable, stackName)\n );\n if (picked === undefined) {\n console.error(`note: ${stackName}: ignore cancelled — config unchanged`);\n return { wrote: false, refused: false, added: 0 };\n }\n const set = new Set(picked);\n chosen = ignorable.filter((f) => set.has(ignoreFindingKey(f)));\n if (chosen.length === 0) {\n console.error(`note: ${stackName}: nothing selected — config unchanged`);\n return { wrote: false, refused: false, added: 0 };\n }\n }\n const { path, added, alreadyPresent } = await addIgnoreRules(\n chosen.map((f) => ignoreRuleFor(f, stackName))\n );\n if (added.length > 0) {\n const dup = alreadyPresent.length > 0 ? `, ${alreadyPresent.length} already present` : '';\n console.log(style.ok(`ignore rule(s) added: ${path} (${added.length} new${dup})`));\n } else {\n console.log(\n style.note(\n `${stackName}: all ${alreadyPresent.length} selected rule(s) already present — config unchanged`\n )\n );\n }\n return { wrote: added.length > 0, refused: false, added: added.length };\n}\n\n// ---- revert ----\n\nexport interface PlanDisplayOptions {\n verbose?: boolean; // expand the NOT-revertable per-reason summary to the full per-finding list\n unrecordedGuidance?: boolean; // unrecorded values present → lead with the record-or-remove fork\n}\n\n/**\n * Render the revert plan (pure — exported for unit tests; printPlan logs it).\n * Revertable items are ALWAYS full detail — confirming what will be written to AWS\n * is the point of the plan. NOT-revertable findings fold into one line per reason\n * (count + reason — same idea as check's `info:` footer, R25/R35); `--verbose`\n * expands them to the full per-finding list.\n */\nexport function formatPlan(\n stackName: string,\n region: string,\n plan: RevertPlan,\n opts: PlanDisplayOptions = {}\n): string[] {\n const lines: string[] = [`\\n=== revert: ${stackName} (${region}) ===`];\n if (opts.unrecordedGuidance) {\n // A fork, not a sequence (R55): recording these values endorses them (they\n // leave the report) — it is NOT a step toward reverting them.\n lines.push(\n `\\nnote: ${stackName} has unrecorded value(s) — never recorded, so there is no recorded state to restore.`,\n ' If the live values are RIGHT, record them (they leave the report);',\n ' if they should be REMOVED, re-run revert with --remove-unrecorded.'\n );\n }\n // A resource can split into MORE THAN ONE plan item (a Cloud Control `cc` item plus a\n // prop-scoped `sdk` item route through different writers — e.g. a Logs LogGroup whose\n // RetentionInDays reverts via CC while BearerTokenAuthenticationEnabled reverts via the\n // SDK writer). Merge them into ONE block per resource so the listing reads per-resource,\n // not per-writer-group (two identical-header blocks for the same resource is confusing).\n const planByResource = new Map<\n string,\n { displayId: string; resourceType: string; humans: string[] }\n >();\n for (const item of plan.items) {\n const g = planByResource.get(item.logicalId);\n const humans = item.ops.map((op) => op.human);\n if (g) g.humans.push(...humans);\n else\n planByResource.set(item.logicalId, {\n displayId: item.displayId,\n resourceType: item.resourceType,\n humans,\n });\n }\n for (const g of planByResource.values()) {\n lines.push(`\\n ${g.displayId} (${g.resourceType})`);\n for (const h of g.humans) lines.push(` - ${h}`);\n }\n if (plan.notRevertable.length > 0) {\n if (opts.verbose) {\n lines.push(`\\n NOT revertable (${plan.notRevertable.length}):`);\n for (const n of plan.notRevertable)\n lines.push(` - ${n.displayId}.${n.path} (${n.resourceType}) — ${n.reason}`);\n } else {\n const counts = new Map<string, number>();\n for (const n of plan.notRevertable) counts.set(n.reason, (counts.get(n.reason) ?? 0) + 1);\n const groups = [...counts.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1));\n groups.forEach(([reason, count], i) => {\n lines.push(\n i === 0\n ? `\\n NOT revertable: ${count} (${reason})`\n : ` · ${count} (${reason})`\n );\n });\n lines.push(' (run with --verbose for the full list)');\n }\n }\n return lines;\n}\n\n/** Collapse per-item apply results into ONE outcome per resource (logical id). A\n * resource that split into a `cc` item and a prop-scoped `sdk` item produced two\n * results; print a single `reverted:` line for it when every item succeeded, and a\n * single `FAILED:` line (joining the failing writers' errors) when any did not — so a\n * fully reverted resource never prints twice and a partial failure is never shown as a\n * plain success. Insertion order (first item per resource) is preserved. */\nexport function summarizeRevertResults(\n applied: readonly {\n logicalId: string;\n displayId: string;\n ok: boolean;\n error?: string;\n hint?: string;\n }[]\n): { displayId: string; ok: boolean; error?: string; hint?: string }[] {\n const byResource = new Map<\n string,\n { displayId: string; ok: boolean; errors: string[]; hints: string[] }\n >();\n for (const a of applied) {\n const g = byResource.get(a.logicalId) ?? {\n displayId: a.displayId,\n ok: true,\n errors: [],\n hints: [],\n };\n if (!a.ok) {\n g.ok = false;\n if (a.error) g.errors.push(a.error);\n // Collapse duplicate hints (a cc + sdk split can both fail transiently) to one line.\n if (a.hint && !g.hints.includes(a.hint)) g.hints.push(a.hint);\n }\n byResource.set(a.logicalId, g);\n }\n return [...byResource.values()].map((g) =>\n g.ok\n ? { displayId: g.displayId, ok: true }\n : {\n displayId: g.displayId,\n ok: false,\n error: g.errors.join('; '),\n ...(g.hints.length > 0 && { hint: g.hints.join('; ') }),\n }\n );\n}\n\nfunction printPlan(\n stackName: string,\n region: string,\n plan: RevertPlan,\n opts: PlanDisplayOptions\n): void {\n // formatPlan stays pure/plain (unit-tested verbatim); only the banner line is\n // styled here, at the printing edge.\n for (const line of formatPlan(stackName, region, plan, opts)) {\n console.log(line.startsWith('\\n=== ') ? '\\n' + style.header(line.slice(1)) : line);\n }\n}\n\nexport interface RevertStackParams {\n stackName: string;\n region: string;\n gathered: GatherResult; // the check/revert gather (findings + desired + schemas)\n baseline: BaselineFile | undefined;\n config: CdkrdConfig; // .cdkrd/ignore.yaml ignore rules (ignored findings drop out of the plan)\n dryRun: boolean;\n yes: boolean;\n removeUnrecorded: boolean;\n verbose: boolean; // expand the NOT-revertable summary to the full list\n interactive: boolean; // whether the confirm prompt may be shown (TTY only)\n // check's \"Decide per finding\" path (R121): the user already chose WHICH findings to\n // revert (passed in via gathered.findings), so revertStack skips its own op-multiselect\n // and reverts every op of the plan — but STILL shows the AWS-write confirm. Off by\n // default, so the standalone `revert` keeps its per-op multiselect.\n autoSelectAll?: boolean;\n // Delay before the single convergence re-read retry (SDK-writer paths can lag\n // behind their API response — eventual consistency). Overridable so unit tests\n // don't sleep for real.\n convergeRetryDelayMs?: number;\n // `revert --wait[=DURATION]` (issue #467): on a TRANSIENT \"resource is mid-update\"\n // failure (RSLVR-00705 & friends), keep retrying the write until the resource settles\n // (up to this many ms) instead of stopping at the short default backoff — so a\n // minutes-long UPDATING window converges in one command. undefined = default backoff.\n waitMs?: number;\n // Injected clock/sleep for the wait path so deadline-mode unit tests don't sleep.\n waitNow?: () => number;\n waitSleep?: (ms: number) => Promise<void>;\n}\n\nconst CONVERGE_RETRY_DELAY_MS = 3000;\n\n/**\n * Outcome of a per-stack revert.\n * - `exit`: the exit contribution — 0 clean / 1 drift remains (including \"drift\n * exists but nothing is revertable\", R35) / 2 apply failure (or a non-interactive\n * write refusal).\n * - `aborted`: true ONLY when the user cancelled the confirm prompt (no AWS write\n * happened). The standalone `revert` command treats an abort as exit 0 (nothing\n * changed), but `check`'s interactive flow must NOT let an abort drop a drifted\n * stack to exit 0 — it keeps the pre-revert exit 1 (symmetric with \"Nothing\").\n * See R30.\n */\nexport interface RevertOutcome {\n exit: number;\n aborted: boolean;\n}\n\n/**\n * Build the revert plan from the gather's findings + baseline, show it, confirm\n * (unless --yes / --dry-run), apply via Cloud Control / SDK writers, then re-gather\n * to verify convergence. Does NOT re-gather to build the plan (uses the passed\n * gather) — only the convergence re-check re-gathers.\n */\n// R113: whether to include the REMOVE of standout undeclared (unrecorded) values in\n// a revert. The explicit `--remove-unrecorded` flag always includes them. Otherwise\n// include them ONLY when an interactive multiselect will be shown to gate them\n// per-item (TTY and not --yes) — its unselected-by-default REMOVE rows ARE the\n// consent the flag provides. A no-prompt run (--yes or non-TTY) keeps requiring the\n// flag, since there is nothing to opt in with. Pure + exported for tests.\nexport function includeUnrecordedRemovals(\n removeUnrecorded: boolean,\n interactive: boolean,\n yes: boolean\n): boolean {\n return removeUnrecorded || (interactive && !yes);\n}\n\nexport async function revertStack(p: RevertStackParams): Promise<RevertOutcome> {\n const {\n stackName,\n region,\n gathered,\n baseline,\n config,\n dryRun,\n yes,\n removeUnrecorded,\n verbose,\n interactive,\n autoSelectAll,\n waitMs,\n waitNow,\n waitSleep,\n } = p;\n let worst = 0;\n // R113: a standout undeclared value is surfaced to the user as [Potential Drift] (it is\n // NOT a folded default — we deliberately show it), so, like declared drift, it\n // belongs in the revert list. Reverting an undeclared value REMOVES it (cdk drift\n // reports the same values and `cdk deploy --revert-drift` removes them). The\n // multiselect's REMOVE rows start UNSELECTED, so listing them is the per-item\n // consent that `--remove-unrecorded` provides non-interactively — no flag needed in\n // a gated prompt. A no-prompt run (--yes or non-TTY) has no multiselect to gate, so\n // it still requires the explicit flag.\n const includeRemovals = includeUnrecordedRemovals(removeUnrecorded, interactive, yes);\n const declaredByLogical = declaredKeysByLogical(gathered.desired.resources);\n // physicalId + constructPath maps so a synthesized \"baseline value removed since\n // record\" finding carries them — physicalId lets `revert` actually restore the\n // removed value (else buildRevertPlan rejects it \"no physical id\"); constructPath\n // lets a constructPath-form ignore rule match it during applyIgnores.\n const physicalIdByLogical = physicalIdsByLogical(gathered.desired.resources);\n const constructPathByLogical = constructPathsByLogical(gathered.desired.resources);\n const baselineOpts = { declaredByLogical, physicalIdByLogical, constructPathByLogical };\n const drifted = applyIgnores(\n applyBaseline(gathered.findings, baseline, { ...baselineOpts, warn: console.error }),\n { stackName, accountId: gathered.desired.accountId, region },\n config\n );\n let plan = buildRevertPlan(drifted, baseline, {\n removeUnrecorded: includeRemovals,\n schemas: gathered.schemas,\n siblingSgRules: buildSiblingSgRules(gathered.desired),\n stackName,\n });\n\n if (plan.items.length === 0 && plan.notRevertable.length === 0) {\n console.log(style.clean(`${stackName} (${region}): no drift to revert.`));\n return { exit: 0, aborted: false };\n }\n printPlan(stackName, region, plan, {\n verbose,\n // Only when the unrecorded guard actually fires: with removals included the plan\n // REMOVES those values, so a \"no revert target — record first\" note would\n // contradict the plan printed right below it (R35 review).\n unrecordedGuidance: !includeRemovals && drifted.some((f) => f.unrecorded === true),\n });\n if (plan.items.length === 0) {\n // Findings exist but none are revertable (R35). That is NOT the clean\n // \"no drift to revert\" case — the findings still stand, so exit 1 (the same\n // \"drift remains\" semantics as a post-apply non-convergence; not a usage\n // error). Unrecorded values are named as such, not folded into \"drift\" (R62).\n const dc = driftCount(drifted);\n const uc = unrecordedCount(drifted);\n const parts = [\n ...(dc > 0 ? [`${dc} drift(s)`] : []),\n ...(uc > 0 ? [`${uc} unrecorded value(s)`] : []),\n ];\n console.log('\\n' + style.drift(`nothing revertable — ${parts.join(' + ')} remain.`));\n return { exit: 1, aborted: false };\n }\n\n if (dryRun) {\n const opCount = plan.items.reduce((n, i) => n + i.ops.length, 0);\n console.log(\n `\\n(dry-run) would apply ${opCount} op(s) to ${plan.items.length} resource(s). No changes made.`\n );\n return { exit: 0, aborted: false };\n }\n if (!yes) {\n if (!interactive) {\n console.error(\n `\\nrefusing to write to AWS non-interactively — pass --yes to apply (or --dry-run to preview).`\n );\n return { exit: 2, aborted: false };\n }\n // R57: pick WHICH op(s) to write — symmetric with record's multiselect.\n // RESTORE ops are pre-selected; REMOVE ops start unselected (an explicit\n // per-item opt-in to deleting a live value). Selecting nothing aborts.\n // Skipped on the per-finding path (autoSelectAll): the action picker already chose\n // the findings, so revert every op of the plan — but still confirm the AWS write.\n if (!autoSelectAll) {\n const picked = await bulkMultiselect(\n revertSelectMessage(stackName),\n revertSelectOptions(plan)\n );\n if (picked === undefined) {\n console.log(style.note('aborted.'));\n return { exit: 0, aborted: true };\n }\n plan = filterRevertPlan(plan, new Set(picked));\n if (plan.items.length === 0) {\n console.log(style.note('nothing selected — aborted.'));\n return { exit: 0, aborted: true };\n }\n }\n const opCount = plan.items.reduce((n, i) => n + i.ops.length, 0);\n const ok = await confirm({\n message: revertConfirmMessage(stackName, opCount, plan.notRevertable.length),\n });\n if (isCancel(ok) || !ok) {\n console.log(style.note('aborted.'));\n return { exit: 0, aborted: true };\n }\n }\n\n const cc = new CloudControlClient({ region });\n const byLogical = new Map(gathered.desired.resources.map((res) => [res.logicalId, res]));\n // `added` delete items have a SYNTHESIZED logicalId (not a template resource), so the\n // scoped convergence re-read below cannot regenerate them — a SUCCESSFUL delete then\n // correctly vanishes from `post`, but a FAILED one would vanish too (reading as CLEAN).\n // Track the failed ones and re-add their findings so they still count as drift.\n const failedDeleteIds = new Set<string>();\n const applied: {\n logicalId: string;\n displayId: string;\n ok: boolean;\n error?: string;\n hint?: string;\n }[] = [];\n // Per-item transient-retry options (issue #467). `--wait` turns the short default\n // backoff into a deadline-bounded wait so a minutes-long UPDATING window (RSLVR-00705)\n // converges in one command; each item gets its OWN wait budget. `onRetry` prints a\n // per-retry progress line so the wait never looks frozen (see #477's spinner ethos).\n const clock = waitNow ?? Date.now;\n const buildRetryOpts = (displayId: string): RetryOptions => ({\n ...(waitMs !== undefined && { deadlineMs: clock() + waitMs }),\n ...(waitNow && { now: waitNow }),\n ...(waitSleep && { sleep: waitSleep }),\n onRetry: ({ attempt, delayMs, hint }) => {\n const reason = (hint ?? 'transient error').split(' — ')[0];\n const secs = Math.max(1, Math.round(delayMs / 1000));\n console.log(\n style.note(` ↻ ${displayId}: ${reason} — retry ${attempt} (next in ${secs}s)…`)\n );\n },\n });\n for (const item of plan.items) {\n let r: { ok: boolean; error?: string; hint?: string };\n if (item.kind === 'delete') {\n // physicalId IS the CC identifier (the composite the finding carried); delete it.\n r = await applyRevertDelete(cc, item, item.physicalId, buildRetryOpts(item.displayId));\n if (!r.ok) failedDeleteIds.add(item.logicalId);\n } else if (item.kind === 'sdk') {\n const res = byLogical.get(item.logicalId);\n // Same transient-retry wrapper as the Cloud Control path (issue #467): an SDK\n // writer can also throw a \"resource is currently updating\" error that settles on\n // a retry, and exhausted retries carry the targeted hint.\n r = await retryTransient(async () => {\n try {\n const writer = resolveSdkWriter(item.resourceType, item.ops);\n if (!writer) throw new Error(`no SDK writer for ${item.resourceType}`);\n // A Cloud-Control-routed nested writer addresses the resource by the composite CC\n // identifier (e.g. AWS::ApiGateway::Stage `RestApiId|StageName`) the READ path\n // resolves — pass it so its GetResource/UpdateResource doesn't ValidationException\n // on the bare physical id. Falls back to the physical id when no adapter applies.\n const identifier =\n CC_IDENTIFIER_ADAPTERS[item.resourceType]?.(item.physicalId, res?.declared ?? {}) ??\n item.physicalId;\n await writer(\n {\n physicalId: item.physicalId,\n identifier,\n declared: res?.declared ?? {},\n region,\n accountId: gathered.desired.accountId,\n resourceType: item.resourceType,\n },\n item.ops\n );\n return { ok: true };\n } catch (e) {\n return { ok: false, error: errorText(e) };\n }\n }, buildRetryOpts(item.displayId));\n } else {\n const res = byLogical.get(item.logicalId);\n const identifier =\n CC_IDENTIFIER_ADAPTERS[item.resourceType]?.(item.physicalId, res?.declared ?? {}) ??\n item.physicalId;\n // Re-attach the live aws:* managed tags onto any /Tags op, so the Cloud Control\n // read-modify-write does not tell the provider to UNtag them (AWS rejects an\n // external write that drops an aws:-prefixed key). Uses the UN-stripped live model\n // kept on the gather (the compare side strips aws:* tags; the write side must not).\n const tagged = tagPreservingOps(item.ops, gathered.liveByLogical.get(item.logicalId));\n // Re-include write-only props the Cloud Control read-modify-write would drop\n // (cdkd #812 — e.g. ECS Service VolumeConfigurations). cc-kind items only.\n const extra = writeOnlyReincludeOps(\n res?.declared,\n gathered.schemas.get(item.resourceType),\n tagged\n );\n // Drop service-echoed empty arrays the service itself rejects on update\n // (#481 — VpcLattice Rule HeaderMatches []). Live-gated + ancestor-aware.\n const strip = rejectedEmptyStripOps(\n item.resourceType,\n [...tagged, ...extra],\n gathered.liveByLogical.get(item.logicalId)\n );\n const combined = [...tagged, ...extra, ...strip];\n const ccItem = { ...item, ops: combined.length > tagged.length ? combined : tagged };\n r = await applyRevertItem(cc, ccItem, identifier, buildRetryOpts(item.displayId));\n }\n applied.push({\n logicalId: item.logicalId,\n displayId: item.displayId,\n ok: r.ok,\n ...(r.error !== undefined && { error: r.error }),\n ...(r.hint !== undefined && { hint: r.hint }),\n });\n if (!r.ok) worst = Math.max(worst, 2);\n }\n // Print ONE outcome per resource (a resource that split into a `cc` + `sdk` item\n // produced two results) so a fully reverted resource never prints `reverted:` twice.\n for (const s of summarizeRevertResults(applied)) {\n if (s.ok) {\n console.log(style.ok(` reverted: ${s.displayId}`));\n } else {\n console.log(style.fail(` FAILED: ${s.displayId} — ${s.error}`));\n // Transient \"resource is mid-update\" failure that survived the retries: add a\n // targeted hint so the user knows this is retry-later, not a real failure. When we\n // did NOT already wait (`--wait` off), point at it as the one-command settle path.\n if (s.hint) {\n const suffix =\n waitMs === undefined ? ' (or re-run with --wait to block until it settles)' : '';\n console.log(style.note(` ↳ ${s.hint}${suffix}`));\n }\n }\n }\n\n // Re-check convergence — scoped to the resources the revert just touched (R44).\n // A full gatherFindings here re-read the ENTIRE stack (a long silent wait that\n // scaled with stack size, not with the revert); regatherTouched re-reads only\n // plan.items and carries every other finding forward from the original gather.\n const touched = new Set(plan.items.map((i) => i.logicalId));\n console.log(\n '\\n' + style.note(`verifying convergence (re-reading ${touched.size} resource(s))...`)\n );\n const reconcile = (findings: Finding[]): Finding[] =>\n applyIgnores(\n applyBaseline(findings, baseline, baselineOpts),\n { stackName, accountId: gathered.desired.accountId, region },\n config\n );\n // regatherTouched drops every `touched` finding (including the synthesized-id `added`\n // deletes) and re-reads only template resources — so a FAILED delete's finding is gone\n // from `post` though the resource still lives. Re-add the failed ones so convergence\n // reflects reality (a successful delete stays dropped = resolved).\n const readdFailedDeletes = (findings: Finding[]): Finding[] =>\n failedDeleteIds.size === 0\n ? findings\n : [...findings, ...gathered.findings.filter((f) => failedDeleteIds.has(f.logicalId))];\n let post = readdFailedDeletes(reconcile(await regatherTouched(gathered, touched, region)));\n if (driftCount(post.filter((f) => touched.has(f.logicalId))) > 0) {\n // A touched resource still reads as drifted. SDK-writer paths (IAM etc.) are\n // eventually consistent — the old slow full re-gather granted propagation time\n // for free; the scoped read must wait deliberately. One retry only.\n await sleep(p.convergeRetryDelayMs ?? CONVERGE_RETRY_DELAY_MS);\n post = readdFailedDeletes(reconcile(await regatherTouched(gathered, touched, region)));\n }\n const remainingDrift = post.filter(isDrift);\n const remaining = remainingDrift.length;\n // A touched resource whose verification RE-READ failed (skipped tier — a throttle /\n // transient CC or SDK-override read error) is NOT proof the write landed: a write CC\n // accepted (200) but silently rejected, followed by an unreadable re-read, would\n // otherwise count as zero drift and print \"CLEAN\". Likewise a FAILED delete of an\n // UNRECORDED `added` resource is re-added to `post` but is excluded from `isDrift`\n // (unrecorded), so it too would read as CLEAN though the resource still lives. Treat\n // both as UNCONFIRMED — never claim convergence we could not verify.\n const unverified = post.filter((f) => touched.has(f.logicalId) && f.tier === 'skipped').length;\n const unconfirmed = unverified + failedDeleteIds.size;\n const converged = remaining === 0 && unconfirmed === 0;\n console.log(\n converged\n ? style.clean(`${stackName}: CLEAN after revert.`)\n : remaining > 0\n ? style.drift(`${stackName}: ${remaining} drift(s) remain.`)\n : style.drift(\n `${stackName}: revert applied, but ${unconfirmed} resource(s) could not be confirmed converged (see above).`\n )\n );\n // unrecorded values are not drift, but silently dropping them here would read\n // as \"all good\" when a decision is still pending — one dim pointer line (R62).\n const unrecordedLeft = unrecordedCount(post);\n if (unrecordedLeft > 0)\n console.log(\n style.note(\n ` (${unrecordedLeft} unrecorded value(s) still await a baseline — run cdkrd record)`\n )\n );\n // A touched resource we could not re-read leaves the revert UNVERIFIED — point the\n // user at a re-run rather than implying success. (A failed delete already printed its\n // own `FAILED:` line above and bumped the exit to 2 in the apply loop.)\n if (unverified > 0)\n console.log(\n style.note(\n ` (${unverified} resource(s) could not be re-read to verify — re-run cdkrd check to confirm)`\n )\n );\n // Say WHICH drift survived — without this the user must re-run `check` just to\n // learn what didn't converge (R46). A terse id-per-line pointer, not a report;\n // capped so a no-baseline partial revert doesn't re-list 100+ lines (R52).\n for (const line of formatSurvivingDrift(remainingDrift, stackName)) console.log(line);\n // remaining drift OR an unverifiable re-read both mean \"not confirmed clean\" → exit 1\n // (a failed delete already set 2). Never return 0 (\"converged\") when we could not check.\n if (remaining > 0 || unverified > 0) worst = Math.max(worst, 1);\n return { exit: worst, aborted: false };\n}\n\n/**\n * Map a revert outcome back to `check`'s exit code in the interactive flow (R30).\n * An aborted confirm wrote nothing to AWS, so the drift still stands — keep the\n * pre-revert code (always 1 here, the drift branch); otherwise adopt the outcome's\n * exit (0 clean / 1 drift remains / 2 failure). Pure so the asymmetry is unit-tested.\n */\nexport function resolveInteractiveRevertExit(currentCode: number, outcome: RevertOutcome): number {\n return outcome.aborted ? currentCode : outcome.exit;\n}\n\n// ---- interactive choice (pure, unit-tested) ----\n\nexport interface Actions {\n record: boolean; // an undeclared drift exists to record\n ignore: boolean; // a declared or undeclared finding exists to ignore (ignore.yaml)\n revert: boolean; // at least one finding is revertable\n}\n\n/**\n * Which interactive actions make sense for a stack's (baseline-reconciled) findings:\n * - Record when there is undeclared drift OR an out-of-band `added` resource (PR4:\n * record now snapshots added too — it can't fix declared drift, which is\n * template-vs-reality, unrelated to the baseline);\n * - Ignore when there is any declared OR undeclared finding (ignore is symmetric\n * with revert — it is the only in-tool way to accept a declared drift; R120);\n * - Revert only when buildRevertPlan yields >=1 revertable item (a stack with only\n * not-revertable findings, e.g. deleted-only, offers no Revert).\n * Pure: no AWS, no prompts. `schemas` feeds the create-only revert gate.\n */\nexport function availableActions(\n findings: Finding[],\n baseline: BaselineFile | undefined,\n schemas: Map<string, SchemaInfo>,\n removeUnrecorded: boolean\n): Actions {\n const recordable = findings.some((f) => f.tier === 'undeclared' || f.tier === 'added');\n // R141: with NO baseline file yet, `record` is ALWAYS offered — it writes the initial\n // baseline (snapshot-complete resources, plus any undeclared entries) so a fresh deploy can\n // be blessed as the day-1 baseline through `check`'s own prompt (no separate `cdkrd record`\n // step). It is offered EVEN when the only drift is a declared/deleted one it cannot itself\n // resolve: establishing the baseline STARTS undeclared watching, which is orthogonal to that\n // drift — the drift keeps being reported until the user reverts/ignores it. Withholding\n // `record` here used to force the user to clear (or permanently `ignore`) the declared drift\n // before they could even begin watching undeclared state, defeating the tool's core value.\n // `buildResolveOptions` worded the establish option honestly for that case (\"the declared\n // drift stays reported\"), so it no longer reads as \"all done\". Once a baseline exists,\n // `record` is offered only when there is undeclared/added state to snapshot.\n const record = recordable || baseline === undefined;\n const ignore = findings.some(\n (f) => f.tier === 'declared' || f.tier === 'undeclared' || f.tier === 'added'\n );\n const plan = buildRevertPlan(findings, baseline, { removeUnrecorded, schemas });\n return { record, ignore, revert: plan.items.length > 0 };\n}\n","// `cdkrd record [<stack>...] [--app ...] [--region r] [--profile p] [--yes]`\n// Write the current undeclared state into the baseline FILE(s). Writes ONLY\n// git-committed baselines; no AWS writes. The per-stack record flow lives in\n// stack-actions.ts (shared with check's interactive prompt, R28).\nimport { isStackNotDeployed, StackNotCheckableError } from '../aws-errors.js';\nimport { isInteractive, parseCommonArgs } from '../cli-args.js';\nimport { applyIgnores, loadConfig } from '../config/config-file.js';\nimport { resolveStacks } from './resolve-stacks.js';\nimport { gatherFindings } from './gather.js';\nimport { gatherWithProgress, progressLabel } from './progress.js';\nimport { recordStack } from './stack-actions.js';\n\nexport async function runRecord(args: string[]): Promise<number> {\n const a = parseCommonArgs(args);\n if (a.profile) process.env.AWS_PROFILE = a.profile;\n\n let config;\n try {\n config = await loadConfig();\n } catch (e) {\n console.error(`error: ${(e as Error).message}`);\n return 2;\n }\n\n let stacks;\n try {\n stacks = await resolveStacks(a);\n } catch (e) {\n console.error(`error: ${(e as Error).message}`);\n return 2;\n }\n if (stacks.length === 0) {\n console.error('note: the CDK app defines no stacks — nothing to record');\n return 0;\n }\n\n let worst = 0;\n // gather-phase spinner (see gatherWithProgress) — text mode + TTY only.\n const showProgress = !a.json && isInteractive();\n for (const [idx, { stackName, region, template }] of stacks.entries()) {\n if (!region) {\n console.error(\n `error: ${stackName}: no region — set env on the stack, pass --region, or set a region for the AWS profile`\n );\n worst = Math.max(worst, 2);\n continue;\n }\n try {\n // gather FIRST: the baseline filename embeds the accountId, which only the\n // gather (DescribeStackResources) resolves. (R21 — was load-then-gather.)\n // `template` (synth) recovers GetTemplate's `?`-masked non-ASCII literals.\n const { desired, findings } = await gatherWithProgress(\n showProgress,\n progressLabel(idx, stacks.length, stackName, region),\n () => gatherFindings(stackName, region, undefined, template)\n );\n // ignore rules re-tag matching undeclared findings out of the record set, so an\n // externally-managed property is never recorded (and never re-detected).\n const result = await recordStack({\n stackName,\n region,\n desired,\n findings: applyIgnores(\n findings,\n { stackName, accountId: desired.accountId, region },\n config\n ),\n yes: a.yes,\n interactive: isInteractive(),\n expandNested: a.verbose, // --verbose itemizes the nested sub-keys (--show-all is the separate inventory mode, not a picker-detail flag)\n });\n // a non-interactive record that needed a decision but had no --yes refuses (R38)\n if (result.refused) worst = Math.max(worst, 2);\n } catch (e) {\n if (isStackNotDeployed(e)) {\n console.error(`note: ${stackName}: not deployed yet — nothing to record`);\n continue;\n }\n if (e instanceof StackNotCheckableError) {\n console.error(`note: ${stackName}: ${e.message} — nothing to record`);\n continue;\n }\n console.error(`error: ${stackName}: ${(e as Error).message}`);\n worst = Math.max(worst, 2);\n }\n }\n if (worst === 0)\n console.log('commit the baseline file(s) so drift is detected against them going forward.');\n return worst;\n}\n","// `cdkrd ignore [<stack>...] [--app ...] [--region r] [--profile p] [--yes]`\n// Append ignore rules to .cdkrd/ignore.yaml for the chosen declared/undeclared drift —\n// it stops being reported entirely (the \"stop watching\" counterpart to `record`, which\n// keeps watching). Writes ONLY the git-committed config file; no AWS writes. The\n// per-stack ignore flow lives in stack-actions.ts (shared with check's interactive\n// prompt in PR-B2).\nimport { isStackNotDeployed, StackNotCheckableError } from '../aws-errors.js';\nimport {\n applyBaseline,\n checkBaselineAccount,\n declaredKeysByLogical,\n loadBaseline,\n} from '../baseline/baseline-file.js';\nimport { isInteractive, parseCommonArgs } from '../cli-args.js';\nimport { applyIgnores, loadConfig } from '../config/config-file.js';\nimport { resolveStacks } from './resolve-stacks.js';\nimport { gatherFindings } from './gather.js';\nimport { gatherWithProgress, progressLabel } from './progress.js';\nimport { ignoreStack } from './stack-actions.js';\n\nexport async function runIgnore(args: string[]): Promise<number> {\n const a = parseCommonArgs(args);\n if (a.profile) process.env.AWS_PROFILE = a.profile;\n\n let config;\n try {\n config = await loadConfig();\n } catch (e) {\n console.error(`error: ${(e as Error).message}`);\n return 2;\n }\n\n let stacks;\n try {\n stacks = await resolveStacks(a);\n } catch (e) {\n console.error(`error: ${(e as Error).message}`);\n return 2;\n }\n if (stacks.length === 0) {\n console.error('note: the CDK app defines no stacks — nothing to ignore');\n return 0;\n }\n\n let worst = 0;\n let wroteAny = false;\n // gather-phase spinner (see gatherWithProgress) — text mode + TTY only.\n const showProgress = !a.json && isInteractive();\n for (const [idx, { stackName, region, template }] of stacks.entries()) {\n if (!region) {\n console.error(\n `error: ${stackName}: no region — set env on the stack, pass --region, or set a region for the AWS profile`\n );\n worst = Math.max(worst, 2);\n continue;\n }\n try {\n const { desired, findings } = await gatherWithProgress(\n showProgress,\n progressLabel(idx, stacks.length, stackName, region),\n () => gatherFindings(stackName, region, undefined, template)\n );\n // Reconcile exactly as check does so the offered drift matches what the user saw:\n // suppress already-recorded baseline entries, then re-tag config-ignored findings\n // out (they are already `ignored`, so ignoreStack never re-offers them).\n const baseline = await loadBaseline(stackName, desired.accountId, region);\n if (baseline) checkBaselineAccount(baseline, desired.accountId, stackName);\n const reconciled = applyIgnores(\n applyBaseline(findings, baseline, {\n declaredByLogical: declaredKeysByLogical(desired.resources),\n warn: console.error,\n }),\n { stackName, accountId: desired.accountId, region },\n config\n );\n const result = await ignoreStack({\n stackName,\n findings: reconciled,\n yes: a.yes,\n interactive: isInteractive(),\n });\n if (result.wrote) wroteAny = true;\n // a non-interactive ignore that needed a decision but had no --yes refuses (R38)\n if (result.refused) worst = Math.max(worst, 2);\n } catch (e) {\n if (isStackNotDeployed(e)) {\n console.error(`note: ${stackName}: not deployed yet — nothing to ignore`);\n continue;\n }\n // A stack that exists but has no meaningful deployed state (REVIEW_IN_PROGRESS /\n // deleting): skip, not error — matching check/record/revert. There is nothing to\n // ignore, so one un-checkable stack must not drag the whole run to exit 2.\n if (e instanceof StackNotCheckableError) {\n console.error(`note: ${stackName}: ${e.message} — nothing to ignore`);\n continue;\n }\n console.error(`error: ${stackName}: ${(e as Error).message}`);\n worst = Math.max(worst, 2);\n }\n }\n if (worst === 0 && wroteAny)\n console.log('commit .cdkrd/ignore.yaml so the ignore rules apply for everyone going forward.');\n return worst;\n}\n","// Non-classifying, human-facing HINTS for findings whose live value has a recognizable\n// external origin. A hint NEVER folds or re-tiers a finding — the divergence is still\n// reported as real drift (an account-wide enablement the user did not expect must stay\n// visible). It only annotates the finding with WHERE the value likely came from, so a\n// puzzling \"I never touched this\" finding is self-explaining.\n//\n// The first (and currently only) recognized footprint is CloudWatch Application Signals /\n// Lambda Insights auto-instrumentation. When enabled at the ACCOUNT/REGION level (a\n// CloudWatch setting, not a per-resource console edit), AWS uniformly:\n// - adds the AWS-owned Lambda Insights extension LAYER to every function\n// (`arn:aws:lambda:<region>:<aws-owned-acct>:layer:LambdaInsightsExtension[-Arm64]:N`), and\n// - attaches a tracer / insights execution POLICY to each function's role\n// (`AWSLambdaTracerAccessExecutionRole-<uuid>` or `CloudWatchLambdaInsightsExecutionRolePolicy`).\n// Neither is a CDK-declared intent, so cdkrd surfaces them (Layers = undeclared, the extra\n// ManagedPolicyArns entry = declared drift) — correctly. This hint just names the source.\nimport type { Finding } from '../types.js';\n\nconst APP_SIGNALS_HINT =\n 'looks like CloudWatch Application Signals / Lambda Insights auto-instrumentation — ' +\n 'typically enabled at the account/region level (a CloudWatch setting), not a per-resource ' +\n 'edit; declare it in CDK to make it intent, or record/ignore to accept it';\n\n// The AWS-owned Lambda Insights extension layer name is constant across regions (only the\n// publisher account and version vary), so match on the layer-name segment.\nconst INSIGHTS_LAYER = /:layer:LambdaInsightsExtension(-Arm64)?:/;\n\n// The two managed policies Application Signals / Lambda Insights attach to a function's\n// execution role. The tracer policy carries a random UUID suffix, so match the stable stem.\nconst INSIGHTS_POLICY =\n /(AWSLambdaTracerAccessExecutionRole|CloudWatchLambdaInsightsExecutionRolePolicy)/;\n\n/** All string leaves of a value (scalar, array, or nested) — flattened. Pure. */\nfunction strings(v: unknown): string[] {\n if (typeof v === 'string') return [v];\n if (Array.isArray(v)) return v.flatMap(strings);\n return [];\n}\n\n/**\n * The hint for a single finding, or undefined if none applies. Pure + exported for tests.\n * Path is matched leniently (bare `Layers`, an indexed `Layers[0]`, or a nested\n * `...ManagedPolicyArns`) so the same detector fires whether the property surfaced whole or\n * per-element. For the role policy — a DECLARED drift carrying both sides — only the\n * LIVE-ONLY entries (actual minus desired) are inspected, so a hint fires on the ADDED\n * policy, never on one the template already declared.\n */\nexport function findingHint(f: Finding): string | undefined {\n if (f.resourceType === 'AWS::Lambda::Function' && /(^|\\.)Layers(\\[|$)/.test(f.path)) {\n if (strings(f.actual).some((s) => INSIGHTS_LAYER.test(s))) return APP_SIGNALS_HINT;\n }\n if (f.resourceType === 'AWS::IAM::Role' && /(^|\\.)ManagedPolicyArns(\\[|$)/.test(f.path)) {\n const declared = new Set(strings(f.desired));\n const liveOnly = strings(f.actual).filter((s) => !declared.has(s));\n if (liveOnly.some((s) => INSIGHTS_POLICY.test(s))) return APP_SIGNALS_HINT;\n }\n return undefined;\n}\n\n/**\n * Return a copy of `findings` with a `hint` set on any finding whose live value has a\n * recognized external origin. Non-mutating; leaves an already-set hint untouched. Applied\n * just before the report so both the text and --json outputs carry it.\n */\nexport function annotateHints(findings: Finding[]): Finding[] {\n return findings.map((f) => {\n if (f.hint !== undefined) return f;\n const hint = findingHint(f);\n return hint === undefined ? f : { ...f, hint };\n });\n}\n","// Tiered, CI-greppable report. Plain text or --json. No TUI/panes.\n// Exit: report() returns 0 clean / 1 drift; check maps 1→0 unless --fail (R53).\n//\n// Default layout is deliberately terse (a 40-resource CLEAN stack was 30+ lines):\n// header -> DRIFT tier sections (full detail) -> result: -> info: footer\n// Spacing (R37, revised by R48): no blank line before the header; the FIRST drift\n// section follows the header directly (no stray blank); subsequent sections get a\n// blank line between them (grouping); when at least one drift section was printed\n// `result:` is FRAMED by a horizontal rule above and below (with a blank line before\n// the frame) so the verdict stands out from the wall of findings — bold alone got lost;\n// a CLEAN stack (no sections) skips the frame and stays exactly 3 lines. `result:` keeps\n// column 0 for the `^result:` grep contract (the rules are their own lines). Section\n// headers carry the count INSIDE the brackets\n// (`[CFn-Declared Drift: 3]`) — a bare digit to the right of `]` read as noise (R48);\n// the explanatory note follows outside the brackets. DRIFT tiers\n// (deleted/declared/undeclared) are ALWAYS shown in full — they are the point.\n// INFORMATIONAL tiers (readGap/unresolved/skipped) are folded into the `info:`\n// footer (counts + reason breakdown): one line when a single tier is present, a\n// one-line-per-tier bullet list when 2+ (R37); `--verbose` expands them to full\n// sections (below result, as a footer). 0-count tiers are never printed. The\n// \"surfaced, never silently dropped\" invariant is preserved by the counts.\nimport { withinStackPath } from '../construct-path.js';\nimport { deepEqual } from '../diff/drift-calculator.js';\nimport { annotateHints } from '../diff/hints.js';\nimport type { ArrayDelta, Finding, Tier } from '../types.js';\nimport { style } from './style.js';\n\n// The report header is `<stackName> (<region>)`; recover the bare stack name (used to\n// strip the stack/Stage prefix off each finding's construct path). Only a TRAILING\n// ` (...)` is removed, so a stack name that itself contains parens survives.\nfunction stackNameFromHeader(header: string): string {\n return header.replace(/\\s*\\([^)]*\\)\\s*$/, '');\n}\n\n// Strip SGR color codes to measure a line's VISIBLE width (for the result-line rule).\n// Built from the ESC char via fromCharCode so no control byte sits in a regex literal.\nconst ANSI_RE = new RegExp(`${String.fromCharCode(27)}\\\\[[0-9;]*m`, 'g');\n\n// Section headers are Title Case (not all-caps) — uniform and readable, and crucially\n// so `CFn-Declared Drift` vs `CFn-Undeclared Drift`, which share the `CFn-` prefix, the\n// ` Drift` suffix, and the same red colour, read as distinct WORDS at a glance instead\n// of two near-identical all-caps tokens (R130 dogfood). `CFn` / `AWS` stay as the\n// acronyms they are. The not-in-baseline section is `[Potential Drift]` (literal below):\n// live-only values with no baseline yet, so cdkrd can't confirm them as drift or not —\n// it ties directly to the `cdkrd record` verb (record resolves the ambiguity).\nconst TIER_NAMES: Record<Tier, string> = {\n deleted: 'Deleted',\n added: 'Added Resource',\n declared: 'CFn-Declared Drift',\n undeclared: 'CFn-Undeclared Drift',\n atDefault: 'At AWS Default',\n generated: 'AWS Generated',\n ignored: 'Ignored',\n readGap: 'Read Gap',\n unresolved: 'Unresolved',\n skipped: 'Skipped',\n};\n// Explanation printed after the bracketed name+count, outside the brackets.\n// The notes anchor the THREE sources cdkrd touches, so \"declared\" is never misread as\n// \"in my CDK code\" or \"in the .cdkrd baseline\": (1) the DEPLOYED CloudFormation template\n// (declared/undeclared), (2) the live resource (undeclared = live-only), (3) the .cdkrd\n// baseline file (recorded/unrecorded — a separate axis).\nconst TIER_NOTES: Partial<Record<Tier, string>> = {\n deleted: 'resource deleted out of band — always drift',\n added:\n 'a WHOLE live resource not in your CloudFormation template (the resource-level counterpart of CFn-Undeclared) — created out of band under a declared parent, changed from your .cdkrd baseline (an unrecorded one is Potential Drift, not confirmed drift)',\n declared: 'declared in your CloudFormation template — the live value differs',\n undeclared:\n 'live-only (not in your CloudFormation template), changed from your .cdkrd baseline — the differentiator',\n atDefault: 'undeclared, but the live value matches a known AWS default — not drift',\n generated: 'auto-generated identifier not in your template (AWS-assigned at deploy) — not drift',\n ignored: 'matched a .cdkrd/ignore.yaml ignore rule — not drift',\n readGap: \"declared, but AWS doesn't return it on read so cdkrd can't verify it — not drift\",\n unresolved:\n \"declared, but its value references a CloudFormation intrinsic cdkrd couldn't resolve to a concrete value — e.g. Fn::GetAZs, a {{resolve:...}} dynamic reference, or an Fn::GetAtt whose target wasn't readable — so it can't be compared, not drift\",\n skipped:\n 'NOT checked (coverage incomplete) — CC API unsupported / no physical id / custom resource',\n};\n// Section + result-line order (both iterate this). `added` (whole out-of-band\n// resources) sorts AFTER the property tiers — declared/undeclared are the per-property\n// differentiator the report leads with, and the resource-level `added` follows them.\n// `deleted` stays first (the most blatant drift).\nconst DRIFT_TIERS: Tier[] = ['deleted', 'declared', 'undeclared', 'added'];\n// atDefault leads the informational footer: it is the bulk of a first run (undeclared\n// values sitting at their AWS default) and folding it is the whole point of R86 — the\n// report states the complete undeclared count but lists only the values that actually\n// diverge, with the at-default remainder collapsed to a count (expanded by --verbose\n// or --show-all).\nconst INFO_TIERS: Tier[] = [\n 'atDefault',\n 'generated',\n 'ignored',\n 'readGap',\n 'unresolved',\n 'skipped',\n];\n\nexport interface ReportOptions {\n json?: boolean;\n verbose?: boolean; // expand informational tiers (readGap/unresolved/skipped) to full lists\n expandAtDefault?: boolean; // expand ONLY the atDefault tier to a full list (--show-all inventory mode)\n log?: (s: string) => void;\n}\n// Unrecorded values (R60, per finding since R62): an undeclared finding tagged\n// `unrecorded` by applyBaseline (no baseline entry, resource never\n// snapshot-complete) is an inventory awaiting a decision, not drift — the\n// baseline entry is the contract that defines undeclared drift, and with no\n// entry there is nothing to violate. They render as their own [Potential Drift: N]\n// section, are excluded from the drift verdict/exit, and the result line points\n// at `cdkrd record`.\n\nexport function formatFinding(f: Finding, stackName = ''): string {\n // prefer the CDK construct path for the human-facing id; fall back to logical id\n // (the id stays uncolored — it gets copy-pasted; only the values are styled,\n // and style.* is the identity when stdout is not a TTY, so piped output and\n // unit-test assertions see plain text). The construct path is shown WITHIN its stack\n // (the stack/Stage prefix stripped — the header already names the stack), so a Stage's\n // `dev-main/AuroraDB/...` no longer sits beside the `dev-main-AuroraDB` header looking\n // like a different id. `stackName` defaults to '' (no strip) for direct unit calls; the\n // report passes the real name. The displayed id stays byte-identical to the ignore-rule\n // path token (both are `withinStackPath(...).<path>`), so what you see IS what an\n // ignore.yaml rule uses.\n const id = f.constructPath ? withinStackPath(f.constructPath, stackName) : f.logicalId;\n // R78: an ELB attribute-bag drift names the changed attribute by Key\n // (LoadBalancerAttributes[idle_timeout.timeout_seconds]) rather than a bare\n // array index, so the report points at the exact setting.\n const pathDisplay = f.attributeKey ? `${f.path}[${f.attributeKey}]` : f.path;\n let s = `${pathDisplay ? `${id}.${pathDisplay}` : id} (${f.resourceType})`;\n if (f.note) s += ` — ${f.note}`;\n if (f.tier === 'declared') {\n // A map-valued drift (both sides objects) is shown as a per-KEY delta, not a truncated\n // whole-object dump (see formatMapDelta) — the user's case: one ResponseParameters\n // header value changed but the raw pair-truncation windowed on the template-vs-live key\n // ORDER and hid it. A scalar drift keeps the plain desired/actual lines.\n if (isRecord(f.desired) && isRecord(f.actual)) s += formatMapDelta(f.desired, f.actual, false);\n else {\n const { a: d, b: act } = jPair(f.desired, f.actual);\n s += `\\n desired=${style.desired(d)}\\n actual =${style.actual(act)}`;\n }\n } else if (f.tier === 'added' && f.desired !== undefined) {\n // PR4: a recorded `added` resource whose live model CHANGED since record — show the\n // recorded baseline model vs the live one so the user sees WHAT changed. Both are full\n // models (objects), so the same per-key delta applies (baseline-vs-actual labels).\n if (isRecord(f.desired) && isRecord(f.actual)) s += formatMapDelta(f.desired, f.actual, true);\n else {\n const { a: base, b: act } = jPair(f.desired, f.actual);\n s += `\\n baseline=${style.desired(base)}\\n actual =${style.actual(act)}`;\n }\n } else if (f.tier === 'undeclared' && f.arrayDelta)\n // R128: a recorded identity-keyed array changed — show the element delta, not the\n // whole array dump (the property stays recorded; this is the WHICH-element view).\n s += formatArrayDelta(f.arrayDelta);\n else if (f.tier === 'undeclared' || f.tier === 'atDefault' || f.tier === 'generated')\n // Put the live value on its OWN indented line, aligned with declared's `actual =`\n // column — a long ARN/JSON list crammed inline after the id was unreadable, and it read\n // inconsistently next to a declared drift's stacked desired/actual. An undeclared value\n // has only the live side, so it's a single `actual =` line (no desired to contrast).\n s += `\\n actual =${style.actual(j(f.actual))}`;\n // A non-classifying origin hint (diff/hints.ts) — the finding is still real drift; this\n // just names where the live value likely came from. Readable (style.note) trailing line\n // below the values — it is meant to be read, so NOT dim.\n if (f.hint) s += `\\n ${style.note(`↳ ${f.hint}`)}`;\n return s;\n}\n\nconst isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v);\n\n// Render a CHANGED MAP as a per-key delta — only the keys that actually differ — instead of\n// a truncated whole-object dump of both sides. A free-form map whose keys hold the path\n// grammar's separators (`method.response.header.X`, a Docker label `com.example.x`, a tag\n// key with a `.`) is emitted WHOLE by the drift calculator (the dotted key can't ride the\n// finding path safely — drift-calculator `hasPathUnsafeKey`). So `desired`/`actual` are the\n// full maps, and because the deployed template's key ORDER differs from the live read's, a\n// raw `jPair` pair-truncation windows on the key-order divergence and HIDES the one value\n// the user changed (e.g. an Access-Control-Allow-Origin header). Showing only the diverging\n// keys pinpoints the change. Walks the UNION so a key present on one side only is shown too;\n// a value change uses `jPair` so a long value still truncates around its divergence.\n// `baselineLabels` swaps desired/actual wording for the `added` (baseline-vs-live) tier.\nfunction formatMapDelta(\n desired: Record<string, unknown>,\n actual: Record<string, unknown>,\n baselineLabels: boolean\n): string {\n const lhs = baselineLabels ? 'baseline' : 'desired';\n const rhs = baselineLabels ? 'actual ' : 'actual ';\n const keys = [...new Set([...Object.keys(desired), ...Object.keys(actual)])].sort();\n let s = '';\n for (const k of keys) {\n const inD = Object.hasOwn(desired, k);\n const inA = Object.hasOwn(actual, k);\n if (inD && inA) {\n if (deepEqual(desired[k], actual[k])) continue;\n const { a, b } = jPair(desired[k], actual[k]);\n s += `\\n ~ ${k}\\n ${lhs}=${style.desired(a)}\\n ${rhs}=${style.actual(b)}`;\n } else if (inD) {\n s += `\\n - ${k} (in ${baselineLabels ? 'baseline' : 'template'}, absent in live)\\n ${lhs}=${style.desired(j(desired[k]))}`;\n } else {\n s += `\\n + ${k} (in live, not in ${baselineLabels ? 'baseline' : 'template'})\\n ${rhs}=${style.actual(j(actual[k]))}`;\n }\n }\n // A whole-object swap with NO per-key difference shouldn't happen (deepEqual gates the\n // finding), but fall back to the plain pair so a finding never renders value-less.\n if (s === '') {\n const { a, b } = jPair(desired, actual);\n s = `\\n ${lhs}=${style.desired(a)}\\n ${rhs}=${style.actual(b)}`;\n }\n return s;\n}\n\n// R128/R130: render an identity-keyed array delta as one block per changed element\n// (added / changed / removed), keyed by its identity value — far more legible than a\n// whole-array dump when only one element of many differs. The element id sits on its\n// own marker line (+ added / ~ changed / - removed); the baseline / actual value(s)\n// follow on their own indented lines (mirrors the declared tier's desired/actual\n// layout — `baseline`/`actual` are padded so the `=` aligns), so two long policy\n// documents are read top-to-bottom instead of wrapping on one line (R130).\nfunction formatArrayDelta(d: ArrayDelta): string {\n // 8 = len('baseline'); pad 'actual' to match so the '=' column lines up.\n const baseline = (v: unknown): string => `\\n baseline=${style.desired(j(v))}`;\n const actual = (v: unknown): string => `\\n actual =${style.actual(j(v))}`;\n let s = ` — ${d.identityField}-keyed element(s) changed vs .cdkrd baseline:`;\n for (const a of d.added) s += `\\n + [${a.id}]${actual(a.value)}`;\n for (const c of d.changed) {\n // pair-aware truncation so a long recorded-vs-live element shows WHERE it diverges\n const { a: base, b: act } = jPair(c.recorded, c.actual);\n s += `\\n ~ [${c.id}]\\n baseline=${style.desired(base)}\\n actual =${style.actual(act)}`;\n }\n for (const r of d.removed) s += `\\n - [${r.id}]${baseline(r.value)}`;\n return s;\n}\n\n// section-title color by tier: deleted/declared = red (drift), undeclared =\n// yellow (the differentiator), informational tiers = readable default (style.note,\n// not dim — a --verbose info section is content to read).\nfunction tierStyle(t: Tier): (s: string) => string {\n // All three DRIFT tiers are RED — they are drift (exit-affecting). undeclared was\n // previously yellow (undeclaredTier), which collided with the [Potential Drift] section\n // (also yellow) and made a real undeclared DRIFT look identical to a not-drift\n // unrecorded value. Yellow (undeclaredTier) is now reserved for UNRECORDED / \"to\n // review\" — so colour alone separates drift (red) from to-review (yellow). R125.\n if (t === 'deleted' || t === 'added' || t === 'declared' || t === 'undeclared')\n return style.driftTier;\n return style.note;\n}\n\n// A short, human label for WHY an informational finding is not actionable drift, so\n// the `info:` summary can break a tier's count down by cause.\nfunction reasonKey(f: Finding): string {\n const n = f.note ?? '';\n if (f.tier === 'ignored') return n.replace(/^ignored by config rule /, '') || 'ignored';\n if (f.tier === 'unresolved') return 'intrinsic unresolved';\n if (n.includes('write-only')) return 'write-only';\n if (n.startsWith('custom resource')) return 'custom resource';\n if (n.includes('target not resolvable')) return 'override target unresolved';\n if (n.startsWith('CC API: ')) return `CC ${n.slice('CC API: '.length)}`;\n if (n === 'no physical id') return 'no physical id';\n return n || 'other';\n}\n\nfunction groupReasons(items: Finding[]): string {\n const counts = new Map<string, number>();\n for (const f of items) {\n const k = reasonKey(f);\n counts.set(k, (counts.get(k) ?? 0) + 1);\n }\n return [...counts.entries()]\n .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))\n .map(([k, c]) => `${k} ${c}`)\n .join(', ');\n}\n\nexport function report(rawFindings: Finding[], header: string, opts: ReportOptions = {}): number {\n const log = opts.log ?? console.log;\n const stackName = stackNameFromHeader(header);\n // Annotate origin hints (diff/hints.ts) here, at the single render chokepoint, so the\n // text report, the --json payload, and the --pre-deploy report all carry them. A hint is\n // display-only — it never changes a tier — so the `drifted` verdict below is unaffected.\n const findings = annotateHints(rawFindings);\n // unrecorded findings (R60/R62): an inventory awaiting a baseline decision,\n // not drift — they never count toward the verdict or the exit.\n const isDriftHere = (f: Finding): boolean => DRIFT_TIERS.includes(f.tier) && !f.unrecorded;\n const drifted = findings.filter(isDriftHere).length;\n\n if (opts.json) {\n log(JSON.stringify({ stack: header, drifted, findings }, null, 2));\n return drifted === 0 ? 0 : 1;\n }\n\n const byTier = (t: Tier) => findings.filter((f) => f.tier === t && !f.unrecorded);\n const unrecordedItems = findings.filter((f) => f.unrecorded === true);\n // SURFACE every nested undeclared value (a live sub-key inside a DECLARED object the\n // template never set) in [Potential Drift], like a top-level one. R96 originally FOLDED\n // them behind a count + --show-all because the live model materializes many nested AWS\n // defaults. But those catalogued defaults are already removed UPSTREAM (atDefault /\n // generated / KNOWN_DEFAULT_PATHS / schema defaults), so what still reaches the report as\n // tier:undeclared nested is a NON-default value the user most likely set out of band —\n // e.g. an ApiGateway Method Integration.PassthroughBehavior=NEVER or an\n // IntegrationResponses[x].SelectionPattern. That undeclared-property dimension IS cdkrd's\n // differentiator, so hiding it defeated the point. An uncatalogued AWS-populated nested\n // value that slips through is quieted by EXTENDING KNOWN_DEFAULT_PATHS (the same catalogue\n // model as top-level), never by hiding the whole class. `nestedFolded` stays (empty) so the\n // folded-count machinery below is a no-op rather than a special case.\n const unrecordedShown = unrecordedItems;\n const nestedFolded: Finding[] = [];\n // Count inside the brackets (`[NAME: N]`), explanation outside (readable — style.note,\n // not dim: it is meant to be read) — see the\n // layout comment at the top (R48). `leadingBlank` separates a section from\n // whatever precedes it; the FIRST drift section sits directly under the header.\n const section = (\n items: Finding[],\n name: string,\n note: string | undefined,\n color: (s: string) => string,\n leadingBlank: boolean\n ): boolean => {\n if (items.length === 0) return false; // 0-count tiers are never printed\n log(\n (leadingBlank ? '\\n' : '') +\n color(`[${name}: ${items.length}]`) +\n (note ? ' ' + style.note(`(${note})`) : '')\n );\n for (const f of items) log(' ' + formatFinding(f, stackName));\n return true;\n };\n const tierSection = (tier: Tier, leadingBlank: boolean): boolean =>\n section(byTier(tier), TIER_NAMES[tier], TIER_NOTES[tier], tierStyle(tier), leadingBlank);\n\n log(style.header(`=== check: ${header} ===`));\n // When STANDOUT live-only values have no baseline yet, say so up front: with nothing\n // to compare against, cdkrd genuinely CANNOT tell whether they are intentional or an\n // out-of-band change — that ambiguity (not \"all clear\") is why they are POTENTIAL\n // drift. Gated on the SHOWN count: nested undeclared values now surface too (R96 fold\n // removed), and they are exactly the live-only sub-keys this preamble describes.\n if (unrecordedShown.length > 0) {\n log(\n style.undeclaredTier(\n \"No baseline yet — these live-only values can't be confirmed as drift. Record them right from this `cdkrd check` prompt, or run `cdkrd record`.\"\n )\n );\n log(''); // blank line so the no-baseline note reads as its own preamble, not a section header\n }\n // DRIFT tiers: always full detail (the point of the tool)\n let driftSections = 0;\n for (const tier of DRIFT_TIERS) {\n if (tierSection(tier, driftSections > 0)) driftSections++;\n }\n // UNRECORDED: full detail like a drift section (these values await a decision —\n // hiding them would defeat the differentiator), but kept OUT of the verdict.\n if (\n section(\n unrecordedShown,\n 'Potential Drift',\n \"live-only and not yet in your .cdkrd baseline, so cdkrd can't tell whether it's intended or an out-of-band change — Record to accept it, or Revert to remove it\",\n style.undeclaredTier,\n driftSections > 0\n )\n ) {\n driftSections++;\n // Potential drift is UNCONFIRMED by definition (no baseline), so it is the one tier\n // where a value can be a false positive — an AWS-managed default or noise that slipped\n // the fold tables. Point the user at the issue tracker so those become fold-table fixes.\n // Scoped to THIS tier only (a `↳` note like the origin hint): declared / deleted drift\n // is confirmed against the template, never guessed, so it carries no such caveat.\n log(\n style.note(\n ' ↳ this tier is a best-effort guess and can include false positives — if a value here is really an AWS-managed default or noise, please report it: https://github.com/go-to-k/cdk-real-drift/issues'\n )\n );\n }\n // result: line — the conclusion. Lists ONLY the non-zero DRIFT tier counts (the\n // informational breakdown lives on the `info:` line, so the two never duplicate);\n // CLEAN prints just `CLEAN`. `^result:` stays greppable for the verdict; the formal\n // machine-readable contract is `--json` (the info: footer may span lines).\n const driftCounts = DRIFT_TIERS.filter((t) => byTier(t).length > 0)\n .map((t) => `${t}=${byTier(t).length}`)\n .join(' ');\n const unrecordedFoldedCount = unrecordedItems.length - unrecordedShown.length;\n // R114: when DRIFT and standout UNRECORDED values are BOTH visible, a lone\n // \"1 drift(s)\" verdict reads as a mismatch against the 2+ printed blocks (the user\n // sees [CFn-Declared Drift: 1] + [Potential Drift: 2] but a single \"1 drift\"). Combine them\n // under one findings count — `N findings — X drift (...) + Y potential drift` —\n // keeping the red drift verdict and its breakdown so exit-1 stays legible, and\n // counting only what is SHOWN (folded values are not findings, just a parenthetical).\n // The combined framing fires ONLY in this mixed case; single-category runs keep their\n // natural verdict (CLEAN / N drift / inventory note) — the mismatch can't arise there.\n // \"potential drift\" counts the SHOWN live-only values — which now include nested\n // undeclared sub-keys (R96's fold was removed: catalogued AWS defaults are stripped\n // upstream, so a surviving nested undeclared value is a real out-of-band setting worth\n // surfacing). `folded` is therefore 0 in practice; the `(+ N nested live-only to record)`\n // tail and the folded branches below stay only so a future re-fold needs no rewiring.\n const shown = unrecordedShown.length;\n const folded = unrecordedFoldedCount;\n const nestedTail = folded > 0 ? ` (+ ${folded} nested live-only to record)` : '';\n const mixed = drifted > 0 && shown > 0;\n let resultBody: string;\n if (mixed) {\n // R114: DRIFT + standout potential both visible -> one combined findings count so the\n // verdict matches the printed blocks (was a lone \"1 drift(s)\" beside 2 sections).\n resultBody =\n `${drifted + shown} findings — ${style.drift(`${drifted} drift`)} (${driftCounts})` +\n ` + ${style.undeclaredTier(`${shown} potential drift`)}` +\n style.note(nestedTail);\n } else {\n // the verdict is the one line that must stand out: green CLEAN / red drift count.\n // \"CLEAN\" is reserved for a truly clean stack (nothing unrecorded). With only FOLDED\n // nested live-only values it is \"no confirmed drift\" + a neutral \"to record\" count\n // (NOT potential drift). With SHOWN standout values it is \"no confirmed drift · N\n // potential drift\" — those are what cdkrd genuinely cannot yet judge.\n const verdict =\n drifted > 0\n ? `${style.drift(`${drifted} drift(s)`)} (${driftCounts})`\n : shown > 0 || folded > 0\n ? 'no confirmed drift'\n : style.clean('CLEAN');\n const unrecordedNote =\n shown > 0\n ? style.undeclaredTier(` · ${shown} potential drift`) + style.note(nestedTail)\n : folded > 0\n ? style.note(` · ${folded} live-only value(s) to record as baseline (run cdkrd record)`)\n : '';\n resultBody = `${verdict}${unrecordedNote}`;\n }\n // The verdict is the one line that must stand out. Bold alone got lost under a wall of\n // findings, so when drift sections were printed the verdict is FRAMED with a horizontal\n // rule above and below (and a blank line separating it from the section above — R48). A\n // leading glyph was rejected: `result:` must stay at column 0 for the `^result:` CI/integ\n // grep contract, and the rules are their own lines so grep is untouched. The rule width\n // tracks the (uncolored) verdict length so it reads intentional. A CLEAN stack (no\n // sections) keeps its compact 3-line form — nothing above it to get lost under.\n const resultLine = `${style.resultLabel('result:')} ${resultBody}`;\n if (driftSections > 0) {\n const width = resultLine.replace(ANSI_RE, '').length;\n const rule = style.note('─'.repeat(width));\n log('\\n' + rule);\n log(resultLine);\n log(rule);\n } else {\n log(resultLine);\n }\n // INFORMATIONAL tiers: footer below result. Each tier is either EXPANDED to a full\n // section or FOLDED into the `info:` summary. --verbose expands all of them;\n // --show-all expands ONLY atDefault (inventory mode lists every undeclared value but\n // keeps the read-gap/skip breakdown terse). A tier's count is always stated, so the\n // \"surfaced, never silently dropped\" invariant holds whichever way it renders.\n const isExpanded = (t: Tier): boolean =>\n !!opts.verbose || (t === 'atDefault' && !!opts.expandAtDefault);\n for (const tier of INFO_TIERS) if (isExpanded(tier)) tierSection(tier, true);\n const summaryFor = (t: Tier, items: Finding[]): string => {\n // atDefault / generated each have a single cause, so the generic reason-breakdown\n // would just echo the count — give them a plain-English label instead.\n if (t === 'atDefault')\n return `atDefault=${items.length} (undeclared values matching a known AWS default — not drift)`;\n if (t === 'generated')\n return `generated=${items.length} (auto-generated identifiers not in your template, AWS-assigned at deploy — not drift)`;\n // readGap is jargon (\"not returned by live read\"): spell out that these are declared\n // values cdkrd could not VERIFY because AWS does not return them on read, and split\n // the cause (write-only props are never readable by design vs simply not returned).\n if (t === 'readGap') {\n const writeOnly = items.filter((f) => (f.note ?? '').includes('write-only')).length;\n const notReturned = items.length - writeOnly;\n const parts = [\n ...(notReturned > 0 ? [`${notReturned} not returned by AWS`] : []),\n ...(writeOnly > 0 ? [`${writeOnly} write-only`] : []),\n ];\n return `readGap=${items.length} (declared but unverifiable — AWS doesn't return them on read, not drift: ${parts.join(', ')})`;\n }\n // unresolved is jargon too: these are declared values whose CloudFormation intrinsic\n // cdkrd could not resolve to a concrete value, so there is nothing concrete to compare\n // against live — unverifiable, not drift. The representative examples are ones that are\n // resolution-unable BY NATURE: Fn::GetAZs and {{resolve:...}} dynamic references (SSM /\n // Secrets Manager). Fn::GetAtt is NOT listed bare — cdkrd re-resolves it once the target\n // is read live (gather.ts), so it lands here only when the target itself wasn't readable.\n // The generic groupReasons breakdown would just echo \"intrinsic unresolved N\", so spell it out.\n if (t === 'unresolved')\n return `unresolved=${items.length} (declared values whose CloudFormation intrinsic cdkrd couldn't resolve to a concrete value — e.g. Fn::GetAZs, a {{resolve:...}} dynamic reference, or an Fn::GetAtt whose target wasn't readable — unverifiable, not drift)`;\n // skipped = resources cdkrd genuinely could NOT read this run (CC-unsupported with\n // no SDK override, read error, missing physical id, custom resource). It is the one\n // info: tier that is a COVERAGE GAP, not a not-drift classification — so it carries\n // the \"NOT checked / coverage incomplete\" framing here (R28-era loud coverage warning,\n // folded into the footer in R127 so the drift result stays the first thing on screen).\n if (t === 'skipped')\n return `skipped=${items.length} — NOT checked (coverage incomplete: ${groupReasons(items)})`;\n return `${t}=${items.length} (${groupReasons(items)})`;\n };\n const summaries = INFO_TIERS.filter((t) => !isExpanded(t))\n .map((t) => {\n const items = byTier(t);\n return items.length ? summaryFor(t, items) : null;\n })\n .filter((s): s is string => s !== null);\n // R96: the folded nested-unrecorded count joins the info: footer (--show-all lists them).\n // Labelled `undeclared-subkey` rather than the bare `nested` — \"nested\" reads as a\n // nested STACK, but these are undeclared live-only sub-keys INSIDE a declared object,\n // not a stack relationship.\n if (nestedFolded.length > 0)\n summaries.push(\n `undeclared-subkey=${nestedFolded.length} (undeclared live-only values inside a declared object — record to record; --show-all to list)`\n );\n if (summaries.length === 1) {\n log(style.note(`info: ${summaries[0]} — run with --verbose for the list`));\n } else if (summaries.length > 1) {\n log(style.note('info:'));\n for (const s of summaries) log(style.note(` - ${s}`));\n log(style.note(' run with --verbose for the list'));\n }\n return drifted === 0 ? 0 : 1;\n}\n\n// R37: multi-stack runs print ONE blank line between consecutive stack reports —\n// never before the first (so a single-stack run has no stray leading blank). Lives\n// at the check-loop call site, not inside report(); exported pure for unit tests.\nexport function stackSeparator(log: (s: string) => void = console.log): () => void {\n let first = true;\n return () => {\n if (first) first = false;\n else log('');\n };\n}\nconst VALUE_CAP = 200;\n\n// Slice on SAFE boundaries so truncating a JSON-stringified value never splits a\n// surrogate pair (a lone surrogate renders as the replacement char `�`) or a JSON\n// escape (a dangling odd run of backslashes would escape the following `…`). Trims a\n// leading low-surrogate / trailing high-surrogate left by a mid-pair cut and a\n// trailing odd backslash run left by a mid-escape cut. Cosmetic-only (TEXT mode; the\n// `--json` path emits the raw untruncated value), but keeps long policy-doc values\n// from rendering as corrupted `\\uD83C…` / `…\\\\n\\\\…`.\nexport function safeSlice(s: string, start: number, end: number): string {\n let out = s.slice(start, end);\n if (out.length > 0) {\n const first = out.charCodeAt(0);\n if (first >= 0xdc00 && first <= 0xdfff) out = out.slice(1); // leading low surrogate\n }\n if (out.length > 0) {\n const last = out.charCodeAt(out.length - 1);\n if (last >= 0xd800 && last <= 0xdbff) out = out.slice(0, -1); // trailing high surrogate\n }\n let bs = 0;\n for (let k = out.length - 1; k >= 0 && out[k] === '\\\\'; k--) bs++;\n if (bs % 2 === 1) out = out.slice(0, -1); // trailing half-escape (odd backslash run)\n return out;\n}\n\nfunction j(v: unknown): string {\n const s = JSON.stringify(v);\n return s && s.length > VALUE_CAP ? safeSlice(s, 0, VALUE_CAP) + '…' : (s ?? String(v));\n}\n\n// Truncate a desired/actual (or baseline/actual) PAIR so the FIRST point at which the\n// two diverge is visible even when both exceed the cap — one shared window centered on\n// the divergence, applied to both. Independently slicing each at a fixed 200-char prefix\n// (the old behavior) made two long values that differ only PAST the cap render as\n// identical blobs, hiding the very change the report exists to show (common for long\n// inline-policy / bucket-policy documents). Pure + exported for tests.\nexport function jPair(a: unknown, b: unknown): { a: string; b: string } {\n const as = JSON.stringify(a) ?? String(a);\n const bs = JSON.stringify(b) ?? String(b);\n if (as.length <= VALUE_CAP && bs.length <= VALUE_CAP) return { a: as, b: bs };\n let i = 0;\n const min = Math.min(as.length, bs.length);\n while (i < min && as[i] === bs[i]) i++; // first index at which they differ\n const CONTEXT = 40; // chars of shared lead-in kept before the divergence, for orientation\n const start = Math.max(0, i - CONTEXT);\n const window = (s: string): string => {\n let out = safeSlice(s, start, start + VALUE_CAP);\n if (start > 0) out = `…${out}`;\n if (start + VALUE_CAP < s.length) out = `${out}…`;\n return out;\n };\n return { a: window(as), b: window(bs) };\n}\n","// Per-finding action picker for check's interactive \"Decide per finding\" path (R121).\n//\n// The bulk options (Record / Ignore / Revert) apply ONE action to every\n// applicable finding. When a stack mixes findings that each deserve a different verb,\n// this picker assigns an action PER finding in a single screen:\n// ↑↓ = move · space = cycle the focused row's action · → = set every VISIBLE row to\n// the focused row's action · type = filter rows by label · ⌫ = clear filter · enter = apply\n// Type-to-filter (R132): with many findings the target property is hard to spot, so any\n// printable character narrows the visible rows to those whose label contains the typed\n// text (case-insensitive); the chosen actions on hidden rows are PRESERVED (actions stay\n// indexed by ORIGINAL row). → then applies only to the visible (filtered) set, making\n// \"filter to Tags, → record\" a targeted bulk-apply. Movement is arrows-only — j/k are\n// freed up as filter input.\n// There is deliberately no ← (the bulk-multiselect uses ←/→ for none/all; here → is\n// the only bulk key and space cycles, so the two prompts stay key-consistent without\n// ← meaning two different things). Each row cycles through only the actions that APPLY\n// to its tier, plus `skip` (the default — nothing happens to a skipped finding).\n//\n// Built on `@clack/core`'s low-level `Prompt` (like bulk-multiselect builds on\n// `MultiSelectPrompt`) so it can bind these keys directly. All decision logic is pure\n// and unit-tested; the prompt is a thin rendering/key shell.\nimport { isCancel, Prompt } from '@clack/core';\nimport { S_BAR, S_BAR_END, S_BAR_START } from '@clack/prompts';\nimport { isManagedPolicyAttachmentMember, isUnrevertableNested } from '../revert/plan.js';\nimport type { Finding } from '../types.js';\nimport { style } from '../report/style.js';\n\n// `skip` is always available (the default); the others are gated by tier.\nexport type FindingAction = 'record' | 'ignore' | 'revert' | 'skip';\n\n/**\n * The actions that apply to a finding, in cycle order (EXCLUDING the always-present\n * `skip`). Mirrors the verbs' scope:\n * - undeclared → record (snapshot the norm; gentlest, keeps watching), then ignore\n * (stop watching), then revert (REMOVE the live value — destructive, so last) —\n * BUT revert is dropped for a nested undeclared value revert CANNOT target (an\n * array-element bracketed path, `isUnrevertableNested`): offering it would let the user\n * pick an action revert can't run. A pure-dotted nested value (a free-form map key like\n * an env var, or a map-shaped tag key) stays revertable;\n * - added → record (snapshot the out-of-band resource; keeps watching for changes),\n * ignore (stop watching), revert (DELETE the resource — destructive, so last). PR4\n * makes added the resource-level sibling of undeclared, so it takes the same verbs;\n * - declared → revert (restore the template intent — the natural fix), then ignore;\n * - everything else (deleted / readGap / unresolved / atDefault / generated / skipped)\n * has no in-tool action → an empty list, so it is not a decidable row.\n * Pure + exported. `isUnrevertableNested` is the SAME predicate buildRevertPlan uses, so\n * the picker's revert offer and revert's actual capability never diverge.\n */\nexport function applicableActions(finding: Finding): FindingAction[] {\n if (finding.tier === 'undeclared')\n return isUnrevertableNested(finding) && !isManagedPolicyAttachmentMember(finding)\n ? ['record', 'ignore']\n : ['record', 'ignore', 'revert'];\n if (finding.tier === 'added')\n // A `modelReadFailed` added finding carries only an identity snippet (its full model\n // could not be read this run). buildRecorded DROPS it, so offering `record` is a\n // silent no-op that the closing note still tallies as \"1 record\" — misleading. Offer\n // only ignore + revert (a delete needs only the identifier), both of which work.\n return finding.modelReadFailed ? ['ignore', 'revert'] : ['record', 'ignore', 'revert'];\n if (finding.tier === 'declared') return ['revert', 'ignore'];\n return [];\n}\n\n/** Advance the focused row's action to the next in its ring (`applicable` then `skip`,\n * wrapping). An action no longer applicable (shouldn't happen) restarts at skip. Pure. */\nexport function cycleAction(current: FindingAction, applicable: FindingAction[]): FindingAction {\n const ring: FindingAction[] = [...applicable, 'skip'];\n const i = ring.indexOf(current);\n return ring[(i + 1) % ring.length] ?? 'skip';\n}\n\n/** Set every VISIBLE row to `action` where that action applies (else `skip`); rows NOT in\n * `visible` keep their current action. The → key scopes to the current filter, so → after\n * typing a filter is a targeted bulk-apply over just the matched rows. With `visible` =\n * every index (no filter) this is the plain \"all to focused\". Pure + exported. */\nexport function setVisibleToAction(\n rows: { applicable: FindingAction[] }[],\n actions: FindingAction[],\n visible: number[],\n action: FindingAction\n): FindingAction[] {\n const vis = new Set(visible);\n return rows.map((r, i) => {\n if (!vis.has(i)) return actions[i] ?? 'skip';\n return action === 'skip' || r.applicable.includes(action) ? action : 'skip';\n });\n}\n\n/** Original-row indices whose label contains `filter` (case-insensitive, trimmed). An empty\n * filter returns every index. Backs the picker's type-to-filter: the visible set is derived,\n * so hidden rows never lose their chosen action (actions stay keyed by original index).\n * Pure + exported. */\nexport function filterRows(rows: { label: string }[], filter: string): number[] {\n const all = rows.map((_, i) => i);\n const f = filter.trim().toLowerCase();\n if (!f) return all;\n return all.filter((i) => (rows[i]?.label ?? '').toLowerCase().includes(f));\n}\n\nconst CHIP_WIDTH = 6; // max action label length ('record'/'ignore'/'revert')\n\n/** Center a short string within `width` (extra space biased right). Pure. */\nfunction center(s: string, width: number): string {\n if (s.length >= width) return s;\n const total = width - s.length;\n const left = Math.floor(total / 2);\n return `${' '.repeat(left)}${s}${' '.repeat(total - left)}`;\n}\n\n/** The bracketed, fixed-width action chip so the chips form an aligned column:\n * `[ record ]`, `[ ignore ]`, `[ revert ]`, `[ skip ]`. Pure + exported. */\nexport function actionChip(action: FindingAction): string {\n return `[ ${center(action, CHIP_WIDTH)} ]`;\n}\n\n/** The key-hint line shown under the message (readable — it is meant to be read, so\n * style.note not dim). Pure + exported for unit tests. The action picker only runs inside\n * check's interactive flow, where Esc returns to the action menu — so `esc = back` (R130). */\nexport function actionPickerHint(): string {\n return 'type = filter · ↑↓ = move · space = cycle · → = all (filtered) · ⌫ = clear · enter = apply · esc = back';\n}\n\n/**\n * Partition items by their chosen action (parallel arrays), dropping `skip`. The\n * dispatch in check.ts routes each group to record / ignore / revert. Pure + exported.\n */\nexport function groupByAction<T>(\n items: T[],\n actions: FindingAction[]\n): { record: T[]; ignore: T[]; revert: T[] } {\n const g: { record: T[]; ignore: T[]; revert: T[] } = { record: [], ignore: [], revert: [] };\n items.forEach((item, i) => {\n const a = actions[i];\n if (a === 'record' || a === 'ignore' || a === 'revert') g[a].push(item);\n });\n return g;\n}\n\n/** Tally chosen actions for the one-line submit/summary frame. Pure + exported. */\nexport function summarizeChoices(actions: FindingAction[]): string {\n const n = (a: FindingAction): number => actions.filter((x) => x === a).length;\n const parts = (['record', 'ignore', 'revert'] as const)\n .filter((a) => n(a) > 0)\n .map((a) => `${n(a)} ${a}`);\n return parts.length > 0 ? parts.join(' · ') : 'nothing selected';\n}\n\n/**\n * One rendered row: a focus pointer, the action chip, and the finding label. The\n * focused row is cyan (matches bulk-multiselect's cursor); a non-skip action is shown\n * in its accent (revert is destructive → drift-red), skip is dim. Pure + exported so\n * the \"focused row differs + action is legible\" invariant is unit-tested. R121.\n */\nexport function formatActionRow(label: string, action: FindingAction, active: boolean): string {\n const pointer = active ? '❯' : ' ';\n const chip = actionChip(action);\n const cell = `${pointer} ${chip} ${label}`;\n if (active) return style.cursor(cell);\n if (action === 'skip') return `${pointer} ${style.infoTier(chip)} ${style.infoTier(label)}`;\n const paint = action === 'revert' ? style.drift : style.ok;\n return `${pointer} ${paint(chip)} ${label}`;\n}\n\nexport interface PickerRow {\n label: string;\n applicable: FindingAction[]; // non-empty (decidable rows only); excludes skip\n}\n\n/**\n * Assemble the full prompt frame (clack bars + header + rows, or the one-line summary on\n * submit/cancel). Pure + exported so the rendering — the part hardest to exercise through\n * a real TTY — is unit-tested directly. `actionPicker`'s render() is a one-line delegate.\n */\nexport function renderPickerFrame(\n message: string,\n rows: PickerRow[],\n actions: FindingAction[],\n cursor: number,\n done: boolean,\n filter = '',\n visible?: number[]\n): string {\n if (done) return `${S_BAR_START} ${message}\\n${S_BAR} ${summarizeChoices(actions)}`;\n const vis = visible ?? rows.map((_, i) => i);\n const header = `${S_BAR_START} ${message}\\n${S_BAR} ${style.note(actionPickerHint())}`;\n // Show the active filter (and a match count) so the narrowing is visible; the row body is\n // the visible subset, with the cursor an index INTO that subset (vi), pointing at the\n // original row visible[vi].\n const filterLine =\n filter.trim().length > 0\n ? `${S_BAR} ${style.cursor(`filter: ${filter}`)}${style.note(` (${vis.length} match${vis.length === 1 ? '' : 'es'})`)}`\n : undefined;\n const body =\n vis.length === 0\n ? `${S_BAR} ${style.note(`(no rows match \"${filter.trim()}\" — ⌫ to clear)`)}`\n : vis\n .map(\n (origIdx, vi) =>\n `${S_BAR} ${formatActionRow(rows[origIdx]?.label ?? '', actions[origIdx] ?? 'skip', vi === cursor)}`\n )\n .join('\\n');\n return [header, filterLine, body, S_BAR_END].filter((l) => l !== undefined).join('\\n');\n}\n\n/**\n * Show the per-finding picker and return one action per row (parallel to `rows`), or\n * `undefined` on cancel (Ctrl+C / Esc). Every row starts at `skip`, so pressing enter\n * immediately is a safe no-op. `message` is the prompt header; the hint line is\n * appended for you.\n */\nexport async function actionPicker(\n message: string,\n rows: PickerRow[]\n): Promise<FindingAction[] | undefined> {\n const actions: FindingAction[] = rows.map(() => 'skip');\n let cursor = 0; // index INTO the visible subset, not into `rows`\n let filter = '';\n const prompt = new Prompt<FindingAction[]>(\n {\n render() {\n return renderPickerFrame(\n message,\n rows,\n actions,\n cursor,\n this.state === 'submit' || this.state === 'cancel',\n filter,\n filterRows(rows, filter)\n );\n },\n },\n false\n );\n prompt.value = actions;\n prompt.on('key', (char, info) => {\n const name = info?.name;\n const visible = filterRows(rows, filter); // current matched original-row indices\n const focused = visible[cursor]; // the original row the cursor points at (or undefined)\n // Movement is arrows-only — j/k are filter input now. Cursor wraps within the visible set.\n if (name === 'up') {\n if (visible.length > 0) cursor = (cursor - 1 + visible.length) % visible.length;\n } else if (name === 'down') {\n if (visible.length > 0) cursor = (cursor + 1) % visible.length;\n } else if (name === 'space') {\n if (focused !== undefined) {\n actions[focused] = cycleAction(actions[focused] ?? 'skip', rows[focused]?.applicable ?? []);\n prompt.value = [...actions];\n }\n } else if (name === 'right') {\n // bulk-apply the focused action to the VISIBLE (filtered) rows only\n if (focused !== undefined) {\n const next = setVisibleToAction(rows, actions, visible, actions[focused] ?? 'skip');\n for (let i = 0; i < actions.length; i++) actions[i] = next[i] ?? 'skip';\n prompt.value = [...actions];\n }\n } else if (name === 'backspace' || name === 'delete') {\n if (filter.length > 0) {\n filter = filter.slice(0, -1);\n cursor = 0;\n }\n } else if (\n // any other single printable character (not space — that cycles) is filter input\n typeof char === 'string' &&\n char.length === 1 &&\n char >= ' ' &&\n char !== ' ' &&\n !info?.ctrl &&\n !info?.meta\n ) {\n filter += char;\n cursor = 0;\n }\n });\n const result = await prompt.prompt();\n if (isCancel(result)) return undefined;\n return [...actions];\n}\n","// check's interactive after-report resolution (R28, extended R121). After `check`\n// reports drift in a TTY, it offers to resolve it inline instead of making the user\n// re-run a separate verb. The top-level choice is:\n// Record / Revert / Ignore — ONE action; its multiselect then narrows which findings\n// (and which ops) it applies to\n// Decide per finding — assign a DIFFERENT action PER finding (the picker)\n// Nothing — leave it (default)\n// Each bulk option appears only when >=1 finding can take that action; \"Decide per\n// finding\" appears only when >1 finding is decidable (with one, the bulk option already\n// IS per-finding). All paths route through the SAME stack-actions code as the standalone\n// verbs, so the interactive flow and `cdkrd record/ignore/revert` can never diverge.\nimport { isCancel, select } from '@clack/prompts';\nimport {\n applyBaseline,\n type ApplyBaselineOptions,\n type BaselineFile,\n buildRecorded,\n constructPathsByLogical,\n declaredKeysByLogical,\n loadBaseline,\n physicalIdsByLogical,\n recordedKey,\n} from '../baseline/baseline-file.js';\nimport { applyIgnores, type CdkrdConfig, loadConfig } from '../config/config-file.js';\nimport { withinStackPath } from '../construct-path.js';\nimport type { Desired } from '../desired/template-adapter.js';\nimport type { Finding, SchemaInfo } from '../types.js';\nimport {\n actionPicker,\n applicableActions,\n groupByAction,\n summarizeChoices,\n} from './action-picker.js';\nimport {\n type Actions,\n availableActions,\n ignoreStack,\n includeUnrecordedRemovals,\n recordStack,\n revertStack,\n} from './stack-actions.js';\n\nexport interface ResolveParams {\n stackName: string;\n region: string;\n desired: Desired;\n findings: Finding[]; // RAW gather findings (pre-baseline) — what the stack-actions expect\n reconciled: Finding[]; // baseline + ignore applied (exactly what the report showed)\n baseline: BaselineFile | undefined;\n schemas: Map<string, SchemaInfo>;\n liveByLogical: Map<string, Record<string, unknown>>; // logicalId -> live model, for tag-preserving revert\n config: CdkrdConfig;\n code: number; // pre-prompt exit (1 = drift, else 0)\n yes: boolean;\n removeUnrecorded: boolean;\n verbose: boolean;\n positionPrefix?: string; // `[2/3] ` in a multi-stack run, '' otherwise (issue #539)\n}\n\n/**\n * Closing note after an interactive record inside `check` (R52). A PARTIAL record used\n * to end with `baseline written: ...` and a silent failure-looking exit. State plainly\n * what remains; check is report-only (exit 0 on drift) unless --fail, and the interactive\n * prompts never fire in fail mode, so this note never coexists with a drift exit. Pure +\n * exported for tests.\n */\nexport function postRecordNote(remainingUndeclared: number, remainingDeclared: number): string {\n if (remainingDeclared > 0) {\n const alsoUndeclared =\n remainingUndeclared > 0\n ? ` ${remainingUndeclared} unrecorded value(s) also stay reported.`\n : '';\n // resolutions span the tiers: declared → fix the code / revert / ignore; deleted →\n // cdk deploy; a changed-since-record added resource → re-record (accept) / revert /\n // ignore. \"fix the code, or revert / ignore them\" covers all without listing each.\n return `record succeeded, but ${remainingDeclared} declared/deleted/added drift(s) remain un-addressed (fix the code, or revert / ignore them).${alsoUndeclared}`;\n }\n if (remainingUndeclared > 0)\n return `record succeeded — ${remainingUndeclared} unrecorded value(s) stay reported from the next check on.`;\n return 'stack is now CLEAN.';\n}\n\n// Identity shared by raw and reconciled findings (one property of one resource).\n// Includes `attributeKey` so the ELB attribute-bag findings — which all share one\n// logicalId+path (`LoadBalancerAttributes`) and differ only by attributeKey — get\n// DISTINCT keys. Without it, choosing `revert` for one bag attribute and `skip` for\n// another in the per-finding picker collapses both to one key, and the\n// `p.findings.filter(keyOf ∈ revertKeys)` re-admit in perFinding then reverts the\n// SKIPPED attribute too — an unintended AWS write. Mirrors revertOpKey in\n// stack-actions.ts (same fix, same reason). Exported for the collision unit test.\nexport const keyOf = (f: Finding): string =>\n `${f.logicalId}::${f.path}${f.attributeKey !== undefined ? `[${f.attributeKey}]` : ''}`;\n\n// The tier tag shown on each picker row. Anchors the vocabulary to its source so\n// \"declared\" is never misread as the .cdkrd baseline: CFn-declared = in the deployed\n// CloudFormation template; undeclared = live-only (not in the template); `unrecorded`\n// is the separate baseline-file axis.\nconst tierTag = (f: Finding): string =>\n f.tier === 'declared'\n ? 'CFn-declared'\n : f.tier === 'added'\n ? `added resource · live-only${f.unrecorded ? ' · unrecorded' : ''}`\n : `CFn-undeclared · live-only${f.unrecorded ? ' · unrecorded' : ''}`;\n\n// Show `attributeKey` (e.g. `LoadBalancerAttributes[idle_timeout.timeout_seconds]`)\n// so ELB attribute-bag rows are distinguishable in the picker — without it the bag's\n// rows render identically and the user can't tell which attribute they're deciding\n// on (mirrors report.ts's `path[attributeKey]`).\nexport const pickerLabel = (f: Finding, stackName = ''): string => {\n const id = f.constructPath ? withinStackPath(f.constructPath, stackName) : f.logicalId;\n return `${id}${f.path ? `.${f.path}` : ''}${\n f.attributeKey !== undefined ? `[${f.attributeKey}]` : ''\n } (${tierTag(f)})`;\n};\n\n// Mirrors report.ts's R96 fold: a NESTED unrecorded undeclared value (a live-only sub-key\n// inside a declared object) collapses out of the report body by default — the live model\n// carries many such sub-keys, so listing them all re-floods the first run. The interactive\n// pickers mirror that fold: they default to the SHOWN findings and gate the folded ones\n// behind an explicit \"include folded\" choice, so a picker never silently balloons from the\n// report's small drift count to a wall of nested values (the 3-vs-26 surprise) — and, for\n// ignore, never blind-ignores values the user never saw. `--verbose` means the report\n// already listed them in full, so nothing is folded. A free-form map key (freeFormKey) is\n// NEVER folded — the report shows it, so the picker itemizes it too. Pure + exported for tests.\nexport const isFoldedFinding = (f: Finding, verbose: boolean): boolean =>\n !verbose && f.unrecorded === true && f.nested === true && !f.freeFormKey;\n\n// The two scope rows shown when check folded undeclared inventory out of the report:\n// decide on just what was shown, or pull the folded values in too. Pure + exported.\nexport function buildScopeOptions(\n shownCount: number,\n foldedCount: number\n): { value: string; label: string }[] {\n return [\n { value: 'shown', label: `Just the ${shownCount} shown in the report` },\n {\n value: 'all',\n label: `Also the ${foldedCount} folded undeclared value(s) (${shownCount + foldedCount} total)`,\n },\n ];\n}\n\n/**\n * Ask which findings the ignore / per-finding picker should cover when check folded\n * undeclared inventory out of the report body. Returns 'shown' (default) or 'all', or\n * `null` on cancel (→ back to the menu). No prompt — and 'all' returned — when there is no\n * meaningful split: nothing folded, nothing else shown, or `--yes` (the caller asked not\n * to be prompted, so it gets the full set, matching the pre-gate `--yes` behaviour). The\n * `--yes` case never reaches the AWS-mutating revert through here (revert has no gate).\n */\nasync function chooseScope(\n stackName: string,\n shownCount: number,\n foldedCount: number,\n yes: boolean\n): Promise<'shown' | 'all' | null> {\n if (yes || foldedCount === 0 || shownCount === 0) return 'all';\n const choice = await select({\n message: `${stackName}: the report folded ${foldedCount} undeclared value(s) — which to decide on?`,\n options: buildScopeOptions(shownCount, foldedCount),\n initialValue: 'shown',\n });\n if (isCancel(choice)) return null;\n return choice as 'shown' | 'all';\n}\n\n// declared/constructPath/physicalId maps for applyBaseline. The physicalId + the\n// constructPath are what a synthesized \"baseline value removed since record\" finding\n// needs (physicalId so a later in-menu revert can act on it, constructPath so an\n// ignore rule matches); shared so every re-reconciliation here matches stack-actions.\nconst baselineOpts = (p: ResolveParams): ApplyBaselineOptions => ({\n declaredByLogical: declaredKeysByLogical(p.desired.resources),\n constructPathByLogical: constructPathsByLogical(p.desired.resources),\n physicalIdByLogical: physicalIdsByLogical(p.desired.resources),\n});\n\n/**\n * Re-evaluate check's exit WITHOUT re-reading AWS: reload the (possibly just-written)\n * baseline + config and re-apply them to the original gather findings. Declared/deleted\n * drift that the user did not resolve keeps exit 1; ignored findings now drop to the\n * `ignored` tier (config reloaded) and reverted findings are excluded as resolved.\n * Undeclared/unrecorded values never set the exit (R60/R52). TTY-only, so no CI contract.\n */\nasync function recomputeExit(p: ResolveParams, resolvedKeys: Set<string>): Promise<number> {\n const nb = await loadBaseline(p.stackName, p.desired.accountId, p.region);\n const nc = await loadConfig();\n const reEval = applyIgnores(\n applyBaseline(p.findings, nb, baselineOpts(p)),\n { stackName: p.stackName, accountId: p.desired.accountId, region: p.region },\n nc\n );\n const remainingDeclared = reEval.filter(\n (f) =>\n // PR4: an UNRECORDED added resource is inventory, not drift (like an unrecorded\n // undeclared value), so it must NOT keep exit 1 — only a recorded-but-changed\n // added resource counts. declared/deleted are never unrecorded.\n (f.tier === 'declared' || f.tier === 'deleted' || (f.tier === 'added' && !f.unrecorded)) &&\n !resolvedKeys.has(keyOf(f))\n ).length;\n return remainingDeclared > 0 ? 1 : 0;\n}\n\n/**\n * Outcome of a sub-action (one menu choice carried out).\n * - `exit`: the exit contribution after the action.\n * - `awsMutated`: whether the action wrote to AWS (a revert ran). A NON-AWS action\n * (record/ignore) only writes the local baseline/config, so its effect is fully\n * re-derivable by reloading those files — the chain loop re-reconciles and re-shows\n * the menu so leftover drift it could not touch (e.g. a declared drift after Record)\n * is not a dead-end. An AWS-mutating action is TERMINAL: revert already re-checked\n * convergence against live AWS and returned its exit, and we deliberately do NOT\n * re-read AWS in the loop, so re-deriving from the (now stale) findings would be wrong.\n * A `null` sub-action result means its prompt was cancelled (nothing happened) → re-show\n * the SAME menu.\n */\ninterface SubResult {\n exit: number;\n awsMutated: boolean;\n}\n\n/**\n * How to word the Record option (its action is always the same — snapshot undeclared into\n * the baseline, R141-establishing the file if absent — but the label must describe what it\n * actually does HERE so it never over-promises):\n * - 'snapshot' — there ARE undeclared/added values to record (baseline present or not).\n * - 'establish' — nothing undeclared to record and no baseline yet, on an otherwise\n * CLEAN stack: Record just establishes the day-1 baseline (marks reviewed).\n * - 'establish-drift' — nothing undeclared to record and no baseline yet, but a DECLARED drift\n * coexists: Record establishes the baseline + STARTS undeclared watching,\n * while that drift stays reported (revert/ignore it separately).\n * - 'establish-deleted' — same, but the coexisting drift is a DELETED declared resource: it stays\n * reported and is restored by re-deploying (NOT revert/ignore), so the\n * hint differs. Only used when there is no declared drift to take priority.\n */\nexport type RecordLabelKind = 'snapshot' | 'establish' | 'establish-drift' | 'establish-deleted';\n\nfunction recordOptionLabel(kind: RecordLabelKind): string {\n switch (kind) {\n case 'establish':\n return 'Record current state as the .cdkrd baseline (marks this stack reviewed)';\n case 'establish-drift':\n return 'Record current state as the .cdkrd baseline (start watching undeclared now — the declared drift stays reported; revert/ignore it separately)';\n case 'establish-deleted':\n return 'Record current state as the .cdkrd baseline (start watching undeclared now — the deleted-resource drift stays reported; re-deploy to restore it)';\n default:\n return 'Record undeclared (live-only) — snapshot into the .cdkrd baseline (keeps watching)';\n }\n}\n\n/**\n * Build the top-menu options for the current action surface (R133). Nothing is FIRST so\n * the safe no-op is the top row AND the default cursor — Enter is a harmless exit, never\n * an accidental write. \"Decide per finding\" appears only when >1 finding is decidable\n * (with one, a bulk option already IS per-finding). Pure + exported for tests.\n */\nexport function buildResolveOptions(\n actions: Actions,\n decidableCount: number,\n recordLabel: RecordLabelKind = 'snapshot'\n): { value: string; label: string }[] {\n const options: { value: string; label: string }[] = [\n { value: 'nothing', label: 'Nothing (decide later)' },\n ];\n if (actions.record) options.push({ value: 'record-all', label: recordOptionLabel(recordLabel) });\n if (actions.revert)\n options.push({ value: 'revert-all', label: 'Revert — write the desired values back to AWS' });\n if (actions.ignore)\n options.push({\n value: 'ignore-all',\n label: 'Ignore — stop reporting it (writes .cdkrd/ignore.yaml)',\n });\n // The bulk options above each apply ONE action (the picker then narrows WHICH findings,\n // and which ops within a finding); \"Decide per finding\" is the only path that assigns a\n // DIFFERENT action to each finding — say that, so the contrast is explicit (the values\n // are 'revert-all'/'ignore-all' for back-compat, but the labels no longer say \"all\"\n // since revert's picker starts fully UNSELECTED, R137).\n if (decidableCount > 1)\n options.push({\n value: 'per-finding',\n label: 'Decide per finding — assign a different action to each',\n });\n return options;\n}\n\n/** The top-menu prompt, worded by the remaining exit state (drift vs unrecorded-only vs\n * R141 no-baseline establish). `prefix` carries the `[2/3] ` multi-stack position cue\n * (issue #539) — empty for a lone stack. Pure + exported. */\nexport function resolveMenuMessage(\n stackName: string,\n code: number,\n establishOnly = false,\n prefix = ''\n): string {\n if (establishOnly)\n return `${prefix}${stackName}: no .cdkrd baseline yet — record the current state as your baseline?`;\n return code === 1\n ? `${prefix}${stackName}: drift found — what do you want to do?`\n : `${prefix}${stackName}: potential drift found (live-only, no baseline yet) — what do you want to do?`;\n}\n\nexport async function resolveInteractively(p: ResolveParams): Promise<number> {\n const opts = baselineOpts(p);\n // Whether undeclared REMOVE ops belong in a revert plan — true in a gated TTY prompt.\n const includeRemovals = includeUnrecordedRemovals(p.removeUnrecorded, true, p.yes);\n // Chain state: a record/ignore mutates only local files, so after one runs we reload\n // the baseline + config and RE-RECONCILE the raw findings — the menu re-shows with the\n // leftover, addressable drift (R133). reconciled/baseline/config advance each iteration;\n // code carries the exit forward.\n let reconciled = p.reconciled;\n let baseline = p.baseline;\n let config = p.config;\n let code = p.code;\n\n // Loop so a CANCELLED sub-prompt (Esc) returns to this menu (a \"back\" affordance) AND so\n // a COMPLETED non-AWS action re-shows the menu for any drift it could not resolve. Esc /\n // Nothing at THIS top menu exits with the current code; the menu stops appearing once no\n // action applies (e.g. the stack is clean, or only an AWS-mutating action ran).\n while (true) {\n const actions = availableActions(reconciled, baseline, p.schemas, includeRemovals);\n if (!actions.record && !actions.ignore && !actions.revert) return code;\n const decidable = reconciled.filter((f) => applicableActions(f).length > 0);\n // R141: nothing to act on, but no baseline yet → Record establishes the day-1 baseline.\n // The only available action is `record` and there are no actionable findings to decide.\n const establishOnly = baseline === undefined && decidable.length === 0;\n // Word the Record option for what it does HERE. With undeclared/added to snapshot it is a\n // plain snapshot; with none and no baseline it establishes the baseline — and when a hard\n // drift coexists (R141 relaxed), say so honestly so \"Record\" never reads as \"all done\" next\n // to a drift it does not itself resolve. A DECLARED drift takes priority (its hint points at\n // revert/ignore); a DELETED declared resource gets its own hint (re-deploy to restore — it\n // is not revert/ignore-able from this menu).\n const recordable = reconciled.some((f) => f.tier === 'undeclared' || f.tier === 'added');\n const declaredDrift = reconciled.some((f) => f.tier === 'declared');\n const deletedDrift = reconciled.some((f) => f.tier === 'deleted');\n const recordLabel: RecordLabelKind = recordable\n ? 'snapshot'\n : declaredDrift\n ? 'establish-drift'\n : deletedDrift\n ? 'establish-deleted'\n : 'establish';\n const options = buildResolveOptions(actions, decidable.length, recordLabel);\n\n const choice = await select({\n message: resolveMenuMessage(p.stackName, code, establishOnly, p.positionPrefix ?? ''),\n options,\n initialValue: 'nothing',\n });\n if (isCancel(choice) || choice === 'nothing') return code;\n\n const cur: ResolveParams = { ...p, reconciled, baseline, config, code };\n let result: SubResult | null;\n if (choice === 'record-all') result = await recordAll(cur);\n else if (choice === 'ignore-all') result = await ignoreAll(cur);\n else if (choice === 'revert-all') result = await revertAll(cur);\n else if (choice === 'per-finding') result = await perFinding(cur, decidable);\n else result = { exit: code, awsMutated: false };\n\n if (result === null) continue; // sub-prompt cancelled → re-show the same menu\n code = result.exit;\n // An AWS-mutating action is terminal: convergence was already verified against live\n // AWS inside revert, and we never re-read AWS here, so re-deriving from stale findings\n // would be wrong. A non-AWS action (record/ignore) is fully re-derivable — reload the\n // local files, re-reconcile, and loop so leftover drift re-surfaces in the menu.\n if (result.awsMutated) return code;\n baseline = await loadBaseline(p.stackName, p.desired.accountId, p.region);\n config = await loadConfig();\n reconciled = applyIgnores(\n applyBaseline(p.findings, baseline, opts),\n { stackName: p.stackName, accountId: p.desired.accountId, region: p.region },\n config\n );\n }\n}\n\n// record snapshots UNDECLARED + out-of-band ADDED resources (PR4); recordStack emits the\n// \"declared/deleted NOT approved\" scope note after the write (R117), so this path warns\n// consistently with `cdkrd record`.\nasync function recordAll(p: ResolveParams): Promise<SubResult | null> {\n const result = await recordStack({\n stackName: p.stackName,\n region: p.region,\n desired: p.desired,\n findings: applyIgnores(\n p.findings,\n { stackName: p.stackName, accountId: p.desired.accountId, region: p.region },\n p.config\n ),\n yes: p.yes,\n interactive: true,\n expandNested: p.verbose, // --show-all skips the interactive flow, so only --verbose expands here\n });\n // !wrote in this interactive path means the multiselect was cancelled (nothing\n // written) — signal \"back to the menu\" rather than exit.\n if (!result.wrote) return null;\n // R52: a successful interactive record is a SUCCESS for THIS run — unselected\n // undeclared values surface from the next check on, not as a failure now. Declared/\n // deleted drift is outside record's reach and keeps exit 1. Say what remains plainly.\n const nb = await loadBaseline(p.stackName, p.desired.accountId, p.region);\n const reEval = applyIgnores(\n applyBaseline(p.findings, nb, baselineOpts(p)),\n { stackName: p.stackName, accountId: p.desired.accountId, region: p.region },\n p.config\n );\n const remainingDeclared = reEval.filter(\n // PR4: a recorded-but-CHANGED added resource is still drift and keeps exit 1; an\n // UNRECORDED added one (not snapshotted) is inventory, counted with the undeclared\n // bucket below. declared/deleted are always drift, never recordable.\n (f) => f.tier === 'declared' || f.tier === 'deleted' || (f.tier === 'added' && !f.unrecorded)\n ).length;\n const remainingUndeclared = reEval.filter(\n (f) => f.tier === 'undeclared' || (f.tier === 'added' && f.unrecorded)\n ).length;\n console.error(`note: ${p.stackName}: ${postRecordNote(remainingUndeclared, remainingDeclared)}`);\n return { exit: remainingDeclared > 0 ? 1 : 0, awsMutated: false };\n}\n\nasync function ignoreAll(p: ResolveParams): Promise<SubResult | null> {\n // ignoreStack filters to the ignorable tiers (declared / undeclared / added) and shows\n // its own multiselect (default NONE selected, R137) when !yes, mirroring `cdkrd ignore`.\n // Pre-split here so the folded undeclared inventory is gated behind chooseScope: the\n // picker defaults to the report's SHOWN findings, not a wall of nested values.\n const ignorable = p.reconciled.filter(\n (f) => f.tier === 'declared' || f.tier === 'undeclared' || f.tier === 'added'\n );\n const foldedCount = ignorable.filter((f) => isFoldedFinding(f, p.verbose)).length;\n const scope = await chooseScope(p.stackName, ignorable.length - foldedCount, foldedCount, p.yes);\n if (scope === null) return null; // scope prompt cancelled → back to the menu\n const findings =\n scope === 'all' ? ignorable : ignorable.filter((f) => !isFoldedFinding(f, p.verbose));\n const result = await ignoreStack({\n stackName: p.stackName,\n findings,\n yes: p.yes,\n interactive: true,\n });\n // reconciled findings are all not-yet-ignored, so a completed run always writes a new\n // rule; !wrote means the multiselect was cancelled → back to the menu.\n return result.wrote ? { exit: await recomputeExit(p, new Set()), awsMutated: false } : null;\n}\n\nasync function revertAll(p: ResolveParams): Promise<SubResult | null> {\n const outcome = await revertStack({\n stackName: p.stackName,\n region: p.region,\n gathered: {\n desired: p.desired,\n findings: p.findings,\n schemas: p.schemas,\n liveByLogical: p.liveByLogical,\n },\n baseline: p.baseline,\n config: p.config,\n dryRun: false,\n // NEVER inherit --yes here. `check` is the read-only verb; reaching a revert\n // through its interactive menu must still show the \"this WRITES to AWS\" confirm.\n // `yes:true` would skip BOTH the op-multiselect AND that confirm (the whole block\n // in revertStack is `if (!yes)`), so `check --yes` + \"Revert all\" would mutate AWS\n // with no prompt. The standalone `cdkrd revert --yes` bypass is intended and goes\n // through revert.ts directly, not this path.\n yes: false,\n removeUnrecorded: p.removeUnrecorded,\n verbose: p.verbose,\n interactive: true,\n });\n // R30: an aborted confirm wrote nothing — signal \"back to the menu\" (the drift still\n // stands; the caller keeps the pre-prompt code if the user then exits).\n return outcome.aborted ? null : { exit: outcome.exit, awsMutated: true };\n}\n\nasync function perFinding(p: ResolveParams, decidable: Finding[]): Promise<SubResult | null> {\n // Gate the folded undeclared inventory the same way ignore does: default the picker to\n // the report's SHOWN findings, ask before pulling the folded nested values in.\n const foldedCount = decidable.filter((f) => isFoldedFinding(f, p.verbose)).length;\n const scope = await chooseScope(p.stackName, decidable.length - foldedCount, foldedCount, p.yes);\n if (scope === null) return null; // scope prompt cancelled → back to the menu\n const scoped =\n scope === 'all' ? decidable : decidable.filter((f) => !isFoldedFinding(f, p.verbose));\n const rows = scoped.map((f) => ({\n label: pickerLabel(f, p.stackName),\n applicable: applicableActions(f),\n }));\n const chosen = await actionPicker(`${p.stackName}: assign an action to each finding`, rows);\n if (chosen === undefined) return null; // picker cancelled (Esc) → back to the menu\n const groups = groupByAction(scoped, chosen);\n if (groups.record.length + groups.ignore.length + groups.revert.length === 0)\n return { exit: p.code, awsMutated: false };\n\n // record: the picker already chose which undeclared values — recordStack records\n // exactly those (preselectedKeys) while still auto-keeping the existing baseline.\n if (groups.record.length > 0) {\n const preselectedKeys = new Set(buildRecorded(groups.record).map(recordedKey));\n await recordStack({\n stackName: p.stackName,\n region: p.region,\n desired: p.desired,\n findings: applyIgnores(\n p.findings,\n { stackName: p.stackName, accountId: p.desired.accountId, region: p.region },\n p.config\n ),\n yes: p.yes,\n interactive: true,\n preselectedKeys,\n });\n }\n // ignore: write rules for exactly the chosen findings (yes:true skips ignoreStack's\n // own multiselect — the picker IS the selection). addIgnoreRules unions, no data loss.\n if (groups.ignore.length > 0) {\n await ignoreStack({\n stackName: p.stackName,\n findings: groups.ignore,\n yes: true,\n interactive: true,\n });\n }\n // revert (AWS, last): pass ONLY the chosen findings; autoSelectAll skips the op\n // multiselect (already chosen) but keeps the AWS-write confirm.\n let revertResolved = new Set<string>();\n let revertExit = 0;\n if (groups.revert.length > 0) {\n const revertKeys = new Set(groups.revert.map(keyOf));\n const outcome = await revertStack({\n stackName: p.stackName,\n region: p.region,\n gathered: {\n desired: p.desired,\n findings: p.findings.filter((f) => revertKeys.has(keyOf(f))),\n schemas: p.schemas,\n liveByLogical: p.liveByLogical,\n },\n baseline: p.baseline,\n config: p.config,\n dryRun: false,\n // NEVER inherit --yes (see revertAll): the read-only `check` verb must still\n // confirm an AWS write. autoSelectAll skips the op-multiselect (the picker already\n // chose), but the \"this WRITES to AWS\" confirm must fire — which only happens when\n // yes is false (the confirm lives inside `if (!yes)` in revertStack).\n yes: false,\n removeUnrecorded: p.removeUnrecorded,\n verbose: p.verbose,\n interactive: true,\n autoSelectAll: true,\n });\n if (!outcome.aborted) {\n revertResolved = revertKeys; // converged-or-attempted; outcome.exit folds in non-convergence\n revertExit = outcome.exit;\n }\n }\n console.error(\n `note: ${p.stackName}: per-finding decisions applied (${summarizeChoices(chosen)}).`\n );\n return {\n exit: Math.max(await recomputeExit(p, revertResolved), revertExit),\n // per-finding is terminal only if it actually wrote to AWS (a revert ran); a\n // record/ignore-only per-finding pass is re-derivable, so the menu re-shows.\n awsMutated: groups.revert.length > 0,\n };\n}\n","// `cdkrd check [<stack>...] [--region r] [--profile p] [--app ...] [-c k=v]\n// [--json] [--fail] [--show-all]`\n// Read-only. Reports drift per stack; undeclared findings are filtered against the\n// baseline file (if present) so a stack with an recorded baseline reports CLEAN.\n// Exit (R53, the `cdk diff --fail` convention): report-only by default — drift\n// exits 0 (a hint names --fail); with --fail drift exits 1 and prompts are\n// suppressed. Errors always exit 2. The exit is the worst across all checked\n// stacks.\nimport { isStackNotDeployed, StackNotCheckableError } from '../aws-errors.js';\nimport {\n applyBaseline,\n type ApplyBaselineOptions,\n type BaselineFile,\n checkBaselineAccount,\n constructPathsByLogical,\n declaredKeysByLogical,\n loadBaseline,\n physicalIdsByLogical,\n warnBaselineSchemaV1,\n warnTemplateHashDrift,\n} from '../baseline/baseline-file.js';\nimport { isInteractive, parseCommonArgs } from '../cli-args.js';\nimport { applyIgnores, loadConfig } from '../config/config-file.js';\nimport { withinStackPath } from '../construct-path.js';\nimport { report, stackSeparator } from '../report/report.js';\nimport { resolveApp } from '../synth/resolve-app.js';\nimport { synthApp } from '../synth/synth.js';\nimport type { DesiredResource, Finding } from '../types.js';\nimport { resolveStacks } from './resolve-stacks.js';\nimport { gatherFindings } from './gather.js';\nimport {\n gatherWithProgress,\n positionPrefix,\n progressLabel,\n stackCountAnnouncement,\n} from './progress.js';\nimport { resolveInteractively } from './interactive-resolve.js';\n\n// --pre-deploy reports declared-side drift the next deploy would clobber; the\n// undeclared tier AND its undeclared-side siblings (`generated` and `atDefault` —\n// both classified only in classify's undeclared loops) are meaningless against a\n// synth (not deployed) declared set, so all three are excluded. --declared-only\n// reuses the same filter against the DEPLOYED template (R59) — its \"undeclared\n// values are not compared\" contract must hold for the `atDefault` footer too, else\n// Key a synth template by stack name + region (a CFn stack name is region-scoped, so\n// the same name can recur across regions in one app). Exported (pure) for unit testing.\nexport function synthKey(stackName: string, region: string | undefined): string {\n return `${stackName}\\0${region ?? ''}`;\n}\n\n// Reconcile classified findings against the baseline for the report. Exported (pure)\n// so the --show-all contract below is unit-tested.\n//\n// `--declared-only` is the ONLY mode that bypasses applyBaseline: it filters the\n// undeclared tier out entirely, so applyBaseline's removal pass would misread EVERY\n// recorded entry as \"baseline value removed since record\" (latent in R59).\n//\n// `--show-all` (inventory mode) does NOT bypass it. The caller already loaded\n// `baseline = undefined` for show-all (it lists ALL current undeclared state,\n// ignoring whatever is recorded), and applyBaseline(findings, undefined) is exactly\n// the path that tags every undeclared/added value `unrecorded` — i.e. POTENTIAL\n// drift, not confirmed drift. Bypassing it (the pre-#378 behavior) left those values\n// untagged, so the report mislabeled a fresh deploy's live-only inventory as\n// \"CFn-Undeclared Drift\" / \"N drift(s)\" and `--show-all --fail` exited 1 on a stack\n// nobody had touched — the first-run false-drift the Potential Drift model removed.\nexport function reconcileBaseline(\n findings: Finding[],\n baseline: BaselineFile | undefined,\n opts: { declaredOnly: boolean; applyOpts: ApplyBaselineOptions }\n): Finding[] {\n if (opts.declaredOnly) return findings;\n return applyBaseline(findings, baseline, opts.applyOpts);\n}\n\n// `--declared-only` still prints an `At AWS Default (N)` line for values it claims\n// not to compare. Exported (pure) so the contract is unit-tested.\nexport function preDeployFindings(findings: Finding[]): Finding[] {\n return findings.filter(\n (f) =>\n f.tier !== 'undeclared' &&\n f.tier !== 'generated' &&\n f.tier !== 'atDefault' &&\n // `added` is a LIVE-only divergence (a resource not in the template) — the\n // declared-side / pre-deploy view is about template-declared props, and a deploy\n // won't remove an out-of-band resource, so it belongs with the undeclared side.\n f.tier !== 'added'\n );\n}\n\n// --undeclared-only (R59): the declared-side comparison is delegated to\n// `cdk drift` / CFn drift detection, so declared findings AND the\n// declared-comparison byproducts (readGap = declared-but-unreadable,\n// unresolved = declared-but-GetAtt) drop out. `deleted` stays — a gone resource\n// has no undeclared values to check, and hiding it would be a lie. Exported\n// (pure) so the contract is unit-tested.\nexport function undeclaredOnlyFindings(findings: Finding[]): Finding[] {\n return findings.filter(\n (f) => f.tier !== 'declared' && f.tier !== 'readGap' && f.tier !== 'unresolved'\n );\n}\n\n// A nested CloudFormation stack (the CDK `NestedStack` construct, or any plain\n// `AWS::CloudFormation::Stack` resource) is deployed as a SEPARATE child stack whose\n// own resources are the real infrastructure. cdkrd checks the PARENT's\n// `AWS::CloudFormation::Stack` resource (its TemplateURL / Parameters) via Cloud\n// Control, but does NOT recurse into the child stack — so the child's resources\n// (buckets, roles, …) are never checked. A drift tool silently under-covering is the\n// danger: a CLEAN verdict that never looked inside the nested stack reads as\n// fully-checked. Surface the gap LOUDLY so coverage is never silently incomplete.\n// Returns the warning line, or null when the stack has no nested stacks. Pure +\n// exported for unit tests.\nexport function nestedStackWarning(resources: DesiredResource[], stackName: string): string | null {\n const nested = resources.filter((r) => r.resourceType === 'AWS::CloudFormation::Stack');\n if (nested.length === 0) return null;\n const names = nested\n .map((r) => (r.constructPath ? withinStackPath(r.constructPath, stackName) : r.logicalId))\n .sort();\n return `warning: ${stackName} has ${nested.length} nested CloudFormation stack(s) — cdkrd does not recurse into them, so the resources INSIDE them are NOT checked: ${names.join(', ')}`;\n}\n\n// Resources cdkrd could NOT read this run land in the `skipped` tier — a\n// CC-unsupported type with no SDK override, a read error (throttle / AccessDenied), a\n// missing physical id, a Custom resource. They are genuinely UNCHECKED, yet `skipped`\n// is excluded from the verdict and from `--fail`, and only folded into the `info:`\n// footer — so a materially under-covered run can read `result: CLEAN`, exit 0. Surface\n// the gap LOUDLY (same not-silent principle as the nested-stack / KMS warnings); the\n// `--strict` flag additionally turns it into a non-zero exit. Returns null when nothing\n// was skipped. Pure + exported for unit tests.\nexport function coverageWarning(findings: Finding[], stackName: string): string | null {\n const skipped = findings.filter((f) => f.tier === 'skipped');\n if (skipped.length === 0) return null;\n const names = skipped\n .map((f) => (f.constructPath ? withinStackPath(f.constructPath, stackName) : f.logicalId))\n .sort();\n const shown = names.slice(0, 10);\n const more = names.length > shown.length ? `, …(+${names.length - shown.length} more)` : '';\n return `warning: ${stackName}: ${skipped.length} resource(s) were NOT checked (coverage incomplete) — ${shown.join(', ')}${more}; see the skipped breakdown (--verbose)`;\n}\n\n// The coverage gap that `--strict` fails on: any resource skipped (unread) OR any\n// nested stack not recursed into. Pure + exported.\nexport function hasCoverageGap(findings: Finding[], resources: DesiredResource[]): boolean {\n return (\n findings.some((f) => f.tier === 'skipped') ||\n resources.some((r) => r.resourceType === 'AWS::CloudFormation::Stack')\n );\n}\n\n// The exit contribution of `--strict`: a coverage gap is a non-zero exit\n// independent of --fail's drift axis. Returns 1 when --strict is set AND coverage\n// is incomplete, else 0. Pure + exported so BOTH the normal and the --pre-deploy\n// path fold the identical value into `worst` — the --pre-deploy branch returns\n// early (its own report + continue), so without sharing this it silently never\n// applied --strict (a skipped resource / un-recursed nested stack under\n// --strict --pre-deploy exited 0).\nexport function strictCoverageExit(\n strict: boolean,\n findings: Finding[],\n resources: DesiredResource[]\n): number {\n return strict && hasCoverageGap(findings, resources) ? 1 : 0;\n}\n\n/**\n * Map a stack's drift code to check's final exit (R53, the `cdk diff --fail` /\n * `cdk drift --fail` convention): without --fail, check is REPORT-ONLY — drift\n * (1) exits 0; errors (2) always propagate. With --fail, drift exits 1. Pure + exported for tests.\n */\nexport function finalCheckExit(code: number, fail: boolean): number {\n return fail || code !== 1 ? code : 0;\n}\n\nexport async function runCheck(args: string[]): Promise<number> {\n const a = parseCommonArgs(args);\n if (a.profile) process.env.AWS_PROFILE = a.profile; // honored by SDK clients + synth subprocess\n\n // .cdkrd/ignore.yaml ignore rules, loaded once (cwd-relative). A malformed config\n // fails the whole run fast — a silently-ineffective ignore rule is the dangerous case.\n let config;\n try {\n config = await loadConfig();\n } catch (e) {\n console.error(`error: ${(e as Error).message}`);\n return 2;\n }\n\n let stacks;\n try {\n stacks = await resolveStacks(a);\n } catch (e) {\n console.error(`error: ${(e as Error).message}`);\n return 2;\n }\n if (stacks.length === 0) {\n console.error('note: the CDK app defines no stacks — nothing to check');\n return 0;\n }\n\n // Announce the total up front (issue #539): in a multi-stack run each stack prints its\n // report + interactive prompt one at a time, so without this the count only ever shows\n // embedded in the scrolled-away `[i/N]` spinner line. To stderr (never pollutes --json\n // stdout) and suppressed under --json; a lone stack gets nothing (stackCountAnnouncement\n // returns null — consistent with the `[1/1]`-is-noise rule).\n if (!a.json) {\n const announce = stackCountAnnouncement(stacks.map((s) => s.stackName));\n if (announce) console.error(announce);\n }\n\n // --pre-deploy: synth the local app once and use each stack's synth template as\n // the declared source, so check reports the declared drift the next deploy would\n // overwrite (clobber) rather than comparing against the already-deployed template.\n let synthTemplates: Map<string, Record<string, unknown>> | undefined;\n if (a.preDeploy) {\n const app = resolveApp(a.app);\n if (!app) {\n console.error('error: --pre-deploy needs a CDK app (--app or a cdk.json in the cwd)');\n return 2;\n }\n const synthed = await synthApp(app, {\n region: a.region,\n profile: a.profile,\n context: a.context,\n });\n // Key by stackName + region, NOT stackName alone: a stack name is region-scoped in\n // CloudFormation, so an app can define two same-named stacks in different regions.\n // Keyed by name alone, the second would overwrite the first and BOTH would then be\n // compared against the wrong (last-synthesized) template. The region resolution\n // mirrors resolveStacks (`s.region ?? a.region`) so the loop's lookup key matches.\n synthTemplates = new Map(\n synthed.map((s) => [synthKey(s.stackName, s.region ?? a.region), s.template])\n );\n console.error('(--pre-deploy) comparing live state against the LOCAL synth template');\n }\n\n let worst = 0;\n let anyDrift = false; // for the report-only hint (R53)\n // R37: one blank line between consecutive stack reports (text mode only) — done\n // here at the call site so a single-stack run never gets a stray leading blank.\n const separate = stackSeparator();\n // The gather-phase spinner (see gatherWithProgress) — text mode + TTY only.\n const showProgress = !a.json && isInteractive();\n for (const [idx, { stackName, region, template }] of stacks.entries()) {\n if (!region) {\n console.error(\n `error: ${stackName}: no region — set env on the stack, pass --region, or set a region for the AWS profile`\n );\n worst = Math.max(worst, 2);\n continue;\n }\n // The `[i/N] ` position cue (issue #539) — same gating as the spinner label: only in\n // a multi-stack text run, '' for a lone stack or --json. Threaded into the report\n // header and the interactive prompt so the cue is present where the user reads/decides,\n // not only on the scrolled-away spinner line.\n const posPrefix = a.json ? '' : positionPrefix(idx, stacks.length);\n try {\n const sKey = synthKey(stackName, region);\n if (synthTemplates && !synthTemplates.has(sKey)) {\n console.error(`note: ${stackName}: not in the synth output — skipped (--pre-deploy)`);\n continue;\n }\n // The stack's synth template (always carried by resolveStacks) is the non-ASCII\n // RECOVERY source for the deployed-template path — loadDesired ignores it under\n // --pre-deploy (where synthTemplates is already the declared override).\n const gathered = await gatherWithProgress(\n showProgress,\n progressLabel(idx, stacks.length, stackName, region),\n () => gatherFindings(stackName, region, synthTemplates?.get(sKey), template)\n );\n const { desired, schemas, liveByLogical } = gathered;\n let findings = gathered.findings;\n\n // Loudly flag incomplete coverage — a CLEAN verdict must never silently hide an\n // unchecked nested stack or an unread (skipped) resource. To stderr so it survives\n // `--json` (whose machine output is stdout) without polluting it. `--strict` turns\n // any such gap into a non-zero exit (folded into `worst` after the report).\n const nestedWarn = nestedStackWarning(desired.resources, stackName);\n if (nestedWarn) console.error(nestedWarn);\n // Coverage gap (skipped / unread resources): R127 folds this into the report's\n // info: footer for TEXT mode — the `skipped=` line there now carries the \"NOT\n // checked (coverage incomplete)\" framing, so emitting a separate stderr warning\n // BEFORE the report would (a) bury the drift result below the fold (the very UX\n // complaint that prompted R127) and (b) duplicate the footer. --json has no info:\n // footer, so keep the loud stderr warning there to preserve the invariant.\n if (a.json) {\n const covWarn = coverageWarning(gathered.findings, stackName);\n if (covWarn) console.error(covWarn);\n }\n // a mid-operation / failed stack state still gets compared, but the result may be\n // transient/unreliable — say so loudly (REVIEW_IN_PROGRESS / deleting states never\n // reach here; loadDesired throws StackNotCheckableError, handled in the catch).\n if (desired.stackStatusWarning)\n console.error(`warning: ${stackName}: ${desired.stackStatusWarning}`);\n\n // Scope flags (R59). --undeclared-only delegates the declared side to\n // `cdk drift` / CFn drift detection (no double reporting when pairing);\n // --declared-only is the inverse (undeclared tier skipped, baseline\n // untouched) — unlike --pre-deploy, it compares against the DEPLOYED\n // template. Filtering up front keeps everything downstream consistent:\n // first-run prompt counts, baseline notes, interactive actions, reverts.\n if (a.undeclaredOnly) {\n findings = undeclaredOnlyFindings(findings);\n if (!a.json)\n console.error(\n `note: ${stackName}: --undeclared-only — declared-side drift is not compared (pair with cdk drift / CFn drift detection)`\n );\n }\n if (a.declaredOnly) {\n findings = preDeployFindings(findings); // same filter: drop the undeclared tier\n if (!a.json)\n console.error(\n `note: ${stackName}: --declared-only — undeclared values are not compared (baseline untouched)`\n );\n }\n\n // --pre-deploy: the declared set comes from the LOCAL synth template, so the\n // ONLY meaningful signal is declared drift the next deploy would clobber. The\n // undeclared tier is \"live minus declared\" — with a synth declared set its\n // meaning silently shifts, so we drop it and do NOT touch the baseline at all\n // (no record offer, no baseline load — which would also wrongly hash the synth\n // template). See ARCHITECTURE §13-2.\n if (a.preDeploy) {\n const declaredOnly = preDeployFindings(findings);\n if (!a.json)\n console.error(\n `note: ${stackName}: --pre-deploy reports declared drift only (undeclared tiers are evaluated against the deployed template — run check without --pre-deploy)`\n );\n if (!a.json) separate();\n const preDeployCode = report(\n applyIgnores(declaredOnly, { stackName, accountId: desired.accountId, region }, config),\n `${posPrefix}${stackName} (${region})`,\n {\n json: a.json,\n verbose: a.verbose,\n }\n );\n if (preDeployCode === 1) anyDrift = true;\n worst = Math.max(worst, finalCheckExit(preDeployCode, a.fail));\n // --strict still applies under --pre-deploy: live reads (and so the skipped\n // tier / un-recursed nested stacks) happen here too, only the DECLARED side\n // comes from the synth template. Fold the coverage-gap exit BEFORE the early\n // continue, or --strict --pre-deploy would silently never fail.\n worst = Math.max(worst, strictCoverageExit(a.strict, gathered.findings, desired.resources));\n continue;\n }\n\n const baseline = a.showAll\n ? undefined\n : await loadBaseline(stackName, desired.accountId, region);\n // per-account guard: a baseline captured in a different account is wrong here\n if (baseline) checkBaselineAccount(baseline, desired.accountId, stackName);\n // stale-baseline warning (pre-deploy already returned above, so always safe here)\n if (baseline) warnTemplateHashDrift(baseline, desired.rawTemplate, stackName);\n // schema-v1 baseline: no completeResources — appeared-since-record values\n // read as unrecorded until the next record upgrades the file (R62)\n if (baseline && !a.json) warnBaselineSchemaV1(baseline, stackName);\n // First run (no baseline): R110 removed the pre-report \"Record ALL sight-unseen\"\n // prompt (R45/R52). It buried the very values it flagged as possible out-of-band\n // edits — pressing Enter recorded them into the baseline BEFORE the user ever saw\n // them, and the report then suppressed them, so a real edit could vanish in one\n // keystroke. Now the report ALWAYS prints first; the post-report prompt below\n // (\"potential drift found — Record/Revert/Nothing\") offers a SELECTIVE record\n // after the user has seen the standout values. Folding (atDefault/generated/\n // nested) keeps that list short, so the old bulk-record-to-avoid-scrolling\n // rationale no longer applies. `cdkrd record` still writes a baseline directly.\n // applyBaseline classifies per ENTRY (R62): matching entries are suppressed,\n // changed values are drift, entry-less values are drift only on a\n // snapshot-complete resource (appeared since record) and UNRECORDED\n // otherwise — including the whole no-baseline first run (R60). The report\n // renders unrecorded values as [Potential Drift: N], excludes them from the\n // verdict/exit, and points at `cdkrd record` on the result line.\n // --show-all loaded baseline=undefined above (it lists ALL undeclared state,\n // ignoring what is recorded) but STILL reconciles: applyBaseline(_, undefined)\n // tags every undeclared/added value `unrecorded` (potential drift, not confirmed\n // drift), so a fresh deploy's inventory is not mislabeled as drift and\n // --show-all --fail does not exit 1 on an untouched stack. Only --declared-only\n // bypasses applyBaseline (see reconcileBaseline). R59/R86/#378.\n const reconciled = applyIgnores(\n reconcileBaseline(findings, baseline, {\n declaredOnly: a.declaredOnly,\n applyOpts: {\n declaredByLogical: declaredKeysByLogical(desired.resources),\n constructPathByLogical: constructPathsByLogical(desired.resources),\n physicalIdByLogical: physicalIdsByLogical(desired.resources),\n warn: (s: string) => {\n if (!a.json) console.error(s);\n },\n },\n }),\n { stackName, accountId: desired.accountId, region },\n config\n );\n if (!a.json) separate();\n let code = report(reconciled, `${posPrefix}${stackName} (${region})`, {\n json: a.json,\n verbose: a.verbose,\n // --show-all is inventory mode: list every undeclared value, including the\n // ones at an AWS default (otherwise folded to a count) (R86).\n expandAtDefault: a.showAll,\n });\n const hasUnrecorded = reconciled.some((f) => f.unrecorded === true);\n\n // R28 (extended R121): drift found in a TTY → offer to resolve it inline\n // (Record / Revert / Ignore / Decide per finding / Nothing) instead\n // of making the user re-run a separate verb. Skipped for --json (machine output),\n // --show-all (baseline not applied — record would mean something else), and\n // --pre-deploy (declared-only, baseline-untouched contract). UNRECORDED values do\n // not set code 1 (R60) but still deserve the prompt. R141: a stack with NO baseline\n // file ALSO opens the prompt even when clean — so the day-1 baseline is established\n // through `check`'s own flow (pick Record) rather than a separate `cdkrd record`.\n // The whole resolution flow lives in interactive-resolve.ts; it returns the exit code.\n if (\n (code === 1 || hasUnrecorded || !baseline) &&\n !a.json &&\n !a.showAll &&\n !a.preDeploy &&\n !a.fail &&\n isInteractive()\n ) {\n code = await resolveInteractively({\n stackName,\n region,\n desired,\n findings,\n reconciled,\n baseline,\n schemas,\n liveByLogical,\n config,\n code,\n yes: a.yes,\n removeUnrecorded: a.removeUnrecorded,\n verbose: a.verbose,\n positionPrefix: posPrefix,\n });\n } else if (!baseline && !hasUnrecorded && !a.json && !a.showAll && !a.preDeploy) {\n // R142: no interactive establish prompt could fire (non-TTY, or --fail) and there is\n // no baseline on an otherwise-quiet stack — the report gave no record cue (nothing is\n // unrecorded), so point at how to create the day-1 baseline. stderr keeps stdout clean.\n console.error(\n `note: ${stackName}: no .cdkrd baseline yet — run \\`cdkrd record\\` to establish one (future out-of-band changes then report as drift).`\n );\n }\n if (code === 1) anyDrift = true;\n worst = Math.max(worst, finalCheckExit(code, a.fail));\n // --strict: incomplete coverage (a skipped resource or an un-recursed nested\n // stack) is a non-zero exit, independent of --fail's drift axis. The loud\n // coverage warnings above always print; --strict makes them CI-failing.\n worst = Math.max(worst, strictCoverageExit(a.strict, gathered.findings, desired.resources));\n } catch (e) {\n if (isStackNotDeployed(e)) {\n console.error(`note: ${stackName}: not deployed yet — skipped`);\n continue;\n }\n // a stack that exists but has no meaningful deployed state (REVIEW_IN_PROGRESS /\n // deleting): skip with a clear reason, not a meaningless CLEAN and not an error.\n if (e instanceof StackNotCheckableError) {\n console.error(`note: ${stackName}: ${e.message} — skipped`);\n continue;\n }\n console.error(`error: ${stackName}: ${(e as Error).message}`);\n worst = Math.max(worst, 2);\n }\n }\n // Report-only mode found drift: say so, and say how to make it fail — a script\n // author piping this must discover --fail from the output, not from a surprise\n // green pipeline (R53). Suppressed under --json (machine consumers read stdout).\n if (anyDrift && !a.fail && !a.json) {\n console.error(\n 'note: drift found — exit 0 (report-only). Pass --fail to make drift fail this command.'\n );\n }\n return worst;\n}\n","// `cdkrd revert [<stack>...] [--app ...] [--region r] [--profile p]\n// [--dry-run] [--yes]`\n// The ONLY AWS-mutating command. Reverts drift to its desired value:\n// declared -> deployed-template value\n// undeclared -> baseline value (restore) or removal (if never recorded)\n// The per-stack plan / apply / converge flow lives in stack-actions.ts (shared with\n// check's interactive prompt, R28).\nimport { isStackNotDeployed, StackNotCheckableError } from '../aws-errors.js';\nimport {\n type BaselineFile,\n checkBaselineAccount,\n loadBaseline,\n} from '../baseline/baseline-file.js';\nimport { isInteractive, parseCommonArgs } from '../cli-args.js';\nimport { loadConfig } from '../config/config-file.js';\nimport { gatherFindings } from './gather.js';\nimport { gatherWithProgress, progressLabel } from './progress.js';\nimport { resolveStacks } from './resolve-stacks.js';\nimport { revertStack } from './stack-actions.js';\n\nexport async function runRevert(args: string[]): Promise<number> {\n const a = parseCommonArgs(args);\n if (a.profile) process.env.AWS_PROFILE = a.profile;\n const dryRun = args.includes('--dry-run');\n\n let config;\n try {\n config = await loadConfig();\n } catch (e) {\n console.error(`error: ${(e as Error).message}`);\n return 2;\n }\n\n let stacks;\n try {\n stacks = await resolveStacks(a);\n } catch (e) {\n console.error(`error: ${(e as Error).message}`);\n return 2;\n }\n if (stacks.length === 0) {\n console.error('note: the CDK app defines no stacks — nothing to revert');\n return 0;\n }\n\n let worst = 0;\n // gather-phase spinner (see gatherWithProgress) — text mode + TTY only. The revert\n // confirm prompt fires AFTER the gather, so the spinner never overlaps it.\n const showProgress = !a.json && isInteractive();\n for (const [idx, { stackName, region, template }] of stacks.entries()) {\n if (!region) {\n console.error(\n `error: ${stackName}: no region — set env on the stack, pass --region, or set a region for the AWS profile`\n );\n worst = Math.max(worst, 2);\n continue;\n }\n try {\n // gather FIRST: the baseline filename embeds the accountId, which only the\n // gather (DescribeStackResources) resolves. (R21 — was load-then-gather.)\n // `template` (synth) recovers GetTemplate's `?`-masked non-ASCII literals so a\n // revert writes the REAL declared value, never a `?????` mask.\n const gathered = await gatherWithProgress(\n showProgress,\n progressLabel(idx, stacks.length, stackName, region),\n () => gatherFindings(stackName, region, undefined, template)\n );\n const baseline: BaselineFile | undefined = await loadBaseline(\n stackName,\n gathered.desired.accountId,\n region\n );\n if (baseline) checkBaselineAccount(baseline, gathered.desired.accountId, stackName);\n // standalone revert: an aborted confirm means nothing changed → exit 0 (the\n // outcome's `exit` already encodes that; `aborted` is only consulted by check).\n const { exit } = await revertStack({\n stackName,\n region,\n gathered,\n baseline,\n config,\n dryRun,\n yes: a.yes,\n removeUnrecorded: a.removeUnrecorded,\n verbose: a.verbose,\n interactive: isInteractive(),\n ...(a.waitMs !== undefined && { waitMs: a.waitMs }),\n });\n worst = Math.max(worst, exit);\n } catch (e) {\n if (isStackNotDeployed(e)) {\n console.error(`note: ${stackName}: not deployed — skipped`);\n continue;\n }\n if (e instanceof StackNotCheckableError) {\n console.error(`note: ${stackName}: ${e.message} — skipped`);\n continue;\n }\n console.error(`error: ${stackName}: ${(e as Error).message}`);\n worst = Math.max(worst, 2);\n }\n }\n return worst;\n}\n","#!/usr/bin/env node\n// cdk-real-drift CLI entry. Dispatches: check | record | ignore | revert (+ help/version).\n// check/record/ignore never write to AWS (record writes only the baseline FILE; ignore\n// writes only .cdkrd/ignore.yaml); revert is the one AWS-mutating command.\nimport { readFileSync } from 'node:fs';\nimport { runRecord } from './commands/record.js';\nimport { runIgnore } from './commands/ignore.js';\nimport { runCheck } from './commands/check.js';\nimport { runRevert } from './commands/revert.js';\n\nconst HELP = `cdkrd — drift detection + revert for AWS CDK, including UNDECLARED\nproperties that 'cdk drift' / CloudFormation drift detection never see.\n\nUSAGE\n cdkrd check [<stack>...] detect drift (read-only)\n cdkrd record [<stack>...] snapshot current undeclared state + out-of-band added\n resources into the baseline — KEEPS watching\n (re-surfaces if the value/resource changes)\n cdkrd ignore [<stack>...] stop reporting the chosen drift (writes ignore.yaml)\n — STOPS watching (declared, undeclared, or added)\n cdkrd revert [<stack>...] write the desired value back to AWS (confirms)\n\n \\`cdkrd check\\` is the entry point: run it and act from its prompt — it\n establishes the first baseline and offers record / revert / ignore inline on\n whatever it finds, so day to day you only run check. The standalone verbs above\n are the SAME actions for scripts / non-TTY / CI (with --yes); a human rarely\n needs them directly.\n\n cdkrd is CDK-only: it synthesizes the CDK app (--app / cdk.json, or a\n pre-synthesized cdk.out) to discover stacks. With no stack argument (or --all),\n every stack the app defines is targeted; a <stack> arg (exact or a *?-glob)\n selects among them. The drift comparison itself reads each stack's DEPLOYED\n template + live state from AWS.\n\nOPTIONS\n --region <r> AWS region (or $AWS_REGION / $AWS_DEFAULT_REGION);\n CDK stacks with explicit env.region are auto-detected.\n An env-agnostic stack with none of these falls back to\n the active --profile's configured region (~/.aws/config)\n --profile <p> AWS profile (or $AWS_PROFILE)\n -a, --app <cmd|cdk.out> CDK app command or pre-synthesized assembly dir\n (or $CDKRD_APP / cdk.json \"app\") — enables stack\n auto-discovery + construct-path output\n -c, --context key=value context for synth (repeatable; cdk.json is the base)\n --all target EVERY stack the app defines (the default when\n no <stack> is named; overrides any positional names)\n --json machine-readable output\n --fail (check) exit 1 on drift + never prompt — for\n scripts/CI (same convention as \\`cdk diff --fail\\`);\n without it, check REPORTS drift but exits 0\n --strict (check) exit 1 when coverage is INCOMPLETE — any\n resource skipped (unread) or a nested stack not\n recursed into. A loud coverage warning always prints;\n --strict makes it CI-failing. Orthogonal to --fail\n --show-all inventory mode: show ALL current undeclared state\n (not just changes since record)\n --verbose (check) expand informational tiers / (revert) the\n NOT-revertable summary to full per-finding lists\n --pre-deploy (check) compare live state vs the LOCAL synth template\n — the declared drift your next deploy would overwrite\n --undeclared-only (check) undeclared drift only — pair cdkrd with\n \\`cdk drift\\` / CFn drift detection for the declared side\n --declared-only (check) declared drift vs the DEPLOYED template only\n (undeclared tier skipped; baseline untouched)\n --dry-run (revert) print the plan; make no changes\n --wait[=DURATION] (revert) on a transient \"resource is mid-update\" error\n (e.g. RSLVR-00705) keep retrying until it settles, up to\n DURATION (default 10m; e.g. --wait=5m, --wait=90s)\n --remove-unrecorded (revert) REMOVE unrecorded values + DELETE unrecorded\n added resources (never recorded; default: refuse —\n record the ones that are right)\n --yes, -y skip confirmation (revert) / overwrite notice (record) /\n ignore ALL shown drift without the multiselect (ignore)\n --help, -h --version, -v\n\n Automation: check --fail / record --yes / ignore --yes / revert --yes (or\n --dry-run); non-TTY runs never prompt.\n\nEXIT CODES\n check: 0 = clean (or drift without --fail) 1 = drift (--fail) / incomplete coverage (--strict) 2 = error\n record: 0 = written 2 = error/refused\n ignore: 0 = rule(s) written / nothing to ignore 2 = error/refused\n revert: 0 = converged/aborted 1 = drift remains 2 = error/apply failure\n\nThe baseline lives at .cdkrd/baselines/<stack>.<accountId>.<region>.json — commit it; review\nits diff in PRs. Ignore rules live in .cdkrd/ignore.yaml — also git-committed.`;\n\nfunction version(): string {\n try {\n const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));\n return pkg.version ?? '0.0.0';\n } catch {\n return '0.0.0';\n }\n}\n\nasync function main(argv: string[]): Promise<number> {\n const [cmd, ...rest] = argv;\n if (cmd === undefined || cmd === '-h' || cmd === '--help' || cmd === 'help') {\n console.log(HELP);\n return 0;\n }\n if (cmd === '--version' || cmd === '-v') {\n console.log(version());\n return 0;\n }\n // `cdkrd <verb> --help` — unknown options now fail fast, so route help here\n if (rest.includes('--help') || rest.includes('-h')) {\n console.log(HELP);\n return 0;\n }\n switch (cmd) {\n case 'check':\n return runCheck(rest);\n case 'record':\n return runRecord(rest);\n case 'ignore':\n return runIgnore(rest);\n case 'revert':\n return runRevert(rest);\n default:\n console.error(`unknown command: ${cmd}\\n`);\n console.error(HELP);\n return 2;\n }\n}\n\nmain(process.argv.slice(2))\n .then((code) => process.exit(code))\n .catch((e: unknown) => {\n const msg = (e as { message?: string })?.message ?? String(e);\n if (/credential|could not load cred|security token/i.test(msg)) {\n console.error(\n 'error: no AWS credentials available. Configure them (aws configure / AWS_PROFILE / env vars) and retry.'\n );\n } else if (/stack/i.test(msg) && /(does not exist|ValidationError)/i.test(msg)) {\n console.error(\n 'error: stack not found in this account/region. Check the stack name and --region.'\n );\n } else if (/AccessDenied|not authorized/i.test(msg)) {\n console.error(`error: access denied — ${msg}`);\n } else {\n console.error(`error: ${msg}`);\n }\n process.exit(2);\n });\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAgB,mBAAmB,GAAqB;CACtD,MAAM,MAAO,GAA4B,WAAW,OAA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