@intentius/chant-lexicon-terraform 0.124.102 → 0.124.103

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.
@@ -247,6 +247,12 @@ export const TERRAFORM_REFERENCE_CATALOG = {
247
247
  // and project, or the ARN's role name, so these only make them findable.
248
248
  { kind: "google_service_account", ids: ["account_id"] },
249
249
  { kind: "aws_iam_role", ids: ["name"] },
250
+ // Named by a literal in the block that uses them (#5340): the value a
251
+ // roster node's `db_subnet_group_name`, `subnet_group_name` or
252
+ // `function_name` carries.
253
+ { kind: "aws_db_subnet_group", ids: ["name"] },
254
+ { kind: "aws_elasticache_subnet_group", ids: ["name"] },
255
+ { kind: "aws_lambda_function", ids: ["function_name"] },
250
256
  ],
251
257
  refs: [
252
258
  // ── containment (→ boundary pairs, and containment edges) ──
@@ -24,6 +24,15 @@ export declare function plannerForBinary(binary: string | undefined): ChangeSetP
24
24
  * disruption ({@link disruptionFor}).
25
25
  */
26
26
  export declare function actionFor(actions: unknown): ChangeSetAction;
27
+ /**
28
+ * The disruption one `resource_changes[]` entry's `actions` mean (#5338):
29
+ * `update` is in place, `create, delete` a replacement made first, `delete,
30
+ * create` and `delete` destroy. Undefined for a create, a read, a no-op or a
31
+ * forget, which change nothing that exists. `classifyDisruption`
32
+ * (`./disruption.ts`) reads the same table, so the change set and the
33
+ * lifecycle plan agree.
34
+ */
35
+ export declare function terraformActionsDisruption(actions: unknown): "in-place" | "replace" | "destroy" | undefined;
27
36
  /** A resource address's module path, name and index, read off the address when the entry does not carry them. */
28
37
  export declare function parseTerraformAddress(address: string): {
29
38
  module?: string;
@@ -69,13 +69,26 @@ export function actionFor(actions) {
69
69
  }
70
70
  throw new Error(`a plan entry has actions ${JSON.stringify(actions)}, which the change set has no action for`);
71
71
  }
72
- function disruptionFor(actions, action) {
73
- switch (action) {
74
- case "update": return "in-place";
75
- case "delete": return "destroy";
76
- case "replace": return actions[0] === "create" ? "replace" : "destroy";
77
- default: return undefined;
78
- }
72
+ /**
73
+ * The disruption one `resource_changes[]` entry's `actions` mean (#5338):
74
+ * `update` is in place, `create, delete` a replacement made first, `delete,
75
+ * create` and `delete` destroy. Undefined for a create, a read, a no-op or a
76
+ * forget, which change nothing that exists. `classifyDisruption`
77
+ * (`./disruption.ts`) reads the same table, so the change set and the
78
+ * lifecycle plan agree.
79
+ */
80
+ export function terraformActionsDisruption(actions) {
81
+ const a = Array.isArray(actions) ? actions.map(String) : [];
82
+ if (a.length === 1 && a[0] === "update")
83
+ return "in-place";
84
+ if (a.length === 1 && a[0] === "delete")
85
+ return "destroy";
86
+ if (a.length === 2 && a.includes("create") && a.includes("delete"))
87
+ return a[0] === "create" ? "replace" : "destroy";
88
+ return undefined;
89
+ }
90
+ function disruptionFor(actions, _action) {
91
+ return terraformActionsDisruption(actions);
79
92
  }
80
93
  /** A resource address's module path, name and index, read off the address when the entry does not carry them. */
81
94
  export function parseTerraformAddress(address) {
@@ -1,20 +1,3 @@
1
- /**
2
- * The floors of the terraform lexicon's parts (#4916): for each part a
3
- * product may feature-detect on, the first release of
4
- * `@intentius/chant-lexicon-terraform` that has it. Each package has its own
5
- * version (#5138), so these are versions of the terraform lexicon, not of
6
- * chant core. chant core's floor table (`@intentius/chant/floor-table`)
7
- * lists them beside core's with the package each belongs to, and `chant dev
8
- * dead-guards` reads them against a product's pin on the lexicon.
9
- *
10
- * Only this file is read for the table: the `_FLOOR` constants elsewhere in
11
- * the lexicon name versions of other tools (`NEXUS_HOSTED_FLOOR` in
12
- * ./registry/targets/nexus.ts is a Nexus version). The entries that serve a
13
- * part re-export its floor by name, so the table names those subpaths too.
14
- *
15
- * This file imports nothing, so an entry that must stay light (./module-catalog)
16
- * can re-export from it.
17
- */
18
1
  /**
19
2
  * The first terraform lexicon release that has `moduleConsumers`, the scan of
20
3
  * every registry module call a root makes, with `readRegistryCatalog` and
@@ -29,3 +12,30 @@ export declare const MODULE_CONSUMERS_FLOOR = "0.124.55";
29
12
  export declare const USED_SOURCES_FLOOR = "0.124.55";
30
13
  /** The first terraform lexicon release that has `./module-catalog`, the known-module catalog TF047 reads (#4560). */
31
14
  export declare const MODULE_CATALOG_FLOOR = "0.124.55";
15
+ /**
16
+ * The first terraform lexicon release whose `classifyDisruption` classifies a
17
+ * planned update from the plan's actions (in place, replace, destroy), with
18
+ * `terraformDisruptionQueries` for a plan in hand, and whose `healthTargets`
19
+ * reads a root's covered resources through the aws, azure and gcp health
20
+ * reads with ids from its state (#5338).
21
+ */
22
+ export declare const TERRAFORM_HEALTH_DISRUPTION_FLOOR = "0.124.103";
23
+ /**
24
+ * The first terraform lexicon release that puts `facts.ownershipRows` on a
25
+ * choudoufu live root's nodes (#5402): `live-plan`'s `bound[].source`,
26
+ * `identity_values`, omission and adoption rows, `live-graph`'s
27
+ * `meta.engineGraph.gaps`, and with `CHANT_TERRAFORM_LIVE_LISTING=1`,
28
+ * `live-ls`'s `gaps[]` and `listed`. It needs `@intentius/chant` at
29
+ * `ENGINE_OWNERSHIP_ROWS_FLOOR` or later.
30
+ */
31
+ export declare const TERRAFORM_OWNERSHIP_ROWS_FLOOR = "0.124.103";
32
+ /**
33
+ * The first terraform lexicon release that reports a choudoufu live root's
34
+ * bound objects no block declares as live nodes (#5429): each `live-plan`
35
+ * `bound[]` address no declared block answers for, and with
36
+ * `CHANT_TERRAFORM_LIVE_LISTING=1` each `live-ls` item with `declared: false`,
37
+ * with choudoufu's resource type as its kind, status `orphan`, and
38
+ * `boundBy`, `listed` and `gaps` under `facts.ownershipRows`. It needs
39
+ * `@intentius/chant` at `UNDECLARED_LIVE_NODES_FLOOR` or later to draw them.
40
+ */
41
+ export declare const TERRAFORM_UNDECLARED_NODES_FLOOR = "0.124.103";
@@ -1,20 +1,3 @@
1
- /**
2
- * The floors of the terraform lexicon's parts (#4916): for each part a
3
- * product may feature-detect on, the first release of
4
- * `@intentius/chant-lexicon-terraform` that has it. Each package has its own
5
- * version (#5138), so these are versions of the terraform lexicon, not of
6
- * chant core. chant core's floor table (`@intentius/chant/floor-table`)
7
- * lists them beside core's with the package each belongs to, and `chant dev
8
- * dead-guards` reads them against a product's pin on the lexicon.
9
- *
10
- * Only this file is read for the table: the `_FLOOR` constants elsewhere in
11
- * the lexicon name versions of other tools (`NEXUS_HOSTED_FLOOR` in
12
- * ./registry/targets/nexus.ts is a Nexus version). The entries that serve a
13
- * part re-export its floor by name, so the table names those subpaths too.
14
- *
15
- * This file imports nothing, so an entry that must stay light (./module-catalog)
16
- * can re-export from it.
17
- */
18
1
  /**
19
2
  * The first terraform lexicon release that has `moduleConsumers`, the scan of
20
3
  * every registry module call a root makes, with `readRegistryCatalog` and
@@ -29,3 +12,30 @@ export const MODULE_CONSUMERS_FLOOR = "0.124.55";
29
12
  export const USED_SOURCES_FLOOR = "0.124.55";
30
13
  /** The first terraform lexicon release that has `./module-catalog`, the known-module catalog TF047 reads (#4560). */
31
14
  export const MODULE_CATALOG_FLOOR = "0.124.55";
15
+ /**
16
+ * The first terraform lexicon release whose `classifyDisruption` classifies a
17
+ * planned update from the plan's actions (in place, replace, destroy), with
18
+ * `terraformDisruptionQueries` for a plan in hand, and whose `healthTargets`
19
+ * reads a root's covered resources through the aws, azure and gcp health
20
+ * reads with ids from its state (#5338).
21
+ */
22
+ export const TERRAFORM_HEALTH_DISRUPTION_FLOOR = "0.124.103";
23
+ /**
24
+ * The first terraform lexicon release that puts `facts.ownershipRows` on a
25
+ * choudoufu live root's nodes (#5402): `live-plan`'s `bound[].source`,
26
+ * `identity_values`, omission and adoption rows, `live-graph`'s
27
+ * `meta.engineGraph.gaps`, and with `CHANT_TERRAFORM_LIVE_LISTING=1`,
28
+ * `live-ls`'s `gaps[]` and `listed`. It needs `@intentius/chant` at
29
+ * `ENGINE_OWNERSHIP_ROWS_FLOOR` or later.
30
+ */
31
+ export const TERRAFORM_OWNERSHIP_ROWS_FLOOR = "0.124.103";
32
+ /**
33
+ * The first terraform lexicon release that reports a choudoufu live root's
34
+ * bound objects no block declares as live nodes (#5429): each `live-plan`
35
+ * `bound[]` address no declared block answers for, and with
36
+ * `CHANT_TERRAFORM_LIVE_LISTING=1` each `live-ls` item with `declared: false`,
37
+ * with choudoufu's resource type as its kind, status `orphan`, and
38
+ * `boundBy`, `listed` and `gaps` under `facts.ownershipRows`. It needs
39
+ * `@intentius/chant` at `UNDECLARED_LIVE_NODES_FLOOR` or later to draw them.
40
+ */
41
+ export const TERRAFORM_UNDECLARED_NODES_FLOOR = "0.124.103";
@@ -151,7 +151,7 @@ import { PlanShapeMovedError, planShapeDifferences, planShapeDigest, } from "@in
151
151
  import { computePlanDigest } from "@intentius/chant/lifecycle/plan-digest";
152
152
  import { terraformResourceDigests } from "../plan-digest.js";
153
153
  import { ownPackageVersion } from "@intentius/chant/components/capability-plugin";
154
- import { choudoufuMemberOutputs, choudoufuMemberPlanSet, choudoufuPlanSet, choudoufuWaveApply, choudoufuWaveRoot, asUpstreamCommands, terraformApply, terraformInit, terraformOutputs, terraformPlan, withTerraformCommandHook, } from "../op/activities/terraform.js";
154
+ import { choudoufuMemberOutputs, choudoufuMemberPlanSet, choudoufuPlanSet, choudoufuWaveApply, choudoufuWaveRoot, asUpstreamCommands, terraformApply, terraformInit, terraformMarkedOutputs, terraformOutputs, terraformPlan, withTerraformCommandHook, } from "../op/activities/terraform.js";
155
155
  import { terraformPlanMoved } from "../exit-codes.js";
156
156
  import { terraformPlanShape } from "../plan-shape.js";
157
157
  import { plannerForBinary, terraformChangeSetPart } from "../change-set.js";
@@ -573,6 +573,7 @@ export function terraformApplyCapabilityWith(deps = {}) {
573
573
  plan: (ctx, step) => withTerraformCommandHook(hook, scope("plan", step), () => cap.plan(ctx, step)),
574
574
  run: (ctx, step) => withTerraformCommandHook(hook, scope("run", step), () => cap.run(ctx, step)),
575
575
  outputs: (ctx, step) => withTerraformCommandHook(hook, scope("outputs", step), () => cap.outputs(ctx, step)),
576
+ markedOutputs: (ctx, step) => withTerraformCommandHook(hook, scope("outputs", step), () => cap.markedOutputs(ctx, step)),
576
577
  planGroup: (ctx, members) => withTerraformCommandHook(hook, groupScope("plan", members), () => cap.planGroup(ctx, members)),
577
578
  runGroup: (ctx, run, members) => withTerraformCommandHook(hook, groupScope("run", members), () => cap.runGroup(ctx, run, members)),
578
579
  };
@@ -653,6 +654,13 @@ function terraformApplyMethods(deps) {
653
654
  await initRoot(input, ctx.processEnv, ctx.serial);
654
655
  return terraformOutputs(rootArgs(input, ctx.processEnv));
655
656
  },
657
+ // #5345: the same read with the outputs `sensitive = true` marks, which a replan keeps no digest of.
658
+ async markedOutputs(ctx, step) {
659
+ const input = await filledInput(deps.resolveRoot, ctx, step);
660
+ requireRoot(input);
661
+ await initRoot(input, ctx.processEnv, ctx.serial);
662
+ return terraformMarkedOutputs(rootArgs(input, ctx.processEnv));
663
+ },
656
664
  // #4447 (ws-107): a group core forms of components that read each other plans and applies as one composed run
657
665
  // when `terraform.compose.enabled` is set (./compose-group.ts). Delegates, so the methods are read when called.
658
666
  groupReads: (ctx, members) => group.groupReads(ctx, members),
@@ -7,6 +7,14 @@
7
7
  * const spec = { ..., step: { kind: "terraform-apply", root: "{target}" }, holds: { cost: terraformCostHold({ approveAbove: 100 }) } };
8
8
  * ```
9
9
  *
10
+ * infracost reads a copy of the plan document with its sensitive values
11
+ * replaced by `[redacted]` and runs without the forge tokens in its
12
+ * environment. `redactEnv` names variables whose values are secret though the
13
+ * plan does not mark them (a product's store values): each value is replaced
14
+ * in the copy and the variable leaves infracost's environment. `dropEnv`
15
+ * names more variables to leave out, such as a product's own token variables.
16
+ * Both take names; the job's environment holds the values.
17
+ *
10
18
  * The shape is core's `OpWaveCostHold`, written out here so the lexicon
11
19
  * builds against a core without it.
12
20
  */
@@ -17,10 +25,14 @@ export interface TerraformCostHold {
17
25
  approveAbove: number;
18
26
  format: "infracost";
19
27
  currency?: string;
28
+ redactEnv?: string[];
29
+ dropEnv?: string[];
20
30
  }
21
31
  /** A cost hold that prices each root with infracost, waiting over `approveAbove` a month. `command` replaces infracost's argv; it must name `{planJson}`. */
22
32
  export declare function terraformCostHold(options: {
23
33
  approveAbove: number;
24
34
  currency?: string;
25
35
  command?: string[];
36
+ redactEnv?: string[];
37
+ dropEnv?: string[];
26
38
  }): TerraformCostHold;
package/dist/cost-hold.js CHANGED
@@ -7,15 +7,34 @@
7
7
  * const spec = { ..., step: { kind: "terraform-apply", root: "{target}" }, holds: { cost: terraformCostHold({ approveAbove: 100 }) } };
8
8
  * ```
9
9
  *
10
+ * infracost reads a copy of the plan document with its sensitive values
11
+ * replaced by `[redacted]` and runs without the forge tokens in its
12
+ * environment. `redactEnv` names variables whose values are secret though the
13
+ * plan does not mark them (a product's store values): each value is replaced
14
+ * in the copy and the variable leaves infracost's environment. `dropEnv`
15
+ * names more variables to leave out, such as a product's own token variables.
16
+ * Both take names; the job's environment holds the values.
17
+ *
10
18
  * The shape is core's `OpWaveCostHold`, written out here so the lexicon
11
19
  * builds against a core without it.
12
20
  */
13
21
  /** infracost's own command over one plan document. */
14
22
  export const INFRACOST_ARGV = ["infracost", "breakdown", "--path", "{planJson}", "--format", "json", "--log-level", "error"];
23
+ /** Names of environment variables only, so no secret value sits in the spec. */
24
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
25
+ function envNames(option, names) {
26
+ if (names === undefined)
27
+ return undefined;
28
+ if (!Array.isArray(names) || !names.every((n) => typeof n === "string" && ENV_NAME.test(n)))
29
+ throw new Error(`terraformCostHold: ${option} is a list of environment variable names, never their values`);
30
+ return names;
31
+ }
15
32
  /** A cost hold that prices each root with infracost, waiting over `approveAbove` a month. `command` replaces infracost's argv; it must name `{planJson}`. */
16
33
  export function terraformCostHold(options) {
17
34
  const command = options.command ?? [...INFRACOST_ARGV];
18
35
  if (!command.some((a) => a.includes("{planJson}")))
19
36
  throw new Error("terraformCostHold: the command must name {planJson}, the root's plan document");
20
- return { command, approveAbove: options.approveAbove, format: "infracost", ...(options.currency ? { currency: options.currency } : {}) };
37
+ const redactEnv = envNames("redactEnv", options.redactEnv);
38
+ const dropEnv = envNames("dropEnv", options.dropEnv);
39
+ return { command, approveAbove: options.approveAbove, format: "infracost", ...(options.currency ? { currency: options.currency } : {}), ...(redactEnv ? { redactEnv } : {}), ...(dropEnv ? { dropEnv } : {}) };
21
40
  }
@@ -239,7 +239,7 @@
239
239
  import type { DescribeResourcesResult, ResourceMetadata, TeardownEnumeration } from "@intentius/chant/lexicon";
240
240
  import { type DeclaredEntity, type UnobservedReason } from "@intentius/chant/observation";
241
241
  import type { OwnershipMarker } from "@intentius/chant/ownership";
242
- import type { EngineFacts } from "@intentius/chant/engine-facts";
242
+ import { type EngineFacts, type EngineOwnershipRows } from "@intentius/chant/engine-facts";
243
243
  import type { IREdge } from "@intentius/chant/graph-ir";
244
244
  import { choudoufuLiveGraph, choudoufuLiveLs, choudoufuLivePlanDocument, terraformInit, terraformPlanRead, terraformShow } from "./op/activities/terraform.js";
245
245
  import type { TerraformObserveDepth } from "./config.js";
@@ -291,6 +291,8 @@ export interface LivePlanBoundRow {
291
291
  identity?: string;
292
292
  /** Which admission path supplied the identity: `marker`, `record`, `derived` or `cache`. */
293
293
  source?: string;
294
+ /** `identity_values`: the values that identify the bound object, by argument (#5402). */
295
+ identityValues?: Record<string, string>;
294
296
  }
295
297
  /** One `omissions[]` entry: a declared instance the plan could not read, and why. */
296
298
  export interface LivePlanOmissionRow {
@@ -310,6 +312,8 @@ export interface LivePlanUnownedRow {
310
312
  adoptEstate?: string;
311
313
  /** `adopt_tofu_address`: the escaped address the adopting tag write would carry. */
312
314
  adoptAddress?: string;
315
+ /** `adopt_command`, or `hint`: the one-line write choudoufu composed, when it printed one (#5402). */
316
+ adoptCommand?: string;
313
317
  }
314
318
  /**
315
319
  * One `adoptable[]` entry: a live resource the estate-wide sweep matched to a
@@ -328,6 +332,7 @@ export interface LivePlanAdoptableRow {
328
332
  identity?: string;
329
333
  adoptEstate?: string;
330
334
  adoptAddress?: string;
335
+ adoptCommand?: string;
331
336
  /** `matched[]`: the arguments the declaration and the live resource agreed on exactly. */
332
337
  matched?: Array<{
333
338
  attribute: string;
@@ -359,6 +364,15 @@ export interface LivePlanIndex {
359
364
  * degrade to "this section said nothing", never to a throw.
360
365
  */
361
366
  export declare function indexLivePlan(document: unknown): LivePlanIndex;
367
+ /**
368
+ * The rows behind each address's ownership (#5402), by the address
369
+ * `live-plan` printed: `bound[]`'s source and `identity_values`, the
370
+ * omission, and the adoption an `unowned[]` or `adoptable[]` row offers. With
371
+ * a `live-ls` listing, also its `gaps[]` (read `listing`, the rung as the
372
+ * reason) and, on a bound address, whether the listing holds it under the
373
+ * estate's marker. An address with none of these is left out.
374
+ */
375
+ export declare function ownershipRowsByAddress(index: LivePlanIndex, listing?: LiveLsListing): Map<string, EngineOwnershipRows>;
362
376
  /**
363
377
  * Every instance address in the document belonging to the declared block
364
378
  * `address`. Exported for the behaviour request builder (`./behaviour/`,
@@ -397,9 +411,9 @@ export declare function classifyLiveInstance(address: string, index: LivePlanInd
397
411
  * The environment variable that asks for each live root's `live-plan -json`
398
412
  * document as a file, in a directory the caller owns (behold#924).
399
413
  *
400
- * The overlay keeps chant's verdict per block and drops the rows behind it:
401
- * each instance's omission reason and detail, `identity_values`, the adoptable
402
- * row's own fields. A caller that paints ownership from those rows and wants
414
+ * The overlay keeps chant's verdict per block; the rows behind it (each
415
+ * instance's omission reason and detail, `identity_values`, the adoptable
416
+ * row's own fields) ride on each node's `facts.ownershipRows` (#5402). A caller that paints ownership from those rows and wants
403
417
  * the plan's attributes from the plan depth would otherwise run its own
404
418
  * `live-plan` beside this one, two refreshes of the estate that can disagree
405
419
  * (choudoufu #1014). With this set to an absolute directory, the document this
@@ -419,6 +433,8 @@ export interface EngineGraphRead {
419
433
  blocks: Map<string, EngineFacts>;
420
434
  /** Facts of an instance node, by its block's entity key, then by the instance address. */
421
435
  instances: Map<string, Map<string, EngineFacts>>;
436
+ /** Each instance address's node id, as `observedInstanceNodeId` gives it and the declared graph draws it (#5333). */
437
+ instanceNodes: Map<string, string>;
422
438
  /** Edges with a grain, endpoints as live graph node ids. */
423
439
  edges: IREdge[];
424
440
  }
@@ -432,9 +448,13 @@ export interface EngineGraphRead {
432
448
  * the configuration reads, `estate:<name>`) has no chant entity, so its
433
449
  * edges are left out. Edges keep their grain; one without a grain is left out.
434
450
  *
451
+ * Each node's facts also carry its `ownershipRows` (#5402): `rows`, by the
452
+ * address `live-plan` printed (`ownershipRowsByAddress`), and the
453
+ * document's own `meta.engineGraph.gaps` entry for the node, read `graph`.
454
+ *
435
455
  * Throws when the document is not an engine graph document.
436
456
  */
437
- export declare function readEngineGraph(root: string, document: unknown): EngineGraphRead;
457
+ export declare function readEngineGraph(root: string, document: unknown, rows?: ReadonlyMap<string, EngineOwnershipRows>): EngineGraphRead;
438
458
  /**
439
459
  * `resources` with {@link readEngineGraph}'s facts on them: a block's on
440
460
  * `ResourceMetadata.facts`, an instance's on its `instances` entry of the
@@ -442,6 +462,42 @@ export declare function readEngineGraph(root: string, document: unknown): Engine
442
462
  * read did not return.
443
463
  */
444
464
  export declare function withEngineFacts(resources: Record<string, ResourceMetadata>, read: EngineGraphRead): Record<string, ResourceMetadata>;
465
+ /**
466
+ * The facts of {@link readEngineGraph}'s reads that no node of the live graph
467
+ * will carry (#5333), by the node id the declared graph gives them: a block
468
+ * `resources` does not hold (a pending create, or one `owned` filtered out),
469
+ * and an instance that is not a present instance of a block it holds. These
470
+ * are the `pending` nodes of a live root, and its `unowned` and `foreign`
471
+ * ones under `--owned`; `chant graph --live --overlay` puts them on the
472
+ * declared nodes (`ObservationResult.engineFacts`).
473
+ */
474
+ export declare function engineFactsBeside(resources: Record<string, ResourceMetadata>, reads: readonly EngineGraphRead[]): Record<string, EngineFacts>;
475
+ /**
476
+ * The environment variable that adds a `live-ls -json` listing to each live
477
+ * root's engine facts (#5402). Set to `1`, a live read also runs `choudoufu
478
+ * live-ls -estate=<estate> -json .` per root, and each node's
479
+ * `facts.ownershipRows` carries the listing's `gaps[]` and, on a bound node,
480
+ * `listed`. Unset, no listing runs.
481
+ */
482
+ export declare const TERRAFORM_LIVE_LISTING_ENV = "CHANT_TERRAFORM_LIVE_LISTING";
483
+ /**
484
+ * The objects a live root's estate binds that no block of its configuration
485
+ * declares (#5429), as live nodes keyed by {@link entityKeyFor}: each
486
+ * `live-plan` `bound[]` address no declared block or module call answers for
487
+ * (choudoufu's `live-graph` gives it a `not-in-configuration` gap), and each
488
+ * `live-ls` item with `declared: false` when the listing ran.
489
+ *
490
+ * Each one's `type` is the resource type choudoufu prints (`bound[].type`, or
491
+ * the item's `type`), its status `orphan`, the word {@link observeAmbient}
492
+ * gives the same object, and its ownership `owned`, since the estate's marker
493
+ * or record bound it. Its facts are the engine graph's node for the address
494
+ * with the address's rows under `ownershipRows`: `boundBy`, `listed` and the
495
+ * gaps from `live-graph` and `live-ls`.
496
+ *
497
+ * Empty when every bound address and listed item is declared, so such a root
498
+ * reads exactly as before.
499
+ */
500
+ export declare function undeclaredBound(root: string, declared: readonly TerraformDeclared[], index: LivePlanIndex, listing?: LiveLsListing, read?: EngineGraphRead): Record<string, ResourceMetadata>;
445
501
  /** One `items[]` entry of a `live-ls -json` listing. */
446
502
  export interface LiveLsItem {
447
503
  /** ARN or other stable identity. */
@@ -238,6 +238,7 @@
238
238
  */
239
239
  import { mergeObservations, normalizeObservation, observation, observeEntities, } from "@intentius/chant/observation";
240
240
  import { observedInstanceNodeId, rollupInstances, terraformInstancePath, TERRAFORM_INSTANCE_ROLLUP, } from "@intentius/chant/instance-nodes";
241
+ import { engineGapsOf, engineOwnershipRowsOf, mergeOwnershipRows, withOwnershipRows, } from "@intentius/chant/engine-facts";
241
242
  import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
242
243
  import { tmpdir } from "node:os";
243
244
  import { isAbsolute, join } from "node:path";
@@ -355,11 +356,13 @@ export function indexLivePlan(document) {
355
356
  const addr = asString(row.addr);
356
357
  if (!addr)
357
358
  continue;
359
+ const identityValues = Object.fromEntries(Object.entries(asRecord(row.identity_values)).filter((e) => typeof e[1] === "string"));
358
360
  index.bound.set(addr, {
359
361
  addr,
360
362
  ...(asString(row.type) ? { type: asString(row.type) } : {}),
361
363
  ...(asString(row.identity) ? { identity: asString(row.identity) } : {}),
362
364
  ...(asString(row.source) ? { source: asString(row.source) } : {}),
365
+ ...(Object.keys(identityValues).length > 0 ? { identityValues } : {}),
363
366
  });
364
367
  }
365
368
  for (const entry of asArray(doc.omissions)) {
@@ -385,6 +388,7 @@ export function indexLivePlan(document) {
385
388
  ...(asString(row.tofu_estate) ? { heldBy: asString(row.tofu_estate) } : {}),
386
389
  ...(asString(row.adopt_tofu_estate) ? { adoptEstate: asString(row.adopt_tofu_estate) } : {}),
387
390
  ...(asString(row.adopt_tofu_address) ? { adoptAddress: asString(row.adopt_tofu_address) } : {}),
391
+ ...adoptCommandOf(row),
388
392
  });
389
393
  }
390
394
  for (const entry of asArray(doc.adoptable)) {
@@ -402,6 +406,7 @@ export function indexLivePlan(document) {
402
406
  ...(asString(row.identity) ? { identity: asString(row.identity) } : {}),
403
407
  ...(asString(row.adopt_tofu_estate) ? { adoptEstate: asString(row.adopt_tofu_estate) } : {}),
404
408
  ...(asString(row.adopt_tofu_address) ? { adoptAddress: asString(row.adopt_tofu_address) } : {}),
409
+ ...adoptCommandOf(row),
405
410
  ...(matched.length > 0 ? { matched } : {}),
406
411
  });
407
412
  }
@@ -421,6 +426,63 @@ export function indexLivePlan(document) {
421
426
  ].sort();
422
427
  return index;
423
428
  }
429
+ /** An `unowned[]` or `adoptable[]` row's composed write: `adopt_command`, else `hint`. */
430
+ function adoptCommandOf(row) {
431
+ const command = asString(row.adopt_command) ?? asString(row.hint);
432
+ return command ? { adoptCommand: command } : {};
433
+ }
434
+ /**
435
+ * The rows behind each address's ownership (#5402), by the address
436
+ * `live-plan` printed: `bound[]`'s source and `identity_values`, the
437
+ * omission, and the adoption an `unowned[]` or `adoptable[]` row offers. With
438
+ * a `live-ls` listing, also its `gaps[]` (read `listing`, the rung as the
439
+ * reason) and, on a bound address, whether the listing holds it under the
440
+ * estate's marker. An address with none of these is left out.
441
+ */
442
+ export function ownershipRowsByAddress(index, listing) {
443
+ const out = new Map();
444
+ const add = (address, rows) => {
445
+ const merged = mergeOwnershipRows(out.get(address), rows);
446
+ if (merged)
447
+ out.set(address, merged);
448
+ };
449
+ const listed = listing ? new Set(listing.items.map((i) => i.address).filter((a) => !!a)) : undefined;
450
+ for (const [address, row] of index.bound) {
451
+ add(address, {
452
+ ...(row.source ? { boundBy: row.source } : {}),
453
+ ...(row.identityValues ? { identityValues: row.identityValues } : {}),
454
+ ...(listed ? { listed: listed.has(address) } : {}),
455
+ });
456
+ }
457
+ for (const [address, row] of index.omissions) {
458
+ if (row.reason)
459
+ add(address, { omission: { reason: row.reason, detail: row.detail } });
460
+ }
461
+ const adoption = (row) => {
462
+ const matched = "matched" in row ? row.matched : undefined;
463
+ const adopt = {
464
+ ...(row.adoptEstate ? { owner: row.adoptEstate } : {}),
465
+ ...(row.adoptAddress ? { address: row.adoptAddress } : {}),
466
+ ...(row.adoptCommand ? { command: row.adoptCommand } : {}),
467
+ ...(matched?.length ? { matched } : {}),
468
+ };
469
+ return Object.keys(adopt).length > 0 ? { adopt } : {};
470
+ };
471
+ for (const [address, row] of index.unowned)
472
+ add(address, adoption(row));
473
+ for (const [address, row] of index.adoptable) {
474
+ // An unowned[] row answers first, as `classifyLiveInstance` reads it.
475
+ if (!index.unowned.has(address))
476
+ add(address, adoption(row));
477
+ }
478
+ for (const gap of listing?.gaps ?? []) {
479
+ add(gap.address, { gaps: [{ read: "listing", reason: gap.rung, detail: gap.detail }] });
480
+ }
481
+ for (const [address, rows] of out)
482
+ if (Object.keys(rows).length === 0)
483
+ out.delete(address);
484
+ return out;
485
+ }
424
486
  /** The chant verdict for one omission: `no-credentials` when its detail says so. */
425
487
  function omissionVerdict(row) {
426
488
  const mapped = LIVE_PLAN_OMISSION_REASONS[row.reason] ?? "read-failed";
@@ -629,9 +691,9 @@ function readLiveResource(entity, index, root, queried) {
629
691
  * The environment variable that asks for each live root's `live-plan -json`
630
692
  * document as a file, in a directory the caller owns (behold#924).
631
693
  *
632
- * The overlay keeps chant's verdict per block and drops the rows behind it:
633
- * each instance's omission reason and detail, `identity_values`, the adoptable
634
- * row's own fields. A caller that paints ownership from those rows and wants
694
+ * The overlay keeps chant's verdict per block; the rows behind it (each
695
+ * instance's omission reason and detail, `identity_values`, the adoptable
696
+ * row's own fields) ride on each node's `facts.ownershipRows` (#5402). A caller that paints ownership from those rows and wants
635
697
  * the plan's attributes from the plan depth would otherwise run its own
636
698
  * `live-plan` beside this one, two refreshes of the estate that can disagree
637
699
  * (choudoufu #1014). With this set to an absolute directory, the document this
@@ -784,6 +846,9 @@ function engineFactsOf(value) {
784
846
  const observedAt = asString(f.observedAt);
785
847
  if (observedAt)
786
848
  out.observedAt = observedAt;
849
+ const rows = engineOwnershipRowsOf(f.ownershipRows);
850
+ if (rows)
851
+ out.ownershipRows = rows;
787
852
  return Object.keys(out).length > 0 ? out : undefined;
788
853
  }
789
854
  /**
@@ -796,16 +861,30 @@ function engineFactsOf(value) {
796
861
  * the configuration reads, `estate:<name>`) has no chant entity, so its
797
862
  * edges are left out. Edges keep their grain; one without a grain is left out.
798
863
  *
864
+ * Each node's facts also carry its `ownershipRows` (#5402): `rows`, by the
865
+ * address `live-plan` printed (`ownershipRowsByAddress`), and the
866
+ * document's own `meta.engineGraph.gaps` entry for the node, read `graph`.
867
+ *
799
868
  * Throws when the document is not an engine graph document.
800
869
  */
801
- export function readEngineGraph(root, document) {
870
+ export function readEngineGraph(root, document, rows) {
802
871
  const doc = asRecord(document);
803
872
  const engineGraph = asRecord(asRecord(doc.meta).engineGraph);
804
873
  if (doc.version !== 1 || engineGraph.format !== 1 || !Array.isArray(doc.nodes)) {
805
874
  throw new Error("not an engine graph document (want GraphIR version 1 with meta.engineGraph format 1)");
806
875
  }
876
+ const graphGaps = new Map();
877
+ for (const entry of asArray(engineGraph.gaps)) {
878
+ const gap = asRecord(entry);
879
+ const address = asString(gap.address);
880
+ const [g] = engineGapsOf([{ read: "graph", reason: gap.reason, detail: gap.detail }]);
881
+ if (address && g)
882
+ graphGaps.set(address, mergeOwnershipRows(graphGaps.get(address), { gaps: [g] }));
883
+ }
884
+ const rowsFor = (id) => mergeOwnershipRows(rows?.get(id), graphGaps.get(id));
807
885
  const blocks = new Map();
808
886
  const instances = new Map();
887
+ const instanceNodes = new Map();
809
888
  const nodeIds = new Map();
810
889
  for (const entry of doc.nodes) {
811
890
  const node = asRecord(entry);
@@ -813,7 +892,7 @@ export function readEngineGraph(root, document) {
813
892
  const address = asString(asRecord(node.attrs).address);
814
893
  if (!id || !address)
815
894
  continue;
816
- const facts = engineFactsOf(node.facts);
895
+ const facts = withOwnershipRows(engineFactsOf(node.facts), rowsFor(id));
817
896
  const instanceOf = asString(node.instanceOf);
818
897
  if (instanceOf) {
819
898
  const block = entityKeyFor(root, instanceOf);
@@ -824,8 +903,10 @@ export function readEngineGraph(root, document) {
824
903
  ...(key !== undefined ? { key } : {}),
825
904
  ...(scope !== undefined ? { scope } : {}),
826
905
  });
827
- if (liveId)
906
+ if (liveId) {
828
907
  nodeIds.set(id, liveId);
908
+ instanceNodes.set(id, liveId);
909
+ }
829
910
  if (facts) {
830
911
  let byAddress = instances.get(block);
831
912
  if (!byAddress)
@@ -857,7 +938,7 @@ export function readEngineGraph(root, document) {
857
938
  seen.add(key);
858
939
  edges.push({ from, to, kind: "ref", ...(viaAttr ? { viaAttr } : {}), grain: grain });
859
940
  }
860
- return { blocks, instances, edges };
941
+ return { blocks, instances, instanceNodes, edges };
861
942
  }
862
943
  /**
863
944
  * `resources` with {@link readEngineGraph}'s facts on them: a block's on
@@ -884,6 +965,65 @@ export function withEngineFacts(resources, read) {
884
965
  }
885
966
  return out;
886
967
  }
968
+ /**
969
+ * The facts of {@link readEngineGraph}'s reads that no node of the live graph
970
+ * will carry (#5333), by the node id the declared graph gives them: a block
971
+ * `resources` does not hold (a pending create, or one `owned` filtered out),
972
+ * and an instance that is not a present instance of a block it holds. These
973
+ * are the `pending` nodes of a live root, and its `unowned` and `foreign`
974
+ * ones under `--owned`; `chant graph --live --overlay` puts them on the
975
+ * declared nodes (`ObservationResult.engineFacts`).
976
+ */
977
+ export function engineFactsBeside(resources, reads) {
978
+ const drawn = new Set(Object.keys(resources));
979
+ for (const [name, meta] of Object.entries(resources)) {
980
+ for (const inst of meta.instances ?? []) {
981
+ if (inst.verdict !== "present")
982
+ continue;
983
+ const id = observedInstanceNodeId(name, inst);
984
+ if (id)
985
+ drawn.add(id);
986
+ }
987
+ }
988
+ const out = {};
989
+ for (const read of reads) {
990
+ for (const [key, facts] of read.blocks)
991
+ if (!drawn.has(key))
992
+ out[key] = facts;
993
+ for (const byAddress of read.instances.values()) {
994
+ for (const [address, facts] of byAddress) {
995
+ const id = read.instanceNodes.get(address);
996
+ if (id && !drawn.has(id))
997
+ out[id] = facts;
998
+ }
999
+ }
1000
+ }
1001
+ return out;
1002
+ }
1003
+ /**
1004
+ * The environment variable that adds a `live-ls -json` listing to each live
1005
+ * root's engine facts (#5402). Set to `1`, a live read also runs `choudoufu
1006
+ * live-ls -estate=<estate> -json .` per root, and each node's
1007
+ * `facts.ownershipRows` carries the listing's `gaps[]` and, on a bound node,
1008
+ * `listed`. Unset, no listing runs.
1009
+ */
1010
+ export const TERRAFORM_LIVE_LISTING_ENV = "CHANT_TERRAFORM_LIVE_LISTING";
1011
+ /**
1012
+ * The listing {@link TERRAFORM_LIVE_LISTING_ENV} asks for, or none. A failed
1013
+ * listing is a note, and the rows from `live-plan` still ride.
1014
+ */
1015
+ async function ownershipListing(root, cwd, deps) {
1016
+ if (process.env[TERRAFORM_LIVE_LISTING_ENV] !== "1")
1017
+ return {};
1018
+ try {
1019
+ const listed = await deps.liveLs({ root, compare: true, ...(cwd ? { cwd } : {}) });
1020
+ return { listing: readLiveLs(listed.json) };
1021
+ }
1022
+ catch (err) {
1023
+ const message = (err instanceof Error ? err.message : String(err)).split("\n")[0];
1024
+ return { note: `terraform.roots.${root}: the listing's rows are absent: \`choudoufu live-ls -json\` failed (${message}); the rest of the read is unchanged` };
1025
+ }
1026
+ }
887
1027
  /**
888
1028
  * Run `choudoufu live-graph -json -from-plan=<file>` over the document a
889
1029
  * live root's bind handed off, and read it (#4528). Never throws: facts are
@@ -907,7 +1047,10 @@ async function engineGraphFor(root, cwd, deps, handoff) {
907
1047
  `(${graph.detail}), which needs v${MIN_CHOUDOUFU_GRAPH_VERSION} or later; the rest of the read is unchanged`,
908
1048
  };
909
1049
  }
910
- return { read: readEngineGraph(root, graph.json) };
1050
+ const listed = await ownershipListing(root, cwd, deps);
1051
+ const rows = ownershipRowsByAddress(indexLivePlan(handoff.json), listed.listing);
1052
+ const read = readEngineGraph(root, graph.json, rows);
1053
+ return { read, ...(listed.listing ? { listing: listed.listing } : {}), ...(listed.note ? { note: listed.note } : {}) };
911
1054
  }
912
1055
  catch (err) {
913
1056
  const message = (err instanceof Error ? err.message : String(err)).split("\n")[0];
@@ -920,6 +1063,91 @@ async function engineGraphFor(root, cwd, deps, handoff) {
920
1063
  rmSync(scratch, { recursive: true, force: true });
921
1064
  }
922
1065
  }
1066
+ /** True when a declared block of the root answers for `address`: its own block, or a module call it sits under. */
1067
+ function declaresAddress(address, declared) {
1068
+ const block = blockAddressOf(address);
1069
+ return declared.some((entity) => entity.type === MODULE_TYPE ? underModule(address, entity.address) : entity.type === RESOURCE_TYPE && entity.address === block);
1070
+ }
1071
+ /** The engine graph's facts for a choudoufu address, block or instance, if the read has a node for it. */
1072
+ function engineFactsAt(read, key, address) {
1073
+ if (!read)
1074
+ return undefined;
1075
+ const block = read.blocks.get(key);
1076
+ if (block)
1077
+ return block;
1078
+ for (const byAddress of read.instances.values()) {
1079
+ const facts = byAddress.get(address);
1080
+ if (facts)
1081
+ return facts;
1082
+ }
1083
+ return undefined;
1084
+ }
1085
+ /**
1086
+ * The objects a live root's estate binds that no block of its configuration
1087
+ * declares (#5429), as live nodes keyed by {@link entityKeyFor}: each
1088
+ * `live-plan` `bound[]` address no declared block or module call answers for
1089
+ * (choudoufu's `live-graph` gives it a `not-in-configuration` gap), and each
1090
+ * `live-ls` item with `declared: false` when the listing ran.
1091
+ *
1092
+ * Each one's `type` is the resource type choudoufu prints (`bound[].type`, or
1093
+ * the item's `type`), its status `orphan`, the word {@link observeAmbient}
1094
+ * gives the same object, and its ownership `owned`, since the estate's marker
1095
+ * or record bound it. Its facts are the engine graph's node for the address
1096
+ * with the address's rows under `ownershipRows`: `boundBy`, `listed` and the
1097
+ * gaps from `live-graph` and `live-ls`.
1098
+ *
1099
+ * Empty when every bound address and listed item is declared, so such a root
1100
+ * reads exactly as before.
1101
+ */
1102
+ export function undeclaredBound(root, declared, index, listing, read) {
1103
+ const rows = ownershipRowsByAddress(index, listing);
1104
+ const listedItems = new Map();
1105
+ for (const item of listing?.items ?? []) {
1106
+ if (!item.declared)
1107
+ listedItems.set(item.address ?? item.id, item);
1108
+ }
1109
+ const addresses = new Set();
1110
+ for (const address of index.bound.keys())
1111
+ if (!declaresAddress(address, declared))
1112
+ addresses.add(address);
1113
+ for (const address of listedItems.keys())
1114
+ if (!declaresAddress(address, declared))
1115
+ addresses.add(address);
1116
+ const estate = index.estate || listing?.estate || "";
1117
+ const out = {};
1118
+ for (const address of [...addresses].sort()) {
1119
+ const bound = index.bound.get(address);
1120
+ const item = listedItems.get(address);
1121
+ const type = bound?.type ?? item?.type;
1122
+ if (!type)
1123
+ continue;
1124
+ const key = entityKeyFor(root, address);
1125
+ // An object only the listing names is listed, though no bound row says so.
1126
+ const facts = withOwnershipRows(engineFactsAt(read, key, address), mergeOwnershipRows(rows.get(address), item ? { listed: true } : undefined));
1127
+ // A marker was read when the plan bound it by marker, or the listing found it by its tags.
1128
+ const byMarker = bound ? bound.source === "marker" : item !== undefined;
1129
+ out[key] = {
1130
+ type,
1131
+ physicalId: bound?.identity ?? item?.id ?? address,
1132
+ status: "orphan",
1133
+ ownership: "owned",
1134
+ ...(byMarker && estate ? { marker: { stack: estate } } : {}),
1135
+ ambient: true,
1136
+ attributes: {
1137
+ address,
1138
+ root,
1139
+ estate,
1140
+ resourceType: type,
1141
+ status: "orphan",
1142
+ ...(bound?.source ? { boundBy: bound.source } : {}),
1143
+ ...(item?.slot ? { slot: item.slot } : {}),
1144
+ ...(item?.source ? { listedBy: item.source } : {}),
1145
+ },
1146
+ ...(facts ? { facts } : {}),
1147
+ };
1148
+ }
1149
+ return out;
1150
+ }
923
1151
  /** Parse a `live-ls -json` document. A missing section reads as empty, never as a throw. */
924
1152
  export function readLiveLs(document) {
925
1153
  const doc = asRecord(document);
@@ -1536,14 +1764,20 @@ export async function describeResources(options, deps = REAL_DEPS) {
1536
1764
  const sources = {};
1537
1765
  const rootReads = {};
1538
1766
  const edges = [];
1767
+ const engineReads = [];
1768
+ // Bound objects no block declares (#5429), as live nodes beside the read.
1769
+ const undeclared = {};
1539
1770
  // A live root's observation with the engine graph's facts and edges on it (#4528).
1540
- const withEngineGraph = async (root, handoff, observed) => {
1771
+ const withEngineGraph = async (root, declared, handoff, observed) => {
1541
1772
  const graph = await engineGraphFor(root, options.cwd, deps, handoff);
1542
1773
  if (graph.note)
1543
1774
  notes.push(graph.note);
1775
+ if (handoff.json !== undefined)
1776
+ Object.assign(undeclared, undeclaredBound(root, declared, indexLivePlan(handoff.json), graph.listing, graph.read));
1544
1777
  if (!graph.read)
1545
1778
  return observed;
1546
1779
  edges.push(...graph.read.edges);
1780
+ engineReads.push(graph.read);
1547
1781
  return { ...observed, resources: withEngineFacts(observed.resources, graph.read) };
1548
1782
  };
1549
1783
  const depthOf = byRoot.size > 0 ? await observeDepths(options, notes) : () => "state";
@@ -1568,14 +1802,14 @@ export async function describeResources(options, deps = REAL_DEPS) {
1568
1802
  rootReads[`terraform.roots.${root}`] = outcome.read;
1569
1803
  if (outcome.note)
1570
1804
  notes.push(outcome.note);
1571
- parts.push(await withEngineGraph(root, handoff, normalizeObservation(read)));
1805
+ parts.push(await withEngineGraph(root, declared, handoff, normalizeObservation(read)));
1572
1806
  continue;
1573
1807
  }
1574
1808
  for (const entity of declared)
1575
1809
  sources[entity.name] = "live";
1576
1810
  const handoff = {};
1577
1811
  const read = await observeEntities(declared, liveAdapter(root, options.cwd, deps, handoff));
1578
- parts.push(await withEngineGraph(root, handoff, normalizeObservation(read)));
1812
+ parts.push(await withEngineGraph(root, declared, handoff, normalizeObservation(read)));
1579
1813
  continue;
1580
1814
  }
1581
1815
  if (depth === "plan") {
@@ -1626,6 +1860,14 @@ export async function describeResources(options, deps = REAL_DEPS) {
1626
1860
  }
1627
1861
  }
1628
1862
  // A planned create's plan attributes (#4372) ride beside the verdict, never
1629
- // in `resources`: the block stays absent.
1630
- return observation(resources, unobserved, merged.queried, merged.notes, undefined, sources, merged.annotations, rootReads, edges);
1863
+ // in `resources`: the block stays absent. So do the engine's facts about
1864
+ // what no live node will carry (#5333), after --owned has filtered.
1865
+ const result = observation(resources, unobserved, merged.queried, merged.notes, undefined, sources, merged.annotations, rootReads, edges);
1866
+ // An undeclared object's facts ride on its own node (#5429), not beside.
1867
+ const beside = engineFactsBeside({ ...undeclared, ...resources }, engineReads);
1868
+ return {
1869
+ ...result,
1870
+ ...(Object.keys(beside).length > 0 ? { engineFacts: beside } : {}),
1871
+ ...(Object.keys(undeclared).length > 0 ? { undeclared } : {}),
1872
+ };
1631
1873
  }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * `classifyDisruption` for terraform (#5338): what applying a planned update
3
+ * costs, from the plan's own `actions`.
4
+ *
5
+ * Terraform already says it. A `resource_changes[]` entry's
6
+ * `change.actions` is `["update"]` for a change in place, `["create",
7
+ * "delete"]` for a replacement created before the old one goes
8
+ * (`create_before_destroy`), `["delete", "create"]` for one that deletes
9
+ * first, and `["delete"]` for a removal. `replace_paths` names the
10
+ * attributes that forced a replacement.
11
+ *
12
+ * | actions | disruption |
13
+ * |---|---|
14
+ * | `update` | `in-place` |
15
+ * | `create`, `delete` | `replace` |
16
+ * | `delete`, `create` | `destroy` |
17
+ * | `delete` | `destroy` |
18
+ *
19
+ * The classifier answers through core's contract, from the attributes the
20
+ * plan depth puts on each block (`planActions`, keyed by instance, and
21
+ * `planReplacePaths`, see `./plan-observation.ts`). A block's verdict is its
22
+ * most disruptive instance's. A query whose attributes carry no plan gets no
23
+ * verdict, which core reads as `unknown`. {@link terraformDisruptionQueries}
24
+ * builds the same queries straight from a `show -json` plan, one per
25
+ * resource change, for a caller holding the plan rather than a read.
26
+ *
27
+ * The table itself is `terraformActionsDisruption` in `./change-set.ts`,
28
+ * which the change set adapter reads too, so the two agree and the change
29
+ * set bundle stays as light as it was.
30
+ */
31
+ import type { DisruptionQuery, DisruptionVerdict } from "@intentius/chant/lexicon";
32
+ import { terraformActionsDisruption } from "./change-set.js";
33
+ export { terraformActionsDisruption };
34
+ /** One query's verdict, or undefined when its attributes carry no plan. */
35
+ export declare function terraformQueryVerdict(query: DisruptionQuery): DisruptionVerdict | undefined;
36
+ /** `LexiconPlugin.classifyDisruption` for terraform. */
37
+ export declare function classifyTerraformDisruption(options: {
38
+ environment: string;
39
+ changes: DisruptionQuery[];
40
+ }): Record<string, DisruptionVerdict>;
41
+ /**
42
+ * The queries a `show -json` plan holds: one per `resource_changes[]` entry
43
+ * that changes something existing (an update, a replacement or a delete),
44
+ * named by its address, with the plan's actions and replace paths as the
45
+ * attributes the classifier reads.
46
+ */
47
+ export declare function terraformDisruptionQueries(plan: unknown): DisruptionQuery[];
@@ -0,0 +1,74 @@
1
+ import { terraformActionsDisruption } from "./change-set.js";
2
+ import { indexPlan } from "./plan-observation.js";
3
+ export { terraformActionsDisruption };
4
+ const RANK = { "in-place": 0, replace: 1, destroy: 2 };
5
+ const DETAIL = {
6
+ "in-place": "the plan updates it in place",
7
+ replace: "the plan creates a replacement, then deletes the old one",
8
+ destroy: "the plan deletes it before anything replaces it",
9
+ };
10
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
11
+ /** One attribute off the query: its observed value, else the new value of a delta on it. */
12
+ function attribute(query, key) {
13
+ if (query.attributes && key in query.attributes)
14
+ return query.attributes[key];
15
+ return query.deltas.find((d) => d.path === `attributes.${key}`)?.newValue;
16
+ }
17
+ /** One query's verdict, or undefined when its attributes carry no plan. */
18
+ export function terraformQueryVerdict(query) {
19
+ const planActions = attribute(query, "planActions");
20
+ if (!isRecord(planActions))
21
+ return undefined;
22
+ let worst;
23
+ for (const actions of Object.values(planActions)) {
24
+ const d = terraformActionsDisruption(actions);
25
+ if (d && (!worst || RANK[d] > RANK[worst]))
26
+ worst = d;
27
+ }
28
+ if (!worst)
29
+ return undefined;
30
+ const paths = attribute(query, "planReplacePaths");
31
+ const because = worst !== "in-place" && Array.isArray(paths) ? paths.filter((p) => typeof p === "string") : [];
32
+ return {
33
+ disruption: worst,
34
+ ...(because.length > 0 ? { because } : {}),
35
+ detail: because.length > 0 ? `${DETAIL[worst]}; ${because.join(", ")} forced it` : DETAIL[worst],
36
+ };
37
+ }
38
+ /** `LexiconPlugin.classifyDisruption` for terraform. */
39
+ export function classifyTerraformDisruption(options) {
40
+ const out = {};
41
+ for (const query of options.changes) {
42
+ const verdict = terraformQueryVerdict(query);
43
+ if (verdict)
44
+ out[query.name] = verdict;
45
+ }
46
+ return out;
47
+ }
48
+ /**
49
+ * The queries a `show -json` plan holds: one per `resource_changes[]` entry
50
+ * that changes something existing (an update, a replacement or a delete),
51
+ * named by its address, with the plan's actions and replace paths as the
52
+ * attributes the classifier reads.
53
+ */
54
+ export function terraformDisruptionQueries(plan) {
55
+ const index = indexPlan(plan);
56
+ const out = [];
57
+ const raw = isRecord(plan) && Array.isArray(plan.resource_changes) ? plan.resource_changes.filter(isRecord) : [];
58
+ for (const rc of raw) {
59
+ const address = typeof rc.address === "string" ? rc.address : undefined;
60
+ const change = address ? index.changes.get(address) : undefined;
61
+ if (!address || !change || !terraformActionsDisruption(change.actions))
62
+ continue;
63
+ out.push({
64
+ name: address,
65
+ ...(typeof rc.type === "string" ? { type: rc.type } : {}),
66
+ deltas: [],
67
+ attributes: {
68
+ planActions: { [address]: change.actions },
69
+ ...(change.replacePaths.length > 0 ? { planReplacePaths: change.replacePaths } : {}),
70
+ },
71
+ });
72
+ }
73
+ return out;
74
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Health for a terraform root (#5338), through the provider lexicons.
3
+ *
4
+ * This lexicon reads no provider API. A root's `aws_ecs_service` is the same
5
+ * object the aws lexicon reads as `AWS::ECS::Service`, so `chant lifecycle
6
+ * health` hands it to that reader. What this lexicon adds is the two facts
7
+ * the reader cannot find on its own: which health type the resource is
8
+ * ({@link TERRAFORM_HEALTH_TYPES}), and the id the root's state recorded for
9
+ * it, read by the same state read `describeResources` makes. The aws reader
10
+ * otherwise finds ids through CloudFormation's `describeStackResources`,
11
+ * which knows nothing of a terraform root.
12
+ *
13
+ * A block expanded with `count` or `for_each` is one target per instance,
14
+ * named by its instance node id (`app/aws_ecs_service.api[0]`). A
15
+ * `resource` block of any other type goes in `uncovered`, and core reports it
16
+ * `unknown`: nothing reads whether it is up. Other blocks (variables, data
17
+ * sources, modules) are not resources and are left out.
18
+ */
19
+ import type { HealthReadOptions, HealthTargetsResult } from "@intentius/chant/lexicon";
20
+ import type { DescribeResourcesResult } from "@intentius/chant/lexicon";
21
+ /**
22
+ * Each terraform resource type a provider lexicon reads health for, with
23
+ * that lexicon and its health type. The docs page on health lists the same
24
+ * table.
25
+ */
26
+ export declare const TERRAFORM_HEALTH_TYPES: Readonly<Record<string, {
27
+ lexicon: string;
28
+ type: string;
29
+ }>>;
30
+ /** The read the targets take their ids from: the lexicon's `describeResources`, at the state depth. */
31
+ export type TerraformIdRead = (options: {
32
+ environment: string;
33
+ buildOutput: string;
34
+ entityNames: string[];
35
+ entities: Map<string, {
36
+ entityType: string;
37
+ props: Record<string, unknown>;
38
+ }>;
39
+ depth: "state";
40
+ }) => Promise<DescribeResourcesResult>;
41
+ /** `LexiconPlugin.healthTargets` for terraform. */
42
+ export declare function terraformHealthTargets(options: HealthReadOptions, read?: TerraformIdRead): Promise<HealthTargetsResult>;
@@ -0,0 +1,96 @@
1
+ import { normalizeObservation } from "@intentius/chant/observation";
2
+ import { observedInstanceNodeId } from "@intentius/chant/instance-nodes";
3
+ import { RESOURCE_TYPE } from "./hcl/parse.js";
4
+ /**
5
+ * Each terraform resource type a provider lexicon reads health for, with
6
+ * that lexicon and its health type. The docs page on health lists the same
7
+ * table.
8
+ */
9
+ export const TERRAFORM_HEALTH_TYPES = {
10
+ aws_route53_health_check: { lexicon: "aws", type: "AWS::Route53::HealthCheck" },
11
+ aws_ecs_service: { lexicon: "aws", type: "AWS::ECS::Service" },
12
+ azurerm_container_app: { lexicon: "azure", type: "Microsoft.App/containerApps" },
13
+ google_cloud_run_v2_service: { lexicon: "gcp", type: "GCP::Run::Service" },
14
+ google_cloud_run_service: { lexicon: "gcp", type: "GCP::Run::Service" },
15
+ google_compute_backend_service: { lexicon: "gcp", type: "GCP::Compute::BackendService" },
16
+ google_compute_region_backend_service: { lexicon: "gcp", type: "GCP::Compute::BackendService" },
17
+ google_project_iam_member: { lexicon: "gcp", type: "GCP::Iam::PolicyMember" },
18
+ };
19
+ const defaultRead = async (options) => {
20
+ const { describeResources } = await import("./describe-resources.js");
21
+ return describeResources(options);
22
+ };
23
+ /** The terraform resource type of a declared entity, or undefined for a block that is not a `resource`. */
24
+ function resourceTypeOf(entity) {
25
+ if (entity.entityType !== RESOURCE_TYPE)
26
+ return undefined;
27
+ const type = entity.props.type;
28
+ return typeof type === "string" && type.length > 0 ? type : undefined;
29
+ }
30
+ /** `LexiconPlugin.healthTargets` for terraform. */
31
+ export async function terraformHealthTargets(options, read = defaultRead) {
32
+ const covered = new Map();
33
+ const kinds = new Map();
34
+ const uncovered = {};
35
+ for (const [name, entity] of options.entities) {
36
+ const type = resourceTypeOf(entity);
37
+ if (!type)
38
+ continue;
39
+ if (TERRAFORM_HEALTH_TYPES[type]) {
40
+ covered.set(name, entity);
41
+ kinds.set(name, type);
42
+ }
43
+ else {
44
+ uncovered[name] = type;
45
+ }
46
+ }
47
+ const targets = {};
48
+ const unobserved = {};
49
+ const absent = [];
50
+ if (covered.size === 0)
51
+ return { targets, unobserved, absent, uncovered };
52
+ const observed = normalizeObservation(await read({
53
+ environment: options.environment,
54
+ buildOutput: options.buildOutput,
55
+ entityNames: [...covered.keys()],
56
+ entities: covered,
57
+ depth: "state",
58
+ }));
59
+ for (const [name] of covered) {
60
+ const engineType = kinds.get(name);
61
+ const { lexicon, type } = TERRAFORM_HEALTH_TYPES[engineType];
62
+ const target = (physicalId) => ({ lexicon, type, engineType, physicalId });
63
+ const hole = observed.unobserved[name];
64
+ const present = observed.resources[name];
65
+ if (hole) {
66
+ unobserved[name] = { type, reason: hole.reason, ...(hole.detail ? { detail: hole.detail } : {}) };
67
+ continue;
68
+ }
69
+ if (!present) {
70
+ absent.push(name);
71
+ continue;
72
+ }
73
+ const instances = present.instances ?? [];
74
+ if (instances.length > 0) {
75
+ for (const inst of instances) {
76
+ const id = observedInstanceNodeId(name, inst) ?? `${name}${inst.key ?? ""}`;
77
+ if (inst.verdict === "absent")
78
+ absent.push(id);
79
+ else if (inst.verdict !== "present")
80
+ unobserved[id] = { type, reason: "read-failed", detail: `the state read did not observe ${inst.address}` };
81
+ else if (!inst.physicalId)
82
+ unobserved[id] = { type, reason: "read-failed", detail: `the state records no id for ${inst.address}` };
83
+ else
84
+ targets[id] = target(inst.physicalId);
85
+ }
86
+ continue;
87
+ }
88
+ const address = typeof present.attributes?.address === "string" ? present.attributes.address : undefined;
89
+ if (!present.physicalId || present.physicalId === address) {
90
+ unobserved[name] = { type, reason: "read-failed", detail: `the state records no id for ${address ?? name}` };
91
+ continue;
92
+ }
93
+ targets[name] = target(present.physicalId);
94
+ }
95
+ return { targets, unobserved, absent, uncovered };
96
+ }
package/dist/index.d.ts CHANGED
@@ -27,3 +27,6 @@ export type { TerraformPinRolloutOpConfig, TerraformPinRolloutOpResources } from
27
27
  export { TERRAFORM_STATE_OWNERSHIP_KEYS } from "./state-ownership.js";
28
28
  export { predictTerraformBehaviour, terraformBehaviourRequest, terraformPredictOptionsFrom, TERRAFORM_REFERENCE_CATALOG, type TerraformBehaviourDeps, type TerraformBehaviourEntity, type TerraformBehaviourRequest, type TerraformBehaviourRequestOptions, type TerraformLiveRead, type TerraformPredictOptions, } from "./behaviour/index.js";
29
29
  export { terraformExitOf, terraformPlanMoved, type TerraformExitSource } from "./exit-codes.js";
30
+ export { classifyTerraformDisruption, terraformActionsDisruption, terraformDisruptionQueries, terraformQueryVerdict, } from "./disruption.js";
31
+ export { TERRAFORM_HEALTH_TYPES, terraformHealthTargets } from "./health-targets.js";
32
+ export { TERRAFORM_HEALTH_DISRUPTION_FLOOR, TERRAFORM_OWNERSHIP_ROWS_FLOOR, TERRAFORM_UNDECLARED_NODES_FLOOR } from "./chant-floors.js";
package/dist/index.js CHANGED
@@ -68,3 +68,7 @@ export { TERRAFORM_STATE_OWNERSHIP_KEYS } from "./state-ownership.js";
68
68
  export { predictTerraformBehaviour, terraformBehaviourRequest, terraformPredictOptionsFrom, TERRAFORM_REFERENCE_CATALOG, } from "./behaviour/index.js";
69
69
  // terraform, tofu and choudoufu exit statuses on chant's exit-code table (#4553).
70
70
  export { terraformExitOf, terraformPlanMoved } from "./exit-codes.js";
71
+ // Disruption from a plan's actions and health through the provider lexicons (#5338).
72
+ export { classifyTerraformDisruption, terraformActionsDisruption, terraformDisruptionQueries, terraformQueryVerdict, } from "./disruption.js";
73
+ export { TERRAFORM_HEALTH_TYPES, terraformHealthTargets } from "./health-targets.js";
74
+ export { TERRAFORM_HEALTH_DISRUPTION_FLOOR, TERRAFORM_OWNERSHIP_ROWS_FLOOR, TERRAFORM_UNDECLARED_NODES_FLOOR } from "./chant-floors.js";
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "algorithm": "sha256",
3
3
  "artifacts": {
4
- "manifest.json": "39a2b1c6acb49f2d3a932682b84629bfe416cd4ea1cbf102518cc089620a18b9",
4
+ "manifest.json": "fc84b232595157b0165647cfdd647f27f87553573ca1c5dfcb5bd0479e78ab7a",
5
5
  "meta.json": "ca3d163bab055381827226140568f3bef7eaac187cebd76878e0b63e9e442356",
6
6
  "types/index.d.ts": "022927e6a7b351cc4cf52d5f973f60ccd140e5810e17b32fb8868965aa1db161",
7
7
  "rules/plan-before-apply.ts": "7c10245b2c3335253b48ee7d8b075d89f43116bde20313a5d1031b343fef1282",
@@ -59,5 +59,5 @@
59
59
  "rules/tf047.ts": "bfa86f85c4c5efff297280fc2f15104d6319fa96dfc444a31829fb7353224092",
60
60
  "skills/chant-terraform.md": "53dd11c7b289652f92fdaf2c03766abda46d8964e31fe709e8b142ced4f19c50"
61
61
  },
62
- "composite": "7813cebfde4a31995e566cfd4c2d3cfc5c6838ac56a1889fc13c47b88d8c7096"
62
+ "composite": "4e60447c7d9895d99c42af2a2747a48238694c6438148278f811cadb1ffe27bc"
63
63
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "terraform",
3
- "version": "0.124.102",
3
+ "version": "0.124.103",
4
4
  "chantVersion": ">=0.1.0",
5
5
  "namespace": "Terraform"
6
6
  }
@@ -301,6 +301,12 @@ export interface ChoudoufuLiveLsArgs extends TerraformRootArgs {
301
301
  estate?: string;
302
302
  /** `-consistent`: poll past the Resource Groups Tagging API's eventual-consistency window. */
303
303
  consistent?: boolean;
304
+ /**
305
+ * Pass the root as `DIR` (`.`), so the listing compares the declared
306
+ * instances and prints `gaps[]` (#5402). Without it, `gaps[]` is empty and
307
+ * `gaps_skipped` says no configuration was given.
308
+ */
309
+ compare?: boolean;
304
310
  }
305
311
  export type ChoudoufuLiveCheckArgs = TerraformRootArgs;
306
312
  export interface ChoudoufuAdoptArgs extends TerraformRootArgs {
@@ -663,6 +669,7 @@ export declare function choudoufuLiveLsCommand(opts: {
663
669
  binary: string;
664
670
  estate: string;
665
671
  consistent?: boolean;
672
+ compare?: boolean;
666
673
  }): string;
667
674
  /**
668
675
  * `live-check -json`. No `DIR` argument: the activity already runs in the
@@ -792,6 +799,16 @@ export declare function terraformApply(args: TerraformApplyArgs, signal?: AbortS
792
799
  * asked for the values to hand them on.
793
800
  */
794
801
  export declare function terraformOutputs(args: TerraformRootArgs, signal?: AbortSignal): Promise<Record<string, unknown>>;
802
+ /** `<binary> output -json` in a root, as `{ name: value }`, with the names it marks `sensitive` (#5345). */
803
+ export declare function terraformMarkedOutputs(args: TerraformRootArgs, signal?: AbortSignal): Promise<{
804
+ outputs: Record<string, unknown>;
805
+ sensitive: string[];
806
+ }>;
807
+ /** `output -json`'s document as values and the names it marks `sensitive`. */
808
+ export declare function markedOutputsOf(stdout: string): {
809
+ outputs: Record<string, unknown>;
810
+ sensitive: string[];
811
+ };
795
812
  /**
796
813
  * `live-plan-set -json` over one root, from the project root, so the
797
814
  * document names the root by its path from there, which is what
@@ -320,6 +320,8 @@ export function choudoufuLiveLsCommand(opts) {
320
320
  const parts = [opts.binary, "live-ls", `-estate=${quoteArg(opts.estate)}`, "-json"];
321
321
  if (opts.consistent)
322
322
  parts.push("-consistent");
323
+ if (opts.compare)
324
+ parts.push(".");
323
325
  return parts.join(" ");
324
326
  }
325
327
  /**
@@ -824,6 +826,20 @@ export async function terraformApply(args, signal) {
824
826
  export async function terraformOutputs(args, signal) {
825
827
  return outputsIn(await resolveRoot(args, signal), signal);
826
828
  }
829
+ /** `<binary> output -json` in a root, as `{ name: value }`, with the names it marks `sensitive` (#5345). */
830
+ export async function terraformMarkedOutputs(args, signal) {
831
+ const { binary, root, dir } = await resolveRoot(args, signal);
832
+ const { stdout } = await run(`${binary} output -json`, dir, terraformEnvironment(root), signal);
833
+ return markedOutputsOf(stdout);
834
+ }
835
+ /** `output -json`'s document as values and the names it marks `sensitive`. */
836
+ export function markedOutputsOf(stdout) {
837
+ const parsed = JSON.parse(stdout || "{}");
838
+ return {
839
+ outputs: Object.fromEntries(Object.entries(parsed).map(([name, entry]) => [name, entry?.value])),
840
+ sensitive: Object.entries(parsed).filter(([, entry]) => entry?.sensitive === true).map(([name]) => name).sort(),
841
+ };
842
+ }
827
843
  /** `<binary> output -json` in a resolved root, as `{ name: value }`. */
828
844
  async function outputsIn({ binary, root, dir }, signal) {
829
845
  const { stdout } = await run(`${binary} output -json`, dir, terraformEnvironment(root), signal);
@@ -1544,10 +1560,11 @@ export async function choudoufuLiveLs(args, signal) {
1544
1560
  const estate = resolveEstate(args, resolved, "choudoufuLiveLs");
1545
1561
  const env = terraformEnvironment(resolved.root);
1546
1562
  const consistent = args.consistent === true;
1547
- const cmd = choudoufuLiveLsCommand({ binary, estate, ...(consistent ? { consistent: true } : {}) });
1563
+ const compare = args.compare === true;
1564
+ const cmd = choudoufuLiveLsCommand({ binary, estate, ...(consistent ? { consistent: true } : {}), ...(compare ? { compare: true } : {}) });
1548
1565
  // Shared with every identical listing in the same read session, the way
1549
1566
  // {@link choudoufuLivePlanDocument} shares the document (chant #2498).
1550
- const key = liveReadKey("live-ls", { root: args.root, dir, binary, estate, consistent, env });
1567
+ const key = liveReadKey("live-ls", { root: args.root, dir, binary, estate, consistent, compare, env });
1551
1568
  const stdout = await memoLiveRead(key, async () => {
1552
1569
  const result = await run(cmd, dir, env, signal);
1553
1570
  report(result.stdout, result.stderr);
package/dist/plugin.js CHANGED
@@ -134,6 +134,26 @@ export const terraformPlugin = {
134
134
  * drift` reaches it through `chant lifecycle drift` in a member's reader
135
135
  * project. See `./drift-read.ts`.
136
136
  */
137
+ /**
138
+ * What applying a planned update costs, from the plan's own actions
139
+ * (#5338): in place, a replacement created first, or a delete first. It
140
+ * answers for a root read at the plan depth, whose blocks carry
141
+ * `planActions`; any other read leaves the update `unknown`. See
142
+ * `./disruption.ts`.
143
+ */
144
+ async classifyDisruption(options) {
145
+ const { classifyTerraformDisruption } = await import("./disruption.js");
146
+ return classifyTerraformDisruption(options);
147
+ },
148
+ /**
149
+ * Health for a root's resources through the provider lexicons (#5338):
150
+ * each covered type mapped to its provider's health type, with the id from
151
+ * the root's state. See `./health-targets.ts`.
152
+ */
153
+ async healthTargets(options) {
154
+ const { terraformHealthTargets } = await import("./health-targets.js");
155
+ return terraformHealthTargets(options);
156
+ },
137
157
  async readDrift(options) {
138
158
  const { readTerraformDrift } = await import("./drift-read.js");
139
159
  return readTerraformDrift(options);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intentius/chant-lexicon-terraform",
3
- "version": "0.124.102",
3
+ "version": "0.124.103",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist/",
@@ -77,7 +77,7 @@
77
77
  "validate": "npx tsx src/validate-cli.ts",
78
78
  "docs": "npx tsx src/codegen/docs-cli.ts",
79
79
  "build": "../../scripts/tsc7.sh -p tsconfig.build.json --sourceMap false && tsc-alias -p tsconfig.build.json && node ../../scripts/copy-lexicon-assets.mjs",
80
- "prepack": "npm run generate && npm run bundle && npm run validate && npm run build",
80
+ "prepack": "npm run generate && npm run bundle && npm run validate && tsx ../../scripts/release-floors.ts --lexicon terraform --pack npm run build",
81
81
  "bundle": "tsx src/package-cli.ts",
82
82
  "module-catalog:refresh": "npx tsx src/module-catalog/refresh-cli.ts"
83
83
  },
@@ -92,7 +92,7 @@
92
92
  "access": "public"
93
93
  },
94
94
  "peerDependencies": {
95
- "@intentius/chant": "^0.124.102",
95
+ "@intentius/chant": "^0.124.110",
96
96
  "zod": "^4.3.6"
97
97
  },
98
98
  "description": "terraform lexicon for chant, existing Terraform root modules as declarable entities",