Repository navigation
Description
Pass-three scope decision (critical review). This issue is a large, unscoped bet whose value is adoption, not core-deepening, and it does not fit the umbrella's "deepen-core vs accrete-orchestration" gate cleanly — it is a third thing, a migration tool. Decision: commit only the read-only advisor, now spun out as #214 (cheap, day-one-useful, a viral on-ramp hook). The emit / boundary-bridging / apply-graduation phases below stay here and are gated on the adoption signal #214 produces — not committed up front. Everything past the advisor is design exploration until a real user pulls it.
Summary
A strangler-fig path off Terraform: peel small, cleanly-mappable pieces out of a Terraform estate into native chant artifacts — incrementally, never the whole estate. The long tail (gnarly count/for_each/data-source resources) stays in Terraform indefinitely; "we can't map this" becomes "leave it where it is," not a failure.
The carve-out lands at the observe position on the lifecycle dial by default — reversible, apply-path untouched — and the user turns the dial up to apply when they're ready. This is the BYOL story applied to migration: chant hands you a native artifact + an observe position; it doesn't pick your lifecycle.
Not a Terraform lexicon. Not whole-estate transcompile. A carve-out tool built on the existing adopt-an-orphan loop + the gitlab/src/migrate/from-github tiered-migration precedent.
The unit: a carve-out
Select a slice by Terraform address (aws_s3_bucket.assets, module.cdn). chant produces three things:
- Native chant source for the carved piece — spec-true (
AWS::S3::Bucket, K8s manifests), zero walk-away cost. - A boundary report — every dependency edge the carve cut, classified inbound/outbound, each with a bridge action + provenance.
- A handoff runbook — ordered steps to transfer ownership without touching the live resource.
The mechanic: zero-downtime, observe-first handoff
Carving does not destroy/recreate. It reuses chant's adopt-an-orphan loop with one line prepended:
terraform state rm aws_s3_bucket.assets # TF forgets it; resource stays LIVE
terraform plan # confirm: no destroy
# (patch the surviving TF — see boundary report)
chant import --from prod --name assets # chant adopts the now-orphaned live resource
# apply ownership marker → chant-owned, OBSERVE position
Why this de-risks the scary part:
state rmdoesn't touch the resource.- chant only observes — won't mutate until you turn the dial.
- Sit at observe, confirm
lifecycle diffmatches reality, then move. - Cold feet →
terraform importputs it back. Fully reversible.
The hard part: the boundary (bidirectional)
You must edit the Terraform you're leaving behind, not just emit new chant:
- Inbound edge (surviving TF reads the carved piece): TF loses the reference → patch it to a
datasource. Required immediately. - Outbound edge (carved piece read something in TF): the value must enter chant from outside synthesis → a deploy-time input. Deferred until you turn the dial to apply — at observe, only provenance is recorded.
Advisor scoring model
Now lives in #214 (committed, read-only). Kept here for context; the rest of this issue builds on it.
Before emitting anything, parse .tf + .tfstate, build the graph, and rank every resource/module by peelability (higher = easier). Pure analysis — useful on day one.
score = 100
- 12 * inbound # surviving resources that depend on this → each = a TF data-source patch
- 4 * outbound # this depends on surviving resources → deferred input (cheaper)
- 15 * (tier - 1) # native-spec map: tier1=0, tier2=-15, tier3=-30
- 10 * has_dynamic # count / for_each / data / unresolved interpolation present
- 3 * (instances - 1) # state-expanded instance count
clamp 0..100 (unsupported provider → 0)
Bands:
| Score | Band | Action |
|---|---|---|
| 80–100 | clean leaf | carve now |
| 50–79 | carvable w/ edits | has boundary work |
| 0–49 | leave in Terraform | unmappable or load-bearing |
Example outputs:
aws_s3_bucket.assets— inbound 1, tier 1, no dynamic → 88 (clean leaf)module.cdn(3 tier-1 resources, 2 inbound) → ~64 (carvable w/ edits)aws_vpc.main— inbound 40 → 0 (leave it)
Worked example: carve one bucket a Lambda reads from
Before (Terraform)
resource "aws_s3_bucket" "assets" {
bucket = "myapp-assets-prod"
tags = { Team = "web", Env = "prod" }
}
resource "aws_s3_bucket_versioning" "assets" {
bucket = aws_s3_bucket.assets.id
versioning_configuration { status = "Enabled" }
}
resource "aws_lambda_function" "api" { # stays in Terraform
function_name = "myapp-api"
environment {
variables = {
ASSETS_BUCKET = aws_s3_bucket.assets.bucket # inbound edge
ASSETS_ARN = aws_s3_bucket.assets.arn # inbound edge
}
}
}Emitted chant source (src/assets.ts)
import { Bucket } from "@intentius/chant-lexicon-aws";
// Carved from Terraform: aws_s3_bucket.assets + aws_s3_bucket_versioning.assets
// (TF splits bucket config across sub-resources; CFN inlines them.)
// Adopted live 2026-06-05 — chant-owned via ownership marker.
export const assets = new Bucket({
bucketName: "myapp-assets-prod",
versioningConfiguration: { status: "Enabled" }, // folded in from aws_s3_bucket_versioning
tags: [
{ key: "Team", value: "web" },
{ key: "Env", value: "prod" },
],
});Boundary report (carveout-report.json + summary)
{
"carveSet": [
{ "address": "aws_s3_bucket.assets", "type": "aws_s3_bucket", "tier": 1, "maps_to": "AWS::S3::Bucket" },
{ "address": "aws_s3_bucket_versioning.assets", "type": "aws_s3_bucket_versioning",
"tier": 1, "folded_into": "aws_s3_bucket.assets",
"note": "TF sub-resource inlined as VersioningConfiguration" }
],
"peelability": 88,
"edges": [
{
"direction": "inbound",
"from": "aws_lambda_function.api",
"to": "aws_s3_bucket.assets",
"attrs": ["bucket", "arn"],
"bridge": "tf-data-source",
"required": "immediately",
"patch": "data \"aws_s3_bucket\" \"assets\" { bucket = \"myapp-assets-prod\" }"
}
],
"outbound": [],
"diagnostics": [],
"reversible": true
}Summary — Carving
aws_s3_bucket.assets(peelability 88, clean leaf).
• 2 resources → 1AWS::S3::Bucket(versioning folded in).
• 1 inbound edge fromaws_lambda_function.api(.bucket,.arn) → patch the surviving TF to adatasource (see runbook step 4). Required.
• 0 outbound edges → no deploy-time inputs needed.
• Nocount/for_each/data/dynamic. Fully reversible.
Patch to the surviving Terraform (api.tf)
-resource "aws_s3_bucket" "assets" { ... } # carved to chant
-resource "aws_s3_bucket_versioning" "assets" { ... } # carved to chant
+
+data "aws_s3_bucket" "assets" { # read the now-chant-managed bucket
+ bucket = "myapp-assets-prod"
+}
resource "aws_lambda_function" "api" {
environment {
variables = {
- ASSETS_BUCKET = aws_s3_bucket.assets.bucket
- ASSETS_ARN = aws_s3_bucket.assets.arn
+ ASSETS_BUCKET = data.aws_s3_bucket.assets.bucket
+ ASSETS_ARN = data.aws_s3_bucket.assets.arn
}
}
}Handoff runbook (carveout-runbook.md)
Carve-out: aws_s3_bucket.assets → chant (AWS::S3::Bucket) [observe-first, reversible]
1. Review emitted source
$ cat src/assets.ts
$ chant build src --lexicon aws -o assets.template.json # confirm spec-true output
2. Stop Terraform managing the bucket (does NOT destroy it)
$ terraform state rm aws_s3_bucket.assets aws_s3_bucket_versioning.assets
3. Confirm no destroy + see the broken refs
$ terraform plan
# expect: 0 to destroy. Plan will error on aws_s3_bucket.assets refs → fixed in step 4.
4. Patch the surviving Terraform (inbound edge)
$ git apply api.tf.patch # adds the data source, rewires the Lambda
$ terraform plan # expect: in-place update of aws_lambda_function.api only
$ terraform apply
5. Adopt the live bucket into chant (now an orphan)
$ chant import --from prod --name myapp-assets-prod --output src/ # confirms it matches src/assets.ts
# apply the ownership marker (tag) so chant owns it
6. Sit at OBSERVE — change nothing, verify
$ chant lifecycle diff --live prod # expect: unchanged. Watch for a cycle or two.
7. (LATER, OPTIONAL) turn the dial up when ready
- easy: aws cloudformation deploy --template-file assets.template.json ...
- durable: graduate to ApplyOp
ROLLBACK at any point before step 7:
$ terraform import aws_s3_bucket.assets myapp-assets-prod # back under Terraform
Phasing
Phase 1 (the advisor) is committed and tracked in #214. Phases 2–5 below are gated on the adoption signal #214 produces — design exploration, not commitments.
- Advisor (→ feat: Terraform peelability advisor (read-only carve-out scoring) (DEFERRED) #214, committed) — parse
.tf+.tfstate, build graph, rank peelability. No emit. Useful immediately. - K8s carve-out (gated) —
kubernetes_manifest.*→ native manifests. Near-1:1; exercises select → emit → report → runbook with no cloud-spec mismatch. - AWS Tier-1 leaves (gated) — buckets, log groups, IAM policies; native CFN maps, few edges.
- Boundary bridging (gated) — the bidirectional edit (data-source patch in; deferred inputs out). Where trust is earned.
- Apply graduation (gated) — wire
ApplyOp/ native-CLI as an opt-in step. Only when the user turns the dial.
Open questions
- Read
.tfstateby default? It's what makescount/for_each/datalosslessly carvable (state has the unrolled instances + resolved values), but it turns carve-out from a pure file transform into something that reads a state backend. (First answered in feat: Terraform peelability advisor (read-only carve-out scoring) (DEFERRED) #214 T2 for the advisor.) - Module carve-out → chant composite mapping: how to thread module inputs/outputs across the boundary.
- Where this lives: a shared
@intentius/chant/migrateHCL front-end (one parser, many lexicon targets) vs. per-lexiconmigrate/from-terraform/. (Shared front-end recommended; first exercised by feat: Terraform peelability advisor (read-only carve-out scoring) (DEFERRED) #214.)
Design exploration — phases 2–5 not yet scoped into tasks, and gated on demand. Mirrors the gitlab/src/migrate/from-github tiered/provenance/diagnostics precedent and the existing adopt-an-orphan + observational-lifecycle machinery. Advisor slice committed as #214.
Activity
lex00 commentedon Jun 5, 2026
Design refinements (thread follow-up)
Source corpus — three files, not one. Parse
.tf(structure/intent + graph) +.tfstate(resolved values & unrolledcount/for_eachinstances — the value oracle for carved resources) +.tfvars/*.auto.tfvars/defaults (variable values). Use tfvars to preserve parameterization, not flatten it:var.region→ a chantconst region(value from tfvars), not a hardcoded literal. Gap:TF_VAR_*env and-varCLI aren't always visible → record provenance and prompt.Structure — shared front-end, per-lexicon mappers. A single
.tfspansaws_*/kubernetes_*/google_*→ multiple target lexicons at once, and HCL parsing is provider-agnostic. So:@intentius/chant/migrate: HCL+state+tfvars parser, resource graph, and the advisor (peelability is graph math).<lex>/src/migrate/from-terraform/: type map +tier-1/2/3+provenance.ts+diagnostics.ts— thegitlab/src/migrate/from-github/shape.The CloudFormation objection + resolution. People fled CFN stacks (rollback, ~500-resource limit, slow ops, weak drift), not the CFN resource schema. AWS Cloud Control API speaks that same schema per-resource with no stacks (
cloudcontrol create-resource --type-name AWS::S3::Bucket --desired-state ...; basis of TF'sawsccand Pulumiaws-native), and maps 1:1 to chant's create/update/delete/adopt change-set.ApplyOptargets arecloudformation | kubectl | arm→ AWS apply =aws cloudformation deploy(stacks). Objection is real as-built.cloudcontrolApplyTarget→ carved AWS resources apply per-resource via Cloud Control, the AWS resource model without the stack lifecycle. Advisor folds 'is this Cloud-Control-applyable' into peelability (coverage broad, not 100%).describe) — moot for drift-only adopters.Testbed — Terraform golden examples as a roundtrip oracle + demo source.
terraform-aws-modules/*(realistic, exercises count/for_each/modules → advisor friction cases), provider-doc per-resource examples (Tier-1 fixtures), HashiCorp Learn tutorials (boundary-report fixtures). Demo: advisor score → carve → emitted resource +data-source patch + runbook →terraform planshows 0 to destroy.lex00 commentedon Jun 5, 2026
Terragrunt: state file is the equalizer
Does the parser need to understand Terragrunt, or is the state file enough? State is enough — Terragrunt is not needed for parsing the carve target.
Terragrunt is a wrapper above Terraform (DRY remote-state,
inputs = {},dependencyblocks,generate, run-all). All of it resolves before apply, so by the time state exists it's baked into concrete values + a flat graph. Raw TF, Terragrunt, TF Cloud, Spacelift all emit the same state JSON. The real input isterraform show -json(stable schema), which Terragrunt produces identically (it shells out to terraform) — sidesteps Terragrunt HCL entirely.This reinforces 'read state by default': state isn't only what makes count/for_each losslessly carvable — it's also what makes the tool wrapper-agnostic.
Where Terragrunt re-enters (phase 2, via its CLI, never by re-implementing its HCL):
terragrunt run-all show -json/ per-backend pulls. A find-the-states problem, not an HCL one.dependency.x.outputs.y, so the inbound-edge fix may belong in aterragrunt.hclblock, not a.tfdata source. State gives the value, not which file to edit. Degrade gracefully.Recommendation: v1 consumes
terraform show -json(works under Terragrunt unchanged); never re-implement Terragrunt HCL evaluation; add Terragrunt-aware multi-state aggregation + patch-targeting only if Terragrunt estates are a named audience.lex00 commentedon Jun 5, 2026
Sharpened scope + generalization + prior art (Formae)
Scope: not import, not whole-estate — referenced extraction.
terraform import -generate-config-out, CFN import,pulumi import, Cloud Control get-resource, chant's ownimport --from). Ships today, not novel.state rm, the opposite of import — skip it → two tools assert ownership → next apply destroys/fights), (b) boundary surgery (rewrite the surviving config when the resource has N referrers), (c) the advisor (what's safe to extract).Generalizes via three primitives (read reality · forget-without-destroy · patchable boundary):
terraform state rmpulumi state delete <urn>;aws-native= CFN schemaDeletionPolicy: Retain+ remove (or stack-refactor)Orphan/abandon/retainannotationNot Terraform-specific: a general 'break an IaC ownership boundary into typed no-state native resources, one reversible piece at a time', parameterized by (source adapter) × (target lexicon).
Prior art — Formae (platform.engineering). Open-source IaC that is its own 'always-current model / system of record' via 'continuous discovery', with an 'extract–patch loop' (extract code from running system + 'precise patches at any granularity', 'minimal blast radius', 'runs alongside' existing IaC). This is convergent with the carve-out: extract–patch ≈ carve + boundary patch; always-current model ≈ observational lifecycle; runs-alongside/any-granularity ≈ incremental strangler-fig. So Formae is not a carve source — it's a peer/competitor and an independent arrival at the same thesis. Validates the direction; signals a contested space. Likely differentiator (chant's terms): chant is a pure synthesis compiler — spec-true output, zero walk-away, no system-of-record — vs Formae becoming the model you adopt. (Thin public read; warrants a real eval.)
lex00 commentedon Jun 5, 2026
Adopt Formae's behaviors, not its stance — and they're nearly latent already
Formae's 'extract–patch loop' maps onto chant primitives that already exist, unbundled:
WatchOp(snapshot +lifecycle diff --liveon Temporal schedule)import --from+ carve-outReconcileOp/ApplyOpcloudcontroltargetWatchOp→ on drift →ReconcileOp/ApplyOpin a*.op.tsConclusion: the Formae loop is ~latent in existing Ops. The gap is a named loop composite (WatchOp → Reconcile/Apply) + the
cloudcontrolapply target — packaging, not capability. Adopt the behaviors (continuous discovery, granular minimal-blast-radius patching, extract-from-running, run-alongside); not the stance (becoming the authoritative system of record).Mirror: same gap chant exploits against Terraform — capability exists, nobody assembled the obvious loop. Formae assembled + named it; chant makes you discover you can compose it. Highest-leverage response is shipping the loop as a demoable named composite, not new engineering.
lex00 commentedon Jun 6, 2026
Rev. 2 — after a critical review (red-team)
Three changes that strengthen the design, two bug fixes.
Unit is a chunk, not a node. Carve a cohesive subgraph — a service's security groups, a logging stack — not a single resource. This answers 'why carve at all' (you get a self-contained native capability, not a trivial slice; carving one bucket never relieves state burden since the backend stays for the other 90%) and makes 'strangler-fig' honest (it replaces bounded capabilities, which is what peeling chunks is).
Advisor is min-cut, not magic coefficients. Because the unit is a subgraph, peelability is a real graph property — conductance: low inbound cut, high internal cohesion, coherent mapping. Internal edges are free; only boundary edges count. Candidates seed from Terraform module boundaries (pre-drawn chunks) + community detection. Present as ordinal triage (clean cut / cut-with-bridges / leave), not a 0–100 score. (The earlier weighted formula was theater and even mis-computed its own example.)
Chunk → composite. The natural chant target for a chunk is one composite call. Reassembling N TF resources into one composite isn't a wart — it's what composites are for. Mapper tiers by composite match → flat native → leave-in-place. Caveat: composites relocate the work into pattern recognition, they don't eliminate it.
Bug fix — runbook rebuilt on
removed {}blocks (TF 1.7+). The old 'state rm then patch config' sequence was wrong — config-without-state makesplantry to recreate the resource.removed { from = ... lifecycle { destroy = false } }drops from state without destroying, atomically with the config edit, soplancorrectly reads 0 to destroy, 0 to add.Honesty caveats added. Adoption writes the ownership marker tag = the one adopt-time mutation (the 'never mutates at observe' claim had this hole). Cloud Control
update-resourceis low-blast-radius only for mutable props — createOnly forces replace. Rollback is more thanterraform import(revert removed blocks + restore blocks + import + drop marker). 'No system of record' vs Formae is thin — a continuous WatchOp snapshot branch is arguably a record by another name; needs a real Formae eval.Worked example swapped bucket → a checkout service's security-group set (app SG + db SG + the rule): a textbook clean cut with one internal-free rule, one outbound edge to the surviving VPC (deferred at observe), one inbound edge from a surviving EC2 instance (data-source patch).
lex00 commentedon Jun 6, 2026
Flagship vertical: IAM & security policy
The carve-out's weakest spot was 'why carve one chunk at all.' IAM/policy answers it — a different team (security) owns the concern, the toolchain-coupling actively hurts them, and they have the mandate. The first wedge, and the sharpest.
Ownership boundary is real and mis-drawn. Security owns the policy; the platform team owns the file it's buried in. Every policy change rides the app team's
terraform apply; every review means reading HCL +planagainst a stack security doesn't own → a separation-of-duties violation (a SOC2/PCI audit finding, not a preference). Carving IAM out restores SoD: a typed artifact security owns and reviews in isolation; an app deploy can't silently widen permissions; an IAM review doesn't gate a release.Policy is data → the cleanest possible chunk. Roles, policies, trust docs, KMS/bucket policies are static JSON — almost no count/for_each. Maps clean (
AWS::IAM::Role/Policy, document inline). And state already holds the resolved policy JSON, sidestepping TF'saws_iam_policy_documentdata source. State-first pays off hardest here.Where chant's semantic lint is worth the most. On a Deployment, marginal; on IAM it's the product — least-privilege,
Resource: "*"on sensitive actions,Principal: "*"trust, escalation paths (iam:PassRole+iam:CreatePolicyVersion), confused-deputy (missingaws:SourceArn). Buried in TF none is linted; de-toolchained + typed = a continuous least-privilege gate.Observe-first is security's native posture. They won't let a tool apply IAM day one, but they want continuous drift detection + audit history →
WatchOp+lifecycle diff --live, read-only, zero-risk. Observe alone (drift + lint + audit, no apply) is already worth adopting.Reframe: de-toolchained IAM/policy governance — owned by security, typed, linted for least-privilege, continuously observed — with the chunk carve-out as the lift-and-shift on-ramp. Sharper than 'migrate off Terraform', with a buyer the generic version lacked.
Counterweights. (1) Don't apply IAM yet — the tool that mutates IAM needs
iam:*-class power, a juicy target; defensible position is observe+lint+drift, not apply. (2) Boundary doesn't fully sever — roles are assumed by compute that stays in TF (PassRole) → permanent inbound edge, bridged by adata aws_iam_rolelookup. (3) Adoption is a people problem — pitch is 'the policy JSON you already read + a lint that catches escalation paths + drift', not 'learn TypeScript'. (4) Scope: clean flagship = roles + attached/inline policies + trust in one account; SCPs / permission boundaries / for_each-policy tier behind it.[-]design: strangler-fig carve-out from Terraform (observe-first, incremental)[/-][+]design: strangler-fig carve-out from Terraform (observe-first, incremental) (DEFERRED)[/+]lex00 commentedon Jun 8, 2026
Deferred (2026-06-07). Per project decision, all Terraform features are deferred. The strangler-fig carve-out (and its spun-out advisor slice #214) is parked in full. Design is preserved for when Terraform interop becomes a priority again.
lex00 commentedon Jul 22, 2026
Refresh cross-ref → see #214 comment
Re-verified this design against the repo + everything closed since filing (2026-06-05 → 2026-07-21). Full write-up is on the read-only advisor ticket: #214 (comment). Summary of what changed for this parent design:
chant import/liveImportFromPlugins),chant graph --live(feat(graph): chant graph --live <env> — project provisioned resources into IR nodes #777) with per-lexicon edge reconstruction (feat(graph): reconstruct live edges — per-lexicon reference resolver (AWS first) #778/feat(graph): enrich --live node attributes so edge reconstruction has references to match #784) + containment (feat(graph): live containment/grouping metadata (VPC/subnet boundaries) #779),lifecycle diff --live --json(lifecycle diff --live: emit --json (LiveDiffResult per lexicon) for programmatic consumers #852/lifecycle diff --live --json: include observed resource metadata (status/attributes) #862), snapshot diff (lifecycle: diff two historical snapshots (saved T1 vs saved T2) #822),lifecycle rollbackPR (lifecycle: rollback command — open a PR restoring source to a git revision #873), reconcile cloud→code Ops (feat(loom): observe + reconcile lifecycle Ops (WatchOp drift, ReconcileOp cloud→code) #904), andorphanclassification (lifecycle/live-diff.ts). The observe-first, reversible adopt-an-orphan runbook here is now mostly backed by real primitives rather than sketch.concepts/lifecycle-models.mdxdial page this issue links still exists.Gate unchanged — phases 2–5 stay DEFERRED and gated on the adoption signal #214 would produce; defer-all-Terraform policy stands. Bookkeeping refresh only.
feat(carve): read-only Terraform peelability advisor (#214) (#993)
feat(carve): carve emit — adopt a TF resource + report its boundary (#…
feat(carve): carve bridge — patch the surviving Terraform (#197) (#996)
feat(carve): carve apply — graduation + full carve-out docs (#197) (#997
lex00 commentedon Jul 22, 2026
Emit + boundary bridging + apply graduation shipped
The gated phases are now built and merged (the advisor #214 produced enough signal to proceed). The full strangler-fig carve composes end to end:
advisor (#214, #993) →
carve emit(#995) →carve bridge(#996) →carve apply(#997)Mapping to this issue's phases:
carve bridgegenerates the surviving-TFdatasources + rewired references (inbound) and the deferred deploy-time inputs (outbound), plus the reversible observe-first runbook. Safe by default (proposals to an output dir);--apply-rewritesedits in place.carve applyresolves the ownership marker (chant:managed-by/stack/env) + finalized runbook. BYOL-honest — no cloud call; the apply is your lifecycle, which stamps the marker.carve emitadopts via the cloud→code live-import path and emits a Declarable; proven on the S3-bucket-behind-Lambda worked example.kubernetes_manifestis in the tier map but not yet exercised end-to-end for K8s (emit/bridge are lexicon-agnostic; the K8s path just needs a fixture + proof).Deliberately deferred (follow-ups)
.tf— hcl2json gives no source spans, so block removal is a runbook step, not an automatic edit.Docs:
cli/carve-out.mdxdocuments the full emit → bridge → apply arc.docs(carve): runnable tutorial + example fixture + smoke coverage (#197…
lex00 commentedon Sep 7, 2026
Closing: the gated phases shipped (#993, #995, #996, #997; epic #998 closed) and carve emit, bridge, apply and status are in the tree with docs and an example. The named leftovers have their own tickets: #1000 module to Composite, #2034 kubernetes_manifest bridge, #1008 auto-excise (closed as a known limitation).