31 Commits
Author SHA1 Message Date
Jeremy Ruppel e049627258 test(coderd/templatebuilder): fix ETXTBSY flake in TestQuickstartCppInstallGuard (#32403)
`TestQuickstartCppInstallGuard` wrote stub executables in parallel
subtests and then executed them through the quickstart install script. A
concurrent fork could inherit a stub's write fd, so the exec failed with
`Text file busy` (golang/go#22315). The stubs are now bash functions
prepended to the script, so the test does not write or execute any
files.

This PR also adds `TestBaseBundlesReferencedFiles`. It walks each base's
rendered `main.tf` HCL and checks that every `file()`/`templatefile()`
path is bundled in `BaseExtraFiles`. It replaces the hand-written
`AWSLinuxExtraFiles` and `AzureLinuxExtraFiles` subtests.

Fixes CLIENT-1102

<details>
<summary>Plan and decision log</summary>

### Fix CLIENT-1102: flake in TestQuickstartCppInstallGuard

#### Problem

`TestQuickstartCppInstallGuard` wrote stub executables in parallel
subtests, then executed the quickstart install script. A concurrent fork
could inherit a stub's write fd, so executing a stub failed with
`ETXTBSY` (golang/go#22315).

#### Decision log

1. Hold `syscall.ForkLock` while writing stubs. Rejected: it keeps the
file setup and protects only this process.
2. Replace the stub files with bash functions, so no file is written or
executed. Implemented.
3. Delete the test and only check that the files are referenced. Tried,
then reverted after review: the test is the only regression test for the
C/C++ install guard (#30374), and running scripts from Go tests is not
against repo policy.
4. Keep the reference check as a separate test. It covers a different
contract: every file that a base's `main.tf` passes to
`file()`/`templatefile()` must be bundled.

#### Change

- `TestQuickstartCppInstallGuard`: define the stubs as bash functions
prepended to the script. `PATH` is an empty temp dir, `sudo` echoes its
arguments, and the test checks stdout for `SUDO: apt-get install`.
- Add `TestBaseBundlesReferencedFiles`: one parallel subtest per base.
Each renders `main.tf` with `testRenderContext`, walks the parsed HCL
for `file()`/`templatefile()` calls, evaluates the path with
`path.module = "."`, and checks that it is a key of `BaseExtraFiles`,
which `Compose` passes through unchanged. A path that is not a literal
fails the test, and so does a base that bundles files without
referencing any of them. Calls in comments and heredocs are ignored.
- Remove the `AWSLinuxExtraFiles` and `AzureLinuxExtraFiles` subtests,
which only listed file names by hand and are now covered by
`TestBaseBundlesReferencedFiles`.

#### Verification

- With the guard set back to gcc only, `MissingCmake` and `OnlyGcc`
fail.
- `go test ./coderd/templatebuilder -run
'^TestQuickstartCppInstallGuard$' -count=500 -cpu=8` passes, as does the
whole package with `-count=20 -cpu=8`.
- Reference check mutations: a renamed quickstart reference, a removed
aws-linux file, and a misspelled DigitalOcean reference each fail the
subtest for that base with a short message. A path that is not a literal
fails. A call in a comment is ignored.
- `golangci-lint` (0 issues), `gofmt`, `git diff --check`.

</details>

---

_Generated with Coder Agents on behalf of @jeremyruppel._
2026-11-18 14:59:15 -05:00
Nick Vigilante 6afd1515e0 fix(coderd/templatebuilder): guard quickstart C/C++ install on every tool it installs (#30374)
The Quickstart base's C/C++ branch guarded on `command -v gcc`, but
installs `gcc g++ make cmake`. `codercom/enterprise-base:ubuntu` ships
gcc but not cmake, so cmake was never installed while the script
reported success. The guard now checks every tool the install provides
(`gcc`, `g++`, `make`, `cmake`).

Adds `TestQuickstartCppInstallGuard`, which runs the rendered C/C++
branch against stubbed tools and asserts the install runs when any of
them is missing. It fails without the fix.

Fixes DOCS-736. The matching example template change is in the DOCS-613
PR.

Generated by Coder Agents on behalf of @nickvigilante.
2026-10-14 12:35:48 -04:00
Michael Suchacz 26e4429362 test: fold near-identical test bodies into tables across eight packages (#29463)
Folds groups of near-identical test bodies (same parent, same parallel
flag, differing only in inputs and expected values) into table-driven
tests in eight packages: `coderd/templatebuilder`, `scripts/develop`,
`agent/agentfiles`, `coderd/x/chatd/chatloop`,
`coderd/x/chatd/chatdebug`, `enterprise/aibridgeproxyd`, `cli`, and
`coderd/database/db2sdk`. One commit per package.

Every case keeps its previous subtest name, `t.Parallel()` placement is
unchanged, and the set of `=== RUN` names is identical except where
standalone `TestX_Y` funcs became `TestX/Y` subtests (chatloop: 9 funcs
into `TestExecuteLocalTools_BatchRuntime`; chatdebug: 15 funcs into two
tables). Members whose bodies differ in more than data stayed as they
were (listed per package in the commit messages). In `agent/agentfiles`
the four `TestFuzzyReplace_*` funcs were already tables, so the shared
request plumbing was hoisted into one helper instead of merging the
funcs and losing their per-rule docs. Net -1035 lines across 9 test
files; runtime is unchanged (all sub-100ms unit tests).

| Package | Diff | Funcs removed | Subtests | RUN lines |
|---|---|---|---|---|
| coderd/templatebuilder | +237 / -291 | 0 | 31 -> 31 | 33 -> 33 |
| scripts/develop | +194 / -246 | 0 | 27 -> 27 | 28 -> 28 |
| agent/agentfiles | +117 / -260 | 0 | unchanged | 58 -> 58 |
| coderd/x/chatd/chatloop | +224 / -306 | 9 | 3 -> 12 | 14 -> 15 |
| coderd/x/chatd/chatdebug | +251 / -537 | 13 | 0 -> 15 | 42 -> 44 |
| enterprise/aibridgeproxyd | +287 / -419 | 0 | 31 -> 31 | 32 -> 32 |
| cli | +143 / -326 | 0 | 15 -> 15 | 16 -> 16 |
| coderd/database/db2sdk | +130 / -233 | 0 | 9 -> 9 | 10 -> 10 |

## Validation

- Per package: `go test -count=1 -tags=testsmallbatch -parallel=8
./<pkg>/ -run <regex> -v` before and after, with the `=== RUN` name sets
diffed
- `go test -race -count=2 -shuffle=on` on each converted test: pass
- `golangci-lint run ./<pkg>/...` with a fresh cache: 0 issues in all
eight packages
- Repository pre-commit hook (including lint/go) passed on every commit

Part of the test-suite speedup series (see #29457); independent of the
other PRs.

## Remote validation

Remote run on a dogfood workspace (separate compute), chat
https://dogfood.cdr.dev/agents/5bbe73d0-866a-4841-9cc3-c5e5b4d97e44,
tested head `d7c55d6b0e8` against base `9d973372774`: all eight packages
pass on the head and under `-race -count=3 -shuffle=on`; package times
are sub-second on both sides (unchanged). `=== RUN` name sets: chatloop
15 to 16 lines with all nine `TestExecuteLocalTools_<X>` leaves
surviving as `TestExecuteLocalTools_BatchRuntime/<X>`; chatdebug 42 to
44; `aibridgeproxyd` `TestNew` 32 to 32, byte-identical sorted list. One
correction to the text above: seven chatdebug leaves are renamed, not
preserved verbatim (`TestRecordingTransport_*UnknownLength*` became
`TestRecordingTransport_UnknownLengthClose/<name without
"UnknownLength">`), so `-run` filters keyed on those old names need
updating. Endorsed verdict: PASS.


> Xum (an AI agent) authored this PR on behalf of @ibetitsmike.
2026-09-17 19:26:18 +02:00
david-fraley fef0763820 feat: report template builder build failure reasons in telemetry (#28586) 2026-09-10 08:21:29 -04:00
Jeremy RuppelandAndrew Aquino 52142e6e94 fix(coderd/templatebuilder): strip prerequisite markers from delivered README (#28953)
## Problem

Template builder base READMEs delimit their prerequisites section with
HTML comment markers (`<!-- prerequisites:start -->` / `<!--
prerequisites:end -->`). `ExtractPrerequisites` uses these to populate
the builder's Prerequisites step, which works correctly.

However, `Compose` embeds the **full** base README verbatim into the
generated template's tarball. Because `react-markdown` renders raw HTML
comments as literal text, the markers were visible when the delivered
README is viewed via `MemoizedMarkdown`.

<img width="876" height="586" alt="Screenshot 2026-09-03 at 3 28 08 PM"
src="https://github.com/user-attachments/assets/70353ee2-1ff6-4e70-9b5d-7ac0521b945f"
/>

## Fix

Strip the prerequisite markers from the README before writing it into
the tarball (Option 2), keeping the change contained to the template
builder and leaving global markdown rendering untouched.

- `prerequisites.go`: new `StripPrerequisiteMarkers` removes each marker
line (plus an optional trailing blank line so no gap is left) while
preserving the content between them.
- `compose.go`: new `composedReadme` helper applies the strip in both
`Compose` return paths; returns `nil` for an empty README, preserving
the existing "omit README.md when empty" behavior.
- `ExtractPrerequisites` still reads the markers from the source
`BaseReadme`, so the builder's Prerequisites step is unaffected.

## Testing

- `TestStripPrerequisiteMarkers` covers both markers, no markers, single
markers, missing trailing blank line, and end-of-file cases.
- Extended the compose test to assert the delivered README contains no
marker text.
- `go test ./coderd/templatebuilder/`, `go vet`, and `golangci-lint run
./coderd/templatebuilder/...` all pass.

<details>
<summary>Approach considered</summary>

Two options were on the table:

1. Skip HTML comments in the shared `MemoizedMarkdown` component (fixes
any stray comment globally, but changes shared rendering behavior
app-wide).
2. Strip the markers from the README before inserting it into the
template zipball (targeted; markers have no purpose in the delivered
README since prerequisites are already extracted separately).

Option 2 was chosen for being contained and easily unit-tested.
</details>

---
_This PR was created by Coder Agents on behalf of @jeremyruppel._

---------

Co-authored-by: Andrew Aquino <dawneraq@gmail.com>
2026-09-04 19:14:10 +00:00
Jeremy Ruppel 7e0f62c204 feat(coderd/templatebuilder): add base agent metadata and per-module agent targeting (#28794) 2026-09-01 13:10:55 -04:00
Jeremy RuppelandCoder Agents a93b2258cf refactor(coderd/templatebuilder): parse rendered HCL with hclparse and support multiple agents (#28787)
Part of [DEVEX-556](https://linear.app/codercom/issue/DEVEX-556).

## Summary

Replaces the Template Builder's regex-based extraction of information
from base-template Terraform with an `hclsyntax` parse of the rendered
output, and removes the single-`coder_agent` assumption from the compose
core.

## What changed

- `render.go`: parse rendered Terraform via `hclsyntax.ParseConfig`
instead of regex.
- Added `ExtractedAgent{Name, Reference}` and
`ExtractAgentResourceNames`, which enumerates every `coder_agent` in
declaration order and reads `count`/`for_each` from each block body.
This is robust to nested blocks (`env {}`, `metadata {}`), fixing a case
the old `[^}]*` regex missed.
- Kept singular `ExtractAgentResourceName` as a compatibility wrapper
that still errors unless exactly one agent exists.
- `ExtractModuleNames` now walks parsed `module` blocks rather than
line-anchored regex.
- `compose.go`: `Compose` wires modules to the base's first/default
agent instead of erroring when a base declares multiple agents.
Single-agent output is byte-identical.
- `render_test.go`: added `TestExtractAgentResourceNames`
(multiple-in-order, `count` after a nested block, no agents).

## Scope

Parsing/compose layer only. Per-module agent **selection** (SDK/UI) is
intentionally out of scope and left as follow-up.

## Testing

- `go test ./coderd/templatebuilder/` passes (golden snapshots
unchanged).
- `golangci-lint run ./coderd/templatebuilder/` reports 0 issues.
- `go build ./coderd/...` succeeds. No new dependencies
(`hashicorp/hcl/v2` already vendored).

<details>
<summary>Design context</summary>

- The `.tf.tmpl` files are Go templates and only become valid HCL after
rendering, so parsing happens on rendered output (which the extractors
already operated on).
- `base.json` stays authoritative; no manifest fields are inferred or
removed here. A survey found `os` is mostly inferable from
`coder_agent.os` (except `scratch`, which uses a dynamic
`data.coder_provisioner.me.os`), and that `variables` cannot be safely
inferred because base variables are Go-template inputs, not Terraform
`variable` blocks. These were left out to keep the change minimal.
- Multiple agents are supported by wiring modules to the first agent in
document order; single-agent bases are unaffected because first == only.

</details>

---
🤖 Generated with Coder Agents on behalf of @jeremyruppel.

---------

Co-authored-by: Coder Agents <agents@coder.com>
2026-08-31 16:59:36 -04:00
Jeremy Ruppel c73f34c35d feat: honor the deployment registry mirror in template builder bases (#28727)
## Summary

Threads the deployment's configured module registry
(`CODER_TEMPLATE_BUILDER_REGISTRY_URL`) into template-builder **base**
rendering, so a base that embeds a catalog module (e.g. the quickstart
base's `git-clone`) resolves its `source` through a registry mirror the
same way wizard-composed modules already do. Previously base-embedded
module sources hardcoded `registry.coder.com`, so on a
mirror/private-registry deployment a base-embedded module reached the
public registry while wizard modules used the mirror.

Implements [DOCS-610](https://linear.app/codercom/issue/DOCS-610).

## What changed

* `BaseRenderContext.RegistryBase` (new field), mirroring
`ModuleRenderContext.RegistryBase`. `Compose` threads the deployment
registry through `renderBase` into the base render context, and the four
hardcoded base module sources (`quickstart` git-clone,
`azure-linux`/`gcp-linux`/`gcp-windows` region modules) now use `{{
.RegistryBase }}`. Because the value defaults back to
`registry.coder.com`, rendered sources stay byte-identical; the only
golden change is the removal of the now-stale quickstart "follow-up"
note.
* **Boot-time validation.**
`codersdk.ValidateTemplateBuilderRegistryURL` runs in
`DeploymentValues.Validate()`, gated on the builder being enabled,
matching the chat-hook precedent. A malformed value fails at server
start naming the option, instead of surfacing as a per-request error to
a template author who cannot fix it. It uses `net/url` in authority form
to reject a scheme, path, query, fragment, trailing slash, or
credentials and accept a bare `host[:port]`; it does not canonicalize
the host.
* `Compose` **trusts the validated value**, defaulting an unset one and
defensively rejecting a malformed one for direct callers that bypass
boot.

## Tests

* `codersdk`: validator accept/reject matrix (incl.
credentials-without-echo) and a `DeploymentValues.Validate` boundary
test with a disabled-skips-validation case.
* `templatebuilder`: a base honors the mirror and falls back to the
default when unset, plus a defensive-reject case; existing compose tests
updated to bare-host registry values.

<details><summary>Design decision log</summary>

This PR is a deliberately minimal reimplementation of the
[DOCS-610](https://linear.app/codercom/issue/DOCS-610/template-builder-base-embedded-modules-should-honor-the-deployment)
scope, started fresh from `main` rather than carrying forward an
earlier, larger draft (coder/coder#28480). Key decisions:

* **Scope kept to the ticket.** The ticket's fix is three bullets: add a
registry field to `BaseRenderContext`, thread the deployment
`RegistryURL` through `Compose` -> `renderBase`, and use it in base
module sources. Independent hardening explored in the earlier draft was
dropped as out of scope: `terraform-svchost`-based IDN/punycode/port
canonicalization, a rendered-HCL backstop with a 500 mapping, and HCL
module-source extraction helpers. Telemetry misclassification of mirror
modules is tracked separately
([DOCS-712](https://linear.app/codercom/issue/DOCS-712/telemetry-misclassifies-registry-mirror-modules-as-non-coder))
and is not addressed here.
* **Default lives in the render layer.**
`templatebuilder.DefaultRegistryBase` holds the fallback host;
`codersdk` keeps its own option-default literal. An earlier version
exported the constant from `codersdk`, which only emitted a dead
`typesGenerated.ts` entry that nothing in the frontend consumed, so it
was moved out. The `codersdk` validator is a function, so it generates
no TS type.
* **Validate at the config boundary, fail fast.** The repo convention is
to hard-fail structurally invalid config in
`DeploymentValues.Validate()` (access URL, OAuth lifetimes, chat hook
URL) and to warn only for functional-but-risky settings. A malformed
registry host is structurally invalid, so it fails at boot. This also
puts the error in front of the admin who set it, rather than a template
author hitting a per-request error they cannot fix.
* `net/url`**, not a regex.** The codebase validates identifiers/names
with regexes but host/URL-shaped config with `url.Parse` (chat hook URL,
OAuth redirect URIs, AI provider base URL). This value is host-shaped,
so it follows that convention. `url.Parse("//" + v)` with `u.Host == v`
rejects a scheme/path/query/fragment/trailing-slash in one check.

</details>

> This PR was created with AI assistance (Coder Agents).
2026-08-31 09:32:24 -04:00
Nick Vigilante c78dca5141 feat: add Coder Quickstart base to the template builder (#27247)
## Summary

Adds the **Coder Quickstart** template as a selectable base in the
[template builder](coderd/templatebuilder) guided wizard. It is a
Docker-based starter that lets a user pick languages and optionally
clone a repo.

## What changed

- **New base package** `coderd/templatebuilder/bases/quickstart/`:
- `base.json`: `id: "quickstart"`, `display_name: "Coder Quickstart"`,
`os: "linux"`.
- `main.tf.tmpl`: a Docker workspace with a language selector, a single
language-install script, an optional Git clone, and workspace presets.
Editors are added via the builder's module step rather than baked into
the base.
- `install-languages.sh.tftpl` and `README.md` (with prerequisites
markers so the builder can extract the prerequisites section).
- **Placement**: the bases endpoint returns a plain list sorted by
display name (with ID as a deterministic tiebreak). The wizard's
base-infra select step prioritizes the Quickstart and Docker starters to
the front on the client, mirroring the existing client-side module
prioritization in `ModuleSelectStep` (shared `sortByPriority` helper).
- **Base/module collision guard**: a base's bundled catalog modules are
derived from its rendered Terraform (`ExtractModuleNames`, cached with
`sync.OnceValues` and filtered to catalog IDs). `validateModules` seeds
its seen-set from that derived set, so a wizard-selected module the base
already renders is rejected with a clear error, and the modules endpoint
omits it so the wizard never offers a colliding module. The base's
Terraform is the single source of truth, so there is no separate
manifest list that can drift.

## Testing

- `go test ./coderd/` (template builder handler: bases ordering, the
`baseSpec` table, the modules-endpoint base filter): pass.
- `go test ./coderd/templatebuilder/` (all-bases render/snapshot, the
collision guard, `TestBaseIncludedModules`, the selector/install-script
drift test): pass.
- `gofmt`, `go vet`, `golangci-lint`: clean.
- Frontend `tsc`, `biome`, and `knip`: clean.

## Review decisions

- **Template scope**: trimmed to infrastructure, a language selector,
and an optional Git clone. The IDE selector was removed; editors are
added via the builder's module step.
- **Placement**: base ordering is presentational, so it lives on the
client base-infra select step rather than in the API.
- **git-clone in the base**: kept for the build-time clone affordance.
The base renders its module source verbatim, so it currently pins the
public registry and does not yet honor a deployment's registry mirror;
that fix is tracked in DOCS-610 and delivered as a stacked follow-up PR
(an in-code note documents the current behavior).
- **Container image**: left hardcoded
(`codercom/enterprise-base:ubuntu`). The quickstart base is the
opinionated path; the Docker base covers custom images. Revisiting a
`container_image` variable is tracked in DOCS-611.

## Review updates (@jeremyruppel)

- **Ordering moved to the client**: deleted the server-side
Quickstart-before-Docker grouping (and its position test); the
base-infra select step now prioritizes bases client-side via a shared
`sortByPriority` helper, following the `ModuleSelectStep` precedent. The
API just returns a stable, name-sorted list.
- **Derive included modules from render**: dropped the
`included_modules` manifest field and the `IncludedModules` struct
field; `BaseIncludedModules` now derives from the rendered base (single
source of truth). Removed `TestBaseIncludedModulesMatchRendered` and
added a direct `TestBaseIncludedModules`.
- **Kept the PR scoped to "add quickstart base"**: reverted
`ExtractAgentResourceName`/`ExtractModuleNames` to the pre-`hclsyntax`
regex extraction and removed the option/preset HCL extractor family; the
selector↔install-script drift test now uses a small regex. The broader
templatebuilder HCL migration and the preset-language subset guard are
tracked in DOCS-735.
- Branch rebased onto `origin/main` (no content changes beyond the
above).

---

Linear:
[DOCS-558](https://linear.app/codercom/issue/DOCS-558/add-coder-quickstart-template-to-template-builder)

> This PR was created with AI assistance (Coder Agents).
2026-08-26 20:29:20 -04:00
Jeremy Ruppel d0982e3cc7 fix(coderd/templatebuilder): prompt for DigitalOcean base variables (#27268)
## Summary

The DigitalOcean template builder base declared Terraform `variable`
blocks for `project_uuid` and `ssh_key_id` that the template builder
never filled. `project_uuid` was required with no default, so the build
broke with no way to supply a value from the wizard (DEVEX-591).

This brings the DigitalOcean base to parity with the GCP bases fixed in
#27015:

- Declare `project_uuid` (required) and `ssh_key_id` (optional, default
`0`) in `base.json` so the wizard prompts for them on the first step.
- Inject the entered values via `default = {{ .Variables.* }}` in
`main.tf.tmpl`, keeping the existing `variable` blocks and validation.
- Drop the `sensitive` flags. The variable-injection path
(`mergeBaseVariables`, `DefaultBaseRenderContext`, and the snapshot test
helper) skips sensitive variables, so a sensitive base variable renders
empty. A project UUID / SSH key ID are not secrets.
- Update the README now that the values are prompted rather than
manually edited.
- Regenerate the `digitalocean-linux.tf.golden` snapshot.

## Testing

- `go test ./coderd/templatebuilder/`

<img width="1048" height="616" alt="Screenshot 2026-07-15 at 12 44
42 PM"
src="https://github.com/user-attachments/assets/89e334ca-e904-4387-9264-6ed1614a40ba"
/>

<details>
<summary>Audit of all template builder bases for unfilled
variables</summary>

| Base | Variable status | Verdict |
|------|-----------------|---------|
| aws-linux | no HCL `variable` blocks; provider env auth | OK |
| aws-windows | same | OK |
| azure-linux | same | OK |
| **digitalocean-linux** | `project_uuid` (required, no default) +
`ssh_key_id`; absent from `base.json` | **Fixed here** |
| docker | `docker_socket` has `default = ""`; `container_image` via `{{
.Variables }}` + declared | OK |
| gcp-linux | fixed in #27015 | OK |
| gcp-windows | fixed in #27015 | OK |
| kubernetes | `namespace` (required), `use_kubeconfig`,
`container_image` all via `{{ .Variables }}` + declared | OK |
| scratch | no variables | OK |

DigitalOcean was the only broken base; all others either have safe
defaults or already declare their variables.

**Mechanism note:** `base.json` `variables[]` drives the first-step
prompts and values are injected as HCL literals via `{{
.Variables.<name> }}` (strings quoted, numbers/bools raw; supported
types: string, number, bool). Sensitive/computed variables are
intentionally skipped everywhere the injection map is built, so they
cannot currently be injected. That is why the `sensitive` flags were
removed here.
</details>

---
*This PR was generated by Coder Agents on behalf of @jeremyruppel.*
2026-07-15 14:05:18 -04:00
Jeremy Ruppel 581f906947 fix(coderd): declare project_id variable in GCP template builder bases (#27015)
## Summary

GCP base templates (`gcp-linux`, `gcp-windows`) in the Template Builder
had a Terraform `variable "project_id"` with no default, but their
`base.json` manifests didn't declare it. The UI never prompted for it,
so the provisioner import always failed with:

```
required template variables need values: project_id
```

## Changes

- Add `project_id` as a required variable in both GCP `base.json`
manifests
- Convert templates from raw Terraform variable blocks to Go template
injection (`{{ .Variables.project_id }}`), matching the existing
kubernetes pattern
- Fix `DefaultBaseRenderContext` to supply a `"REQUIRED"` placeholder
for required variables without defaults (previously rendered as `<no
value>`)
- Replace duplicate test subtests with proper GCP coverage including a
missing-variable error case

<details>
<summary>Implementation plan</summary>

### Root cause

The GCP base templates contained `variable "project_id" {}` (no default
= required) in their `.tf.tmpl` files, but the `base.json` manifests had
an empty `variables` array. The Template Builder UI
(`BaseTemplateParametersStep`) is data-driven from `base.json`, so it
never showed a field for `project_id`. The composed Terraform output
still contained the required variable, causing the provisioner import to
fail.

### Fix approach

Follow the pattern established by the kubernetes base template:
1. Declare variables in `base.json` so the UI prompts for them
2. Use Go template syntax (`{{ .Variables.project_id }}`) to inject
values at compose time
3. Remove raw Terraform `variable` blocks from the template since the
value is now baked in

### Files changed

| File | Change |
|---|---|
| `bases/gcp-linux/base.json` | Added `project_id` as a required
variable |
| `bases/gcp-windows/base.json` | Added `project_id` as a required
variable |
| `bases/gcp-linux/main.tf.tmpl` | Removed Terraform variable block, use
Go template injection |
| `bases/gcp-windows/main.tf.tmpl` | Same |
| `bases.go` | `DefaultBaseRenderContext` supplies placeholder for
required vars without defaults |
| `compose_test.go` | Replaced duplicate subtests with proper GCP tests
|
| `templatebuilder_handler_test.go` | Updated `gcp-windows` spec to
expect `project_id` variable |
| Golden files | Regenerated |

</details>

> 🤖 Generated by Coder Agents on behalf of @jeremyruppel
2026-07-06 16:48:00 -04:00
Ben PotterandJeremy Ruppel 7b19ec3933 feat: improve the image management experience with template builder (#27018)
Makes it easier to pick the right workspace image, both in the template
builder and in the docs.

- Template builder: the Docker and Kubernetes bases now expose a
`container_image` variable in the wizard (freeform text, defaults to
`codercom/example-base:ubuntu`), and their prerequisites explain why
image choice matters, with tradeoffs between
`codercom/example-base:ubuntu` (minimal) and
`codercom/example-universal:ubuntu` (catch-all), plus pointers to
[coder/images](https://github.com/coder/images) and the image management
docs.
- Docs: reworked [image
management](https://coder.com/docs/@ben%2Fdevrel-201-image-guidance-prereqs/admin/templates/managing-templates/image-management)
into a clearer maturity ladder (minimal → golden → project-specific →
developer customization), with pullable image references in every
example, `codercom/oss-dogfood` as a project-specific example, and Dev
Containers + [mise](https://mise.jdx.dev/) as ways to customize without
new images.

Companion PR for the starter templates: coder/registry#943

Part of DEVREL-201.

🤖 Generated with Coder Agents using Claude, on behalf of @bpmct (wizard
variable by @jeremyruppel in #27024)

---------

Co-authored-by: Jeremy Ruppel <jeremyruppel@users.noreply.github.com>
2026-07-06 20:37:34 +00:00
Jeremy Ruppel 3d966d48b5 fix(coderd/templatebuilder): fix archive bundling for nested static files and counted agents (#26901)
Fixes two template builder bugs that caused AWS EC2 (Linux) template
imports to fail:

1. **Missing directory entries in tar archive**: `BundleTar` wrote
static files with nested paths (e.g.
`cloud-init/cloud-config.yaml.tftpl`) without emitting `TypeDir` entries
for parent directories. The provisioner's archive extractor requires
explicit directory entries and failed with "no such file or directory".

2. **Incorrect agent reference for counted resources**:
`ExtractAgentResourceName` returned `dev` for the AWS Linux base
template, but the agent uses `count =
data.coder_workspace.me.start_count`, so module templates need
`coder_agent.dev[0].id`. The function now detects `count`/`for_each` and
appends `[0]`.

> [!NOTE]
> Generated by Coder Agents (on behalf of @jeremyruppel)
2026-06-30 19:37:30 -04:00
Jeremy Ruppel a48ace5017 fix(coderd/templatebuilder): include Terraform diagnostics in import errors (#26677)
`ClassifyProvisionerError` previously returned only the raw job error
string (e.g. "terraform plan: exit status 1") for unrecognized failures,
discarding the provisioner log lines it already had. This made template
import errors in the builder unactionable.

Now the function extracts Terraform diagnostic blocks (Error:/Warning:
lines and their context) from the provisioner logs and appends them to
the error detail. This surfaces the actual failure cause (missing
credentials, invalid references, unsupported blocks) in the ErrorAlert
banner.

Changes:
- `extractDiagnostics` parses Terraform diagnostic blocks from log
output, capped at 20 lines with a truncation marker
- Auth error classification for AWS, GCP, Azure credential failures with
a targeted user-facing message
- Case-insensitive pattern matching via `strings.ToLower` on the
combined text
- Auth branch guarded against empty diagnostics (no trailing `\n\n`)

> [!NOTE]
> This PR was authored by Coder Agents on behalf of @jeremyruppel.
2026-06-30 18:43:58 -04:00
Jeremy Ruppel c40b3b9bcb feat: add base templates for all major cloud providers (#26634)
Add 6 new base templates to the template builder, covering all major
cloud providers and platforms:

- **scratch**: Minimal starter template with only `coder_agent` and
metadata
- **aws-windows**: AWS EC2 Windows instances with PowerShell user_data
- **azure-linux**: Azure VMs with cloud-init and managed disk
persistence
- **gcp-linux**: Google Compute Engine Linux instances with persistent
disk
- **gcp-windows**: Google Compute Engine Windows instances
- **digitalocean-linux**: DigitalOcean Linux droplets with persistent
volumes

Each base includes `base.json`, `main.tf.tmpl`, `README.md` (with
prerequisite markers), and any static files (cloud-init configs). Tests
verify all 9 bases load, render without error, and produce valid
single-agent declarations.

`azure-windows` is deferred; it needs to be registered in the `examples`
package first.

Depends on #26633

> [!NOTE]
> This PR was authored by Coder Agents on behalf of @jeremyruppel.

---

NB: This is very much an agent-generated PR and draws completely from
base templates that exist in `examples/templates/`. The base.json files
are new, so review those, but don't spend any brain tokens on the
correctness of the terraform and supporting files: any issues there are
issues with the upstream example template
2026-06-30 18:26:31 -04:00
Jeremy Ruppel 6f0b81cfbc feat(coderd/templatebuilder): validation extraction, static file bundling, Windows OS (#26633)
Extract validation helpers to a dedicated file, add static file bundling
for base templates, and add Windows OS support.

**Commit 1: Extract validation to `validate.go`**
Move `validateVariableValue`, `validateStringValue`,
`validateNumberValue`, `validateBoolValue`, `toHCLLiteral`, `hclQuote`,
and `isSimpleJSONValue` from `compose.go` into `validate.go`.
Corresponding tests move to `validate_internal_test.go`. This keeps
`compose.go` focused on the compose pipeline.

**Commit 2: Static file bundling**
Add `StaticFiles` field to `ComposeResult` and a `collectStaticFiles`
helper that walks the base template FS to collect non-template files
(e.g. cloud-init `.tftpl` inputs). `BundleTar` now writes these files
into the output archive in sorted order for deterministic output. This
fixes `aws-linux`, whose cloud-init files were embedded but never
included in the tar.

**Commit 3: Windows OS support**
Add `BaseOSWindows` constant and register `"windows"` in `validBaseOS`
so that base templates with `os="windows"` can be loaded and used for
module compatibility filtering.

> [!NOTE]
> This PR was authored by Coder Agents on behalf of @jeremyruppel.
2026-06-30 18:08:02 -04:00
Jeremy Ruppel 7daf3123cb feat: import new modules and refactor codegen script (#26838) 2026-06-29 17:47:06 -04:00
Jeremy Ruppel 48e8f70e09 fix: remove Goose module from catalog (#26833)
Removes the Goose AI agent module from the template builder backend
catalog.

## Changes

- Deleted `coderd/templatebuilder/modules/goose/` (Terraform template
and module metadata)
- Removed the `"goose"` entry from
`scripts/templatebuildermodulegen/main.go`

Frontend assets (`goose.svg`, `icons.json`) are intentionally left in
place as other parts of the app still reference them.

> Generated by Coder Agents on behalf of @jeremyruppel
2026-06-29 16:52:41 -04:00
Jeremy Ruppel 7bdeee166c fix(coderd/templatebuilder): shorten long module variable descriptions (#26747) 2026-06-26 10:57:01 -04:00
Jeremy Ruppel 10717572ac feat: show template prerequisites in builder UI (#26523)
Surface base template prerequisites to admins before they create a
template in the Template Builder wizard.

Today, template prerequisites (Docker socket setup, Kubernetes auth, AWS
IAM policies) are only visible in the registry README after import.
Admins hit opaque provisioner errors and have to hunt for docs. This
change extracts the prerequisites from the README and serves them via
the API so the frontend can display them inline.

## How it works

Each base template README uses HTML comment markers (`<!--
prerequisites:start -->` / `<!-- prerequisites:end -->`) to delimit the
prerequisites section. At boot time, the base catalog loader reads the
README, extracts the content between markers via `strings.Index`, and
caches both the full README and the prerequisites string.

The prerequisites are served via a new `prerequisites` field on `GET
/api/v2/templatebuilder/bases`. The full README is included in the
composed template tar bundle and stored as the template version readme.

## Changes

- Add `README.md` with prerequisite markers to
`coderd/templatebuilder/bases/{docker,kubernetes,aws-linux}/`
- New `ExtractPrerequisites()` in `prerequisites.go` using literal
string matching
- `bases.go`: load README at boot, fail loudly if missing, extract
prerequisites
- `compose.go`: include README in `ComposeResult` and tar bundle
- `codersdk`: add `Prerequisites` field to `TemplateBuilderBase`
- Handler: populate prerequisites in bases response, set readme on
template version

<details>
<summary>Implementation notes</summary>

- Prerequisites extraction uses `strings.Index` for exact literal marker
matching; no regex or AST parser needed since we control the markers.
- YAML frontmatter is deliberately retained in the stored README. The
frontend `TemplateDocsPage` already strips it at render time via
`front-matter`.
- The prerequisite markers are HTML comments, invisible in rendered
markdown.
- The `RejectsMissingReadme` test enforces that every base template must
include a README.
- AWS Linux prerequisites span two H2 sections (`## Prerequisites` and
`## Required permissions / policy`), which is why heading-based parsing
was rejected in favor of explicit markers.

*Generated with the assistance of an AI coding agent. Reviewed by
@jeremyruppel.*
</details>

Relates to https://linear.app/codercom/issue/DEVEX-446
2026-06-23 11:36:07 -04:00
Jeremy Ruppel 7ea5d48296 fix: render base variables into templates instead of tfvars (DEVEX-287) (#26436)
Part of the Template Builder wizard PR stack.

## Problem

The kubernetes base template used Terraform `variable` blocks and
`var.*` references for `use_kubeconfig` and `namespace`, but the
composed tar bundle never included a `.tfvars` file. This caused
`terraform plan` to fail with "required template variables need values:
namespace".

## Fix

Base templates now use Go template variables (`{{ .Variables.* }}`) just
like module templates do. Values are validated, HCL-quoted, and rendered
directly into the output HCL.

Also adds explicit "variable is required" validation to both
`mergeBaseVariables` and `mergeModuleVariables`, replacing the previous
reliance on `missingkey=error` at render time for clearer error
messages.

---
> [!NOTE]
> Generated by Coder Agents on behalf of @jeremyruppel
2026-06-23 11:26:38 -04:00
Jeremy Ruppel a30631198d feat: template builder backend fixes (DEVEX-287) (#26432)
Part of the Template Builder wizard PR stack.

## Backend fixes

1. **Registry URL scheme fix**: Default
`CODER_TEMPLATE_BUILDER_REGISTRY_URL` was `https://registry.coder.com`
but Terraform module registry addresses must be scheme-less. Changed to
`registry.coder.com`.

2. **Sensitive variable defaults**: Module `.tf.tmpl` files for
claude-code, aider, amazon-q had sensitive `variable` blocks without
`default`, causing `terraform plan` to fail during template import. Also
fixed the `templatebuildermodulegen` script.

3. **Auto-quote string variables**: The backend now accepts raw string
values from callers and wraps them in HCL quotes automatically.
Previously callers were required to send pre-quoted HCL literals, which
is not a reasonable API contract.

---
> [!NOTE]
> Generated by Coder Agents on behalf of @jeremyruppel
2026-06-23 09:17:14 -04:00
Jeremy Ruppel 87de6dc23e feat: add base template variables to API (#26425) 2026-06-17 12:22:35 -04:00
Jeremy Ruppel de31c7c18e feat: add TemplateBuilderCreateTemplate SDK types and client method (#26360)
Adds `POST /api/v2/templatebuilder/compose/template`, a synchronous
endpoint that composes a template from a base and modules, validates it
via a provisioner import job, and creates the template in a single
request.

The handler composes terraform files, bundles them as a tar, inserts the
file with hash-based dedup, creates a template version with an import
job, waits up to 2 minutes for the job to complete, classifies errors
for known failure modes (network-unreachable registry, DNS failures),
then creates the template on success. Canceled and failed jobs return
appropriate error responses.

Also adds `hclwrite.Format` to composed terraform output for canonical
HCL formatting.

Closes https://linear.app/codercom/issue/DEVEX-279

<details>
<summary>Implementation notes</summary>

- SDK types and client method in `codersdk/templatebuilder.go` with
validation tags matching the standard template creation path
(`template_display_name`, `lt=128`)
- `ClassifyProvisionerError` in `coderd/templatebuilder/errors.go`
detects DNS, connection refused, i/o timeout, and TLS handshake failures
and returns actionable messages
- `waitForProvisionerJob` polls with a ramp-up interval schedule (100ms,
200ms, 500ms, then 1s steady) and accepts an `onUpdate` callback for
future SSE streaming
- Audit logging for both template and template version creation
- TOCTOU name uniqueness: early check for fast feedback, DB unique
constraint catch for the race window (returns 409, not 500)
- Swagger annotations for all error responses (400, 404, 409, 504)

</details>

> 🤖 Generated by Coder Agents
2026-06-15 18:12:55 -04:00
Jeremy Ruppel 4574c7d792 feat: validate module variable keys and values (#26354)
Validates caller-supplied module variable keys and values in the
template builder compose endpoint before template rendering. Previously,
`mergeModuleVariables` accepted any caller-supplied key and value
without validation, allowing unknown keys, computed/sensitive variable
overrides, and malformed HCL literals (including injection payloads) to
pass through to rendered output.

Now `mergeModuleVariables` rejects unknown keys (those not in the
manifest's non-computed, non-sensitive variables) and type-checks
values: strings must be quoted HCL literals without interpolation
markers or unescaped newlines, numbers must be strict numeric literals,
and bools must be exactly `true` or `false`. The literal `null` is
accepted for any type.

Closes https://linear.app/codercom/issue/DEVEX-278

<details>
<summary>Implementation details</summary>

- Changed `mergeModuleVariables` signature from `map[string]string` to
`(map[string]string, error)` to surface validation failures
- Added `validateVariableValue`, `validateStringValue`,
`validateNumberValue`, `validateBoolValue` in `compose.go`
- String validation rejects: unquoted values, HCL interpolation (`${`,
`%{`), unescaped newlines/quotes, trailing backslashes (which would
escape the closing delimiter), and values exceeding 4096 bytes
- Errors wrap the module ID and variable name for clear diagnostics
(e.g. `module "code-server": variable "port": invalid number value`)
- Tests cover key validation, type validation, injection attempts, and
full Compose flow integration

> Generated with the help of [Coder Agents](https://coder.com) by
@jeremyruppel
</details>
2026-06-15 11:34:47 -04:00
Jeremy Ruppel 877f4def4a feat(coderd/templatebuilder): add Compose and BundleTar functions (#26349)
> [!NOTE]
> This PR was authored by Coder Agents on behalf of @jeremyruppel.

Part 2 of DEVEX-277 (POST /api/v2/templatebuilder/compose).

Adds the core composition and bundling logic for the template builder.

`Compose` renders a base template and selected modules into Terraform source files. It validates modules before rendering (rejects duplicates, ConflictsWith violations, unknown IDs, OS incompatibility), then for each module merges manifest defaults with caller-supplied variable overrides and renders the module template.

`mergeModuleVariables` fills in defaults for non-computed, non-sensitive variables from the manifest (with basic JSON type validation via `isSimpleJSONValue`), uses `null` for non-required variables without defaults, and leaves required variables absent so `missingkey=error` catches omissions at render time.

`BundleTar` packages the result into a tar archive with reproducible timestamps. Writes `main.tf` always, `modules.tf` only when modules are present.

Conflict detection is bidirectional so module ordering in the request does not affect validation.
2026-06-15 09:28:39 -04:00
Jeremy Ruppel 6b890116aa feat(coderd/templatebuilder): add module rendering and agent name extraction (#26347)
> [!NOTE]
> This PR was authored by Coder Agents on behalf of @jeremyruppel.

Part 1 of DEVEX-277 (POST /api/v2/templatebuilder/compose).

Adds module rendering support and agent resource name extraction to the template builder, preparing for the compose endpoint.

- `ModuleRenderContext` and `RenderModuleTemplate` for rendering module `.tf.tmpl` files with registry URL, pinned version, agent resource name, and variable values. Nil-guards the Variables map to prevent panics.
- Extract shared `renderTemplate` with `missingkey=error` so missing variable keys fail loudly instead of producing `<no value>` in rendered HCL.
- `ExtractAgentResourceName` uses a regex to find the `coder_agent` resource name from rendered base HCL. Errors unless exactly one agent is found.
- `ModuleTemplateFS` exposes module template files from the embedded catalog, with validation that the expected `.tf.tmpl` file exists (`fs.Sub` on `embed.FS` silently succeeds for nonexistent paths).
2026-06-15 09:27:39 -04:00
Jeremy Ruppel 1cdb7ed9f7 feat(coderd/templatebuilder): author initial module catalog for 19 modules (#26194)
> [!NOTE]
> This PR was authored by Coder Agents on behalf of @jeremyruppel.

Runs the `scripts/modulegen` generator against the coder/registry to produce the initial module catalog for the template builder. Generates `module.json` and `.tf.tmpl` files for 19 modules across four categories:

- **IDE**: code-server, jetbrains, vscode-desktop, vscode-web, cursor, windsurf, zed, kiro
- **AI Agent**: claude-code, aider, goose, amazon-q
- **Source Control**: git-clone, git-config, git-commit-signing
- **Utility**: dotfiles, personalize, filebrowser, jupyterlab

Also updates `catalog_test.go` to validate the new embedded modules load correctly.
2026-06-15 09:26:39 -04:00
Jeremy Ruppel 9a6e348f5d feat: add GET /api/v2/templatebuilder/modules endpoint (#26117)
Implement `GET /api/v2/templatebuilder/modules`, which returns the
filtered list of modules available for a given base template. Reads from
the bundled catalog via `LoadModules()` and applies OS-compatibility
filtering based on the `base` query param.

Computed variables (e.g. `agent_id`) are excluded from the API response
at the `ToSDK()` conversion boundary since they are wired automatically
by the builder. The `Computed` field is removed from the SDK type. Adds
`CompatibleWithOS()` to `ModuleManifest` for OS filtering.

Returns 400 for unknown base IDs and 404 when the template builder is
disabled.

Depends on #26116

> [!NOTE]
> This PR was authored by Coder Agents on behalf of @jeremyruppel.
2026-06-12 17:53:48 -04:00
Jeremy Ruppel 71957a2bc0 feat(coderd/templatebuilder): add exampleID->OS map and base template .tf.tmpl files (#26115)
Add the bundled `exampleID -> OS` Go map for Docker, Kubernetes, and AWS
EC2 Linux base templates. Create `.tf.tmpl` Go template files for each
within `coderd/templatebuilder/bases/`, along with `BaseRenderContext`
and `RenderBaseTemplate` rendering helpers.

The `.tf.tmpl` files are independent copies of the example templates
with module blocks (code-server, jetbrains) removed, since the template
builder composes modules separately into `modules.tf`. When
`ImageOptions` is provided, the container image field references the
Terraform parameter; otherwise it uses the hardcoded value via Go
template whitespace control (`{{-`).

Golden file snapshot tests verify rendered output stability with an
`-update` flag for regeneration.

Depends on #25909

> [!NOTE]
> This PR was authored by Coder Agents on behalf of @jeremyruppel.
2026-06-12 17:12:17 -04:00
Jeremy RuppelandMcKayla はな dd7d2653ca feat: add template builder module catalog structure and go:embed wiring (#25909)
Scaffolds the `coderd/templatebuilder` package for the guided template
builder ([DEVEX-272](https://linear.app/codercom/issue/DEVEX-272),
[RFC](https://www.notion.so/coderhq/RFC-Guided-Template-Creation-Workflow-342d579be59280dfbf8eea2e5006dbda)).

Adds the module catalog types and `go:embed` wiring that the template
builder endpoints will use:

- `codersdk.TemplateBuilderModule`, `TemplateBuilderModuleVariable`, and
related types matching the RFC schema
- Internal `ModuleManifest` type with `go:embed` wiring to bundle
`module.json` files from `coderd/templatebuilder/modules/`
- `LoadModules()` with defensive copy, unexported
`parseModulesFromFS(fs.FS)` for test isolation, `ToSDK()` conversion
- Real `code-server` module manifest as the first catalog entry
- Strict validation: ID uniqueness, version non-empty, variable
type/name validation, `DisallowUnknownFields`, and requiring
`module.json` in every module directory
- Tests via internal `catalog_internal_test.go` (for
`parseModulesFromFS` with `fstest.MapFS` fixtures) and external
`catalog_test.go` (for `LoadModules` and `ToSDK`), covering multi-module
parsing, all variable types, validation errors, nil-slice normalization,
and full SDK field assertions

> [!NOTE]
> Generated with [Coder Agents](https://coder.com/agents) by
@jeremyruppel

---------

Co-authored-by: McKayla はな <mckayla@hey.com>
2026-06-12 09:40:36 -04:00