@intentius/behold 0.29.26 → 0.29.27

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/demos.json CHANGED
@@ -116,7 +116,7 @@
116
116
  },
117
117
  {
118
118
  "name": "terralith",
119
- "description": "A terralith, adopted and split, on a scratch floci. Phase 1 applies one stock Terraform root with 23 resources in one state file. Adopt runs terragucci's backends migration, in which choudoufu live-import stamps its marker on each resource it verifies. Split runs the moves migration, in which live-mv moves each team's resources into the team's own estate with one tag write each, and split.json records it. Each card shows whether its identity comes from its marker or from its name, and the cards glide into the team boxes as they appear. You run each phase's script line, and behold reads what it leaves. It requires choudoufu 0.28.0 or newer (or CHOUDOUFU_BIN) with Docker and curl, and providers download on first init. scripts/terralith-down.sh removes the container.",
119
+ "description": "A terralith, adopted and split, on a scratch floci. Phase 1 applies one stock Terraform root with 23 resources in one state file. Adopt runs terragucci's backends migration, in which choudoufu live-import stamps its marker on each resource it verifies. Split runs the moves migration, in which live-mv moves each team's resources into the team's own estate with one tag write each, and split.json records it. Plan changes all four estates at once without applying. The team roots plan against the terralith's planned output inside their cones, and live-summary folds their identical changes into one group. Each card shows whether its identity comes from its marker or from its name, and the cards glide into the team boxes as they appear. You run each phase's script line, and behold reads what it leaves. It requires choudoufu 0.28.0 or newer (or CHOUDOUFU_BIN) with Docker and curl, and providers download on first init. scripts/terralith-down.sh removes the container.",
120
120
  "source": "bundled",
121
121
  "dir": "example-terralith",
122
122
  "requires": [
package/dist/cli.js CHANGED
@@ -23080,7 +23080,8 @@ import { join as join36 } from "node:path";
23080
23080
  var TERRALITH_PHASES = [
23081
23081
  { id: "stock", n: 1, dir: "1-stock" },
23082
23082
  { id: "adopt", n: 2, dir: "2-adopt" },
23083
- { id: "split", n: 3, dir: "3-split" }
23083
+ { id: "split", n: 3, dir: "3-split" },
23084
+ { id: "plan", n: 4, dir: "4-plan" }
23084
23085
  ];
23085
23086
  var isRecord12 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
23086
23087
  function readJson(path, notes, label) {
@@ -23149,6 +23150,37 @@ function retagsOf(dir, notes) {
23149
23150
  }
23150
23151
  return out;
23151
23152
  }
23153
+ function plannedChanges(plan) {
23154
+ const out = /* @__PURE__ */ new Map();
23155
+ if (!isRecord12(plan) || !Array.isArray(plan.resource_changes)) return out;
23156
+ for (const rc of plan.resource_changes) {
23157
+ if (!isRecord12(rc) || typeof rc.address !== "string" || !isRecord12(rc.change)) continue;
23158
+ const actions = Array.isArray(rc.change.actions) ? rc.change.actions.filter((a) => typeof a === "string") : [];
23159
+ if (!actions.length || actions.every((a) => a === "no-op" || a === "read")) continue;
23160
+ const before = isRecord12(rc.change.before) ? rc.change.before : {};
23161
+ const after2 = isRecord12(rc.change.after) ? rc.change.after : {};
23162
+ const unknown = isRecord12(rc.change.after_unknown) ? rc.change.after_unknown : {};
23163
+ const keys = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after2), ...Object.keys(unknown)]);
23164
+ const attributes = [...keys].filter((k) => unknown[k] === true || JSON.stringify(before[k]) !== JSON.stringify(after2[k])).sort();
23165
+ out.set(rc.address, { actions, attributes });
23166
+ }
23167
+ return out;
23168
+ }
23169
+ function outputReads(plan) {
23170
+ if (!isRecord12(plan) || !isRecord12(plan.configuration) || !isRecord12(plan.configuration.root_module)) return [];
23171
+ const resources = plan.configuration.root_module.resources;
23172
+ return (Array.isArray(resources) ? resources : []).flatMap((r) => {
23173
+ if (!isRecord12(r) || r.mode !== "data" || r.type !== "terraform_estate_outputs" || !isRecord12(r.expressions)) return [];
23174
+ const estate = isRecord12(r.expressions.estate) ? r.expressions.estate.constant_value : void 0;
23175
+ const names = isRecord12(r.expressions.names) ? r.expressions.names.constant_value : void 0;
23176
+ return typeof estate === "string" ? [{ estate, names: Array.isArray(names) ? names.filter((n) => typeof n === "string") : [] }] : [];
23177
+ });
23178
+ }
23179
+ function coneFallback(log) {
23180
+ const text2 = log.replace(/\x1b\[[0-9;]*m/g, "").replace(/^[│╷╵ ]+/gm, "");
23181
+ const m = /Cone plan fell back to a full plan\s+This plan covers the whole estate \(guard ([a-z-]+)\):\s*([\s\S]*?)(?:\n\s*\n|$)/.exec(text2);
23182
+ return m ? { kind: m[1], reason: m[2].replace(/\s+/g, " ").trim() } : void 0;
23183
+ }
23152
23184
  function readTerralithPhase(snapshots, phase2, before) {
23153
23185
  const dir = join36(snapshots, phase2.dir);
23154
23186
  const notes = [];
@@ -23156,6 +23188,12 @@ function readTerralithPhase(snapshots, phase2, before) {
23156
23188
  if (!isRecord12(meta)) return void 0;
23157
23189
  const roots = Array.isArray(meta.roots) ? meta.roots.filter((r) => typeof r === "string") : [];
23158
23190
  const retags = retagsOf(dir, notes);
23191
+ const set = readJson(join36(dir, "set.json"), notes, "set.json");
23192
+ const setPlans = /* @__PURE__ */ new Map();
23193
+ if (isRecord12(set) && Array.isArray(set.roots)) {
23194
+ for (const r of set.roots) if (isRecord12(r) && typeof r.root === "string") setPlans.set(r.root, r.plan);
23195
+ }
23196
+ const planOf = (root) => setPlans.get(root) ?? readJson(join36(dir, root, "plan.json"), notes, `${root}/plan.json`);
23159
23197
  const seen = new Set(before?.boxes.map((b) => b.id) ?? []);
23160
23198
  const boxes = roots.map((root) => {
23161
23199
  const at2 = (f) => join36(dir, root, f);
@@ -23166,6 +23204,10 @@ function readTerralithPhase(snapshots, phase2, before) {
23166
23204
  const plan = readJson(at2("live-plan.json"), notes, `${root}/live-plan.json`);
23167
23205
  const ratified = existsSync23(at2("live-import.txt")) ? parseRatification(readFileSync27(at2("live-import.txt"), "utf8")) : /* @__PURE__ */ new Map();
23168
23206
  const ids = stateIds(state);
23207
+ const cone = readJson(at2("cone.json"), notes, `${root}/cone.json`);
23208
+ const planDoc = planOf(root);
23209
+ const changes = plannedChanges(planDoc);
23210
+ const inCone = new Set(isRecord12(cone) && isRecord12(cone.guard) && cone.guard.full !== true && Array.isArray(cone.targets) ? cone.targets.filter((t2) => typeof t2 === "string") : []);
23169
23211
  const listed = /* @__PURE__ */ new Map();
23170
23212
  if (isRecord12(ls) && Array.isArray(ls.items)) {
23171
23213
  for (const i of ls.items) {
@@ -23191,12 +23233,61 @@ function readTerralithPhase(snapshots, phase2, before) {
23191
23233
  identity: { source: source2, marked: listed.has(d.address) },
23192
23234
  ...liveId ? { liveId } : {},
23193
23235
  ...r ? { ratified: r.status } : {},
23194
- ...moved && moved.to === estate ? { moved } : {}
23236
+ ...moved && moved.to === estate ? { moved } : {},
23237
+ ...changes.has(d.address) ? { planned: changes.get(d.address) } : {},
23238
+ ...inCone.has(d.address) ? { inCone: true } : {}
23195
23239
  };
23196
23240
  });
23197
23241
  cards.sort(cardOrder);
23198
- return { id: root, ...estate ? { estate } : {}, stock: !estate, spawned: !!before && !seen.has(root), cards };
23242
+ const log = existsSync23(at2("plan.log")) ? readFileSync27(at2("plan.log"), "utf8") : "";
23243
+ const fallback = log ? coneFallback(log) : void 0;
23244
+ const rootPlan = isRecord12(cone) || planDoc !== void 0 ? {
23245
+ ...isRecord12(cone) && isRecord12(cone.guard) ? {
23246
+ cone: {
23247
+ full: cone.guard.full === true,
23248
+ ...typeof cone.guard.kind === "string" ? { kind: cone.guard.kind } : {},
23249
+ ...typeof cone.guard.reason === "string" ? { reason: cone.guard.reason } : {},
23250
+ blocks: typeof cone.blocks === "number" ? cone.blocks : 0,
23251
+ coneBlocks: typeof cone.cone_blocks === "number" ? cone.cone_blocks : 0
23252
+ }
23253
+ } : {},
23254
+ ...fallback ? { fallback } : {},
23255
+ changes: changes.size
23256
+ } : void 0;
23257
+ return { id: root, ...estate ? { estate } : {}, stock: !estate, spawned: !!before && !seen.has(root), cards, ...rootPlan ? { plan: rootPlan } : {} };
23199
23258
  });
23259
+ const summary = readJson(join36(dir, "summary.json"), notes, "summary.json");
23260
+ const groups = isRecord12(summary) && Array.isArray(summary.groups) ? summary.groups.flatMap(
23261
+ (g) => isRecord12(g) && typeof g.id === "number" && Array.isArray(g.members) ? [
23262
+ {
23263
+ id: g.id,
23264
+ members: g.members.filter((m) => typeof m === "string"),
23265
+ changes: (Array.isArray(g.changes) ? g.changes : []).flatMap((c) => isRecord12(c) && typeof c.line === "string" ? [{ line: c.line, action: String(c.action ?? "") }] : [])
23266
+ }
23267
+ ] : []
23268
+ ) : [];
23269
+ for (const g of groups) for (const m of g.members) {
23270
+ const box = boxes.find((b) => b.id === m);
23271
+ if (box?.plan) box.plan.group = g.id;
23272
+ }
23273
+ const outputs = [];
23274
+ for (const box of boxes) {
23275
+ for (const read of outputReads(planOf(box.id))) {
23276
+ const producer = boxes.find((b) => b.estate === read.estate);
23277
+ const planned = producer ? planOf(producer.id) : void 0;
23278
+ const values = isRecord12(planned) && isRecord12(planned.planned_values) && isRecord12(planned.planned_values.outputs) ? planned.planned_values.outputs : {};
23279
+ for (const name of read.names) {
23280
+ let o = outputs.find((x) => x.estate === read.estate && x.name === name);
23281
+ if (!o) {
23282
+ const v = values[name];
23283
+ const known = isRecord12(v) && "value" in v && v.sensitive !== true;
23284
+ o = { estate: read.estate, ...producer ? { root: producer.id } : {}, name, ...known ? { value: v.value } : {}, known, readers: [] };
23285
+ outputs.push(o);
23286
+ }
23287
+ o.readers.push(box.id);
23288
+ }
23289
+ }
23290
+ }
23200
23291
  const all = boxes.flatMap((b) => b.cards);
23201
23292
  return {
23202
23293
  id: phase2.id,
@@ -23210,8 +23301,10 @@ function readTerralithPhase(snapshots, phase2, before) {
23210
23301
  marker: all.filter((c) => c.identity.source === "marker").length,
23211
23302
  derived: all.filter((c) => c.identity.source === "derived").length,
23212
23303
  state: all.filter((c) => c.identity.source === "state").length,
23213
- moved: all.filter((c) => c.moved).length
23304
+ moved: all.filter((c) => c.moved).length,
23305
+ planned: all.filter((c) => c.planned).length
23214
23306
  },
23307
+ ...groups.length || outputs.length ? { plan: { groups, outputs } } : {},
23215
23308
  notes
23216
23309
  };
23217
23310
  }
@@ -17,6 +17,7 @@ leaves in `snapshots/`, and shows the next phase's line for you to run here.
17
17
  | 1. Stock | `bash scripts/terralith-up.sh` (the demo runs it) | a floci on 127.0.0.1:4652, a state bucket, and `terralith/` applied the stock way: 23 resources in one state file |
18
18
  | 2. Adopt | `bash scripts/terralith-step.sh adopt` | terragucci's `backends:` migration: the backend block becomes a live block (`phases/adopt/`), `choudoufu live-import` reads the state once and stamps the two tags on each resource it verifies |
19
19
  | 3. Split | `bash scripts/terralith-step.sh split` | terragucci's `moves:` migration: three team roots (`phases/split/`), and `choudoufu live-mv -from-estate` moves each team's resources into the team's estate, one tag write each, recorded in `split.json` |
20
+ | 4. Plan | `bash scripts/terralith-step.sh plan` | one change across the estates (`phases/plan/`): the terralith outputs `log_retention_days`, each team's first log group reads it, `live-cone` gives each team's cone, the team roots plan against the terralith's planned output with `-estate-outputs-from` in one `live-plan-set`, and `live-summary` folds the three changes into one group. Nothing is applied |
20
21
 
21
22
  From adopt on, each card carries a tag. A filled tag means the resource wears the
22
23
  marker; an outlined one means it has no tags argument and rides the role it
@@ -0,0 +1,58 @@
1
+ terraform {
2
+ required_providers {
3
+ aws = {
4
+ source = "hashicorp/aws"
5
+ version = "= 6.59.0"
6
+ }
7
+ }
8
+ live {
9
+ estate = "team-a"
10
+ }
11
+ }
12
+
13
+ provider "aws" {
14
+ region = "us-east-1"
15
+ }
16
+
17
+ # ---- team-a ----
18
+ resource "aws_iam_role" "team_a" {
19
+ name = "terralith-team-a-role"
20
+ assume_role_policy = jsonencode({ Version = "2012-10-17", Statement = [{ Effect = "Allow", Principal = { Service = "ec2.amazonaws.com" }, Action = "sts:AssumeRole" }] })
21
+ }
22
+
23
+ resource "aws_iam_role_policy" "team_a_inline" {
24
+ name = "terralith-team-a-inline"
25
+ role = aws_iam_role.team_a.id
26
+ policy = jsonencode({ Version = "2012-10-17", Statement = [{ Effect = "Allow", Action = ["logs:CreateLogStream"], Resource = "*" }] })
27
+ }
28
+
29
+ resource "aws_iam_policy" "team_a" {
30
+ name = "terralith-team-a-policy"
31
+ policy = jsonencode({ Version = "2012-10-17", Statement = [{ Effect = "Allow", Action = ["logs:PutLogEvents"], Resource = "*" }] })
32
+ }
33
+
34
+ resource "aws_iam_role_policy_attachment" "team_a" {
35
+ role = aws_iam_role.team_a.name
36
+ policy_arn = aws_iam_policy.team_a.arn
37
+ }
38
+
39
+ resource "aws_cloudwatch_log_group" "team_a_0" {
40
+ name = "/terralith/team-a/svc-0"
41
+ retention_in_days = data.terraform_estate_outputs.platform.values.log_retention_days
42
+ }
43
+
44
+ resource "aws_cloudwatch_log_group" "team_a_1" {
45
+ name = "/terralith/team-a/svc-1"
46
+ retention_in_days = 7
47
+ }
48
+
49
+ resource "aws_cloudwatch_log_group" "team_a_2" {
50
+ name = "/terralith/team-a/svc-2"
51
+ retention_in_days = 7
52
+ }
53
+
54
+ # ---- the platform's shared settings ----
55
+ data "terraform_estate_outputs" "platform" {
56
+ estate = "terralith"
57
+ names = ["log_retention_days"]
58
+ }
@@ -0,0 +1,58 @@
1
+ terraform {
2
+ required_providers {
3
+ aws = {
4
+ source = "hashicorp/aws"
5
+ version = "= 6.59.0"
6
+ }
7
+ }
8
+ live {
9
+ estate = "team-b"
10
+ }
11
+ }
12
+
13
+ provider "aws" {
14
+ region = "us-east-1"
15
+ }
16
+
17
+ # ---- team-b ----
18
+ resource "aws_iam_role" "team_b" {
19
+ name = "terralith-team-b-role"
20
+ assume_role_policy = jsonencode({ Version = "2012-10-17", Statement = [{ Effect = "Allow", Principal = { Service = "ec2.amazonaws.com" }, Action = "sts:AssumeRole" }] })
21
+ }
22
+
23
+ resource "aws_iam_role_policy" "team_b_inline" {
24
+ name = "terralith-team-b-inline"
25
+ role = aws_iam_role.team_b.id
26
+ policy = jsonencode({ Version = "2012-10-17", Statement = [{ Effect = "Allow", Action = ["logs:CreateLogStream"], Resource = "*" }] })
27
+ }
28
+
29
+ resource "aws_iam_policy" "team_b" {
30
+ name = "terralith-team-b-policy"
31
+ policy = jsonencode({ Version = "2012-10-17", Statement = [{ Effect = "Allow", Action = ["logs:PutLogEvents"], Resource = "*" }] })
32
+ }
33
+
34
+ resource "aws_iam_role_policy_attachment" "team_b" {
35
+ role = aws_iam_role.team_b.name
36
+ policy_arn = aws_iam_policy.team_b.arn
37
+ }
38
+
39
+ resource "aws_cloudwatch_log_group" "team_b_0" {
40
+ name = "/terralith/team-b/svc-0"
41
+ retention_in_days = data.terraform_estate_outputs.platform.values.log_retention_days
42
+ }
43
+
44
+ resource "aws_cloudwatch_log_group" "team_b_1" {
45
+ name = "/terralith/team-b/svc-1"
46
+ retention_in_days = 7
47
+ }
48
+
49
+ resource "aws_cloudwatch_log_group" "team_b_2" {
50
+ name = "/terralith/team-b/svc-2"
51
+ retention_in_days = 7
52
+ }
53
+
54
+ # ---- the platform's shared settings ----
55
+ data "terraform_estate_outputs" "platform" {
56
+ estate = "terralith"
57
+ names = ["log_retention_days"]
58
+ }
@@ -0,0 +1,58 @@
1
+ terraform {
2
+ required_providers {
3
+ aws = {
4
+ source = "hashicorp/aws"
5
+ version = "= 6.59.0"
6
+ }
7
+ }
8
+ live {
9
+ estate = "team-c"
10
+ }
11
+ }
12
+
13
+ provider "aws" {
14
+ region = "us-east-1"
15
+ }
16
+
17
+ # ---- team-c ----
18
+ resource "aws_iam_role" "team_c" {
19
+ name = "terralith-team-c-role"
20
+ assume_role_policy = jsonencode({ Version = "2012-10-17", Statement = [{ Effect = "Allow", Principal = { Service = "ec2.amazonaws.com" }, Action = "sts:AssumeRole" }] })
21
+ }
22
+
23
+ resource "aws_iam_role_policy" "team_c_inline" {
24
+ name = "terralith-team-c-inline"
25
+ role = aws_iam_role.team_c.id
26
+ policy = jsonencode({ Version = "2012-10-17", Statement = [{ Effect = "Allow", Action = ["logs:CreateLogStream"], Resource = "*" }] })
27
+ }
28
+
29
+ resource "aws_iam_policy" "team_c" {
30
+ name = "terralith-team-c-policy"
31
+ policy = jsonencode({ Version = "2012-10-17", Statement = [{ Effect = "Allow", Action = ["logs:PutLogEvents"], Resource = "*" }] })
32
+ }
33
+
34
+ resource "aws_iam_role_policy_attachment" "team_c" {
35
+ role = aws_iam_role.team_c.name
36
+ policy_arn = aws_iam_policy.team_c.arn
37
+ }
38
+
39
+ resource "aws_cloudwatch_log_group" "team_c_0" {
40
+ name = "/terralith/team-c/svc-0"
41
+ retention_in_days = data.terraform_estate_outputs.platform.values.log_retention_days
42
+ }
43
+
44
+ resource "aws_cloudwatch_log_group" "team_c_1" {
45
+ name = "/terralith/team-c/svc-1"
46
+ retention_in_days = 7
47
+ }
48
+
49
+ resource "aws_cloudwatch_log_group" "team_c_2" {
50
+ name = "/terralith/team-c/svc-2"
51
+ retention_in_days = 7
52
+ }
53
+
54
+ # ---- the platform's shared settings ----
55
+ data "terraform_estate_outputs" "platform" {
56
+ estate = "terralith"
57
+ names = ["log_retention_days"]
58
+ }
@@ -0,0 +1,32 @@
1
+ terraform {
2
+ required_providers {
3
+ aws = {
4
+ source = "hashicorp/aws"
5
+ version = "= 6.59.0"
6
+ }
7
+ }
8
+ live {
9
+ estate = "terralith"
10
+ }
11
+ }
12
+
13
+ provider "aws" {
14
+ region = "us-east-1"
15
+ }
16
+
17
+ # ---- network ----
18
+ resource "aws_vpc" "main" {
19
+ cidr_block = "10.42.0.0/16"
20
+ tags = { Name = "terralith-main" }
21
+ }
22
+
23
+ resource "aws_subnet" "app" {
24
+ vpc_id = aws_vpc.main.id
25
+ cidr_block = "10.42.1.0/24"
26
+ tags = { Name = "terralith-app" }
27
+ }
28
+
29
+ # ---- shared settings, read by the team estates ----
30
+ output "log_retention_days" {
31
+ value = 14
32
+ }
@@ -41,7 +41,8 @@ snap() {
41
41
  (cd "$root" && "$CHOUDOUFU" show -json -no-color >"$out/state.json" 2>"$out/state.err") || true
42
42
  else
43
43
  (cd "$root" && "$CHOUDOUFU" live-ls -estate="$estate" -consistent -json . >"$out/live-ls.json" 2>"$out/live-ls.err") || true
44
- (cd "$root" && "$CHOUDOUFU" live-plan -json >"$out/live-plan.json" 2>"$out/live-plan.err") || true
44
+ # SNAP_PLAN_ARGS: extra live-plan flags, such as -estate-outputs-from in the plan phase.
45
+ (cd "$root" && "$CHOUDOUFU" live-plan -json ${SNAP_PLAN_ARGS:-} >"$out/live-plan.json" 2>"$out/live-plan.err") || true
45
46
  fi
46
47
  }
47
48
 
@@ -10,6 +10,14 @@
10
10
  # choudoufu live-mv -from-estate rewrites each team resource's
11
11
  # markers, run in the root it moves to. One tag write per resource.
12
12
  # The record is split.json.
13
+ # plan a change across the new estates, planned the way terragucci
14
+ # plans a pull request: the terralith publishes a shared setting as
15
+ # an output, and each team's first log group reads it. The
16
+ # terralith plans first; each team root plans its cone with
17
+ # -estate-outputs-from, so it reads the terralith's PLANNED output
18
+ # (choudoufu falls back to a full plan there, and says why); the
19
+ # three team plans run as one live-plan-set, and live-summary folds
20
+ # the identical changes into one group. Nothing is applied.
13
21
  #
14
22
  # Each phase ends in a snapshot under snapshots/<n>-<phase>/.
15
23
  set -euo pipefail
@@ -82,7 +90,50 @@ case "$phase" in
82
90
  finish snapshots/3-split split 3 terralith team-a team-b team-c
83
91
  say "split. Four estates, one tag write per resource."
84
92
  ;;
93
+ plan)
94
+ [ -f snapshots/3-split/phase.json ] || die "split has not run yet. Run scripts/terralith-step.sh split first."
95
+ [ -f snapshots/4-plan/phase.json ] && { say "plan already ran (snapshots/4-plan)."; exit 0; }
96
+ command -v git >/dev/null 2>&1 || die "git is not on PATH; the cone is a diff against each root's last commit."
97
+ out="$PWD/snapshots/4-plan"
98
+ mkdir -p "$out"
99
+ # Each estate root keeps its own history, as a split estate's repository
100
+ # would: the base is the root as the split left it. (A root in a
101
+ # subdirectory of one shared repository gets no cone from choudoufu 0.28.0:
102
+ # live-cone lists the base with `git ls-tree` from inside the root, which
103
+ # git filters to that directory, so the base reads empty.)
104
+ for root in terralith team-a team-b team-c; do
105
+ if [ ! -d "$root/.git" ]; then
106
+ (cd "$root" && git init -q && printf '%s\n' .terraform/ .terraform.lock.hcl .tofu-records/ >.gitignore \
107
+ && git add -A && git -c user.name=terralith-demo -c user.email=terralith-demo@localhost commit -q -m "the root as the split left it")
108
+ fi
109
+ done
110
+ say "the code change: the terralith outputs log_retention_days, and each team's first log group reads it"
111
+ for root in terralith team-a team-b team-c; do cp "phases/plan/$root/main.tf" "$root/main.tf"; done
112
+ say "live-cone: what each change reaches, against the root's last commit"
113
+ for root in terralith team-a team-b team-c; do
114
+ mkdir -p "$out/$root"
115
+ (cd "$root" && "$CHOUDOUFU" live-cone -json HEAD >"$out/$root/cone.json" 2>"$out/$root/cone.err") || true
116
+ done
117
+ say "plan the terralith first: its planned output is what the teams read"
118
+ (cd terralith && "$CHOUDOUFU" plan -input=false -no-color "-out=$PWD/../$WORK/terralith.tfplan" >"$out/terralith/plan.log" 2>&1) \
119
+ || die "the terralith's plan failed (snapshots/4-plan/terralith/plan.log)"
120
+ (cd terralith && "$CHOUDOUFU" show -json "$PWD/../$WORK/terralith.tfplan" >"$out/terralith/plan.json")
121
+ say "live-plan-set: the three team roots, each its cone, reading the terralith's planned output"
122
+ TF_CLI_ARGS_plan="-cone=HEAD -estate-outputs-from=terralith=$out/terralith/plan.json" \
123
+ "$CHOUDOUFU" live-plan-set -json "-out-dir=$WORK/plan-set" team-a team-b team-c >"$out/set.json" 2>"$out/set.err" || true
124
+ for root in team-a team-b team-c; do cp "$WORK/plan-set/$root.log" "$out/$root/plan.log" 2>/dev/null || true; done
125
+ say "live-summary: the identical changes, folded"
126
+ "$CHOUDOUFU" live-summary -json "$out/set.json" >"$out/summary.json"
127
+ "$CHOUDOUFU" live-summary "$out/set.json" | head -8
128
+ say "snapshot: phase 4"
129
+ snap snapshots/4-plan terralith
130
+ for root in team-a team-b team-c; do
131
+ SNAP_PLAN_ARGS="-estate-outputs-from=terralith=$out/terralith/plan.json" snap snapshots/4-plan "$root"
132
+ done
133
+ finish snapshots/4-plan plan 4 terralith team-a team-b team-c
134
+ say "planned. Nothing was applied: the plans are in .terralith/plan-set."
135
+ ;;
85
136
  *)
86
- die "which phase? bash scripts/terralith-step.sh adopt | split"
137
+ die "which phase? bash scripts/terralith-step.sh adopt | split | plan"
87
138
  ;;
88
139
  esac
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intentius/behold",
3
- "version": "0.29.26",
3
+ "version": "0.29.27",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "description": "behold — a live control plane on chant. See your whole estate (every substrate in one graph), coloured by drift; act through delegated, gated Ops.",
package/web/app.js CHANGED
@@ -33,7 +33,7 @@ import { seconds, whyQuery, whyView } from "./why.js";
33
33
  import { edgeKey, edgeLabel, edgeLegend, edgeTitle, isCiKind, viaIndex } from "./edge-kind.js";
34
34
  import { readCostLine } from "./read-cost.js";
35
35
  import { mountHistoryPicker } from "./history-picker.js";
36
- import { applyMemberFrame, pendingLine, stillPending } from "./pending.js";
36
+ import { applyMemberFrame, createMemberFrames, pendingLine, stillPending } from "./pending.js";
37
37
  import { initTheme, setTheme, mountThemePicker, readableOn, inkOn, colorForCategory, onThemeChange, getTokens, getTheme, pinTokensFor } from "./theme.js";
38
38
  // #399 M2 / #401 M4 of #397: the colour-by modes' arithmetic and the
39
39
  // provenance badge's wording — every decision the behaviour overlay makes,
@@ -1701,6 +1701,8 @@ let runtimeCapable = false;
1701
1701
  * overlay's `meta.pending`. Empty on every non-progressive load, which is every
1702
1702
  * single-project serve and every static snapshot. */
1703
1703
  let pendingMembers = [];
1704
+ // The frames of the progressive load in flight, replayed once it is drawn.
1705
+ const memberFrames = createMemberFrames();
1704
1706
  let pendingTotal = 0;
1705
1707
  /** #426: whether the apply-order stop is worth offering — /api/project's
1706
1708
  * `stacksCapable`, which is false for an estate and for a single-lexicon
@@ -7210,6 +7212,10 @@ function renderPreconditionError(body) {
7210
7212
  const load = createRefreshQueue(loadOnce);
7211
7213
  async function loadOnce(opts = {}, isCurrent = () => true) {
7212
7214
  const meta = document.getElementById("meta");
7215
+ // #422: set when this load asks for the progressive overlay; `frameLoad` is
7216
+ // its turn in memberFrames, so an older load's end never releases a newer one.
7217
+ let progressive = false;
7218
+ let frameLoad = 0;
7213
7219
  // A background settle re-pull (post-apply) shouldn't flash the meta/overlay.
7214
7220
  if (!opts.quiet) {
7215
7221
  meta.textContent = view.env ? `loading overlay for ${view.env}…` : "loading…";
@@ -7272,7 +7278,10 @@ async function loadOnce(opts = {}, isCurrent = () => true) {
7272
7278
  // its own live read lands, instead of a blank canvas until the slowest
7273
7279
  // one finishes. The server only honours it for a composed estate, and
7274
7280
  // never in a static snapshot, where there is no stream to follow.
7275
- if (!staticMode) q.set("progressive", "1");
7281
+ if (!staticMode) {
7282
+ q.set("progressive", "1");
7283
+ progressive = true;
7284
+ }
7276
7285
  // The runtime tier (#86) descends below the declaration boundary. It is
7277
7286
  // live-only by nature — owner-referenced children exist in the cluster,
7278
7287
  // never in your source — so it rides the overlay and means nothing
@@ -7302,6 +7311,7 @@ async function loadOnce(opts = {}, isCurrent = () => true) {
7302
7311
  ciByComponent = new Map();
7303
7312
  resourcesByComponent = {};
7304
7313
  }
7314
+ if (progressive) frameLoad = memberFrames.begin();
7305
7315
  const res = await apiFetch(`${endpoint}?${q}`);
7306
7316
  const body = await res.json();
7307
7317
  if (!isCurrent()) return; // a newer view/event is pending; do not paint the old result
@@ -7337,6 +7347,7 @@ async function loadOnce(opts = {}, isCurrent = () => true) {
7337
7347
  if (view.components) takeTerragucciFacets(body.meta);
7338
7348
  render(body.ir, body.svg, body.meta);
7339
7349
  afterPaint(body.ir);
7350
+ if (progressive) replayMemberFrames(frameLoad);
7340
7351
  } catch (err) {
7341
7352
  // A background settle poll must not blow away a good graph on a transient error.
7342
7353
  if (!opts.quiet && isCurrent()) {
@@ -7353,9 +7364,25 @@ async function loadOnce(opts = {}, isCurrent = () => true) {
7353
7364
  }
7354
7365
  } finally {
7355
7366
  if (!opts.quiet) hideLoading();
7367
+ // Drawn, refused or superseded: either way nothing waits on this load's
7368
+ // answer any more, so a later frame applies as it lands.
7369
+ if (progressive) memberFrames.cancel(frameLoad);
7356
7370
  }
7357
7371
  }
7358
7372
 
7373
+ /** The frames that landed before this load's answer was drawn, folded into it now. */
7374
+ function replayMemberFrames(load) {
7375
+ if (!lastGraphIr) return;
7376
+ const r = memberFrames.replay(lastGraphIr, pendingMembers, load);
7377
+ if (!r) return;
7378
+ pendingMembers = r.pending;
7379
+ if (r.failed) nowline(`the estate read failed — ${r.failed}`);
7380
+ if (r.moved.length) recolorNodesByCategory(lastGraphIr);
7381
+ markPendingCards(lastGraphIr);
7382
+ markIdentityCards(lastGraphIr);
7383
+ renderStatusbar();
7384
+ }
7385
+
7359
7386
  /**
7360
7387
  * #404: re-read the overlay AND ask for the attribute-drift plan.
7361
7388
  *
@@ -7497,6 +7524,9 @@ events.addEventListener("member", (e) => {
7497
7524
  }
7498
7525
  // The live pass itself failed. Say so on the now-line and stop claiming the
7499
7526
  // remaining members are still arriving, because nothing more is coming.
7527
+ // A frame that lands while its load's answer is still on the way waits
7528
+ // for the draw, which replays it (web/pending.js createMemberFrames).
7529
+ if (!memberFrames.note(frame)) return;
7500
7530
  if (frame.error) {
7501
7531
  pendingMembers = [];
7502
7532
  nowline(`the estate read failed — ${frame.error}`);
package/web/pending.js CHANGED
@@ -67,3 +67,55 @@ export function pendingLine(pending, total) {
67
67
  const who = pending.length <= 3 ? ` — waiting on ${pending.join(", ")}` : "";
68
68
  return `${scope}${who}`;
69
69
  }
70
+
71
+ /**
72
+ * The frames of one progressive load, kept from the moment its request goes
73
+ * out until the answer is drawn.
74
+ *
75
+ * The live pass starts when the server takes the request, and with the
76
+ * overlay cache warm it can settle and broadcast every member before the
77
+ * answer reaches the page. A frame that lands then has no picture to fold
78
+ * into: the answer, drawn a moment later, paints every card pending again.
79
+ * So every frame is noted here (the newest per member wins), applied at once
80
+ * only when the picture it belongs to is already up, and replayed onto the
81
+ * picture right after it is drawn. A failed live pass is noted the same way.
82
+ */
83
+ export function createMemberFrames() {
84
+ let frames = new Map();
85
+ let failed = null;
86
+ let drawing = false;
87
+ let load = 0;
88
+ return {
89
+ /** A progressive request is going out: its frames start here. Returns the load's turn. */
90
+ begin() {
91
+ frames = new Map();
92
+ failed = null;
93
+ drawing = true;
94
+ return ++load;
95
+ },
96
+ /** Note a frame. True when it can be applied now, false when it waits for the draw. */
97
+ note(frame) {
98
+ if (!frame) return false;
99
+ if (frame.error) failed = frame.error;
100
+ else if (frame.member) frames.set(frame.member, frame);
101
+ return !drawing;
102
+ },
103
+ /** Load `turn`'s answer is drawn: fold every noted frame into it. Null when a newer load took over. */
104
+ replay(ir, pending, turn = load) {
105
+ if (turn !== load) return null;
106
+ drawing = false;
107
+ const moved = [];
108
+ let still = Array.isArray(pending) ? [...pending] : [];
109
+ for (const frame of frames.values()) {
110
+ moved.push(...applyMemberFrame(ir, frame));
111
+ still = stillPending(still, frame);
112
+ }
113
+ if (failed) still = [];
114
+ return { moved, pending: still, failed };
115
+ },
116
+ /** Load `turn` ended without drawing (an error, a newer view): stop holding frames back, unless a newer load holds them. */
117
+ cancel(turn = load) {
118
+ if (turn === load) drawing = false;
119
+ },
120
+ };
121
+ }
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it } from "vitest";
2
- import { applyMemberFrame, pendingLine, stillPending } from "./pending.js";
2
+ import { applyMemberFrame, createMemberFrames, pendingLine, stillPending } from "./pending.js";
3
3
 
4
4
  const ir = () => ({
5
5
  nodes: [
@@ -67,3 +67,42 @@ describe("what is still arriving", () => {
67
67
  expect(pendingLine(undefined, 5)).toBeNull();
68
68
  });
69
69
  });
70
+
71
+ describe("createMemberFrames: frames that land before the draw (#422)", () => {
72
+ const frame = { member: "team-a", statuses: { "team-a/bucket": "good", "team-a/role": "warn" } };
73
+
74
+ it("holds a frame that lands while the answer is on the way, and replays it onto the drawn picture", () => {
75
+ const frames = createMemberFrames();
76
+ const turn = frames.begin();
77
+ expect(frames.note(frame)).toBe(false);
78
+ const graph = ir();
79
+ const r = frames.replay(graph, ["team-a", "team-b"], turn);
80
+ expect(r.moved.sort()).toEqual(["team-a/bucket", "team-a/role"]);
81
+ expect(r.pending).toEqual(["team-b"]);
82
+ expect(graph.nodes[0].attrs).toEqual({ _status: "good" });
83
+ // Once drawn, a later frame applies as it lands.
84
+ expect(frames.note({ member: "team-b", statuses: {} })).toBe(true);
85
+ });
86
+
87
+ it("keeps the newest frame per member, and a failed pass clears the pending list", () => {
88
+ const frames = createMemberFrames();
89
+ const turn = frames.begin();
90
+ frames.note({ member: "team-a", statuses: { "team-a/bucket": "warn" } });
91
+ frames.note({ member: "team-a", statuses: { "team-a/bucket": "good" } });
92
+ frames.note({ error: "live-plan exited 1" });
93
+ const graph = ir();
94
+ const r = frames.replay(graph, ["team-a", "team-b"], turn);
95
+ expect(graph.nodes[0].attrs._status).toBe("good");
96
+ expect(r).toMatchObject({ pending: [], failed: "live-plan exited 1" });
97
+ });
98
+
99
+ it("leaves a newer load's frames alone when an older load ends", () => {
100
+ const frames = createMemberFrames();
101
+ const older = frames.begin();
102
+ const newer = frames.begin();
103
+ frames.cancel(older);
104
+ expect(frames.note(frame)).toBe(false);
105
+ expect(frames.replay(ir(), [], older)).toBeNull();
106
+ expect(frames.replay(ir(), ["team-a"], newer).pending).toEqual([]);
107
+ });
108
+ });
@@ -38,6 +38,18 @@ export const PHASES = [
38
38
  return `${p.counts.moved} resources moved into ${fresh} new estate${fresh === 1 ? "" : "s"}. The terralith keeps the network.`;
39
39
  },
40
40
  },
41
+ {
42
+ id: "plan",
43
+ n: 4,
44
+ label: "Plan",
45
+ title: "Plan across the estates",
46
+ lead: "One pull request touches all four estates. The terralith publishes a shared setting as an output, and each team's first log group reads it through terraform_estate_outputs. It plans first. With -estate-outputs-from, each team root then plans against that planned value, so nothing waits for an apply. Last, live-summary folds the identical team changes into one group.",
47
+ facts: (p) => {
48
+ const groups = (p.plan && p.plan.groups) || [];
49
+ const folded = groups.reduce((n, g) => n + g.members.length, 0);
50
+ return `${p.counts.planned} planned changes in ${folded} estates, folded into ${groups.length} group${groups.length === 1 ? "" : "s"}. Nothing is applied.`;
51
+ },
52
+ },
41
53
  ];
42
54
 
43
55
  export const phaseById = (id) => PHASES.find((p) => p.id === id) || null;
@@ -66,6 +78,7 @@ export function cardFace(card) {
66
78
  export function cardNews(card, phaseId) {
67
79
  if (phaseId === "adopt" && card.ratified) return card.ratified;
68
80
  if (phaseId === "split" && card.moved) return card.moved.follows ? "follows its role" : `from ${card.moved.from}`;
81
+ if (phaseId === "plan" && card.planned) return `${card.planned.actions.includes("update") ? "~" : card.planned.actions.join("/")} ${card.planned.attributes.join(", ")}`;
69
82
  return "";
70
83
  }
71
84
 
@@ -91,3 +104,39 @@ export function flipDelta(before, after) {
91
104
  const dy = before.top - after.top;
92
105
  return Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5 ? null : { dx, dy };
93
106
  }
107
+
108
+ /** Short words for a guard that planned a root in full, by choudoufu's guard kind. */
109
+ const FULL_PLAN_WORDS = {
110
+ "empty-cone": "planned in full: the change reaches no resource",
111
+ "estate-outputs-from": "planned in full: it reads planned outputs",
112
+ };
113
+
114
+ /** A box's plan badges: the cone, and the full plan when there was one. */
115
+ export function planBadges(box) {
116
+ const plan = box && box.plan;
117
+ if (!plan) return [];
118
+ const out = [];
119
+ if (plan.cone && !plan.cone.full) out.push({ kind: "cone", text: `cone ${plan.cone.coneBlocks} of ${plan.cone.blocks} blocks`, tip: "live-cone: the blocks this change reaches against the root's last commit." });
120
+ const full = plan.fallback || (plan.cone && plan.cone.full ? { kind: plan.cone.kind, reason: plan.cone.reason } : null);
121
+ if (full) out.push({ kind: "full", text: FULL_PLAN_WORDS[full.kind] || "planned in full", tip: full.reason || "" });
122
+ return out;
123
+ }
124
+
125
+ /** The folded group's one line, as live-summary prints it. */
126
+ export function groupLabel(group) {
127
+ const n = group.members.length;
128
+ const change = group.changes.length === 1 ? group.changes[0].line : `${group.changes.length} changes`;
129
+ return `${n} estates, one change: ${change}`;
130
+ }
131
+
132
+ /** A planned output's edge label. */
133
+ export function outputLabel(o) {
134
+ return o.known ? `${o.name} = ${JSON.stringify(o.value)} · planned` : `${o.name} · known after apply`;
135
+ }
136
+
137
+ /** Are these rects one row (the desktop layout) or stacked (the phone's)? */
138
+ export function oneRow(rects) {
139
+ if (rects.length < 2) return true;
140
+ const top = rects[0].top;
141
+ return rects.every((r) => Math.abs(r.top - top) < 4);
142
+ }
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect } from "vitest";
2
- import { PHASES, boxSubtitle, cardFace, cardNews, flipDelta, legendFor, shownPhase, stepperItems } from "./terralith-steps.js";
2
+ import { PHASES, boxSubtitle, cardFace, cardNews, flipDelta, groupLabel, legendFor, oneRow, outputLabel, planBadges, shownPhase, stepperItems } from "./terralith-steps.js";
3
3
 
4
4
  const card = (id, identity, extra = {}) => ({ id, type: id.split(".")[0], root: "terralith", identity, ...extra });
5
5
  const phase = (id, boxes, counts = {}) => ({ id, n: PHASES.find((p) => p.id === id).n, boxes, counts: { cards: 0, marked: 0, moved: 0, ...counts }, notes: [] });
@@ -22,6 +22,7 @@ describe("the walkthrough's phases", () => {
22
22
  ["stock", true, false, false],
23
23
  ["adopt", true, true, false],
24
24
  ["split", false, false, true],
25
+ ["plan", false, false, false],
25
26
  ]);
26
27
  });
27
28
 
@@ -69,3 +70,28 @@ describe("FLIP", () => {
69
70
  expect(flipDelta(undefined, { left: 0, top: 0 })).toBeNull();
70
71
  });
71
72
  });
73
+
74
+ describe("the plan phase", () => {
75
+ it("badges a team root with its cone and the full plan it fell back to", () => {
76
+ const box = { plan: { cone: { full: false, blocks: 8, coneBlocks: 2 }, fallback: { kind: "estate-outputs-from", reason: "every reader of them is planned" }, changes: 1 } };
77
+ expect(planBadges(box).map((b) => [b.kind, b.text])).toEqual([
78
+ ["cone", "cone 2 of 8 blocks"],
79
+ ["full", "planned in full: it reads planned outputs"],
80
+ ]);
81
+ expect(planBadges({ plan: { cone: { full: true, kind: "empty-cone", reason: "the diff reaches no resource", blocks: 2, coneBlocks: 0 }, changes: 0 } }).map((b) => b.text)).toEqual(["planned in full: the change reaches no resource"]);
82
+ expect(planBadges({})).toEqual([]);
83
+ });
84
+
85
+ it("says a folded group once, and a planned output with its value", () => {
86
+ expect(groupLabel({ members: ["team-a", "team-b", "team-c"], changes: [{ line: "~ aws_cloudwatch_log_group.<estate>_0: retention_in_days" }] })).toBe(
87
+ "3 estates, one change: ~ aws_cloudwatch_log_group.<estate>_0: retention_in_days",
88
+ );
89
+ expect(outputLabel({ name: "log_retention_days", value: 14, known: true })).toBe("log_retention_days = 14 · planned");
90
+ expect(cardNews({ id: "x", planned: { actions: ["update"], attributes: ["retention_in_days"] } }, "plan")).toBe("~ retention_in_days");
91
+ });
92
+
93
+ it("tells a row of boxes from a stack", () => {
94
+ expect(oneRow([{ top: 10 }, { top: 11 }])).toBe(true);
95
+ expect(oneRow([{ top: 10 }, { top: 300 }])).toBe(false);
96
+ });
97
+ });
@@ -66,6 +66,23 @@
66
66
  .t-card .news { font-size: 11.5px; color: var(--muted); margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
67
67
  .t-card .news.drifted { color: var(--foreign); }
68
68
  .t-card.moved { border-color: color-mix(in srgb, var(--managed) 55%, var(--line)); }
69
+ .t-stage { position: relative; }
70
+ .t-stage.planning { padding: 52px 0 40px; }
71
+ .t-overlay { position: absolute; inset: 0; pointer-events: none; overflow: visible; }
72
+ .t-edge { fill: none; stroke: var(--runtime); stroke-width: 1.6; stroke-dasharray: 5 4; }
73
+ .t-edge-head { fill: var(--runtime); }
74
+ .t-edge-label { fill: var(--runtime); font: 12px var(--font-mono); }
75
+ .t-bracket { fill: none; stroke: var(--foreign); stroke-width: 2; }
76
+ .t-bracket-label { fill: var(--foreign); font: 12.5px var(--font-mono); }
77
+ .t-badges { display: flex; flex-wrap: wrap; gap: 5px; flex-basis: 100%; }
78
+ .t-badge { font-size: 11.5px; padding: 1px 8px; border-radius: 999px; border: 1px solid var(--line); color: var(--muted); }
79
+ .t-badge.cone { border-color: var(--managed); color: var(--managed); }
80
+ .t-badge.full { border-style: dashed; }
81
+ .t-badge.group { border-color: var(--foreign); color: var(--foreign); }
82
+ .t-card.in-cone { outline: 2px dashed var(--managed); outline-offset: 2px; }
83
+ .t-card .news.change { color: var(--foreign); }
84
+ .t-groups, .t-groups[hidden] { display: none; }
85
+ .t-group { margin: 0; font: 13px var(--font-mono); color: var(--foreign); overflow-wrap: anywhere; }
69
86
  .t-empty { color: var(--muted); padding: 30px 0; }
70
87
  .t-notes { color: var(--foreign); font-size: 13px; margin-top: 10px; }
71
88
  .t-foot { color: var(--muted); font-size: 12.5px; margin-top: 18px; }
@@ -78,6 +95,8 @@
78
95
  .t-lead { grid-template-columns: 1fr; padding: 12px; }
79
96
  .t-theme { margin-left: 0; }
80
97
  .t-cards { grid-template-columns: repeat(2, minmax(0, 1fr)); }
98
+ .t-stage.planning { padding: 0 16px 24px 16px; }
99
+ .t-groups:not([hidden]) { display: block; margin: 0 0 10px; }
81
100
  }
82
101
  </style>
83
102
  </head>
@@ -90,6 +109,7 @@
90
109
  </header>
91
110
  <section class="t-lead" id="t-lead" aria-live="polite"></section>
92
111
  <section class="t-next" id="t-next" hidden></section>
112
+ <div class="t-groups" id="t-groups" hidden></div>
93
113
  <section class="t-stage" id="t-stage"></section>
94
114
  <div class="t-notes" id="t-notes" hidden></div>
95
115
  <p class="t-foot">The scripts save choudoufu's own documents under <code>snapshots/</code>, and each phase is drawn from them.</p>
package/web/terralith.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // the split spawned, while that box fades in. Decisions live in
5
5
  // terralith-steps.js and identity-mark.js; this file only draws.
6
6
 
7
- import { PHASES, boxSubtitle, cardFace, cardNews, flipDelta, legendFor, phaseById, shownPhase, stepperItems } from "./terralith-steps.js";
7
+ import { PHASES, boxSubtitle, cardFace, cardNews, flipDelta, groupLabel, legendFor, oneRow, outputLabel, phaseById, planBadges, shownPhase, stepperItems } from "./terralith-steps.js";
8
8
  import { identityMark, tagGlyphSvg } from "./identity-mark.js";
9
9
 
10
10
  const POLL_MS = 3000;
@@ -90,7 +90,7 @@ function renderNext(host, model) {
90
90
  function cardEl(card, phaseId) {
91
91
  const face = cardFace(card);
92
92
  const mark = identityMark(card.identity);
93
- const c = el("div", `t-card${phaseId === "split" && card.moved ? " moved" : ""}`);
93
+ const c = el("div", `t-card${phaseId === "split" && card.moved ? " moved" : ""}${phaseId === "plan" && card.inCone ? " in-cone" : ""}${phaseId === "plan" && card.planned ? " planned" : ""}`);
94
94
  c.dataset.card = card.id;
95
95
  c.title = [card.id, card.liveId ? `live id: ${card.liveId}` : "", mark ? mark.tip : ""].filter(Boolean).join("\n");
96
96
  c.append(el("div", "k", face.kind), el("div", "n", face.name));
@@ -102,17 +102,29 @@ function cardEl(card, phaseId) {
102
102
  c.appendChild(m);
103
103
  }
104
104
  const news = cardNews(card, phaseId);
105
- if (news) c.appendChild(el("div", news === "drifted" ? "news drifted" : "news", news));
105
+ if (news) c.appendChild(el("div", news === "drifted" ? "news drifted" : phaseId === "plan" && card.planned ? "news change" : "news", news));
106
106
  return c;
107
107
  }
108
108
 
109
109
  function renderStage(host, phase) {
110
110
  host.replaceChildren();
111
+ host.classList.toggle("planning", !!phase.plan);
111
112
  for (const box of phase.boxes) {
112
113
  const b = el("section", `t-box${box.stock ? " stock" : ""}${box.spawned ? " spawned" : ""}`);
113
114
  b.dataset.box = box.id;
114
115
  const head = el("div", "t-box-head");
115
116
  head.append(el("h3", null, box.id), el("span", null, `${boxSubtitle(box)} · ${box.cards.length}`));
117
+ const badges = planBadges(box);
118
+ if (badges.length) {
119
+ const row = el("div", "t-badges");
120
+ for (const bd of badges) {
121
+ const chip = el("span", `t-badge ${bd.kind}`, bd.text);
122
+ chip.title = bd.tip;
123
+ row.appendChild(chip);
124
+ }
125
+ if (box.plan && box.plan.group) row.appendChild(el("span", "t-badge group", `group ${box.plan.group}`));
126
+ head.appendChild(row);
127
+ }
116
128
  const cards = el("div", "t-cards");
117
129
  for (const card of box.cards) cards.appendChild(cardEl(card, phase.id));
118
130
  b.append(head, cards);
@@ -120,6 +132,77 @@ function renderStage(host, phase) {
120
132
  }
121
133
  }
122
134
 
135
+ const SVGNS = "http://www.w3.org/2000/svg";
136
+
137
+ /**
138
+ * The plan's overlay on the stage: a bracket under the boxes of each folded
139
+ * group, with its one change, and an edge from the box that plans an output
140
+ * to each box that reads it. In one row (wide screens) the edges arc over the
141
+ * boxes and the bracket runs under them; stacked (a phone) both run down the
142
+ * gutters beside the boxes.
143
+ */
144
+ function drawPlanOverlay(stage, phase) {
145
+ const old = stage.querySelector(".t-overlay");
146
+ if (old) old.remove();
147
+ if (!phase.plan) return;
148
+ const host = stage.getBoundingClientRect();
149
+ const rectOf = (id) => {
150
+ const n = stage.querySelector(`[data-box="${CSS.escape(id)}"]`);
151
+ if (!n) return null;
152
+ const r = n.getBoundingClientRect();
153
+ return { left: r.left - host.left, top: r.top - host.top, right: r.right - host.left, bottom: r.bottom - host.top, width: r.width, height: r.height };
154
+ };
155
+ const svg = document.createElementNS(SVGNS, "svg");
156
+ svg.setAttribute("class", "t-overlay");
157
+ svg.setAttribute("width", String(host.width));
158
+ svg.setAttribute("height", String(host.height));
159
+ svg.setAttribute("aria-hidden", "true");
160
+ const add = (tag, attrs, text) => {
161
+ const n = document.createElementNS(SVGNS, tag);
162
+ for (const [k, v] of Object.entries(attrs)) n.setAttribute(k, String(v));
163
+ if (text != null) n.textContent = text;
164
+ svg.appendChild(n);
165
+ return n;
166
+ };
167
+ const all = phase.boxes.map((b) => rectOf(b.id)).filter(Boolean);
168
+ const row = oneRow(all);
169
+ for (const o of phase.plan.outputs) {
170
+ const from = o.root && rectOf(o.root);
171
+ if (!from) continue;
172
+ const readers = o.readers.map(rectOf).filter(Boolean);
173
+ readers.forEach((to, i) => {
174
+ if (row) {
175
+ const x0 = from.left + from.width * 0.45 + i * 18, y0 = from.top;
176
+ const x1 = to.left + 26, y1 = to.top;
177
+ const lift = 14 + i * 11;
178
+ add("path", { class: "t-edge", d: `M${x0},${y0} C${x0},${y0 - lift} ${x1},${y1 - lift} ${x1},${y1}` });
179
+ add("polygon", { class: "t-edge-head", points: `${x1 - 4},${y1 - 7} ${x1 + 4},${y1 - 7} ${x1},${y1}` });
180
+ } else {
181
+ const gx = 6, y0 = from.bottom - 14, y1 = to.top + 20;
182
+ add("path", { class: "t-edge", d: `M${from.left},${y0} H${gx} V${y1} H${to.left}` });
183
+ add("polygon", { class: "t-edge-head", points: `${to.left - 7},${y1 - 4} ${to.left - 7},${y1 + 4} ${to.left},${y1}` });
184
+ }
185
+ });
186
+ const label = outputLabel(o);
187
+ if (row) add("text", { class: "t-edge-label", x: from.left + 4, y: from.top - 0.75 * (14 + (readers.length - 1) * 11) - 8 }, label);
188
+ else add("text", { class: "t-edge-label", x: from.left + 2, y: from.bottom + 14 }, label);
189
+ }
190
+ for (const g of phase.plan.groups) {
191
+ const rs = g.members.map(rectOf).filter(Boolean);
192
+ if (!rs.length) continue;
193
+ const label = groupLabel(g);
194
+ if (row) {
195
+ const left = Math.min(...rs.map((r) => r.left)), right = Math.max(...rs.map((r) => r.right)), y = Math.max(...rs.map((r) => r.bottom)) + 10;
196
+ add("path", { class: "t-bracket", d: `M${left + 4},${y - 6} V${y} H${right - 4} V${y - 6}` });
197
+ add("text", { class: "t-bracket-label", x: (left + right) / 2, y: y + 18, "text-anchor": "middle" }, label);
198
+ } else {
199
+ const x = host.width - 7, top = Math.min(...rs.map((r) => r.top)) + 6, bottom = Math.max(...rs.map((r) => r.bottom)) - 6;
200
+ add("path", { class: "t-bracket", d: `M${x - 6},${top} H${x} V${bottom} H${x - 6}` });
201
+ }
202
+ }
203
+ stage.appendChild(svg);
204
+ }
205
+
123
206
  /** Where every card and box is now, by id. */
124
207
  function measure(root) {
125
208
  const at = new Map();
@@ -163,6 +246,9 @@ export function startTerralith(doc) {
163
246
  const next = doc.getElementById("t-next");
164
247
  const stage = doc.getElementById("t-stage");
165
248
  const notes = doc.getElementById("t-notes");
249
+ const groups = doc.getElementById("t-groups");
250
+ let lastShown = null;
251
+ addEventListener("resize", () => lastShown && drawPlanOverlay(stage, lastShown));
166
252
  let model = null;
167
253
  let shownId = null;
168
254
  let lastKey = "";
@@ -181,6 +267,10 @@ export function startTerralith(doc) {
181
267
  setUrl(phase.id);
182
268
  renderLead(lead, phase);
183
269
  renderStage(stage, phase);
270
+ groups.replaceChildren(...((phase.plan && phase.plan.groups) || []).map((g) => el("p", "t-group", `Group ${g.id}: ${groupLabel(g)}`)));
271
+ groups.hidden = !(phase.plan && phase.plan.groups.length);
272
+ drawPlanOverlay(stage, phase);
273
+ lastShown = phase;
184
274
  notes.hidden = !phase.notes.length;
185
275
  notes.textContent = phase.notes.length ? `Some files could not be read: ${phase.notes.join("; ")}` : "";
186
276
  play(stage, before);