cmd/cue/cmd: fix cue cmd crash

Fixes #650

Change-Id: I948676759284592ab2156ad70d03ca8a8174518e
Reviewed-on: https://cue-review.googlesource.com/c/cue/+/8281
Reviewed-by: CUE cueckoo <cueckoo@gmail.com>
Reviewed-by: Marcel van Lohuizen <mpvl@golang.org>
diff --git a/cmd/cue/cmd/testdata/script/cmd_issue650.txt b/cmd/cue/cmd/testdata/script/cmd_issue650.txt
new file mode 100644
index 0000000..7dcede3
--- /dev/null
+++ b/cmd/cue/cmd/testdata/script/cmd_issue650.txt
@@ -0,0 +1,32 @@
+cue cmd test
+
+-- blah/blah.cue --
+package blah
+
+#Pod: {
+ spec?: #PodSpec
+}
+
+#PodSpec: {
+}
+-- cue.mod/module.cue --
+module: "mod.com"
+-- x.cue --
+package kube
+
+import (
+ "tool/cli"
+ "mod.com/blah"
+)
+
+root: blah.#Pod
+
+root: spec: _
+
+command: test: task: test: cli.Print & {
+ for _ in root {
+  text: "success"
+ }
+}
+-- y_tool.cue --
+package kube
\ No newline at end of file
diff --git a/tools/flow/tasks.go b/tools/flow/tasks.go
index 1bfd1d9..a20c0be 100644
--- a/tools/flow/tasks.go
+++ b/tools/flow/tasks.go
@@ -165,6 +165,21 @@
 	}
 
 	n := d.Node
+
+	// This Finalize should not be necessary, as the input to dep is already
+	// finalized. However, cue cmd uses some legacy instance stitching code
+	// where some of the backlink Environments are not properly initialized.
+	// Finalizing should patch those up at the expense of doing some duplicate
+	// work. The plan is to replace `cue cmd` with a much more clean
+	// implementation (probably a separate tool called `cuerun`) where this
+	// issue is fixed. For now we leave this patch.
+	//
+	// Note that this issue predates package flow, but that it just surfaced in
+	// flow and having a different evaluation order.
+	//
+	// Note: this call is cheap if n is already Finalized.
+	n.Finalize(c.opCtx)
+
 	for ; n != nil; n = n.Parent {
 		if c.cfg.IgnoreConcrete && n.IsConcrete() {
 			if k := n.BaseValue.Kind(); k != adt.StructKind && k != adt.ListKind {