APP := equipo

# The gate and the release run on one named Go, not whichever release this
# machine has. govulncheck judges the standard library of the Go doing the
# scan, and make release builds the binary you ship with it, so a patch
# release behind is both a red gate and an unpatched binary. go fetches
# this release through the module proxy on first use. Raise it with
# each Go security release.
#
# A plain =, not ?=: Go's container images set GOTOOLCHAIN=local, and ?=
# would quietly keep whatever Go they ship. To override for one run:
#   make ci GOTOOLCHAIN=local
export GOTOOLCHAIN = go1.26.11
export CGO_ENABLED = 0

# The deployment platform target for a release. Building for your own machine and shipping that is a
# silent architecture mismatch: the binary uploads fine and fails to exec
# on the instance. Override for a one-off:
#   make release RELEASE_GOARCH=amd64
RELEASE_GOOS   ?= linux
RELEASE_GOARCH ?= arm64
RELEASE_VERSION = $(shell git rev-parse --short HEAD)
RELEASE_BIN = releases/$(APP)-$(RELEASE_GOOS)-$(RELEASE_GOARCH)-$(RELEASE_VERSION)
RUNNER_RELEASE_DIR = releases/equipo-runner-linux-amd64-$(RELEASE_VERSION)

# One target at a time, even under make -j: the perf lane measures time,
# and a suite running beside it would be measured too.
.NOTPARALLEL:

.PHONY: build release test test-lane ci-shard ci-compile lanes-check test-quarantine vet fmt-check staticcheck govulncheck gitleaks budget perf migration-check runner-adapter-test runner-namespace-test runner-host runner-dead-references ci

RASTRILLO := go run amadan.net/rastrillo/rastrillo/cmd/rastrillo

# build is the compile check: with more than one package matched, go
# build discards the output, so this catches a broken package without
# producing an artifact. The runner also builds for a Mac worker
# (darwin/arm64), so a Linux-only call outside a _linux.go file fails here.
# The tool proxy is Linux only.
build:
	CGO_ENABLED=0 go build ./...
	CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -o /dev/null ./cmd/equipo-runner

# A release is built from one fixed commit in a tree of its own
# (scripts/release-isolated.sh): a fresh clone at HEAD under $TMPDIR,
# clean before the build and after it, each binary checked against the
# commit by its own build information, and only then the provenance
# manifest. An edit here while it builds cannot reach a binary.
release:
	scripts/release-isolated.sh $(RELEASE_GOOS) $(RELEASE_GOARCH)

# release-in-tree is the build itself, run by release in its own tree.
# Stamp the clean commit so /api/version identifies the running release.
# Strip debug data to reduce the upload size; keep module build metadata.
.PHONY: release-in-tree
release-in-tree: release-runner
	@test -z "$$(git ls-files --others --exclude-standard)"
	@git diff --quiet && git diff --cached --quiet || \
		{ echo "refusing to build a release from a dirty tree"; exit 1; }
	@mkdir -p $(dir $(RELEASE_BIN))
	scripts/build-instance-release.sh $(RUNNER_RELEASE_DIR) $(RELEASE_BIN) $(RELEASE_GOOS) $(RELEASE_GOARCH) "$$(git rev-parse --short HEAD)"
	@git rev-parse HEAD > $(RELEASE_BIN).COMMIT

# staged-check is the production gate: it refuses unless the artifacts
# are the ones this release's build recorded (its provenance manifest,
# written by make release) and releases/staged records a green staging
# suite for exactly those bytes.
.PHONY: staged-check
staged-check:
	python3 scripts/staged-artifacts.py check $(RELEASE_VERSION)

# budget size holds each directory to 5,000 source and 8,000 test lines.
# Past that, split by feature (docs/site/testing.md); a record in
# .rastrillo/budgets.txt with a reason is the exception, not the fix.
budget:
	$(RASTRILLO) budget size

# budget test runs go test itself, so its exit status survives, and
# reports each package's time against its budget using the time
# budget.Main prints in the package's TestMain, cached runs included.
# Timing fails the step only where EQUIPO_CI_DEDICATED=1: on a shared,
# loaded runner a package's time measures the box, not the change, so
# there it is reported. go test's own 10-minute limit is set above the
# longest package budget, so on a loaded runner the budget, not a panic,
# says which package is slow.
#
# Results are cached: a package whose test binary, declared inputs
# (internal/testci) and environment are unchanged replays its pass, so a
# rerun after one failure runs only what failed. scripts/ci-test.py
# lists the packages that must run every time (UNCACHED).
#
# test runs every package at once. CI runs the same packages as lanes,
# shards of .amadan/ci.d/20-check@N side by side: the slow packages split
# by test name into lanes of about a minute (make test-lane
# LANE=headless-work runs one; scripts/ci-test.py lanes lists them), with
# test-quarantine, runner-host and the static checks as further shards.
# Known flaky tests are quarantined (scripts/ci-quarantine.txt): skipped
# here and run by test-quarantine. The browser tests (-tags browser) run
# after the rest, as their own lanes on CI; they need a Chromium
# (RASTRILLO_CHROME, or one on PATH).
#
# A failed test is retried once, in the lane where it failed. A pass on
# the retry keeps the lane green and prints a FLAKE line (the test, the
# lane, the commit, how long the failed attempt took, the load average);
# red means it failed twice. scripts/ci-flakes.py reads those lines back
# from CI and names the tests that keep flaking.
test:
	RASTRILLO='$(RASTRILLO)' python3 scripts/ci-test.py all

test-lane:
	RASTRILLO='$(RASTRILLO)' python3 scripts/ci-test.py lane $(LANE)

ci-shard:
	RASTRILLO='$(RASTRILLO)' python3 scripts/ci-test.py shard

# ci-compile compiles every package once, before the shards of 20-check
# start. Go does not share a compile between processes that start
# together: 23 shards on an empty cache each compiled the same packages,
# and every one of them took as long as the whole job used to. After this
# the shards find their packages, their test packages and the tools the
# static checks run in the cache: on an empty cache the shards building
# those side by side held the load near 100 on 32 CPUs, and tests timed
# out. No test is linked, so with a warm cache it takes a few seconds.
ci-compile:
	go build ./...
	RASTRILLO='$(RASTRILLO)' python3 scripts/ci-test.py compile
	go run $(STATICCHECK) -version
	go run $(GOVULNCHECK) -version
	go run $(GITLEAKS) version

test-quarantine:
	python3 scripts/ci-test.py quarantine

# lanes-check fails when the lanes do not run every test exactly once: a
# lane names a test or package that no longer exists, two lanes take the
# same test, or a split package has no lane for the tests nobody names.
# It also holds the shard count of .amadan/ci.d/20-check@N to the lanes.
# It reads the test files every time, so it runs on CI uncached.
lanes-check:
	python3 scripts/ci-test.py check

# The perf lane: every GET screen at 150ms to first byte, cold boot at
# 500ms. Serial (-p 1 -parallel 1) and uncached (-count=1), because a
# measurement taken beside other work, or replayed from a cache, is not
# one. -require fails the lane if the perf tests did not both run.
perf:
	$(RASTRILLO) budget test -no-time -require TestPerfScreens,TestPerfBoot -tags perf -count=1 -p 1 -parallel 1 -run '^TestPerf' ./...

vet:
	go vet ./...
	go vet -tags testbuild ./internal/runner/thin ./internal/headless
	GOOS=darwin GOARCH=arm64 go vet ./cmd/equipo-runner/... ./internal/runner/... ./internal/wire/... ./internal/release/...

fmt-check:
	@out=$$(gofmt -l .); if [ -n "$$out" ]; then echo "gofmt needed:"; echo "$$out"; exit 1; fi

# spacing holds the app's stylesheets to Fiesta's spacing scale: every
# margin, padding and gap is a var(--rst-sp-N) step, or says why it is
# not with a /* spacing-allow: why */ comment. tokens.css is rastrillo's,
# copied byte for byte, so it is not read here. The rhythm audit, its
# runtime half, is TestBrowserRhythm (internal/thintest).
.PHONY: spacing
spacing:
	go tool fiesta spacing -skip tokens.css internal/equipo/static

# staticcheck catches what vet does not: deprecated APIs, values that are
# never read, a &*x that looks like a copy and is not.
#
# go run with a version, not a tool directive in go.mod. A tool's
# requirements join the app's own module graph and can move the versions
# of modules the app shares with it (golang.org/x/tools, which sqlc also
# needs); go run resolves the tool in a graph of its own. The version is
# the one rastrillo's own gate runs. Bump it when you raise the go
# directive: a staticcheck older than your Go does not know that
# release's deprecations, and says nothing.
#
# -tags browser,perf so the browser drive and the perf tests are read
# too; no file is left out by them, so it covers everything the plain
# build does.
STATICCHECK := honnef.co/go/tools/cmd/staticcheck@v0.7.0
# staticcheck keeps its cache in the user cache directory, ~/.cache,
# which a sandboxed CI runner mounts read-only: "failed to initialize
# build cache ... read-only file system". Where the runner hands the job
# an absolute GOCACHE, staticcheck's goes inside it: writable wherever
# Go's is, and evicted with it. Anywhere else it stays where staticcheck
# puts it. Not beside it: a writable GOCACHE says nothing about its
# parent.
ifneq ($(filter /%,$(firstword $(GOCACHE))),)
export STATICCHECK_CACHE ?= $(GOCACHE)/staticcheck
# The mixed-version test (M8) builds the older release once and keeps it
# beside the build cache, so later runs do not compile it again.
export EQUIPO_M8_CACHE ?= $(GOCACHE)/equipo-m8
endif

staticcheck:
	go run $(STATICCHECK) -tags browser,perf,testbuild ./...

# govulncheck reports only the vulnerabilities your code can reach: a call
# path, not a module that merely sits in go.sum. It reads the live
# vulnerability database, so it can go red with no change here, which is
# the point of running it on every push. A module finding is fixed by
# raising that requirement in go.mod; a standard-library one by raising
# GOTOOLCHAIN above.
GOVULNCHECK := golang.org/x/vuln/cmd/govulncheck@v1.8.0
govulncheck:
	go run $(GOVULNCHECK) ./...

# gitleaks scans every commit, not just the files you have now: a key that
# was committed and then deleted is still in every clone. It only scans
# when this directory is the root of its own repository. Before git init
# there is nothing committed, and an app scaffolded inside somebody else's
# checkout must not scan theirs. --redact keeps a finding out of CI logs.
GITLEAKS := github.com/zricethezav/gitleaks/v8@v8.30.1
gitleaks:
	@if [ "$$(git rev-parse --is-inside-work-tree 2>/dev/null)" = true ] && [ -z "$$(git rev-parse --show-prefix)" ]; then \
		go run $(GITLEAKS) git --no-banner --redact --log-opts=HEAD .; \
	else \
		echo "gitleaks: this directory is not the root of a git repository, so there is nothing committed to scan"; \
	fi

# Rastrillo v0.30.0's CLI assumes a single internal app directory. The
# runner protocol is a second package, so call the same dump.Compute API
# from the app test instead of using CLI package discovery.
migration-check:
	CGO_ENABLED=0 go test ./internal/equipo -run '^TestMigrationModels$$' -count=1

runner-prerequisites:
	python3 scripts/runner-prerequisites.py
	@test "$$("$${EQUIPO_BWRAP_PATH:-/usr/bin/bwrap}" --version)" = "bubblewrap 0.11.0"

runner-namespace-test:
	@test "$$(/usr/bin/bwrap --version)" = "bubblewrap 0.11.0"
	CGO_ENABLED=0 EQUIPO_REQUIRE_USER_SESSION=1 RASTRILLO='$(RASTRILLO)' python3 scripts/ci-test.py retried runner-host -run '^TestNamespace' -count=1 ./internal/runner/containment

runner-adapter-test: runner-prerequisites
	CGO_ENABLED=0 RASTRILLO='$(RASTRILLO)' python3 scripts/ci-test.py retried runner-host -run 'TestDirect|TestProvider|TestCheckSandbox' -count=1 ./internal/runner/provider/... ./internal/runner/checks

runner-dead-references:
	python3 scripts/runner-dead-references.py
	python3 native/scripts/check-share.py

# runner-host checks the machine the tests run on, not only the code: the
# exact bubblewrap build, the pinned Codex program, real namespaces, and a
# process moved between two delegated cgroups. Uncached, every time. On
# hosted CI the machine is the CI box (scripts/ci-box.py), which is made
# to pass for a runner host. Its tests have the same one retry as the
# lanes (scripts/ci-test.py retried).
runner-host: runner-adapter-test runner-namespace-test

# ci is the one gate: what a runner executes and what you run before
# pushing are the same definition. amadan's runner falls back to this
# target when .amadan/ci is absent; ci.d/ carries the same targets,
# reported one by one, for a runner with step support. migration-check
# fails the build the moment models.go and migrations/ disagree,
# instead of at boot on whatever machine notices next. If the app
# declares manifest resources, also add: rastrillo generate --check
ci: copy-release-check runner-dead-references lanes-check build vet fmt-check spacing staticcheck govulncheck gitleaks budget test test-quarantine runner-host migration-check perf

.PHONY: copy-release-check direct-release-check release-runner runner-prerequisites
copy-release-check:
	EQUIPO_RELEASE_COPY_CHECK=1 CGO_ENABLED=0 go test ./internal/equipotest -run '^TestReleaseCopyReviewed$$' -count=1

# The programs this repository does not build (claude, codex, its code
# mode host, bwrap) are pinned by digest in internal/release/manifest.json
# and in the provider packages; a release needs both, and the installed
# programs, to agree.
direct-release-check:
	python3 scripts/runner-release-check.py

# What protects a release is where its bytes came from: a clean tree at one
# commit, built by the Go named above. The tool proxy is built first and
# its SHA-256 is linked into both runners and the instance
# (internal/release toolProxySHA256), so a runner installs, and an instance
# serves, only the tool proxy of its own build. Nothing here is typed in
# after a live run, so raising GOTOOLCHAIN needs no one's sign-off. Every
# binary carries its commit (go version -m), the tool proxy too.
TOOL_PROXY_SHA256 = $$(sha256sum $(RUNNER_RELEASE_DIR)/equipo-tool-proxy | cut -d ' ' -f 1)
GITLEAKS_SHA256 = $$(sha256sum $(RUNNER_RELEASE_DIR)/gitleaks | cut -d ' ' -f 1)
# The renderer tree (scripts/build-renderer-tree.py, from the pinned debs
# of internal/release/renderer.json) is named by its MANIFEST: that
# digest is linked into the Linux runner as gitleaks' is, and recorded in
# the install manifest's Linux target. A Mac runner has no renderer.
RENDERER_SHA256 = $$(tar -xzOf $(RUNNER_RELEASE_DIR)/renderer.tar.gz MANIFEST | sha256sum | cut -d ' ' -f 1)
# The archive itself is not in the instance (it would pass the platform's
# 256 MiB ship cap): the Linux runner fetches it from its forge release,
# renderer-<first 12 of its SHA-256> (internal/release RendererForge), and
# checks its digest and size, linked here from the same file. A withdrawn
# release's bytes are published again as renderer-<12>-<RENDERER_REVISION>
# (r2, r3, ...): set it for that build. scripts/publish-renderer.sh
# publishes the kit's archive and SOURCES under the linked tag.
RENDERER_ARCHIVE_SHA256 = $$(sha256sum $(RUNNER_RELEASE_DIR)/renderer.tar.gz | cut -d ' ' -f 1)
RENDERER_ARCHIVE_SIZE = $$(stat -c %s $(RUNNER_RELEASE_DIR)/renderer.tar.gz)
RENDERER_REVISION ?=
RENDERER_TAG = renderer-$$(sha256sum $(RUNNER_RELEASE_DIR)/renderer.tar.gz | cut -c 1-12)$(if $(RENDERER_REVISION),-$(RENDERER_REVISION))
RELEASE_LDFLAGS = -s -w -X amadan.net/rastrillo/rastrillo.BuildVersion=$$(git rev-parse --short HEAD) -X amadan.net/oficina/equipo/internal/release.toolProxySHA256=$(TOOL_PROXY_SHA256)

release-runner: copy-release-check direct-release-check
	@test -z "$$(git ls-files --others --exclude-standard)"
	@git diff --quiet && git diff --cached --quiet || exit 1
	@$(MAKE) --no-print-directory runner-prerequisites
	@mkdir -p $(RUNNER_RELEASE_DIR)
	CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -mod=readonly -trimpath -o $(abspath $(RUNNER_RELEASE_DIR))/gitleaks github.com/zricethezav/gitleaks/v8
	@mkdir -p $(RUNNER_RELEASE_DIR)/darwin-arm64
	CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -mod=readonly -trimpath -o $(abspath $(RUNNER_RELEASE_DIR))/darwin-arm64/gitleaks github.com/zricethezav/gitleaks/v8
	CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags "-s -w" -o $(RUNNER_RELEASE_DIR)/equipo-tool-proxy ./cmd/equipo-tool-proxy
	python3 scripts/build-renderer-tree.py internal/release/renderer.json $(RUNNER_RELEASE_DIR)/renderer.tar.gz
	CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath \
		-ldflags "$(RELEASE_LDFLAGS) -X amadan.net/oficina/equipo/internal/release.gitleaksSHA256=$(GITLEAKS_SHA256) -X amadan.net/oficina/equipo/internal/release.rendererSHA256=$(RENDERER_SHA256) -X amadan.net/oficina/equipo/internal/release.rendererArchiveSHA256=$(RENDERER_ARCHIVE_SHA256) -X amadan.net/oficina/equipo/internal/release.rendererArchiveSize=$(RENDERER_ARCHIVE_SIZE) -X amadan.net/oficina/equipo/internal/release.rendererTag=$(RENDERER_TAG)" \
		-o $(RUNNER_RELEASE_DIR)/equipo-runner ./cmd/equipo-runner
	scripts/no-fake-worker.sh $(RUNNER_RELEASE_DIR)/equipo-runner
	@mkdir -p $(RUNNER_RELEASE_DIR)/darwin-arm64
	CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -trimpath \
		-ldflags "$(RELEASE_LDFLAGS) -X amadan.net/oficina/equipo/internal/release.gitleaksSHA256=$$(sha256sum $(RUNNER_RELEASE_DIR)/darwin-arm64/gitleaks | cut -d ' ' -f 1)" \
		-o $(RUNNER_RELEASE_DIR)/darwin-arm64/equipo-runner ./cmd/equipo-runner
	scripts/no-fake-worker.sh $(RUNNER_RELEASE_DIR)/darwin-arm64/equipo-runner
	cp packaging/equipo-runner.service internal/release/manifest.json $(RUNNER_RELEASE_DIR)/
	cp packaging/install/install-v1.sh $(RUNNER_RELEASE_DIR)/install-v1.sh
	python3 scripts/runner-install-manifest.py $(RUNNER_RELEASE_DIR) "$$(git rev-parse --short HEAD)"
	@git rev-parse HEAD > $(RUNNER_RELEASE_DIR)/COMMIT

.PHONY: e2e-live
e2e-live:
	CGO_ENABLED=0 go test ./internal/runner/provider -run '^Test(Refresh|SourceRefresh)' -count=1
	EQUIPO_E2E_LIVE=1 go test -tags e2elive,browser ./internal/e2elivetest -run '^TestCoordinatorE2ELive$$' -count=1 -timeout=10m -v
