Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 143 additions & 0 deletions packages/core/src/cli/commands/carve-emit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import { describe, test, expect, vi } from "vitest";
import { mkdtempSync, writeFileSync, rmSync, readFileSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
import { carveEmit, formatCarveEmit } from "./carve-emit";
import { loadHcl2json } from "../../terraform/parse";
import type { ImportResult, LiveImportOptions } from "./import";
import type { LexiconPlugin } from "../../lexicon";

let parserAvailable = false;
try {
await loadHcl2json();
parserAvailable = true;
} catch {
parserAvailable = false;
}

const ESTATE = `
resource "aws_s3_bucket" "assets" {
bucket = "myapp-assets-prod"
}
resource "aws_s3_bucket_versioning" "assets" {
bucket = aws_s3_bucket.assets.id
versioning_configuration { status = "Enabled" }
}
resource "aws_lambda_function" "api" {
function_name = "myapp-api"
environment {
variables = {
ASSETS_BUCKET = aws_s3_bucket.assets.bucket
ASSETS_ARN = aws_s3_bucket.assets.arn
}
}
}
resource "random_pet" "suffix" {
length = 2
}
`;

async function withEstate<T>(fn: (dir: string) => Promise<T>): Promise<T> {
const dir = mkdtempSync(join(tmpdir(), "chant-carve-emit-"));
try {
writeFileSync(join(dir, "main.tf"), ESTATE);
return await fn(dir);
} finally {
rmSync(dir, { recursive: true, force: true });
}
}

const fakeImport = (files: string[] = ["infra/assets.ts"]) =>
vi.fn(
async (_plugins: LexiconPlugin[], _options: LiveImportOptions): Promise<ImportResult> => ({
success: true,
generatedFiles: files,
warnings: [],
lexicon: "aws",
}),
);

const noPlugins: LexiconPlugin[] = [];

describe("carveEmit — validation", () => {
test("requires --from, --select, --env", async () => {
const li = fakeImport();
expect((await carveEmit({}, { plugins: noPlugins, liveImport: li })).error).toContain("--from");
expect((await carveEmit({ from: "/x" }, { plugins: noPlugins, liveImport: li })).error).toContain("--select");
expect(li).not.toHaveBeenCalled();
});
});

describe("carveEmit — emit + boundary", () => {
test("adopts the selected resource with a native selector and reports the boundary", async () => {
if (!parserAvailable) return;
await withEstate(async (dir) => {
const li = fakeImport(["infra/assets.ts"]);
const reportFile = join(dir, "carveout-report.json");
const res = await carveEmit(
{ from: dir, select: "aws_s3_bucket.assets", env: "prod", reportFile },
{ plugins: noPlugins, liveImport: li },
);

expect(res.ok).toBe(true);
// Selector: native type from the tier map, physical name from the HCL.
expect(res.selector).toEqual({ type: "AWS::S3::Bucket", name: "myapp-assets-prod" });
expect(li).toHaveBeenCalledOnce();
expect(li.mock.calls[0][1]).toMatchObject({
environment: "prod",
selector: { type: "AWS::S3::Bucket", name: "myapp-assets-prod" },
});

// Boundary: one inbound edge from the Lambda; versioning folded away.
expect(res.report!.inbound).toHaveLength(1);
expect(res.report!.inbound[0].survivor).toBe("aws_lambda_function.api");
expect(res.report!.outbound).toHaveLength(0);

// Report written to disk.
const written = JSON.parse(readFileSync(reportFile, "utf-8"));
expect(written.target).toBe("aws_s3_bucket.assets");
expect(written.reversible).toBe(true);
});
});

test("refuses to emit an unsupported type (no native mapping)", async () => {
if (!parserAvailable) return;
await withEstate(async (dir) => {
const li = fakeImport();
const res = await carveEmit(
{ from: dir, select: "random_pet.suffix", env: "prod" },
{ plugins: noPlugins, liveImport: li },
);
expect(res.ok).toBe(false);
expect(res.error).toMatch(/no known native mapping/i);
expect(li).not.toHaveBeenCalled(); // never adopts something it can't map
});
});

test("errors when the address is not in the estate", async () => {
if (!parserAvailable) return;
await withEstate(async (dir) => {
const res = await carveEmit(
{ from: dir, select: "aws_s3_bucket.nope", env: "prod" },
{ plugins: noPlugins, liveImport: fakeImport() },
);
expect(res.ok).toBe(false);
expect(res.error).toContain("not found");
});
});

test("formatCarveEmit describes the adoption and the pending boundary work", async () => {
if (!parserAvailable) return;
await withEstate(async (dir) => {
const res = await carveEmit(
{ from: dir, select: "aws_s3_bucket.assets", env: "prod" },
{ plugins: noPlugins, liveImport: fakeImport(["infra/assets.ts"]) },
);
const text = formatCarveEmit(res);
expect(text).toContain("observe position, reversible");
expect(text).toContain('AWS::S3::Bucket "myapp-assets-prod"');
expect(text).toContain("inbound");
expect(text).toContain("carve bridge"); // points at the next step
});
});
});
131 changes: 131 additions & 0 deletions packages/core/src/cli/commands/carve-emit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/**
* `chant carve emit` — the first strangler-fig emit step (#197).
*
* Given a resource selected from a Terraform estate, it:
* 1. classifies the boundary (which edges the carve cuts),
* 2. adopts the live resource into typed chant source via live import
* (`chant import --from <env>` machinery — cloud→code, read-only export),
* 3. writes a boundary report.
*
* It does not patch the surviving Terraform or apply anything — that is the
* boundary-bridging and apply-graduation work (later PRs). This lands the
* resource at the observe position: emitted, reversible, nothing mutated.
*/

import { existsSync, statSync, writeFileSync } from "fs";
import { parseTerraformDir, Hcl2JsonNotInstalled } from "../../terraform/parse";
import { boundaryReport, type CarveReport } from "../../terraform/carve";
import { resolveTier } from "../../terraform/tier-map";
import type { LexiconPlugin, ResourceSelector } from "../../lexicon";
import type { ImportResult, LiveImportOptions } from "./import";

export interface CarveEmitOptions {
/** Terraform estate directory (`--from`). */
from?: string;
/** Terraform address to carve, e.g. `aws_s3_bucket.assets` (`--select`). */
select?: string;
/** Live environment to adopt from (`--env`). */
env?: string;
/** Opt-in `.tfstate` for instance counts (`--state`). */
statePath?: string;
/** Output directory for the emitted source (`--output`). */
output?: string;
/** Write the boundary report JSON here (`--report`). */
reportFile?: string;
}

/** Injected so tests exercise emit without cloud calls. */
export interface CarveEmitDeps {
plugins: LexiconPlugin[];
liveImport: (plugins: LexiconPlugin[], options: LiveImportOptions) => Promise<ImportResult>;
}

export interface CarveEmitResult {
ok: boolean;
error?: string;
report?: CarveReport;
emit?: ImportResult;
/** The selector used for the live adoption, for transparency. */
selector?: ResourceSelector;
}

export async function carveEmit(opts: CarveEmitOptions, deps: CarveEmitDeps): Promise<CarveEmitResult> {
if (!opts.from) return { ok: false, error: "chant carve emit requires --from <terraform-dir>" };
if (!opts.select) return { ok: false, error: "chant carve emit requires --select <tf-address>" };
if (!opts.env) return { ok: false, error: "chant carve emit requires --env <environment> to adopt the live resource" };
if (!existsSync(opts.from) || !statSync(opts.from).isDirectory()) {
return { ok: false, error: `Not a directory: ${opts.from}` };
}

let report: CarveReport | null;
let identity: string | undefined;
let tfType: string | undefined;
try {
const graph = await parseTerraformDir(opts.from, { statePath: opts.statePath });
report = boundaryReport(graph, opts.select);
const node = graph.nodes.find((n) => n.address === opts.select);
identity = node?.identity;
tfType = node?.type;
} catch (err) {
if (err instanceof Hcl2JsonNotInstalled) return { ok: false, error: err.message };
return { ok: false, error: `Failed to parse Terraform in ${opts.from}: ${err instanceof Error ? err.message : String(err)}` };
}

if (!report) return { ok: false, error: `${opts.select} not found in ${opts.from}` };

const tier = tfType ? resolveTier(tfType) : null;
if (!tier) {
return {
ok: false,
error: `${opts.select} (${tfType ?? "unknown type"}) has no known native mapping, so it cannot be emitted. Advisor bands it "leave in Terraform".`,
};
}

// Build the live-import selector: native type from the tier map, physical
// name from the HCL identity attribute (falling back to the TF logical name).
const name = identity ?? opts.select!.split(".").slice(1).join(".");
const selector: ResourceSelector = { type: tier.mapsTo, name };

const emit = await deps.liveImport(deps.plugins, {
environment: opts.env,
selector,
output: opts.output,
lexicon: tier.mapsTo.split("::")[0]?.toLowerCase() === "aws" ? "aws" : undefined,
});

if (opts.reportFile) writeFileSync(opts.reportFile, JSON.stringify(report, null, 2));

return { ok: true, report, emit, selector };
}

/** Human-readable emit summary: what was adopted and what boundary work remains. */
export function formatCarveEmit(result: CarveEmitResult): string {
if (!result.ok || !result.report) return result.error ?? "carve emit failed";
const r = result.report;
const lines: string[] = [];
lines.push(`Carved ${r.target} (peelability ${r.peelability}) — observe position, reversible.`);
if (result.selector) lines.push(` Adopted live as ${result.selector.type} "${result.selector.name}".`);
if (result.emit?.generatedFiles?.length) {
lines.push(` Emitted: ${result.emit.generatedFiles.join(", ")}`);
}
if (r.carveSet.length > 1) {
const folded = r.carveSet.filter((m) => m.foldedInto).map((m) => m.address);
lines.push(` Folded in: ${folded.join(", ")}`);
}
lines.push("");
lines.push("Boundary (not yet patched — that is `carve bridge`, the next step):");
if (r.inbound.length === 0 && r.outbound.length === 0) {
lines.push(" none — a clean leaf, nothing depends on it and it depends on nothing.");
}
for (const e of r.inbound) {
lines.push(` inbound ${e.survivor} reads ${e.attrs.join(", ")} → rewrite to a data source (required immediately)`);
}
for (const e of r.outbound) {
lines.push(` outbound ${e.carved} reads ${e.survivor}.${e.attrs.join(", ")} → deferred deploy-time input (at apply)`);
}
if (r.diagnostics.length) {
lines.push("");
for (const d of r.diagnostics) lines.push(` ! ${d}`);
}
return lines.join("\n");
}
38 changes: 38 additions & 0 deletions packages/core/src/cli/handlers/carve-emit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { carveEmit, formatCarveEmit } from "../commands/carve-emit";
import { liveImportFromPlugins } from "../commands/import";
import { formatError } from "../format";
import type { CommandContext } from "../registry";

/**
* `chant carve emit --from <tf-dir> --select <address> --env <env> [--output <dir>] [--report <path>]`
*
* Adopts the selected Terraform resource into typed chant source (cloud→code
* live import) and reports its boundary. Requires the target lexicon's plugins
* (loaded from the project) for the live export.
*/
export async function runCarveEmit(ctx: CommandContext): Promise<number> {
const { args, plugins } = ctx;

const result = await carveEmit(
{
from: args.migrateFrom, // `--from <terraform-dir>`
select: args.selectAddress, // `--select <tf-address>`
env: args.env,
statePath: args.statePath,
output: args.output,
reportFile: args.reportFile,
},
{ plugins, liveImport: liveImportFromPlugins },
);

if (!result.ok) {
console.error(formatError({
message: result.error ?? "carve emit failed",
hint: "chant carve emit --from ./tf --select aws_s3_bucket.assets --env prod",
}));
return 1;
}

console.log(formatCarveEmit(result));
return 0;
}
10 changes: 10 additions & 0 deletions packages/core/src/cli/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { runList, runDescribe, runImport, runAudit, runUpdate, runDoctor } from
import { runVendor } from "./handlers/vendor";
import { runMigrate } from "./handlers/migrate";
import { runCarveAdvise, runCarveUnknown } from "./handlers/carve";
import { runCarveEmit } from "./handlers/carve-emit";
import { runLifecycleSnapshot, runLifecycleShow, runLifecycleDiff, runLifecycleRollback, runLifecyclePlan, runLifecycleAffected, runLifecycleLog, runLifecycleUnknown } from "./handlers/lifecycle";
import { runComponentsStatus, runComponentsReleaseRecord, runComponentsUnknown } from "./handlers/components";
import { runGraph } from "./handlers/graph";
Expand Down Expand Up @@ -119,6 +120,8 @@ export function parseArgs(args: string[]): ParsedArgs {
result.verbatim = true;
} else if (arg === "--state") {
result.statePath = args[++i];
} else if (arg === "--select") {
result.selectAddress = args[++i];
} else if (arg === "--to") {
result.migrateTo = args[++i];
} else if (arg === "--emit") {
Expand Down Expand Up @@ -252,6 +255,10 @@ Commands:
--from <tf-dir> resources are cheap to carve into native chant
(--json, --report <path>). Emits nothing, changes nothing.
Needs @cdktf/hcl2json (npm install -D @cdktf/hcl2json).
carve emit Adopt a selected TF resource into chant source via live
--from <tf-dir> import (cloud→code) and report its boundary.
--select <addr> Observe position, reversible; patches nothing.
--env <env> (next: carve bridge patches the surviving TF)

Ops:
run <name> Start an Op workflow (spawns worker + submits to Temporal)
Expand Down Expand Up @@ -438,6 +445,9 @@ const registry: CommandDef[] = [
// Read-only Terraform peelability advisor (#214). Compound so "advise" lands
// in args.path; the estate dir comes from --from. No plugins, no project.
{ name: "carve advise", handler: runCarveAdvise },
// Emit step (#197): adopt a selected TF resource into chant source via live
// import. Needs the target lexicon's plugins for the cloud→code export.
{ name: "carve emit", requiresPlugins: true, handler: runCarveEmit },
{ name: "init", handler: runInit },
{ name: "init lexicon", handler: runInitLexicon },
{ name: "update", handler: runUpdate },
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/cli/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ export interface ParsedArgs {
migrateFrom?: string;
/** `chant carve advise --state <path>` — opt-in .tfstate for accurate instance counts */
statePath?: string;
/** `chant carve emit --select <tf-address>` — the Terraform resource to carve */
selectAddress?: string;
/** `chant migrate --to <name>` (default "gitlab") */
migrateTo?: string;
/** `chant migrate --emit yaml|ts` */
Expand Down
Loading