oficina / equipo Public

places: protocol 31 and the runner's place-bound publish

Wire (protocol 31): a hello's reach (owner logins per console, deploy
keys held or lost, no secret) and carlos health; a publish dispatch bound
to its place (console, sqid, account, app, revisions, destination hash,
mode, key name); publish and mint checks carrying the destination; four
place tools and the place card. Below 31 the hello's fields are dropped
and a publish dispatch, a publish or mint check and a place tool's call
are refused: an older runner would deploy to its fixed account, an older
instance would decide a check without the destination.

Runner: one carlos lookup, its version read at start and hourly; preview
and publish refuse carlos_outdated below v0.43.0 before building. Reach
from the credential file's live https consoles (names only) and accounts
list owner rows. Publish in the tapped mode only: setup (strict taken
check, deploy with the login behind its check, creation recorded, mint
behind its own check), mint (only with this runner's creation record at
that exact place; else app_unproven or app_missing), publish (the held
key only; CARLOS_SERVICE_TOKEN and CARLOS_CONSOLE, credentials named
absent). Keys 0600 by atomic rename outside sandbox mounts; a lost mint
stays reported until a key is held. The trusted secret scan runs on the
exact export. EQUIPO_SITE_HOST and the oficina constants are gone.

Mutation checks (each guard broken, test failed, restored):
WIRE: publish dispatch refusal <31 off KILLED places_test:45; console
twice KILLED; ok with an old carlos KILLED; WithoutPlaces off KILLED
places_test:50; publish/mint check refusal off KILLED; account twice
KILLED; version compare inverted KILLED.
RUNNER (CGO_ENABLED=0): key publish with the login KILLED
SetupThenPublish; mint without a creation record KILLED MintRecovery:487;
scan skipped KILLED Fence:609; setup mint check skipped KILLED
MintLost:527; destination hash unchecked KILLED Fence:575; preview carlos
guard off KILLED PreviewRefusesOldCarlos:25; lax list parser KILLED
NameTaken:411; rungs unchecked KILLED DeployArgs:697; Link check <31
allowed KILLED Handshake; publish carlos guard off KILLED Fence:595; lost
intent kept after storing KILLED MintLost:520; key deploy keeps the login
KILLED SetupThenPublish:382.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 20fb73b670376a38f7e19567a7a996b1efad8057 parent a2018cb
42 files changed, +2,246 −485
  • docs/api/equipo-v1.openapi.json +174 −3
  • internal/headless/assistant_test.go +6 −3
  • internal/runner/config.go +6 −9
  • internal/runner/provider/actions.go +1 −1
  • internal/runner/provider/claude/launcher.go +1 −1
  • internal/runner/thin/bridge.go +3 −0
  • internal/runner/thin/capabilities.go +10 −2
  • internal/runner/thin/carlos.go +150 −0
  • internal/runner/thin/carlos_test.go +33 −0
  • internal/runner/thin/claude.go +2 −2
  • internal/runner/thin/contract_test.go +3 −0
  • internal/runner/thin/engineer.go +7 −1
  • internal/runner/thin/link.go +22 −6
  • internal/runner/thin/mcp.go +5 −1
  • internal/runner/thin/places.go +20 −0
  • internal/runner/thin/preview.go +5 −0
  • internal/runner/thin/preview_security_test.go +1 −1
  • internal/runner/thin/research_step_test.go +1 −1
  • internal/runner/thin/run.go +3 −3
  • internal/runner/thin/site.go +675 −177
  • internal/runner/thin/site_test.go +551 −244
  • internal/runner/thin/tool_health_test.go +1 −1
  • internal/wire/api.go +2 −0
  • internal/wire/assistant_test.go +1 −1
  • internal/wire/frames.go +9 −2
  • internal/wire/injection_test.go +2 −2
  • internal/wire/mixed_protocol_test.go +1 −1
  • internal/wire/models_test.go +1 −1
  • internal/wire/opencode_test.go +9 −8
  • internal/wire/pinned_release_test.go +1 −1
  • internal/wire/places.go +301 −0
  • internal/wire/places_test.go +155 −0
  • internal/wire/publish.go +33 −3
  • internal/wire/publish_test.go +11 −2
  • internal/wire/runners.go +22 −2
  • internal/wire/runners_test.go +1 −1
  • internal/wire/schedule_test.go +1 −1
  • internal/wire/stuck.go +5 −1
  • internal/wire/stuck_test.go +1 −1
  • internal/wire/tasks.go +8 −0
  • internal/wire/usage_test.go +1 −1
  • internal/wire/warm_test.go +1 −1
diff --git a/docs/api/equipo-v1.openapi.json b/docs/api/equipo-v1.openapi.json
index 7aca4bcf..280a0b15 100644
--- a/docs/api/equipo-v1.openapi.json
+++ b/docs/api/equipo-v1.openapi.json
@@ -18805,6 +18805,9 @@
},
"tools": {
"$ref": "#/components/schemas/ToolHealth"
+ },
+ "reach": {
+ "$ref": "#/components/schemas/Reach"
}
},
"required": [
@@ -18820,6 +18823,9 @@
"Card": {
"type": "object",
"properties": {
+ "placement_by_name": {
+ "type": "boolean"
+ },
"remember_name": {
"type": "string"
},
@@ -18896,14 +18902,14 @@
"site": {
"$ref": "#/components/schemas/CardSite"
},
+ "place": {
+ "$ref": "#/components/schemas/CardPlaceView"
+ },
"advice": {
"$ref": "#/components/schemas/Advice"
},
"aside": {
"type": "boolean"
- },
- "placement_by_name": {
- "type": "boolean"
}
},
"required": [
@@ -21110,6 +21116,9 @@
},
"outcome": {
"type": "string"
+ },
+ "deploy_held": {
+ "type": "boolean"
}
},
"required": [
@@ -24145,6 +24154,12 @@
},
"renderer": {
"type": "string"
+ },
+ "carlos": {
+ "type": "string"
+ },
+ "carlos_version": {
+ "type": "string"
}
},
"required": [
@@ -24171,6 +24186,162 @@
],
"additionalProperties": false,
"x-go-type": "wire.StepHosted"
+ },
+ "CardPlaceView": {
+ "type": "object",
+ "properties": {
+ "kind": {
+ "type": "string"
+ },
+ "project": {
+ "type": "string"
+ },
+ "candidates": {
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/components/schemas/PlaceCandidate"
+ }
+ }
+ },
+ "required": [
+ "kind",
+ "project",
+ "candidates"
+ ],
+ "additionalProperties": false,
+ "x-go-type": "wire.CardPlaceView"
+ },
+ "PlaceCandidate": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "console": {
+ "type": "string"
+ },
+ "console_label": {
+ "type": "string"
+ },
+ "account": {
+ "type": "string"
+ },
+ "sqid": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "console",
+ "console_label",
+ "account",
+ "sqid"
+ ],
+ "additionalProperties": false,
+ "x-go-type": "wire.PlaceCandidate"
+ },
+ "Reach": {
+ "type": "object",
+ "properties": {
+ "logins": {
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/components/schemas/ReachLogin"
+ }
+ },
+ "deploys": {
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/components/schemas/ReachDeploy"
+ }
+ }
+ },
+ "required": [
+ "logins",
+ "deploys"
+ ],
+ "additionalProperties": false,
+ "x-go-type": "wire.Reach"
+ },
+ "ReachAccount": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "sqid": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "sqid"
+ ],
+ "additionalProperties": false,
+ "x-go-type": "wire.ReachAccount"
+ },
+ "ReachDeploy": {
+ "type": "object",
+ "properties": {
+ "console": {
+ "type": "string"
+ },
+ "account": {
+ "type": "string"
+ },
+ "app": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "fingerprint": {
+ "type": "string"
+ },
+ "lost": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "console",
+ "account",
+ "app",
+ "name"
+ ],
+ "additionalProperties": false,
+ "x-go-type": "wire.ReachDeploy"
+ },
+ "ReachLogin": {
+ "type": "object",
+ "properties": {
+ "console": {
+ "type": "string"
+ },
+ "accounts": {
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/components/schemas/ReachAccount"
+ }
+ }
+ },
+ "required": [
+ "console",
+ "accounts"
+ ],
+ "additionalProperties": false,
+ "x-go-type": "wire.ReachLogin"
}
},
"responses": {
diff --git a/internal/headless/assistant_test.go b/internal/headless/assistant_test.go
index 30f17178..dde3953b 100644
--- a/internal/headless/assistant_test.go
+++ b/internal/headless/assistant_test.go
@@ -219,11 +219,14 @@ func TestHeadlessAssistant(t *testing.T) {
// EQUIPO_CARLOS_PATH and EQUIPO_PREVIEW_CREDENTIAL_PATH when not the
// defaults) say so.
t.Run("quick_website", func(t *testing.T) {
- if os.Getenv("EQUIPO_SITE_HOST") == "" || os.Getenv("EQUIPO_PREVIEW_HOST") == "" {
- t.Skip("no site host: set EQUIPO_SITE_HOST and EQUIPO_PREVIEW_HOST")
+ // Since places (2026-11-26) a site publishes only to a place an
+ // owner confirmed on a place card first; this live run still taps
+ // Publish alone, so it waits for its place-card step (slice 3).
+ if os.Getenv("EQUIPO_LIVE_PLACES") == "" || os.Getenv("EQUIPO_PREVIEW_HOST") == "" {
+ t.Skip("needs a confirmed place: set EQUIPO_LIVE_PLACES and EQUIPO_PREVIEW_HOST")
}
env, inst, r := localEnv(t)
- r.cfg.SiteHost, r.cfg.PreviewHost = os.Getenv("EQUIPO_SITE_HOST"), os.Getenv("EQUIPO_PREVIEW_HOST")
+ r.cfg.PreviewHost = os.Getenv("EQUIPO_PREVIEW_HOST")
r.cfg.CarlosPath, r.cfg.PreviewCredentialPath = os.Getenv("EQUIPO_CARLOS_PATH"), os.Getenv("EQUIPO_PREVIEW_CREDENTIAL_PATH")
r.opts.NoMoveIn = true
r.start(t)
diff --git a/internal/runner/config.go b/internal/runner/config.go
index bdfb05a6..5b1fec7f 100644
--- a/internal/runner/config.go
+++ b/internal/runner/config.go
@@ -16,14 +16,11 @@ type Config struct {
MachineLabel string
ClaudeModel, CodexModel string
ToolProxyPath, BwrapPath, ModuleCache, PreviewCredentialPath, CarlosPath, PreviewHost string
- // SiteHost pairs the runner with a site host that publishes merged
- // websites (EQUIPO_SITE_HOST=carloku); empty, it publishes none.
- SiteHost string
- ClaudePath, CodexCodeModeHostPath string
- Report func(string)
- Origin, StateDir, AmadanCredentialPath, AccountBindingsPath, CodexPath string
- GoRoot, GoBinary, WorkspaceRoot, ScratchRoot, GitPath, AmadanPath, Executable string
- InstanceID string
+ ClaudePath, CodexCodeModeHostPath string
+ Report func(string)
+ Origin, StateDir, AmadanCredentialPath, AccountBindingsPath, CodexPath string
+ GoRoot, GoBinary, WorkspaceRoot, ScratchRoot, GitPath, AmadanPath, Executable string
+ InstanceID string
// PiRoot is where the pinned Pi is installed (EQUIPO_PI_ROOT, laid
// out as provider/pi.Paths says); empty, this runner has no Pi and
// runs no step on a metered connection.
@@ -43,7 +40,7 @@ type Config struct {
}
func LoadConfig(getenv func(string) string) (Config, error) {
- c := Config{WorkerOnly: runtime.GOOS == "darwin" || getenv("EQUIPO_FAKE_PLATFORM") != "", ClaudeModel: getenv("EQUIPO_CLAUDE_MODEL"), CodexModel: getenv("EQUIPO_CODEX_MODEL"), MachineLabel: getenv("EQUIPO_MACHINE_LABEL"), ToolProxyPath: getenv("EQUIPO_TOOL_PROXY_PATH"), CodexCodeModeHostPath: getenv("EQUIPO_CODEX_CODE_MODE_HOST_PATH"), BwrapPath: getenv("EQUIPO_BWRAP_PATH"), ModuleCache: getenv("EQUIPO_GO_MODULE_CACHE"), PreviewCredentialPath: getenv("EQUIPO_PREVIEW_CREDENTIAL_PATH"), CarlosPath: getenv("EQUIPO_CARLOS_PATH"), PreviewHost: getenv("EQUIPO_PREVIEW_HOST"), SiteHost: getenv("EQUIPO_SITE_HOST"), ClaudePath: getenv("EQUIPO_CLAUDE_PATH"), Origin: getenv("EQUIPO_ORIGIN"), StateDir: getenv("EQUIPO_RUNNER_STATE_DIR"), AmadanCredentialPath: getenv("EQUIPO_AMADAN_CREDENTIAL_PATH"), AccountBindingsPath: getenv("EQUIPO_ACCOUNT_BINDINGS_PATH"), CodexPath: getenv("EQUIPO_CODEX_PATH"), GoRoot: getenv("EQUIPO_GO_ROOT"), GoBinary: getenv("EQUIPO_GO_BINARY"), WorkspaceRoot: getenv("EQUIPO_WORKSPACE_ROOT"), ScratchRoot: getenv("EQUIPO_SCRATCH_ROOT"), GitPath: getenv("EQUIPO_GIT_PATH"), AmadanPath: getenv("EQUIPO_AMADAN_PATH"), InstanceID: getenv("EQUIPO_INSTANCE_ID"), PiRoot: getenv("EQUIPO_PI_ROOT"), OpenCodeRoot: getenv("EQUIPO_OPENCODE_ROOT")}
+ c := Config{WorkerOnly: runtime.GOOS == "darwin" || getenv("EQUIPO_FAKE_PLATFORM") != "", ClaudeModel: getenv("EQUIPO_CLAUDE_MODEL"), CodexModel: getenv("EQUIPO_CODEX_MODEL"), MachineLabel: getenv("EQUIPO_MACHINE_LABEL"), ToolProxyPath: getenv("EQUIPO_TOOL_PROXY_PATH"), CodexCodeModeHostPath: getenv("EQUIPO_CODEX_CODE_MODE_HOST_PATH"), BwrapPath: getenv("EQUIPO_BWRAP_PATH"), ModuleCache: getenv("EQUIPO_GO_MODULE_CACHE"), PreviewCredentialPath: getenv("EQUIPO_PREVIEW_CREDENTIAL_PATH"), CarlosPath: getenv("EQUIPO_CARLOS_PATH"), PreviewHost: getenv("EQUIPO_PREVIEW_HOST"), ClaudePath: getenv("EQUIPO_CLAUDE_PATH"), Origin: getenv("EQUIPO_ORIGIN"), StateDir: getenv("EQUIPO_RUNNER_STATE_DIR"), AmadanCredentialPath: getenv("EQUIPO_AMADAN_CREDENTIAL_PATH"), AccountBindingsPath: getenv("EQUIPO_ACCOUNT_BINDINGS_PATH"), CodexPath: getenv("EQUIPO_CODEX_PATH"), GoRoot: getenv("EQUIPO_GO_ROOT"), GoBinary: getenv("EQUIPO_GO_BINARY"), WorkspaceRoot: getenv("EQUIPO_WORKSPACE_ROOT"), ScratchRoot: getenv("EQUIPO_SCRATCH_ROOT"), GitPath: getenv("EQUIPO_GIT_PATH"), AmadanPath: getenv("EQUIPO_AMADAN_PATH"), InstanceID: getenv("EQUIPO_INSTANCE_ID"), PiRoot: getenv("EQUIPO_PI_ROOT"), OpenCodeRoot: getenv("EQUIPO_OPENCODE_ROOT")}
if c.PreviewHost == "" {
c.PreviewHost = "devbox"
}
diff --git a/internal/runner/provider/actions.go b/internal/runner/provider/actions.go
index 79f7f809..224f52f5 100644
--- a/internal/runner/provider/actions.go
+++ b/internal/runner/provider/actions.go
@@ -177,7 +177,7 @@ func ResearchReaderAction(action string) bool { return action == "implement" ||
// ConverseTools is the thin coordinator's tool set (wire.ConverseTools
// plus create_project, which the runner carries out itself).
func ConverseTools() []string {
- return []string{"request_access", "status", "find", "search_code", "read_file", "add_project", "create_project", "set_project_home", "star_project", "ask_person", "write_note", "read_notes", "record_task", "add_finding", "start_task", "read_task", "cancel_task", "add_report", "hold_merge", "set_merge_policy", "propose_specialist", "research", "offer_retry", "retry_step"}
+ return []string{"request_access", "status", "find", "search_code", "read_file", "add_project", "create_project", "set_project_home", "star_project", "ask_person", "write_note", "read_notes", "record_task", "add_finding", "start_task", "read_task", "cancel_task", "add_report", "hold_merge", "set_merge_policy", "propose_specialist", "research", "offer_retry", "retry_step", "places", "propose_place", "publish_site", "site_status"}
}
// AssistTools is the Assistant's tool set (wire.AssistTools).
diff --git a/internal/runner/provider/claude/launcher.go b/internal/runner/provider/claude/launcher.go
index 3b80d2c8..84cc0e56 100644
--- a/internal/runner/provider/claude/launcher.go
+++ b/internal/runner/provider/claude/launcher.go
@@ -140,7 +140,7 @@ func PolicyInputs(b provider.Binding, in provider.PolicyInputs, specialist, mode
}
tools := append(append([]string{}, native...), "mcp__equipo__permission")
for _, tool := range in.Tools {
- converse := in.Action == "converse" && slices.Contains([]string{"mcp__equipo__request_access", "mcp__equipo__status", "mcp__equipo__find", "mcp__equipo__search_code", "mcp__equipo__read_file", "mcp__equipo__add_project", "mcp__equipo__create_project", "mcp__equipo__set_project_home", "mcp__equipo__star_project", "mcp__equipo__write_note", "mcp__equipo__read_notes", "mcp__equipo__record_task", "mcp__equipo__add_finding", "mcp__equipo__start_task", "mcp__equipo__read_task", "mcp__equipo__cancel_task", "mcp__equipo__add_report", "mcp__equipo__hold_merge", "mcp__equipo__set_merge_policy", "mcp__equipo__propose_specialist", "mcp__equipo__research", "mcp__equipo__offer_retry", "mcp__equipo__retry_step"}, tool)
+ converse := in.Action == "converse" && slices.Contains([]string{"mcp__equipo__request_access", "mcp__equipo__status", "mcp__equipo__find", "mcp__equipo__search_code", "mcp__equipo__read_file", "mcp__equipo__add_project", "mcp__equipo__create_project", "mcp__equipo__set_project_home", "mcp__equipo__star_project", "mcp__equipo__write_note", "mcp__equipo__read_notes", "mcp__equipo__record_task", "mcp__equipo__add_finding", "mcp__equipo__start_task", "mcp__equipo__read_task", "mcp__equipo__cancel_task", "mcp__equipo__add_report", "mcp__equipo__hold_merge", "mcp__equipo__set_merge_policy", "mcp__equipo__propose_specialist", "mcp__equipo__research", "mcp__equipo__offer_retry", "mcp__equipo__retry_step", "mcp__equipo__places", "mcp__equipo__propose_place", "mcp__equipo__publish_site", "mcp__equipo__site_status"}, tool)
assist := in.Action == "assist" && slices.Contains([]string{"mcp__equipo__look", "mcp__equipo__describe", "mcp__equipo__use", "mcp__equipo__write_note", "mcp__equipo__read_notes"}, tool)
answer := in.Action == "answer" && slices.Contains([]string{"mcp__equipo__git_log", "mcp__equipo__git_diff", "mcp__equipo__git_show"}, tool)
research := provider.ResearchAction(in.Action) && slices.Contains([]string{"mcp__equipo__submit_findings", "mcp__equipo__keep_image"}, tool)
diff --git a/internal/runner/thin/bridge.go b/internal/runner/thin/bridge.go
index 995147eb..b0ec7704 100644
--- a/internal/runner/thin/bridge.go
+++ b/internal/runner/thin/bridge.go
@@ -598,6 +598,9 @@ func (b *bridge) roundTrip(ctx context.Context, call wire.ToolCall) wire.ToolRes
if res, no := stuckRefused(call, b.spoken()); no {
return res
}
+ if res, no := placesRefused(call, b.spoken()); no {
+ return res
+ }
if res, refused := exploreRefused(call, b.spoken(), nil); refused {
// An instance below protocol 10 refuses it anyway (the kind is
// never dropped from an exploration); say why, here.
diff --git a/internal/runner/thin/capabilities.go b/internal/runner/thin/capabilities.go
index 05338a55..94ca26b0 100644
--- a/internal/runner/thin/capabilities.go
+++ b/internal/runner/thin/capabilities.go
@@ -77,19 +77,27 @@ var goVersion = regexp.MustCompile(`\bgo1\.[0-9]+(?:\.[0-9]+)?\b`)
// when it runs Claude Code, go when checks have the Go toolchain. Never a
// path or raw output.
// addrs lists this machine's addresses (nil: its interfaces).
-func linuxCapabilities(c runner.Config, previews func() *wire.PreviewHost, sites bool, addrs func() ([]netip.Addr, error)) func(context.Context) wire.Capabilities {
+func linuxCapabilities(c runner.Config, previews func() *wire.PreviewHost, site *SiteOptions, addrs func() ([]netip.Addr, error)) func(context.Context) wire.Capabilities {
if addrs == nil {
addrs = webread.LocalAddresses
}
return func(ctx context.Context) wire.Capabilities {
host := previews()
- out := wire.Capabilities{Simulators: []wire.Simulator{}, Tags: []string{wire.TagLinux}, Previews: host != nil, PreviewHost: host, Sites: sites}
+ out := wire.Capabilities{Simulators: []wire.Simulator{}, Tags: []string{wire.TagLinux}, Previews: host != nil, PreviewHost: host}
// The Research site inventory's detected addresses (absent when
// they cannot be read).
out.Research = researchCapability(addrs)
// Whether the pinned preview scanner is installed and matches its
// pin (protocol 30, for the coordinator's status).
out.Tools = previewToolHealth(c)
+ // Which carlos, and what it can reach (protocol 31): its version,
+ // the owner logins and the deploy keys, never a secret.
+ var cli *carlosCLI
+ if site != nil {
+ cli = site.cli()
+ }
+ out.Tools.Carlos, out.Tools.CarlosVersion = cli.Health(ctx)
+ out.Reach = site.Reach(ctx)
if c.ClaudePath != "" {
out.Harness.Claude = provider.ClaudeVersion
out.Tags = append(out.Tags, wire.TagClaude)
diff --git a/internal/runner/thin/carlos.go b/internal/runner/thin/carlos.go
new file mode 100644
index 00000000..0ff37b03
--- /dev/null
+++ b/internal/runner/thin/carlos.go
@@ -0,0 +1,150 @@
+package thin
+
+import (
+ "context"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// The carlos CLI the runner runs for previews and sites: one lookup
+// (EQUIPO_CARLOS_PATH, else PATH, else ~/.local/bin), an absolute regular
+// executable file or none. A stale carlos earlier on PATH broke every
+// preview on the production runner (2026-11-26), so its version is read
+// at start and with every capability probe and said in the hello; a
+// preview or a publish refuses carlos_outdated below wire.MinCarlos.
+
+// carlosLookup is the carlos the configuration names, "" when none is a
+// usable file.
+func carlosLookup(c runner.Config) string {
+ carlos := c.CarlosPath
+ if carlos == "" {
+ if p, err := exec.LookPath("carlos"); err == nil {
+ carlos = p
+ } else if home, err := os.UserHomeDir(); err == nil {
+ carlos = filepath.Join(home, ".local", "bin", "carlos")
+ }
+ }
+ if !filepath.IsAbs(carlos) {
+ return ""
+ }
+ if info, err := os.Stat(carlos); err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0o111 == 0 {
+ return ""
+ }
+ return carlos
+}
+
+// carlosRelease is the release `carlos version` names on its first line.
+var carlosRelease = regexp.MustCompile(`^carlos (v[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,4})\b`)
+
+// carlosVersionOf runs `carlos version` (5 seconds, an empty environment)
+// and returns the release it names, "" when it names none.
+func carlosVersionOf(ctx context.Context, bin string) string {
+ if bin == "" {
+ return ""
+ }
+ cctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(cctx, bin, "version")
+ dir, err := os.MkdirTemp("", "carlos-version-")
+ if err != nil {
+ return ""
+ }
+ defer os.RemoveAll(dir)
+ cmd.Dir, cmd.Env = dir, []string{"HOME=" + dir, "PATH=/usr/bin:/bin", "CARLOS_NO_UPDATE_CHECK=1"}
+ out, _, err := boundedOutput(cmd, 4096)
+ if err != nil {
+ return ""
+ }
+ line, _, _ := strings.Cut(ansi.ReplaceAllString(string(out), ""), "\n")
+ m := carlosRelease.FindStringSubmatch(strings.TrimSpace(line))
+ if m == nil {
+ return ""
+ }
+ return m[1]
+}
+
+// readCarlosVersion reads a carlos's version (a seam: the package's tests
+// stand in for the many fake carlos binaries that have no version verb).
+var readCarlosVersion = carlosVersionOf
+
+// carlosCLI is the runner's carlos and its version, read at most once a
+// capability period.
+type carlosCLI struct {
+ Bin string
+ // Read is the seam for the version read (nil: carlosVersionOf).
+ Read func(ctx context.Context, bin string) string
+
+ mu sync.Mutex
+ version string
+ at time.Time
+}
+
+// Version is the carlos release, re-read when older than an hour.
+func (c *carlosCLI) Version(ctx context.Context) string {
+ if c == nil {
+ return ""
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.at.IsZero() || time.Since(c.at) > capabilityEvery {
+ read := c.Read
+ if read == nil {
+ read = readCarlosVersion
+ }
+ c.version, c.at = read(ctx, c.Bin), time.Now()
+ }
+ return c.version
+}
+
+// Health is the carlos health a hello says: missing with no binary,
+// outdated when its version is unreadable or below wire.MinCarlos, else
+// ok, with the version when one was read.
+func (c *carlosCLI) Health(ctx context.Context) (string, string) {
+ if c == nil || c.Bin == "" {
+ return wire.CarlosMissing, ""
+ }
+ v := c.Version(ctx)
+ if !wire.ValidCarlosVersion(v) {
+ return wire.CarlosOutdated, ""
+ }
+ if !wire.CarlosAtLeast(v, wire.MinCarlos) {
+ return wire.CarlosOutdated, v
+ }
+ return wire.CarlosOK, v
+}
+
+// OK reports whether previews and sites may run carlos now.
+func (c *carlosCLI) OK(ctx context.Context) bool {
+ state, _ := c.Health(ctx)
+ return state == wire.CarlosOK
+}
+
+// carlosCLIs are the carlos binaries previews run, each read once a
+// capability period.
+var carlosCLIs sync.Map
+
+// carlosOK reports whether the carlos at bin is at least wire.MinCarlos.
+func carlosOK(ctx context.Context, bin string) bool {
+ v, _ := carlosCLIs.LoadOrStore(bin, &carlosCLI{Bin: bin})
+ return v.(*carlosCLI).OK(ctx)
+}
+
+// previewCarlosOK reports whether the preview host's carlos may run: the
+// devbox's, else the temporary sites' credential's.
+func (e *Engineer) previewCarlosOK(ctx context.Context) bool {
+ switch {
+ case e.Devbox != nil:
+ return carlosOK(ctx, e.Devbox.Carlos)
+ case e.Preview != nil:
+ return carlosOK(ctx, e.Preview.Carlos)
+ }
+ return false
+}
diff --git a/internal/runner/thin/carlos_test.go b/internal/runner/thin/carlos_test.go
new file mode 100644
index 00000000..aa18933f
--- /dev/null
+++ b/internal/runner/thin/carlos_test.go
@@ -0,0 +1,33 @@
+package thin
+
+import (
+ "context"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// TestPreviewRefusesOldCarlos: a preview whose host's carlos is older than
+// wire.MinCarlos, or whose version cannot be read, refuses carlos_outdated
+// before anything is built or sent (production ran a stale carlos on its
+// PATH, 2026-11-26, and every preview failed obscurely at the deploy).
+func TestPreviewRefusesOldCarlos(t *testing.T) {
+ for _, v := range []string{"v0.32.2", "", "v0.42.9"} {
+ old := readCarlosVersion
+ readCarlosVersion = func(context.Context, string) string { return v }
+ carlosCLIs.Clear()
+ e, fc, confirms, r := previewRig(t, mockups, nil)
+ built := false
+ rep := e.Exec(context.Background(), r, func(p wire.StepReport) { built = built || p.Preview != nil })
+ readCarlosVersion = old
+ carlosCLIs.Clear()
+ if rep.State != wire.StepFailed || rep.Reason != wire.ReasonCarlosOutdated || !rep.Termination || built || len(fc.calls) != 0 || len(*confirms) != 0 {
+ t.Fatalf("%q: %+v built %t calls %d", v, rep, built, len(fc.calls))
+ }
+ }
+ // At the minimum it runs.
+ e, _, _, r := previewRig(t, mockups, nil)
+ if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.Reason == wire.ReasonCarlosOutdated {
+ t.Fatalf("a current carlos refused: %+v", rep)
+ }
+}
diff --git a/internal/runner/thin/claude.go b/internal/runner/thin/claude.go
index 1a99a147..735d3eda 100644
--- a/internal/runner/thin/claude.go
+++ b/internal/runner/thin/claude.go
@@ -681,7 +681,7 @@ func (c *claudeCoordinator) idleExit() {
// houseRule versions the opening's rule. Changing the rule's text changes
// it, so sessions started under an older rule are not resumed.
-const houseRule = "2026-11-25.1"
+const houseRule = "2026-11-26.1"
// sessionAccount records the account and the lane's rule a session runs
// on.
@@ -775,7 +775,7 @@ func opening(person string, catalog []wire.RepoInfo) string {
b.WriteString("You are the Equipo coordinator for " + person + ". You talk with them about their software work. Answer briefly in plain words. Do not use em dashes.\n")
b.WriteString(accessPrompt + "Use the named project or the clear continuation. If placement is ambiguous, ask_person with structured placement choices, best guess first. Always confirm a new repository unless the person directly requested one in the main composer this turn. Hand-offs, nudges, quotes and ordinary card answers cannot grant creation. One turn permits one creation; placement-card labels name the repository and come from the server. Wait for the answer before recording or starting work. Learn from project corrections in your notebook. Call status to see reachable repositories and create_in namespaces.\n")
b.WriteString("For settled placement, call add_project for existing work or create_project for explicitly requested or confirmed new work. Choose the related namespace, otherwise home from status. Change home only when asked. Never fall back silently to a different project after a refusal.\n")
- b.WriteString("Once placement is settled for a bug or change, call record_task before investigating, with the repository it belongs to, a short title and their words as the brief. Then investigate with search_code and read_file, attach what you found with add_finding (a one-sentence headline for the person, plain words and no file paths, and the full finding with its file and line), and call start_task with a brief for Engineering. Engineering changes the code on the task's own branch and pushes it to Amadan; the change is then checked and reviewed, and Equipo's merge rules decide whether it merges on its own or asks the person with a card that gives Equipo's call. You cannot make it merge: when you have a concrete reason a change needs the person's look, call hold_merge with that reason. When the person says how a project should merge (\"always ask me about Suite\", \"main is not a release for Woodstar\"), call set_merge_policy with their words; a stricter rule applies at once and a looser one waits for their tap. Never offer to merge or open a pull request, and never ask the person to merge. The one exception: when a merge failed and the task waits at Ready to merge, offer_retry puts a card in front of the person to try it again, and only their tap merges. Use ask_person only for a question only the person can answer. Mockups, prototypes, design options and spikes are explorations: record them with kind explore; they end at a preview and the person's choice of direction, never a merge. A website meant to go live is a change, not an exploration: ask Engineering for plain HTML and CSS files with no build step, kept in one folder that release/preview.json names. Once it is merged its person is asked whether to publish it; never say it is live before then.\n")
+ b.WriteString("Once placement is settled for a bug or change, call record_task before investigating, with the repository it belongs to, a short title and their words as the brief. Then investigate with search_code and read_file, attach what you found with add_finding (a one-sentence headline for the person, plain words and no file paths, and the full finding with its file and line), and call start_task with a brief for Engineering. Engineering changes the code on the task's own branch and pushes it to Amadan; the change is then checked and reviewed, and Equipo's merge rules decide whether it merges on its own or asks the person with a card that gives Equipo's call. You cannot make it merge: when you have a concrete reason a change needs the person's look, call hold_merge with that reason. When the person says how a project should merge (\"always ask me about Suite\", \"main is not a release for Woodstar\"), call set_merge_policy with their words; a stricter rule applies at once and a looser one waits for their tap. Never offer to merge or open a pull request, and never ask the person to merge. The one exception: when a merge failed and the task waits at Ready to merge, offer_retry puts a card in front of the person to try it again, and only their tap merges. Use ask_person only for a question only the person can answer. Mockups, prototypes, design options and spikes are explorations: record them with kind explore; they end at a preview and the person's choice of direction, never a merge. A website meant to go live is a change, not an exploration: ask Engineering for plain HTML and CSS files with no build step, kept in one folder that release/preview.json names. Once it is merged its person is asked whether to publish it. To publish a merged website when asked (also one merged before and never offered), call publish_site with its task: a card names where it goes, and only the person's tap publishes; with no confirmed place it asks where first. places and site_status say where sites go and what Equipo recorded; never look for a site anywhere else, and never say it is live until the task shows its address.\n")
b.WriteString("Never file the same problem twice. If record_task returns similar open tasks and one of them is what the person is reporting, call add_report on it with their words and tell them in one line it is already logged and where it stands, naming it as a markdown link; record a separate task only when it is clearly a different problem.\n")
b.WriteString("Speak at the outcome level: what you understood, what is happening, what you need from the person. For example: \"Got it, I've logged [Swipe back doesn't work](/tasks/tk...) and Engineering is on it.\" No file paths, line numbers or code mechanics in your replies; the diagnosis goes on the task with add_finding. Always name a task as a markdown link with its title and the link from record_task, start_task or read_task, never as \"the task card\".\n")
b.WriteString("Anything the person may need to paste (commands, prompts, config, codes) goes in a fenced code block, one block per thing to paste, with its kind after the opening fence (bash for a command, prompt for a prompt, text for plain text): the chat shows each block with a Copy button.\n")
diff --git a/internal/runner/thin/contract_test.go b/internal/runner/thin/contract_test.go
index 757f3428..25e107f9 100644
--- a/internal/runner/thin/contract_test.go
+++ b/internal/runner/thin/contract_test.go
@@ -47,6 +47,9 @@ func TestMain(m *testing.M) {
if len(os.Args) > 1 && os.Args[1] == "__namespace" {
os.Exit(containment.NamespaceMain(os.Args[2:]))
}
+ // The fake carlos binaries answer no version verb: a current release
+ // stands in, and the guard's own tests set theirs.
+ readCarlosVersion = func(context.Context, string) string { return "v0.43.3" }
code := budget.Main(m)
if scannerBuild.binary != "" {
_ = os.RemoveAll(filepath.Dir(scannerBuild.binary))
diff --git a/internal/runner/thin/engineer.go b/internal/runner/thin/engineer.go
index ee0d9f89..da3fe876 100644
--- a/internal/runner/thin/engineer.go
+++ b/internal/runner/thin/engineer.go
@@ -95,7 +95,13 @@ type Engineer struct {
// none). ConfirmPublish is the check right before its deploy
// (protocol 16), for the export's digest.
Site *SiteOptions
- ConfirmPublish func(ctx context.Context, step string, attempt int64, digest string) error
+ ConfirmPublish func(ctx context.Context, step string, attempt int64, digest, destination string) error
+ // ConfirmMint is the check right before a setup's or a mint's
+ // services create, bound to the same export and destination
+ // (protocol 31); SiteChanged makes the next hello carry the runner's
+ // new reach.
+ ConfirmMint func(ctx context.Context, step string, attempt int64, digest, destination string) error
+ SiteChanged func()
// ConfirmPublication confirms a worker's commit is still to be
// published, right before the push.
ConfirmPublication func(ctx context.Context, step string, attempt int64, publication string) error
diff --git a/internal/runner/thin/link.go b/internal/runner/thin/link.go
index 7f059679..8c243329 100644
--- a/internal/runner/thin/link.go
+++ b/internal/runner/thin/link.go
@@ -259,17 +259,28 @@ func (l *Link) ConfirmPreview(ctx context.Context, step string, attempt int64, d
}
// ConfirmPublish is the check right before a publish step's deploy,
-// bound to its export's digest. Below protocol 16 it is refused here,
-// never sent. ErrPublishNotBuilt: the instance has not applied the
+// bound to its export's digest and its destination. Below protocol 31 it
+// is refused here, never sent: an older instance would decide it without
+// the destination. ErrPublishNotBuilt: the instance has not applied the
// step's built report yet.
-func (l *Link) ConfirmPublish(ctx context.Context, step string, attempt int64, digest string) error {
+func (l *Link) ConfirmPublish(ctx context.Context, step string, attempt int64, digest, destination string) error {
+ return l.siteCheck(ctx, wire.LeaseCheck{StepID: step, Attempt: attempt, Purpose: wire.LeasePurposePublish, Digest: digest, Destination: destination})
+}
+
+// ConfirmMint is the check right before a setup's or a mint's services
+// create, bound like ConfirmPublish, and refused below protocol 31 alike.
+func (l *Link) ConfirmMint(ctx context.Context, step string, attempt int64, digest, destination string) error {
+ return l.siteCheck(ctx, wire.LeaseCheck{StepID: step, Attempt: attempt, Purpose: wire.LeasePurposeMint, Digest: digest, Destination: destination})
+}
+
+func (l *Link) siteCheck(ctx context.Context, check wire.LeaseCheck) error {
l.mu.Lock()
proto := l.proto
l.mu.Unlock()
- if proto < wire.ProtocolPublish {
+ if proto < wire.ProtocolPlaces || !wire.ValidDestination(check.Destination) {
return ErrNoAuthority
}
- return l.lease(ctx, wire.LeaseCheck{StepID: step, Attempt: attempt, Purpose: wire.LeasePurposePublish, Digest: digest})
+ return l.lease(ctx, check)
}
// ConfirmPublication is the primary's confirmation right before it pushes
@@ -478,6 +489,9 @@ func (l *Link) send(ctx context.Context, c *websocket.Conn, f wire.Frame) error
if !refused {
result, refused = stuckRefused(*call, proto)
}
+ if !refused {
+ result, refused = placesRefused(*call, proto)
+ }
if refused {
if err := l.State.Acked(ctx, f.ID); err != nil {
return err
@@ -568,6 +582,8 @@ func (l *Link) handshake(ctx context.Context, offer int) (*websocket.Conn, *wire
heldUsage := wire.WithoutUsageRefresh(&hello)
// Nor the sites capability, below protocol 16.
heldSites := wire.WithoutSites(&hello)
+ // Nor the reach and carlos health, below protocol 31.
+ heldPlaces := wire.WithoutPlaces(&hello)
// Nor the tool health, below protocol 30.
heldTools := wire.WithoutToolHealth(&hello)
l.mu.Lock()
@@ -618,7 +634,7 @@ func (l *Link) handshake(ctx context.Context, offer int) (*websocket.Conn, *wire
}
l.mu.Lock()
l.proto, l.role = min(spoken, offer), role
- if heldUsage && l.proto >= wire.ProtocolUsageRefresh || held && l.proto >= wire.ProtocolEmptyRepos || heldPreviews && l.proto >= wire.ProtocolExplore || heldResearch && l.proto >= wire.ProtocolResearch || heldReadings && l.proto >= wire.ProtocolReadings || heldSites && l.proto >= wire.ProtocolPublish || heldTools && l.proto >= wire.ProtocolStuckTasks {
+ if heldUsage && l.proto >= wire.ProtocolUsageRefresh || held && l.proto >= wire.ProtocolEmptyRepos || heldPreviews && l.proto >= wire.ProtocolExplore || heldResearch && l.proto >= wire.ProtocolResearch || heldReadings && l.proto >= wire.ProtocolReadings || heldSites && l.proto >= wire.ProtocolPublish || heldTools && l.proto >= wire.ProtocolStuckTasks || heldPlaces && l.proto >= wire.ProtocolPlaces {
l.helloSoon = true
}
l.mu.Unlock()
diff --git a/internal/runner/thin/mcp.go b/internal/runner/thin/mcp.go
index a37cd600..8f6dfe11 100644
--- a/internal/runner/thin/mcp.go
+++ b/internal/runner/thin/mcp.go
@@ -150,7 +150,7 @@ var str = map[string]string{"type": "string"}
// descriptions are for the model; people never read them.
var converseTools = []any{
map[string]any{"name": wire.ToolRequestAccess, "description": "Propose an access request for an unreachable repository. The person confirms before filing; never retry unprompted. Prefer one repository; namespace only if explicitly requested. Role defaults to agent.", "inputSchema": toolSchema(map[string]any{"target": str, "role": str, "reason": str}, "target", "reason")},
- map[string]any{"name": "status", "description": "Read-only: this person's runner, model connections, current projects, the repositories you can add (can_add) and the namespaces you can create repositories in (create_in, with home for unrelated new work). Call it before choosing where work goes. runner.tools says whether the runner's pinned preview scanner is installed and matches its pin (ok, missing, mismatch, unpinned, or unknown when the runner does not say): a preview that failed for its scanner needs the runner fixed or updated, not another try.", "inputSchema": toolSchema(map[string]any{})},
+ map[string]any{"name": "status", "description": "Read-only: this person's runner, model connections, current projects, the repositories you can add (can_add) and the namespaces you can create repositories in (create_in, with home for unrelated new work). Call it before choosing where work goes. runner.tools says whether the runner's pinned preview scanner is installed and matches its pin (ok, missing, mismatch, unpinned, or unknown when the runner does not say): a preview that failed for its scanner needs the runner fixed or updated, not another try. runner.tools.carlos says whether its CARLOS command line tool is current enough for previews and sites (ok, outdated, missing) and carlos_version which release it is: outdated or missing needs the person to update it, not another try.", "inputSchema": toolSchema(map[string]any{})},
map[string]any{"name": "find", "description": "Read-only: find which repository an app, product or feature lives in, by name, alias or keyword (for example Woodstar). Returns candidates with reasons, or says nothing Equipo's agent can reach matches.", "inputSchema": toolSchema(map[string]any{"query": str}, "query")},
map[string]any{"name": "search_code", "description": "Read-only: search a repository's default branch for a fixed string, case insensitive. Returns path:line: text, bounded.", "inputSchema": toolSchema(map[string]any{"repo": str, "query": str}, "repo", "query")},
map[string]any{"name": "read_file", "description": "Read-only: read a file from a repository's default branch with line numbers (up to 300 lines from start), or list a directory (empty path is the root). For a file the person attached, repo is \"attachments\" and path is the one given with their message.", "inputSchema": toolSchema(map[string]any{"repo": str, "path": str, "start": map[string]string{"type": "integer"}}, "repo", "path")},
@@ -173,6 +173,10 @@ var converseTools = []any{
map[string]any{"name": "research", "description": "Ask Research (once it is on the team; see propose_specialist) to read public web pages for one of the person's tasks. Use it when an exploration or change names an outside site, brand, API or docs, or the person asking (their business, their own site), and the work needs what those pages say. task is the task id; question (at most 1,000 bytes) is what to look for, for example colours, logo, fonts, opening hours and services; urls are pages you propose (https or http, no query string, a path of at most 100 characters, at most 10), or []. URLs and bare domains the person typed on the task are read without asking; your urls are shown to the person in full on a card and read only if they tap Allow, so propose only pages the task needs and never put anything from a repository in them. This only requests a run: Equipo starts it only at the task's start (call it before start_task) or after a review round, before Engineering's next round, and Engineering waits until Research ends. At most one run per start or round and 3 per task, and Equipo never retries a run for you. Research's findings reach Engineering and Review; do not wait for them in your reply.", "inputSchema": toolSchema(map[string]any{"task": str, "question": str, "urls": map[string]any{"type": "array", "items": str, "maxItems": 10}}, "task", "question", "urls")},
map[string]any{"name": wire.ToolOfferRetry, "description": "When a task's merge failed and it waits at Ready to merge (read_task shows the failed merge step), put a card in front of the person asking whether to try the merge again. You cannot merge: only their tap merges, through Equipo's merge rules, and it is offered only when that tap could merge now. One card per task; do not ask again in your reply, and never say it is merged.", "inputSchema": toolSchema(map[string]any{"task": str}, "task")},
map[string]any{"name": wire.ToolRetryStep, "description": "Run a task's failed preview, checks or review again, as the person's own Retry would (step: preview, checks or review). Only when read_task shows that step failed and why, and another try could help: a preview that failed for its scanner (status runner.tools) needs the runner fixed first. Never a merge (use offer_retry: only the person's tap merges) and never Engineering's work. The task shows that you started it. Call it once per step.", "inputSchema": toolSchema(map[string]any{"task": str, "step": map[string]any{"type": "string", "enum": wire.RetryStepKinds}}, "task", "step")},
+ map[string]any{"name": wire.ToolPlaces, "description": "Read-only: where the team's sites go. For one project (project: its name) or every project with a site: the confirmed place (console and account), the app Equipo made for it, what the person's runner can do there now (can: setup, mint or publish; missing says why it cannot), whether it holds the site's deploy key, and the newest publish's outcome and address. While a project has no place, candidates lists where the runner's CARLOS login can publish, best first, each with the id propose_place takes. Everything is quoted data from CARLOS and the repository.", "inputSchema": toolSchema(map[string]any{"project": str})},
+ map[string]any{"name": wire.ToolProposePlace, "description": "Ask an owner where a project's site goes: kind site, the project, and one candidate id from places (never a console, an account or an app; you cannot name one). A card offers the candidates with yours first; only their tap confirms one, and confirming publishes nothing. Refused once a place is confirmed or a card is open. Usually publish_site does this for you.", "inputSchema": toolSchema(map[string]any{"kind": map[string]any{"type": "string", "enum": []string{wire.PlaceSite}}, "project": str, "candidate": str}, "kind", "project", "candidate")},
+ map[string]any{"name": wire.ToolPublishSite, "description": "Offer to publish a merged website: task is the person's own task that Equipo merged with Review's approval of its site config (release/preview.json). It puts a card in front of the person naming the place and the app; only their tap publishes. With no confirmed place it first raises a place card, and the publish card follows their choice. Use it when the person asks to publish a site, also for an older merged task that was never asked. target is site (temporary sites are not places yet). Never say a site is live until the task shows its address.", "inputSchema": toolSchema(map[string]any{"task": str, "target": map[string]any{"type": "string", "enum": []string{wire.PlaceSite}}}, "task")},
+ map[string]any{"name": wire.ToolSiteStatus, "description": "Read-only: what Equipo recorded about one project's site: its place, app, deploy key, and the newest publish's outcome, address and when. It does not ask CARLOS: the version the site serves now and its domains are not known yet. Use it when the person asks where a site is or whether it is live.", "inputSchema": toolSchema(map[string]any{"project": str}, "project")},
}
// stepTools are the tools the implement profile pins for an Engineering
diff --git a/internal/runner/thin/places.go b/internal/runner/thin/places.go
new file mode 100644
index 00000000..e93c570a
--- /dev/null
+++ b/internal/runner/thin/places.go
@@ -0,0 +1,20 @@
+package thin
+
+import (
+ "slices"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// toolPlacesOld: the instance cannot take a place tool yet (below
+// wire.ProtocolPlaces). For the model; people never read it.
+const toolPlacesOld = "Equipo needs an update before it can say where sites go or offer to publish one. Tell the person that in one line."
+
+// placesRefused answers a place tool here on a link below protocol 31:
+// Encode refuses the call, so it is never sent to an older instance.
+func placesRefused(call wire.ToolCall, protocol int) (wire.ToolResult, bool) {
+ if !slices.Contains(wire.PlacesTools, call.Name) || protocol == 0 || protocol >= wire.ProtocolPlaces {
+ return wire.ToolResult{}, false
+ }
+ return wire.ToolResult{CallID: call.CallID, IsError: true, Code: "places_unsupported", Text: toolPlacesOld}, true
+}
diff --git a/internal/runner/thin/preview.go b/internal/runner/thin/preview.go
index 1c7182ba..79ce2f69 100644
--- a/internal/runner/thin/preview.go
+++ b/internal/runner/thin/preview.go
@@ -485,6 +485,11 @@ func (e *Engineer) preview(ctx context.Context, r stepRow, progress func(wire.St
served, why := e.previewServed(context.WithoutCancel(ctx), r, mark)
return e.previewDone(rep, r, previewExport{Digest: mark.Digest}, nil, served, why)
}
+ // A carlos too old for the preview's headers refuses now, before
+ // anything is built (it would fail obscurely at the deploy).
+ if !e.previewCarlosOK(ctx) {
+ return failed(wire.ReasonCarlosOutdated)
+ }
tree, reason, err := e.judgeTree(ctx, r)
if err != nil {
rep.State, rep.Reason, rep.Termination = wire.StepFailed, reason, true
diff --git a/internal/runner/thin/preview_security_test.go b/internal/runner/thin/preview_security_test.go
index 3322cb78..901de40e 100644
--- a/internal/runner/thin/preview_security_test.go
+++ b/internal/runner/thin/preview_security_test.go
@@ -107,7 +107,7 @@ func TestPreviewUnsupportedHeaders(t *testing.T) {
e, fc, _, r := previewRig(t, mockups, nil)
const refusal = "pack preview: _headers: line 2: header \"Content-Security-Policy\" is not supported yet"
if host == "private" {
- e.Devbox = &DevboxOptions{State: filepath.Join(e.O.Runner.StateDir, "devbox"), Run: func(context.Context, string, []string, []string) (string, error) {
+ e.Devbox = &DevboxOptions{Carlos: "/carlos", State: filepath.Join(e.O.Runner.StateDir, "devbox"), Run: func(context.Context, string, []string, []string) (string, error) {
return refusal, errors.New("unsupported headers")
}}
if err := os.MkdirAll(e.Devbox.State, 0700); err != nil {
diff --git a/internal/runner/thin/research_step_test.go b/internal/runner/thin/research_step_test.go
index f9e21063..89c3af6f 100644
--- a/internal/runner/thin/research_step_test.go
+++ b/internal/runner/thin/research_step_test.go
@@ -738,7 +738,7 @@ func TestResearchCapabilityAddresses(t *testing.T) {
t.Fatalf("an error reported %+v", c)
}
// A Linux primary's capability report carries them.
- if c := linuxCapabilities(runner.Config{}, func() *wire.PreviewHost { return nil }, false, nil)(context.Background()); c.Research == nil {
+ if c := linuxCapabilities(runner.Config{}, func() *wire.PreviewHost { return nil }, nil, nil)(context.Background()); c.Research == nil {
t.Fatal("the Linux report has no Research addresses")
}
var many []string
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go
index 9a431dba..38ce17f7 100644
--- a/internal/runner/thin/run.go
+++ b/internal/runner/thin/run.go
@@ -185,9 +185,9 @@ func Run(ctx context.Context, c runner.Config, o Options) error {
preview := previewOptions(c, o.Logger)
// A paired CARLOS devbox wins over Carloku temporary sites.
devbox := ProbeDevbox(c, o.Logger, nil)
- // Merged websites publish on Carloku only when paired explicitly.
+ // Merged websites publish to their confirmed places through carlos.
site := ProbeSite(c, o.Logger)
- caps := &Capabilities{Probe: linuxCapabilities(c, PreviewHostOf(devbox, preview), site != nil, o.ResearchAddresses), Logger: o.Logger}
+ caps := &Capabilities{Probe: linuxCapabilities(c, PreviewHostOf(devbox, preview), site, o.ResearchAddresses), Logger: o.Logger}
link := &Link{Origin: c.Origin, Token: creds.Bearer.Token, State: state, Logger: o.Logger, Connected: o.Connected, Protocol: o.Protocol, WorkerOnly: platform.OS == "darwin", Role: enrolledRole(c, creds.Bearer.Role)}
link.Files = &Files{State: state, SessionRoot: o.Claude.SessionRoot, Logger: o.Logger}
// Attachments stay bounded whether or not anything arrives.
@@ -345,7 +345,7 @@ func Run(ctx context.Context, c runner.Config, o Options) error {
if err = engine.Start(ctx); err != nil {
return err
}
- engineer := &Engineer{O: o.Claude, Codex: o.Codex, Pi: piOptions(c, o.Pi), OpenCode: opencodeOptions(c, o.OpenCode), Clones: clones, Forge: fg, CI: hostedCIOf(fg), Authorize: link.Confirm, AuthorizeStep: link.ConfirmStep, ConfirmMerge: link.ConfirmMerge, ConfirmPreview: link.ConfirmPreview, Preview: preview, Devbox: devbox, Site: site, ConfirmPublish: link.ConfirmPublish, ConfirmPublication: link.ConfirmPublication, Owners: withPerson(coordinatorPersons(c)(), creds.Bearer.Person), MaxStep: o.MaxStep, Note: o.StepNote, Healthy: conns.Usable, Conns: conns, Delta: link.Delta, Activity: link.Activity, StepActivity: link.StepActivity, Retention: o.KeptRetention, Host: c.MachineLabel, Merged: func(string) { index.Kick() }}
+ engineer := &Engineer{O: o.Claude, Codex: o.Codex, Pi: piOptions(c, o.Pi), OpenCode: opencodeOptions(c, o.OpenCode), Clones: clones, Forge: fg, CI: hostedCIOf(fg), Authorize: link.Confirm, AuthorizeStep: link.ConfirmStep, ConfirmMerge: link.ConfirmMerge, ConfirmPreview: link.ConfirmPreview, Preview: preview, Devbox: devbox, Site: site, ConfirmPublish: link.ConfirmPublish, ConfirmMint: link.ConfirmMint, SiteChanged: func() { caps.Stale(); link.HelloSoon() }, ConfirmPublication: link.ConfirmPublication, Owners: withPerson(coordinatorPersons(c)(), creds.Bearer.Person), MaxStep: o.MaxStep, Note: o.StepNote, Healthy: conns.Usable, Conns: conns, Delta: link.Delta, Activity: link.Activity, StepActivity: link.StepActivity, Retention: o.KeptRetention, Host: c.MachineLabel, Merged: func(string) { index.Kick() }}
link.Forget = engineer.RemoveKept
link.TaskEnded = engineer.PreviewTaskEnded
// A Research step that met an address outside the confirmed inventory
diff --git a/internal/runner/thin/site.go b/internal/runner/thin/site.go
index cb3a7e0b..7525eea4 100644
--- a/internal/runner/thin/site.go
+++ b/internal/runner/thin/site.go
@@ -1,15 +1,20 @@
package thin
import (
+ "bufio"
"context"
+ "crypto/sha256"
+ "encoding/hex"
"encoding/json"
"errors"
"log/slog"
"net/http"
+ "net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
+ "sort"
"strings"
"time"
@@ -18,32 +23,35 @@ import (
"golang.org/x/sys/unix"
)
-// Publishing a merged website on Carloku (oficina/equipo discussion 11).
-// The site host is an adapter behind the preview hosts' interface: it
-// names the app, says where its marker is fetched, and publishes an
-// export. It uses the runner person's own signed-in carlos (their
-// ~/.carlos/credentials), so its one command is fenced hard: this
-// runner's process, never a model's sandbox, runs exactly
+// Publishing a merged website to its confirmed place (oficina/equipo
+// discussion 11; places spec 2026-11-26, slice 1). The place (console
+// host, account sqid and name, app) and the mode come from the dispatch,
+// bound to the person's tap by their destination hash; this runner
+// deploys there and nowhere else, and never changes the mode. Every
+// command is one of five fixed templates, run by this runner's process,
+// never a model's sandbox, from an empty private directory that is also
+// HOME, with CARLOS_CONFIG naming an empty configuration of the runner's
+// own:
//
-// carlos deploy --kind static --account oficina --console
-// https://console.carloku.com --app site-<slug>-<id> --channel edge
-// --timeout 5m --version <v> --no-prompt <export>
+// carlos accounts list --console <o> (reach)
+// carlos apps list --account-id <sqid> --console <o> (taken)
+// carlos deploy --kind static --account-id <sqid> --console <o>
+// --app <app> --channel edge --timeout 5m --version <v> --no-prompt <export>
+// carlos services create --role deploy --app <app> --rungs edge
+// --account-id <sqid> --console <o> <name>
//
-// built from fixed parts and three checked values (the app the instance
-// minted for the project, a version made of the merged commit, the step
-// and the attempt, and this runner's own export folder). Before the first
-// deploy of a name it has no record of, it runs one read-only command,
-// carlos apps list --account oficina --console https://console.carloku.com,
-// and refuses a name the account already holds. No other carlos
-// subcommand can be reached from here. Both run with CARLOS_CONFIG naming
-// an empty configuration of the runner's own, so no .carlos/config of
-// the person's (in a parent folder, or ~/.carlos/config) is read. A Platform role for Equipo
-// will replace the person's credential (carlos/platform 935).
+// The person's own login (their ~/.carlos/credentials) is used only for
+// the reach, a setup (the taken check, the deploy that creates the app,
+// the mint of its deploy key) and a mint (the existence check and the
+// mint), each behind its own final check. Every other deploy uses the
+// app's deploy key: CARLOS_SERVICE_TOKEN and CARLOS_CONSOLE in the
+// environment, the credentials file named absent. The key's secret is
+// read from the mint's output by this process, stored 0600 in the
+// runner's state, outside every sandbox mount, and never logged,
+// reported or put in argv.
// The fixed parts of the deploy.
const (
- siteAccount = "oficina"
- siteConsole = "https://console.carloku.com"
siteChannel = "edge"
siteTimeout = "5m"
// siteMarker is the file the runner adds beside the export and fetches
@@ -51,23 +59,29 @@ const (
siteMarker = "equipo-site.json"
)
-// phaseSitePublishing marks a publish attempt that may have changed
-// Carloku: after a restart it only reconciles from the marker.
-const phaseSitePublishing = "site_publishing"
+// Step phases of a publish attempt that may have changed CARLOS: after a
+// restart they only reconcile.
+const (
+ phaseSitePublishing = "site_publishing"
+ phaseSiteMinting = "site_minting"
+)
-// SiteOptions is Carloku as the site host: the carlos binary, the
-// person's signed-in credential file it reads (CARLOS_CREDENTIALS), and
-// this runner's state for it. Client and URL are seams for the tests
-// (nil: a client that follows no redirect, and the URL deploy printed).
+// SiteOptions is CARLOS as the site host: the carlos binary, the person's
+// signed-in credential file ("" when none passes its checks: publishing
+// with held deploy keys still works), and this runner's state for sites.
+// Client and URL are seams for the tests (nil: a client that follows no
+// redirect, and the URL deploy printed).
type SiteOptions struct {
Carlos string
Credentials string
State string
Client *http.Client
URL func(app string) string
+ // CLI is the carlos and its version (nil: one for Carlos).
+ CLI *carlosCLI
}
-func (s *SiteOptions) Kind() string { return wire.SiteHostCarloku }
+func (s *SiteOptions) Kind() string { return "carlos" }
// App is the app a publish step names, when it is a site's.
func (s *SiteOptions) App(app string) string {
@@ -77,72 +91,64 @@ func (s *SiteOptions) App(app string) string {
return ""
}
-// Origin is where app's marker is fetched: the address its deploy printed
-// (recorded), "" before one did.
+// Origin is where app's marker is fetched: the URL its deploy printed in
+// this attempt, through the URL seam.
func (s *SiteOptions) Origin(app string) string {
if s.URL != nil {
return s.URL(app)
}
- rec, ok := s.recorded(app)
- if !ok || rec.URL == "" {
- return ""
- }
- return strings.TrimSuffix(rec.URL, "/")
+ return ""
}
func (s *SiteOptions) HTTP() *http.Client { return s.Client }
var _ previewHost = (*SiteOptions)(nil)
-// ProbeSite pairs the runner with Carloku sites when its configuration
-// says so (EQUIPO_SITE_HOST=carloku: explicit, never a guess), carlos is
-// found (EQUIPO_CARLOS_PATH, else PATH, else ~/.local/bin) and the signed-
-// in credential (CARLOS_CREDENTIALS, else ~/.carlos/credentials) is this
-// user's own regular file, mode 0600, outside every directory a sandbox
-// mounts. It runs no carlos command. nil when not.
-func ProbeSite(c runner.Config, logger *slog.Logger) *SiteOptions {
- if c.SiteHost != wire.SiteHostCarloku || c.StateDir == "" {
- return nil
+func (s *SiteOptions) cli() *carlosCLI {
+ if s.CLI == nil {
+ s.CLI = &carlosCLI{Bin: s.Carlos}
}
- carlos := c.CarlosPath
- if carlos == "" {
- if p, err := exec.LookPath("carlos"); err == nil {
- carlos = p
- } else if home, err := os.UserHomeDir(); err == nil {
- carlos = filepath.Join(home, ".local", "bin", "carlos")
- }
- }
- if !filepath.IsAbs(carlos) {
+ return s.CLI
+}
+
+// ProbeSite pairs the runner with CARLOS sites when carlos is found and
+// the runner has a state directory. The person's signed-in credential
+// (CARLOS_CREDENTIALS, else ~/.carlos/credentials) is used only when it
+// is this user's own regular file, mode 0600, outside every directory a
+// sandbox mounts. It runs no carlos command. nil when not.
+func ProbeSite(c runner.Config, logger *slog.Logger) *SiteOptions {
+ carlos := carlosLookup(c)
+ if carlos == "" || c.StateDir == "" {
return nil
}
- if info, err := os.Stat(carlos); err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0o111 == 0 {
+ s := &SiteOptions{Carlos: carlos, State: filepath.Join(c.StateDir, "site")}
+ if err := os.MkdirAll(s.State, 0o700); err != nil {
return nil
}
creds := os.Getenv("CARLOS_CREDENTIALS")
if creds == "" {
- home, err := os.UserHomeDir()
- if err != nil {
- return nil
+ if home, err := os.UserHomeDir(); err == nil {
+ creds = filepath.Join(home, ".carlos", "credentials")
}
- creds = filepath.Join(home, ".carlos", "credentials")
}
- if err := siteCredential(c, creds); err != nil {
- if logger != nil {
- logger.Warn("sites are off: the carlos credential was refused", "reason", err.Error())
- }
- return nil
+ if err := siteCredential(c, creds); err == nil {
+ s.Credentials = creds
+ } else if logger != nil && !errors.Is(err, os.ErrNotExist) {
+ logger.Warn("site setup is off: the carlos credential was refused", "reason", err.Error())
}
- s := &SiteOptions{Carlos: carlos, Credentials: creds, State: filepath.Join(c.StateDir, "site")}
- if err := os.MkdirAll(s.State, 0o700); err != nil {
+ // Deploy keys live under the state: never inside a sandbox mount.
+ place := c
+ place.PreviewCredentialPath = s.State
+ if previewCredentialPlace(place) != nil {
return nil
}
if logger != nil {
- logger.Info("sites publish on Carloku", "account", siteAccount, "channel", siteChannel)
+ logger.Info("sites publish through carlos", "login", s.Credentials != "")
}
return s
}
-// siteCredential checks the credential file without reading it: an
+// siteCredential checks a credential file without reading it: an
// absolute path to a regular file (not a link), mode exactly 0600, owned
// by this user, in no directory a sandbox mounts.
func siteCredential(c runner.Config, file string) error {
@@ -150,7 +156,13 @@ func siteCredential(c runner.Config, file string) error {
return errPreviewCredentialFile
}
var st unix.Stat_t
- if unix.Lstat(file, &st) != nil || st.Mode&unix.S_IFMT != unix.S_IFREG || st.Mode&0o7777 != 0o600 || int(st.Uid) != os.Getuid() {
+ if err := unix.Lstat(file, &st); err != nil {
+ if errors.Is(err, unix.ENOENT) {
+ return os.ErrNotExist
+ }
+ return errPreviewCredentialFile
+ }
+ if st.Mode&unix.S_IFMT != unix.S_IFREG || st.Mode&0o7777 != 0o600 || int(st.Uid) != os.Getuid() {
return errPreviewCredentialFile
}
c.PreviewCredentialPath = file
@@ -163,27 +175,56 @@ var (
siteStepID = regexp.MustCompile(`^s_([a-z0-9]{1,40})$`)
)
-// siteDeployArgs is the one command the site host runs, from its fixed
-// parts: app must be a site's app, version a site version and dir an
-// absolute, clean folder; anything else is refused.
-func siteDeployArgs(app, version, dir string) ([]string, error) {
- if !wire.ValidSiteApp(app) || !siteVersion.MatchString(version) || !filepath.IsAbs(dir) || filepath.Clean(dir) != dir || dir == "/" || strings.ContainsAny(dir, "\x00\r\n") {
+// siteTarget is a dispatch's destination, checked: every part of its
+// shape and hashing to its Destination.
+type siteTarget struct {
+ Console, Sqid, Name, App, Mode, DeployName, Destination string
+}
+
+func (t siteTarget) origin() string { return wire.ConsoleOrigin(t.Console) }
+
+// targetOf is the dispatch's checked destination, ok false when any part
+// is out of shape or the hash does not bind them.
+func targetOf(d *wire.PublishDispatch) (siteTarget, bool) {
+ if d == nil {
+ return siteTarget{}, false
+ }
+ t := siteTarget{Console: d.Console, Sqid: d.Account, Name: d.AccountName, App: d.App, Mode: d.Mode, DeployName: d.DeployName, Destination: d.Destination}
+ if !wire.ValidConsoleHost(t.Console) || !wire.ValidSqid(t.Sqid) || !wire.ValidAccountName(t.Name) || !wire.ValidSiteApp(t.App) || t.Destination != wire.SiteDestination(t.Console, t.Sqid, t.Name, t.App) {
+ return siteTarget{}, false
+ }
+ switch t.Mode {
+ case wire.SitePublish:
+ return t, t.DeployName == ""
+ case wire.SiteSetup, wire.SiteMint:
+ return t, wire.ValidDeployName(t.DeployName)
+ }
+ return siteTarget{}, false
+}
+
+func cleanDir(dir string) bool {
+ return filepath.IsAbs(dir) && filepath.Clean(dir) == dir && dir != "/" && !strings.ContainsAny(dir, "\x00\r\n")
+}
+
+// siteDeployArgs is the deploy template.
+func siteDeployArgs(t siteTarget, version, dir string) ([]string, error) {
+ if !siteVersion.MatchString(version) || !cleanDir(dir) {
return nil, errSiteCommand
}
- return []string{"deploy", "--kind", "static", "--account", siteAccount, "--console", siteConsole, "--app", app, "--channel", siteChannel, "--timeout", siteTimeout, "--version", version, "--no-prompt", dir}, nil
+ return []string{"deploy", "--kind", "static", "--account-id", t.Sqid, "--console", t.origin(), "--app", t.App, "--channel", siteChannel, "--timeout", siteTimeout, "--version", version, "--no-prompt", dir}, nil
}
// siteListArgs is the read-only command that says whether a name is taken.
-func siteListArgs() []string {
- return []string{"apps", "list", "--account", siteAccount, "--console", siteConsole}
+func siteListArgs(t siteTarget) []string {
+ return []string{"apps", "list", "--account-id", t.Sqid, "--console", t.origin()}
}
-// taken reports whether the account already holds app (live, kept or in
-// the Trash). A list it cannot read counts as taken.
-func (s *SiteOptions) taken(ctx context.Context, app string) bool {
- out, err := s.run(ctx, siteListArgs())
- state, ok := appState(out, app)
- return err != nil || !ok || state != appMissing
+// siteMintArgs is the mint template: an edge-only deploy key for the app.
+func siteMintArgs(t siteTarget) ([]string, error) {
+ if !wire.ValidDeployName(t.DeployName) {
+ return nil, errSiteCommand
+ }
+ return []string{"services", "create", "--role", "deploy", "--app", t.App, "--rungs", siteChannel, "--account-id", t.Sqid, "--console", t.origin(), t.DeployName}, nil
}
// siteVersionOf is the version a publish attempt deploys: the merged
@@ -197,22 +238,20 @@ func siteVersionOf(r stepRow) (string, bool) {
return v, siteVersion.MatchString(v)
}
-// deploy runs the deploy for app, from an empty private directory that is
-// also HOME, with the person's credential named in the environment and
-// nothing else of theirs or of the repository.
-func (s *SiteOptions) deploy(ctx context.Context, app, version, dir string) (string, error) {
- args, err := siteDeployArgs(app, version, dir)
- if err != nil {
- return "", err
- }
- return s.run(ctx, args)
+// runAs says whose authority a command runs with: the person's login, or
+// an app's deploy key.
+type runAs struct {
+ login bool
+ key *deployKey
}
-// run runs one of the two fixed commands from an empty private directory
-// that is also HOME, with the person's credential, an empty configuration
-// of the runner's own and no update check in the environment, and nothing
-// else of theirs or of the repository.
-func (s *SiteOptions) run(ctx context.Context, args []string) (string, error) {
+// run runs one fixed command from an empty private directory that is also
+// HOME, with an empty configuration of the runner's own, no update check,
+// and either the person's credential or a deploy key, nothing else.
+func (s *SiteOptions) run(ctx context.Context, as runAs, args []string) (string, error) {
+ if as.login == (as.key != nil) || as.login && s.Credentials == "" {
+ return "", errSiteCommand
+ }
config := filepath.Join(s.State, "config", "carlos.json")
if err := os.MkdirAll(filepath.Dir(config), 0o700); err != nil {
return "", err
@@ -231,7 +270,12 @@ func (s *SiteOptions) run(ctx context.Context, args []string) (string, error) {
defer cancel()
cmd := exec.CommandContext(cctx, s.Carlos, args...)
cmd.Dir = run
- cmd.Env = []string{"HOME=" + run, "PATH=/usr/bin:/bin", "CARLOS_CREDENTIALS=" + s.Credentials, "CARLOS_CONFIG=" + config, "CARLOS_NO_UPDATE_CHECK=1"}
+ cmd.Env = []string{"HOME=" + run, "PATH=/usr/bin:/bin", "CARLOS_CONFIG=" + config, "CARLOS_NO_UPDATE_CHECK=1"}
+ if as.login {
+ cmd.Env = append(cmd.Env, "CARLOS_CREDENTIALS="+s.Credentials)
+ } else {
+ cmd.Env = append(cmd.Env, "CARLOS_CREDENTIALS="+filepath.Join(run, "none"), "CARLOS_SERVICE_TOKEN="+as.key.Token, "CARLOS_CONSOLE="+wire.ConsoleOrigin(as.key.Console))
+ }
out, clipped, err := boundedOutput(cmd, 64<<10)
if clipped && err == nil {
err = errors.New("carlos output too long")
@@ -239,38 +283,53 @@ func (s *SiteOptions) run(ctx context.Context, args []string) (string, error) {
return string(out), err
}
-// siteRecord is what this runner deployed for an app: written before the
-// deploy (intent) and completed with the URL it printed. Owned is the
-// proof that this runner made the app: set only once a deploy succeeded
-// and its marker answered, never by an intent, a failed deploy or one
-// that could not be confirmed.
-type siteRecord struct {
- App string `json:"app"`
- Task string `json:"task"`
- URL string `json:"url,omitempty"`
- Owned bool `json:"owned,omitempty"`
-}
-
-func (s *SiteOptions) recordPath(app string) string { return filepath.Join(s.State, app+".json") }
-
-func (s *SiteOptions) record(rec siteRecord) error {
- if !wire.ValidSiteApp(rec.App) {
- return errSiteCommand
+// siteListed reads `carlos apps list` strictly: a "using" line, then
+// either "no apps in this account" or app lines (with or without the
+// header and the region column). present says whether app is listed; ok
+// false when the output is anything else.
+func siteListed(out, app string) (present, ok bool) {
+ sc := bufio.NewScanner(strings.NewReader(ansi.ReplaceAllString(out, "")))
+ var lines []string
+ for sc.Scan() {
+ if l := strings.TrimSpace(sc.Text()); l != "" {
+ lines = append(lines, l)
+ }
}
- if err := os.MkdirAll(s.State, 0o700); err != nil {
- return err
+ if len(lines) == 0 || !strings.HasPrefix(lines[0], "using ") {
+ return false, false
}
- raw, _ := json.Marshal(rec)
- return os.WriteFile(s.recordPath(rec.App), raw, 0o600)
+ rest := lines[1:]
+ if len(rest) == 1 && rest[0] == "no apps in this account" {
+ return false, true
+ }
+ if len(rest) > 0 {
+ if f := strings.Fields(rest[0]); len(f) >= 2 && f[0] == "APP" && f[1] == "STATE" {
+ rest = rest[1:]
+ }
+ }
+ if len(rest) == 0 {
+ return false, false
+ }
+ for _, l := range rest {
+ f := strings.Fields(l)
+ if len(f) < 2 || !listedApp.MatchString(f[0]) || f[1] != "live" && f[1] != "trashed" {
+ return false, false
+ }
+ present = present || f[0] == app
+ }
+ return present, true
}
-func (s *SiteOptions) recorded(app string) (siteRecord, bool) {
- var rec siteRecord
- if !wire.ValidSiteApp(app) {
- return rec, false
+var listedApp = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`)
+
+// listed asks the account whether it holds app; ok false when the list
+// could not be read.
+func (s *SiteOptions) listed(ctx context.Context, t siteTarget) (present, ok bool) {
+ out, err := s.run(ctx, runAs{login: true}, siteListArgs(t))
+ if err != nil {
+ return false, false
}
- raw, err := os.ReadFile(s.recordPath(app))
- return rec, err == nil && json.Unmarshal(raw, &rec) == nil && rec.App == app
+ return siteListed(out, t.App)
}
// siteURL is the app's address as deploy printed it: the first
@@ -280,14 +339,328 @@ func siteURL(out, app string) (string, bool) {
return m, m != "" && len(m) <= 200
}
+// ---- this runner's site state ----------------------------------------------
+
+// deployKey is a deploy key this runner holds: where it was minted for, its
+// CARLOS name, the secret and its fingerprint.
+type deployKey struct {
+ Console string `json:"console"`
+ Account string `json:"account"`
+ App string `json:"app"`
+ Name string `json:"name"`
+ Token string `json:"token"`
+ Fingerprint string `json:"fingerprint"`
+ MintedAt time.Time `json:"minted_at"`
+}
+
+// destDir is a destination's folder under dir: console, sqid and app are
+// each checked, so none can climb out.
+func destDir(root, console, sqid string) (string, bool) {
+ if !wire.ValidConsoleHost(console) || !wire.ValidSqid(sqid) {
+ return "", false
+ }
+ return filepath.Join(root, console, sqid), true
+}
+
+func (s *SiteOptions) keyPath(t siteTarget) (string, bool) {
+ d, ok := destDir(filepath.Join(s.State, "keys"), t.Console, t.Sqid)
+ return filepath.Join(d, t.App+".json"), ok && wire.ValidSiteApp(t.App)
+}
+
+func (s *SiteOptions) lostPath(t siteTarget) (string, bool) {
+ d, ok := destDir(filepath.Join(s.State, "keys"), t.Console, t.Sqid)
+ return filepath.Join(d, t.App+".lost"), ok && wire.ValidSiteApp(t.App)
+}
+
+func (s *SiteOptions) createdPath(t siteTarget) (string, bool) {
+ d, ok := destDir(filepath.Join(s.State, "created"), t.Console, t.Sqid)
+ return filepath.Join(d, t.App+".json"), ok && wire.ValidSiteApp(t.App)
+}
+
+// key is the deploy key held for exactly this destination.
+func (s *SiteOptions) key(t siteTarget) (*deployKey, bool) {
+ p, ok := s.keyPath(t)
+ if !ok {
+ return nil, false
+ }
+ raw, err := os.ReadFile(p)
+ if err != nil {
+ return nil, false
+ }
+ var k deployKey
+ if json.Unmarshal(raw, &k) != nil || k.Token == "" {
+ return nil, false
+ }
+ return &k, true
+}
+
+// writeSecret writes raw to p, 0600 in 0700 folders, through a temp file
+// renamed into place, so a crash leaves the old file or the new, never a
+// part.
+func writeSecret(p string, raw []byte) error {
+ if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
+ return err
+ }
+ f, err := os.CreateTemp(filepath.Dir(p), ".tmp-*")
+ if err != nil {
+ return err
+ }
+ defer os.Remove(f.Name())
+ if err := f.Chmod(0o600); err != nil {
+ f.Close()
+ return err
+ }
+ if _, err := f.Write(raw); err != nil {
+ f.Close()
+ return err
+ }
+ if err := f.Sync(); err != nil {
+ f.Close()
+ return err
+ }
+ if err := f.Close(); err != nil {
+ return err
+ }
+ return os.Rename(f.Name(), p)
+}
+
+// created records that this runner's setup creates the app at t, right
+// before its deploy, the name having just been found free: the one proof
+// a mint accepts that the app is Equipo's.
+func (s *SiteOptions) created(t siteTarget, task string) error {
+ p, ok := s.createdPath(t)
+ if !ok {
+ return errSiteCommand
+ }
+ raw, _ := json.Marshal(map[string]any{"console": t.Console, "account": t.Sqid, "app": t.App, "task": task, "at": time.Now().UTC()})
+ return writeSecret(p, raw)
+}
+
+func (s *SiteOptions) madeHere(t siteTarget) bool {
+ p, ok := s.createdPath(t)
+ if !ok {
+ return false
+ }
+ raw, err := os.ReadFile(p)
+ var rec struct{ Console, Account, App string }
+ return err == nil && json.Unmarshal(raw, &rec) == nil && rec.Console == t.Console && rec.Account == t.Sqid && rec.App == t.App
+}
+
+// mintToken is the one secret line a mint prints, and the line naming
+// what it minted.
+var (
+ mintToken = regexp.MustCompile(`^\s*CARLOS_SERVICE_TOKEN=([!-~]{16,512})\s*$`)
+ mintedLine = regexp.MustCompile(`^minted service:([^/\s]+)/(\S+) \(role deploy, app (\S+), rungs ([a-z, ]+)\)$`)
+)
+
+// mintedKey reads a mint's output: exactly one token line and the line
+// naming the name, app and edge only. The secret never leaves here but in
+// the key.
+func mintedKey(out string, t siteTarget) (string, bool) {
+ token, names := "", 0
+ okLine := false
+ for _, l := range strings.Split(ansi.ReplaceAllString(out, ""), "\n") {
+ if m := mintToken.FindStringSubmatch(l); m != nil {
+ token, names = m[1], names+1
+ }
+ if m := mintedLine.FindStringSubmatch(strings.TrimSpace(l)); m != nil {
+ okLine = okLine || m[1] == t.Sqid && m[2] == t.DeployName && m[3] == t.App && m[4] == siteChannel
+ }
+ }
+ return token, names == 1 && okLine
+}
+
+// mint asks CARLOS for the app's deploy key with the person's login,
+// once: the intent is recorded first (lost until the key is stored), the
+// secret stored before the intent goes. held false leaves it lost.
+func (s *SiteOptions) mint(ctx context.Context, t siteTarget) bool {
+ lost, ok := s.lostPath(t)
+ keyFile, ok2 := s.keyPath(t)
+ args, err := siteMintArgs(t)
+ if !ok || !ok2 || err != nil {
+ return false
+ }
+ intent, _ := json.Marshal(map[string]string{"name": t.DeployName})
+ if writeSecret(lost, intent) != nil {
+ return false
+ }
+ out, err := s.run(ctx, runAs{login: true}, args)
+ token, good := mintedKey(out, t)
+ if err != nil || !good {
+ return false
+ }
+ sum := sha256.Sum256([]byte(token))
+ raw, _ := json.Marshal(deployKey{Console: t.Console, Account: t.Sqid, App: t.App, Name: t.DeployName, Token: token, Fingerprint: hex.EncodeToString(sum[:])[:16], MintedAt: time.Now().UTC()})
+ if writeSecret(keyFile, raw) != nil {
+ return false
+ }
+ os.Remove(lost)
+ return true
+}
+
+// deploys are the keys this runner holds and the mints it lost, for the
+// hello: never a secret.
+func (s *SiteOptions) deploys() []wire.ReachDeploy {
+ out := []wire.ReachDeploy{}
+ root := filepath.Join(s.State, "keys")
+ consoles, _ := os.ReadDir(root)
+ for _, c := range consoles {
+ sqids, _ := os.ReadDir(filepath.Join(root, c.Name()))
+ for _, q := range sqids {
+ files, _ := os.ReadDir(filepath.Join(root, c.Name(), q.Name()))
+ for _, f := range files {
+ name := f.Name()
+ t := siteTarget{Console: c.Name(), Sqid: q.Name()}
+ switch {
+ case strings.HasSuffix(name, ".json"):
+ t.App = strings.TrimSuffix(name, ".json")
+ if k, ok := s.key(t); ok && k.Console == t.Console && k.Account == t.Sqid && k.App == t.App && wire.ValidDeployName(k.Name) {
+ out = append(out, wire.ReachDeploy{Console: t.Console, Account: t.Sqid, App: t.App, Name: k.Name, Fingerprint: k.Fingerprint})
+ }
+ case strings.HasSuffix(name, ".lost"):
+ t.App = strings.TrimSuffix(name, ".lost")
+ raw, err := os.ReadFile(filepath.Join(root, c.Name(), q.Name(), name))
+ var in struct{ Name string }
+ if err == nil && json.Unmarshal(raw, &in) == nil && wire.ValidSiteApp(t.App) && wire.ValidDeployName(in.Name) && wire.ValidConsoleHost(t.Console) && wire.ValidSqid(t.Sqid) {
+ out = append(out, wire.ReachDeploy{Console: t.Console, Account: t.Sqid, App: t.App, Name: in.Name, Lost: true})
+ }
+ }
+ }
+ }
+ }
+ sort.Slice(out, func(i, j int) bool {
+ a, b := out[i], out[j]
+ return a.Console+a.Account+a.App+a.Name < b.Console+b.Account+b.App+b.Name
+ })
+ if len(out) > wire.MaxReachDeploys {
+ out = out[:wire.MaxReachDeploys]
+ }
+ return out
+}
+
+// loginConsoles are the console hosts of the live entries in the
+// person's credential file, read by this process for their names only.
+func (s *SiteOptions) loginConsoles() []string {
+ if s.Credentials == "" {
+ return nil
+ }
+ raw, err := os.ReadFile(s.Credentials)
+ if err != nil || len(raw) > 1<<20 {
+ return nil
+ }
+ var f struct {
+ Credentials []struct {
+ Console string `json:"console"`
+ ExpiresAt time.Time `json:"expires_at"`
+ } `json:"credentials"`
+ }
+ err = json.Unmarshal(raw, &f)
+ clear(raw)
+ if err != nil {
+ return nil
+ }
+ var out []string
+ for _, c := range f.Credentials {
+ u, err := url.Parse(c.Console)
+ if err != nil || u.Scheme != "https" || u.User != nil || u.Port() != "" || u.Path != "" && u.Path != "/" || u.RawQuery != "" || !wire.ValidConsoleHost(u.Host) {
+ continue
+ }
+ if !c.ExpiresAt.IsZero() && time.Now().After(c.ExpiresAt) {
+ continue
+ }
+ if !containsString(out, u.Host) {
+ out = append(out, u.Host)
+ }
+ }
+ if len(out) > wire.MaxReachLogins {
+ out = out[:wire.MaxReachLogins]
+ }
+ return out
+}
+
+func containsString(list []string, s string) bool {
+ for _, v := range list {
+ if v == s {
+ return true
+ }
+ }
+ return false
+}
+
+// ownedAccounts reads `carlos accounts list`: its NAME SQID ROLE table,
+// the owner rows, each validated.
+func ownedAccounts(out string) []wire.ReachAccount {
+ sc := bufio.NewScanner(strings.NewReader(ansi.ReplaceAllString(out, "")))
+ header := false
+ seen := map[string]bool{}
+ accounts := []wire.ReachAccount{}
+ for sc.Scan() {
+ f := strings.Fields(sc.Text())
+ if len(f) == 0 {
+ continue
+ }
+ if !header {
+ header = len(f) == 3 && f[0] == "NAME" && f[1] == "SQID" && f[2] == "ROLE"
+ if !header {
+ return []wire.ReachAccount{}
+ }
+ continue
+ }
+ if len(f) != 3 || f[2] != "owner" || !wire.ValidAccountName(f[0]) || !wire.ValidSqid(f[1]) || seen[f[1]] {
+ continue
+ }
+ seen[f[1]] = true
+ accounts = append(accounts, wire.ReachAccount{Name: f[0], Sqid: f[1]})
+ if len(accounts) == wire.MaxReachAccounts {
+ break
+ }
+ }
+ return accounts
+}
+
+// Reach is what this runner's carlos can do now: the owned accounts on
+// each console its login reaches (one read-only list each, 20 seconds),
+// and the deploy keys it holds or lost. nil without a usable carlos.
+func (s *SiteOptions) Reach(ctx context.Context) *wire.Reach {
+ if s == nil || !s.cli().OK(ctx) {
+ return nil
+ }
+ r := &wire.Reach{Logins: []wire.ReachLogin{}, Deploys: s.deploys()}
+ for _, console := range s.loginConsoles() {
+ lctx, cancel := context.WithTimeout(ctx, 20*time.Second)
+ out, err := s.run(lctx, runAs{login: true}, []string{"accounts", "list", "--console", wire.ConsoleOrigin(console)})
+ cancel()
+ if err != nil {
+ continue
+ }
+ if accounts := ownedAccounts(out); len(accounts) > 0 {
+ r.Logins = append(r.Logins, wire.ReachLogin{Console: console, Accounts: accounts})
+ }
+ }
+ return r
+}
+
// ErrPublishNotBuilt is the instance's refusal of a publish check whose
// built report it has not applied yet.
var ErrPublishNotBuilt = errors.New("publish not built yet")
-// publishSite runs a publish step: the merged commit must be on the
-// default branch; its site is exported from git objects and reported
-// built; the instance decides the deploy for that digest; one fenced
-// deploy; then the marker over https says whether it is served.
+// Reasons a publish ends with that are its own.
+const (
+ reasonPublishSecrets = "publish_secrets"
+ reasonPublishScanner = "publish_scanner"
+ reasonPublishKeyMissing = "publish_key_missing"
+ reasonPublishMintFailed = "publish_mint_failed"
+ reasonPublishAppMissing = "publish_app_missing"
+ reasonPublishAppUnproven = "publish_app_unproven"
+)
+
+// publishSite runs a publish step in the mode the person's tap allowed:
+// the merged commit must be on the default branch; its site is exported
+// from git objects, scanned for secrets and reported built; then, each
+// behind its own final check for this export and destination, a setup's
+// taken check, deploy with the login and mint, a mint's existence check,
+// mint and deploy with the new key, or a publish's deploy with the held
+// key; then the marker over https says whether it is served.
func (e *Engineer) publishSite(ctx context.Context, r stepRow, progress func(wire.StepReport)) wire.StepReport {
rep := judgeReport(r)
failed := func(reason string) wire.StepReport {
@@ -295,29 +668,33 @@ func (e *Engineer) publishSite(ctx context.Context, r stepRow, progress func(wir
return rep
}
site := e.Site
- if site == nil || e.ConfirmPublish == nil {
+ if site == nil || e.ConfirmPublish == nil || e.ConfirmMint == nil {
return failed("publish_off")
}
version, ok := siteVersionOf(r)
- if r.Publish == nil || !wire.ValidSiteApp(r.Publish.App) || !validBranch(r.Publish.Into) || strings.HasPrefix(r.Publish.Into, "-") || !ok {
+ t, tok := targetOf(r.Publish)
+ if !tok || !validBranch(r.Publish.Into) || strings.HasPrefix(r.Publish.Into, "-") || !ok {
return failed("policy_rejected")
}
- app := r.Publish.App
stage := filepath.Join(e.root(), stepKey(r), "site")
- if r.Phase == phaseSitePublishing {
- // After a restart: nothing is rebuilt or sent; the marker decides.
- var mark previewMark
- raw, err := os.ReadFile(filepath.Join(stage, siteMarker))
- if err != nil || json.Unmarshal(raw, &mark) != nil {
- return e.siteDone(rep, app, version, previewExport{}, "", false)
+ if r.Phase == phaseSitePublishing || r.Phase == phaseSiteMinting {
+ return e.siteReconcile(ctx, rep, r, t, version, stage)
+ }
+ if !site.cli().OK(ctx) {
+ return failed(wire.ReasonCarlosOutdated)
+ }
+ var key *deployKey
+ switch t.Mode {
+ case wire.SitePublish:
+ k, held := site.key(t)
+ if !held {
+ return failed(reasonPublishKeyMissing)
}
- rec, _ := site.recorded(app)
- served := rec.URL != "" && e.markerServed(context.WithoutCancel(ctx), site, app, siteMarker, mark)
- if served && !rec.Owned {
- rec.Owned = true
- site.record(rec)
+ key = k
+ case wire.SiteSetup, wire.SiteMint:
+ if site.Credentials == "" {
+ return failed("publish_off")
}
- return e.siteDone(rep, app, version, previewExport{Digest: mark.Digest}, rec.URL, served)
}
tree, reason, err := e.judgeTree(ctx, r)
if err != nil {
@@ -337,6 +714,8 @@ func (e *Engineer) publishSite(ctx context.Context, r stepRow, progress func(wir
if err != nil {
return failed("publish_config")
}
+ // The project's own files only: no Equipo _headers (a project's own
+ // _headers stays, and is scanned with the rest).
ex, err := exportStatic(ctx, tree.Git, tree.GitDir, r.CandidateSHA, cfg.Output, stage, "")
switch {
case errors.Is(err, errPreviewTooLarge):
@@ -344,6 +723,15 @@ func (e *Engineer) publishSite(ctx context.Context, r stepRow, progress func(wir
case err != nil:
return failed("publish_config")
}
+ // The trusted secret scan, on exactly what would be sent: a finding
+ // or a scanner that cannot run refuses the publish.
+ switch e.scanPreview(ctx, stage) {
+ case "":
+ case "preview_secrets":
+ return failed(reasonPublishSecrets)
+ default:
+ return failed(reasonPublishScanner)
+ }
mark := previewMark{Task: r.TaskID, Candidate: r.CandidateSHA, Step: r.StepID, Attempt: r.Attempt, Digest: ex.Digest}
raw, _ := json.Marshal(mark)
if err := os.WriteFile(filepath.Join(stage, siteMarker), raw, 0o600); err != nil {
@@ -352,31 +740,100 @@ func (e *Engineer) publishSite(ctx context.Context, r stepRow, progress func(wir
rep.Publish = &wire.PublishResult{Phase: wire.PublishBuilt, Digest: ex.Digest, Files: ex.Files, Bytes: ex.Bytes}
progress(rep)
rep.Publish = nil
- if err := e.confirmPublish(ctx, r, ex.Digest); err != nil {
+ cancelled := func(err error) wire.StepReport {
rep.State, rep.Reason, rep.Termination = wire.StepCancelled, leaseReason(err), true
return rep
}
- // A name this runner has no verified deploy of: the account must not
- // hold it already (another project's, another Equipo's, a person's
- // own, or one made since a deploy of ours failed). Between this list
- // and the deploy another app of the name could still appear: accepted
- // (controller ruling, 2026-11-12), since the six random characters make
- // it impractical and a create-only deploy needs Platform (carlos/
- // platform 935).
- prev, _ := site.recorded(app)
- owned := prev.Owned
- if !owned && site.taken(ctx, app) {
- return failed("publish_app_taken")
- }
- // From here Carloku may change: a restart only reconciles.
+ switch t.Mode {
+ case wire.SiteSetup:
+ // A name this runner has no proof of making here must be free in
+ // the account (another project's, another Equipo's, a person's
+ // own). Between this list and the deploy another app of the name
+ // could still appear: accepted (controller ruling, 2026-11-12);
+ // the six random characters make it impractical.
+ if !site.madeHere(t) {
+ present, ok := site.listed(ctx, t)
+ if !ok || present {
+ return failed("publish_app_taken")
+ }
+ }
+ if err := e.confirmSite(ctx, e.ConfirmPublish, r, ex.Digest, t.Destination); err != nil {
+ return cancelled(err)
+ }
+ // The name was free a moment ago and this runner creates it now:
+ // recorded first, so a deploy that failed half way (the app made,
+ // the ship not) can still get its key by a mint. The window between
+ // the two is the accepted list and deploy race.
+ if err := site.created(t, r.TaskID); err != nil {
+ return failed("publish_failed")
+ }
+ done, deployed := e.siteDeploy(ctx, rep, r, t, runAs{login: true}, version, stage, ex, mark)
+ if !deployed {
+ return done
+ }
+ // Right after the app exists: its deploy key, behind its own check.
+ if err := e.confirmSite(ctx, e.ConfirmMint, r, ex.Digest, t.Destination); err == nil {
+ if e.O.State.setStepPhase(context.WithoutCancel(ctx), r, phaseSiteMinting, r.Base, r.Candidate) == nil {
+ done.Publish.DeployHeld = site.mint(ctx, t)
+ }
+ }
+ e.siteChanged()
+ return done
+ case wire.SiteMint:
+ if !site.madeHere(t) {
+ present, ok := site.listed(ctx, t)
+ switch {
+ case ok && !present:
+ return failed(reasonPublishAppMissing)
+ case ok:
+ return failed(reasonPublishAppUnproven)
+ }
+ return failed("publish_failed")
+ }
+ if err := e.confirmSite(ctx, e.ConfirmMint, r, ex.Digest, t.Destination); err != nil {
+ return cancelled(err)
+ }
+ if err := e.O.State.setStepPhase(context.WithoutCancel(ctx), r, phaseSiteMinting, r.Base, r.Candidate); err != nil {
+ return failed("publish_failed")
+ }
+ held := site.mint(ctx, t)
+ e.siteChanged()
+ if !held {
+ return failed(reasonPublishMintFailed)
+ }
+ k, _ := site.key(t)
+ key = k
+ }
+ if err := e.confirmSite(ctx, e.ConfirmPublish, r, ex.Digest, t.Destination); err != nil {
+ return cancelled(err)
+ }
+ done, _ := e.siteDeploy(ctx, rep, r, t, runAs{key: key}, version, stage, ex, mark)
+ done.Publish.DeployHeld = true
+ return done
+}
+
+// siteChanged makes the next hello carry the runner's new reach.
+func (e *Engineer) siteChanged() {
+ if e.SiteChanged != nil {
+ e.SiteChanged()
+ }
+}
+
+// siteDeploy marks the attempt as one that may change CARLOS, deploys,
+// and says whether the marker answers. deployed reports the deploy
+// command succeeded.
+func (e *Engineer) siteDeploy(ctx context.Context, rep wire.StepReport, r stepRow, t siteTarget, as runAs, version, stage string, ex previewExport, mark previewMark) (wire.StepReport, bool) {
+ site := e.Site
if err := e.O.State.setStepPhase(context.WithoutCancel(ctx), r, phaseSitePublishing, r.Base, r.Candidate); err != nil {
- return failed("publish_failed")
+ rep.State, rep.Reason, rep.Termination = wire.StepFailed, "publish_failed", true
+ return rep, false
}
- if err := site.record(siteRecord{App: app, Task: r.TaskID, Owned: owned}); err != nil {
- return failed("publish_failed")
+ args, err := siteDeployArgs(t, version, stage)
+ out := ""
+ if err == nil {
+ out, err = site.run(ctx, as, args)
}
- out, err := site.deploy(ctx, app, version, stage)
- // Carloku keeps its own copy: the export can go (the marker stays for
+ // CARLOS keeps its own copy: the export can go (the marker stays for
// a restart's reconcile).
if entries, rerr := os.ReadDir(stage); rerr == nil {
for _, en := range entries {
@@ -385,31 +842,72 @@ func (e *Engineer) publishSite(ctx context.Context, r stepRow, progress func(wir
}
}
}
- url, _ := siteURL(out, app)
+ url, _ := siteURL(out, t.App)
if url != "" {
- site.record(siteRecord{App: app, Task: r.TaskID, URL: url, Owned: owned})
+ os.WriteFile(filepath.Join(filepath.Dir(stage), "site-url"), []byte(url), 0o600)
}
if err != nil {
- e.log("site deploy", err)
- done := e.siteDone(rep, app, version, ex, url, false)
+ e.log("site deploy", errors.New("carlos deploy failed"))
+ done := e.siteDone(rep, t.App, version, ex, url, false)
done.Reason = "publish_failed"
+ return done, false
+ }
+ served := url != "" && e.markerServed(ctx, siteAt{site, url}, t.App, siteMarker, mark)
+ return e.siteDone(rep, t.App, version, ex, url, served), true
+}
+
+// siteReconcile settles an attempt that restarted after it may have
+// changed CARLOS: nothing is rebuilt, sent or minted again. The marker
+// over the recorded URL decides published or unconfirmed; a mint that had
+// not stored its key stays lost. A mint attempt that restarted before its
+// deploy ends failed: nothing of the site was sent.
+func (e *Engineer) siteReconcile(ctx context.Context, rep wire.StepReport, r stepRow, t siteTarget, version, stage string) wire.StepReport {
+ site := e.Site
+ _, held := site.key(t)
+ if r.Phase == phaseSiteMinting && t.Mode == wire.SiteMint {
+ rep.State, rep.Reason, rep.Termination = wire.StepFailed, reasonPublishMintFailed, true
+ return rep
+ }
+ var mark previewMark
+ raw, err := os.ReadFile(filepath.Join(stage, siteMarker))
+ if err != nil || json.Unmarshal(raw, &mark) != nil {
+ done := e.siteDone(rep, t.App, version, previewExport{}, "", false)
+ done.Publish.DeployHeld = held
return done
}
- served := url != "" && e.markerServed(ctx, site, app, siteMarker, mark)
- if served && !owned {
- // Verified: the name is this runner's from now on.
- site.record(siteRecord{App: app, Task: r.TaskID, URL: url, Owned: true})
+ url := ""
+ if b, err := os.ReadFile(filepath.Join(filepath.Dir(stage), "site-url")); err == nil {
+ if u, ok := siteURL(string(b), t.App); ok {
+ url = u
+ }
+ }
+ served := url != "" && e.markerServed(context.WithoutCancel(ctx), siteAt{site, url}, t.App, siteMarker, mark)
+ done := e.siteDone(rep, t.App, version, previewExport{Digest: mark.Digest}, url, served)
+ done.Publish.DeployHeld = held
+ return done
+}
+
+// siteAt is the site host with the marker fetched from the URL this
+// attempt's deploy printed (the URL seam first, for the tests).
+type siteAt struct {
+ *SiteOptions
+ url string
+}
+
+func (s siteAt) Origin(app string) string {
+ if s.SiteOptions.URL != nil {
+ return s.SiteOptions.URL(app)
}
- return e.siteDone(rep, app, version, ex, url, served)
+ return strings.TrimSuffix(s.url, "/")
}
-// confirmPublish is the instance's decision right before the deploy, for
-// this export's digest. The built report travels on the outbox: a refusal
-// for that alone is asked again, briefly.
-func (e *Engineer) confirmPublish(ctx context.Context, r stepRow, digest string) error {
+// confirmSite is the instance's decision right before a mint or a deploy,
+// for this export's digest and destination. The built report travels on
+// the outbox: a refusal for that alone is asked again, briefly.
+func (e *Engineer) confirmSite(ctx context.Context, check func(context.Context, string, int64, string, string) error, r stepRow, digest, destination string) error {
var err error
for i := 0; i < 10; i++ {
- if err = e.ConfirmPublish(ctx, r.StepID, r.Attempt, digest); !errors.Is(err, ErrPublishNotBuilt) {
+ if err = check(ctx, r.StepID, r.Attempt, digest, destination); !errors.Is(err, ErrPublishNotBuilt) {
return err
}
select {
diff --git a/internal/runner/thin/site_test.go b/internal/runner/thin/site_test.go
index ca032526..7f376bf2 100644
--- a/internal/runner/thin/site_test.go
+++ b/internal/runner/thin/site_test.go
@@ -1,9 +1,12 @@
package thin
import (
+ "bytes"
"context"
"encoding/json"
"errors"
+ "io/fs"
+ "log/slog"
"net/http"
"net/http/httptest"
"os"
@@ -17,22 +20,39 @@ import (
"amadan.net/oficina/equipo/internal/wire"
)
+// The deploy key the fake carlos mints: assembled so the repository's own
+// scan does not read it as a credential.
+var fakeDeployToken = strings.Join([]string{"cst", "Qm9vZ3lXb29naWU", "x7Lp2Rk9"}, "_")
+
// fakeCarlosScript writes a carlos that records each run (its argv, one
-// argument per line, its working directory and its environment) and
-// serves the folder it was given, printing the deploy's live line. It
-// is a real program the runner executes, as Paul's own carlos is.
-// "apps list" prints the file apps beside it (an account with no apps
-// until a test writes one).
+// argument per line, its working directory and its environment) and acts
+// as the real one does for the five templates: accounts list prints the
+// file accounts beside it; apps list the file apps; services create
+// prints its minted line and one CARLOS_SERVICE_TOKEN line (or fails when
+// a file mintfail is there); deploy serves the folder it was given and
+// prints the live line (or fails when a file fail is there).
func fakeCarlosScript(t *testing.T, dir, live string) (bin, calls, served string) {
t.Helper()
bin, calls, served = filepath.Join(dir, "carlos"), filepath.Join(dir, "calls"), filepath.Join(dir, "served")
- apps := filepath.Join(dir, "apps")
- if err := os.WriteFile(apps, []byte("using https://console.carloku.com as paul@keymail.dev\n"+listHeader), 0o644); err != nil {
+ apps, accounts := filepath.Join(dir, "apps"), filepath.Join(dir, "accounts")
+ if err := os.WriteFile(apps, []byte("using https://console.carloku.com as paul@keymail.dev\nno apps in this account\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(accounts, []byte("NAME SQID ROLE\npaulca kmnpq owner\noficina bcdfg owner\nshared hjkmn member\n"), 0o644); err != nil {
t.Fatal(err)
}
script := "#!/bin/sh\n" +
"{ echo CALL; for a in \"$@\"; do printf 'ARG %s\\n' \"$a\"; done; printf 'PWD %s\\n' \"$(pwd)\"; env | sort | sed 's/^/ENV /'; } >> '" + calls + "'\n" +
+ "if [ \"$1\" = accounts ]; then cat '" + accounts + "'; exit 0; fi\n" +
"if [ \"$1\" = apps ]; then cat '" + apps + "'; exit 0; fi\n" +
+ "if [ \"$1\" = services ]; then\n" +
+ " if [ -e '" + filepath.Join(dir, "mintfail") + "' ]; then echo 'services create: unexpected response (status 502)'; exit 1; fi\n" +
+ " for last in \"$@\"; do :; done\n" +
+ " echo 'using https://console.carloku.com as paul@keymail.dev'\n" +
+ " printf 'minted service:%s/%s (role deploy, app %s, rungs edge)\\n\\n' \"${10}\" \"$last\" \"$6\"\n" +
+ " printf ' CARLOS_SERVICE_TOKEN=%s\\n\\n' '" + fakeDeployToken + "'\n" +
+ " exit 0\n" +
+ "fi\n" +
"if [ -e '" + filepath.Join(dir, "fail") + "' ]; then echo 'deploy: upload failed'; exit 1; fi\n" +
"for last in \"$@\"; do :; done\n" +
"rm -rf '" + served + "' && cp -R \"$last\" '" + served + "'\n" +
@@ -76,22 +96,58 @@ func carlosRuns(t *testing.T, calls string) []carlosRun {
return out
}
+func (r carlosRun) envOf(key string) (string, bool) {
+ for _, kv := range r.env {
+ if v, ok := strings.CutPrefix(kv, key+"="); ok {
+ return v, true
+ }
+ }
+ return "", false
+}
+
+func verbsOf(runs []carlosRun) []string {
+ var out []string
+ for _, r := range runs {
+ out = append(out, strings.Join(r.args[:2], " "))
+ }
+ return out
+}
+
// siteRig is a remote whose default branch holds the merged commit of a
-// website task (and a task branch beside it), an Engineer paired with
-// Carloku sites through the fake carlos, and a marker origin that serves
-// what carlos was last given.
+// website task (and a task branch beside it), an Engineer with CARLOS
+// sites through the fake carlos and the person's login, and a marker
+// origin that serves what carlos was last given.
type siteRig struct {
e *Engineer
r stepRow
merged string
unmerged string
+ bin string
calls string
apps string
creds string
planted string
+ logs *bytes.Buffer
confirms []string
}
+const (
+ rigConsole = "console.carloku.com"
+ rigSqid = "kmnpq"
+ rigName = "paulca"
+ rigApp = "site-sample"
+ rigKeyName = "eq-sample-ab12"
+)
+
+// target is a dispatch for the rig's place in mode.
+func rigTarget(mode string) *wire.PublishDispatch {
+ d := &wire.PublishDispatch{App: rigApp, Into: "main", Console: rigConsole, Account: rigSqid, AccountName: rigName, Place: "pl_1", PlaceRevision: 1, BindingRevision: 1, Destination: wire.SiteDestination(rigConsole, rigSqid, rigName, rigApp), Mode: mode}
+ if mode != wire.SitePublish {
+ d.DeployName = rigKeyName
+ }
+ return d
+}
+
func newSiteRig(t *testing.T, files map[string]string) *siteRig {
t.Helper()
root := t.TempDir()
@@ -127,7 +183,7 @@ func newSiteRig(t *testing.T, files map[string]string) *siteRig {
os.WriteFile(filepath.Join(root, ".carlos", "config"), []byte(planted), 0o600)
os.WriteFile(filepath.Join(root, "state", ".carlos", "config"), []byte(planted), 0o600)
creds := filepath.Join(root, "home", ".carlos", "credentials")
- os.WriteFile(creds, []byte(`{"version":1}`), 0o600)
+ os.WriteFile(creds, []byte(`{"version":1,"credentials":[{"console":"https://console.carloku.com","address":"p@x","token":"login-secret","expires_at":"2999-01-01T00:00:00Z"}]}`), 0o600)
s, err := OpenState(context.Background(), filepath.Join(root, "state"))
if err != nil {
t.Fatal(err)
@@ -142,17 +198,22 @@ func newSiteRig(t *testing.T, files map[string]string) *siteRig {
http.ServeFile(w, r, filepath.Join(served, siteMarker))
}))
t.Cleanup(origin.Close)
- rig := &siteRig{merged: merged, unmerged: unmerged, calls: calls, apps: filepath.Join(root, "bin", "apps"), creds: creds, planted: planted}
+ rig := &siteRig{merged: merged, unmerged: unmerged, bin: bin, calls: calls, apps: filepath.Join(root, "bin", "apps"), creds: creds, planted: planted, logs: &bytes.Buffer{}}
f := &hubForge{dir: remote}
- e := &Engineer{Clones: &Clones{Root: filepath.Join(root, "work"), Git: "/usr/bin/git", Forge: f}, Forge: f, Owners: []string{"p@x"}, Host: "test",
- Site: &SiteOptions{Carlos: bin, Credentials: creds, State: filepath.Join(root, "state", "site"), URL: func(string) string { return origin.URL }},
- ConfirmPublish: func(_ context.Context, step string, attempt int64, digest string) error {
- rig.confirms = append(rig.confirms, step+"/"+itoa(attempt)+"/"+digest)
+ check := func(purpose string) func(context.Context, string, int64, string, string) error {
+ return func(_ context.Context, step string, attempt int64, digest, destination string) error {
+ rig.confirms = append(rig.confirms, purpose+":"+step+"/"+itoa(attempt)+"/"+digest+"/"+destination)
return nil
- }}
+ }
+ }
+ e := &Engineer{Clones: &Clones{Root: filepath.Join(root, "work"), Git: "/usr/bin/git", Forge: f}, Forge: f, Owners: []string{"p@x"}, Host: "test",
+ Site: &SiteOptions{Carlos: bin, Credentials: creds, State: filepath.Join(root, "state", "site"), URL: func(string) string { return origin.URL }},
+ ConfirmPublish: check("publish"), ConfirmMint: check("mint")}
e.O.Runner.GitPath, e.O.Runner.WorkspaceRoot, e.O.Runner.StateDir, e.O.State = "/usr/bin/git", filepath.Join(root, "work"), filepath.Join(root, "state"), s
+ e.O.Runner.Executable = previewScannerFixture(t)
+ e.O.Logger = slog.New(slog.NewTextHandler(rig.logs, &slog.HandlerOptions{Level: slog.LevelDebug}))
rig.e = e
- rig.r = stepRow{DispatchCommand: wire.DispatchCommand{Person: "p@x", TaskID: "tk1", StepID: "s_pub1", Attempt: 1, Specialist: wire.SpecialistPublish, Repo: "amadan.net/oficina/sample", Branch: "equipo/tk1-quick-site", Title: "Quick site", CandidateSHA: merged, Publish: &wire.PublishDispatch{App: "site-sample", Into: "main"}}}
+ rig.r = stepRow{DispatchCommand: wire.DispatchCommand{Person: "p@x", TaskID: "tk1", StepID: "s_pub1", Attempt: 1, Specialist: wire.SpecialistPublish, Repo: "amadan.net/paulca/sample", Branch: "equipo/tk1-quick-site", Title: "Quick site", CandidateSHA: merged, Publish: rigTarget(wire.SiteSetup)}}
if err := s.AcceptDispatch(context.Background(), "d1", rig.r.DispatchCommand); err != nil {
t.Fatal(err)
}
@@ -160,23 +221,62 @@ func newSiteRig(t *testing.T, files map[string]string) *siteRig {
return rig
}
+// step is the rig's step in mode with id.
+func (rig *siteRig) step(id, mode string) stepRow {
+ r := rig.r
+ r.StepID, r.Publish = id, rigTarget(mode)
+ return r
+}
+
+// noSecretOutsideKeys: the deploy key's secret is only in its key file:
+// never in a report, the logs, argv, or any other file of the state.
+func (rig *siteRig) noSecretOutsideKeys(t *testing.T, reports ...wire.StepReport) {
+ t.Helper()
+ for _, rep := range reports {
+ raw, _ := json.Marshal(rep)
+ if strings.Contains(string(raw), fakeDeployToken) {
+ t.Fatalf("the secret is in a report: %s", raw)
+ }
+ }
+ if strings.Contains(rig.logs.String(), fakeDeployToken) || strings.Contains(rig.logs.String(), "login-secret") {
+ t.Fatalf("the secret is in the logs: %s", rig.logs)
+ }
+ for _, run := range carlosRuns(t, rig.calls) {
+ if strings.Contains(strings.Join(run.args, " "), fakeDeployToken) {
+ t.Fatalf("the secret is in argv %q", run.args)
+ }
+ }
+ keys := filepath.Join(rig.e.Site.State, "keys")
+ filepath.WalkDir(rig.e.O.Runner.StateDir, func(p string, d fs.DirEntry, err error) error {
+ if err != nil || d.IsDir() || strings.HasPrefix(p, keys+string(filepath.Separator)) {
+ return nil
+ }
+ if raw, err := os.ReadFile(p); err == nil && bytes.Contains(raw, []byte(fakeDeployToken)) {
+ t.Fatalf("the secret is in %s", p)
+ }
+ return nil
+ })
+}
+
var quickSite = map[string]string{
"release/preview.json": `{"output": "site"}`,
"site/index.html": "<h1>Quick site</h1>\n",
"site/style.css": "body{margin:0}\n",
+ "site/_headers": "/*\n Cache-Control: max-age=60\n",
"src/kept-out.txt": "not published\n",
}
-// TestSitePublish: a publish step exports the merged commit's site from
-// git objects, reports it built, asks the instance once for that digest,
-// then, for a name this runner never deployed, reads the account's apps
-// (the name must be free), and deploys: two commands, each with fixed
-// flags and the console pinned, from an empty private directory whose
-// environment holds only HOME, PATH, the person's signed-in credential
-// file, an empty configuration of the runner's own and no update check;
-// the marker over the printed URL confirms it. A second publish of the
-// same app deploys without asking again.
-func TestSitePublish(t *testing.T) {
+// TestSiteSetupThenPublish: a setup exports the merged commit's site from
+// git objects, scans it, reports it built; for a name this runner has no
+// record of, reads the account's apps with the person's login (the name
+// must be free); deploys with the login behind its publish check; then
+// behind its mint check mints the app's edge-only deploy key, stored 0600
+// and reported only as held. Every command has fixed flags naming the
+// place's sqid and console, from an empty private directory whose
+// environment holds only what it needs. The next publish deploys with the
+// key alone: the login is not in its environment. The project's own
+// _headers is published; Equipo adds none. The secret is nowhere else.
+func TestSiteSetupThenPublish(t *testing.T) {
rig := newSiteRig(t, quickSite)
var built *wire.PublishResult
rep := rig.e.Exec(context.Background(), rig.r, func(p wire.StepReport) {
@@ -184,206 +284,437 @@ func TestSitePublish(t *testing.T) {
built = p.Publish
}
})
- if built == nil || built.Phase != wire.PublishBuilt || built.Files != 2 || len(built.Digest) != 64 {
+ if built == nil || built.Phase != wire.PublishBuilt || built.Files != 3 || len(built.Digest) != 64 {
t.Fatalf("built %+v", built)
}
- if rep.State != wire.StepDone || rep.Reason != "" || rep.Publish == nil || rep.Publish.Outcome != wire.PublishPublished || rep.Publish.App != "site-sample" || rep.Publish.Digest != built.Digest || rep.Publish.URL != "https://site-sample.bds.oncarlos.com/" {
+ if rep.State != wire.StepDone || rep.Reason != "" || rep.Publish == nil || rep.Publish.Outcome != wire.PublishPublished || rep.Publish.App != rigApp || rep.Publish.Digest != built.Digest || rep.Publish.URL != "https://site-sample.bds.oncarlos.com/" || !rep.Publish.DeployHeld {
t.Fatalf("report %+v %+v", rep, rep.Publish)
}
- if len(rig.confirms) != 1 || rig.confirms[0] != "s_pub1/1/"+built.Digest {
- t.Fatalf("publish checks %v", rig.confirms)
+ dest := wire.SiteDestination(rigConsole, rigSqid, rigName, rigApp)
+ if want := []string{"publish:s_pub1/1/" + built.Digest + "/" + dest, "mint:s_pub1/1/" + built.Digest + "/" + dest}; !slices.Equal(rig.confirms, want) {
+ t.Fatalf("checks %v\nwant %v", rig.confirms, want)
}
runs := carlosRuns(t, rig.calls)
- if len(runs) != 2 {
- t.Fatalf("carlos ran %d times", len(runs))
+ if got := verbsOf(runs); !slices.Equal(got, []string{"apps list", "deploy --kind", "services create"}) {
+ t.Fatalf("runs %v", got)
}
- if want := []string{"apps", "list", "--account", "oficina", "--console", "https://console.carloku.com"}; !slices.Equal(runs[0].args, want) {
- t.Fatalf("list argv %q\nwant %q", runs[0].args, want)
+ origin := "https://" + rigConsole
+ if want := []string{"apps", "list", "--account-id", rigSqid, "--console", origin}; !slices.Equal(runs[0].args, want) {
+ t.Fatalf("list argv %q", runs[0].args)
}
- run := runs[1]
- stage := run.args[len(run.args)-1]
+ stage := runs[1].args[len(runs[1].args)-1]
version := "s-" + rig.merged[:12] + "-pub1-1"
- want := []string{"deploy", "--kind", "static", "--account", "oficina", "--console", "https://console.carloku.com", "--app", "site-sample", "--channel", "edge", "--timeout", "5m", "--version", version, "--no-prompt", stage}
- if !slices.Equal(run.args, want) || rep.Publish.Version != version {
- t.Fatalf("argv %q\nwant %q", run.args, want)
+ if want := []string{"deploy", "--kind", "static", "--account-id", rigSqid, "--console", origin, "--app", rigApp, "--channel", "edge", "--timeout", "5m", "--version", version, "--no-prompt", stage}; !slices.Equal(runs[1].args, want) || rep.Publish.Version != version {
+ t.Fatalf("deploy argv %q", runs[1].args)
}
- for _, r := range runs {
- config := ""
- for _, kv := range r.env {
- if v, ok := strings.CutPrefix(kv, "CARLOS_CONFIG="); ok {
- config = v
+ if want := []string{"services", "create", "--role", "deploy", "--app", rigApp, "--rungs", "edge", "--account-id", rigSqid, "--console", origin, rigKeyName}; !slices.Equal(runs[2].args, want) {
+ t.Fatalf("mint argv %q", runs[2].args)
+ }
+ for _, run := range runs {
+ for _, kv := range run.env {
+ k, _, _ := strings.Cut(kv, "=")
+ if !slices.Contains([]string{"HOME", "PATH", "CARLOS_CREDENTIALS", "CARLOS_CONFIG", "CARLOS_NO_UPDATE_CHECK", "PWD", "SHLVL", "_"}, k) {
+ t.Fatalf("a login run saw %s", kv)
}
}
+ if v, _ := run.envOf("CARLOS_CREDENTIALS"); v != rig.creds {
+ t.Fatalf("login run credentials %q", v)
+ }
+ config, _ := run.envOf("CARLOS_CONFIG")
raw, err := os.ReadFile(config)
- if !strings.HasPrefix(config, rig.e.Site.State) || err != nil || strings.TrimSpace(string(raw)) != "{}" || !slices.Contains(r.env, "CARLOS_NO_UPDATE_CHECK=1") {
+ if !strings.HasPrefix(config, rig.e.Site.State) || err != nil || strings.TrimSpace(string(raw)) != "{}" {
t.Fatalf("configuration %q: %q %v", config, raw, err)
}
- if strings.Contains(strings.Join(r.args, " "), "evil") || strings.Contains(strings.Join(r.args, " "), "elsewhere") {
- t.Fatalf("the planted configuration reached argv %q", r.args)
- }
- }
- if !filepath.IsAbs(stage) || !strings.HasPrefix(stage, rig.e.root()) {
- t.Fatalf("export folder %s", stage)
- }
- for _, kv := range run.env {
- k, _, _ := strings.Cut(kv, "=")
- if !slices.Contains([]string{"HOME", "PATH", "CARLOS_CREDENTIALS", "CARLOS_CONFIG", "CARLOS_NO_UPDATE_CHECK", "PWD", "SHLVL", "_"}, k) {
- t.Fatalf("carlos saw %s", kv)
+ if home, _ := run.envOf("HOME"); home != run.pwd || !strings.HasPrefix(run.pwd, rig.e.Site.State) {
+ t.Fatalf("ran from %s with HOME %s", run.pwd, home)
}
- }
- if !slices.Contains(run.env, "CARLOS_CREDENTIALS="+rig.creds) || !slices.Contains(run.env, "PATH=/usr/bin:/bin") {
- t.Fatalf("environment %v", run.env)
- }
- home := ""
- for _, kv := range run.env {
- if v, ok := strings.CutPrefix(kv, "HOME="); ok {
- home = v
+ if strings.Contains(strings.Join(run.args, " "), "evil") || strings.Contains(strings.Join(run.args, " "), "elsewhere") {
+ t.Fatalf("the planted configuration reached argv %q", run.args)
}
}
- if home != run.pwd || !strings.HasPrefix(run.pwd, rig.e.Site.State) {
- t.Fatalf("ran from %s with HOME %s", run.pwd, home)
- }
- if entries, _ := os.ReadDir(run.pwd); len(entries) != 0 {
- t.Fatalf("carlos ran from a folder holding %v", entries)
- }
served := map[string]bool{}
entries, _ := os.ReadDir(filepath.Join(filepath.Dir(rig.calls), "served"))
for _, en := range entries {
served[en.Name()] = true
}
- if len(served) != 3 || !served["index.html"] || !served["style.css"] || !served[siteMarker] {
+ if len(served) != 4 || !served["index.html"] || !served["style.css"] || !served["_headers"] || !served[siteMarker] {
t.Fatalf("published %v", served)
}
- // The next publish of this app: the name is this runner's; no list.
- next := rig.r
- next.StepID = "s_pub2"
- if rep := rig.e.Exec(context.Background(), next, func(wire.StepReport) {}); rep.State != wire.StepDone || rep.Publish.Outcome != wire.PublishPublished {
- t.Fatalf("second publish %+v", rep.Publish)
+ if raw, _ := os.ReadFile(filepath.Join(filepath.Dir(rig.calls), "served", "_headers")); string(raw) != quickSite["site/_headers"] {
+ t.Fatalf("the project's _headers changed: %q", raw)
+ }
+ keyFile := filepath.Join(rig.e.Site.State, "keys", rigConsole, rigSqid, rigApp+".json")
+ info, err := os.Stat(keyFile)
+ if err != nil || info.Mode().Perm() != 0o600 {
+ t.Fatalf("key file %v %v", info, err)
+ }
+ if dir, _ := os.Stat(filepath.Dir(keyFile)); dir.Mode().Perm() != 0o700 {
+ t.Fatalf("key folder mode %v", dir.Mode())
+ }
+ reach := rig.e.Site.Reach(context.Background())
+ if reach == nil || len(reach.Deploys) != 1 || reach.Deploys[0].Name != rigKeyName || reach.Deploys[0].Lost || len(reach.Deploys[0].Fingerprint) != 16 || reach.Deploys[0].App != rigApp {
+ t.Fatalf("reach %+v", reach)
+ }
+ if len(reach.Logins) != 1 || reach.Logins[0].Console != rigConsole || !slices.Equal(reach.Logins[0].Accounts, []wire.ReachAccount{{Name: "paulca", Sqid: "kmnpq"}, {Name: "oficina", Sqid: "bcdfg"}}) {
+ t.Fatalf("logins %+v", reach.Logins)
+ }
+ if err := wire.ValidCapabilities(wire.Capabilities{Reach: reach}); err != nil {
+ t.Fatalf("reach invalid: %v", err)
+ }
+ // The next publish: the key alone.
+ rig.confirms = nil
+ next := rig.e.Exec(context.Background(), rig.step("s_pub2", wire.SitePublish), func(wire.StepReport) {})
+ if next.State != wire.StepDone || next.Publish.Outcome != wire.PublishPublished || !next.Publish.DeployHeld {
+ t.Fatalf("second publish %+v %+v", next, next.Publish)
+ }
+ runs = carlosRuns(t, rig.calls)
+ last := runs[len(runs)-1]
+ if got := verbsOf(runs); !slices.Equal(got, []string{"apps list", "deploy --kind", "services create", "accounts list", "deploy --kind"}) {
+ t.Fatalf("runs %v", got)
+ }
+ if tok, _ := last.envOf("CARLOS_SERVICE_TOKEN"); tok != fakeDeployToken {
+ t.Fatal("the publish did not use the deploy key")
+ }
+ if c, _ := last.envOf("CARLOS_CONSOLE"); c != origin {
+ t.Fatalf("console %q", c)
+ }
+ if v, _ := last.envOf("CARLOS_CREDENTIALS"); v == rig.creds || !strings.HasPrefix(v, rig.e.Site.State) {
+ t.Fatalf("the login reached a key publish: %q", v)
+ } else if _, err := os.Stat(v); err == nil {
+ t.Fatalf("the absent credentials file exists: %s", v)
}
- if runs := carlosRuns(t, rig.calls); len(runs) != 3 || runs[2].args[0] != "deploy" {
- t.Fatalf("second publish ran %d", len(runs))
+ if len(rig.confirms) != 1 || !strings.HasPrefix(rig.confirms[0], "publish:s_pub2/") {
+ t.Fatalf("checks %v", rig.confirms)
}
+ rig.noSecretOutsideKeys(t, rep, next)
}
-// TestSitePublishNameTaken: before the first deploy of a name, an app of
-// that name already in the account (live, kept or in the Trash), or a
-// list that cannot be read, refuses the publish: nothing is deployed.
-func TestSitePublishNameTaken(t *testing.T) {
+// TestSiteSetupNameTaken: before a setup's deploy, an app of that name
+// already in the account (live, kept, in the Trash, with or without the
+// header and region), or a list that cannot be read strictly, refuses the
+// publish before its check: nothing is deployed or minted.
+func TestSiteSetupNameTaken(t *testing.T) {
+ using := "using https://console.carloku.com as p@x\n"
for name, list := range map[string]string{
- "live": listHeader + "site-sample live eu-west (expires in 3 days)\n",
- "kept": listHeader + "site-sample live eu-west\n",
- "trashed": listHeader + "site-sample trashed eu-west\n",
+ "live": using + listHeader + "site-sample live eu-west expires in 3 days\n",
+ "no header": using + "site-sample live\n",
+ "trashed": using + listHeader + "site-sample trashed eu-west\n",
"unreadable": "something went wrong\n",
+ "no using": "no apps in this account\n",
+ "odd line": using + "other-app live\nwhat is this\n",
} {
rig := newSiteRig(t, quickSite)
os.WriteFile(rig.apps, []byte(list), 0o644)
rep := rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {})
runs := carlosRuns(t, rig.calls)
- if rep.State != wire.StepFailed || rep.Reason != "publish_app_taken" || len(runs) != 1 || runs[0].args[0] != "apps" || len(rig.confirms) != 1 {
- t.Fatalf("%s: %+v, %d runs", name, rep, len(runs))
+ if rep.State != wire.StepFailed || rep.Reason != "publish_app_taken" || len(runs) != 1 || runs[0].args[0] != "apps" || len(rig.confirms) != 0 {
+ t.Fatalf("%s: %+v, runs %v, checks %v", name, rep, verbsOf(runs), rig.confirms)
}
}
}
-// TestSitePublishFence: the app, the version and the folder are checked
-// before anything runs. A hostile app (a flag, a second argument, a path,
-// another account, upper case, too long) is refused; so is a merged
-// commit that is not on the default branch, a missing target, and an
-// instance that refuses the publish check. carlos never runs for any.
-func TestSitePublishFence(t *testing.T) {
- rig := newSiteRig(t, quickSite)
- run := func(r stepRow) wire.StepReport {
- t.Helper()
- rep := rig.e.Exec(context.Background(), r, func(wire.StepReport) {})
- if n := len(carlosRuns(t, rig.calls)); n != 0 {
- t.Fatalf("carlos ran %d times for %+v", n, r.Publish)
+// TestSiteListed: the strict list parser.
+func TestSiteListed(t *testing.T) {
+ using := "using https://console.carloku.com as p@x\n"
+ for name, c := range map[string]struct {
+ out string
+ present, ok bool
+ }{
+ "empty account": {using + "no apps in this account\n", false, true},
+ "others, header": {using + listHeader + "site-other live\n", false, true},
+ "others, none": {using + "site-other live\nsite-third trashed\n", false, true},
+ "listed, region": {using + listHeader + "site-sample live eu-west expires in 2 days\n", true, true},
+ "listed, plain": {"\x1b[2m" + using + "\x1b[0msite-sample live\n", true, true},
+ "header only": {using + listHeader, false, false},
+ "nothing": {"", false, false},
+ "no using": {"site-other live\n", false, false},
+ "bad state": {using + "site-other gone\n", false, false},
+ "empty then apps": {using + "no apps in this account\nsite-sample live\n", false, false},
+ } {
+ present, ok := siteListed(c.out, "site-sample")
+ if present != c.present || ok != c.ok {
+ t.Errorf("%s: present %t ok %t", name, present, ok)
}
- return rep
}
- for _, app := range []string{"--help", "site-x --account other", "site-x\n--account=other", "-site-x", "site-../x", "site-x/../../y", "SITE-X", "site-", "x", "site-" + strings.Repeat("a", 28), "site-x;carlos apps delete", "tmp-x", "site-ñ"} {
- r := rig.r
- r.Publish = &wire.PublishDispatch{App: app, Into: "main"}
- if rep := run(r); rep.State != wire.StepFailed || rep.Reason != "policy_rejected" || len(rig.confirms) != 0 {
- t.Fatalf("app %q: %+v", app, rep)
- }
+}
+
+// TestSiteMintRecovery: a mint runs only with this runner's own record of
+// creating the app at exactly this place: behind its mint check, it mints
+// with the login, then deploys with the new key behind its publish check,
+// never with the login. With no record it never adopts: an app it did not
+// make refuses publish_app_unproven, a missing app publish_app_missing,
+// an unreadable list fails; none mints or deploys. A record for another
+// account proves nothing here.
+func TestSiteMintRecovery(t *testing.T) {
+ rig := newSiteRig(t, quickSite)
+ if err := rig.e.Site.created(siteTarget{Console: rigConsole, Sqid: rigSqid, App: rigApp}, "tk1"); err != nil {
+ t.Fatal(err)
+ }
+ rep := rig.e.Exec(context.Background(), rig.step("s_pub1", wire.SiteMint), func(wire.StepReport) {})
+ if rep.State != wire.StepDone || rep.Publish.Outcome != wire.PublishPublished || !rep.Publish.DeployHeld {
+ t.Fatalf("mint %+v %+v", rep, rep.Publish)
}
- for _, into := range []string{"", "--all", "main..x", "-main"} {
- r := rig.r
- r.Publish = &wire.PublishDispatch{App: "site-sample", Into: into}
- if rep := run(r); rep.State != wire.StepFailed || rep.Reason != "policy_rejected" {
- t.Fatalf("into %q: %+v", into, rep)
+ runs := carlosRuns(t, rig.calls)
+ if got := verbsOf(runs); !slices.Equal(got, []string{"services create", "deploy --kind"}) {
+ t.Fatalf("runs %v", got)
+ }
+ if v, _ := runs[0].envOf("CARLOS_CREDENTIALS"); v != rig.creds {
+ t.Fatal("the mint did not use the login")
+ }
+ if tok, _ := runs[1].envOf("CARLOS_SERVICE_TOKEN"); tok != fakeDeployToken {
+ t.Fatal("the deploy after a mint did not use the new key")
+ }
+ if v, _ := runs[1].envOf("CARLOS_CREDENTIALS"); v == rig.creds {
+ t.Fatal("the login deployed a created app again")
+ }
+ if len(rig.confirms) != 2 || !strings.HasPrefix(rig.confirms[0], "mint:") || !strings.HasPrefix(rig.confirms[1], "publish:") {
+ t.Fatalf("checks %v", rig.confirms)
+ }
+ rig.noSecretOutsideKeys(t, rep)
+
+ using := "using https://console.carloku.com as p@x\n"
+ for name, c := range map[string]struct{ list, reason string }{
+ "not ours": {using + "site-sample live\n", reasonPublishAppUnproven},
+ "absent": {using + "no apps in this account\n", reasonPublishAppMissing},
+ "unreadable": {"oops\n", "publish_failed"},
+ } {
+ rig := newSiteRig(t, quickSite)
+ // Another account's record is no proof here.
+ rig.e.Site.created(siteTarget{Console: rigConsole, Sqid: "bcdfg", App: rigApp}, "tk1")
+ os.WriteFile(rig.apps, []byte(c.list), 0o644)
+ rep := rig.e.Exec(context.Background(), rig.step("s_pub1", wire.SiteMint), func(wire.StepReport) {})
+ if rep.State != wire.StepFailed || rep.Reason != c.reason || len(rig.confirms) != 0 {
+ t.Fatalf("%s: %+v checks %v", name, rep, rig.confirms)
+ }
+ if got := verbsOf(carlosRuns(t, rig.calls)); !slices.Equal(got, []string{"apps list"}) {
+ t.Fatalf("%s: runs %v", name, got)
}
}
- r := rig.r
- r.Publish = nil
- if rep := run(r); rep.State != wire.StepFailed || rep.Reason != "policy_rejected" {
- t.Fatalf("no target: %+v", rep)
+}
+
+// TestSiteMintLost: a mint whose answer fails or cannot be read leaves no
+// key, and the runner says the name is lost (it may be live on CARLOS)
+// until it holds a key; the setup's site is still published. A refused
+// mint check mints nothing and loses nothing.
+func TestSiteMintLost(t *testing.T) {
+ rig := newSiteRig(t, quickSite)
+ os.WriteFile(filepath.Join(filepath.Dir(rig.calls), "mintfail"), nil, 0o644)
+ rep := rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {})
+ if rep.State != wire.StepDone || rep.Publish.Outcome != wire.PublishPublished || rep.Publish.DeployHeld {
+ t.Fatalf("lost mint %+v %+v", rep, rep.Publish)
+ }
+ reach := rig.e.Site.Reach(context.Background())
+ if len(reach.Deploys) != 1 || !reach.Deploys[0].Lost || reach.Deploys[0].Name != rigKeyName || reach.Deploys[0].Fingerprint != "" {
+ t.Fatalf("reach %+v", reach.Deploys)
+ }
+ if err := wire.ValidCapabilities(wire.Capabilities{Reach: reach}); err != nil {
+ t.Fatalf("reach invalid: %v", err)
+ }
+ // A mint step recovers it: the key held, the lost name gone.
+ os.Remove(filepath.Join(filepath.Dir(rig.calls), "mintfail"))
+ again := rig.e.Exec(context.Background(), rig.step("s_pub2", wire.SiteMint), func(wire.StepReport) {})
+ if again.State != wire.StepDone || !again.Publish.DeployHeld {
+ t.Fatalf("recovery %+v %+v", again, again.Publish)
+ }
+ if reach := rig.e.Site.Reach(context.Background()); len(reach.Deploys) != 1 || reach.Deploys[0].Lost {
+ t.Fatalf("after recovery %+v", reach.Deploys)
}
- r = rig.r
- r.CandidateSHA = rig.unmerged
- if rep := run(r); rep.State != wire.StepFailed || rep.Reason != "publish_not_merged" {
- t.Fatalf("a commit off the default branch: %+v", rep)
+
+ rig = newSiteRig(t, quickSite)
+ rig.e.ConfirmMint = func(context.Context, string, int64, string, string) error { return ErrWithdrawn }
+ rep = rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {})
+ if rep.State != wire.StepDone || rep.Publish.DeployHeld {
+ t.Fatalf("refused mint check %+v", rep.Publish)
+ }
+ if got := verbsOf(carlosRuns(t, rig.calls)); !slices.Equal(got, []string{"apps list", "deploy --kind"}) {
+ t.Fatalf("runs %v", got)
+ }
+ if reach := rig.e.Site.Reach(context.Background()); len(reach.Deploys) != 0 {
+ t.Fatalf("a refused mint left %+v", reach.Deploys)
}
+}
+
+// TestSitePublishFence: the target, the version and the folder are checked
+// before anything runs: a destination hash that does not bind the parts,
+// a part out of shape, an unknown mode or a key name where none belongs is
+// refused; so is a merged commit that is not on the default branch, a
+// publish with no key, a key for another place, a carlos too old, a scan
+// that finds a secret or cannot run, and an instance that refuses the
+// check. carlos runs for none of them; none reports built.
+func TestSitePublishFence(t *testing.T) {
+ rig := newSiteRig(t, quickSite)
+ run := func(r stepRow, want string) {
+ t.Helper()
+ built := false
+ rep := rig.e.Exec(context.Background(), r, func(p wire.StepReport) { built = built || p.Publish != nil })
+ if n := len(carlosRuns(t, rig.calls)); n != 0 || built || rep.Reason != want || (want == "withdrawn") != (rep.State == wire.StepCancelled) {
+ t.Fatalf("%+v: %+v, %d runs, built %t; want %s", r.Publish, rep, n, built, want)
+ }
+ }
+ bad := func(f func(d *wire.PublishDispatch)) stepRow {
+ r := rig.step("s_pub1", wire.SiteSetup)
+ f(r.Publish)
+ return r
+ }
+ for name, r := range map[string]stepRow{
+ "app flag": bad(func(d *wire.PublishDispatch) { d.App = "--help" }),
+ "app arg": bad(func(d *wire.PublishDispatch) { d.App = "site-x --account other" }),
+ "app path": bad(func(d *wire.PublishDispatch) { d.App = "site-../x" }),
+ "console path": bad(func(d *wire.PublishDispatch) { d.Console = "console.carloku.com/../x" }),
+ "console scheme": bad(func(d *wire.PublishDispatch) { d.Console = "https://console.carloku.com" }),
+ "sqid": bad(func(d *wire.PublishDispatch) { d.Account = "--all" }),
+ "rehashed": bad(func(d *wire.PublishDispatch) { d.Account = "bcdfg" }),
+ "other app": bad(func(d *wire.PublishDispatch) { d.App = "site-other" }),
+ "mode": bad(func(d *wire.PublishDispatch) { d.Mode = "adopt" }),
+ "no key name": bad(func(d *wire.PublishDispatch) { d.DeployName = "" }),
+ "key name arg": bad(func(d *wire.PublishDispatch) { d.DeployName = "eq-x --role admin" }),
+ "no target": bad(func(d *wire.PublishDispatch) { *d = wire.PublishDispatch{} }),
+ "into": bad(func(d *wire.PublishDispatch) { d.Into = "-main" }),
+ } {
+ _ = name
+ run(r, "policy_rejected")
+ }
+ pub := rig.step("s_pub1", wire.SitePublish)
+ pub.Publish.DeployName = rigKeyName
+ run(pub, "policy_rejected")
+ run(rig.step("s_pub1", wire.SitePublish), reasonPublishKeyMissing)
+ off := rig.r
+ off.CandidateSHA = rig.unmerged
+ run(off, "publish_not_merged")
confirm := rig.e.ConfirmPublish
- rig.e.ConfirmPublish = func(context.Context, string, int64, string) error { return ErrWithdrawn }
- if rep := run(rig.r); rep.State != wire.StepCancelled {
- t.Fatalf("refused check: %+v", rep)
+ rig.e.ConfirmPublish = func(context.Context, string, int64, string, string) error { return ErrWithdrawn }
+ os.WriteFile(rig.apps, []byte("using x\nno apps in this account\n"), 0o644)
+ if rep := rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {}); rep.State != wire.StepCancelled || slices.Contains(verbsOf(carlosRuns(t, rig.calls)), "deploy --kind") {
+ t.Fatalf("refused check: %+v %v", rep, verbsOf(carlosRuns(t, rig.calls)))
}
rig.e.ConfirmPublish = confirm
+ os.Remove(rig.calls)
+ // A carlos older than the minimum, or one whose version is unreadable.
+ for _, v := range []string{"v0.32.2", ""} {
+ rig.e.Site.CLI = &carlosCLI{Bin: rig.bin, Read: func(context.Context, string) string { return v }}
+ run(rig.r, wire.ReasonCarlosOutdated)
+ }
+ rig.e.Site.CLI = nil
+ // No login: a setup cannot run.
+ creds := rig.e.Site.Credentials
+ rig.e.Site.Credentials = ""
+ run(rig.r, "publish_off")
+ rig.e.Site.Credentials = creds
+ // The secret scan, on the exact export.
+ files := map[string]string{"release/preview.json": `{"output": "site"}`, "site/index.html": "<p>x</p>\n",
+ "site/config.js": `const token = "` + "ghp_" + strings.Join([]string{"Vw3K", "8pRt", "a9Qz", "6LmN", "2sDx", "7bJh", "4cFv", "0uEy", "5nWi"}, "") + `"; // gitleaks:allow` + "\n",
+ "site/gitleaks.toml": "[allowlist]\nregexes = ['.*']\n"}
+ secret := newSiteRig(t, files)
+ if rep := secret.e.Exec(context.Background(), secret.r, func(wire.StepReport) {}); rep.Reason != reasonPublishSecrets || carlosRuns(t, secret.calls) != nil {
+ t.Fatalf("a secret published: %+v", rep)
+ }
+ unscanned := newSiteRig(t, quickSite)
+ unscanned.e.O.Runner.Executable = filepath.Join(t.TempDir(), "missing-runner")
+ if rep := unscanned.e.Exec(context.Background(), unscanned.r, func(wire.StepReport) {}); rep.Reason != reasonPublishScanner || carlosRuns(t, unscanned.calls) != nil {
+ t.Fatalf("published unscanned: %+v", rep)
+ }
site := rig.e.Site
rig.e.Site = nil
- if rep := run(rig.r); rep.State != wire.StepFailed || rep.Reason != "publish_off" {
- t.Fatalf("no site host: %+v", rep)
- }
+ run(rig.r, "publish_off")
rig.e.Site = site
- // A config this version cannot use, or an output carrying the marker.
- for name, files := range map[string]map[string]string{
- "bad config": {"release/preview.json": `{"output": "../x"}`, "site/index.html": "<p>x</p>\n"},
- "a planted marker": {"release/preview.json": `{"output": "site"}`, "site/index.html": "<p>x</p>\n", "site/" + siteMarker: "{}"},
- } {
- other := newSiteRig(t, files)
- if rep := other.e.Exec(context.Background(), other.r, func(wire.StepReport) {}); rep.State != wire.StepFailed || rep.Reason != "publish_config" || carlosRuns(t, other.calls) != nil {
- t.Fatalf("%s: %+v", name, rep)
+}
+
+// TestSitePublishKeyForAnotherPlace: a key is found only at its own
+// console, sqid and app: a key held for the same app in another account
+// is not this place's.
+func TestSitePublishKeyForAnotherPlace(t *testing.T) {
+ rig := newSiteRig(t, quickSite)
+ other := siteTarget{Console: rigConsole, Sqid: "bcdfg", Name: "oficina", App: rigApp, DeployName: rigKeyName}
+ p, _ := rig.e.Site.keyPath(other)
+ raw, _ := json.Marshal(deployKey{Console: rigConsole, Account: "bcdfg", App: rigApp, Name: rigKeyName, Token: fakeDeployToken, Fingerprint: "0123456789abcdef"})
+ if err := writeSecret(p, raw); err != nil {
+ t.Fatal(err)
+ }
+ rep := rig.e.Exec(context.Background(), rig.step("s_pub1", wire.SitePublish), func(wire.StepReport) {})
+ if rep.Reason != reasonPublishKeyMissing || carlosRuns(t, rig.calls) != nil {
+ t.Fatalf("another place's key used: %+v", rep)
+ }
+}
+
+// TestSitePublishRestart: an attempt that may have changed CARLOS only
+// reconciles after a restart: it never deploys or mints again; the marker
+// over the URL this attempt's deploy printed decides. A mint attempt that
+// restarted before its deploy fails, its lost name kept.
+func TestSitePublishRestart(t *testing.T) {
+ rig := newSiteRig(t, quickSite)
+ first := rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {})
+ for _, phase := range []string{phaseSitePublishing, phaseSiteMinting} {
+ again := rig.r
+ again.Phase = phase
+ rep := rig.e.Exec(context.Background(), again, func(wire.StepReport) {})
+ if rep.State != wire.StepDone || rep.Publish == nil || rep.Publish.Outcome != wire.PublishPublished || rep.Publish.Digest != first.Publish.Digest || rep.Publish.URL != "https://site-sample.bds.oncarlos.com/" || !rep.Publish.DeployHeld {
+ t.Fatalf("%s reconciled %+v", phase, rep.Publish)
}
}
+ if n := len(carlosRuns(t, rig.calls)); n != 3 {
+ t.Fatalf("carlos ran %d times", n)
+ }
+ mint := rig.step("s_pub1", wire.SiteMint)
+ mint.Phase = phaseSiteMinting
+ if rep := rig.e.Exec(context.Background(), mint, func(wire.StepReport) {}); rep.State != wire.StepFailed || rep.Reason != reasonPublishMintFailed {
+ t.Fatalf("mint restart %+v", rep)
+ }
+ if n := len(carlosRuns(t, rig.calls)); n != 3 {
+ t.Fatalf("a restart ran carlos: %d", n)
+ }
}
-// TestSiteDeployArgs: the command is built from fixed parts and three
-// checked values; nothing else can be produced, whatever it is given.
+// TestSiteDeployArgs: the templates are built from fixed parts and
+// checked values; nothing else can be produced, whatever they are given.
func TestSiteDeployArgs(t *testing.T) {
- got, err := siteDeployArgs("site-sample", "s-0123456789ab-pub1-1", "/state/steps/k/site")
- want := []string{"deploy", "--kind", "static", "--account", "oficina", "--console", "https://console.carloku.com", "--app", "site-sample", "--channel", "edge", "--timeout", "5m", "--version", "s-0123456789ab-pub1-1", "--no-prompt", "/state/steps/k/site"}
+ tg, ok := targetOf(rigTarget(wire.SiteSetup))
+ if !ok {
+ t.Fatal("rig target refused")
+ }
+ got, err := siteDeployArgs(tg, "s-0123456789ab-pub1-1", "/state/steps/k/site")
+ want := []string{"deploy", "--kind", "static", "--account-id", rigSqid, "--console", "https://console.carloku.com", "--app", rigApp, "--channel", "edge", "--timeout", "5m", "--version", "s-0123456789ab-pub1-1", "--no-prompt", "/state/steps/k/site"}
if err != nil || !slices.Equal(got, want) {
t.Fatalf("%q %v", got, err)
}
- for _, c := range [][3]string{
- {"site-x --account o", "s-0123456789ab-a-1", "/s/site"},
- {"site-sample", "--console=x", "/s/site"},
- {"site-sample", "s-0123456789ab-a-1 --x", "/s/site"},
- {"site-sample", "s-0123456789AB-a-1", "/s/site"},
- {"site-sample", "s-0123456789ab-a-1", "relative/site"},
- {"site-sample", "s-0123456789ab-a-1", "/s/../site"},
- {"site-sample", "s-0123456789ab-a-1", "/s/site\n--x"},
- {"site-sample", "s-0123456789ab-a-1", "/"},
+ for _, c := range [][2]string{
+ {"--console=x", "/s/site"},
+ {"s-0123456789ab-a-1 --x", "/s/site"},
+ {"s-0123456789AB-a-1", "/s/site"},
+ {"s-0123456789ab-a-1", "relative/site"},
+ {"s-0123456789ab-a-1", "/s/../site"},
+ {"s-0123456789ab-a-1", "/s/site\n--x"},
+ {"s-0123456789ab-a-1", "/"},
} {
- if args, err := siteDeployArgs(c[0], c[1], c[2]); err == nil {
+ if args, err := siteDeployArgs(tg, c[0], c[1]); err == nil {
t.Fatalf("built %q from %q", args, c)
}
}
+ tg.DeployName = "eq x"
+ if _, err := siteMintArgs(tg); err == nil {
+ t.Fatal("a mint built with a bad name")
+ }
+ if _, ok := mintedKey("minted service:kmnpq/eq-sample-ab12 (role deploy, app site-sample, rungs edge, beta)\n CARLOS_SERVICE_TOKEN="+fakeDeployToken+"\n", siteTarget{Sqid: rigSqid, App: rigApp, DeployName: rigKeyName}); ok {
+ t.Fatal("a key with more rungs than edge accepted")
+ }
+ if _, ok := mintedKey("minted service:kmnpq/eq-sample-ab12 (role deploy, app site-sample, rungs edge)\n CARLOS_SERVICE_TOKEN=a1234567890123456\n CARLOS_SERVICE_TOKEN=b1234567890123456\n", siteTarget{Sqid: rigSqid, App: rigApp, DeployName: rigKeyName}); ok {
+ t.Fatal("two tokens accepted")
+ }
}
-// TestProbeSite: pairing is explicit (EQUIPO_SITE_HOST=carloku), carlos is
-// found on PATH, and the signed-in credential must be this user's own
-// regular file, mode 0600, outside every directory a sandbox mounts. The
-// probe runs no carlos command at all.
+// TestProbeSite: carlos is found on PATH; the signed-in credential is used
+// only when it is this user's own regular file, mode 0600, outside every
+// directory a sandbox mounts (else sites still publish with held keys,
+// and set up none); the state may not lie inside a sandbox mount. The
+// probe runs no carlos command at all. The reach reads only the live
+// https consoles of the credential file.
func TestProbeSite(t *testing.T) {
root := t.TempDir()
bin, calls, _ := fakeCarlosScript(t, root, "https://site-x.example")
creds := filepath.Join(root, "credentials")
- os.WriteFile(creds, []byte("{}"), 0o600)
+ os.WriteFile(creds, []byte(`{"version":1,"credentials":[{"console":"https://console.carloku.com","token":"x"},{"console":"https://console.platform.tito.io/","token":"y"},{"console":"http://plain.example","token":"z"},{"console":"https://old.example","token":"w","expires_at":"2001-01-01T00:00:00Z"},{"console":"https://console.carloku.com","token":"again"}]}`), 0o600)
t.Setenv("PATH", root+":/usr/bin:/bin")
t.Setenv("CARLOS_CREDENTIALS", creds)
- c := runner.Config{SiteHost: wire.SiteHostCarloku, StateDir: filepath.Join(root, "state"), WorkspaceRoot: filepath.Join(root, "ws")}
+ c := runner.Config{StateDir: filepath.Join(root, "state"), WorkspaceRoot: filepath.Join(root, "ws")}
s := ProbeSite(c, nil)
if s == nil || s.Carlos != bin || s.Credentials != creds {
t.Fatalf("probe %+v", s)
@@ -391,129 +722,105 @@ func TestProbeSite(t *testing.T) {
if carlosRuns(t, calls) != nil {
t.Fatal("the probe ran carlos")
}
- if ProbeSite(runner.Config{StateDir: c.StateDir}, nil) != nil {
- t.Fatal("paired without being asked")
+ if got := s.loginConsoles(); !slices.Equal(got, []string{wire.FlagshipConsole, wire.TitoConsole}) {
+ t.Fatalf("consoles %v", got)
}
os.Chmod(creds, 0o644)
- if ProbeSite(c, nil) != nil {
- t.Fatal("a readable credential accepted")
+ if s := ProbeSite(c, nil); s == nil || s.Credentials != "" {
+ t.Fatalf("a readable credential accepted: %+v", s)
}
os.Chmod(creds, 0o600)
link := filepath.Join(root, "link")
os.Symlink(creds, link)
t.Setenv("CARLOS_CREDENTIALS", link)
- if ProbeSite(c, nil) != nil {
+ if s := ProbeSite(c, nil); s == nil || s.Credentials != "" {
t.Fatal("a linked credential accepted")
}
inside := filepath.Join(c.WorkspaceRoot, "credentials")
os.MkdirAll(c.WorkspaceRoot, 0o700)
os.WriteFile(inside, []byte("{}"), 0o600)
t.Setenv("CARLOS_CREDENTIALS", inside)
- if ProbeSite(c, nil) != nil {
+ if s := ProbeSite(c, nil); s == nil || s.Credentials != "" {
t.Fatal("a credential inside the workspace accepted")
}
+ if ProbeSite(runner.Config{StateDir: filepath.Join(c.WorkspaceRoot, "state"), WorkspaceRoot: c.WorkspaceRoot}, nil) != nil {
+ t.Fatal("site state inside the workspace accepted")
+ }
+ if ProbeSite(runner.Config{WorkspaceRoot: c.WorkspaceRoot}, nil) != nil {
+ t.Fatal("paired with no state")
+ }
}
-// TestHandshakeHelloWithholdsSites: the first hello never says the runner
-// can publish sites (an older instance would refuse it); after a protocol
-// 16 welcome the next hello, sent at once, does; at 15 none ever does.
-// Below 16 the deploy check is refused here and never sent.
-func TestHandshakeHelloWithholdsSites(t *testing.T) {
+// TestOwnedAccounts: only the owner rows of a NAME SQID ROLE table, each
+// validated; anything else is no account at all.
+func TestOwnedAccounts(t *testing.T) {
+ got := ownedAccounts("NAME SQID ROLE\npaulca kmnpq owner\nfriend bcdfg member\nbad-- -x owner\npaulca kmnpq owner\nkeymail hjkmn owner extra\n")
+ if !slices.Equal(got, []wire.ReachAccount{{Name: "paulca", Sqid: "kmnpq"}}) {
+ t.Fatalf("accounts %+v", got)
+ }
+ if got := ownedAccounts("Error: not logged in\n"); len(got) != 0 {
+ t.Fatalf("accounts from an error %+v", got)
+ }
+}
+
+// TestCarlosHealth: the version comes from carlos's own first line; the
+// health is missing with no binary, outdated when the version is
+// unreadable or below the minimum, else ok with the version.
+func TestCarlosHealth(t *testing.T) {
+ dir := t.TempDir()
+ write := func(name, out string) string {
+ p := filepath.Join(dir, name)
+ os.WriteFile(p, []byte("#!/bin/sh\n[ \"$1\" = version ] && printf '"+out+"'\n"), 0o755)
+ return p
+ }
+ cur, old, odd := write("cur", "carlos v0.43.3\\ncommit abc\\n"), write("old", "carlos v0.32.2\\n"), write("odd", "v0.43.3\\n")
+ if v := carlosVersionOf(context.Background(), cur); v != "v0.43.3" {
+ t.Fatalf("version %q", v)
+ }
+ for bin, want := range map[string][2]string{cur: {wire.CarlosOK, "v0.43.3"}, old: {wire.CarlosOutdated, "v0.32.2"}, odd: {wire.CarlosOutdated, ""}, "": {wire.CarlosMissing, ""}} {
+ c := &carlosCLI{Bin: bin, Read: carlosVersionOf}
+ if state, v := c.Health(context.Background()); state != want[0] || v != want[1] {
+ t.Errorf("%s: %s %s", bin, state, v)
+ }
+ }
+ var nilCLI *carlosCLI
+ if state, _ := nilCLI.Health(context.Background()); state != wire.CarlosMissing {
+ t.Fatal("no carlos is not missing")
+ }
+}
+
+// TestHandshakeHelloWithholdsPlaces: the first hello never carries the
+// reach or the carlos health (an older instance would refuse it); after a
+// protocol 31 welcome the next hello, sent at once, does; at 30 none ever
+// does, and the publish and mint checks are refused here, never sent.
+func TestHandshakeHelloWithholdsPlaces(t *testing.T) {
hello := func() wire.Hello {
return wire.Hello{Repos: []string{"amadan.net/oficina/sample"}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": "test", "claude": "2.1.312"},
- Capabilities: &wire.Capabilities{Tags: []string{wire.TagLinux}, Simulators: []wire.Simulator{}, Sites: true}}
+ Capabilities: &wire.Capabilities{Tags: []string{wire.TagLinux}, Simulators: []wire.Simulator{}, Tools: &wire.ToolHealth{Scanner: wire.ToolHealthy, Carlos: wire.CarlosOK, CarlosVersion: "v0.43.3"}, Reach: &wire.Reach{Logins: []wire.ReachLogin{}, Deploys: []wire.ReachDeploy{}}}}
}
- for _, protocol := range []int{wire.ProtocolReadings, wire.ProtocolPublish} {
+ for _, protocol := range []int{wire.ProtocolStuckTasks, wire.ProtocolPlaces} {
inst := newFakeInstance(t)
link, _, _, _ := startLinkWith(t, inst.url, &stubCoordinator{}, hello)
c := <-inst.conns
_, raw := read(t, c, wire.FrameHello)
- if strings.Contains(string(raw), `"sites"`) || !strings.Contains(string(raw), `"linux"`) {
+ if strings.Contains(string(raw), `"reach"`) || strings.Contains(string(raw), `"carlos`) || !strings.Contains(string(raw), `"linux"`) {
t.Fatalf("handshake hello: %s", raw)
}
welcome, _ := json.Marshal(wire.Frame{ID: "w-s", Type: wire.FrameWelcome, Data: json.RawMessage(`{"generation":3,"runner_id":"RUNNER1","protocol":` + itoa(int64(protocol)) + `,"role":"primary"}`)})
write(t, c, welcome)
read(t, c, wire.FrameSync)
- if protocol < wire.ProtocolPublish {
- link.HelloSoon()
- }
_, raw = read(t, c, wire.FrameHello)
- if got := strings.Contains(string(raw), `"sites":true`); got != (protocol >= wire.ProtocolPublish) {
+ if got := strings.Contains(string(raw), `"reach"`) && strings.Contains(string(raw), `"carlos":"ok"`); got != (protocol >= wire.ProtocolPlaces) {
t.Fatalf("protocol %d hello: %s", protocol, raw)
}
- if protocol < wire.ProtocolPublish {
- if err := link.ConfirmPublish(context.Background(), "s_1", 1, strings.Repeat("a", 64)); !errors.Is(err, ErrNoAuthority) {
+ if protocol < wire.ProtocolPlaces {
+ dest := wire.SiteDestination(rigConsole, rigSqid, rigName, rigApp)
+ if err := link.ConfirmPublish(context.Background(), "s_1", 1, strings.Repeat("a", 64), dest); !errors.Is(err, ErrNoAuthority) {
t.Fatalf("a deploy check at %d: %v", protocol, err)
}
+ if err := link.ConfirmMint(context.Background(), "s_1", 1, strings.Repeat("a", 64), dest); !errors.Is(err, ErrNoAuthority) {
+ t.Fatalf("a mint check at %d: %v", protocol, err)
+ }
}
}
}
-
-// TestSitePublishRestart: an attempt that may have changed Carloku only
-// reconciles after a restart: it never deploys again, and the marker over
-// the recorded URL says whether it is served.
-func TestSitePublishRestart(t *testing.T) {
- rig := newSiteRig(t, quickSite)
- first := rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {})
- again := rig.r
- again.Phase = phaseSitePublishing
- rep := rig.e.Exec(context.Background(), again, func(wire.StepReport) {})
- if rep.State != wire.StepDone || rep.Publish == nil || rep.Publish.Outcome != wire.PublishPublished || rep.Publish.Digest != first.Publish.Digest || rep.Publish.URL != "https://site-sample.bds.oncarlos.com/" {
- t.Fatalf("reconciled %+v", rep.Publish)
- }
- if n := len(carlosRuns(t, rig.calls)); n != 2 {
- t.Fatalf("carlos ran %d times", n)
- }
-}
-
-// TestSitePublishOwnedOnlyWhenVerified: a name is this runner's only after
-// a deploy that succeeded and whose marker answered. A deploy that failed
-// leaves it unowned: the next publish lists the account again, and is
-// refused when the app has appeared meanwhile; once one is verified, the
-// next publish deploys without listing.
-func TestSitePublishOwnedOnlyWhenVerified(t *testing.T) {
- rig := newSiteRig(t, quickSite)
- fail := filepath.Join(filepath.Dir(rig.calls), "fail")
- os.WriteFile(fail, nil, 0o644)
- if rep := rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {}); rep.Reason != "publish_failed" || rep.Publish.Outcome != wire.PublishUnconfirmed {
- t.Fatalf("failed deploy %+v %+v", rep, rep.Publish)
- }
- os.Remove(fail)
- next := rig.r
- next.StepID = "s_pub2"
- if rep := rig.e.Exec(context.Background(), next, func(wire.StepReport) {}); rep.State != wire.StepDone || rep.Publish.Outcome != wire.PublishPublished {
- t.Fatalf("after a failed deploy %+v", rep.Publish)
- }
- verbs := func() []string {
- var out []string
- for _, r := range carlosRuns(t, rig.calls) {
- out = append(out, r.args[0])
- }
- return out
- }
- if got := verbs(); !slices.Equal(got, []string{"apps", "deploy", "apps", "deploy"}) {
- t.Fatalf("after a failed deploy the name was trusted: %v", got)
- }
- third := rig.r
- third.StepID = "s_pub3"
- rig.e.Exec(context.Background(), third, func(wire.StepReport) {})
- if got := verbs(); !slices.Equal(got, []string{"apps", "deploy", "apps", "deploy", "deploy"}) {
- t.Fatalf("a verified name listed again: %v", got)
- }
-
- // The app appears after a failed attempt (someone else made it): refused.
- rig = newSiteRig(t, quickSite)
- fail = filepath.Join(filepath.Dir(rig.calls), "fail")
- os.WriteFile(fail, nil, 0o644)
- rig.e.Exec(context.Background(), rig.r, func(wire.StepReport) {})
- os.Remove(fail)
- os.WriteFile(rig.apps, []byte(listHeader+"site-sample live eu-west\n"), 0o644)
- next = rig.r
- next.StepID = "s_pub2"
- if rep := rig.e.Exec(context.Background(), next, func(wire.StepReport) {}); rep.State != wire.StepFailed || rep.Reason != "publish_app_taken" {
- t.Fatalf("an app made after a failed attempt %+v", rep)
- }
- if got := verbs(); !slices.Equal(got, []string{"apps", "deploy", "apps"}) {
- t.Fatalf("runs %v", got)
- }
-}
diff --git a/internal/runner/thin/tool_health_test.go b/internal/runner/thin/tool_health_test.go
index 8a0a29a4..ac738913 100644
--- a/internal/runner/thin/tool_health_test.go
+++ b/internal/runner/thin/tool_health_test.go
@@ -31,7 +31,7 @@ func TestToolHealthReportsTheScannerPin(t *testing.T) {
t.Cleanup(func() { previewScannerTool = old })
report := func(path, want string) wire.Capabilities {
previewScannerTool = func(runner.Config) (string, string) { return path, want }
- return linuxCapabilities(runner.Config{}, func() *wire.PreviewHost { return nil }, false, nil)(context.Background())
+ return linuxCapabilities(runner.Config{}, func() *wire.PreviewHost { return nil }, nil, nil)(context.Background())
}
for _, c := range []struct{ path, pin, want string }{
{binary, pin, wire.ToolHealthy},
diff --git a/internal/wire/api.go b/internal/wire/api.go
index 0f5ebb02..f6a74727 100644
--- a/internal/wire/api.go
+++ b/internal/wire/api.go
@@ -391,6 +391,8 @@ type Card struct {
PreviewURL string `json:"preview_url,omitempty"`
// Site is a publish card's site; absent on every other card.
Site *CardSite `json:"site,omitempty"`
+ // Place is a place card's proposal; absent on every other card.
+ Place *CardPlaceView `json:"place,omitempty"`
// Advice is an advice card's advice; absent on every other card.
Advice *Advice `json:"advice,omitempty"`
// Aside: the person set the card aside (POST /cards/{id}/visibility).
diff --git a/internal/wire/assistant_test.go b/internal/wire/assistant_test.go
index 3d0b8ab5..2aee5660 100644
--- a/internal/wire/assistant_test.go
+++ b/internal/wire/assistant_test.go
@@ -81,7 +81,7 @@ func TestAssistantCardJSON(t *testing.T) {
// A runner that speaks 24 or more is spoken to at 24, the warm
// protocol; glances came at 23 and jobs at 22.
func TestSpokenIs24(t *testing.T) {
- if wire.Spoken(99) != 30 || wire.ProtocolCurrent != wire.ProtocolStuckTasks || wire.ProtocolWarm != wire.Protocol24 || wire.ProtocolGlance != wire.Protocol23 || wire.ProtocolJobs != wire.Protocol22 || wire.ProtocolCopy != wire.Protocol21 || wire.ProtocolUsageRefresh != wire.Protocol20 || wire.ProtocolAssistant != wire.Protocol19 {
+ if wire.Spoken(99) != 31 || wire.ProtocolCurrent != wire.ProtocolPlaces || wire.ProtocolWarm != wire.Protocol24 || wire.ProtocolGlance != wire.Protocol23 || wire.ProtocolJobs != wire.Protocol22 || wire.ProtocolCopy != wire.Protocol21 || wire.ProtocolUsageRefresh != wire.Protocol20 || wire.ProtocolAssistant != wire.Protocol19 {
t.Fatalf("spoken %d, current %d", wire.Spoken(99), wire.ProtocolCurrent)
}
}
diff --git a/internal/wire/frames.go b/internal/wire/frames.go
index 0f09798a..f303a698 100644
--- a/internal/wire/frames.go
+++ b/internal/wire/frames.go
@@ -420,6 +420,9 @@ type LeaseCheck struct {
// Protocol 9: Digest binds a preview_publish check to the export the
// step reported as built.
Digest string `json:"digest,omitempty"`
+ // ProtocolPlaces: Destination binds a site_publish check to the
+ // SiteDestination the runner is about to deploy to.
+ Destination string `json:"destination,omitempty"`
}
// LeasePurposeMerge is a LeaseCheck's Purpose right before a hub merge
@@ -583,7 +586,7 @@ const (
)
// ConverseTools is the coordinator's tool set in a conversation.
-var ConverseTools = []string{ToolRequestAccess, ToolStatus, ToolFind, ToolSearchCode, ToolReadFile, ToolAddProject, ToolCreateProject, ToolSetProjectHome, ToolStarProject, ToolAskPerson, ToolWriteNote, ToolReadNotes, ToolRecordTask, ToolAddFinding, ToolStartTask, ToolReadTask, ToolCancelTask, ToolAddReport, ToolHoldMerge, ToolSetMergePolicy, ToolProposeSpecialist, ToolResearch, ToolOfferRetry, ToolRetryStep}
+var ConverseTools = []string{ToolRequestAccess, ToolStatus, ToolFind, ToolSearchCode, ToolReadFile, ToolAddProject, ToolCreateProject, ToolSetProjectHome, ToolStarProject, ToolAskPerson, ToolWriteNote, ToolReadNotes, ToolRecordTask, ToolAddFinding, ToolStartTask, ToolReadTask, ToolCancelTask, ToolAddReport, ToolHoldMerge, ToolSetMergePolicy, ToolProposeSpecialist, ToolResearch, ToolOfferRetry, ToolRetryStep, ToolPlaces, ToolProposePlace, ToolPublishSite, ToolSiteStatus}
// MoveInTools are the tools a move_in or explore turn may use: it looks
// around and takes notes, and never acts for the person.
@@ -680,12 +683,16 @@ var MutationKinds = map[string]string{
ToolOfferRetry: "retry_offer",
// One retry per task and step kind in a turn.
ToolRetryStep: "task_retry",
+ // One place proposal per project and one publish offer per task in a
+ // turn.
+ ToolProposePlace: "place_proposal",
+ ToolPublishSite: "site_offer",
}
// WriteTools change something outside the coordinator's session: the
// runner replays an exact repeat of one in a later attempt from its own
// record.
-var WriteTools = []string{ToolRequestAccess, ToolAddProject, ToolCreateProject, ToolSetProjectHome, ToolStarProject, ToolAskPerson, ToolWriteNote, ToolRecordTask, ToolAddFinding, ToolStartTask, ToolCancelTask, ToolAddReport, ToolHoldMerge, ToolSetMergePolicy, ToolProjectCreated, ToolProposeSpecialist, ToolResearch, ToolOfferRetry, ToolRetryStep}
+var WriteTools = []string{ToolRequestAccess, ToolAddProject, ToolCreateProject, ToolSetProjectHome, ToolStarProject, ToolAskPerson, ToolWriteNote, ToolRecordTask, ToolAddFinding, ToolStartTask, ToolCancelTask, ToolAddReport, ToolHoldMerge, ToolSetMergePolicy, ToolProjectCreated, ToolProposeSpecialist, ToolResearch, ToolOfferRetry, ToolRetryStep, ToolProposePlace, ToolPublishSite}
// ActivityReport is what the coordinator started doing: thinking, or a
// tool by name. Sent once, never acked, like a delta.
diff --git a/internal/wire/injection_test.go b/internal/wire/injection_test.go
index e6678b6c..49ac9e94 100644
--- a/internal/wire/injection_test.go
+++ b/internal/wire/injection_test.go
@@ -7,10 +7,10 @@ import (
)
func TestInjectionProtocolDowngrade(t *testing.T) {
- if wire.ProtocolInjectionDefences != 28 || wire.ProtocolCurrent != 30 {
+ if wire.ProtocolInjectionDefences != 28 || wire.ProtocolCurrent != 31 {
t.Fatal("injection guarantees require protocol 28")
}
- for version, want := range map[int]int{26: 26, 27: 27, 28: 28, 29: 29, 30: 30, 99: 30} {
+ for version, want := range map[int]int{26: 26, 27: 27, 28: 28, 29: 29, 30: 30, 31: 31, 99: 31} {
if got := wire.Spoken(version); got != want {
t.Fatalf("negotiated %d as %d, want %d", version, got, want)
}
diff --git a/internal/wire/mixed_protocol_test.go b/internal/wire/mixed_protocol_test.go
index 38424ed1..73a547f3 100644
--- a/internal/wire/mixed_protocol_test.go
+++ b/internal/wire/mixed_protocol_test.go
@@ -15,7 +15,7 @@ import (
// both go out whole; at 11 both are downgraded. The numbers are written
// out so that pointing ProtocolResearch back at 12 fails here.
func TestEncodeMixedMeteredAndResearch(t *testing.T) {
- if wire.ProtocolMetered != wire.Protocol12 || wire.ProtocolResearch != wire.Protocol13 || wire.ProtocolCurrent != wire.Protocol30 {
+ if wire.ProtocolMetered != wire.Protocol12 || wire.ProtocolResearch != wire.Protocol13 || wire.ProtocolCurrent != wire.Protocol31 {
t.Fatalf("metered %d, research %d, current %d", wire.ProtocolMetered, wire.ProtocolResearch, wire.ProtocolCurrent)
}
metered := wire.HeldConnection{LocalID: "tensorx-1", Person: "p", Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, State: wire.ConnHealthy, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Budget: &wire.Budget{Day: 1, Month: 2, Currency: "USD"}, Spend: &wire.Spend{Currency: "USD"}}
diff --git a/internal/wire/models_test.go b/internal/wire/models_test.go
index 28012643..892faa67 100644
--- a/internal/wire/models_test.go
+++ b/internal/wire/models_test.go
@@ -94,7 +94,7 @@ func modelsFrames(t *testing.T) map[string]wire.Frame {
// protocol is checked because an older step in Encode's chain could
// undo a newer one (S5's bug).
func TestEncodeBelowProtocol18AgainstFrozenSchemas(t *testing.T) {
- if wire.ProtocolModels != wire.Protocol18 || wire.ProtocolCurrent != wire.Protocol30 {
+ if wire.ProtocolModels != wire.Protocol18 || wire.ProtocolCurrent != wire.Protocol31 {
t.Fatalf("models %d, current %d", wire.ProtocolModels, wire.ProtocolCurrent)
}
fs := modelsFrames(t)
diff --git a/internal/wire/opencode_test.go b/internal/wire/opencode_test.go
index ef98f25b..61faeeca 100644
--- a/internal/wire/opencode_test.go
+++ b/internal/wire/opencode_test.go
@@ -57,7 +57,7 @@ func providersIn(t *testing.T, raw []byte) (providers, harnesses []string) {
// leave hello and sync, its usage rows leave every report, and a connect
// or a report about one is refused. At 17 nothing changes.
func TestEncodeBelowProtocol17DropsOpenCode(t *testing.T) {
- if wire.ProtocolOpenCode != wire.Protocol17 || wire.ProtocolCurrent != wire.Protocol30 {
+ if wire.ProtocolOpenCode != wire.Protocol17 || wire.ProtocolCurrent != wire.Protocol31 {
t.Fatalf("opencode %d, current %d", wire.ProtocolOpenCode, wire.ProtocolCurrent)
}
budget := &wire.Budget{Day: 1_000_000, Month: 10_000_000, Currency: "USD", Revision: 1}
@@ -164,8 +164,14 @@ func TestEncodeMixedVersionsOpenCodeAndPublish(t *testing.T) {
report := frame("r", wire.FrameStep, built)
hello := frame("h", wire.FrameHello, wire.Hello{Protocol: wire.ProtocolCurrent, Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: held, Capabilities: &wire.Capabilities{Sites: true, Tags: []string{wire.TagLinux}}})
- // At 17 both go out whole.
- for _, f := range []wire.Frame{connect, publish, check, report, hello} {
+ // At 17 both go out whole, but a publish dispatch, place-bound since
+ // 31, is refused below 31.
+ for _, f := range []wire.Frame{publish, check} {
+ if _, err := wire.Encode(f, wire.Protocol17); !errors.Is(err, wire.ErrProtocol) {
+ t.Fatalf("a publish %s encoded at 17: %v", f.Type, err)
+ }
+ }
+ for _, f := range []wire.Frame{connect, report, hello} {
if same, err := wire.Encode(f, wire.Protocol17); err != nil || !bytes.Equal(same.Data, f.Data) {
t.Fatalf("%s changed at 17: %v", f.Type, err)
}
@@ -175,11 +181,6 @@ func TestEncodeMixedVersionsOpenCodeAndPublish(t *testing.T) {
if _, err := wire.Encode(connect, wire.Protocol16); !errors.Is(err, wire.ErrProtocol) {
t.Fatalf("an OpenCode Go connect encoded at 16: %v", err)
}
- for _, f := range []wire.Frame{publish, check} {
- if same, err := wire.Encode(f, wire.Protocol16); err != nil || !bytes.Equal(same.Data, f.Data) {
- t.Fatalf("publish %s changed at 16: %v", f.Type, err)
- }
- }
got, err := wire.Encode(report, wire.Protocol16)
if err != nil || strings.Contains(string(got.Data), wire.ProviderOpenCodeGo) || !strings.Contains(string(got.Data), `"publish":`) || !strings.Contains(string(got.Data), wire.ProviderTensorX) {
t.Fatalf("report at 16 (OpenCode Go rows out, publish result kept): %v %s", err, got.Data)
diff --git a/internal/wire/pinned_release_test.go b/internal/wire/pinned_release_test.go
index 0a71599a..aeb0eb6c 100644
--- a/internal/wire/pinned_release_test.go
+++ b/internal/wire/pinned_release_test.go
@@ -13,7 +13,7 @@ import (
// carrying a pinned release loses the release and its pin; an unpinned
// release is unchanged from protocol 14.
func TestEncodePinnedReleaseBelow29(t *testing.T) {
- if wire.ProtocolPinnedRelease != wire.Protocol29 || wire.ProtocolCurrent != wire.Protocol30 {
+ if wire.ProtocolPinnedRelease != wire.Protocol29 || wire.ProtocolCurrent != wire.Protocol31 {
t.Fatalf("pinned %d, current %d", wire.ProtocolPinnedRelease, wire.ProtocolCurrent)
}
pinned, err := wire.NewFrame("f1", wire.FrameRelease, wire.ReleaseCommand{ID: "rl_1", Person: "p", TaskID: "tk1", StepID: "s1", StepRevision: 1, Connection: "claude-1"})
diff --git a/internal/wire/places.go b/internal/wire/places.go
new file mode 100644
index 00000000..b16bf7a3
--- /dev/null
+++ b/internal/wire/places.go
@@ -0,0 +1,301 @@
+package wire
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "regexp"
+ "slices"
+ "strconv"
+)
+
+// Places (spec 2026-11-26-places-config.md, slice 1): a place is a named
+// destination the team confirmed. ProtocolPlaces adds what the runner can
+// reach (a hello's Reach: the CARLOS logins it may set a site up with and
+// the deploy keys it may publish with), the carlos CLI's health, a
+// publish dispatch and its publish and mint checks bound to the confirmed
+// place, and the coordinator's four place tools. Below it Encode drops the hello's fields and refuses the rest:
+// an older runner would publish to its own fixed account.
+
+// The place tools. places and site_status are read-only; propose_place
+// raises a card only an owner's tap confirms; publish_site raises the
+// publish card only the creator's tap answers.
+const (
+ ToolPlaces = "places"
+ ToolProposePlace = "propose_place"
+ ToolPublishSite = "publish_site"
+ ToolSiteStatus = "site_status"
+)
+
+// PlacesTools are ProtocolPlaces's coordinator tools.
+var PlacesTools = []string{ToolPlaces, ToolProposePlace, ToolPublishSite, ToolSiteStatus}
+
+// CardPlace asks an owner to confirm where a project's site goes: Options
+// are the candidates' ids, best first, then ChoiceNotNow; Card.Place says
+// what each one is, in words code derived.
+const CardPlace = "place"
+
+// Place kinds and adapters (slice 1: a site, on a CARLOS app).
+const (
+ PlaceSite = "site"
+ AdapterCarlosApp = "carlos_app"
+ PlaceProposed = "proposed"
+ PlaceConfirmed = "confirmed"
+ PlaceRetired = "retired"
+ FlagshipConsole = "console.carloku.com"
+ TitoConsole = "console.platform.tito.io"
+ MaxReachLogins = 8
+ MaxReachAccounts = 20
+ MaxReachDeploys = 50
+ MaxPlaceOptions = 6
+ placeCandidateLen = 15
+)
+
+// Reach is what a runner's carlos can do, with no secret: Logins are the
+// consoles an owner's CLI login on it reaches and the accounts it owns
+// there (a site may be set up there); Deploys are the app deploy keys it
+// holds (a site may be published with one). Console is a host name.
+type Reach struct {
+ Logins []ReachLogin `json:"logins"`
+ Deploys []ReachDeploy `json:"deploys"`
+}
+
+// ReachLogin is one console the runner's carlos is signed in to and the
+// accounts it owns there.
+type ReachLogin struct {
+ Console string `json:"console"`
+ Accounts []ReachAccount `json:"accounts"`
+}
+
+// ReachAccount is one owned account: its name (for people) and its sqid
+// (its identity, what every command names).
+type ReachAccount struct {
+ Name string `json:"name"`
+ Sqid string `json:"sqid"`
+}
+
+// ReachDeploy is one deploy key of the runner's: the console, account
+// sqid and app it was minted for, its CARLOS name and fingerprint. Lost:
+// the runner asked CARLOS for it and does not hold it (the answer was
+// lost or unreadable, or it stopped before storing it): it may be live on
+// CARLOS. The runner keeps saying so until it holds a key for the app.
+type ReachDeploy struct {
+ Console string `json:"console"`
+ Account string `json:"account"`
+ App string `json:"app"`
+ Name string `json:"name"`
+ Fingerprint string `json:"fingerprint,omitempty"`
+ Lost bool `json:"lost,omitempty"`
+}
+
+// CardPlaceView is a place card's proposal: the kind, the project and the
+// candidates in the order the card offers them.
+type CardPlaceView struct {
+ Kind string `json:"kind"`
+ Project string `json:"project"`
+ Candidates []PlaceCandidate `json:"candidates"`
+}
+
+// PlaceCandidate is one destination a runner can reach: its id (what a
+// tool and a tap name), the console host and its label, and the account.
+type PlaceCandidate struct {
+ ID string `json:"id"`
+ Console string `json:"console"`
+ ConsoleLabel string `json:"console_label"`
+ Account string `json:"account"`
+ Sqid string `json:"sqid"`
+}
+
+// The carlos CLI's health (ToolHealth.Carlos) and the oldest release whose
+// deploy and devbox share accept the preview's security headers.
+const (
+ CarlosOK = "ok"
+ CarlosOutdated = "outdated"
+ CarlosMissing = "missing"
+ MinCarlos = "v0.43.0"
+ // ReasonCarlosOutdated ends a preview or a publish whose runner's
+ // carlos is unreadable or older than MinCarlos, before anything is
+ // built or sent.
+ ReasonCarlosOutdated = "carlos_outdated"
+)
+
+var (
+ consoleHost = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$`)
+ accountName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._@+-]{0,99}$`)
+ accountSqid = regexp.MustCompile(`^[abcdefghjkmnpqrstuvwxyz]{3,16}$`)
+ carlosSemver = regexp.MustCompile(`^v([0-9]{1,4})\.([0-9]{1,4})\.([0-9]{1,4})$`)
+ candidateID = regexp.MustCompile(`^pc_[0-9a-f]{12}$`)
+ keyName = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]{0,30}[a-z0-9])?$`)
+ fingerprint = regexp.MustCompile(`^[0-9a-f]{16}$`)
+)
+
+// ValidConsoleHost reports whether host is a console's host name (no
+// scheme, port or path).
+func ValidConsoleHost(host string) bool { return len(host) <= 253 && consoleHost.MatchString(host) }
+
+// ValidAccountName reports whether name may be shown as an account's name.
+func ValidAccountName(name string) bool { return accountName.MatchString(name) }
+
+// ValidSqid reports whether s is a CARLOS account sqid.
+func ValidSqid(s string) bool { return accountSqid.MatchString(s) }
+
+// ValidCandidateID reports whether id is a place candidate's id.
+func ValidCandidateID(id string) bool { return candidateID.MatchString(id) }
+
+// ValidDeployName reports whether n is a deploy key's CARLOS name.
+func ValidDeployName(n string) bool { return keyName.MatchString(n) }
+
+// ConsoleOrigin is a console host's https origin.
+func ConsoleOrigin(host string) string { return "https://" + host }
+
+// CandidateID is the id of the destination console and sqid: stable,
+// derived by code, never chosen by a model.
+func CandidateID(console, sqid string) string {
+ sum := sha256.Sum256([]byte("place-candidate/v1\n" + console + "\n" + sqid))
+ return "pc_" + hex.EncodeToString(sum[:])[:placeCandidateLen-3]
+}
+
+// SiteDestination is the hash a publish's tap, dispatch, final check and
+// deploy are bound to: the console, the account's sqid and name, and the
+// app, in a versioned line.
+func SiteDestination(console, sqid, name, app string) string {
+ sum := sha256.Sum256([]byte("site-destination/v1\n" + console + "\n" + sqid + "\n" + name + "\n" + app))
+ return hex.EncodeToString(sum[:])
+}
+
+var destinationHash = regexp.MustCompile(`^[0-9a-f]{64}$`)
+
+// ValidDestination reports whether d is a SiteDestination.
+func ValidDestination(d string) bool { return destinationHash.MatchString(d) }
+
+// CarlosAtLeast reports whether version (vX.Y.Z) is at least min; an
+// unreadable one never is.
+func CarlosAtLeast(version, min string) bool {
+ a, b := carlosSemver.FindStringSubmatch(version), carlosSemver.FindStringSubmatch(min)
+ if a == nil || b == nil {
+ return false
+ }
+ for i := 1; i <= 3; i++ {
+ x, _ := strconv.Atoi(a[i])
+ y, _ := strconv.Atoi(b[i])
+ if x != y {
+ return x > y
+ }
+ }
+ return true
+}
+
+// ValidCarlosVersion reports whether v is a carlos release version.
+func ValidCarlosVersion(v string) bool { return carlosSemver.MatchString(v) }
+
+// ConsoleLabel is a console's name for people: Carloku and Tito by name,
+// any other console by its host.
+func ConsoleLabel(host string) string {
+ switch host {
+ case FlagshipConsole:
+ return "Carloku"
+ case TitoConsole:
+ return "Tito"
+ }
+ return host
+}
+
+// validReach reports whether a runner's reach is in bounds: valid hosts,
+// names and sqids, no console twice, no account twice in one console, no
+// key twice.
+func validReach(r Reach) bool {
+ if len(r.Logins) > MaxReachLogins || len(r.Deploys) > MaxReachDeploys {
+ return false
+ }
+ consoles := map[string]bool{}
+ for _, l := range r.Logins {
+ if !ValidConsoleHost(l.Console) || consoles[l.Console] || len(l.Accounts) > MaxReachAccounts {
+ return false
+ }
+ consoles[l.Console] = true
+ sqids := map[string]bool{}
+ for _, a := range l.Accounts {
+ if !ValidAccountName(a.Name) || !ValidSqid(a.Sqid) || sqids[a.Sqid] {
+ return false
+ }
+ sqids[a.Sqid] = true
+ }
+ }
+ keys := map[string]bool{}
+ for _, k := range r.Deploys {
+ id := k.Console + " " + k.Account + " " + k.App + " " + k.Name
+ if !ValidConsoleHost(k.Console) || !ValidSqid(k.Account) || !ValidSiteApp(k.App) || keys[id] || !keyName.MatchString(k.Name) || (k.Lost != (k.Fingerprint == "")) || k.Fingerprint != "" && !fingerprint.MatchString(k.Fingerprint) {
+ return false
+ }
+ keys[id] = true
+ }
+ return true
+}
+
+// validCarlosHealth: a fixed state, with a version exactly when one was
+// read.
+func validCarlosHealth(state, version string) bool {
+ switch state {
+ case "":
+ return version == ""
+ case CarlosMissing:
+ return version == ""
+ case CarlosOK:
+ return ValidCarlosVersion(version) && CarlosAtLeast(version, MinCarlos)
+ case CarlosOutdated:
+ return version == "" || ValidCarlosVersion(version)
+ }
+ return false
+}
+
+// WithoutPlaces drops a hello's reach and carlos health, in a copy. The
+// first hello is sent before the instance says its protocol: an older
+// instance's strict decoder would refuse them. It reports whether it
+// dropped anything.
+func WithoutPlaces(h *Hello) bool {
+ if h.Capabilities == nil || h.Capabilities.Reach == nil && (h.Capabilities.Tools == nil || h.Capabilities.Tools.Carlos == "" && h.Capabilities.Tools.CarlosVersion == "") {
+ return false
+ }
+ c := *h.Capabilities
+ c.Reach = nil
+ if c.Tools != nil {
+ t := *c.Tools
+ t.Carlos, t.CarlosVersion = "", ""
+ c.Tools = &t
+ }
+ h.Capabilities = &c
+ return true
+}
+
+// downgradePlaces clears ProtocolPlaces's fields for an older peer and
+// refuses what it cannot carry: a publish dispatch (an older runner would
+// deploy to its fixed account), a publish check (an older instance would
+// decide it without the destination) and a place tool's call.
+func downgradePlaces(body any, protocol int) (bool, error) {
+ switch v := body.(type) {
+ case *Hello:
+ return WithoutPlaces(v), nil
+ case *ToolCall:
+ if slices.Contains(PlacesTools, v.Name) {
+ return false, fmt.Errorf("%w: %s at protocol %d", ErrProtocol, v.Name, protocol)
+ }
+ case *DispatchCommand:
+ if v.Specialist == SpecialistPublish {
+ return false, fmt.Errorf("%w: a place-bound publish at protocol %d", ErrProtocol, protocol)
+ }
+ case *StepReport:
+ if p := v.Publish; p != nil && p.DeployHeld {
+ c := *p
+ c.DeployHeld = false
+ v.Publish = &c
+ return true, nil
+ }
+ case *LeaseCheck:
+ // A publish's final check is bound to its destination; an older
+ // instance would decide a weaker one, so it is never asked.
+ if v.Purpose == LeasePurposePublish || v.Purpose == LeasePurposeMint || v.Destination != "" {
+ return false, fmt.Errorf("%w: a place-bound publish check at protocol %d", ErrProtocol, protocol)
+ }
+ }
+ return false, nil
+}
diff --git a/internal/wire/places_test.go b/internal/wire/places_test.go
new file mode 100644
index 00000000..e637f87e
--- /dev/null
+++ b/internal/wire/places_test.go
@@ -0,0 +1,155 @@
+package wire_test
+
+import (
+ "bytes"
+ "errors"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+func placesHello() wire.Hello {
+ return wire.Hello{Protocol: wire.ProtocolCurrent, Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{}, Capabilities: &wire.Capabilities{Simulators: []wire.Simulator{}, Tags: []string{wire.TagLinux},
+ Tools: &wire.ToolHealth{Scanner: wire.ToolHealthy, Carlos: wire.CarlosOK, CarlosVersion: "v0.43.3"},
+ Reach: &wire.Reach{Logins: []wire.ReachLogin{{Console: wire.FlagshipConsole, Accounts: []wire.ReachAccount{{Name: "paulca", Sqid: "kmnpq"}}}}, Deploys: []wire.ReachDeploy{{Console: wire.FlagshipConsole, Account: "kmnpq", App: "site-nearys-k3x9qa", Name: "eq-nearys-k3x9qa-ab12", Fingerprint: "0123456789abcdef"}, {Console: wire.FlagshipConsole, Account: "kmnpq", App: "site-nearys-k3x9qa", Name: "eq-nearys-k3x9qa-zz00", Lost: true}}}}}
+}
+
+// Protocol 31 (places): at 31 a hello's reach and carlos health, a
+// place-bound publish dispatch, the publish and mint checks and the place
+// tools go out whole. Below it the hello's fields are dropped, and a
+// publish dispatch, a publish or mint check and a place tool's call are
+// refused: an older runner would deploy to its own fixed account, an
+// older instance would decide a check without the destination.
+func TestEncodeBelowProtocol31DropsPlaces(t *testing.T) {
+ if wire.ProtocolPlaces != wire.Protocol31 || wire.ProtocolCurrent != wire.ProtocolPlaces || wire.Spoken(99) != 31 {
+ t.Fatalf("places %d, current %d", wire.ProtocolPlaces, wire.ProtocolCurrent)
+ }
+ hello := placesHello()
+ helloFrame, _ := wire.NewFrame("h", wire.FrameHello, hello)
+ dispatch, _ := wire.NewFrame("d", wire.FrameDispatch, wire.DispatchCommand{Person: "p", TaskID: "tk", StepID: "s", Attempt: 1, Specialist: wire.SpecialistPublish, Findings: []wire.Finding{}, CandidateSHA: strings.Repeat("e", 40), Publish: &wire.PublishDispatch{App: "site-nearys-k3x9qa", Into: "main", Console: wire.FlagshipConsole, Account: "kmnpq", AccountName: "paulca", Place: "pl_1", PlaceRevision: 1, BindingRevision: 1, Destination: wire.SiteDestination(wire.FlagshipConsole, "kmnpq", "paulca", "site-nearys-k3x9qa"), Mode: wire.SiteSetup, DeployName: "eq-nearys-k3x9qa-ab12"}})
+ check, _ := wire.NewFrame("l", wire.FrameLease, wire.LeaseCheck{Generation: 1, StepID: "s", Attempt: 1, Purpose: wire.LeasePurposePublish, Digest: strings.Repeat("a", 64), Destination: strings.Repeat("b", 64)})
+ mint, _ := wire.NewFrame("l", wire.FrameLease, wire.LeaseCheck{Generation: 1, StepID: "s", Attempt: 1, Purpose: wire.LeasePurposeMint, Destination: strings.Repeat("b", 64)})
+ var calls []wire.Frame
+ for _, name := range wire.PlacesTools {
+ f, _ := wire.NewFrame("t", wire.FrameToolCall, wire.ToolCall{TurnID: "t", CallID: "c", Name: name, Args: []byte(`{}`)})
+ calls = append(calls, f)
+ }
+ for _, f := range append([]wire.Frame{helloFrame, dispatch, check, mint}, calls...) {
+ if same, err := wire.Encode(f, wire.Protocol31); err != nil || !bytes.Equal(same.Data, f.Data) {
+ t.Fatalf("%s changed at 31: %v", f.Type, err)
+ }
+ }
+ plainCheck, _ := wire.NewFrame("l", wire.FrameLease, wire.LeaseCheck{Generation: 1, StepID: "s", Attempt: 1, Purpose: wire.LeasePurposePublish, Digest: strings.Repeat("a", 64)})
+ for _, f := range append([]wire.Frame{dispatch, check, plainCheck, mint}, calls...) {
+ if _, err := wire.Encode(f, wire.Protocol30); !errors.Is(err, wire.ErrProtocol) {
+ t.Fatalf("%s %s encoded at 30: %v", f.Type, f.Data, err)
+ }
+ }
+ got, err := wire.Encode(helloFrame, wire.Protocol30)
+ if err != nil || strings.Contains(string(got.Data), `"reach"`) || strings.Contains(string(got.Data), `"carlos`) || !strings.Contains(string(got.Data), `"scanner":"ok"`) {
+ t.Fatalf("hello at 30: %v %s", err, got.Data)
+ }
+ if hello.Capabilities.Reach == nil || hello.Capabilities.Tools.Carlos != wire.CarlosOK {
+ t.Fatal("encoding changed the caller's hello")
+ }
+}
+
+// A runner's reach is bounded and validated like every capability: host
+// names, account names and sqids of their shapes, nothing twice, and a
+// carlos health that is a fixed state with a version exactly when one was
+// read; ok only at or above the minimum.
+func TestValidReachAndCarlosHealth(t *testing.T) {
+ good := placesHello().Capabilities
+ if err := wire.ValidCapabilities(*good); err != nil {
+ t.Fatalf("refused %v", err)
+ }
+ mutate := func(f func(c *wire.Capabilities)) wire.Capabilities {
+ c := *placesHello().Capabilities
+ r := *c.Reach
+ r.Logins = append([]wire.ReachLogin{}, r.Logins...)
+ r.Logins[0].Accounts = append([]wire.ReachAccount{}, r.Logins[0].Accounts...)
+ r.Deploys = append([]wire.ReachDeploy{}, r.Deploys...)
+ c.Reach = &r
+ tools := *c.Tools
+ c.Tools = &tools
+ f(&c)
+ return c
+ }
+ for name, bad := range map[string]wire.Capabilities{
+ "origin not host": mutate(func(c *wire.Capabilities) { c.Reach.Logins[0].Console = "https:" }),
+ "host with port": mutate(func(c *wire.Capabilities) { c.Reach.Logins[0].Console = "console.carloku.com:8443" }),
+ "bad sqid": mutate(func(c *wire.Capabilities) { c.Reach.Logins[0].Accounts[0].Sqid = "abcio" }),
+ "bad name": mutate(func(c *wire.Capabilities) { c.Reach.Logins[0].Accounts[0].Name = "-x" }),
+ "account twice": mutate(func(c *wire.Capabilities) {
+ c.Reach.Logins[0].Accounts = append(c.Reach.Logins[0].Accounts, c.Reach.Logins[0].Accounts[0])
+ }),
+ "console twice": mutate(func(c *wire.Capabilities) { c.Reach.Logins = append(c.Reach.Logins, c.Reach.Logins[0]) }),
+ "deploy twice": mutate(func(c *wire.Capabilities) { c.Reach.Deploys = append(c.Reach.Deploys, c.Reach.Deploys[0]) }),
+ "deploy not site": mutate(func(c *wire.Capabilities) { c.Reach.Deploys[0].App = "tmp-x" }),
+ "held, no print": mutate(func(c *wire.Capabilities) { c.Reach.Deploys[0].Fingerprint = "" }),
+ "lost with print": mutate(func(c *wire.Capabilities) { c.Reach.Deploys[1].Fingerprint = "0123456789abcdef" }),
+ "bad deploy name": mutate(func(c *wire.Capabilities) { c.Reach.Deploys[0].Name = "Eq" }),
+ "too many logins": mutate(func(c *wire.Capabilities) { c.Reach.Logins = manyLogins(wire.MaxReachLogins + 1) }),
+ "ok but old": mutate(func(c *wire.Capabilities) { c.Tools.CarlosVersion = "v0.32.2" }),
+ "ok, no version": mutate(func(c *wire.Capabilities) { c.Tools.CarlosVersion = "" }),
+ "missing, version": mutate(func(c *wire.Capabilities) { c.Tools.Carlos, c.Tools.CarlosVersion = wire.CarlosMissing, "v0.43.3" }),
+ "unknown state": mutate(func(c *wire.Capabilities) { c.Tools.Carlos = "fine" }),
+ "raw version": mutate(func(c *wire.Capabilities) {
+ c.Tools.Carlos, c.Tools.CarlosVersion = wire.CarlosOutdated, "carlos v0.32.2"
+ }),
+ } {
+ if wire.ValidCapabilities(bad) == nil {
+ t.Errorf("%s accepted", name)
+ }
+ }
+ for name, ok := range map[string]wire.Capabilities{
+ "minimum": mutate(func(c *wire.Capabilities) { c.Tools.CarlosVersion = wire.MinCarlos }),
+ "outdated": mutate(func(c *wire.Capabilities) { c.Tools.Carlos, c.Tools.CarlosVersion = wire.CarlosOutdated, "v0.32.2" }),
+ "unreadable": mutate(func(c *wire.Capabilities) { c.Tools.Carlos, c.Tools.CarlosVersion = wire.CarlosOutdated, "" }),
+ "keymail name": mutate(func(c *wire.Capabilities) { c.Reach.Logins[0].Accounts[0].Name = "paul@keymail.dev" }),
+ "most logins": mutate(func(c *wire.Capabilities) { c.Reach.Logins = manyLogins(wire.MaxReachLogins) }),
+ "no carlos at all": mutate(func(c *wire.Capabilities) { c.Tools.Carlos, c.Tools.CarlosVersion = "", "" }),
+ } {
+ if err := wire.ValidCapabilities(ok); err != nil {
+ t.Errorf("%s refused: %v", name, err)
+ }
+ }
+}
+
+func manyLogins(n int) []wire.ReachLogin {
+ out := make([]wire.ReachLogin, n)
+ for i := range out {
+ out[i] = wire.ReachLogin{Console: "console" + string(rune('a'+i)) + ".example.com", Accounts: []wire.ReachAccount{}}
+ }
+ return out
+}
+
+// The ids and hashes code derives: stable, distinct per input, in their
+// fixed shapes.
+func TestPlaceIdentities(t *testing.T) {
+ a, b := wire.CandidateID(wire.FlagshipConsole, "kmnpq"), wire.CandidateID(wire.TitoConsole, "kmnpq")
+ if !wire.ValidCandidateID(a) || a == b || a != wire.CandidateID(wire.FlagshipConsole, "kmnpq") {
+ t.Fatalf("candidate ids %q %q", a, b)
+ }
+ d := wire.SiteDestination(wire.FlagshipConsole, "kmnpq", "paulca", "site-nearys-k3x9qa")
+ for _, other := range []string{wire.SiteDestination(wire.TitoConsole, "kmnpq", "paulca", "site-nearys-k3x9qa"), wire.SiteDestination(wire.FlagshipConsole, "kmnpr", "paulca", "site-nearys-k3x9qa"), wire.SiteDestination(wire.FlagshipConsole, "kmnpq", "oficina", "site-nearys-k3x9qa"), wire.SiteDestination(wire.FlagshipConsole, "kmnpq", "paulca", "site-nearys-k3x9qb")} {
+ if other == d {
+ t.Fatal("a destination hash ignores a part")
+ }
+ }
+ if !wire.ValidDestination(d) || wire.ValidDestination(d[:63]) {
+ t.Fatal("destination shape")
+ }
+ for v, want := range map[string]bool{"v0.43.0": true, "v0.43.3": true, "v1.0.0": true, "v0.42.9": false, "v0.32.2": false, "0.43.3": false, "v0.43": false, "": false} {
+ if wire.CarlosAtLeast(v, wire.MinCarlos) != want {
+ t.Errorf("CarlosAtLeast(%q) != %t", v, want)
+ }
+ }
+ if wire.ConsoleLabel(wire.FlagshipConsole) != "Carloku" || wire.ConsoleLabel(wire.TitoConsole) != "Tito" || wire.ConsoleLabel("console.example.com") != "console.example.com" {
+ t.Fatal("console labels")
+ }
+ if !wire.ValidDeployName("eq-nearys-k3x9qa-ab12") || wire.ValidDeployName("eq x") || wire.ValidDeployName(strings.Repeat("a", 33)) {
+ t.Fatal("deploy name shape")
+ }
+}
diff --git a/internal/wire/publish.go b/internal/wire/publish.go
index 306fbcbd..fa5a31ce 100644
--- a/internal/wire/publish.go
+++ b/internal/wire/publish.go
@@ -38,8 +38,37 @@ const (
type PublishDispatch struct {
App string `json:"app"`
Into string `json:"into"`
+ // ProtocolPlaces: the confirmed place it publishes to (console host,
+ // account sqid and name), the place's and the project binding's
+ // revisions the person's tap saw, and the SiteDestination of all of
+ // it. The runner deploys there and nowhere else.
+ Console string `json:"console,omitempty"`
+ Account string `json:"account,omitempty"`
+ AccountName string `json:"account_name,omitempty"`
+ Place string `json:"place,omitempty"`
+ PlaceRevision int64 `json:"place_revision,omitempty"`
+ BindingRevision int64 `json:"binding_revision,omitempty"`
+ Destination string `json:"destination,omitempty"`
+ // Mode is what the person's tap allowed (SiteSetup, SiteMint or
+ // SitePublish); DeployName the key a setup or mint asks for. The
+ // runner never changes mode.
+ Mode string `json:"mode,omitempty"`
+ DeployName string `json:"deploy_name,omitempty"`
}
+// Publish modes. Setup creates the app with the owner's login, then mints
+// its deploy key; mint only mints the key with that login (the app
+// exists), then deploys with the key; publish deploys with the held key.
+const (
+ SiteSetup = "setup"
+ SiteMint = "mint"
+ SitePublish = "publish"
+)
+
+// LeasePurposeMint is a LeaseCheck's Purpose right before a setup's or a
+// mint's services create, with the destination (ProtocolPlaces).
+const LeasePurposeMint = "site_mint"
+
// PublishResult is a publish step's word: Phase built with the export's
// digest, files and bytes; then, done, the app, the site's public URL and
// the Outcome (published once the marker answered over https, unconfirmed
@@ -53,6 +82,10 @@ type PublishResult struct {
Files int `json:"files"`
Bytes int64 `json:"bytes"`
Outcome string `json:"outcome,omitempty"`
+ // DeployHeld (ProtocolPlaces): a setup's or a mint's done report says
+ // the runner holds the site's deploy key now. Only a recovery card
+ // reads it; the key's evidence is the runner's reach.
+ DeployHeld bool `json:"deploy_held,omitempty"`
}
// Publish phases and outcomes.
@@ -103,9 +136,6 @@ var siteApp = regexp.MustCompile(`^site-[a-z0-9]+(-[a-z0-9]+)*$`)
// ValidSiteApp reports whether app is a publishable site's app name.
func ValidSiteApp(app string) bool { return len(app) <= MaxSiteApp && siteApp.MatchString(app) }
-// SiteHostCarloku is the site host a runner pairs with to publish.
-const SiteHostCarloku = "carloku"
-
// downgradePublish clears a body's ProtocolPublish fields and refuses a
// publish dispatch or check outright: an older peer has no words for them.
func downgradePublish(body any, protocol int) (bool, error) {
diff --git a/internal/wire/publish_test.go b/internal/wire/publish_test.go
index 6f940f0d..a063d2d0 100644
--- a/internal/wire/publish_test.go
+++ b/internal/wire/publish_test.go
@@ -17,7 +17,7 @@ import (
// and a hello's sites capability are dropped, so nothing a protocol 15
// peer decodes strictly carries them.
func TestEncodeBelowProtocol16DropsPublish(t *testing.T) {
- if wire.ProtocolPublish != wire.Protocol16 || wire.ProtocolCurrent != wire.Protocol30 {
+ if wire.ProtocolPublish != wire.Protocol16 || wire.ProtocolCurrent != wire.Protocol31 {
t.Fatalf("publish %d, current %d", wire.ProtocolPublish, wire.ProtocolCurrent)
}
publish := wire.DispatchCommand{Person: "p", TaskID: "tk", StepID: "s", Attempt: 1, Specialist: wire.SpecialistPublish, Findings: []wire.Finding{}, CandidateSHA: strings.Repeat("e", 40), Publish: &wire.PublishDispatch{App: "site-sample", Into: "main"}}
@@ -31,11 +31,20 @@ func TestEncodeBelowProtocol16DropsPublish(t *testing.T) {
hello := wire.Hello{Protocol: wire.Protocol16, Repos: []string{}, Capabilities: &wire.Capabilities{Sites: true, Tags: []string{wire.TagLinux}}}
helloFrame, _ := wire.NewFrame("h", wire.FrameHello, hello)
- for _, f := range []wire.Frame{dispatch, check, report, helloFrame} {
+ for _, f := range []wire.Frame{report, helloFrame} {
if same, err := wire.Encode(f, wire.Protocol16); err != nil || !bytes.Equal(same.Data, f.Data) {
t.Fatalf("%s changed at 16: %v", f.Type, err)
}
}
+ // Since places (31) every publish dispatch and check is bound to a
+ // place, which an older peer would ignore: both are refused below 31.
+ for _, f := range []wire.Frame{dispatch, check} {
+ for _, p := range []int{wire.Protocol30, wire.Protocol16} {
+ if _, err := wire.Encode(f, p); !errors.Is(err, wire.ErrProtocol) {
+ t.Fatalf("a publish %s encoded at %d: %v", f.Type, p, err)
+ }
+ }
+ }
for _, f := range []wire.Frame{dispatch, check} {
for _, p := range []int{wire.Protocol15, wire.Protocol14, wire.Protocol9, wire.Protocol1} {
if _, err := wire.Encode(f, p); !errors.Is(err, wire.ErrProtocol) {
diff --git a/internal/wire/runners.go b/internal/wire/runners.go
index a1c77dc5..b15113c9 100644
--- a/internal/wire/runners.go
+++ b/internal/wire/runners.go
@@ -56,6 +56,7 @@ const (
Protocol28 = 28
Protocol29 = 29
Protocol30 = 30
+ Protocol31 = 31
// ProtocolSpend is the first protocol with a fix round's Feedback and
// a usage row's Turns; Encode drops both below it.
ProtocolSpend = Protocol3
@@ -194,7 +195,13 @@ const (
// Below it Encode drops the tool health and refuses the tool's call
// (downgradeStuck).
ProtocolStuckTasks = Protocol30
- ProtocolCurrent = ProtocolStuckTasks
+ // ProtocolPlaces adds places (places.go): a hello's reach and carlos
+ // health, a publish bound to its confirmed place in dispatch, check
+ // and report, and the place tools. Below it Encode drops the hello's
+ // fields and refuses a publish dispatch and the tools' calls
+ // (downgradePlaces).
+ ProtocolPlaces = Protocol31
+ ProtocolCurrent = ProtocolPlaces
)
// Runner roles. A person's first runner is the primary: the coordinator,
@@ -277,6 +284,9 @@ type Capabilities struct {
// Tools (ProtocolStuckTasks): whether the runner's pinned tools are
// installed and match their pins. Withheld until the welcome says 30.
Tools *ToolHealth `json:"tools,omitempty"`
+ // Reach (ProtocolPlaces): the CARLOS logins and deploy keys this
+ // runner holds, no secret. Withheld until the welcome says 31.
+ Reach *Reach `json:"reach,omitempty"`
}
// PreviewHost is a preview host a runner pairs with: its kind (an
@@ -374,6 +384,9 @@ func ValidCapabilities(c Capabilities) error {
if h := c.Tools; h != nil && !validToolHealth(*h) {
return ErrCapabilities
}
+ if r := c.Reach; r != nil && !validReach(*r) {
+ return ErrCapabilities
+ }
if err := checkStrings(reflect.ValueOf(c)); err != nil {
return err
}
@@ -630,12 +643,19 @@ func Encode(f Frame, protocol int) (Frame, error) {
return Frame{}, ErrProtocol
}
changed := false
+ if protocol < ProtocolPlaces {
+ dropped, err := downgradePlaces(body, protocol)
+ if err != nil {
+ return Frame{}, err
+ }
+ changed = dropped
+ }
if protocol < ProtocolStuckTasks {
dropped, err := downgradeStuck(body, protocol)
if err != nil {
return Frame{}, err
}
- changed = dropped
+ changed = changed || dropped
}
if protocol < ProtocolPinnedRelease {
if v, ok := body.(*ReleaseCommand); ok && v.Connection != "" {
diff --git a/internal/wire/runners_test.go b/internal/wire/runners_test.go
index cbf4fdd6..18379490 100644
--- a/internal/wire/runners_test.go
+++ b/internal/wire/runners_test.go
@@ -413,7 +413,7 @@ func TestEncodeBelowProtocol9DropsPreviews(t *testing.T) {
if _, err := wire.Encode(d, wire.ProtocolPreview); err != nil {
t.Fatal(err)
}
- if wire.ProtocolCurrent != wire.ProtocolStuckTasks || wire.ProtocolStuckTasks != 30 || wire.ProtocolPinnedRelease != 29 || wire.ProtocolInjectionDefences != 28 || wire.ProtocolWarm != 24 || wire.ProtocolGlance != 23 || wire.ProtocolJobs != 22 || wire.ProtocolCopy != 21 || wire.ProtocolUsageRefresh != 20 || wire.ProtocolAssistant != 19 || wire.ProtocolModels != 18 || wire.ProtocolOpenCode != 17 || wire.ProtocolPublish != 16 || wire.ProtocolReadings != 15 || wire.ProtocolScheduler != 14 || wire.ProtocolResearch != 13 || wire.ProtocolMetered != 12 || wire.ProtocolPreviewHost != 11 || wire.ProtocolExplore != 10 || wire.ProtocolPreview != 9 {
+ if wire.ProtocolCurrent != wire.ProtocolPlaces || wire.ProtocolStuckTasks != 30 || wire.ProtocolPinnedRelease != 29 || wire.ProtocolInjectionDefences != 28 || wire.ProtocolWarm != 24 || wire.ProtocolGlance != 23 || wire.ProtocolJobs != 22 || wire.ProtocolCopy != 21 || wire.ProtocolUsageRefresh != 20 || wire.ProtocolAssistant != 19 || wire.ProtocolModels != 18 || wire.ProtocolOpenCode != 17 || wire.ProtocolPublish != 16 || wire.ProtocolReadings != 15 || wire.ProtocolScheduler != 14 || wire.ProtocolResearch != 13 || wire.ProtocolMetered != 12 || wire.ProtocolPreviewHost != 11 || wire.ProtocolExplore != 10 || wire.ProtocolPreview != 9 {
t.Fatalf("current %d", wire.ProtocolCurrent)
}
}
diff --git a/internal/wire/schedule_test.go b/internal/wire/schedule_test.go
index 50478281..5eab12b5 100644
--- a/internal/wire/schedule_test.go
+++ b/internal/wire/schedule_test.go
@@ -17,7 +17,7 @@ import (
// refused anything that spends, never handed it), and a dispatch loses
// its priority, deadline and release; what 13 already had is unchanged.
func TestEncodeBelowProtocol14DropsScheduler(t *testing.T) {
- if wire.ProtocolScheduler != wire.Protocol14 || wire.ProtocolCurrent != wire.Protocol30 {
+ if wire.ProtocolScheduler != wire.Protocol14 || wire.ProtocolCurrent != wire.Protocol31 {
t.Fatalf("scheduler %d, current %d", wire.ProtocolScheduler, wire.ProtocolCurrent)
}
by := time.Date(2026, 11, 20, 17, 0, 0, 0, time.UTC)
diff --git a/internal/wire/stuck.go b/internal/wire/stuck.go
index 6d930a7a..29ead530 100644
--- a/internal/wire/stuck.go
+++ b/internal/wire/stuck.go
@@ -39,6 +39,10 @@ const RetriedByCoordinator = "coordinator"
type ToolHealth struct {
Scanner string `json:"scanner"`
Renderer string `json:"renderer,omitempty"`
+ // Carlos (ProtocolPlaces) is the carlos CLI's health (CarlosOK and
+ // the rest) and CarlosVersion the release it said, vX.Y.Z.
+ Carlos string `json:"carlos,omitempty"`
+ CarlosVersion string `json:"carlos_version,omitempty"`
}
// Tool health states. ToolUnknown is the instance's word for a runner
@@ -56,7 +60,7 @@ var toolStates = []string{ToolHealthy, ToolMissing, ToolMismatch, ToolUnpinned}
// validToolHealth reports whether a runner's report is in the fixed set:
// the scanner always said, the renderer only when there is one.
func validToolHealth(h ToolHealth) bool {
- return slices.Contains(toolStates, h.Scanner) && (h.Renderer == "" || slices.Contains(toolStates, h.Renderer))
+ return slices.Contains(toolStates, h.Scanner) && (h.Renderer == "" || slices.Contains(toolStates, h.Renderer)) && validCarlosHealth(h.Carlos, h.CarlosVersion)
}
// WithoutToolHealth drops a hello's tool health, in a copy. The first
diff --git a/internal/wire/stuck_test.go b/internal/wire/stuck_test.go
index 337db477..ea32482a 100644
--- a/internal/wire/stuck_test.go
+++ b/internal/wire/stuck_test.go
@@ -14,7 +14,7 @@ import (
// Stuck tasks (protocol 30): a hello's tool health is a fixed state per
// pinned tool, never a path, and an older instance never hears it.
func TestProtocol30ToolHealth(t *testing.T) {
- if wire.ProtocolStuckTasks != wire.Protocol30 || wire.ProtocolCurrent != wire.Protocol30 || wire.Spoken(99) != 30 {
+ if wire.ProtocolStuckTasks != wire.Protocol30 || wire.ProtocolCurrent != wire.Protocol31 || wire.Spoken(99) != 31 {
t.Fatalf("stuck %d, current %d", wire.ProtocolStuckTasks, wire.ProtocolCurrent)
}
caps := func(h *wire.ToolHealth) wire.Capabilities {
diff --git a/internal/wire/tasks.go b/internal/wire/tasks.go
index 6ea9b383..e243e196 100644
--- a/internal/wire/tasks.go
+++ b/internal/wire/tasks.go
@@ -1087,6 +1087,14 @@ var StepReasons = map[string]bool{
"publish_failed": true,
// The account already holds the app's name: nothing was deployed.
"publish_app_taken": true,
+ // Places (protocol 31).
+ "carlos_outdated": true,
+ "publish_secrets": true,
+ "publish_scanner": true,
+ "publish_key_missing": true,
+ "publish_mint_failed": true,
+ "publish_app_missing": true,
+ "publish_app_unproven": true,
// Connections: the provider refused on quota and no other connection
// could take the attempt over (limited); nothing the person connected
// can run this specialist (no_connection).
diff --git a/internal/wire/usage_test.go b/internal/wire/usage_test.go
index 2eeede17..5b254189 100644
--- a/internal/wire/usage_test.go
+++ b/internal/wire/usage_test.go
@@ -44,7 +44,7 @@ func headrooms(t *testing.T, raw []byte) []map[string]json.RawMessage {
// decodes strictly against the frozen protocol 14 headroom, and the
// caller's own values are untouched; at 15 nothing changes.
func TestEncodeBelowProtocol15DropsReadingTimes(t *testing.T) {
- if wire.ProtocolReadings != wire.Protocol15 || wire.ProtocolCurrent != wire.Protocol30 {
+ if wire.ProtocolReadings != wire.Protocol15 || wire.ProtocolCurrent != wire.Protocol31 {
t.Fatalf("readings %d, current %d", wire.ProtocolReadings, wire.ProtocolCurrent)
}
at := time.Date(2026, 11, 12, 9, 58, 0, 0, time.UTC)
diff --git a/internal/wire/warm_test.go b/internal/wire/warm_test.go
index 81358c7d..87fa4419 100644
--- a/internal/wire/warm_test.go
+++ b/internal/wire/warm_test.go
@@ -13,7 +13,7 @@ import (
// other (durable, acked), and Encode refuses it below 24: an older
// runner's strict decoder would close the stream on it.
func TestEncodeWarmBelow24(t *testing.T) {
- if wire.ProtocolWarm != 24 || wire.ProtocolCurrent != wire.ProtocolStuckTasks || wire.Spoken(99) != 30 {
+ if wire.ProtocolWarm != 24 || wire.ProtocolCurrent != wire.ProtocolPlaces || wire.Spoken(99) != 31 {
t.Fatalf("protocols %d %d", wire.ProtocolWarm, wire.ProtocolCurrent)
}
f, err := wire.NewFrame("c1", wire.FrameWarm, wire.WarmCommand{Person: "ana@example.com"})