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
1 change: 1 addition & 0 deletions docs/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ export default defineConfig({
{ label: 'vendor', slug: 'cli/vendor' },
{ label: 'import', slug: 'cli/import' },
{ label: 'carve advise', slug: 'cli/carve' },
{ label: 'carve out (emit/bridge/apply)', slug: 'cli/carve-out' },
{ label: 'audit', slug: 'cli/audit' },
{ label: 'update', slug: 'cli/update' },
{ label: 'doctor', slug: 'cli/doctor' },
Expand Down
83 changes: 83 additions & 0 deletions docs/src/content/docs/cli/carve-out.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
---
title: "chant carve (emit / bridge / apply)"
description: Incrementally carve a resource out of Terraform into native chant — emit, bridge the boundary, graduate to apply
---

## Synopsis

```
chant carve emit --from <tf-dir> --select <address> --env <env>
chant carve bridge --from <tf-dir> --select <address> [--apply-rewrites]
chant carve apply --from <tf-dir> --select <address> --env <env> [--write]
```

## Description

The carve commands peel a resource out of a Terraform estate into native chant source — incrementally, never the whole estate. The long tail stays in Terraform; "we can't map this" becomes "leave it where it is," not a failure. Start with [`chant carve advise`](/chant/cli/carve/) to see what is cheap to carve.

A carve never destroys or recreates. It reuses the adopt-an-orphan loop: Terraform stops managing the resource, chant adopts the still-live resource, and you sit at the observe position until you turn the dial to apply. Every step before graduation is reversible with `terraform import`.

The flow is three steps.

### 1. `carve emit` — adopt into chant source

Adopts the selected live resource into typed chant source via the cloud→code live-import path, and reports the boundary — every dependency edge the carve would cut.

```
chant carve emit --from ./infra --select aws_s3_bucket.assets --env prod
```

It refuses to emit a resource with no native mapping (the advisor bands those "leave in Terraform"). Nothing is patched or applied; the resource lands at the observe position.

### 2. `carve bridge` — patch the survivors

Generates the edits to the Terraform you leave behind so its plan stays valid once the resource is chant-owned.

- **Inbound edges** (a survivor reads the carved resource) become a `data` source plus rewired references. Required immediately, or `terraform plan` errors on the dangling reference.
- **Outbound edges** (the carved resource read a survivor) become deferred deploy-time inputs, wired at apply.

```
chant carve bridge --from ./infra --select aws_s3_bucket.assets
```

Safe by default: it writes the proposed data sources, rewritten survivor files, and a runbook to an output directory for review. `--apply-rewrites` edits the survivor `.tf` in place. The rewrite is idempotent and never touches the carved resource's own declaration.

### 3. `carve apply` — graduate

Resolves the ownership marker that makes the resource chant-owned and finalizes the ordered apply runbook.

```
chant carve apply --from ./infra --select aws_s3_bucket.assets --env prod --stack assets
```

This is BYOL-honest: it makes no cloud call. It computes the marker and the plan; the apply itself is whatever lifecycle you brought — the native CLI, a CI pipeline, an ApplyOp — and it stamps the ownership marker the emitted source carries. `--write` saves the graduation doc.

## The handoff, end to end

```
# 1. see what's cheap to carve
chant carve advise --from ./infra

# 2. adopt the bucket into chant source, see its boundary
chant carve emit --from ./infra --select aws_s3_bucket.assets --env prod

# 3. Terraform stops managing it (does NOT destroy it)
terraform state rm aws_s3_bucket.assets

# 4. patch the survivors so their plan stays valid
chant carve bridge --from ./infra --select aws_s3_bucket.assets --apply-rewrites
terraform plan && terraform apply

# 5. graduate: mark it chant-owned, then apply with your lifecycle
chant carve apply --from ./infra --select aws_s3_bucket.assets --env prod --write
```

At every step before 5, rollback is `terraform import aws_s3_bucket.assets <id>`.

## Scope

These are the emit, boundary-bridging, and apply-graduation phases of the strangler-fig design (#197), built on the read-only advisor (#214). Emit targets a Declarable (a single native resource); a whole service with a deploy pipeline is a Component, not a leaf carve. Removing the carved resource's own block from the `.tf` is a runbook step, not an automatic edit — the parser has no source spans to excise a block precisely.

:::caution
`carve bridge --apply-rewrites` edits your Terraform in place, and `terraform state rm` / `terraform apply` change what Terraform manages. Review the generated proposals and the runbook before running them. The carve is reversible via `terraform import` up until apply graduation.
:::
82 changes: 82 additions & 0 deletions packages/core/src/cli/commands/carve-apply.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { describe, test, expect } from "vitest";
import { mkdtempSync, writeFileSync, rmSync, readFileSync, existsSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
import { carveApply, formatCarveApply } from "./carve-apply";
import { loadHcl2json } from "../../terraform/parse";

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

const ESTATE = `
resource "aws_s3_bucket" "assets" { bucket = "myapp-assets-prod" }
resource "aws_lambda_function" "api" {
environment { variables = { B = aws_s3_bucket.assets.bucket } }
}
`;

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

describe("carveApply", () => {
test("requires --from and --select", async () => {
expect((await carveApply({})).error).toContain("--from");
expect((await carveApply({ from: "/x" })).error).toContain("--select");
});

test("plans graduation with ownership marker; writes nothing by default", async () => {
if (!parserAvailable) return;
await withEstate(async (dir) => {
const res = await carveApply({ from: dir, select: "aws_s3_bucket.assets", env: "prod", stack: "assets" });
expect(res.ok).toBe(true);
expect(res.written).toBeUndefined();
expect(res.plan!.ownershipTags["chant:managed-by"]).toBe("chant");
expect(res.plan!.marker).toEqual({ stack: "assets", env: "prod" });

const text = formatCarveApply(res);
expect(text).toContain("observe → apply");
expect(text).toContain("no cloud call");
});
});

test("--write emits the graduation doc", async () => {
if (!parserAvailable) return;
await withEstate(async (dir) => {
const out = join(dir, "carveout");
const res = await carveApply({
from: dir,
select: "aws_s3_bucket.assets",
env: "prod",
output: out,
write: true,
});
expect(res.ok).toBe(true);
expect(res.written).toBe(join(out, "aws_s3_bucket-assets-graduation.md"));
expect(existsSync(res.written!)).toBe(true);
const doc = readFileSync(res.written!, "utf-8");
expect(doc).toContain("# Apply graduation: aws_s3_bucket.assets");
expect(doc).toContain("chant:managed-by = chant");
});
});

test("errors on an unknown target", async () => {
if (!parserAvailable) return;
await withEstate(async (dir) => {
const res = await carveApply({ from: dir, select: "aws_s3_bucket.nope", env: "prod" });
expect(res.ok).toBe(false);
expect(res.error).toContain("not found");
});
});
});
106 changes: 106 additions & 0 deletions packages/core/src/cli/commands/carve-apply.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/**
* `chant carve apply` — apply graduation for the strangler-fig carve (#197).
*
* The dial-turn from observe to apply: resolve the ownership marker that makes
* the carved resource chant-owned and finalize the ordered apply runbook.
*
* BYOL-honest: it does not call the cloud. It computes the marker + graduation
* plan and (with `--write`) emits a graduation doc. The apply is whatever
* lifecycle you brought.
*/

import { existsSync, statSync, mkdirSync, writeFileSync } from "fs";
import { join } from "path";
import { parseTerraformDir, Hcl2JsonNotInstalled } from "../../terraform/parse";
import { boundaryReport } from "../../terraform/carve";
import { graduationPlan, type GraduationPlan } from "../../terraform/graduate";

export interface CarveApplyOptions {
from?: string;
select?: string;
env?: string;
stack?: string;
statePath?: string;
output?: string;
/** Write the graduation doc to the output dir. */
write?: boolean;
}

export interface CarveApplyResult {
ok: boolean;
error?: string;
plan?: GraduationPlan;
written?: string;
}

export async function carveApply(opts: CarveApplyOptions): Promise<CarveApplyResult> {
if (!opts.from) return { ok: false, error: "chant carve apply requires --from <terraform-dir>" };
if (!opts.select) return { ok: false, error: "chant carve apply requires --select <tf-address>" };
if (!existsSync(opts.from) || !statSync(opts.from).isDirectory()) {
return { ok: false, error: `Not a directory: ${opts.from}` };
}

let plan: GraduationPlan;
try {
const graph = await parseTerraformDir(opts.from, { statePath: opts.statePath });
const report = boundaryReport(graph, opts.select);
if (!report) return { ok: false, error: `${opts.select} not found in ${opts.from}` };
plan = graduationPlan(report, { stack: opts.stack, env: opts.env });
} catch (err) {
if (err instanceof Hcl2JsonNotInstalled) return { ok: false, error: err.message };
return { ok: false, error: `Failed to plan graduation: ${err instanceof Error ? err.message : String(err)}` };
}

let written: string | undefined;
if (opts.write) {
const outDir = opts.output ?? join(opts.from, "carveout");
mkdirSync(outDir, { recursive: true });
const slug = opts.select.replace(/[^A-Za-z0-9_]+/g, "-");
written = join(outDir, `${slug}-graduation.md`);
writeFileSync(written, renderGraduationDoc(plan) + "\n");
}

return { ok: true, plan, written };
}

function renderGraduationDoc(plan: GraduationPlan): string {
const L: string[] = [];
L.push(`# Apply graduation: ${plan.target}`);
L.push("");
L.push(`Ownership marker: stack=${plan.marker.stack}${plan.marker.env ? `, env=${plan.marker.env}` : ""}`);
L.push("");
L.push("## Ownership tags (stamped on apply so chant owns the resource)");
for (const [k, v] of Object.entries(plan.ownershipTags)) L.push(`- ${k} = ${v}`);
L.push("");
L.push("## Steps");
for (const s of plan.steps) L.push(s);
if (plan.warnings.length) {
L.push("");
L.push("## Before you apply");
for (const w of plan.warnings) L.push(`- ${w}`);
}
return L.join("\n");
}

export function formatCarveApply(result: CarveApplyResult): string {
if (!result.ok || !result.plan) return result.error ?? "carve apply failed";
const p = result.plan;
const L: string[] = [];
L.push(`Apply graduation for ${p.target} (dial-turn: observe → apply).`);
L.push(` Ownership marker: stack=${p.marker.stack}${p.marker.env ? `, env=${p.marker.env}` : ""}`);
L.push(" Ownership tags (stamped on apply):");
for (const [k, v] of Object.entries(p.ownershipTags)) L.push(` ${k} = ${v}`);
L.push("");
for (const s of p.steps) L.push(` ${s}`);
if (p.warnings.length) {
L.push("");
for (const w of p.warnings) L.push(` ! ${w}`);
}
L.push("");
if (result.written) {
L.push(`Wrote graduation doc: ${result.written}`);
} else {
L.push("Plan only — no cloud call, nothing written. The apply is your lifecycle (BYOL). Add --write to save this as a doc.");
}
return L.join("\n");
}
34 changes: 34 additions & 0 deletions packages/core/src/cli/handlers/carve-apply.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { carveApply, formatCarveApply } from "../commands/carve-apply";
import { formatError } from "../format";
import type { CommandContext } from "../registry";

/**
* `chant carve apply --from <tf-dir> --select <address> --env <env> [--stack <name>] [--write]`
*
* Resolves the ownership marker + graduation runbook. BYOL-honest: no cloud
* calls. `--write` saves the graduation doc. No lexicon plugins needed.
*/
export async function runCarveApply(ctx: CommandContext): Promise<number> {
const { args } = ctx;

const result = await carveApply({
from: args.migrateFrom, // `--from <terraform-dir>`
select: args.selectAddress, // `--select <tf-address>`
env: args.env,
stack: args.carveStack,
statePath: args.statePath,
output: args.output,
write: args.write,
});

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

console.log(formatCarveApply(result));
return 0;
}
12 changes: 12 additions & 0 deletions packages/core/src/cli/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { runMigrate } from "./handlers/migrate";
import { runCarveAdvise, runCarveUnknown } from "./handlers/carve";
import { runCarveEmit } from "./handlers/carve-emit";
import { runCarveBridge } from "./handlers/carve-bridge";
import { runCarveApply } from "./handlers/carve-apply";
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 @@ -125,6 +126,10 @@ export function parseArgs(args: string[]): ParsedArgs {
result.selectAddress = args[++i];
} else if (arg === "--apply-rewrites") {
result.applyRewrites = true;
} else if (arg === "--stack") {
result.carveStack = args[++i];
} else if (arg === "--write") {
result.write = true;
} else if (arg === "--to") {
result.migrateTo = args[++i];
} else if (arg === "--emit") {
Expand Down Expand Up @@ -266,6 +271,10 @@ Commands:
--from <tf-dir> refs) + deferred inputs + reversible runbook.
--select <addr> Writes proposals for review; --apply-rewrites
edits the .tf in place.
carve apply Apply graduation: ownership marker + finalized apply
--from <tf-dir> runbook (dial-turn observe→apply). BYOL —
--select <addr> no cloud call; --write saves the doc.
--env <env>

Ops:
run <name> Start an Op workflow (spawns worker + submits to Temporal)
Expand Down Expand Up @@ -459,6 +468,9 @@ const registry: CommandDef[] = [
// refs) + runbook. No plugins; Terraform-side only. Read-only unless
// --apply-rewrites.
{ name: "carve bridge", handler: runCarveBridge },
// Apply graduation (#197): ownership marker + finalized apply runbook.
// BYOL-honest — no cloud call; --write saves the graduation doc.
{ name: "carve apply", handler: runCarveApply },
{ name: "init", handler: runInit },
{ name: "init lexicon", handler: runInitLexicon },
{ name: "update", handler: runUpdate },
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/cli/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ export interface ParsedArgs {
selectAddress?: string;
/** `chant carve bridge --apply-rewrites` — write rewritten survivor .tf in place */
applyRewrites?: boolean;
/** `chant carve apply --stack <name>` — ownership-marker stack for graduation */
carveStack?: string;
/** `chant carve apply --write` — save the graduation doc */
write?: boolean;
/** `chant migrate --to <name>` (default "gitlab") */
migrateTo?: string;
/** `chant migrate --emit yaml|ts` */
Expand Down
Loading
Loading