You are implementing Task 18 of the birdseye CLI implementation plan.

## Working Environment

- **Worktree path:** `/Users/steve.briggs/projects/operations/.claude/worktrees/birdseye`
- **Git branch:** `worktree-birdseye`
- Recent commits include Task 17 (`e00763a`).
- Use absolute paths or `cd` into the worktree.
- **NEVER push.** **NEVER use `git add .` / `git add -A`.**

## Context

The root `--json` global flag was added in Task 2 (`g.JSON`). Your job: route `runDiff` to a `renderJSON` function when `--json` is set, which emits a structured JSON payload with files and semantic entries. Add a test that decodes the JSON and asserts the file list is non-empty.

## Task Description (Verbatim)

### Task 18: JSON output mode (`--json`)

**Files:**
- Modify: `apps/birdseye/cmd/diff.go`
- Modify: `apps/birdseye/cmd/diff_test.go`

- [ ] **Step 1: Append failing test** to `apps/birdseye/cmd/diff_test.go`:

Add `"encoding/json"` to the imports if not already there.

```go
func TestDiffJSONOutput(t *testing.T) {
	srv := fakeCrowTwoVersions(t)
	root := NewRootCmd()
	var stdout bytes.Buffer
	root.SetOut(&stdout)
	root.SetArgs([]string{
		"diff",
		"iac/comply/aws", "1.0.0", "1.1.0",
		"--crow-url", srv.URL,
		"--plain",
		"--json",
		"--cache-dir", t.TempDir(),
	})
	if err := root.ExecuteContext(context.Background()); err != nil {
		t.Fatalf("execute: %v", err)
	}
	var payload struct {
		Files []struct {
			Path   string `json:"path"`
			Status string `json:"status"`
		} `json:"files"`
	}
	if err := json.Unmarshal(stdout.Bytes(), &payload); err != nil {
		t.Fatalf("invalid json: %v\nraw:\n%s", err, stdout.String())
	}
	if len(payload.Files) == 0 {
		t.Errorf("expected at least one file entry")
	}
}
```

- [ ] **Step 2: Run, expect FAIL**

Run: `cd /Users/steve.briggs/projects/operations/.claude/worktrees/birdseye/apps/birdseye && go test ./cmd/... -run TestDiffJSONOutput -v`
Expected: output isn't JSON yet (probably `=== ... ===` plain output), so JSON unmarshal fails.

- [ ] **Step 3: Update `runDiff`** in `apps/birdseye/cmd/diff.go`

Find the final render block (last few lines of `runDiff`):

```go
	if !o.Plain && isTTY(cmd.OutOrStdout()) {
		return tui.RunBrowser(ctx, result)
	}
	return renderPlain(cmd.OutOrStdout(), result)
}
```

Replace with:

```go
	if g.JSON {
		return renderJSON(cmd.OutOrStdout(), result)
	}
	if !o.Plain && isTTY(cmd.OutOrStdout()) {
		return tui.RunBrowser(ctx, result)
	}
	return renderPlain(cmd.OutOrStdout(), result)
}
```

- [ ] **Step 4: Add `renderJSON`** to `apps/birdseye/cmd/diff.go`

Append after `renderPlain`:

```go
func renderJSON(w io.Writer, r diff.Result) error {
	type fileOut struct {
		Path    string `json:"path"`
		Status  string `json:"status"`
		Adds    int    `json:"adds"`
		Dels    int    `json:"dels"`
		Unified string `json:"unified"`
	}
	type semOut struct {
		Kind   string `json:"kind"`
		Name   string `json:"name"`
		Status string `json:"status"`
		Detail string `json:"detail,omitempty"`
	}
	type payload struct {
		Files    []fileOut `json:"files"`
		Semantic []semOut  `json:"semantic,omitempty"`
	}
	out := payload{Files: make([]fileOut, 0, len(r.Files))}
	for _, fd := range r.Files {
		out.Files = append(out.Files, fileOut{Path: fd.Path, Status: fd.Status.String(), Adds: fd.Adds, Dels: fd.Dels, Unified: fd.Unified})
	}
	for _, c := range r.Semantic {
		out.Semantic = append(out.Semantic, semOut{Kind: c.Kind, Name: c.Name, Status: c.Status.String(), Detail: c.Detail})
	}
	return json.NewEncoder(w).Encode(out)
}
```

Add `"encoding/json"` to the import block at the top of `diff.go` (merge into existing block — alphabetical order with stdlib).

- [ ] **Step 5: Run, expect PASS**

Run: `cd /Users/steve.briggs/projects/operations/.claude/worktrees/birdseye/apps/birdseye && go test -race ./... -v`
Expected: All PASS, including new `TestDiffJSONOutput`.

- [ ] **Step 6: Commit**

```bash
cd /Users/steve.briggs/projects/operations/.claude/worktrees/birdseye && git add apps/birdseye/cmd/ && git commit -m "feat(birdseye): --json output for scripting and CI"
```

## Notes & Style

- `--json` is on the ROOT command (`g.JSON`), not the diff subcommand. Use `g.JSON` not `o.JSON`.
- The local `payload`/`fileOut`/`semOut` types are kept inside `renderJSON` to scope them tightly — they're not part of the public API.
- `omitempty` on `Semantic` means the field is absent when semantic changes aren't computed; the test only checks `Files` so this is fine.
- `json.NewEncoder.Encode` adds a trailing newline — that's standard and the test's `json.Unmarshal` handles it.

## Self-Review Checklist

- [ ] `TestDiffJSONOutput` passes
- [ ] All previous tests still pass
- [ ] `go vet ./...` clean
- [ ] `go build ./...` succeeds
- [ ] `g.JSON` (global flag) is what gates JSON output, not a subcommand-specific flag
- [ ] When `--json` is set, neither TUI nor plain output is rendered
- [ ] When `--json` is NOT set, behavior is unchanged
- [ ] Commit message exactly: `feat(birdseye): --json output for scripting and CI`

## Report Format

- **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT
- Files modified
- Test count + race-clean
- Commit SHA
- Anything unexpected


- migrate-flux-app: Use when migrating a Flux CD application from the infrastructure/kubernetes/application-deployments repo to the application-deployment repo. Covers copying app folders, updating kustomizations, committing, pushing, and creating merge requests.
- app-infra-generate: Generate an application-infrastructure Terraform module from a YAML spec produced by app-infra-spec. Reads pattern files and a versions manifest to produce main.tf, variables.tf, outputs.tf, overlay guidance, and a triage list.
- app-infra-spec: Structured questionnaire to gather requirements for an application-infrastructure Terraform module. Produces a YAML spec for the app-infra-generate skill.
- obsidian-load: Load context from Obsidian notes in the `Claude/` directory into the current conversation.
- obsidian-save: Save current conversation context to an Obsidian note under the `Claude/` directory.
- mind:search: Search memories for specific content or patterns
- mind:stats: Show memory statistics and storage information
- mind:recent: Show recent memories and activity timeline
- mind:ask: Ask questions about memories and get context-aware answers
- superpowers:using-git-worktrees: Use when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback
- superpowers:receiving-code-review: Use when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation
- superpowers:finishing-a-development-branch: Use when implementation is complete, all tests pass, and you need to decide how to integrate the work - guides completion of development work by presenting structured options for merge, PR, or cleanup
- superpowers:dispatching-parallel-agents: Use when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies
- superpowers:writing-plans: Use when you have a spec or requirements for a multi-step task, before touching code
- superpowers:using-superpowers: Use when starting any conversation - establishes how to find and use skills, requiring Skill tool invocation before ANY response including clarifying questions
- superpowers:writing-skills: Use when creating new skills, editing existing skills, or verifying skills work before deployment
- superpowers:requesting-code-review: Use when completing tasks, implementing major features, or before merging to verify work meets requirements
- superpowers:executing-plans: Use when you have a written implementation plan to execute in a separate session with review checkpoints
- superpowers:verification-before-completion: Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always
- superpowers:brainstorming: You MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation.
- superpowers:systematic-debugging: Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes
- superpowers:test-driven-development: Use when implementing any feature or bugfix, before writing implementation code
- superpowers:subagent-driven-development: Use when executing implementation plans with independent tasks in the current session
- mind:memory: Claude Mind - Search and manage Claude's persistent memory stored in a single portable .mv2 file
- mind:mind: Claude Mind - Search and manage Claude's persistent memory stored in a single portable .mv2 file
- update-config: Use this skill to configure the Claude Code harness via settings.json. Automated behaviors ("from now on when X", "each time X", "whenever X", "before/after X") require hooks configured in settings.json - the harness executes these, not Claude, so memory/preferences cannot fulfill them. Also use for: permissions ("allow X", "add permission", "move permission to"), env vars ("set X=Y"), hook troubleshooting, or any changes to settings.json/settings.local.json files. Examples: "allow npm commands", "add bq permission to global settings", "move permission to user settings", "set DEBUG=true", "when claude stops show X". For simple settings like theme/model, suggest the /config command.
- keybindings-help: Use when the user wants to customize keyboard shortcuts, rebind keys, add chord bindings, or modify ~/.claude/keybindings.json. Examples: "rebind ctrl+s", "add a chord shortcut", "change the submit key", "customize keybindings".
- simplify: Review changed code for reuse, quality, and efficiency, then fix any issues found.
- fewer-permission-prompts: Scan your transcripts for common read-only Bash and MCP tool calls, then add a prioritized allowlist to project .claude/settings.json to reduce permission prompts.
- loop: Run a prompt or slash command on a recurring interval (e.g. /loop 5m /foo). Omit the interval to let the model self-pace. - When the user wants to set up a recurring task, poll for status, or run something repeatedly on an interval (e.g. "check the deploy every 5 minutes", "keep running /babysit-prs"). Do NOT invoke for one-off tasks.
- schedule: Create, update, list, or run scheduled remote agents (routines) that execute on a cron schedule. - When the user wants to schedule a recurring remote agent, set up automated tasks, create a cron job for Claude Code, or manage their scheduled agents/routines. Also use when the user wants a one-time scheduled run ("run this once at 3pm", "remind me to check X tomorrow").
- claude-api: Build, debug, and optimize Claude API / Anthropic SDK apps. Apps built with this skill should include prompt caching. Also handles migrating existing Claude API code between Claude model versions (4.5 → 4.6, 4.6 → 4.7, retired-model replacements).
TRIGGER when: code imports `anthropic`/`@anthropic-ai/sdk`; user asks for the Claude API, Anthropic SDK, or Managed Agents; user adds/modifies/tunes a Claude feature (caching, thinking, compaction, tool use, batch, files, citations, memory) or model (Opus/Sonnet/Haiku) in a file; questions about prompt caching / cache hit rate in an Anthropic SDK project.
SKIP: file imports `openai`/other-provider SDK, filename like `*-openai.py`/`*-generic.py`, provider-neutral code, general programming/ML.
- init: Initialize a new CLAUDE.md file with codebase documentation
- review: Review a pull request
- security-review: Complete a security review of the pending changes on the current branch


I'll implement Task 18 by following the steps outlined. Let me start by reading the relevant files.


1	package cmd
2
3	import (
4		"context"
5		"fmt"
6		"io"
7		"net/http"
8		"os"
9		"path/filepath"
10		"strings"
11		"time"
12
13		tea "github.com/charmbracelet/bubbletea"
14		"github.com/spf13/cobra"
15		"golang.org/x/term"
16
17		"github.com/immuta/operations/apps/birdseye/internal/archive"
18		"github.com/immuta/operations/apps/birdseye/internal/diff"
19		"github.com/immuta/operations/apps/birdseye/internal/registry"
20		"github.com/immuta/operations/apps/birdseye/internal/tui"
21		"github.com/immuta/operations/services/crow/pkg/api"
22		"github.com/immuta/operations/services/crow/pkg/client"
23	)
24
25	// diffOpts holds the resolved options for `birdseye diff`.
26	type diffOpts struct {
27		Semantic bool
28		Plain    bool
29		CacheDir string
30	}
31
32	const maxArchiveBytes = 50 << 20 // 50 MiB safety cap on uncompressed size
33
34	func newDiffCmd(g *GlobalFlags) *cobra.Command {
35		o := &diffOpts{}
36		c := &cobra.Command{
37			Use:   "diff [module] [versionA] [versionB]",
38			Short: "Diff two versions of a Crow module",
39			Long: "Diff two versions of a module hosted in Crow.\n\n" +
40				"If module/versions are omitted, the interactive TUI launches\n" +
41				"(see picker task). With --plain, prints unified diff to stdout.",
42			Args:          cobra.MaximumNArgs(3),
43			SilenceUsage:  true,
44			SilenceErrors: true,
45			RunE: func(cmd *cobra.Command, args []string) error {
46				return runDiff(cmd.Context(), cmd, args, g, o)
47			},
48		}
49		c.Flags().BoolVar(&o.Semantic, "semantic", false, "include HCL-aware semantic diff alongside textual")
50		c.Flags().BoolVar(&o.Plain, "plain", false, "force plain (non-TUI) output")
51		c.Flags().BoolVar(&o.Plain, "no-tui", false, "alias for --plain")
52		c.Flags().StringVar(&o.CacheDir, "cache-dir", defaultCacheDir(), "module tarball cache directory")
53		return c
54	}
55
56	func defaultCacheDir() string {
57		if home, err := os.UserCacheDir(); err == nil {
58			return filepath.Join(home, "birdseye")
59		}
60		return ".birdseye-cache"
61	}
62
63	func newHTTPClient(d time.Duration) *http.Client {
64		return &http.Client{Timeout: d}
65	}
66
67	func parseModuleAddress(s string) (api.ModuleIdentifier, error) {
68		parts := strings.Split(s, "/")
69		if len(parts) != 3 {
70			return api.ModuleIdentifier{}, fmt.Errorf("%w: module address must be namespace/name/provider, got %q", ErrUsage, s)
71		}
72		id := api.ModuleIdentifier{Namespace: parts[0], Name: parts[1], Provider: parts[2]}
73		if err := id.Validate(); err != nil {
74			return api.ModuleIdentifier{}, fmt.Errorf("%w: %v", ErrUsage, err)
75		}
76		return id, nil
77	}
78
79	func runDiff(ctx context.Context, cmd *cobra.Command, args []string, g *GlobalFlags, o *diffOpts) error {
80		if len(args) == 0 {
81			return runInteractive(ctx, cmd, g, o)
82		}
83		if len(args) != 3 {
84			return fmt.Errorf("%w: diff requires <module> <versionA> <versionB>", ErrUsage)
85		}
86		id, err := parseModuleAddress(args[0])
87		if err != nil {
88			return err
89		}
90		if err := api.ValidateVersion(args[1]); err != nil {
91			return fmt.Errorf("%w: %v", ErrUsage, err)
92		}
93		if err := api.ValidateVersion(args[2]); err != nil {
94			return fmt.Errorf("%w: %v", ErrUsage, err)
95		}
96		modA := api.Module{ModuleIdentifier: id, Version: args[1]}
97		modB := api.Module{ModuleIdentifier: id, Version: args[2]}
98
99		cli := client.New(g.CrowURL, client.WithHTTPClient(newHTTPClient(g.Timeout)))
100		cache, err := registry.NewDiskCache(o.CacheDir)
101		if err != nil {
102			return fmt.Errorf("cache init: %w", err)
103		}
104		reg := registry.New(cli, cache)
105
106		aBytes, bBytes, err := reg.FetchPair(ctx, modA, modB)
107		if err != nil {
108			return err
109		}
110
111		modAExtracted, err := archive.Extract(aBytes, maxArchiveBytes)
112		if err != nil {
113			return fmt.Errorf("%w: %v", ErrArchive, err)
114		}
115		modBExtracted, err := archive.Extract(bBytes, maxArchiveBytes)
116		if err != nil {
117			return fmt.Errorf("%w: %v", ErrArchive, err)
118		}
119
120		result := diff.Result{Files: diff.Textual(modAExtracted, modBExtracted)}
121		if o.Semantic {
122			sem, err := diff.Semantic(modAExtracted, modBExtracted)
123			if err != nil {
124				return fmt.Errorf("%w: %v", ErrSemantic, err)
125			}
126			result.Semantic = sem
127		}
128
129		if !o.Plain && isTTY(cmd.OutOrStdout()) {
130			return tui.RunBrowser(ctx, result)
131		}
132		return renderPlain(cmd.OutOrStdout(), result)
133	}
134
135	// isTTY reports whether w is a *os.File backed by a terminal.
136	func isTTY(w io.Writer) bool {
137		f, ok := w.(*os.File)
138		if !ok {
139			return false
140		}
141		return term.IsTerminal(int(f.Fd()))
142	}
143
144	func runInteractive(ctx context.Context, cmd *cobra.Command, g *GlobalFlags, o *diffOpts) error {
145		if !isTTY(cmd.OutOrStdout()) {
146			return fmt.Errorf("%w: interactive mode requires a TTY", ErrUsage)
147		}
148		cli := client.New(g.CrowURL, client.WithHTTPClient(newHTTPClient(g.Timeout)))
149		cache, err := registry.NewDiskCache(o.CacheDir)
150		if err != nil {
151			return fmt.Errorf("cache init: %w", err)
152		}
153		reg := registry.New(cli, cache)
154
155		// Stage 1: picker → fetched bytes
156		p := tui.NewPicker(&tui.Deps{Client: cli, Reg: reg})
157		prog := tea.NewProgram(p, tea.WithAltScreen(), tea.WithContext(ctx))
158		if _, err := prog.Run(); err != nil {
159			return err
160		}
161		aBytes, bBytes := p.Bytes()
162		if aBytes == nil || bBytes == nil {
163			// User quit before completing picker; not an error.
164			return nil
165		}
166
167		// Stage 2: extract + diff + browser
168		modA, err := archive.Extract(aBytes, maxArchiveBytes)
169		if err != nil {
170			return fmt.Errorf("%w: %v", ErrArchive, err)
171		}
172		modB, err := archive.Extract(bBytes, maxArchiveBytes)
173		if err != nil {
174			return fmt.Errorf("%w: %v", ErrArchive, err)
175		}
176		result := diff.Result{Files: diff.Textual(modA, modB)}
177		return tui.RunBrowser(ctx, result)
178	}
179
180	// renderPlain writes the diff result to w in unified-diff format.
181	// "no differences" is emitted when there are zero files in the result.
182	func renderPlain(w io.Writer, r diff.Result) error {
183		if len(r.Files) == 0 && len(r.Semantic) == 0 {
184			_, err := fmt.Fprintln(w, "no differences")
185			return err
186		}
187		for i, fd := range r.Files {
188			if i > 0 {
189				_, _ = fmt.Fprintln(w)
190			}
191			_, _ = fmt.Fprintf(w, "=== %s (%s) +%d -%d\n", fd.Path, fd.Status, fd.Adds, fd.Dels)
192			_, _ = fmt.Fprint(w, fd.Unified)
193		}
194		if len(r.Semantic) > 0 {
195			_, _ = fmt.Fprintln(w)
196			_, _ = fmt.Fprintln(w, "=== semantic changes ===")
197			for _, c := range r.Semantic {
198				_, _ = fmt.Fprintf(w, "%s %s %s\n", c.Status, c.Kind, c.Name)
199			}
200		}
201		return nil
202	}
203


1	package cmd
2
3	import (
4		"archive/tar"
5		"bytes"
6		"compress/gzip"
7		"context"
8		"net/http"
9		"net/http/httptest"
10		"strings"
11		"testing"
12	)
13
14	// fakeCrow with two versions of moduleA. v1 has main.tf; v2 has main.tf
15	// (modified) and a new variables.tf.
16	func fakeCrowTwoVersions(t *testing.T) *httptest.Server {
17		t.Helper()
18		mkTgz := func(files map[string]string) []byte {
19			var buf bytes.Buffer
20			gz := gzip.NewWriter(&buf)
21			tw := tar.NewWriter(gz)
22			for n, b := range files {
23				_ = tw.WriteHeader(&tar.Header{Name: n, Mode: 0o644, Size: int64(len(b)), Typeflag: tar.TypeReg})
24				_, _ = tw.Write([]byte(b))
25			}
26			_ = tw.Close()
27			_ = gz.Close()
28			return buf.Bytes()
29		}
30		v1 := mkTgz(map[string]string{"main.tf": "resource \"aws_s3_bucket\" \"alpha\" {}\n"})
31		v2 := mkTgz(map[string]string{
32			"main.tf":      "resource \"aws_s3_bucket\" \"beta\" {}\n",
33			"variables.tf": "variable \"name\" { type = string }\n",
34		})
35
36		mux := http.NewServeMux()
37		blob := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
38			switch r.URL.Path {
39			case "/blob/1.0.0":
40				_, _ = w.Write(v1)
41			case "/blob/1.1.0":
42				_, _ = w.Write(v2)
43			default:
44				http.NotFound(w, r)
45			}
46		}))
47		t.Cleanup(blob.Close)
48		mux.HandleFunc("/v1/modules/iac/comply/aws/", func(w http.ResponseWriter, r *http.Request) {
49			parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/v1/modules/iac/comply/aws/"), "/")
50			if len(parts) != 2 || parts[1] != "download" {
51				http.NotFound(w, r)
52				return
53			}
54			w.Header().Set("X-Terraform-Get", blob.URL+"/blob/"+parts[0])
55			w.WriteHeader(http.StatusNoContent)
56		})
57		srv := httptest.NewServer(mux)
58		t.Cleanup(srv.Close)
59		return srv
60	}
61
62	func TestDiffPlainOutput(t *testing.T) {
63		srv := fakeCrowTwoVersions(t)
64		root := NewRootCmd()
65		var stdout, stderr bytes.Buffer
66		root.SetOut(&stdout)
67		root.SetErr(&stderr)
68		root.SetArgs([]string{
69			"diff",
70			"iac/comply/aws", "1.0.0", "1.1.0",
71			"--crow-url", srv.URL,
72			"--plain",
73			"--cache-dir", t.TempDir(),
74		})
75		if err := root.ExecuteContext(context.Background()); err != nil {
76			t.Fatalf("execute: %v\nstderr: %s", err, stderr.String())
77		}
78		out := stdout.String()
79		for _, want := range []string{"main.tf", "variables.tf", "alpha", "beta"} {
80			if !strings.Contains(out, want) {
81				t.Errorf("plain output missing %q\n--- output ---\n%s", want, out)
82			}
83		}
84	}
85
86	func TestDiffIdenticalVersionsNoChanges(t *testing.T) {
87		srv := fakeCrowTwoVersions(t)
88		root := NewRootCmd()
89		var stdout bytes.Buffer
90		root.SetOut(&stdout)
91		root.SetArgs([]string{
92			"diff",
93			"iac/comply/aws", "1.0.0", "1.0.0",
94			"--crow-url", srv.URL,
95			"--plain",
96			"--cache-dir", t.TempDir(),
97		})
98		if err := root.ExecuteContext(context.Background()); err != nil {
99			t.Fatalf("execute: %v", err)
100		}
101		if got := strings.TrimSpace(stdout.String()); got != "no differences" {
102			t.Errorf("output = %q, want \"no differences\"", got)
103		}
104	}
105
106	func TestDiffBadModuleAddress(t *testing.T) {
107		root := NewRootCmd()
108		var stderr bytes.Buffer
109		root.SetErr(&stderr)
110		root.SetArgs([]string{"diff", "bad-address", "1.0.0", "1.1.0"})
111		err := root.ExecuteContext(context.Background())
112		if err == nil {
113			t.Fatal("expected error for bad address")
114		}
115		if ExitCode(err) != 1 {
116			t.Errorf("exit code = %d, want 1", ExitCode(err))
117		}
118	}
119
120	func TestDiffSemanticIncluded(t *testing.T) {
121		srv := fakeCrowTwoVersions(t)
122		root := NewRootCmd()
123		var stdout bytes.Buffer
124		root.SetOut(&stdout)
125		root.SetArgs([]string{
126			"diff",
127			"iac/comply/aws", "1.0.0", "1.1.0",
128			"--crow-url", srv.URL,
129			"--plain",
130			"--semantic",
131			"--cache-dir", t.TempDir(),
132		})
133		if err := root.ExecuteContext(context.Background()); err != nil {
134			t.Fatalf("execute: %v", err)
135		}
136		out := stdout.String()
137		for _, want := range []string{
138			"=== semantic changes ===",
139			"resource",
140			"aws_s3_bucket.alpha",
141			"aws_s3_bucket.beta",
142			"variable",
143			"name",
144		} {
145			if !strings.Contains(out, want) {
146				t.Errorf("semantic output missing %q\n--- output ---\n%s", want, out)
147			}
148		}
149	}
150


Good. Now let me proceed with the implementation steps.

**Step 1: Add the failing test to `diff_test.go`**


Edit

import (
	"archive/tar"
	"bytes"
	"compress/gzip"
	"context"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

import (
	"archive/tar"
	"bytes"
	"compress/gzip"
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)


The file /Users/steve.briggs/projects/operations/.claude/worktrees/birdseye/apps/birdseye/cmd/diff_test.go has been updated successfully. (file state is current in your context — no need to Read it back)


func TestDiffSemanticIncluded(t *testing.T) {

func TestDiffJSONOutput(t *testing.T) {
	srv := fakeCrowTwoVersions(t)
	root := NewRootCmd()
	var stdout bytes.Buffer
	root.SetOut(&stdout)
	root.SetArgs([]string{
		"diff",
		"iac/comply/aws", "1.0.0", "1.1.0",
		"--crow-url", srv.URL,
		"--plain",
		"--json",
		"--cache-dir", t.TempDir(),
	})
	if err := root.ExecuteContext(context.Background()); err != nil {
		t.Fatalf("execute: %v", err)
	}
	var payload struct {
		Files []struct {
			Path   string `json:"path"`
			Status string `json:"status"`
		} `json:"files"`
	}
	if err := json.Unmarshal(stdout.Bytes(), &payload); err != nil {
		t.Fatalf("invalid json: %v\nraw:\n%s", err, stdout.String())
	}
	if len(payload.Files) == 0 {
		t.Errorf("expected at least one file entry")
	}
}

func TestDiffSemanticIncluded(t *testing.T) {


**Step 2: Run test to confirm it fails**


Bash

cd /Users/steve.briggs/projects/operations/.claude/worktrees/birdseye/apps/birdseye && go test ./cmd/... -run TestDiffJSONOutput -v 2>&1

Run failing test to confirm expected failure


Error: Exit code 1
=== RUN   TestDiffJSONOutput
    diff_test.go:144: invalid json: invalid character '=' looking for beginning of value
        raw:
        === main.tf (modified) +1 -1
        --- main.tf
        +++ main.tf
        @@ -1 +1 @@
        -resource "aws_s3_bucket" "alpha" {}
        +resource "aws_s3_bucket" "beta" {}

        === variables.tf (added) +1 -0
        +++ variables.tf
        +variable "name" { type = string }
--- FAIL: TestDiffJSONOutput (0.01s)
FAIL
FAIL	github.com/immuta/operations/apps/birdseye/cmd	0.736s
FAIL


Good, it fails as expected — plain output, not JSON. Now let me implement the fix.

**Step 3: Update `runDiff` to check `g.JSON`**


Edit

	if !o.Plain && isTTY(cmd.OutOrStdout()) {
		return tui.RunBrowser(ctx, result)
	}
	return renderPlain(cmd.OutOrStdout(), result)
}

	if g.JSON {
		return renderJSON(cmd.OutOrStdout(), result)
	}
	if !o.Plain && isTTY(cmd.OutOrStdout()) {
		return tui.RunBrowser(ctx, result)
	}
	return renderPlain(cmd.OutOrStdout(), result)
}


The file /Users/steve.briggs/projects/operations/.claude/worktrees/birdseye/apps/birdseye/cmd/diff.go has been updated successfully. (file state is current in your context — no need to Read it back)


**Step 4: Add `renderJSON` function and `"encoding/json"` import**


import (
	"context"
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"


Now append the `renderJSON` function after `renderPlain`:


	if len(r.Semantic) > 0 {
		_, _ = fmt.Fprintln(w)
		_, _ = fmt.Fprintln(w, "=== semantic changes ===")
		for _, c := range r.Semantic {
			_, _ = fmt.Fprintf(w, "%s %s %s\n", c.Status, c.Kind, c.Name)
		}
	}
	return nil
}

	if len(r.Semantic) > 0 {
		_, _ = fmt.Fprintln(w)
		_, _ = fmt.Fprintln(w, "=== semantic changes ===")
		for _, c := range r.Semantic {
			_, _ = fmt.Fprintf(w, "%s %s %s\n", c.Status, c.Kind, c.Name)
		}
	}
	return nil
}

func renderJSON(w io.Writer, r diff.Result) error {
	type fileOut struct {
		Path    string `json:"path"`
		Status  string `json:"status"`
		Adds    int    `json:"adds"`
		Dels    int    `json:"dels"`
		Unified string `json:"unified"`
	}
	type semOut struct {
		Kind   string `json:"kind"`
		Name   string `json:"name"`
		Status string `json:"status"`
		Detail string `json:"detail,omitempty"`
	}
	type payload struct {
		Files    []fileOut `json:"files"`
		Semantic []semOut  `json:"semantic,omitempty"`
	}
	out := payload{Files: make([]fileOut, 0, len(r.Files))}
	for _, fd := range r.Files {
		out.Files = append(out.Files, fileOut{Path: fd.Path, Status: fd.Status.String(), Adds: fd.Adds, Dels: fd.Dels, Unified: fd.Unified})
	}
	for _, c := range r.Semantic {
		out.Semantic = append(out.Semantic, semOut{Kind: c.Kind, Name: c.Name, Status: c.Status.String(), Detail: c.Detail})
	}
	return json.NewEncoder(w).Encode(out)
}


**Step 5: Run all tests with race detector**


Bash

cd /Users/steve.briggs/projects/operations/.claude/worktrees/birdseye/apps/birdseye && go test -race ./... -v 2>&1

Run all tests with race detector


?   	github.com/immuta/operations/apps/birdseye	[no test files]
=== RUN   TestDiffPlainOutput
--- PASS: TestDiffPlainOutput (0.01s)
=== RUN   TestDiffIdenticalVersionsNoChanges
--- PASS: TestDiffIdenticalVersionsNoChanges (0.01s)
=== RUN   TestDiffBadModuleAddress
--- PASS: TestDiffBadModuleAddress (0.00s)
=== RUN   TestDiffJSONOutput
--- PASS: TestDiffJSONOutput (0.01s)
=== RUN   TestDiffSemanticIncluded
--- PASS: TestDiffSemanticIncluded (0.01s)
=== RUN   TestExitCode
=== RUN   TestExitCode/nil
=== RUN   TestExitCode/not-found
=== RUN   TestExitCode/wrapped-not-found
=== RUN   TestExitCode/context-cancelled
=== RUN   TestExitCode/context-deadline
=== RUN   TestExitCode/generic
--- PASS: TestExitCode (0.00s)
    --- PASS: TestExitCode/nil (0.00s)
    --- PASS: TestExitCode/not-found (0.00s)
    --- PASS: TestExitCode/wrapped-not-found (0.00s)
    --- PASS: TestExitCode/context-cancelled (0.00s)
    --- PASS: TestExitCode/context-deadline (0.00s)
    --- PASS: TestExitCode/generic (0.00s)
=== RUN   TestNewRootCmdHelp
--- PASS: TestNewRootCmdHelp (0.00s)
=== RUN   TestNewRootCmdDefaults
--- PASS: TestNewRootCmdDefaults (0.00s)
=== RUN   TestVersionsCmd
--- PASS: TestVersionsCmd (0.00s)
PASS
ok  	github.com/immuta/operations/apps/birdseye/cmd	1.701s
=== RUN   TestExtractHappyPath
--- PASS: TestExtractHappyPath (0.00s)
=== RUN   TestExtractEmptyArchive
--- PASS: TestExtractEmptyArchive (0.00s)
=== RUN   TestExtractMalformedGzip
--- PASS: TestExtractMalformedGzip (0.00s)
=== RUN   TestExtractZipSlip
=== RUN   TestExtractZipSlip/../evil.tf
=== RUN   TestExtractZipSlip/./../../etc/passwd
=== RUN   TestExtractZipSlip/a/../../etc/passwd
--- PASS: TestExtractZipSlip (0.00s)
    --- PASS: TestExtractZipSlip/../evil.tf (0.00s)
    --- PASS: TestExtractZipSlip/./../../etc/passwd (0.00s)
    --- PASS: TestExtractZipSlip/a/../../etc/passwd (0.00s)
=== RUN   TestExtractAbsolutePath
--- PASS: TestExtractAbsolutePath (0.00s)
=== RUN   TestExtractTooLarge
--- PASS: TestExtractTooLarge (0.00s)
=== RUN   TestExtractIgnoresSymlinks
--- PASS: TestExtractIgnoresSymlinks (0.00s)
PASS
ok  	github.com/immuta/operations/apps/birdseye/internal/archive	(cached)
=== RUN   TestSemanticAddedResource
--- PASS: TestSemanticAddedResource (0.00s)
=== RUN   TestSemanticRemovedVariable
--- PASS: TestSemanticRemovedVariable (0.00s)
=== RUN   TestSemanticModifiedResource
--- PASS: TestSemanticModifiedResource (0.00s)
=== RUN   TestSemanticParseError
--- PASS: TestSemanticParseError (0.00s)
=== RUN   TestTextualAdded
--- PASS: TestTextualAdded (0.00s)
=== RUN   TestTextualRemoved
--- PASS: TestTextualRemoved (0.00s)
=== RUN   TestTextualModified
--- PASS: TestTextualModified (0.00s)
=== RUN   TestTextualIdenticalReturnsEmpty
--- PASS: TestTextualIdenticalReturnsEmpty (0.00s)
=== RUN   TestTextualSortedByPath
--- PASS: TestTextualSortedByPath (0.00s)
PASS
ok  	github.com/immuta/operations/apps/birdseye/internal/diff	(cached)
=== RUN   TestMemCacheRoundTrip
--- PASS: TestMemCacheRoundTrip (0.00s)
=== RUN   TestDiskCacheMissThenHit
--- PASS: TestDiskCacheMissThenHit (0.00s)
=== RUN   TestDiskCacheSurvivesNewInstance
--- PASS: TestDiskCacheSurvivesNewInstance (0.00s)
=== RUN   TestRegistryFetchCacheMiss
--- PASS: TestRegistryFetchCacheMiss (0.00s)
=== RUN   TestRegistryFetchCacheHitSkipsNetwork
--- PASS: TestRegistryFetchCacheHitSkipsNetwork (0.00s)
=== RUN   TestRegistryFetchNotFound
--- PASS: TestRegistryFetchNotFound (0.00s)
=== RUN   TestRegistryFetchPair
--- PASS: TestRegistryFetchPair (0.00s)
=== RUN   TestRegistryFetchPairOneMissing
--- PASS: TestRegistryFetchPairOneMissing (0.00s)
PASS
ok  	github.com/immuta/operations/apps/birdseye/internal/registry	(cached)
=== RUN   TestNewBrowserDefaults
--- PASS: TestNewBrowserDefaults (0.00s)
=== RUN   TestBrowserViewContainsBothFiles
--- PASS: TestBrowserViewContainsBothFiles (0.00s)
=== RUN   TestBrowserMovesDownAndUp
--- PASS: TestBrowserMovesDownAndUp (0.00s)
=== RUN   TestBrowserQuitMessage
--- PASS: TestBrowserQuitMessage (0.00s)
=== RUN   TestBrowserJKDoesNotForwardToViewport
--- PASS: TestBrowserJKDoesNotForwardToViewport (0.00s)
=== RUN   TestPickerStartsAtAskModule
--- PASS: TestPickerStartsAtAskModule (0.00s)
=== RUN   TestPickerAdvancesOnEnter
--- PASS: TestPickerAdvancesOnEnter (0.00s)
=== RUN   TestPickerRejectsBadAddressInline
--- PASS: TestPickerRejectsBadAddressInline (0.00s)
PASS
ok  	github.com/immuta/operations/apps/birdseye/internal/tui	(cached)


All 9 test suites pass, race-clean. Now let me also run `go vet` and `go build` to complete the self-review checklist:


cd /Users/steve.briggs/projects/operations/.claude/worktrees/birdseye/apps/birdseye && go vet ./... && go build ./... 2>&1

Run go vet and go build


(Bash completed with no output)


Clean. Now commit.

**Step 6: Commit**


git add apps/birdseye/cmd/diff.go apps/birdseye/cmd/diff_test.go && git commit -m "feat(birdseye): --json output for scripting and CI"

Commit the JSON output changes


[worktree-birdseye 1c85b59] feat(birdseye): --json output for scripting and CI
 2 files changed, 63 insertions(+)


---

**Status:** DONE

**Files modified:**
- `/Users/steve.briggs/projects/operations/.claude/worktrees/birdseye/apps/birdseye/cmd/diff.go` — added `"encoding/json"` import, `g.JSON` gate in `runDiff`, and `renderJSON` function
- `/Users/steve.briggs/projects/operations/.claude/worktrees/birdseye/apps/birdseye/cmd/diff_test.go` — added `"encoding/json"` import and `TestDiffJSONOutput`

**Test count:** 9 packages, all PASS, race-clean. `go vet` and `go build` both clean.

**Commit SHA:** `1c85b59`

**Nothing unexpected** — the implementation followed the plan exactly. `g.JSON` (global flag on root command) correctly gates the JSON path before the TUI/plain branches, so existing behavior is fully preserved when `--json` is absent.