@intentius/behold 0.32.0 → 0.33.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.
package/README.md CHANGED
@@ -175,9 +175,20 @@ npx @intentius/behold graph ./infra --changed origin/main...HEAD -o cut.json
175
175
  npx @intentius/behold graph ./infra --around prod/prod/aws_vpc.main --depth 2
176
176
  ```
177
177
 
178
- The same command ships on its own as `@intentius/behold-graph`
179
- (`npx @intentius/behold-graph ./infra`), a smaller install with none of the
180
- server's dependencies; packages/graph/README.md has its budget.
178
+ `npx @intentius/behold graph ./infra` is a lean install. The Kubernetes client
179
+ is an optional peer, so `npm install` does not fetch it;
180
+ see "Optional install" below.
181
+
182
+ ### Optional install: the Kubernetes client
183
+
184
+ `@intentius/chant-k8s-client` (it brings `@kubernetes/client-node`, 63 MB) is an
185
+ optional peer of `@intentius/behold`, so a plain `npm install` does not fetch it.
186
+ It is loaded only to read a kubeconfig: the server's context lookups, the
187
+ kubectl context pills and `behold doctor`. When it is missing those paths stop
188
+ with one line naming it. Install it with `npm i @intentius/chant-k8s-client`.
189
+
190
+ `behold graph` on a Terraform folder, `serve`, `export` and `behold mcp` do not
191
+ need it.
181
192
 
182
193
  ## Export and host: a shareable, interactive snapshot
183
194
 
@@ -612,7 +623,7 @@ reason. [example-carve/README.md](example-carve/README.md) has the estate's full
612
623
  and the offline/`--live` split.
613
624
 
614
625
  behold writes only into `app/carveout/` inside the demo copy it made, and
615
- nothing else. Your Terraform is never edited; see AGENTS.md, "Invariant".
626
+ nothing else. Your Terraform is never edited; see AGENTS.md, "The write boundary".
616
627
 
617
628
  ## Configuration: `.behold.json`
618
629
 
@@ -728,8 +739,8 @@ yourself when you like.
728
739
 
729
740
  ## Layout
730
741
 
731
- A shape rather than a manifest. `src/` is ~85 modules with one concern each, and
732
- [AGENTS.md](./AGENTS.md) is the map that stays current.
742
+ A shape rather than a manifest. `src/` is ~85 modules with one concern each;
743
+ [AGENTS.md](./AGENTS.md) names the rules that hold across them.
733
744
 
734
745
  ```
735
746
  src/
@@ -0,0 +1,117 @@
1
+ import {
2
+ CI_FORGES,
3
+ ChantCliError,
4
+ TRAFFIC_FLOOR,
5
+ applyArgs,
6
+ carveStatus,
7
+ chantBinFrom,
8
+ chantFloor,
9
+ chantPackageFrom,
10
+ ciForgeFor,
11
+ ciPipeline,
12
+ ciPipelineArgs,
13
+ ciWorkflowName,
14
+ classifyChantFailure,
15
+ clusterRootGraphIr,
16
+ compareEnvs,
17
+ compareEnvsArgs,
18
+ componentGraphIr,
19
+ componentGraphLayout,
20
+ componentGraphPath,
21
+ componentStatus,
22
+ componentStatusArgs,
23
+ envOverridesFor,
24
+ graphArgs,
25
+ graphFlags,
26
+ graphIr,
27
+ graphLayout,
28
+ graphPath,
29
+ helmRenderDiffArgs,
30
+ helmRenderDiffLive,
31
+ helmRenders,
32
+ helmRendersArgs,
33
+ isIntentRead,
34
+ isScheduledRead,
35
+ isSearchRead,
36
+ lifecycleDiffArgs,
37
+ lifecycleDiffLive,
38
+ lifecyclePlan,
39
+ lifecyclePlanArgs,
40
+ meetsFloor,
41
+ memberTakesTraffic,
42
+ opRunArgs,
43
+ parseCiPipeline,
44
+ pipeLines,
45
+ pipelineEnvFromYaml,
46
+ readsInFlight,
47
+ resolveChant,
48
+ resolveLexicons,
49
+ runChantRaw,
50
+ runChantStream,
51
+ runCommandStream,
52
+ runEventsArgs,
53
+ sanitizeStackGraph,
54
+ stackGraph,
55
+ stackGraphArgs,
56
+ stripAnsi,
57
+ withLoaderPath
58
+ } from "./chunk-OY4EF7ZO.js";
59
+ import "./chunk-7DQDWJI5.js";
60
+ export {
61
+ CI_FORGES,
62
+ ChantCliError,
63
+ TRAFFIC_FLOOR,
64
+ applyArgs,
65
+ carveStatus,
66
+ chantBinFrom,
67
+ chantFloor,
68
+ chantPackageFrom,
69
+ ciForgeFor,
70
+ ciPipeline,
71
+ ciPipelineArgs,
72
+ ciWorkflowName,
73
+ classifyChantFailure,
74
+ clusterRootGraphIr,
75
+ compareEnvs,
76
+ compareEnvsArgs,
77
+ componentGraphIr,
78
+ componentGraphLayout,
79
+ componentGraphPath,
80
+ componentStatus,
81
+ componentStatusArgs,
82
+ envOverridesFor,
83
+ graphArgs,
84
+ graphFlags,
85
+ graphIr,
86
+ graphLayout,
87
+ graphPath,
88
+ helmRenderDiffArgs,
89
+ helmRenderDiffLive,
90
+ helmRenders,
91
+ helmRendersArgs,
92
+ isIntentRead,
93
+ isScheduledRead,
94
+ isSearchRead,
95
+ lifecycleDiffArgs,
96
+ lifecycleDiffLive,
97
+ lifecyclePlan,
98
+ lifecyclePlanArgs,
99
+ meetsFloor,
100
+ memberTakesTraffic,
101
+ opRunArgs,
102
+ parseCiPipeline,
103
+ pipeLines,
104
+ pipelineEnvFromYaml,
105
+ readsInFlight,
106
+ resolveChant,
107
+ resolveLexicons,
108
+ runChantRaw,
109
+ runChantStream,
110
+ runCommandStream,
111
+ runEventsArgs,
112
+ sanitizeStackGraph,
113
+ stackGraph,
114
+ stackGraphArgs,
115
+ stripAnsi,
116
+ withLoaderPath
117
+ };
@@ -0,0 +1,36 @@
1
+ import {
2
+ LIVE_PLAN_DIR_ENV,
3
+ cacheChoudoufuPlan,
4
+ cachedChoudoufuPlan,
5
+ choudoufuChantArgs,
6
+ choudoufuChantUnavailable,
7
+ choudoufuRootName,
8
+ livePlanDocumentFile,
9
+ planDriftFromIr,
10
+ readChoudoufuThroughChant,
11
+ resetChoudoufuPlanCache,
12
+ rootAnswerOf,
13
+ rootAnswerOfNotes,
14
+ setChoudoufuChantDeps
15
+ } from "./chunk-26K6QLVB.js";
16
+ import "./chunk-4IETG5U7.js";
17
+ import {
18
+ memberSourceStamp
19
+ } from "./chunk-OY4EF7ZO.js";
20
+ import "./chunk-7DQDWJI5.js";
21
+ export {
22
+ LIVE_PLAN_DIR_ENV,
23
+ cacheChoudoufuPlan,
24
+ cachedChoudoufuPlan,
25
+ choudoufuChantArgs,
26
+ choudoufuChantUnavailable,
27
+ choudoufuRootName,
28
+ livePlanDocumentFile,
29
+ memberSourceStamp,
30
+ planDriftFromIr,
31
+ readChoudoufuThroughChant,
32
+ resetChoudoufuPlanCache,
33
+ rootAnswerOf,
34
+ rootAnswerOfNotes,
35
+ setChoudoufuChantDeps
36
+ };
@@ -0,0 +1,157 @@
1
+ import {
2
+ PLAN_READ_ENV,
3
+ TERRAFORM_OBSERVE_ENV,
4
+ hasRootReads,
5
+ rootReadReasonWords,
6
+ rootReadsOf
7
+ } from "./chunk-4IETG5U7.js";
8
+ import {
9
+ CHOUDOUFU_PLAN_CHANT_FLOOR,
10
+ ChoudoufuReadError,
11
+ TERRAFORM_LEXICON_PKG,
12
+ choudoufuSpawnOverride,
13
+ meetsFloor,
14
+ parseLivePlan,
15
+ resolvedVersion,
16
+ stripAnsi,
17
+ terraformReaderState,
18
+ writeTerraformScratchProject
19
+ } from "./chunk-OY4EF7ZO.js";
20
+
21
+ // src/choudoufu-chant-read.ts
22
+ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
23
+ import { tmpdir } from "node:os";
24
+ import { basename, join } from "node:path";
25
+ var LIVE_PLAN_DIR_ENV = "CHANT_TERRAFORM_LIVE_PLAN_DIR";
26
+ var choudoufuChantArgs = () => ["graph", ".", "--live", "--overlay", "--env", PLAN_READ_ENV, "--format", "ir", "--detail", "3"];
27
+ var livePlanDocumentFile = (root) => `${root.replace(/[^A-Za-z0-9._-]/g, "_")}.live-plan.json`;
28
+ var choudoufuRootName = (dir) => basename(dir);
29
+ var depsOverride;
30
+ function setChoudoufuChantDeps(deps) {
31
+ depsOverride = deps;
32
+ }
33
+ async function choudoufuChantUnavailable(deps = depsOverride) {
34
+ if (deps === null) return "no chant to read the plan through";
35
+ const d = deps ?? {};
36
+ const absent = d.readerAbsent ? d.readerAbsent() : terraformReaderState().refusal?.error;
37
+ if (absent) return absent;
38
+ const chant = d.chantVersion ? d.chantVersion() : (await import("./chant-KLLNQOCK.js")).resolveChant().version;
39
+ if (!meetsFloor(chant, CHOUDOUFU_PLAN_CHANT_FLOOR)) return `the plan read on a choudoufu member needs chant ${CHOUDOUFU_PLAN_CHANT_FLOOR} or newer; behold has ${chant ?? "(unknown version)"}`;
40
+ const lexicon = d.lexiconVersion ? d.lexiconVersion() : resolvedVersion(TERRAFORM_LEXICON_PKG);
41
+ if (!meetsFloor(lexicon, CHOUDOUFU_PLAN_CHANT_FLOOR)) return `the plan read on a choudoufu member needs ${TERRAFORM_LEXICON_PKG} ${CHOUDOUFU_PLAN_CHANT_FLOOR} or newer; behold has ${lexicon ?? "(unknown version)"}`;
42
+ return void 0;
43
+ }
44
+ function rootAnswerOf(ir, root, stderr = "") {
45
+ const key = `terraform.roots.${root}`;
46
+ if (!hasRootReads(ir)) return rootAnswerOfNotes(stderr, root);
47
+ const rr = rootReadsOf(ir)[key];
48
+ if (!rr) return { answered: "live" };
49
+ if (rr.depth === "live+plan" && rr.fellBackTo === void 0) return { answered: "live+plan", note: `${key}: the plan read answered, beside live-plan, which answered presence and ownership` };
50
+ const why = rr.reason ? ` (${rootReadReasonWords(rr.reason)})` : "";
51
+ return {
52
+ answered: "live",
53
+ note: rr.fellBackTo === "declared" ? `${key}: no read answered${why}` : `${key}: the ${rr.depth} read failed${why}, so live-plan alone answered; plan attributes are absent`
54
+ };
55
+ }
56
+ function rootAnswerOfNotes(stderr, root) {
57
+ const prefix = `terraform.roots.${root}: `;
58
+ for (const line of stripAnsi(stderr).split("\n")) {
59
+ const at = line.indexOf(prefix);
60
+ if (at === -1) continue;
61
+ const rest = line.slice(at + prefix.length).trim();
62
+ if (rest.startsWith("the plan read answered")) return { answered: "live+plan", note: `${prefix}${rest}` };
63
+ if (rest.startsWith("the plan read failed") || rest.startsWith("no read answered")) return { answered: "live", note: `${prefix}${rest}` };
64
+ }
65
+ return { answered: "live" };
66
+ }
67
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
68
+ function blockAddressOf(n, root) {
69
+ if (!n.id.startsWith(`${root}/`)) return void 0;
70
+ return n.id.slice(root.length + 1).replace(/~\d+$/, "").split("/").join(".");
71
+ }
72
+ var comparable = (actions) => actions.includes("update") || actions.includes("delete") && actions.includes("create");
73
+ function planDriftFromIr(ir, root) {
74
+ const out = /* @__PURE__ */ new Map();
75
+ for (const n of ir.nodes) {
76
+ if (n.kind !== "Terraform::Resource") continue;
77
+ const block = blockAddressOf(n, root);
78
+ const a = n.attrs ?? {};
79
+ if (!block || typeof a.planAction !== "string") continue;
80
+ const actions = isRecord(a.planActions) ? a.planActions : { [block]: [a.planAction] };
81
+ const changes = Array.isArray(a.planChanges) ? a.planChanges : [];
82
+ for (const [instance, acts] of Object.entries(actions)) {
83
+ if (!Array.isArray(acts) || !comparable(acts)) continue;
84
+ const mine = changes.filter((c) => typeof c.path === "string" && (typeof c.instance === "string" ? c.instance : block) === instance).map((c) => ({ path: c.path, oldValue: c.before ?? null, newValue: c.after ?? null }));
85
+ if (mine.length) out.set(instance, { address: instance, actions: acts, changes: mine });
86
+ }
87
+ }
88
+ return out;
89
+ }
90
+ async function readChoudoufuThroughChant(dir, deps = depsOverride ?? void 0) {
91
+ const root = choudoufuRootName(dir);
92
+ const project = writeTerraformScratchProject(dir, { roots: [{ name: root, dir: "." }], skipped: [] }, void 0, "chdf");
93
+ const handed = mkdtempSync(join(tmpdir(), "behold-choudoufu-live-plan-"));
94
+ try {
95
+ const env = { ...choudoufuSpawnOverride() ?? {}, [TERRAFORM_OBSERVE_ENV]: "plan", [LIVE_PLAN_DIR_ENV]: handed };
96
+ const run = deps?.run ?? (async (args, cwd, e) => (await import("./chant-KLLNQOCK.js")).runChantRaw(args, cwd, e));
97
+ const res = await run(choudoufuChantArgs(), project, env);
98
+ let ir;
99
+ try {
100
+ ir = res.code === 0 ? JSON.parse(res.stdout) : void 0;
101
+ } catch {
102
+ ir = void 0;
103
+ }
104
+ const answer = rootAnswerOf(ir, root, res.stderr);
105
+ let text;
106
+ try {
107
+ text = readFileSync(join(handed, livePlanDocumentFile(root)), "utf8");
108
+ } catch {
109
+ const why = answer.note ?? stripAnsi(res.stderr).split("\n").find((l) => /error/i.test(l))?.trim() ?? `chant exited ${res.code} and handed back no live-plan document`;
110
+ throw new ChoudoufuReadError(
111
+ { error: `chant could not read ${dir} live: ${why}`, code: "choudoufu-live-check", remedy: "Give behold the ambient read-only AWS credentials the estate's `live-plan` and `plan` need (AWS_PROFILE, or AWS_ENDPOINT_URL for an emulator), then re-check live with plan." },
112
+ dir
113
+ );
114
+ }
115
+ const parsed = parseLivePlan({ code: 0, stdout: text, stderr: "" }, dir);
116
+ if (!parsed.ok) throw new ChoudoufuReadError(parsed.refusal, dir);
117
+ let drift = /* @__PURE__ */ new Map();
118
+ if (res.code === 0 && !ir) return { plan: parsed.doc, answered: "live", note: `chant printed something that is not a graph for ${dir}; the plan was not read`, drift };
119
+ if (ir && answer.answered === "live+plan") {
120
+ drift = planDriftFromIr(ir, root);
121
+ return { plan: parsed.doc, answered: "live+plan", ...answer.note ? { note: answer.note } : {}, drift };
122
+ }
123
+ return { plan: parsed.doc, answered: "live", ...answer.note ? { note: answer.note } : {}, drift };
124
+ } finally {
125
+ rmSync(handed, { recursive: true, force: true });
126
+ }
127
+ }
128
+ var planCache = /* @__PURE__ */ new Map();
129
+ function resetChoudoufuPlanCache(dir) {
130
+ if (dir === void 0) planCache.clear();
131
+ else planCache.delete(dir);
132
+ }
133
+ function cachedChoudoufuPlan(dir, stamp) {
134
+ if (stamp === void 0) return void 0;
135
+ const hit = planCache.get(dir);
136
+ return hit && hit.stamp === stamp ? hit.drift : void 0;
137
+ }
138
+ function cacheChoudoufuPlan(dir, stamp, drift) {
139
+ if (stamp === void 0) return;
140
+ planCache.set(dir, { stamp, drift });
141
+ }
142
+
143
+ export {
144
+ LIVE_PLAN_DIR_ENV,
145
+ choudoufuChantArgs,
146
+ livePlanDocumentFile,
147
+ choudoufuRootName,
148
+ setChoudoufuChantDeps,
149
+ choudoufuChantUnavailable,
150
+ rootAnswerOf,
151
+ rootAnswerOfNotes,
152
+ planDriftFromIr,
153
+ readChoudoufuThroughChant,
154
+ resetChoudoufuPlanCache,
155
+ cachedChoudoufuPlan,
156
+ cacheChoudoufuPlan
157
+ };
@@ -0,0 +1,267 @@
1
+ import {
2
+ TERRAFORM_LEXICON,
3
+ TERRAFORM_LEXICON_PKG,
4
+ floorFor,
5
+ floorMet,
6
+ floorRefusal,
7
+ graphIr,
8
+ invalidateReadGeneration,
9
+ memberSourceStamp,
10
+ resolveChant,
11
+ resolvedVersion,
12
+ stripAnsi,
13
+ terraformMemberScan,
14
+ terraformReaderState,
15
+ writeTerraformScratchProject
16
+ } from "./chunk-OY4EF7ZO.js";
17
+
18
+ // src/terraform-plan.ts
19
+ var TERRAFORM_PLAN_READ = "plan read on a Terraform root";
20
+ var TERRAFORM_OBSERVE_ENV = "CHANT_TERRAFORM_OBSERVE";
21
+ var PLAN_READ_ENV = "behold-plan";
22
+ var terraformPlanArgs = () => ["graph", ".", "--live", "--overlay", "--env", PLAN_READ_ENV, "--format", "ir", "--detail", "3"];
23
+ function rootReadsOf(ir) {
24
+ const reads = ir?.rootReads;
25
+ if (!reads || typeof reads !== "object" || Array.isArray(reads)) return {};
26
+ const out = {};
27
+ for (const [key, v] of Object.entries(reads)) {
28
+ if (!v || typeof v !== "object" || typeof v.depth !== "string") continue;
29
+ out[key] = v;
30
+ }
31
+ return out;
32
+ }
33
+ function hasRootReads(ir) {
34
+ const reads = ir?.rootReads;
35
+ return !!reads && typeof reads === "object" && !Array.isArray(reads);
36
+ }
37
+ var NOTE = /terraform\.roots\.([^:\s]+): (.*)$/;
38
+ function parsePlanNotes(stderr) {
39
+ const out = /* @__PURE__ */ new Map();
40
+ for (const line of stripAnsi(stderr).split("\n")) {
41
+ const m = NOTE.exec(line.trim());
42
+ if (!m) continue;
43
+ const [, root, rest] = m;
44
+ const answered = rest.startsWith("the plan read answered") ? "plan" : /so the state read answered/.test(rest) ? "state" : rest.startsWith("no read answered") ? "none" : void 0;
45
+ const reason = answered !== "plan" && /no provider credentials/.test(rest) ? { reason: "no-credentials" } : {};
46
+ if (answered) out.set(root, { root, answered, ...reason, note: `terraform.roots.${root}: ${rest}` });
47
+ }
48
+ return [...out.values()].sort((a, b) => a.root.localeCompare(b.root));
49
+ }
50
+ function rootReadReasonWords(reason) {
51
+ const words = {
52
+ "no-credentials": "no provider credentials",
53
+ "plan-failed": "the plan failed",
54
+ "needs-init": "the root needs init, which chant never runs",
55
+ "backend-unreachable": "the plan read could not reach the backend",
56
+ "state-read-failed": "the state read failed",
57
+ "read-failed": "the read failed"
58
+ };
59
+ return words[reason] ?? reason;
60
+ }
61
+ function planRootAnswers(ir) {
62
+ const out = [];
63
+ for (const [key, rr] of Object.entries(rootReadsOf(ir))) {
64
+ if (!key.startsWith("terraform.roots.")) continue;
65
+ const root = key.slice("terraform.roots.".length);
66
+ const read = rr.fellBackTo ?? rr.depth;
67
+ const answered = read === "plan" ? "plan" : read === "state" ? "state" : "none";
68
+ const why = rr.reason ? ` (${rootReadReasonWords(rr.reason)})` : "";
69
+ const words = rr.fellBackTo === void 0 ? `the ${rr.depth} read answered` : rr.fellBackTo === "declared" ? `no read answered, declared only: the ${rr.depth} read failed${why}` : `the ${rr.depth} read failed${why}, so the ${rr.fellBackTo} read answered`;
70
+ out.push({ root, answered, ...rr.reason ? { reason: rr.reason } : {}, note: `${key}: ${words}` });
71
+ }
72
+ return out.sort((a, b) => a.root.localeCompare(b.root));
73
+ }
74
+ var strings = (v) => Array.isArray(v) && v.every((x) => typeof x === "string") && v.length ? v : void 0;
75
+ var entries = (v) => Array.isArray(v) && v.length ? v : void 0;
76
+ function planFactsOf(node) {
77
+ const a = node.attrs ?? {};
78
+ if (typeof a.planAction !== "string") return void 0;
79
+ const facts = { source: "plan", action: a.planAction };
80
+ if (a.planActions && typeof a.planActions === "object") facts.actions = a.planActions;
81
+ if (typeof a.planActionReason === "string") facts.reason = a.planActionReason;
82
+ const replace = strings(a.planReplacePaths);
83
+ if (replace) facts.replacePaths = replace;
84
+ const unknown = strings(a.planAfterUnknown);
85
+ if (unknown) facts.afterUnknown = unknown;
86
+ const changes = entries(a.planChanges);
87
+ if (changes) facts.changes = changes;
88
+ const drift = entries(a.planDrift);
89
+ if (drift) facts.drift = drift;
90
+ if (typeof a.planDriftAction === "string") facts.driftAction = a.planDriftAction;
91
+ const relevant = strings(a.planRelevantAttributes);
92
+ if (relevant) facts.relevant = relevant;
93
+ return facts;
94
+ }
95
+ var rootOf = (n) => typeof n.attrs?.root === "string" && n.attrs.root ? n.attrs.root : n.id.includes("/") ? n.id.slice(0, n.id.indexOf("/")) : void 0;
96
+ var isBlockWithRows = (n) => n.lexicon === TERRAFORM_LEXICON && (n.kind === "Terraform::Resource" || n.kind === "Terraform::Data");
97
+ var topAttr = (path) => path.split(/[.[]/)[0];
98
+ function forcedFromOf(id, root, paths, edges) {
99
+ const out = [];
100
+ for (const path of paths) {
101
+ for (const e of edges ?? []) {
102
+ const via = e.viaAttr;
103
+ if (e.from !== id || typeof via !== "string" || topAttr(via) !== topAttr(path)) continue;
104
+ const from = root && e.to.startsWith(`${root}/`) ? e.to.slice(root.length + 1) : e.to;
105
+ if (!out.some((o) => o.path === path && o.from === from)) out.push({ path, from });
106
+ }
107
+ }
108
+ return out.length ? out : void 0;
109
+ }
110
+ function terraformPlanReadOf(ir, stderr = "") {
111
+ const roots = hasRootReads(ir) ? planRootAnswers(ir) : parsePlanNotes(stderr);
112
+ const byRoot = new Map(roots.map((r) => [r.root, r]));
113
+ const cards = {};
114
+ for (const n of ir.nodes) {
115
+ if (!isBlockWithRows(n)) continue;
116
+ const root = rootOf(n);
117
+ const answer = root ? byRoot.get(root) : void 0;
118
+ if (answer?.answered === "plan") {
119
+ const facts = planFactsOf(n);
120
+ if (facts) {
121
+ const from = facts.replacePaths ? forcedFromOf(n.id, root, facts.replacePaths, ir.edges ?? []) : void 0;
122
+ cards[n.id] = from ? { ...facts, forcedFrom: from } : facts;
123
+ }
124
+ } else if (answer) {
125
+ cards[n.id] = { source: answer.answered, note: answer.note, ...answer.reason ? { readReason: answer.reason } : {} };
126
+ }
127
+ }
128
+ return { roots, cards };
129
+ }
130
+ function planReadFloorRefusal(chant, lexicon) {
131
+ const f = floorFor(TERRAFORM_PLAN_READ);
132
+ if (!floorMet(f, chant)) return floorRefusal(f, chant);
133
+ if (!floorMet(f, lexicon)) {
134
+ return {
135
+ error: `The ${f.read} needs ${TERRAFORM_LEXICON_PKG} ${f.floor} or newer. behold has ${lexicon ?? "(unknown version)"}.`,
136
+ code: "chant-too-old",
137
+ remedy: `Upgrade ${TERRAFORM_LEXICON_PKG} to ${f.floor} or newer beside behold.`
138
+ };
139
+ }
140
+ return void 0;
141
+ }
142
+ async function readTerraformPlan(dir, deps = {}) {
143
+ const { resolveChant: resolveChant2 } = await import("./chant-KLLNQOCK.js");
144
+ const chant = deps.chantVersion ? deps.chantVersion() : resolveChant2().version;
145
+ const lexicon = deps.lexiconVersion ? deps.lexiconVersion() : resolvedVersion(TERRAFORM_LEXICON_PKG);
146
+ const refusal = planReadFloorRefusal(chant, lexicon);
147
+ if (refusal) return { ok: false, refusal };
148
+ const state = terraformReaderState();
149
+ if (state.refusal) return { ok: false, refusal: state.refusal };
150
+ const { scan, components } = terraformMemberScan(dir);
151
+ if (!scan.roots.length) return { ok: true, read: { roots: [], cards: {} } };
152
+ const project = writeTerraformScratchProject(dir, scan, void 0, "tf", components);
153
+ const env = { ...deps.spawnEnv, [TERRAFORM_OBSERVE_ENV]: "plan" };
154
+ const run = deps.run ?? (async (args, cwd, e) => (await import("./chant-KLLNQOCK.js")).runChantRaw(args, cwd, e));
155
+ const res = await run(terraformPlanArgs(), project, env);
156
+ if (res.code !== 0) {
157
+ const first = stripAnsi(res.stderr).split("\n").find((l) => /error/i.test(l)) ?? `exit ${res.code}`;
158
+ return { ok: false, refusal: { error: `chant could not read the plan for ${dir}: ${first.trim()}`, code: "terraform-plan", remedy: "Run the same read by hand in the scratch project to see chant's whole message." } };
159
+ }
160
+ let ir;
161
+ try {
162
+ ir = JSON.parse(res.stdout);
163
+ } catch {
164
+ return { ok: false, refusal: { error: `chant printed something that is not a graph for ${dir}.`, code: "terraform-plan", remedy: "Check the chant behold runs: `behold doctor`." } };
165
+ }
166
+ return { ok: true, read: terraformPlanReadOf(ir, res.stderr) };
167
+ }
168
+ function paintTerraformPlan(ir, read, member) {
169
+ let painted = 0;
170
+ for (const n of ir.nodes) {
171
+ if (n.lexicon !== TERRAFORM_LEXICON) continue;
172
+ const key = member && n.id.startsWith(`${member}/`) ? n.id.slice(member.length + 1) : n.id;
173
+ const facts = read.cards[key];
174
+ if (!facts) continue;
175
+ n.attrs = { ...n.attrs, _plan: facts };
176
+ painted++;
177
+ }
178
+ return painted;
179
+ }
180
+ function terraformPlanNote(answers) {
181
+ if (!answers.length) return "plan: no stock Terraform root is served";
182
+ const parts = [];
183
+ for (const a of answers) {
184
+ const who = a.member ? `${a.member}: ` : "";
185
+ if (a.refusal) {
186
+ parts.push(`${who}plan not read (${a.refusal.error})`);
187
+ continue;
188
+ }
189
+ for (const r of a.roots ?? []) {
190
+ parts.push(
191
+ r.answered === "plan" ? `${who}${r.root} read from the plan` : r.answered === "state" ? `${who}${r.root} plan not read, the state read answered (${r.note.replace(/^terraform\.roots\.[^:]+: /, "")})` : `${who}${r.root} plan not read, nothing answered (${r.note.replace(/^terraform\.roots\.[^:]+: /, "")})`
192
+ );
193
+ }
194
+ }
195
+ return parts.length ? `plan: ${parts.join("; ")}` : void 0;
196
+ }
197
+
198
+ // src/member-ir.ts
199
+ import { resolve } from "node:path";
200
+ function memberIrCacheSize(env = process.env) {
201
+ const override = Number.parseInt(env.BEHOLD_ESTATE_IR_CACHE ?? "", 10);
202
+ return Number.isInteger(override) && override >= 0 ? override : 64;
203
+ }
204
+ var chantVia = {
205
+ tool: (dir) => {
206
+ const chant = resolveChant(dir);
207
+ return `${chant.bin}\0${chant.version ?? ""}`;
208
+ },
209
+ read: (dir, opts) => graphIr(dir, opts)
210
+ };
211
+ function cacheKey(dir, opts, via) {
212
+ const canonical = JSON.stringify(opts, Object.keys(opts).sort());
213
+ return `${resolve(dir)}\0${via.tool(dir)}\0${canonical}`;
214
+ }
215
+ var cache = /* @__PURE__ */ new Map();
216
+ var hits = 0;
217
+ var misses = 0;
218
+ function memberIrCacheStats() {
219
+ return { hits, misses, entries: cache.size };
220
+ }
221
+ function invalidateMember(dir) {
222
+ invalidateReadGeneration();
223
+ if (dir === void 0) {
224
+ cache.clear();
225
+ return;
226
+ }
227
+ const root = resolve(dir);
228
+ for (const [key, entry] of cache) if (entry.dir === root) cache.delete(key);
229
+ }
230
+ async function memberIr(dir, opts = {}, via = chantVia) {
231
+ const size = memberIrCacheSize();
232
+ if (opts.live || opts.overlay || size === 0) return via.read(dir, opts);
233
+ const stamp = memberSourceStamp(dir);
234
+ const key = cacheKey(dir, opts, via);
235
+ const hit = stamp !== void 0 ? cache.get(key) : void 0;
236
+ if (hit && hit.stamp === stamp) {
237
+ hits++;
238
+ cache.delete(key);
239
+ cache.set(key, hit);
240
+ return structuredClone(hit.ir);
241
+ }
242
+ misses++;
243
+ const ir = await via.read(dir, opts);
244
+ if (stamp === void 0 || memberSourceStamp(dir) !== stamp) return ir;
245
+ cache.delete(key);
246
+ cache.set(key, { dir: resolve(dir), stamp, ir });
247
+ for (const oldest of cache.keys()) {
248
+ if (cache.size <= size) break;
249
+ cache.delete(oldest);
250
+ }
251
+ return structuredClone(ir);
252
+ }
253
+
254
+ export {
255
+ TERRAFORM_OBSERVE_ENV,
256
+ PLAN_READ_ENV,
257
+ rootReadsOf,
258
+ hasRootReads,
259
+ rootReadReasonWords,
260
+ readTerraformPlan,
261
+ paintTerraformPlan,
262
+ terraformPlanNote,
263
+ chantVia,
264
+ memberIrCacheStats,
265
+ invalidateMember,
266
+ memberIr
267
+ };
@@ -0,0 +1,46 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
+ }) : x)(function(x) {
10
+ if (typeof require !== "undefined") return require.apply(this, arguments);
11
+ throw Error('Dynamic require of "' + x + '" is not supported');
12
+ });
13
+ var __commonJS = (cb, mod) => function __require2() {
14
+ try {
15
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
16
+ } catch (e) {
17
+ throw mod = 0, e;
18
+ }
19
+ };
20
+ var __export = (target, all) => {
21
+ for (var name in all)
22
+ __defProp(target, name, { get: all[name], enumerable: true });
23
+ };
24
+ var __copyProps = (to, from, except, desc) => {
25
+ if (from && typeof from === "object" || typeof from === "function") {
26
+ for (let key of __getOwnPropNames(from))
27
+ if (!__hasOwnProp.call(to, key) && key !== except)
28
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
29
+ }
30
+ return to;
31
+ };
32
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
33
+ // If the importer is in node compatibility mode or this is not an ESM
34
+ // file that has been converted to a CommonJS file using a Babel-
35
+ // compatible transform (i.e. "__esModule" has not been set), then set
36
+ // "default" to the CommonJS "module.exports" for node compatibility.
37
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
38
+ mod
39
+ ));
40
+
41
+ export {
42
+ __require,
43
+ __commonJS,
44
+ __export,
45
+ __toESM
46
+ };