@intentius/chant 0.52.1 → 0.53.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.
Files changed (149) hide show
  1. package/dist/agents/checks.d.ts +35 -0
  2. package/dist/agents/checks.d.ts.map +1 -0
  3. package/dist/agents/discover.d.ts +86 -0
  4. package/dist/agents/discover.d.ts.map +1 -0
  5. package/dist/agents/importer.d.ts +46 -0
  6. package/dist/agents/importer.d.ts.map +1 -0
  7. package/dist/agents/index.d.ts +14 -0
  8. package/dist/agents/index.d.ts.map +1 -0
  9. package/dist/agents/types.d.ts +196 -0
  10. package/dist/agents/types.d.ts.map +1 -0
  11. package/dist/audit/catalog.d.ts +4 -1
  12. package/dist/audit/catalog.d.ts.map +1 -1
  13. package/dist/audit/report.d.ts +8 -0
  14. package/dist/audit/report.d.ts.map +1 -1
  15. package/dist/audit/rules-doc.d.ts.map +1 -1
  16. package/dist/cdk/advise.d.ts +29 -0
  17. package/dist/cdk/advise.d.ts.map +1 -0
  18. package/dist/cdk/assembly.d.ts +38 -0
  19. package/dist/cdk/assembly.d.ts.map +1 -0
  20. package/dist/cdk/graph.d.ts +68 -0
  21. package/dist/cdk/graph.d.ts.map +1 -0
  22. package/dist/cdk/tier-map.d.ts +44 -0
  23. package/dist/cdk/tier-map.d.ts.map +1 -0
  24. package/dist/cdk/types.d.ts +114 -0
  25. package/dist/cdk/types.d.ts.map +1 -0
  26. package/dist/cli/commands/audit-agents.d.ts +83 -0
  27. package/dist/cli/commands/audit-agents.d.ts.map +1 -0
  28. package/dist/cli/commands/carve-apply.d.ts.map +1 -1
  29. package/dist/cli/commands/carve-bridge.d.ts.map +1 -1
  30. package/dist/cli/commands/carve-emit.d.ts.map +1 -1
  31. package/dist/cli/commands/carve.d.ts +48 -6
  32. package/dist/cli/commands/carve.d.ts.map +1 -1
  33. package/dist/cli/commands/import-agents.d.ts +64 -0
  34. package/dist/cli/commands/import-agents.d.ts.map +1 -0
  35. package/dist/cli/handlers/carve-emit.d.ts.map +1 -1
  36. package/dist/cli/handlers/carve.d.ts +5 -4
  37. package/dist/cli/handlers/carve.d.ts.map +1 -1
  38. package/dist/cli/handlers/lifecycle.d.ts +10 -0
  39. package/dist/cli/handlers/lifecycle.d.ts.map +1 -1
  40. package/dist/cli/handlers/misc.d.ts.map +1 -1
  41. package/dist/cli/main.d.ts.map +1 -1
  42. package/dist/cli/registry.d.ts +15 -0
  43. package/dist/cli/registry.d.ts.map +1 -1
  44. package/dist/identity.d.ts +196 -0
  45. package/dist/identity.d.ts.map +1 -0
  46. package/dist/index.d.ts +1 -0
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/lexicon.d.ts +52 -0
  49. package/dist/lexicon.d.ts.map +1 -1
  50. package/dist/terraform/adopt-state.d.ts +17 -63
  51. package/dist/terraform/adopt-state.d.ts.map +1 -1
  52. package/dist/terraform/aws-resources.d.ts +1 -1
  53. package/dist/terraform/bridge.d.ts.map +1 -1
  54. package/dist/terraform/carve-provider.d.ts +142 -0
  55. package/dist/terraform/carve-provider.d.ts.map +1 -0
  56. package/dist/terraform/carve.d.ts +36 -3
  57. package/dist/terraform/carve.d.ts.map +1 -1
  58. package/dist/terraform/emit-source.d.ts +25 -0
  59. package/dist/terraform/emit-source.d.ts.map +1 -0
  60. package/dist/terraform/graduate.d.ts +11 -1
  61. package/dist/terraform/graduate.d.ts.map +1 -1
  62. package/dist/terraform/providers/aws.d.ts +19 -0
  63. package/dist/terraform/providers/aws.d.ts.map +1 -0
  64. package/dist/terraform/providers/gcp.d.ts +41 -0
  65. package/dist/terraform/providers/gcp.d.ts.map +1 -0
  66. package/dist/terraform/providers/index.d.ts +15 -0
  67. package/dist/terraform/providers/index.d.ts.map +1 -0
  68. package/dist/terraform/providers/kubernetes.d.ts +29 -0
  69. package/dist/terraform/providers/kubernetes.d.ts.map +1 -0
  70. package/dist/terraform/score.d.ts +70 -4
  71. package/dist/terraform/score.d.ts.map +1 -1
  72. package/dist/terraform/tier-map.d.ts +38 -26
  73. package/dist/terraform/tier-map.d.ts.map +1 -1
  74. package/dist/terraform/types.d.ts +6 -0
  75. package/dist/terraform/types.d.ts.map +1 -1
  76. package/dist/yaml.d.ts.map +1 -1
  77. package/package.json +6 -1
  78. package/src/agents/checks.test.ts +228 -0
  79. package/src/agents/checks.ts +429 -0
  80. package/src/agents/discover.test.ts +310 -0
  81. package/src/agents/discover.ts +939 -0
  82. package/src/agents/importer.ts +49 -0
  83. package/src/agents/index.ts +29 -0
  84. package/src/agents/types.ts +207 -0
  85. package/src/audit/catalog.ts +90 -1
  86. package/src/audit/report.ts +9 -1
  87. package/src/audit/rules-doc.ts +6 -0
  88. package/src/cdk/__fixtures__/cdk.out/AppStack.template.json +171 -0
  89. package/src/cdk/__fixtures__/cdk.out/DataStack.template.json +90 -0
  90. package/src/cdk/__fixtures__/cdk.out/cdk.out +1 -0
  91. package/src/cdk/__fixtures__/cdk.out/manifest.json +30 -0
  92. package/src/cdk/__fixtures__/cdk.out/tree.json +201 -0
  93. package/src/cdk/__fixtures__/cdk.out-dummy/LookupStack.template.json +29 -0
  94. package/src/cdk/__fixtures__/cdk.out-dummy/manifest.json +26 -0
  95. package/src/cdk/advise.test.ts +208 -0
  96. package/src/cdk/advise.ts +44 -0
  97. package/src/cdk/assembly.ts +133 -0
  98. package/src/cdk/graph.test.ts +206 -0
  99. package/src/cdk/graph.ts +525 -0
  100. package/src/cdk/tier-map.ts +71 -0
  101. package/src/cdk/types.ts +115 -0
  102. package/src/cli/commands/audit-agents.test.ts +260 -0
  103. package/src/cli/commands/audit-agents.ts +387 -0
  104. package/src/cli/commands/carve-apply.ts +20 -4
  105. package/src/cli/commands/carve-bridge.test.ts +30 -0
  106. package/src/cli/commands/carve-bridge.ts +24 -2
  107. package/src/cli/commands/carve-emit-k8s.test.ts +262 -0
  108. package/src/cli/commands/carve-emit-provider.test.ts +207 -0
  109. package/src/cli/commands/carve-emit.test.ts +72 -1
  110. package/src/cli/commands/carve-emit.ts +55 -28
  111. package/src/cli/commands/carve.ts +139 -36
  112. package/src/cli/commands/import-agents.test.ts +208 -0
  113. package/src/cli/commands/import-agents.ts +196 -0
  114. package/src/cli/handlers/carve-emit.ts +8 -1
  115. package/src/cli/handlers/carve.ts +8 -7
  116. package/src/cli/handlers/lifecycle.test.ts +187 -1
  117. package/src/cli/handlers/lifecycle.ts +125 -1
  118. package/src/cli/handlers/misc.ts +111 -0
  119. package/src/cli/main.ts +29 -5
  120. package/src/cli/registry.ts +15 -0
  121. package/src/identity.test.ts +199 -0
  122. package/src/identity.ts +346 -0
  123. package/src/index.ts +1 -0
  124. package/src/lexicon.ts +65 -0
  125. package/src/terraform/__fixtures__/gcp-estate/main.tf +60 -0
  126. package/src/terraform/adopt-state.test.ts +131 -0
  127. package/src/terraform/adopt-state.ts +22 -167
  128. package/src/terraform/aws-resources.test.ts +55 -16
  129. package/src/terraform/aws-resources.ts +1 -1
  130. package/src/terraform/bridge.test.ts +12 -0
  131. package/src/terraform/bridge.ts +4 -1
  132. package/src/terraform/carve-provider.test.ts +155 -0
  133. package/src/terraform/carve-provider.ts +237 -0
  134. package/src/terraform/carve.test.ts +55 -1
  135. package/src/terraform/carve.ts +0 -0
  136. package/src/terraform/emit-source.ts +39 -0
  137. package/src/terraform/graduate.test.ts +37 -0
  138. package/src/terraform/graduate.ts +55 -7
  139. package/src/terraform/graph.ts +3 -3
  140. package/src/terraform/providers/aws.ts +169 -0
  141. package/src/terraform/providers/gcp.test.ts +228 -0
  142. package/src/terraform/providers/gcp.ts +329 -0
  143. package/src/terraform/providers/index.ts +21 -0
  144. package/src/terraform/providers/kubernetes.ts +224 -0
  145. package/src/terraform/score.ts +111 -25
  146. package/src/terraform/tier-map.ts +55 -90
  147. package/src/terraform/types.ts +6 -0
  148. package/src/yaml.test.ts +54 -0
  149. package/src/yaml.ts +24 -3
@@ -0,0 +1,196 @@
1
+ /**
2
+ * `chant import --agents` — re-express this machine's agent configuration as
3
+ * chant code.
4
+ *
5
+ * Shares its front half with `chant audit --agents` (the same scan, the same
6
+ * normalized sites) and its back half with every other import path (a lexicon's
7
+ * `templateGenerator()` turning IR into TypeScript). The only new step is the
8
+ * middle: `LexiconPlugin.agentConfigImporter()`, which maps sites onto the
9
+ * lexicon's own resource types.
10
+ *
11
+ * The command is loud about what it changed. Re-expression here is lossy in
12
+ * three specific ways — a skipped runtime, a defaulted model, a redacted
13
+ * secret — and each one is something the user would otherwise find only by
14
+ * diffing the generated code against their real config. Printing them is not
15
+ * politeness; it is the difference between generated code you can trust and
16
+ * generated code you have to re-verify by hand.
17
+ */
18
+
19
+ import { existsSync, mkdirSync, writeFileSync } from "fs";
20
+ import { homedir } from "os";
21
+ import { join, resolve } from "path";
22
+ import { scanAgentConfigs } from "../../agents/discover";
23
+ import type { AgentRuntime, AgentScope } from "../../agents/types";
24
+ import type { AgentImportOutcome } from "../../agents/importer";
25
+ import type { LexiconPlugin } from "../../lexicon";
26
+ import { loadPlugin } from "../plugins";
27
+
28
+ /** The lexicon used when `--lexicon` isn't given: the one that models agent workloads. */
29
+ export const DEFAULT_AGENT_LEXICON = "fountain";
30
+
31
+ /**
32
+ * Loads the lexicon plugin. Injectable so this command can be unit-tested
33
+ * without a built lexicon package on disk — the same seam `audit.ts` uses for
34
+ * its `ChecksProvider`.
35
+ */
36
+ export type PluginLoader = (name: string) => Promise<LexiconPlugin>;
37
+
38
+ export interface ImportAgentsOptions {
39
+ /** Lexicon to re-express into. Defaults to {@link DEFAULT_AGENT_LEXICON}. */
40
+ lexicon?: string;
41
+ /** Injectable plugin loader (testing). Defaults to the real one. */
42
+ pluginLoader?: PluginLoader;
43
+ /** Output directory. Defaults to `./infra/agents`. */
44
+ output?: string;
45
+ force?: boolean;
46
+ scopes?: readonly AgentScope[];
47
+ runtimes?: readonly AgentRuntime[];
48
+ projectRoots?: string[];
49
+ home?: string;
50
+ platform?: NodeJS.Platform;
51
+ }
52
+
53
+ export interface ImportAgentsResult {
54
+ success: boolean;
55
+ generatedFiles: string[];
56
+ /** Sites found, mapped, and deliberately not mapped. */
57
+ summary: { discovered: number; mapped: number };
58
+ outcome?: AgentImportOutcome;
59
+ warnings: string[];
60
+ error?: string;
61
+ }
62
+
63
+ /**
64
+ * Scan, re-express, and write.
65
+ *
66
+ * Refuses to overwrite existing files without `--force`, matching `chant
67
+ * import` — generated agent code is likely to be edited by hand after the
68
+ * first run, and silently reverting those edits would be the worst possible
69
+ * behavior for a command whose whole purpose is capturing hand-tuned config.
70
+ */
71
+ export async function importAgentsCommand(opts: ImportAgentsOptions = {}): Promise<ImportAgentsResult> {
72
+ const lexiconName = opts.lexicon ?? DEFAULT_AGENT_LEXICON;
73
+ const outputDir = resolve(opts.output ?? join("infra", "agents"));
74
+ const warnings: string[] = [];
75
+
76
+ const scan = scanAgentConfigs({
77
+ scopes: opts.scopes,
78
+ runtimes: opts.runtimes,
79
+ projectRoots: opts.projectRoots,
80
+ home: opts.home ?? homedir(),
81
+ platform: opts.platform,
82
+ });
83
+
84
+ if (scan.sites.length === 0) {
85
+ return {
86
+ success: false,
87
+ generatedFiles: [],
88
+ summary: { discovered: 0, mapped: 0 },
89
+ warnings,
90
+ error: "No agent configuration found to import.",
91
+ };
92
+ }
93
+
94
+ let plugin: LexiconPlugin;
95
+ try {
96
+ plugin = await (opts.pluginLoader ?? loadPlugin)(lexiconName);
97
+ } catch (err) {
98
+ return {
99
+ success: false,
100
+ generatedFiles: [],
101
+ summary: { discovered: scan.sites.length, mapped: 0 },
102
+ warnings,
103
+ error:
104
+ `Could not load the ${lexiconName} lexicon: ${err instanceof Error ? err.message : String(err)}\n` +
105
+ `Install it with: npm i @intentius/chant-lexicon-${lexiconName}`,
106
+ };
107
+ }
108
+
109
+ const importer = plugin.agentConfigImporter?.();
110
+ if (!importer) {
111
+ return {
112
+ success: false,
113
+ generatedFiles: [],
114
+ summary: { discovered: scan.sites.length, mapped: 0 },
115
+ warnings,
116
+ error: `The ${lexiconName} lexicon cannot express agent configuration (no agentConfigImporter). Try --lexicon ${DEFAULT_AGENT_LEXICON}.`,
117
+ };
118
+ }
119
+
120
+ const generator = plugin.templateGenerator?.();
121
+ if (!generator) {
122
+ return {
123
+ success: false,
124
+ generatedFiles: [],
125
+ summary: { discovered: scan.sites.length, mapped: 0 },
126
+ warnings,
127
+ error: `The ${lexiconName} lexicon has no templateGenerator, so it cannot emit TypeScript.`,
128
+ };
129
+ }
130
+
131
+ const outcome = importer.toTemplateIR(scan.sites);
132
+
133
+ for (const skip of outcome.skipped) warnings.push(`Skipped ${skip.siteId}: ${skip.reason}`);
134
+ if (outcome.unmappedModel.length > 0) {
135
+ warnings.push(
136
+ `No model was pinned in the local config for ${outcome.unmappedModel.join(", ")}; a default was written. Edit it before applying.`,
137
+ );
138
+ }
139
+ if (outcome.redactedSecrets.length > 0) {
140
+ warnings.push(
141
+ `Literal credentials in ${outcome.redactedSecrets.join(", ")} were replaced with \`\${VAR}\` references — the values were NOT copied into the generated code. Supply them via a Vault or the environment.`,
142
+ );
143
+ }
144
+
145
+ if (outcome.ir.resources.length === 0) {
146
+ return {
147
+ success: false,
148
+ generatedFiles: [],
149
+ summary: { discovered: scan.sites.length, mapped: 0 },
150
+ outcome,
151
+ warnings,
152
+ error: `Found ${scan.sites.length} agent config(s), but none could be expressed as ${lexiconName} resources.`,
153
+ };
154
+ }
155
+
156
+ const files = generator.generate(outcome.ir);
157
+
158
+ const existing = files.map((f) => join(outputDir, f.path)).filter((p) => existsSync(p));
159
+ if (existing.length > 0 && !opts.force) {
160
+ return {
161
+ success: false,
162
+ generatedFiles: [],
163
+ summary: { discovered: scan.sites.length, mapped: outcome.ir.resources.length },
164
+ outcome,
165
+ warnings,
166
+ error: `Refusing to overwrite ${existing.join(", ")}. Re-run with --force to replace.`,
167
+ };
168
+ }
169
+
170
+ const generatedFiles: string[] = [];
171
+ try {
172
+ mkdirSync(outputDir, { recursive: true });
173
+ for (const file of files) {
174
+ const full = join(outputDir, file.path);
175
+ writeFileSync(full, file.content, "utf-8");
176
+ generatedFiles.push(full);
177
+ }
178
+ } catch (err) {
179
+ return {
180
+ success: false,
181
+ generatedFiles,
182
+ summary: { discovered: scan.sites.length, mapped: outcome.ir.resources.length },
183
+ outcome,
184
+ warnings,
185
+ error: `Failed to write generated files: ${err instanceof Error ? err.message : String(err)}`,
186
+ };
187
+ }
188
+
189
+ return {
190
+ success: true,
191
+ generatedFiles,
192
+ summary: { discovered: scan.sites.length, mapped: outcome.ir.resources.length },
193
+ outcome,
194
+ warnings,
195
+ };
196
+ }
@@ -1,5 +1,6 @@
1
1
  import { carveEmit, formatCarveEmit } from "../commands/carve-emit";
2
2
  import { liveImportFromPlugins } from "../commands/import";
3
+ import { carveEmitLexicons, resolveEmitProvider } from "../../terraform/carve-provider";
3
4
  import { loadPlugins } from "../plugins";
4
5
  import { formatError } from "../format";
5
6
  import type { CommandContext } from "../registry";
@@ -16,10 +17,16 @@ export async function runCarveEmit(ctx: CommandContext): Promise<number> {
16
17
  const { args } = ctx;
17
18
 
18
19
  // Load plugins only for the live path; the offline --state path needs none.
20
+ // Which lexicon comes from the carve provider seam (#2016), resolved off the
21
+ // selected address's type without parsing the estate — so a second provider
22
+ // needs no edit here. A type no provider emits falls back to every lexicon
23
+ // emit can adopt into, and carveEmit refuses the type properly afterwards.
19
24
  let plugins = ctx.plugins;
20
25
  if (!args.statePath && args.env) {
26
+ const tfType = args.selectAddress?.split(".")[0] ?? "";
27
+ const lexicon = resolveEmitProvider(tfType)?.lexicon;
21
28
  try {
22
- plugins = await loadPlugins(["aws"]);
29
+ plugins = await loadPlugins(lexicon ? [lexicon] : carveEmitLexicons());
23
30
  } catch {
24
31
  // fall through with whatever ctx provided; carveEmit surfaces a clear error
25
32
  }
@@ -3,17 +3,18 @@ import { formatError } from "../format";
3
3
  import type { CommandContext } from "../registry";
4
4
 
5
5
  /**
6
- * `chant carve advise --from <terraform-dir> [--json] [--report <path>]`
6
+ * `chant carve advise --from <terraform-dir | cdk.out> [--json] [--report <path>]`
7
7
  *
8
- * Read-only. Reuses `--from` (shared with migrate/import) for the estate dir.
9
- * Loads no chant project and no lexicon plugins — pure analysis of a foreign
10
- * Terraform tree.
8
+ * Read-only. Reuses `--from` (shared with migrate/import) for the source dir,
9
+ * and works out which source it is by looking at the directory (#1056) rather
10
+ * than adding a second flag. Loads no chant project and no lexicon plugins —
11
+ * pure analysis of a foreign tree.
11
12
  */
12
13
  export async function runCarveAdvise(ctx: CommandContext): Promise<number> {
13
14
  const { args } = ctx;
14
15
 
15
16
  const result = await carveAdvise({
16
- from: args.migrateFrom, // `--from <terraform-dir>`
17
+ from: args.migrateFrom, // `--from <terraform-dir | cdk.out>`
17
18
  statePath: args.statePath, // `--state <tfstate>`
18
19
  reportFile: args.reportFile, // `--report <path>`
19
20
  });
@@ -21,7 +22,7 @@ export async function runCarveAdvise(ctx: CommandContext): Promise<number> {
21
22
  if (!result.ok) {
22
23
  console.error(formatError({
23
24
  message: result.error ?? "carve advise failed",
24
- hint: "chant carve advise --from ./path/to/terraform",
25
+ hint: "chant carve advise --from ./path/to/terraform (or ./cdk.out)",
25
26
  }));
26
27
  return 1;
27
28
  }
@@ -38,7 +39,7 @@ export async function runCarveAdvise(ctx: CommandContext): Promise<number> {
38
39
  export async function runCarveUnknown(_ctx: CommandContext): Promise<number> {
39
40
  console.error(formatError({
40
41
  message: "Unknown carve subcommand",
41
- hint: "chant carve advise --from <terraform-dir> (read-only peelability report)",
42
+ hint: "chant carve advise --from <terraform-dir | cdk.out> (read-only peelability report)",
42
43
  }));
43
44
  return 1;
44
45
  }
@@ -53,7 +53,7 @@ vi.mock("../../config", async () => {
53
53
  };
54
54
  });
55
55
 
56
- const { runLifecycleDiff, runLifecyclePlan, runLifecycleSnapshot, runLifecycleShow, runLifecycleLog, runLifecycleTeardown, runLifecycleUnknown } = await import("./lifecycle");
56
+ const { runLifecycleDiff, runLifecyclePlan, runLifecycleSnapshot, runLifecycleShow, runLifecycleLog, runLifecycleTeardown, runLifecycleWhoami, runLifecycleUnknown } = await import("./lifecycle");
57
57
 
58
58
  function makeArgs(overrides: Partial<ParsedArgs>): ParsedArgs {
59
59
  return {
@@ -1673,3 +1673,189 @@ describe("runLifecycleTeardown (#1222 — plan only)", () => {
1673
1673
  expect(parsed.entries).toHaveLength(1);
1674
1674
  });
1675
1675
  });
1676
+
1677
+ describe("runLifecycleWhoami (#1982)", () => {
1678
+ let stdoutBuf: string[];
1679
+ let stderrBuf: string[];
1680
+
1681
+ beforeEach(() => {
1682
+ stdoutBuf = [];
1683
+ stderrBuf = [];
1684
+ vi.spyOn(console, "log").mockImplementation((s: string) => { stdoutBuf.push(s); });
1685
+ vi.spyOn(console, "error").mockImplementation((s: string) => { stderrBuf.push(s); });
1686
+ loadChantConfigMock.mockReset();
1687
+ loadChantConfigMock.mockResolvedValue({ config: { environments: ["prod"] } });
1688
+ });
1689
+
1690
+ afterEach(() => {
1691
+ vi.restoreAllMocks();
1692
+ delete process.env.AWS_ENDPOINT_URL;
1693
+ });
1694
+
1695
+ function whoamiCtx(plugins: LexiconPlugin[], overrides: Partial<ParsedArgs> = {}) {
1696
+ return {
1697
+ args: makeArgs({ command: "lifecycle", path: "whoami", extraPositional: "prod", ...overrides }),
1698
+ plugins,
1699
+ serializers: plugins.map((p) => p.serializer),
1700
+ };
1701
+ }
1702
+
1703
+ const awsIdentity = createMockPlugin({
1704
+ name: "aws",
1705
+ describeIdentity: async () => ({
1706
+ identity: "arn:aws:sts::491500000000:assumed-role/deploy/ci",
1707
+ scope: "491500000000 us-east-1",
1708
+ source: "env AWS_ACCESS_KEY_ID",
1709
+ endpoint: "https://sts.us-east-1.amazonaws.com/",
1710
+ }),
1711
+ });
1712
+
1713
+ test("missing environment arg → exit 1", async () => {
1714
+ const exit = await runLifecycleWhoami(whoamiCtx([], { extraPositional: undefined }));
1715
+ expect(exit).toBe(1);
1716
+ expect(stderrBuf.join("\n")).toContain("Environment is required");
1717
+ });
1718
+
1719
+ test("environment not in config → exit 1", async () => {
1720
+ const exit = await runLifecycleWhoami(whoamiCtx([], { extraPositional: "nope" }));
1721
+ expect(exit).toBe(1);
1722
+ expect(stderrBuf.join("\n")).toContain('Unknown environment "nope"');
1723
+ });
1724
+
1725
+ test("one row per configured lexicon, and --json emits the same rows", async () => {
1726
+ const plugins: LexiconPlugin[] = [
1727
+ awsIdentity,
1728
+ createMockPlugin({
1729
+ name: "k8s",
1730
+ describeIdentity: async () => ({ unresolved: { reason: "no-binding", detail: "no context" } }),
1731
+ }),
1732
+ createMockPlugin({ name: "github" }),
1733
+ ];
1734
+
1735
+ expect(await runLifecycleWhoami(whoamiCtx(plugins))).toBe(0);
1736
+ const table = stdoutBuf.join("\n");
1737
+ expect(table).toContain("arn:aws:sts::491500000000:assumed-role/deploy/ci");
1738
+ expect(table).toContain("k8s");
1739
+ expect(table).toContain("github");
1740
+
1741
+ stdoutBuf.length = 0;
1742
+ expect(await runLifecycleWhoami(whoamiCtx(plugins, { json: true }))).toBe(0);
1743
+ const parsed = JSON.parse(stdoutBuf.join("\n")) as {
1744
+ environment: string;
1745
+ identities: Array<{ lexicon: string; status: string; identity?: string; reason?: string }>;
1746
+ };
1747
+ expect(parsed.environment).toBe("prod");
1748
+ expect(parsed.identities.map((r) => [r.lexicon, r.status])).toEqual([
1749
+ ["aws", "reported"],
1750
+ ["k8s", "unresolved"],
1751
+ ["github", "not-reported"],
1752
+ ]);
1753
+ expect(parsed.identities[1].reason).toBe("no-binding");
1754
+ });
1755
+
1756
+ test("a lexicon that implements nothing reads as 'not reported', never an empty identity", async () => {
1757
+ const exit = await runLifecycleWhoami(whoamiCtx([createMockPlugin({ name: "helm" })]));
1758
+ expect(exit).toBe(0);
1759
+ expect(stdoutBuf.join("\n")).toContain("not reported");
1760
+ });
1761
+
1762
+ test("an unresolved identity exits 0 by default and nonzero only under --strict", async () => {
1763
+ const plugins: LexiconPlugin[] = [
1764
+ createMockPlugin({
1765
+ name: "aws",
1766
+ describeIdentity: async () => ({ unresolved: { reason: "no-credentials" } }),
1767
+ }),
1768
+ ];
1769
+ expect(await runLifecycleWhoami(whoamiCtx(plugins))).toBe(0);
1770
+ expect(await runLifecycleWhoami(whoamiCtx(plugins, { strict: true }))).toBe(1);
1771
+ });
1772
+
1773
+ test("--strict does not fail on a lexicon that simply does not implement the capability", async () => {
1774
+ const exit = await runLifecycleWhoami(whoamiCtx([createMockPlugin({ name: "github" })], { strict: true }));
1775
+ expect(exit).toBe(0);
1776
+ });
1777
+
1778
+ test("the positional lexicon filter narrows the report", async () => {
1779
+ const plugins: LexiconPlugin[] = [awsIdentity, createMockPlugin({ name: "k8s" })];
1780
+ expect(await runLifecycleWhoami(whoamiCtx(plugins, { extraPositional2: "aws", json: true }))).toBe(0);
1781
+ const parsed = JSON.parse(stdoutBuf.join("\n")) as { identities: Array<{ lexicon: string }> };
1782
+ expect(parsed.identities.map((r) => r.lexicon)).toEqual(["aws"]);
1783
+ });
1784
+
1785
+ test("an unconfigured lexicon filter → exit 1", async () => {
1786
+ const exit = await runLifecycleWhoami(whoamiCtx([awsIdentity], { extraPositional2: "gcp" }));
1787
+ expect(exit).toBe(1);
1788
+ expect(stderrBuf.join("\n")).toContain('Lexicon "gcp" is not configured');
1789
+ });
1790
+
1791
+ test("the environment's declared endpoint is applied for the identity query, exactly as for a live read", async () => {
1792
+ // #1166 parity: without this, whoami reports the identity of real AWS
1793
+ // while `describeResources` reads the emulator — the wrong-target answer
1794
+ // this command exists to surface.
1795
+ loadChantConfigMock.mockResolvedValue({
1796
+ config: { environments: [{ name: "prod", endpoint: "http://localhost:4566" }] },
1797
+ });
1798
+ let seenEndpoint: string | undefined;
1799
+ const plugins: LexiconPlugin[] = [
1800
+ createMockPlugin({
1801
+ name: "aws",
1802
+ emulator: awsEmulatorStub,
1803
+ describeIdentity: async () => {
1804
+ seenEndpoint = process.env.AWS_ENDPOINT_URL;
1805
+ return { identity: "arn:x", scope: "s", source: "env" };
1806
+ },
1807
+ }),
1808
+ ];
1809
+ expect(await runLifecycleWhoami(whoamiCtx(plugins))).toBe(0);
1810
+ expect(seenEndpoint).toBe("http://localhost:4566");
1811
+ // Restored after the call, so it never leaks into a later invocation.
1812
+ expect(process.env.AWS_ENDPOINT_URL).toBeUndefined();
1813
+ });
1814
+
1815
+ test("a single declared stack region is handed to the lexicon; disagreeing regions are not guessed", async () => {
1816
+ const seen: Array<string | undefined> = [];
1817
+ const plugin = createMockPlugin({
1818
+ name: "aws",
1819
+ describeIdentity: async (options) => {
1820
+ seen.push(options.region);
1821
+ return { identity: "arn:x", scope: "s", source: "env" };
1822
+ },
1823
+ });
1824
+ loadChantConfigMock.mockResolvedValue({
1825
+ config: { environments: ["prod"], stacks: [{ name: "a", src: "src/a", region: "eu-west-1" }] },
1826
+ });
1827
+ await runLifecycleWhoami(whoamiCtx([plugin]));
1828
+ loadChantConfigMock.mockResolvedValue({
1829
+ config: {
1830
+ environments: ["prod"],
1831
+ stacks: [
1832
+ { name: "a", src: "src/a", region: "eu-west-1" },
1833
+ { name: "b", src: "src/b", region: "us-east-1" },
1834
+ ],
1835
+ },
1836
+ });
1837
+ await runLifecycleWhoami(whoamiCtx([plugin]));
1838
+ expect(seen).toEqual(["eu-west-1", undefined]);
1839
+ });
1840
+
1841
+ test("no credential value survives into the rendered rows", async () => {
1842
+ process.env.CHANT_TEST_API_TOKEN = "tok_averyrealtokenvalue";
1843
+ try {
1844
+ const plugins: LexiconPlugin[] = [
1845
+ createMockPlugin({
1846
+ name: "aws",
1847
+ describeIdentity: async () => ({
1848
+ identity: "arn:aws:iam::1:user/ci",
1849
+ scope: "us-east-1",
1850
+ source: "tok_averyrealtokenvalue",
1851
+ }),
1852
+ }),
1853
+ ];
1854
+ expect(await runLifecycleWhoami(whoamiCtx(plugins, { json: true }))).toBe(0);
1855
+ expect(stdoutBuf.join("\n")).not.toContain("tok_averyrealtokenvalue");
1856
+ expect(stdoutBuf.join("\n")).toContain("[redacted]");
1857
+ } finally {
1858
+ delete process.env.CHANT_TEST_API_TOKEN;
1859
+ }
1860
+ });
1861
+ });
@@ -30,6 +30,7 @@ import {
30
30
  type NormalizedObservation,
31
31
  type UnobservedEntity,
32
32
  } from "../../observation";
33
+ import { describeIdentities, identityStatusText, type IdentityRow } from "../../identity";
33
34
  import { discoverComponents } from "../../components/discover";
34
35
  import { cfnDeployStacks } from "./components";
35
36
  import { affectedStacks } from "../../lifecycle/affected";
@@ -1583,13 +1584,136 @@ export async function runLifecycleLog(ctx: CommandContext): Promise<number> {
1583
1584
  return 0;
1584
1585
  }
1585
1586
 
1587
+ /**
1588
+ * The region core hands `describeIdentity` — the one the environment's stacks
1589
+ * declare, when they declare exactly one (#1261's `stacks[].region`).
1590
+ *
1591
+ * Stacks that declare none, or that disagree, resolve to `undefined`, and the
1592
+ * lexicon then resolves the region its own read path would. Guessing one of
1593
+ * several would report a binding half the estate does not use, which is the
1594
+ * failure this command exists to prevent.
1595
+ */
1596
+ function singleDeclaredRegion(targets: readonly StackTarget[]): string | undefined {
1597
+ const regions = new Set(targets.map((t) => t.region).filter((r): r is string => Boolean(r)));
1598
+ return regions.size === 1 ? [...regions][0] : undefined;
1599
+ }
1600
+
1601
+ /**
1602
+ * chant lifecycle whoami <environment> [lexicon] [--json] [--strict]
1603
+ *
1604
+ * Read-only pre-flight (#1982): who chant would act as in each configured
1605
+ * lexicon, and what that principal is scoped to, before it acts. Never
1606
+ * mutates, never gates — `--strict` is the only way this exits non-zero on an
1607
+ * unresolved row, and a lexicon that answers for nothing is reported as such
1608
+ * rather than as an empty identity.
1609
+ */
1610
+ export async function runLifecycleWhoami(ctx: CommandContext): Promise<number> {
1611
+ const { args, plugins } = ctx;
1612
+ const environment = args.extraPositional;
1613
+ const lexiconFilter = args.extraPositional2;
1614
+
1615
+ if (!environment) {
1616
+ console.error(formatError({
1617
+ message: "Environment is required: chant lifecycle whoami <environment> [lexicon] [--json] [--strict]",
1618
+ }));
1619
+ return 1;
1620
+ }
1621
+
1622
+ const projectPath = resolve(".");
1623
+ const { config } = await loadChantConfig(projectPath);
1624
+ const declaredEnvNames = environmentNames(config.environments);
1625
+ if (declaredEnvNames && !matchesDeclaredEnvironment(config.environments, environment)) {
1626
+ console.error(formatError({
1627
+ message: `Unknown environment "${environment}"`,
1628
+ hint: `Defined environments: ${declaredEnvNames.join(", ")}`,
1629
+ }));
1630
+ return 1;
1631
+ }
1632
+
1633
+ const targetPlugins = lexiconFilter ? plugins.filter((p) => p.name === lexiconFilter) : plugins;
1634
+ if (targetPlugins.length === 0) {
1635
+ console.error(formatError({
1636
+ message: `Lexicon "${lexiconFilter}" is not configured for this project`,
1637
+ hint: `Configured: ${plugins.map((p) => p.name).join(", ") || "(none)"}`,
1638
+ }));
1639
+ return 1;
1640
+ }
1641
+
1642
+ // The environment's declared endpoint applies here exactly as it does to a
1643
+ // `--live` read (#1166). Without it whoami would report the identity of real
1644
+ // AWS while `describeResources` reads the emulator — the wrong-target answer
1645
+ // this command exists to make visible.
1646
+ const endpointResult = applyLiveEndpoint(config.environments, environment, targetPlugins);
1647
+ if (endpointResult.notice) console.error(formatWarning({ message: endpointResult.notice }));
1648
+
1649
+ const region = singleDeclaredRegion(resolveStackTargets(args, config));
1650
+ let rows: IdentityRow[];
1651
+ try {
1652
+ rows = await describeIdentities(targetPlugins, {
1653
+ environment,
1654
+ ...(region ? { region } : {}),
1655
+ cwd: projectPath,
1656
+ });
1657
+ } finally {
1658
+ endpointResult.restore();
1659
+ }
1660
+
1661
+ if (args.json) {
1662
+ console.log(JSON.stringify({ environment, identities: rows }, null, 2));
1663
+ } else {
1664
+ printIdentityTable(rows);
1665
+ }
1666
+
1667
+ // Never a gate by default: an unresolved identity is a report, and a
1668
+ // pre-flight command that fails the build has stopped being pre-flight.
1669
+ const unresolved = rows.filter((r) => r.status === "unresolved");
1670
+ if (args.strict && unresolved.length > 0) {
1671
+ console.error(formatError({
1672
+ message: `--strict: ${unresolved.length} lexicon(s) could not resolve an identity: ${unresolved.map((r) => r.lexicon).join(", ")}`,
1673
+ }));
1674
+ return 1;
1675
+ }
1676
+ return 0;
1677
+ }
1678
+
1679
+ function printIdentityTable(rows: IdentityRow[]): void {
1680
+ if (rows.length === 0) {
1681
+ console.error(formatWarning({ message: "No lexicons are configured for this project" }));
1682
+ return;
1683
+ }
1684
+ const width = (pick: (r: IdentityRow) => string): number =>
1685
+ Math.max(...rows.map((r) => pick(r).length));
1686
+ const lexWidth = Math.max(width((r) => r.lexicon), "LEXICON".length);
1687
+ const idWidth = Math.max(width((r) => r.identity ?? identityStatusText(r)), "IDENTITY".length);
1688
+ const scopeWidth = Math.max(width((r) => r.scope ?? ""), "SCOPE".length);
1689
+
1690
+ console.log(
1691
+ "LEXICON".padEnd(lexWidth + 2) + "IDENTITY".padEnd(idWidth + 2) + "SCOPE".padEnd(scopeWidth + 2) + "SOURCE",
1692
+ );
1693
+ for (const row of rows) {
1694
+ const identity = row.status === "reported" ? (row.identity ?? "") : identityStatusText(row);
1695
+ console.log(
1696
+ row.lexicon.padEnd(lexWidth + 2) +
1697
+ identity.padEnd(idWidth + 2) +
1698
+ (row.scope ?? "").padEnd(scopeWidth + 2) +
1699
+ (row.source ?? ""),
1700
+ );
1701
+ }
1702
+ // The resolved address and the reason's detail are both sentences, so they
1703
+ // go under the table rather than widening a column every row pays for.
1704
+ for (const row of rows) {
1705
+ if (row.endpoint) console.error(` ${row.lexicon}: resolved endpoint ${row.endpoint}`);
1706
+ if (row.detail) console.error(` ${row.lexicon}: ${row.detail}`);
1707
+ }
1708
+ }
1709
+
1586
1710
  /**
1587
1711
  * Fallback for unknown state subcommands.
1588
1712
  */
1589
1713
  export async function runLifecycleUnknown(ctx: CommandContext): Promise<number> {
1590
1714
  console.error(formatError({
1591
1715
  message: `Unknown state subcommand: ${ctx.args.extraPositional ?? ctx.args.path}`,
1592
- hint: "Available: chant lifecycle snapshot, chant lifecycle show, chant lifecycle diff, chant lifecycle plan, chant lifecycle teardown, chant lifecycle log",
1716
+ hint: "Available: chant lifecycle snapshot, chant lifecycle show, chant lifecycle diff, chant lifecycle plan, chant lifecycle whoami, chant lifecycle teardown, chant lifecycle log",
1593
1717
  }));
1594
1718
  return 1;
1595
1719
  }