@intentius/behold 0.30.2 → 0.32.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.
Files changed (102) hide show
  1. package/AGENTS.md +791 -16
  2. package/README.md +78 -23
  3. package/THIRD_PARTY.md +6 -5
  4. package/demos.json +14 -9
  5. package/dist/cli.js +51926 -20221
  6. package/example-carve/README.md +19 -23
  7. package/example-carve/app/package.json +1 -1
  8. package/example-carve/app/src/carved.ts +3 -3
  9. package/example-carve/carve-report.json +1 -1
  10. package/example-carve/{legacy-tf → tf-root}/terraform.tfstate +1 -1
  11. package/example-choudoufu-estate/README.md +7 -0
  12. package/example-choudoufu-estate/chant.workspace.json +1 -1
  13. package/example-choudoufu-estate/scripts/choudoufu-down.sh +2 -1
  14. package/example-choudoufu-estate/scripts/choudoufu-up.sh +10 -3
  15. package/example-terraform-estate/README.md +32 -5
  16. package/example-terraform-estate/chant.workspace.json +1 -1
  17. package/example-terraform-estate/recorded/adoption/platform.json +72 -0
  18. package/example-terraform-estate/recorded/adoption/prod.json +224 -0
  19. package/example-three-cloud/README.md +111 -18
  20. package/example-three-cloud/aws/Pulumi.yaml +15 -0
  21. package/example-three-cloud/aws/index.ts +174 -0
  22. package/example-three-cloud/aws/package-lock.json +2725 -0
  23. package/example-three-cloud/aws/package.json +14 -0
  24. package/example-three-cloud/aws/tsconfig.json +17 -0
  25. package/example-three-cloud/azure/main.tf +48 -0
  26. package/example-three-cloud/azure/site.tf +104 -0
  27. package/example-three-cloud/chant.config.json +9 -0
  28. package/example-three-cloud/chant.workspace.json +30 -4
  29. package/example-three-cloud/dns/chant.config.ts +26 -1
  30. package/example-three-cloud/dns/src/records.component.ts +32 -6
  31. package/example-three-cloud/package-lock.json +48 -27
  32. package/example-three-cloud/package.json +8 -6
  33. package/example-three-cloud/scripts/emulators-up.sh +28 -1
  34. package/example-three-cloud/scripts/front-door.ts +679 -86
  35. package/package.json +26 -8
  36. package/schemas/graph/v1/graph.schema.json +140 -0
  37. package/web/adopt-pulumi.js +114 -0
  38. package/web/adopt-pulumi.test.js +28 -0
  39. package/web/adopt.js +203 -0
  40. package/web/adopt.test.js +27 -0
  41. package/web/app.js +367 -14
  42. package/web/boot-motion.js +6 -0
  43. package/web/carve-steps.js +1 -1
  44. package/web/carve-steps.test.js +2 -2
  45. package/web/change-set-overlay.js +12 -5
  46. package/web/change-set-overlay.test.js +22 -0
  47. package/web/cut-around.d.ts +30 -0
  48. package/web/cut-around.js +138 -0
  49. package/web/drift-stream.js +241 -0
  50. package/web/drift-stream.test.js +146 -0
  51. package/web/edge-weight.d.ts +8 -2
  52. package/web/edge-weight.js +38 -4
  53. package/web/edge-weight.test.js +55 -1
  54. package/web/graph-query.js +180 -0
  55. package/web/graph-query.test.js +49 -0
  56. package/web/graph.html +107 -0
  57. package/web/index-diff.js +109 -0
  58. package/web/index-diff.test.js +39 -0
  59. package/web/index.html +45 -20
  60. package/web/kiosk-ask-tips.js +15 -5
  61. package/web/kiosk-ask-tips.test.js +14 -1
  62. package/web/kiosk-estate-scene.js +72 -8
  63. package/web/kiosk-light-frame.js +1 -0
  64. package/web/kiosk-light.js +41 -3
  65. package/web/kiosk-member-kind.test.js +140 -0
  66. package/web/kiosk-popover.js +4 -1
  67. package/web/kiosk-side.js +296 -0
  68. package/web/kiosk-side.test.js +249 -0
  69. package/web/kiosk-watch.js +12 -0
  70. package/web/kiosk-watch.test.js +15 -1
  71. package/web/kiosk.html +47 -1
  72. package/web/kiosk.js +106 -7
  73. package/web/member-kind.js +31 -0
  74. package/web/neighbourhood.js +105 -0
  75. package/web/neighbourhood.test.js +131 -0
  76. package/web/outside-refs.js +515 -0
  77. package/web/outside-refs.test.js +249 -0
  78. package/web/template-apps.js +245 -0
  79. package/web/template-apps.test.js +252 -0
  80. package/web/templates.js +285 -0
  81. package/web/templates.test.js +155 -0
  82. package/web/terragucci-lifecycle.js +112 -62
  83. package/web/terragucci-lifecycle.test.js +29 -1
  84. package/web/terragucci-timeline.js +39 -2
  85. package/web/terragucci-timeline.test.js +42 -1
  86. package/web/theme-paint.js +14 -0
  87. package/example-three-cloud/aws/chant.config.ts +0 -8
  88. package/example-three-cloud/aws/site.component.ts +0 -13
  89. package/example-three-cloud/aws/src/site.ts +0 -27
  90. package/example-three-cloud/azure/chant.config.ts +0 -1
  91. package/example-three-cloud/azure/src/site.component.ts +0 -13
  92. package/example-three-cloud/azure/src/site.ts +0 -18
  93. /package/example-carve/{legacy-tf → tf-root}/cdn.tf +0 -0
  94. /package/example-carve/{legacy-tf → tf-root}/compute.tf +0 -0
  95. /package/example-carve/{legacy-tf → tf-root}/floci-override.tf.disabled +0 -0
  96. /package/example-carve/{legacy-tf → tf-root}/modules/cdn/main.tf +0 -0
  97. /package/example-carve/{legacy-tf → tf-root}/naming.tf +0 -0
  98. /package/example-carve/{legacy-tf → tf-root}/network.tf +0 -0
  99. /package/example-carve/{legacy-tf → tf-root}/observability.tf +0 -0
  100. /package/example-carve/{legacy-tf → tf-root}/outputs.tf +0 -0
  101. /package/example-carve/{legacy-tf → tf-root}/storage.tf +0 -0
  102. /package/example-carve/{legacy-tf → tf-root}/versions.tf +0 -0
@@ -9,6 +9,17 @@
9
9
  // put together. Plumbing that more than two cards share (one role for half
10
10
  // the estate) says nothing at all, so it draws no edge.
11
11
  //
12
+ // An edge chant derived (`origin: "derived"` with the `rule` that drew it,
13
+ // chant#4522/#4523, behold#1030) is a match chant made, not a declaration, so
14
+ // it weighs as an inferred one does.
15
+ //
16
+ // behold#1080: a catalog rule chant drew an edge by (chant#5097) is an exact
17
+ // match, not a guess, so it is "joined" and apart from "inferred", with the
18
+ // rule in its tooltip. A reference that names no node is drawn to a dashed
19
+ // placeholder card ("dangling"), and one that names several gets a dotted edge
20
+ // to each candidate ("ambiguous"). src/catalog-draw.ts adds the card and the
21
+ // edges and marks them (`dangling: true`, `ambiguous: { of, rule, value }`).
22
+ //
12
23
  // Only references are weighed: a CI edge (needs, calls, triggers, …) keeps its
13
24
  // own kind's style (./edge-kind.js).
14
25
 
@@ -16,10 +27,30 @@
16
27
  export const WEIGHTS = {
17
28
  wired: "wired: the traffic path",
18
29
  reference: "reference: names another",
30
+ joined: "joined: exact match by rule",
19
31
  inferred: "inferred: matched by name",
20
32
  plumbing: "plumbing: identity, keys, logs",
33
+ dangling: "dangling: names nothing declared (dashed card)",
34
+ ambiguous: "ambiguous: one of several candidates (dotted)",
21
35
  };
22
36
 
37
+ /** The weights chant's catalog adds. A key with one of these is worth a row when it is the only weight drawn. */
38
+ export const CATALOG_WEIGHTS = ["joined", "dangling", "ambiguous"];
39
+
40
+ /** The rules that drew an edge that is neither a behold pass nor chant's identity-match pass. */
41
+ const NOT_CATALOG_RULE = /^(behold:|identity-match:)/;
42
+
43
+ /**
44
+ * Whether an edge was drawn by a catalog rule. `rules` is the catalog's rule
45
+ * table (ids as keys) when the graph has one; without it, an edge chant stamped
46
+ * with a `relation` (chant#5097 gives every catalog edge one) counts.
47
+ */
48
+ export function isCatalogEdge(e, rules) {
49
+ if (e.origin !== "derived" || typeof e.rule !== "string" || !e.rule || NOT_CATALOG_RULE.test(e.rule)) return false;
50
+ if (rules && Object.keys(rules).length) return Object.prototype.hasOwnProperty.call(rules, e.rule);
51
+ return typeof e.relation === "string";
52
+ }
53
+
23
54
  /** Kinds whose incoming references are plumbing, not traffic. */
24
55
  const PLUMBING_KIND = /(::IAM::|::Iam::|::KMS::|::Kms::|::Logs::|::SecretsManager::|::SecretManager::|::SSM::|ManagedIdentity\/|OperationalInsights\/|KeyVault\/|Microsoft\.Authorization\/|::Logging::|::Monitoring::|::CloudWatch::Alarm)/;
25
56
 
@@ -35,7 +66,7 @@ export function isWired(e) {
35
66
  * The weight of each reference edge, keyed `from→to`. `kindOf` maps a node id
36
67
  * to its kind. A CI edge gets no entry.
37
68
  */
38
- export function edgeWeights(edges = [], kindOf = new Map()) {
69
+ export function edgeWeights(edges = [], kindOf = new Map(), rules = undefined) {
39
70
  const out = new Map();
40
71
  const plumbing = (e) => PLUMBING_KIND.test(kindOf.get(e.to) || "") || PLUMBING_KIND.test(kindOf.get(e.from) || "");
41
72
  const sharers = new Map();
@@ -49,10 +80,13 @@ export function edgeWeights(edges = [], kindOf = new Map()) {
49
80
  for (const e of edges) {
50
81
  if (e.kind && e.kind !== "ref") continue;
51
82
  let w;
52
- if (plumbing(e)) {
83
+ if (e.ambiguous) w = "ambiguous";
84
+ else if (e.dangling === true) w = "dangling";
85
+ else if (plumbing(e)) {
53
86
  const hub = PLUMBING_KIND.test(kindOf.get(e.to) || "") ? e.to : e.from;
54
87
  w = (sharers.get(hub)?.size ?? 0) > 2 ? "hidden" : "plumbing";
55
- } else if (e.inferred) w = "inferred";
88
+ } else if (isCatalogEdge(e, rules)) w = "joined";
89
+ else if (e.inferred || e.origin === "derived") w = "inferred";
56
90
  else if (isWired(e)) w = "wired";
57
91
  else w = "reference";
58
92
  out.set(`${e.from}→${e.to}`, w);
@@ -64,7 +98,7 @@ export function edgeWeights(edges = [], kindOf = new Map()) {
64
98
  export function weightLegend(weights) {
65
99
  const counts = new Map();
66
100
  for (const w of weights.values()) if (w !== "hidden") counts.set(w, (counts.get(w) || 0) + 1);
67
- if (counts.size < 2) return [];
101
+ if (counts.size < 2 && !CATALOG_WEIGHTS.some((w) => counts.has(w))) return [];
68
102
  return Object.keys(WEIGHTS)
69
103
  .filter((w) => counts.has(w))
70
104
  .map((w) => ({ weight: w, label: w, title: WEIGHTS[w], count: counts.get(w) }));
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect } from "vitest";
2
- import { edgeWeights, weightLegend } from "./edge-weight.js";
2
+ import { edgeWeights, weightLegend, WEIGHTS } from "./edge-weight.js";
3
3
 
4
4
  describe("edgeWeights (#878)", () => {
5
5
  const kindOf = new Map([
@@ -47,3 +47,57 @@ describe("edgeWeights (#878)", () => {
47
47
  expect(weightLegend(new Map([["x→y", "reference"]]))).toEqual([]);
48
48
  });
49
49
  });
50
+
51
+ describe("edgeWeights over chant's derived edges (behold#1030)", () => {
52
+ it("weighs an edge chant derived as inferred, as the matcher's were", () => {
53
+ const kindOf = new Map([
54
+ ["db", "AWS::RDS::DBInstance"],
55
+ ["group", "AWS::RDS::DBSubnetGroup"],
56
+ ]);
57
+ const w = edgeWeights(
58
+ [{ from: "db", to: "group", kind: "ref", viaAttr: "DBSubnetGroupName", origin: "derived", rule: "aws:AWS::RDS::DBInstance:DBSubnetGroupName" }],
59
+ kindOf,
60
+ );
61
+ expect(w.get("db→group")).toBe("inferred");
62
+ });
63
+
64
+ it("keeps a declared edge a reference", () => {
65
+ const w = edgeWeights([{ from: "db", to: "group", kind: "ref", viaAttr: "DBSubnetGroupName", origin: "declared" }], new Map());
66
+ expect(w.get("db→group")).toBe("reference");
67
+ });
68
+ });
69
+
70
+ describe("edgeWeights over chant's catalog (behold#1080)", () => {
71
+ const rules = { "k8s:K8s::Apps::Deployment:spec.template.spec.serviceAccountName": { label: "runs as", relation: "reference" } };
72
+ const joined = { from: "app/web", to: "app/runner", kind: "ref", viaAttr: "spec", origin: "derived", rule: "k8s:K8s::Apps::Deployment:spec.template.spec.serviceAccountName", relation: "reference" };
73
+
74
+ it("weighs an edge with a catalog rule as joined, apart from inferred", () => {
75
+ const guess = { from: "a", to: "b", kind: "ref", origin: "derived", rule: "identity-match:name" };
76
+ const w = edgeWeights([joined, guess], new Map(), rules);
77
+ expect(w.get("app/web→app/runner")).toBe("joined");
78
+ expect(w.get("a→b")).toBe("inferred");
79
+ });
80
+
81
+ it("reads a catalog edge by its relation when the graph carries no rule table", () => {
82
+ expect(edgeWeights([joined], new Map()).get("app/web→app/runner")).toBe("joined");
83
+ expect(edgeWeights([{ ...joined, relation: undefined }], new Map()).get("app/web→app/runner")).toBe("inferred");
84
+ });
85
+
86
+ it("weighs the edge to a placeholder dangling and each edge of an ambiguous reference ambiguous", () => {
87
+ const w = edgeWeights(
88
+ [
89
+ { from: "h", to: "dangling:x", kind: "ref", dangling: true, rule: "r" },
90
+ { from: "h", to: "c1", kind: "ref", ambiguous: { of: 2, rule: "r", value: "v" }, rule: "r" },
91
+ { from: "h", to: "c2", kind: "ref", ambiguous: { of: 2, rule: "r", value: "v" }, rule: "r" },
92
+ ],
93
+ new Map(),
94
+ );
95
+ expect([...w.values()]).toEqual(["dangling", "ambiguous", "ambiguous"]);
96
+ });
97
+
98
+ it("gives each its legend row even when it is the only weight drawn", () => {
99
+ expect(weightLegend(new Map([["a→b", "joined"]])).map((r) => [r.weight, r.title, r.count])).toEqual([["joined", WEIGHTS.joined, 1]]);
100
+ expect(weightLegend(new Map([["a→b", "dangling"], ["c→d", "ambiguous"], ["c→e", "ambiguous"]])).map((r) => [r.weight, r.count])).toEqual([["dangling", 1], ["ambiguous", 2]]);
101
+ expect(WEIGHTS.joined).toBe("joined: exact match by rule");
102
+ });
103
+ });
@@ -0,0 +1,180 @@
1
+ /**
2
+ * behold#1027: the graph pane's page logic (web/graph.html).
3
+ *
4
+ * A Cypher box over GET /api/graphdb/query, a resolve box over
5
+ * GET /api/graphdb/resolve with the templates that apply to the node it lands
6
+ * on, and a small drawing of each answer: its nodes and the REF edges among
7
+ * them, derived edges dashed and labelled with their rule. Every answer shows
8
+ * when each source was read. The page only reads: every request it makes is a
9
+ * GET.
10
+ *
11
+ * The pure helpers are exported for web/graph-query.test.js; `initGraphPane`
12
+ * wires them to the page.
13
+ */
14
+
15
+ /** The route URL for a Cypher query and its parameters. */
16
+ export function queryUrl(cypher, params) {
17
+ const q = new URLSearchParams({ cypher });
18
+ if (params && Object.keys(params).length) q.set("params", JSON.stringify(params));
19
+ return `/api/graphdb/query?${q}`;
20
+ }
21
+
22
+ /** The route URL for resolving a resource. */
23
+ export function resolveUrl(ref) {
24
+ return `/api/graphdb/resolve?${new URLSearchParams({ ref })}`;
25
+ }
26
+
27
+ /** The route URL for one template on one node. */
28
+ export function templateUrl(name, node, inputs = {}) {
29
+ const q = new URLSearchParams({ name, node });
30
+ for (const [k, v] of Object.entries(inputs)) q.set(`in.${k}`, v);
31
+ return `/api/graphdb/template?${q}`;
32
+ }
33
+
34
+ /** One line per source: what it is and when it was read ("declared" when nothing was read live). */
35
+ export function sourceLines(sources) {
36
+ return (sources ?? []).map((s) => {
37
+ const what = `${s.member ? `${s.member}: ` : ""}${s.name}${s.version ? ` ${s.version}` : ""} (${s.source}, ${s.scopeKey})`;
38
+ const when = s.observedAt ? `observed ${s.observedAt}` : "declared source, not observed";
39
+ return `${what}: ${when}; loaded ${s.readAt}; ${s.nodes} nodes, ${s.edges} edges`;
40
+ });
41
+ }
42
+
43
+ /** Node positions on a circle, in answer order; small answers get a readable radius. */
44
+ export function circleLayout(nodes, size = 520) {
45
+ const n = nodes.length;
46
+ const r = n <= 1 ? 0 : Math.min(size / 2 - 60, 40 + n * 14);
47
+ const c = size / 2;
48
+ const at = {};
49
+ nodes.forEach((node, i) => {
50
+ const a = (2 * Math.PI * i) / Math.max(n, 1) - Math.PI / 2;
51
+ at[node.key] = { x: Math.round(c + r * Math.cos(a)), y: Math.round(c + r * Math.sin(a)) };
52
+ });
53
+ return at;
54
+ }
55
+
56
+ const esc = (s) => String(s).replace(/[&<>"']/g, (ch) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[ch]);
57
+
58
+ /** The answer's drawing as SVG text. */
59
+ export function drawSvg(draw, size = 520) {
60
+ const nodes = draw?.nodes ?? [];
61
+ if (!nodes.length) return "";
62
+ const at = circleLayout(nodes, size);
63
+ const edges = (draw.edges ?? [])
64
+ .filter((e) => at[e.from] && at[e.to])
65
+ .map((e) => {
66
+ const a = at[e.from];
67
+ const b = at[e.to];
68
+ const derived = e.origin === "derived";
69
+ const title = `${e.from} -> ${e.to}${e.viaAttr ? ` via ${e.viaAttr}` : ""}${derived ? ` (derived: ${e.rule})` : ""}`;
70
+ return `<line class="g-edge${derived ? " derived" : ""}" x1="${a.x}" y1="${a.y}" x2="${b.x}" y2="${b.y}" marker-end="url(#g-arrow)"><title>${esc(title)}</title></line>`;
71
+ })
72
+ .join("");
73
+ const dots = nodes
74
+ .map((n) => {
75
+ const p = at[n.key];
76
+ const label = n.name || n.key;
77
+ return `<g class="g-node ${esc(n.source)}"><circle cx="${p.x}" cy="${p.y}" r="7"><title>${esc(`${n.key} (${n.kind}, ${n.scopeKey})`)}</title></circle><text x="${p.x + 10}" y="${p.y + 4}">${esc(label.length > 32 ? `${label.slice(0, 29)}...` : label)}</text></g>`;
78
+ })
79
+ .join("");
80
+ return `<svg viewBox="0 0 ${size} ${size}" role="img" aria-label="answer graph"><defs><marker id="g-arrow" viewBox="0 0 10 10" refX="16" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0,0 L10,5 L0,10 z" class="g-arrowhead"/></marker></defs>${edges}${dots}</svg>`;
81
+ }
82
+
83
+ /** A table of the answer's rows as HTML text. */
84
+ export function rowsTable(columns, rows) {
85
+ if (!rows?.length) return "<p class=\"g-muted\">No rows.</p>";
86
+ const cell = (v) => esc(typeof v === "string" ? v : JSON.stringify(v));
87
+ const head = columns.map((c) => `<th>${esc(c)}</th>`).join("");
88
+ const body = rows.map((r) => `<tr>${columns.map((c) => `<td>${cell(r[c])}</td>`).join("")}</tr>`).join("");
89
+ return `<table><thead><tr>${head}</tr></thead><tbody>${body}</tbody></table>`;
90
+ }
91
+
92
+ /** The refusal text a failed answer shows: the error, and the install line when the peer is missing. */
93
+ export function refusalText(body) {
94
+ if (!body) return "No answer.";
95
+ const lines = [body.error ?? "Refused."];
96
+ if (body.code === "graph-peer-missing") lines.push(`Install: ${body.install}`, ...(body.stillWorks ?? []).map((w) => `Still works: ${w}`));
97
+ else if (body.remedy) lines.push(body.remedy);
98
+ return lines.join("\n");
99
+ }
100
+
101
+ /* c8 ignore start: the DOM half, driven by the page */
102
+ export function initGraphPane(doc = document, fetchJson = (u) => fetch(u, { headers: { accept: "application/json" } }).then(async (r) => ({ status: r.status, body: await r.json().catch(() => ({})) }))) {
103
+ const $ = (id) => doc.getElementById(id);
104
+ const show = (answer) => {
105
+ const { status, body } = answer;
106
+ $("g-error").textContent = status === 200 ? "" : refusalText(body);
107
+ $("g-draw").innerHTML = status === 200 ? drawSvg(body.draw) : "";
108
+ $("g-rows").innerHTML = status === 200 && body.columns ? rowsTable(body.columns, body.rows) : "";
109
+ $("g-sources").textContent = sourceLines(body.sources).join("\n");
110
+ const link = $("g-link");
111
+ if (status === 200 && body.link) {
112
+ link.href = body.link;
113
+ link.hidden = false;
114
+ } else link.hidden = true;
115
+ };
116
+ const status = async () => {
117
+ const s = await fetchJson("/api/graphdb");
118
+ if (s.status !== 200) return show(s);
119
+ const peer = s.body.peer;
120
+ $("g-peer").textContent = peer?.available ? `LadybugDB ${peer.version ?? ""}`.trim() : refusalText(peer?.refusal);
121
+ $("g-counts").textContent = `${s.body.counts.resources} resources, ${s.body.counts.refs} edges (${s.body.counts.derived} derived), ${s.body.counts.cloudIds} cloud ids`;
122
+ $("g-sources").textContent = sourceLines(s.body.sources).join("\n");
123
+ $("g-notes").textContent = (s.body.notes ?? []).join("\n");
124
+ };
125
+ $("g-cypher-form").addEventListener("submit", async (ev) => {
126
+ ev.preventDefault();
127
+ let params;
128
+ const raw = $("g-params").value.trim();
129
+ if (raw) {
130
+ try {
131
+ params = JSON.parse(raw);
132
+ } catch {
133
+ $("g-error").textContent = "Parameters are a JSON object.";
134
+ return;
135
+ }
136
+ }
137
+ show(await fetchJson(queryUrl($("g-cypher").value, params)));
138
+ });
139
+ $("g-resolve-form").addEventListener("submit", async (ev) => {
140
+ ev.preventDefault();
141
+ const r = await fetchJson(resolveUrl($("g-ref").value));
142
+ show(r);
143
+ const list = $("g-candidates");
144
+ list.innerHTML = "";
145
+ if (r.status !== 200) return;
146
+ for (const c of r.body.candidates) {
147
+ const li = doc.createElement("li");
148
+ li.textContent = `${c.key} (${c.kind}, ${c.source}, matched by ${c.matchedBy})`;
149
+ list.append(li);
150
+ }
151
+ const menu = $("g-templates");
152
+ menu.innerHTML = "";
153
+ const node = r.body.resolved ? r.body.candidates[0].key : null;
154
+ for (const t of r.body.templates ?? []) {
155
+ const b = doc.createElement("button");
156
+ b.type = "button";
157
+ b.textContent = `${t.title}${t.language === "cypher" ? " (Cypher)" : ""}`;
158
+ b.disabled = !t.available;
159
+ if (!t.available) b.title = `${t.refusal} ${t.install}`;
160
+ b.addEventListener("click", async () => {
161
+ const inputs = {};
162
+ for (const i of t.inputs) {
163
+ const v = globalThis.prompt?.(`${t.title}: ${i.description}`);
164
+ if (!v) return;
165
+ inputs[i.name] = v;
166
+ }
167
+ const a = await fetchJson(templateUrl(t.name, node, inputs));
168
+ if (a.status === 200 && a.body.search) {
169
+ // A search template draws in behold's own view, through the q key.
170
+ globalThis.location.href = a.body.link;
171
+ return;
172
+ }
173
+ show(a);
174
+ });
175
+ menu.append(b);
176
+ }
177
+ });
178
+ status();
179
+ }
180
+ /* c8 ignore stop */
@@ -0,0 +1,49 @@
1
+ // behold#1027: the graph pane page's pure helpers.
2
+ import { describe, expect, it } from "vitest";
3
+ import { circleLayout, drawSvg, queryUrl, refusalText, resolveUrl, rowsTable, sourceLines, templateUrl } from "./graph-query.js";
4
+
5
+ describe("the routes the page asks", () => {
6
+ it("are GETs with the query in the URL", () => {
7
+ expect(queryUrl("MATCH (r) RETURN r", { k: "x" })).toBe(`/api/graphdb/query?${new URLSearchParams({ cypher: "MATCH (r) RETURN r", params: '{"k":"x"}' })}`);
8
+ expect(queryUrl("MATCH (r) RETURN r")).not.toContain("params");
9
+ expect(resolveUrl("arn:aws:s3:::b")).toBe("/api/graphdb/resolve?ref=arn%3Aaws%3As3%3A%3A%3Ab");
10
+ expect(templateUrl("paths-to-kind", "web/a", { kind: "aws_vpc" })).toBe("/api/graphdb/template?name=paths-to-kind&node=web%2Fa&in.kind=aws_vpc");
11
+ });
12
+ });
13
+
14
+ describe("what an answer shows", () => {
15
+ it("one line per source, saying when it was observed or that it is declared", () => {
16
+ const lines = sourceLines([
17
+ { scopeKey: "chant/web", source: "chant", name: "chant", member: "web", observedAt: null, readAt: "r", nodes: 2, edges: 1 },
18
+ { scopeKey: "engine/choudoufu/web", source: "engine", name: "choudoufu", version: "0.33.0", observedAt: "2026-10-26T12:00:00Z", readAt: "r", nodes: 6, edges: 2 },
19
+ ]);
20
+ expect(lines[0]).toMatch(/^web: chant .*declared source, not observed/);
21
+ expect(lines[1]).toMatch(/choudoufu 0.33.0 .*observed 2026-10-26T12:00:00Z/);
22
+ });
23
+
24
+ it("draws nodes and the edges among them, derived edges dashed with their rule", () => {
25
+ const svg = drawSvg({
26
+ nodes: [
27
+ { key: "a", kind: "k", name: "a", source: "chant", scopeKey: "chant/x" },
28
+ { key: "b", kind: "k", name: "b", source: "engine", scopeKey: "engine/y" },
29
+ ],
30
+ edges: [{ from: "a", to: "b", viaAttr: "arn", origin: "derived", rule: "identity:arn" }],
31
+ });
32
+ expect(svg).toContain('class="g-edge derived"');
33
+ expect(svg).toContain("identity:arn");
34
+ expect(svg.match(/<circle/g)).toHaveLength(2);
35
+ expect(drawSvg({ nodes: [], edges: [] })).toBe("");
36
+ expect(Object.keys(circleLayout([{ key: "a" }, { key: "b" }, { key: "c" }]))).toEqual(["a", "b", "c"]);
37
+ });
38
+
39
+ it("escapes what it draws", () => {
40
+ expect(rowsTable(["k"], [{ k: "<script>" }])).toContain("&lt;script&gt;");
41
+ expect(drawSvg({ nodes: [{ key: "<x>", kind: "k", name: "<x>", source: "chant", scopeKey: "s" }], edges: [] })).not.toContain("<x>");
42
+ });
43
+
44
+ it("a refusal without the peer shows the install line and what still works", () => {
45
+ const t = refusalText({ error: "needs the peer", code: "graph-peer-missing", install: "npm i -g @ladybugdb/core", stillWorks: ["chant search"] });
46
+ expect(t).toContain("Install: npm i -g @ladybugdb/core");
47
+ expect(t).toContain("Still works: chant search");
48
+ });
49
+ });
package/web/graph.html ADDED
@@ -0,0 +1,107 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>behold · graph</title>
7
+ <style>
8
+ /* behold#1027: the graph pane. Box's tokens (theme.js KIOSK_THEME) as the fallback, as terralith.html does. */
9
+ :root {
10
+ --bg: #141d2b; --panel: #213027; --line: #2e3d2a; --fg: #9fef00; --muted: #7d9e5a; --edge: #40601d;
11
+ --managed: #19cb00; --foreign: #cecb00; --pending: #0d73cc; --degraded: #cc0403; --runtime: #0dcdcd;
12
+ --well: #070f1c; --surface-box: #20242a; --surface-pane-a: #262a30;
13
+ --font-ui: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
14
+ --font-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
15
+ }
16
+ @media (prefers-color-scheme: light) {
17
+ :root { --bg: #f6f7f4; --panel: #ffffff; --line: #d5dacb; --fg: #1d2a12; --muted: #5d6b4f; --edge: #8aa06a; --well: #eef1e8; --surface-box: #ffffff; --surface-pane-a: #f0f2ec; }
18
+ }
19
+ * { box-sizing: border-box; }
20
+ html, body { margin: 0; background: var(--bg); color: var(--fg); font: 14px/1.45 var(--font-ui); }
21
+ main { max-width: 1400px; margin: 0 auto; padding: 16px; display: grid; gap: 14px; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); }
22
+ @media (max-width: 900px) { main { grid-template-columns: minmax(0, 1fr); } }
23
+ header { grid-column: 1 / -1; display: flex; flex-wrap: wrap; gap: 8px 18px; align-items: baseline; }
24
+ h1 { font-size: 18px; margin: 0; }
25
+ section { background: var(--surface-pane-a); border-radius: 8px; padding: 12px 14px; min-width: 0; }
26
+ h2 { font-size: 14px; margin: 0 0 8px; }
27
+ textarea, input { width: 100%; background: var(--well); color: var(--fg); border: 1px solid var(--line); border-radius: 6px; padding: 8px; font: 13px/1.4 var(--font-mono); }
28
+ textarea { min-height: 7em; resize: vertical; }
29
+ button { background: var(--surface-box); color: var(--fg); border: 1px solid var(--line); border-radius: 6px; padding: 5px 10px; margin: 6px 6px 0 0; font: inherit; cursor: pointer; }
30
+ button:disabled { opacity: 0.5; cursor: not-allowed; }
31
+ pre { white-space: pre-wrap; font: 12px/1.4 var(--font-mono); margin: 6px 0 0; color: var(--muted); }
32
+ #g-error { color: var(--degraded); }
33
+ .g-muted { color: var(--muted); }
34
+ table { border-collapse: collapse; width: 100%; font: 12px/1.35 var(--font-mono); display: block; overflow-x: auto; }
35
+ th, td { border-bottom: 1px solid var(--line); padding: 4px 6px; text-align: left; vertical-align: top; }
36
+ svg { width: 100%; height: auto; max-height: 560px; }
37
+ .g-edge { stroke: var(--edge); stroke-width: 1.4; }
38
+ .g-edge.derived { stroke-dasharray: 5 4; stroke: var(--foreign); }
39
+ .g-arrowhead { fill: var(--edge); }
40
+ .g-node circle { fill: var(--managed); }
41
+ .g-node.engine circle { fill: var(--runtime); }
42
+ .g-node.index circle, .g-node.cloud circle { fill: var(--pending); }
43
+ .g-node text { fill: var(--fg); font: 11px var(--font-mono); }
44
+ /* behold#1028: the index diff overlay. Not observed is never drawn as removed. */
45
+ .g-node.d-added circle { fill: var(--managed); }
46
+ .g-node.d-removed circle { fill: var(--degraded); }
47
+ .g-node.d-changed circle { fill: var(--foreign); }
48
+ .g-node.d-not-observed circle { fill: none; stroke: var(--muted); stroke-dasharray: 3 2; }
49
+ .g-node.d-same circle { fill: var(--edge); }
50
+ .g-edge.d-added { stroke: var(--managed); }
51
+ .g-edge.d-removed { stroke: var(--degraded); }
52
+ .g-edge.d-not-observed { stroke: var(--muted); stroke-dasharray: 3 3; }
53
+ select { background: var(--well); color: var(--fg); border: 1px solid var(--line); border-radius: 6px; padding: 4px; font: 12px var(--font-mono); max-width: 100%; }
54
+ ul { margin: 6px 0 0; padding-left: 18px; font: 12px/1.4 var(--font-mono); }
55
+ a { color: var(--runtime); }
56
+ </style>
57
+ </head>
58
+ <body>
59
+ <main>
60
+ <header>
61
+ <h1>Graph</h1>
62
+ <span id="g-peer" class="g-muted"></span>
63
+ <span id="g-counts" class="g-muted"></span>
64
+ <a href="/">Back to the estate</a>
65
+ </header>
66
+ <section>
67
+ <h2>Cypher</h2>
68
+ <form id="g-cypher-form">
69
+ <textarea id="g-cypher" spellcheck="false" aria-label="Cypher query">MATCH (a:Resource)-[:KNOWN_AS]->(c:CloudId)&lt;-[:KNOWN_AS]-(b:Resource) WHERE a.scopeKey &lt;&gt; b.scopeKey RETURN a.key, b.key, c.value LIMIT 50</textarea>
70
+ <input id="g-params" placeholder='Parameters as JSON, such as {"k": "aws_s3_bucket"}' aria-label="Parameters" />
71
+ <button type="submit">Ask</button>
72
+ </form>
73
+ <h2 style="margin-top: 14px">Start from a resource</h2>
74
+ <form id="g-resolve-form">
75
+ <input id="g-ref" placeholder="A name, an IR id, a block address or a cloud id" aria-label="Resource" />
76
+ <button type="submit">Resolve</button>
77
+ </form>
78
+ <ul id="g-candidates"></ul>
79
+ <div id="g-templates"></div>
80
+ <pre id="g-error"></pre>
81
+ <h2 style="margin-top: 14px">What changed between two reads</h2>
82
+ <form id="d-form">
83
+ <label>Scope <select id="d-scope" aria-label="Index scope"></select></label>
84
+ <label>From <select id="d-from" aria-label="Earlier version"></select></label>
85
+ <label>To <select id="d-to" aria-label="Later version"></select></label>
86
+ <button type="submit">Diff</button>
87
+ </form>
88
+ <p id="d-hint" class="g-muted"></p>
89
+ <pre id="d-summary"></pre>
90
+ <h2 style="margin-top: 14px">Sources, and when each was read</h2>
91
+ <pre id="g-sources"></pre>
92
+ <pre id="g-notes"></pre>
93
+ </section>
94
+ <section>
95
+ <h2>Answer <a id="g-link" hidden>open in the estate view</a></h2>
96
+ <div id="g-draw"></div>
97
+ <div id="g-rows"></div>
98
+ </section>
99
+ </main>
100
+ <script type="module">
101
+ import { initGraphPane } from "./graph-query.js";
102
+ import { initIndexDiff } from "./index-diff.js";
103
+ initGraphPane();
104
+ initIndexDiff();
105
+ </script>
106
+ </body>
107
+ </html>
@@ -0,0 +1,109 @@
1
+ /**
2
+ * behold#1028: the index diff overlay on the graph pane (web/graph.html).
3
+ *
4
+ * Picks a scope and two of its versions from GET /api/graphdb/index-versions,
5
+ * asks GET /api/graphdb/index-diff, and draws the answer's overlay: added
6
+ * nodes and edges green, removed red, changed amber with the changed paths
7
+ * in the tooltip, and not-observed grey and dashed (an unobserved type is
8
+ * never drawn as removed). Both reads' stamps are shown above the drawing.
9
+ * Every request is a GET.
10
+ *
11
+ * The pure helpers are exported for web/index-diff.test.js.
12
+ */
13
+ import { circleLayout } from "./graph-query.js";
14
+
15
+ /** The diff route for a scope and two versions; empty arguments are left to the server's defaults. */
16
+ export function diffUrl(scope, from, to) {
17
+ const q = new URLSearchParams();
18
+ if (scope) q.set("scope", scope);
19
+ if (from) q.set("from", from);
20
+ if (to) q.set("to", to);
21
+ const s = q.toString();
22
+ return `/api/graphdb/index-diff${s ? `?${s}` : ""}`;
23
+ }
24
+
25
+ /** The two stamps and the counts, as lines. */
26
+ export function diffSummary(diff) {
27
+ if (!diff) return [];
28
+ const stamp = (s) => `${s.version ?? "?"}: observed ${s.observedAt}${s.completedAt ? ` to ${s.completedAt}` : ""}, digest ${String(s.digest).slice(0, 12)}`;
29
+ const c = diff.counts;
30
+ const lines = [`scope ${diff.scopeKey}`, `from ${stamp(diff.from)}`, `to ${stamp(diff.to)}`];
31
+ if (diff.unchanged) lines.push("unchanged: both reads have the same digest");
32
+ else {
33
+ lines.push(`${c.added} added, ${c.removed} removed, ${c.changed} changed (${c.properties} properties), ${c.notObserved} not observed in one read`);
34
+ lines.push(`edges: ${c.edgesAdded} added, ${c.edgesRemoved} removed, ${c.edgesNotObserved} not observed`);
35
+ }
36
+ for (const n of diff.nodes?.changed ?? []) for (const p of n.properties) lines.push(` ${n.key} ${p.path}: ${JSON.stringify(p.before)} -> ${JSON.stringify(p.after)}`);
37
+ for (const k of diff.coverage ?? []) lines.push(` coverage ${k.listedType} in ${k.location}: ${k.before ?? "absent"} -> ${k.after ?? "absent"}`);
38
+ return lines;
39
+ }
40
+
41
+ const esc = (s) => String(s).replace(/[&<>"']/g, (ch) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[ch]);
42
+
43
+ /** The overlay as SVG text. Each node and edge carries its change as a class: d-added, d-removed, d-changed, d-not-observed, d-same. */
44
+ export function drawOverlaySvg(draw, size = 520) {
45
+ const nodes = draw?.nodes ?? [];
46
+ if (!nodes.length) return "";
47
+ const at = circleLayout(nodes, size);
48
+ const edges = (draw.edges ?? [])
49
+ .filter((e) => at[e.from] && at[e.to])
50
+ .map((e) => {
51
+ const a = at[e.from];
52
+ const b = at[e.to];
53
+ return `<line class="g-edge d-${esc(e.change)}" x1="${a.x}" y1="${a.y}" x2="${b.x}" y2="${b.y}" marker-end="url(#g-arrow)"><title>${esc(`${e.from} -> ${e.to}${e.viaAttr ? ` via ${e.viaAttr}` : ""}: ${e.change}`)}</title></line>`;
54
+ })
55
+ .join("");
56
+ const dots = nodes
57
+ .map((n) => {
58
+ const p = at[n.key];
59
+ const label = n.name || n.key;
60
+ const title = `${n.key} (${n.kind}): ${n.change}${n.detail ? `, ${n.detail}` : ""}`;
61
+ return `<g class="g-node d-${esc(n.change)}"><circle cx="${p.x}" cy="${p.y}" r="7"><title>${esc(title)}</title></circle><text x="${p.x + 10}" y="${p.y + 4}">${esc(label.length > 32 ? `${label.slice(0, 29)}...` : label)}</text></g>`;
62
+ })
63
+ .join("");
64
+ return `<svg viewBox="0 0 ${size} ${size}" role="img" aria-label="index diff overlay"><defs><marker id="g-arrow" viewBox="0 0 10 10" refX="16" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0,0 L10,5 L0,10 z" class="g-arrowhead"/></marker></defs>${edges}${dots}</svg>`;
65
+ }
66
+
67
+ /* c8 ignore start: the DOM half, driven by the page */
68
+ export function initIndexDiff(doc = document, fetchJson = (u) => fetch(u, { headers: { accept: "application/json" } }).then(async (r) => ({ status: r.status, body: await r.json().catch(() => ({})) }))) {
69
+ const $ = (id) => doc.getElementById(id);
70
+ if (!$("d-form")) return;
71
+ let scopes = [];
72
+ const fill = (sel, items, pick) => {
73
+ sel.innerHTML = "";
74
+ for (const v of items) {
75
+ const o = doc.createElement("option");
76
+ o.value = v;
77
+ o.textContent = v;
78
+ sel.append(o);
79
+ }
80
+ if (pick !== undefined) sel.value = pick;
81
+ };
82
+ const versionsFor = () => {
83
+ const s = scopes.find((x) => x.scopeKey === $("d-scope").value);
84
+ const vs = (s?.versions ?? []).map((v) => v.version);
85
+ fill($("d-from"), vs, vs[vs.length - 2]);
86
+ fill($("d-to"), vs, vs[vs.length - 1]);
87
+ };
88
+ fetchJson("/api/graphdb/index-versions").then((r) => {
89
+ if (r.status !== 200) return;
90
+ scopes = r.body.scopes ?? [];
91
+ fill($("d-scope"), scopes.map((s) => s.scopeKey));
92
+ versionsFor();
93
+ $("d-hint").textContent = scopes.length ? "" : "No index versions yet: run behold index <substrate> twice on one scope.";
94
+ });
95
+ $("d-scope").addEventListener("change", versionsFor);
96
+ $("d-form").addEventListener("submit", async (ev) => {
97
+ ev.preventDefault();
98
+ const r = await fetchJson(diffUrl($("d-scope").value, $("d-from").value, $("d-to").value));
99
+ if (r.status !== 200) {
100
+ $("g-error").textContent = `${r.body.error ?? "Refused."}${r.body.code ? ` (${r.body.code})` : ""}`;
101
+ return;
102
+ }
103
+ $("g-error").textContent = "";
104
+ $("g-rows").innerHTML = "";
105
+ $("g-draw").innerHTML = drawOverlaySvg(r.body.draw);
106
+ $("d-summary").textContent = [...diffSummary(r.body.diff), r.body.chantStore ? `read through chant's ${r.body.chantStore.kind} store` : "", r.body.draw.omitted ? `${r.body.draw.omitted} unchanged nodes not drawn` : ""].filter(Boolean).join("\n");
107
+ });
108
+ }
109
+ /* c8 ignore stop */
@@ -0,0 +1,39 @@
1
+ // behold#1028: the index diff overlay's pure helpers.
2
+ import { describe, expect, it } from "vitest";
3
+ import { diffSummary, diffUrl, drawOverlaySvg } from "./index-diff.js";
4
+
5
+ describe("the overlay", () => {
6
+ it("asks a GET with only the arguments given", () => {
7
+ expect(diffUrl()).toBe("/api/graphdb/index-diff");
8
+ expect(diffUrl("cloud/aws/1/abc", "a.json", "")).toBe("/api/graphdb/index-diff?scope=cloud%2Faws%2F1%2Fabc&from=a.json");
9
+ });
10
+
11
+ it("draws each change as a class, and not observed is never drawn as removed", () => {
12
+ const svg = drawOverlaySvg({
13
+ nodes: [
14
+ { key: "a", kind: "k", name: "a", change: "changed", detail: "attrs.x" },
15
+ { key: "b", kind: "k", name: "b", change: "not-observed" },
16
+ ],
17
+ edges: [{ from: "a", to: "b", change: "not-observed" }],
18
+ });
19
+ expect(svg).toContain('class="g-node d-changed"');
20
+ expect(svg).toContain('class="g-node d-not-observed"');
21
+ expect(svg).toContain('class="g-edge d-not-observed"');
22
+ expect(svg).not.toContain("d-removed");
23
+ });
24
+
25
+ it("shows both stamps and each changed property", () => {
26
+ const lines = diffSummary({
27
+ scopeKey: "cloud/aws/1/abc",
28
+ from: { version: "v1", observedAt: "t1", digest: "a".repeat(64) },
29
+ to: { version: "v2", observedAt: "t2", digest: "b".repeat(64) },
30
+ unchanged: false,
31
+ counts: { added: 0, removed: 0, changed: 1, properties: 1, notObserved: 0, edgesAdded: 0, edgesRemoved: 0, edgesNotObserved: 0 },
32
+ nodes: { changed: [{ key: "n", properties: [{ path: "attrs.x", before: 1, after: 2 }] }] },
33
+ coverage: [],
34
+ });
35
+ expect(lines[1]).toMatch(/^from v1: observed t1/);
36
+ expect(lines[2]).toMatch(/^to {3}v2: observed t2/);
37
+ expect(lines).toContain(" n attrs.x: 1 -> 2");
38
+ });
39
+ });