Merge remote-tracking branch 'origin/main' into managed-fleets-1b
# Conflicts: # internal/provision/testdata/plan14-root-reads-chain.tsv
22 files changed,
+1,520
−23
apimode.go+7 −1copy-review/result.json+150 −0copy-review/strings.json+114 −0deploy.go+80 −15deploy_first.go+198 −0deploy_first_cli_test.go+145 −0deploy_first_copy.go+39 −0deploy_first_preflight.go+63 −0deploy_first_preflight_test.go+46 −0deploy_first_test.go+470 −0docs/site/cli.md+6 −0docs/site/plans.md+1 −1docs/superpowers/notes/census-proposal-first-deploy-493.md+23 −0docs/superpowers/notes/census-proposal-managed-fleets-1b.md+1 −1docs/superpowers/reviews/CODEX-REVIEW-BRIEF-checkout-tax-id.md+23 −0docs/superpowers/reviews/first-deploy-493-brief.md+7 −0docs/superpowers/reviews/first-deploy-493-opus.md+63 −0internal/billingstripe/prepared.go+12 −2internal/billingstripe/prepared_test.go+61 −1internal/provision/testdata/plan14-root-reads-chain.tsv+2 −1internal/provision/testdata/plan14-root-reads-first-deploy-493.tsv+8 −0internal/provision/testdata/plan14-root-reads-managed-fleets-1b.tsv+1 −1
CI passed — run details
diff --git a/apimode.go b/apimode.go| index 0c364f827..57190d25e 100644 |
| --- a/apimode.go |
| +++ b/apimode.go |
| @@ -3854,6 +3854,8 @@ func (s *apiSession) instanceSetRateLimit(ctx context.Context, a apiAcct, app, h |
| // predates Task 9 sends no "total" field at all, which decodes as 0 — the |
| // CLI printer treats that as "unknown" rather than "zero matches", since a |
| // non-empty recs slice from the same response proves it isn't really zero. |
| +type apiInstancesMissing struct{ error } |
| + |
| func (s *apiSession) instanceList(ctx context.Context, a apiAcct, app, match, health string) ([]apiInstanceRecord, bool, int, error) { |
| tail := "/instances" |
| v := url.Values{} |
| @@ -3871,7 +3873,11 @@ func (s *apiSession) instanceList(ctx context.Context, a apiAcct, app, match, he |
| return nil, false, 0, err |
| } |
| if status != http.StatusOK { |
| - return nil, false, 0, apiErrorFromBody(status, body) |
| + err := apiErrorFromBody(status, body) |
| + if status == http.StatusNotFound { |
| + err = &apiInstancesMissing{err} |
| + } |
| + return nil, false, 0, err |
| } |
| var res struct { |
| Instances []apiInstanceRecord `json:"instances"` |
diff --git a/copy-review/result.json b/copy-review/result.json| new file mode 100644 |
| index 000000000..fc2c78d39 |
| --- /dev/null |
| +++ b/copy-review/result.json |
| @@ -0,0 +1,150 @@ |
| +{ |
| + "action": "approve", |
| + "guidance": null, |
| + "strings": [ |
| + { |
| + "id": "FD-C1", |
| + "text": "app {app} already exists. If it is in the Trash, restore it before deploying.", |
| + "original": "app {app} already exists. If it is in the Trash, restore it before deploying.", |
| + "edited": false, |
| + "rerolled": false, |
| + "rerolls": [], |
| + "done": false |
| + }, |
| + { |
| + "id": "FD-C2", |
| + "text": "created app {app} in account {account}", |
| + "original": "created app {app} in account {account}", |
| + "edited": false, |
| + "rerolled": false, |
| + "rerolls": [], |
| + "done": false |
| + }, |
| + { |
| + "id": "FD-C3", |
| + "text": "could not check whether {app} exists: {error}", |
| + "original": "could not check whether {app} exists: {error}", |
| + "edited": false, |
| + "rerolled": false, |
| + "rerolls": [], |
| + "done": false |
| + }, |
| + { |
| + "id": "FD-C4", |
| + "text": "no release channel was chosen, so no instance was created.", |
| + "original": "no release channel was chosen, so no instance was created.", |
| + "edited": false, |
| + "rerolled": false, |
| + "rerolls": [], |
| + "done": false |
| + }, |
| + { |
| + "id": "FD-C5", |
| + "text": "the console did not provide an instance domain for {app}. No instance was created.", |
| + "original": "the console did not provide an instance domain for {app}. No instance was created.", |
| + "edited": false, |
| + "rerolled": false, |
| + "rerolls": [], |
| + "done": false |
| + }, |
| + { |
| + "id": "FD-C6", |
| + "text": "created instance {host} on channel {channel}", |
| + "original": "created instance {host} on channel {channel}", |
| + "edited": false, |
| + "rerolled": false, |
| + "rerolls": [], |
| + "done": false |
| + }, |
| + { |
| + "id": "FD-C7", |
| + "text": "env argument {n} is not a KEY=value pair", |
| + "original": "env argument {n} is not a KEY=value pair", |
| + "edited": false, |
| + "rerolled": false, |
| + "rerolls": [], |
| + "done": false |
| + }, |
| + { |
| + "id": "FD-C8", |
| + "text": "env argument {n} has an invalid variable name. Use letters, digits and underscores, starting with a letter or underscore.", |
| + "original": "env argument {n} has an invalid variable name. Use letters, digits and underscores, starting with a letter or underscore.", |
| + "edited": false, |
| + "rerolled": false, |
| + "rerolls": [], |
| + "done": false |
| + }, |
| + { |
| + "id": "FD-C9", |
| + "text": "env argument {n} contains a backslash, quote, newline or NUL in its value.", |
| + "original": "env argument {n} contains a backslash, quote, newline or NUL in its value.", |
| + "edited": false, |
| + "rerolled": false, |
| + "rerolls": [], |
| + "done": false |
| + }, |
| + { |
| + "id": "FD-C10", |
| + "text": "cannot determine the environment bundle for {host}. No environment variables were changed.", |
| + "original": "cannot determine the environment bundle for {host}. No environment variables were changed.", |
| + "edited": false, |
| + "rerolled": false, |
| + "rerolls": [], |
| + "done": false |
| + }, |
| + { |
| + "id": "FD-C11", |
| + "text": "the selected instances use different environment bundles. Select one with --host. No environment variables were changed.", |
| + "original": "the selected instances use different environment bundles. Select one with --host. No environment variables were changed.", |
| + "edited": false, |
| + "rerolled": false, |
| + "rerolls": [], |
| + "done": false |
| + }, |
| + { |
| + "id": "FD-C12", |
| + "text": "no instance serves the selected channel. No environment variables were changed.", |
| + "original": "no instance serves the selected channel. No environment variables were changed.", |
| + "edited": false, |
| + "rerolled": false, |
| + "rerolls": [], |
| + "done": false |
| + }, |
| + { |
| + "id": "FD-C13", |
| + "text": "set an ordinary environment variable before shipping; repeat for more variables", |
| + "original": "set an ordinary environment variable before shipping; repeat for more variables", |
| + "edited": false, |
| + "rerolled": false, |
| + "rerolls": [], |
| + "done": false |
| + }, |
| + { |
| + "id": "FD-C14", |
| + "text": "deploy supports binary or static artifacts", |
| + "original": "deploy supports binary or static artifacts", |
| + "edited": false, |
| + "rerolled": false, |
| + "rerolls": [], |
| + "done": false |
| + }, |
| + { |
| + "id": "FD-C15", |
| + "text": "pass a file for a binary deploy, or one directory for a static deploy", |
| + "original": "pass a file for a binary deploy, or one directory for a static deploy", |
| + "edited": false, |
| + "rerolled": false, |
| + "rerolls": [], |
| + "done": false |
| + }, |
| + { |
| + "id": "FD-D1", |
| + "text": "`carlos deploy --app hello --env PORT=8080 ./hello` creates the app and its first instance if they are missing, then deploys your built binary and waits for it to serve. Existing instances stay unchanged. Use `--region` to choose a new app’s region; for an existing app, it checks the region.\n\nRepeat `--env KEY=value` to set ordinary variables before shipping. They go into the environment bundle shared by the selected instances. If those instances use different bundles, select one with `--host`. Values are not printed, but remain in shell history; use `carlos secrets set` for secrets.\n\nThe console must support instances and provide a platform domain. Trashed apps are not restored. If setup fails partway through, the app, instance or variables already created remain. Fix the reported error and retry.", |
| + "original": "`carlos deploy --app hello --env PORT=8080 ./hello` creates the app and its first instance if they are missing, then deploys your built binary and waits for it to serve. Existing instances stay unchanged. Use `--region` to choose a new app’s region; for an existing app, it checks the region.\n\nRepeat `--env KEY=value` to set ordinary variables before shipping. They go into the environment bundle shared by the selected instances. If those instances use different bundles, select one with `--host`. Values are not printed, but remain in shell history; use `carlos secrets set` for secrets.\n\nThe console must support instances and provide a platform domain. Trashed apps are not restored. If setup fails partway through, the app, instance or variables already created remain. Fix the reported error and retry.", |
| + "edited": false, |
| + "rerolled": false, |
| + "rerolls": [], |
| + "done": false |
| + } |
| + ] |
| +} |
diff --git a/copy-review/strings.json b/copy-review/strings.json| new file mode 100644 |
| index 000000000..bf3caaf00 |
| --- /dev/null |
| +++ b/copy-review/strings.json |
| @@ -0,0 +1,114 @@ |
| +[ |
| + { |
| + "id": "FD-C1", |
| + "section": "app", |
| + "label": "app name taken", |
| + "text": "app {app} already exists. If it is in the Trash, restore it before deploying.", |
| + "context": "Shown when a second lookup finds that the app name is already in use, including in the Trash. Deploy stops without restoring it." |
| + }, |
| + { |
| + "id": "FD-C2", |
| + "section": "app", |
| + "label": "app created", |
| + "text": "created app {app} in account {account}", |
| + "context": "Printed after a new app is created. The next line reports its region." |
| + }, |
| + { |
| + "id": "FD-C3", |
| + "section": "app", |
| + "label": "app list failed", |
| + "text": "could not check whether {app} exists: {error}", |
| + "context": "Shown when deploy cannot verify that an app name is unused. It stops before trying to create the app." |
| + }, |
| + { |
| + "id": "FD-C4", |
| + "section": "instance", |
| + "label": "channel required", |
| + "text": "no release channel was chosen, so no instance was created.", |
| + "context": "Shown if deploy has no channel to use for the first instance. It stops before creating the instance." |
| + }, |
| + { |
| + "id": "FD-C5", |
| + "section": "instance", |
| + "label": "no domain", |
| + "text": "the console did not provide an instance domain for {app}. No instance was created.", |
| + "context": "Shown when the console returns no domain for the default instance address. The app may already have been created." |
| + }, |
| + { |
| + "id": "FD-C6", |
| + "section": "instance", |
| + "label": "instance created", |
| + "text": "created instance {host} on channel {channel}", |
| + "context": "Printed after the first instance is created. It names the address and release channel." |
| + }, |
| + { |
| + "id": "FD-C7", |
| + "section": "env", |
| + "label": "env not a pair", |
| + "text": "env argument {n} is not a KEY=value pair", |
| + "context": "Shown before contacting the console when a --env argument is missing a name or equals sign. Only its position is printed so a secret cannot leak into the error." |
| + }, |
| + { |
| + "id": "FD-C8", |
| + "section": "env", |
| + "label": "env bad name", |
| + "text": "env argument {n} has an invalid variable name. Use letters, digits and underscores, starting with a letter or underscore.", |
| + "context": "Shown before contacting the console for an invalid --env variable name. The argument itself is not printed." |
| + }, |
| + { |
| + "id": "FD-C9", |
| + "section": "env", |
| + "label": "env bad value", |
| + "text": "env argument {n} contains a backslash, quote, newline or NUL in its value.", |
| + "context": "Shown before contacting the console when an environment value cannot be delivered to an instance. The value is not printed." |
| + }, |
| + { |
| + "id": "FD-C10", |
| + "section": "env", |
| + "label": "watched host has no route", |
| + "text": "cannot determine the environment bundle for {host}. No environment variables were changed.", |
| + "context": "Shown when deploy cannot match a selected hostname to an environment bundle. It stops before writing the variables." |
| + }, |
| + { |
| + "id": "FD-C11", |
| + "section": "env", |
| + "label": "mixed bundles", |
| + "text": "the selected instances use different environment bundles. Select one with --host. No environment variables were changed.", |
| + "context": "Shown when --env would affect instances using different environment bundles. The user can narrow the deploy with --host." |
| + }, |
| + { |
| + "id": "FD-C12", |
| + "section": "env", |
| + "label": "routes but none watched", |
| + "text": "no instance serves the selected channel. No environment variables were changed.", |
| + "context": "Shown when --env is supplied but no instance serves the chosen channel. It stops before writing variables." |
| + }, |
| + { |
| + "id": "FD-C13", |
| + "section": "Deploy help", |
| + "label": "Environment flag help", |
| + "text": "set an ordinary environment variable before shipping; repeat for more variables", |
| + "context": "Shown beside --env in deploy help. The value has the form KEY=value." |
| + }, |
| + { |
| + "id": "FD-C14", |
| + "section": "Deploy help", |
| + "label": "Unsupported artifact kind", |
| + "text": "deploy supports binary or static artifacts", |
| + "context": "Shown before setup when --kind is neither binary nor static." |
| + }, |
| + { |
| + "id": "FD-C15", |
| + "section": "Deploy help", |
| + "label": "Wrong artifact shape", |
| + "text": "pass a file for a binary deploy, or one directory for a static deploy", |
| + "context": "Shown before setup when the artifact does not match the selected kind." |
| + }, |
| + { |
| + "id": "FD-D1", |
| + "section": "Documentation", |
| + "label": "First deploy documentation", |
| + "text": "`carlos deploy --app hello --env PORT=8080 ./hello` creates the app and its first instance if they are missing, then deploys your built binary and waits for it to serve. Existing instances stay unchanged. Use `--region` to choose a new app\u2019s region; for an existing app, it checks the region.\n\nRepeat `--env KEY=value` to set ordinary variables before shipping. They go into the environment bundle shared by the selected instances. If those instances use different bundles, select one with `--host`. Values are not printed, but remain in shell history; use `carlos secrets set` for secrets.\n\nThe console must support instances and provide a platform domain. Trashed apps are not restored. If setup fails partway through, the app, instance or variables already created remain. Fix the reported error and retry.", |
| + "context": "New text in the carlos deploy documentation, beside the first command example." |
| + } |
| +] |
diff --git a/deploy.go b/deploy.go| index 9e4e3f33b..63eae5ca9 100644 |
| --- a/deploy.go |
| +++ b/deploy.go |
| @@ -159,9 +159,15 @@ func runDeploy(args []string) { |
| swap := fs.String("swap", "", shipSwapFlagHelp) |
| var assets assetPathsFlag |
| fs.Var(&assets, "assets", shipAssetsFlagHelp) |
| + var envValues deployEnvFlag |
| + fs.Var(&envValues, "env", deployEnvFlagHelp) |
| noAssets := fs.Bool("no-assets", false, deployNoAssetsFlagHelp) |
| fs.Usage = flagUsage(fs, "") |
| fs.Parse(args) |
| + envSet, envErr := parseDeployEnv(envValues) |
| + if envErr != nil { |
| + log.Fatalf("deploy: %v", envErr) |
| + } |
| usage := "usage: carlos deploy --app <a> [--version <sha>] [--kind binary|static] [--target linux-arm64] " + |
| "[--account <sqid-or-name>] [--account-id <sqid>] [--console <origin> | -d <destination>] [--capabilities <file.json>] " + |
| "[--channel <ch>] [--host <host>] [--region <code>] [--label <text>] [--notes <text>] [--swap hold] [--assets <folder>]... [--no-assets] [--temporary] [--ttl 7d] [--timeout 120s] <files-or-site-dir>\n" + // C11.23 |
| @@ -260,14 +266,6 @@ func runDeploy(args []string) { |
| log.Fatal(usage) |
| } |
| } |
| - // --region on an app that already exists is checked against the app's |
| - // stored region before anything is read or shipped (spec §11). |
| - if r := strings.TrimSpace(*regionFlag); r != "" && !createdNow { |
| - res, err := sess.appRegions(ctx, acct, *app) |
| - if err := deployRegionPreflight(res, err, *app, r); err != nil { |
| - log.Fatalf("deploy: %v", err) |
| - } |
| - } |
| if capsSet == nil { |
| if capsSet, err = readCapabilities(*capsFile, *app); err != nil { |
| log.Fatal(err) |
| @@ -371,10 +369,60 @@ func runDeploy(args []string) { |
| "save these as this project's deploy defaults") |
| } |
| - recs, _, _, err := sess.instanceList(ctx, acct, *app, "", "") |
| + message, merr := resolveMutationMessage(fs, messageFlags) |
| + if merr != nil { |
| + log.Fatalf("deploy: %v", merr) |
| + } |
| + if err := deployArtifactPreflight(fs.Args(), *kind, *target); err != nil { |
| + log.Fatalf("deploy: %v", err) |
| + } |
| + recs, truncated, total, err := sess.instanceList(ctx, acct, *app, "", "") |
| + var missing *apiInstancesMissing |
| + if errors.As(err, &missing) && !createdNow { |
| + var createErr error |
| + createdNow, createErr = ensureDeployApp(ctx, sess, acct, *app, strings.TrimSpace(*regionFlag)) |
| + if createErr != nil { |
| + log.Fatalf("deploy: %v", createErr) |
| + } |
| + if createdNow { |
| + recs, truncated, total, err = sess.instanceList(ctx, acct, *app, "", "") |
| + } |
| + } |
| if err != nil { |
| log.Fatalf("deploy: list instances: %v", err) |
| } |
| + // --region on an app that already exists is checked against the app's |
| + // stored region before anything is read or shipped (spec §11). |
| + if r := strings.TrimSpace(*regionFlag); r != "" && !createdNow { |
| + res, err := sess.appRegions(ctx, acct, *app) |
| + if err := deployRegionPreflight(res, err, *app, r); err != nil { |
| + log.Fatalf("deploy: %v", err) |
| + } |
| + } |
| + if *kind == "binary" && len(recs) == 0 && !truncated && total == 0 { |
| + channels, channelsErr := sess.channels(ctx, acct, *app) |
| + if channelsErr != nil && createdNow { |
| + log.Fatalf("deploy: %v", channelsErr) |
| + } |
| + // A new app has its pipeline but no promoted channel yet. Legacy |
| + // and previously deployed apps keep their existing no-route behavior. |
| + if channelsErr == nil && channels.PipelineEntry != "" && len(channels.Channels) == 0 { |
| + firstChannel := *channelFlag |
| + if firstChannel == "" { |
| + firstChannel = channels.PipelineEntry |
| + } |
| + rec, createErr := createDeployInstance(ctx, sess, acct, *app, firstChannel, *hostFlag, message) |
| + var denied *enableError |
| + if !createdNow && errors.As(createErr, &denied) && denied.status == http.StatusForbidden { |
| + // A deploy credential can publish to an existing app without |
| + // permission to enable instances. Keep that no-instance path. |
| + } else if createErr != nil { |
| + log.Fatalf("deploy: %v", createErr) |
| + } else { |
| + recs = []apiInstanceRecord{rec} |
| + } |
| + } |
| + } |
| channel, hosts, staticDeploy, err := deployTargets(recs, *kind, *channelFlag, *hostFlag, |
| func() (apiChannelsResult, error) { return sess.channels(ctx, acct, *app) }) |
| if errors.Is(err, errAmbiguousChannel) && *channelFlag == "" && interactiveTerminal() { |
| @@ -390,12 +438,6 @@ func runDeploy(args []string) { |
| if err != nil && !errors.Is(err, errNoStaticHost) { |
| log.Fatalf("deploy: %v", err) |
| } |
| - // Resolve once, before any route, release or channel write. Both halves |
| - // of deploy carry the same context and neither asks a second question. |
| - message, merr := resolveMutationMessage(fs, messageFlags) |
| - if merr != nil { |
| - log.Fatalf("deploy: %v", merr) |
| - } |
| // A static app with nothing serving it yet: mint its platform host |
| // rather than refusing (#186's static half). Typed, never text-matched, |
| // and BEFORE the ship — attachUnclaimedHost's ordering, so a failed mint |
| @@ -412,6 +454,7 @@ func runDeploy(args []string) { |
| switch { |
| case mintErr == nil: |
| hosts, err = []string{host}, nil |
| + recs = append(recs, apiInstanceRecord{Host: host, Channel: channel, Kind: "static"}) |
| case enableUnavailable(mintErr): |
| // This deployment has no platform host to give — no apps domain, |
| // or an operator-pinned instance domain. The original refusal is |
| @@ -431,6 +474,28 @@ func runDeploy(args []string) { |
| if staticDeploy && *hostFlag != "" { |
| attachUnclaimedHost(ctx, sess, acct, *app, *hostFlag, *kind, channel, recs, message) |
| } |
| + if len(envSet) > 0 { |
| + if staticDeploy && *hostFlag != "" { |
| + recs, truncated, total, err = sess.instanceList(ctx, acct, *app, "", "") |
| + if err != nil { |
| + log.Fatalf("deploy: list instances: %v", err) |
| + } |
| + } |
| + if truncated { |
| + log.Fatal(fillDeployCopy(deployFirstEnvHostMissing, "host", *app)) |
| + } |
| + bundle, bundleErr := deployEnvBundle(recs, hosts) |
| + if bundleErr != nil { |
| + log.Fatalf("deploy: %v", bundleErr) |
| + } |
| + res, configErr := sess.configApply(ctx, acct, *app, |
| + apiConfigApply{Environment: bundle, Set: envSet, Message: message}) |
| + if configErr != nil { |
| + log.Fatalf("deploy: %v", configErr) |
| + } |
| + fmt.Fprintf(stdout, "%s %d env var(s) for %s (%s)\n", colorFor(stdout).ok("set"), len(envSet), *app, bundleLabel(bundle)) |
| + printRestartNotice(stdout, *app, restartFromAPI(res.Restart)) |
| + } |
| // printBanner=false: the "using ..." line already printed above, before |
| // the instance list — so a listing failure still names the console — |
| // and runShipAPI would otherwise print it a second time. |
diff --git a/deploy_first.go b/deploy_first.go| new file mode 100644 |
| index 000000000..8371659bb |
| --- /dev/null |
| +++ b/deploy_first.go |
| @@ -0,0 +1,198 @@ |
| +package main |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "strconv" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| +) |
| + |
| +// Core helpers for a first deploy (#493). They hold the safety rules; the |
| +// caller in deploy.go decides when to use them. User-facing text lives in |
| +// deploy_first_copy.go. |
| + |
| +// Typed refusals, so callers and tests match on the kind of refusal and not |
| +// on text that is still pending review. |
| +var ( |
| + errDeployAppExists = errors.New("deploy: app exists") |
| + errDeployAppListFailed = errors.New("deploy: app list failed") |
| + errDeployChannelRequired = errors.New("deploy: channel required") |
| + errDeployDomainMissing = errors.New("deploy: no instance domain") |
| + errDeployEnvHostMissing = errors.New("deploy: watched host has no record") |
| + errDeployEnvMixed = errors.New("deploy: mixed environments") |
| + errDeployEnvNoWatchedHost = errors.New("deploy: no watched hosts") |
| +) |
| + |
| +// deployRefusal carries a kind and the (reviewed) text. Error() returns the |
| +// text; Is matches the kind. |
| +type deployRefusal struct { |
| + kind error |
| + text string |
| + cause error |
| +} |
| + |
| +func (r *deployRefusal) Error() string { return r.text } |
| +func (r *deployRefusal) Unwrap() error { return r.cause } |
| +func (r *deployRefusal) Is(target error) bool { return target == r.kind } |
| + |
| +func refuseDeploy(kind error, tmpl string, kv ...string) error { |
| + return &deployRefusal{kind: kind, text: fillDeployCopy(tmpl, kv...)} |
| +} |
| + |
| +// fillDeployCopy replaces {name} placeholders. kv is name, value pairs. It is |
| +// deliberately not a printf wrapper: the templates are empty until reviewed. |
| +func fillDeployCopy(tmpl string, kv ...string) string { |
| + args := make([]string, 0, len(kv)) |
| + for i := 0; i+1 < len(kv); i += 2 { |
| + args = append(args, "{"+kv[i]+"}", kv[i+1]) |
| + } |
| + return strings.NewReplacer(args...).Replace(tmpl) |
| +} |
| + |
| +// acctMatches reports whether the membership entry is the account a names. |
| +func acctMatches(e apiAccountEntry, a apiAcct) bool { |
| + if a.Exact { |
| + return e.Sqid == a.Seg |
| + } |
| + return e.Sqid == a.Seg || strings.EqualFold(e.Name, a.Seg) |
| +} |
| + |
| +// ensureDeployApp creates app when, and only when, the account's own listings |
| +// prove the name is free. A console that cannot list memberships, or an |
| +// account that is not one of them, returns (false, nil) so the next call |
| +// meets the ordinary API refusal. A name that is listed, live or in the |
| +// Trash, is never recreated or restored. Absence is never read from a 404. |
| +func ensureDeployApp(ctx context.Context, sess *apiSession, acct apiAcct, app, region string) (created bool, err error) { |
| + accts, supported, err := sess.listAccounts(ctx) |
| + if err != nil { |
| + return false, err |
| + } |
| + if !supported { |
| + return false, nil |
| + } |
| + var member *apiAccountEntry |
| + for i := range accts { |
| + if acctMatches(accts[i], acct) { |
| + if member != nil { |
| + return false, nil |
| + } |
| + member = &accts[i] |
| + } |
| + } |
| + if member == nil { |
| + return false, nil |
| + } |
| + for _, a := range member.Apps { |
| + if a == app { |
| + return false, nil |
| + } |
| + } |
| + // Not in the live membership list. The Trash lives only in appList. |
| + rows, err := sess.appList(ctx, acct) |
| + if err != nil { |
| + return false, &deployRefusal{kind: errDeployAppListFailed, text: fillDeployCopy(deployFirstAppListFailed, "app", app, "error", err.Error()), cause: err} |
| + } |
| + for _, r := range rows { |
| + if r.App == app { |
| + return false, refuseDeploy(errDeployAppExists, deployFirstAppExists, "app", app) |
| + } |
| + } |
| + res, err := sess.createApp(ctx, acct, app, "", false, "", region, detectTimezone()) |
| + if err != nil { |
| + return false, err |
| + } |
| + fmt.Fprintln(stdout, fillDeployCopy(deployFirstAppCreated, "app", app, "account", res.Account)) |
| + printAppRegion(stdout, res, region, false) |
| + return true, nil |
| +} |
| + |
| +// createDeployInstance enables instances for the app (preserving any existing |
| +// manifest: every option is nil) and creates the first instance. The caller |
| +// has already resolved channel; host "" means app + "." + the manifest's |
| +// domain. The host, region (inherited from the app) and kind (instance) go to |
| +// the create door, which validates them; nothing here bypasses it. |
| +func createDeployInstance(ctx context.Context, sess *apiSession, acct apiAcct, app, channel, host, message string) (apiInstanceRecord, error) { |
| + if channel == "" { |
| + return apiInstanceRecord{}, refuseDeploy(errDeployChannelRequired, deployFirstChannelRequired) |
| + } |
| + m, err := sess.instancesEnable(ctx, acct, app, nil, nil, nil) |
| + if err != nil { |
| + return apiInstanceRecord{}, err |
| + } |
| + if host == "" { |
| + if m.Domain == "" { |
| + return apiInstanceRecord{}, refuseDeploy(errDeployDomainMissing, deployFirstDomainMissing, "app", app) |
| + } |
| + host = app + "." + m.Domain |
| + } |
| + rec, err := sess.instanceCreate(ctx, acct, app, host, "", channel, "instance", "", nil, nil, nil, message) |
| + if err != nil { |
| + return apiInstanceRecord{}, err |
| + } |
| + fmt.Fprintln(stdout, fillDeployCopy(deployFirstInstanceCreated, "host", rec.Host, "channel", rec.Channel)) |
| + return rec, nil |
| +} |
| + |
| +// parseDeployEnv turns --env KEY=value arguments into config vars. Errors name |
| +// the argument's position, never its text: a mistyped argument may be a secret. |
| +func parseDeployEnv(args []string) (map[string]appconfig.Var, error) { |
| + if len(args) == 0 { |
| + return nil, nil |
| + } |
| + if _, err := parseKV(args); err != nil { |
| + // parseKV reports the position of the first bad pair. |
| + for i, a := range args { |
| + if k, _, ok := strings.Cut(a, "="); !ok || k == "" { |
| + return nil, errors.New(fillDeployCopy(deployFirstEnvBadPair, "n", strconv.Itoa(i+1))) |
| + } |
| + } |
| + return nil, errors.New(fillDeployCopy(deployFirstEnvBadPair, "n", "0")) |
| + } |
| + out := make(map[string]appconfig.Var, len(args)) |
| + for i, a := range args { |
| + k, v, _ := strings.Cut(a, "=") |
| + n := strconv.Itoa(i + 1) |
| + if !appconfig.ValidVarName(k) { |
| + return nil, errors.New(fillDeployCopy(deployFirstEnvBadName, "n", n)) |
| + } |
| + if err := appconfig.ValidVarValue(v); err != nil { |
| + return nil, errors.New(fillDeployCopy(deployFirstEnvBadValue, "n", n)) |
| + } |
| + out[k] = appconfig.Var{Kind: "env", Value: v} // a repeated key: the last wins, as parseKV |
| + } |
| + return out, nil |
| +} |
| + |
| +// deployEnvBundle names the one config bundle the watched hosts share ("" is |
| +// the default bundle). No records and no hosts is a first deploy: the default. |
| +// Records with no watched host, a watched host with no record, or hosts bound |
| +// to different bundles are refused, so config is never written to a bundle |
| +// nothing watched is served from. |
| +func deployEnvBundle(recs []apiInstanceRecord, hosts []string) (string, error) { |
| + if len(recs) == 0 && len(hosts) == 0 { |
| + return "", nil |
| + } |
| + if len(hosts) == 0 { |
| + return "", refuseDeploy(errDeployEnvNoWatchedHost, deployFirstEnvNoHosts) |
| + } |
| + byHost := make(map[string]string, len(recs)) |
| + for _, r := range recs { |
| + byHost[strings.ToLower(r.Host)] = r.Environment |
| + } |
| + bundle, first := "", true |
| + for _, h := range hosts { |
| + env, ok := byHost[strings.ToLower(h)] |
| + if !ok { |
| + return "", refuseDeploy(errDeployEnvHostMissing, deployFirstEnvHostMissing, "host", h) |
| + } |
| + if first { |
| + bundle, first = env, false |
| + } else if env != bundle { |
| + return "", refuseDeploy(errDeployEnvMixed, deployFirstEnvMixed) |
| + } |
| + } |
| + return bundle, nil |
| +} |
diff --git a/deploy_first_cli_test.go b/deploy_first_cli_test.go| new file mode 100644 |
| index 000000000..d0318532f |
| --- /dev/null |
| +++ b/deploy_first_cli_test.go |
| @@ -0,0 +1,145 @@ |
| +package main |
| + |
| +import ( |
| + "encoding/json" |
| + "net/http" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestFirstDeployCLI(t *testing.T) { |
| + bin := buildCarlos(t) |
| + for _, scenario := range []string{"new", "existing", "restricted", "unavailable", "bad artifact", "bad env"} { |
| + t.Run(scenario, func(t *testing.T) { |
| + exists := scenario == "existing" || scenario == "restricted" |
| + handlers := map[string]func(http.ResponseWriter, []byte){} |
| + handlers["GET /api/cli/apps/ops/hello/instances"] = func(w http.ResponseWriter, _ []byte) { |
| + if scenario == "unavailable" { |
| + w.WriteHeader(503) |
| + return |
| + } |
| + if !exists { |
| + w.WriteHeader(404) |
| + return |
| + } |
| + if scenario == "existing" { |
| + json.NewEncoder(w).Encode(map[string]any{"instances": []apiInstanceRecord{{Host: "hello.test", Channel: "edge", Environment: "preview"}}}) |
| + return |
| + } |
| + json.NewEncoder(w).Encode(map[string]any{"instances": []apiInstanceRecord{}}) |
| + } |
| + handlers["GET /api/cli/apps"] = func(w http.ResponseWriter, _ []byte) { |
| + json.NewEncoder(w).Encode(map[string]any{"accounts": []map[string]any{{"name": "ops", "sqid": "bab", "apps": []string{}}}}) |
| + } |
| + handlers["GET /api/cli/apps/ops/list"] = func(w http.ResponseWriter, _ []byte) { w.Write([]byte("[]")) } |
| + handlers["POST /api/cli/apps/ops/new"] = func(w http.ResponseWriter, b []byte) { |
| + exists = true |
| + json.NewEncoder(w).Encode(map[string]string{"app": "hello", "account": "bab"}) |
| + } |
| + handlers["GET /api/cli/apps/ops/hello/channels"] = func(w http.ResponseWriter, _ []byte) { |
| + w.Write([]byte(`{"channels":[],"pipeline_entry":"edge","pipeline_channels":["edge"]}`)) |
| + } |
| + handlers["PUT /api/cli/apps/ops/hello/instances-manifest"] = func(w http.ResponseWriter, b []byte) { |
| + if scenario == "restricted" { |
| + w.WriteHeader(http.StatusForbidden) |
| + return |
| + } |
| + w.Write([]byte(`{"domain":"bab.apps.test"}`)) |
| + } |
| + handlers["POST /api/cli/apps/ops/hello/instances"] = func(w http.ResponseWriter, b []byte) { |
| + var in map[string]any |
| + json.Unmarshal(b, &in) |
| + if in["channel"] != "edge" || in["host"] != "hello.bab.apps.test" { |
| + t.Errorf("create body: %s", b) |
| + } |
| + w.WriteHeader(http.StatusCreated) |
| + w.Write([]byte(`{"host":"hello.bab.apps.test","channel":"edge","kind":"instance"}`)) |
| + } |
| + handlers["PUT /api/cli/apps/ops/hello/config"] = func(w http.ResponseWriter, b []byte) { |
| + var in apiConfigApply |
| + if err := json.Unmarshal(b, &in); err != nil { |
| + t.Error(err) |
| + } |
| + wantBundle := "" |
| + if scenario == "existing" { |
| + wantBundle = "preview" |
| + } |
| + if in.Environment != wantBundle || in.Set["PORT"].Value != "8080" { |
| + t.Errorf("config: %+v", in) |
| + } |
| + w.Write([]byte(`{}`)) |
| + } |
| + handlers["POST /api/cli/apps/ops/hello/releases"] = func(w http.ResponseWriter, b []byte) { |
| + w.WriteHeader(http.StatusCreated) |
| + w.Write([]byte(`{"version":"first493"}`)) |
| + } |
| + handlers["POST /api/cli/apps/ops/hello/promote"] = func(w http.ResponseWriter, b []byte) { |
| + w.Write([]byte(`{"result":"promoted","held":true,"held_until":"2099-01-01T00:00:00Z"}`)) |
| + } |
| + fc := newFirstDeployServer(t, handlers) |
| + credPath := filepath.Join(t.TempDir(), "credentials") |
| + t.Setenv("CARLOS_CREDENTIALS", credPath) |
| + creds, err := loadCredentials() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + creds.put(credential{Console: fc.ts.URL, Address: "test@example.test", Token: "test-token", ExpiresAt: time.Now().Add(time.Hour)}) |
| + if err := creds.save(); err != nil { |
| + t.Fatal(err) |
| + } |
| + dir := t.TempDir() |
| + artifact := filepath.Join(dir, "hello") |
| + if scenario != "bad artifact" { |
| + if err := os.WriteFile(artifact, []byte("binary"), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + env := "PORT=8080" |
| + if scenario == "bad env" { |
| + env = "DO-NOT-PRINT" |
| + } |
| + args := []string{"deploy", "--console", fc.ts.URL, "--account", "ops", "--app", "hello", "--version", "first493"} |
| + if scenario == "restricted" { |
| + args = append(args, "--channel", "canary/test") |
| + } else { |
| + args = append(args, "--env", env) |
| + } |
| + args = append(args, artifact) |
| + cmd := exec.Command(bin, args...) |
| + cmd.Env = carlosTestEnv(t, "CARLOS_CREDENTIALS="+credPath, "CARLOS_DEPLOYMENT_BUCKET=", "CARLOS_DEPLOYMENT_DIR=") |
| + cmd.Dir = dir |
| + out, err := cmd.CombinedOutput() |
| + if scenario == "new" || scenario == "existing" || scenario == "restricted" { |
| + if err != nil { |
| + t.Fatalf("deploy: %v\n%s", err, out) |
| + } |
| + if !fc.called("POST /api/cli/apps/ops/hello/promote") { |
| + t.Fatalf("did not promote: %s", out) |
| + } |
| + if scenario == "existing" && (fc.called("GET /api/cli/apps") || fc.called("POST /api/cli/apps/ops/new") || fc.called("PUT /api/cli/apps/ops/hello/instances-manifest")) { |
| + t.Fatal("existing deploy attempted setup") |
| + } |
| + if scenario == "restricted" && (fc.called("POST /api/cli/apps/ops/hello/instances") || fc.called("PUT /api/cli/apps/ops/hello/config")) { |
| + t.Fatal("restricted credential created an instance or changed config") |
| + } |
| + if scenario == "new" && !strings.Contains(string(out), "created instance hello.bab.apps.test") { |
| + t.Fatalf("missing creation output: %s", out) |
| + } |
| + } else { |
| + if err == nil { |
| + t.Fatalf("wanted refusal: %s", out) |
| + } |
| + if writes := fc.wrote(); len(writes) > 0 { |
| + t.Fatalf("refused deploy wrote: %v", writes) |
| + } |
| + if strings.Contains(string(out), "DO-NOT-PRINT") { |
| + t.Fatalf("value leaked: %s", out) |
| + } |
| + } |
| + }) |
| + } |
| +} |
diff --git a/deploy_first_copy.go b/deploy_first_copy.go| new file mode 100644 |
| index 000000000..12817ed42 |
| --- /dev/null |
| +++ b/deploy_first_copy.go |
| @@ -0,0 +1,39 @@ |
| +package main |
| + |
| +// First-deploy strings (#493), approved in copy-review/result.json. |
| +// Placeholders use {name} and are filled by fillDeployCopy. |
| + |
| +const ( |
| + // deployFirstAppExists refuses when the app name is already taken, live or |
| + // in the Trash. Placeholders: {app}. |
| + deployFirstAppExists = "app {app} already exists. If it is in the Trash, restore it before deploying." |
| + // deployFirstAppCreated is printed after the app is created. |
| + // Placeholders: {app}, {account}. |
| + deployFirstAppCreated = "created app {app} in account {account}" |
| + // deployFirstAppListFailed wraps a failure to check the account's apps. |
| + // Placeholders: {app}, {error}. |
| + deployFirstAppListFailed = "could not check whether {app} exists: {error}" |
| + // deployFirstChannelRequired refuses an instance create with no channel. |
| + deployFirstChannelRequired = "no release channel was chosen, so no instance was created." |
| + // deployFirstDomainMissing refuses a default host when the instances |
| + // manifest carries no domain. Placeholders: {app}. |
| + deployFirstDomainMissing = "the console did not provide an instance domain for {app}. No instance was created." |
| + // deployFirstInstanceCreated is printed after the first instance is |
| + // created. Placeholders: {host}, {channel}. |
| + deployFirstInstanceCreated = "created instance {host} on channel {channel}" |
| + // deployFirstEnvBadPair refuses an env argument that is not KEY=value. |
| + // Placeholders: {n} (1-based position). |
| + deployFirstEnvBadPair = "env argument {n} is not a KEY=value pair" |
| + // deployFirstEnvBadName refuses an env variable name. Placeholders: {n}. |
| + deployFirstEnvBadName = "env argument {n} has an invalid variable name. Use letters, digits and underscores, starting with a letter or underscore." |
| + // deployFirstEnvBadValue refuses an env value. Placeholders: {n}. |
| + deployFirstEnvBadValue = "env argument {n} contains a backslash, quote, newline or NUL in its value." |
| + // deployFirstEnvHostMissing refuses when a watched host has no route |
| + // record. Placeholders: {host}. |
| + deployFirstEnvHostMissing = "cannot determine the environment bundle for {host}. No environment variables were changed." |
| + // deployFirstEnvMixed refuses when the watched hosts are bound to more |
| + // than one config bundle. |
| + deployFirstEnvMixed = "the selected instances use different environment bundles. Select one with --host. No environment variables were changed." |
| + // deployFirstEnvNoHosts refuses when routes exist but none is watched. |
| + deployFirstEnvNoHosts = "no instance serves the selected channel. No environment variables were changed." |
| +) |
diff --git a/deploy_first_preflight.go b/deploy_first_preflight.go| new file mode 100644 |
| index 000000000..0ca63db88 |
| --- /dev/null |
| +++ b/deploy_first_preflight.go |
| @@ -0,0 +1,63 @@ |
| +package main |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| +) |
| + |
| +const deployEnvFlagHelp = "set an ordinary environment variable before shipping; repeat for more variables" |
| +const deployArtifactKindError = "deploy supports binary or static artifacts" |
| +const deployArtifactShapeError = "pass a file for a binary deploy, or one directory for a static deploy" |
| + |
| +type deployEnvFlag []string |
| + |
| +func (f *deployEnvFlag) String() string { return "" } |
| +func (f *deployEnvFlag) Set(v string) error { *f = append(*f, v); return nil } |
| + |
| +func deployArtifactPreflight(paths []string, kind, target string) error { |
| + if kind != "binary" && kind != "static" { |
| + return errors.New(deployArtifactKindError) |
| + } |
| + if kind == "static" && len(paths) != 1 { |
| + return errors.New("static ship takes exactly one site directory") |
| + } |
| + if len(paths) == 0 { |
| + return errors.New(deployArtifactShapeError) |
| + } |
| + for _, path := range paths { |
| + if kind == "binary" { |
| + name := target |
| + if len(paths) > 1 { |
| + name = filepath.Base(path) |
| + } |
| + if !shipTargetRe.MatchString(name) { |
| + return fmt.Errorf("ship: invalid artifact name %q (from %s) — want a GOOS-GOARCH shape like linux-arm64 "+ |
| + "(pass --target to name a single file explicitly)", name, path) |
| + } |
| + } |
| + info, err := os.Stat(path) |
| + if err != nil { |
| + return err |
| + } |
| + if (kind == "static") != info.IsDir() { |
| + return errors.New(deployArtifactShapeError) |
| + } |
| + if kind == "binary" && !info.Mode().IsRegular() { |
| + return errors.New(deployArtifactShapeError) |
| + } |
| + if strings.ContainsRune(path, 0) { |
| + return errors.New(deployArtifactShapeError) |
| + } |
| + f, err := os.Open(path) |
| + if err != nil { |
| + return err |
| + } |
| + if err := f.Close(); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
diff --git a/deploy_first_preflight_test.go b/deploy_first_preflight_test.go| new file mode 100644 |
| index 000000000..3c922c70d |
| --- /dev/null |
| +++ b/deploy_first_preflight_test.go |
| @@ -0,0 +1,46 @@ |
| +package main |
| + |
| +import ( |
| + "os" |
| + "path/filepath" |
| + "testing" |
| +) |
| + |
| +func TestDeployArtifactPreflight(t *testing.T) { |
| + dir := t.TempDir() |
| + binary := filepath.Join(dir, "hello") |
| + if err := os.WriteFile(binary, []byte("artifact"), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, tc := range []struct { |
| + name, kind, target string |
| + paths []string |
| + ok bool |
| + }{ |
| + {"binary", "binary", "linux-arm64", []string{binary}, true}, |
| + {"site", "static", "", []string{dir}, true}, |
| + {"missing", "binary", "linux-arm64", []string{filepath.Join(dir, "missing")}, false}, |
| + {"directory binary", "binary", "linux-arm64", []string{dir}, false}, |
| + {"file site", "static", "", []string{binary}, false}, |
| + {"invalid target", "binary", "bad", []string{binary}, false}, |
| + {"unknown kind", "other", "linux-arm64", []string{binary}, false}, |
| + {"empty", "binary", "linux-arm64", nil, false}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + err := deployArtifactPreflight(tc.paths, tc.kind, tc.target) |
| + if (err == nil) != tc.ok { |
| + t.Fatalf("got %v; want success %v", err, tc.ok) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDeployEnvFlagNeverFormatsValues(t *testing.T) { |
| + var f deployEnvFlag |
| + if err := f.Set("TOKEN=do-not-print"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if f.String() != "" { |
| + t.Fatal("flag formatting exposes environment values") |
| + } |
| +} |
diff --git a/deploy_first_test.go b/deploy_first_test.go| new file mode 100644 |
| index 000000000..ecba9e5a4 |
| --- /dev/null |
| +++ b/deploy_first_test.go |
| @@ -0,0 +1,470 @@ |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| +) |
| + |
| +// firstDeployServer is a loopback console. Handlers are keyed "METHOD path"; |
| +// every request is recorded so tests can assert that nothing was written. |
| +type firstDeployServer struct { |
| + mu sync.Mutex |
| + handlers map[string]func(w http.ResponseWriter, body []byte) |
| + calls []string |
| + bodies map[string][]byte |
| + ts *httptest.Server |
| +} |
| + |
| +func newFirstDeployServer(t *testing.T, handlers map[string]func(w http.ResponseWriter, body []byte)) *firstDeployServer { |
| + t.Helper() |
| + fs := &firstDeployServer{handlers: handlers, bodies: map[string][]byte{}} |
| + l, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fs.ts = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + body, _ := io.ReadAll(r.Body) |
| + key := r.Method + " " + r.URL.Path |
| + fs.mu.Lock() |
| + fs.calls = append(fs.calls, key) |
| + fs.bodies[key] = body |
| + h := fs.handlers[key] |
| + fs.mu.Unlock() |
| + if h == nil { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + h(w, body) |
| + })) |
| + fs.ts.Listener.Close() |
| + fs.ts.Listener = l |
| + fs.ts.Start() |
| + t.Cleanup(fs.ts.Close) |
| + return fs |
| +} |
| + |
| +func (f *firstDeployServer) wrote() []string { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + var out []string |
| + for _, c := range f.calls { |
| + if !strings.HasPrefix(c, "GET ") { |
| + out = append(out, c) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +func (f *firstDeployServer) called(key string) bool { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + for _, c := range f.calls { |
| + if c == key { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +func jsonReply(status int, v any) func(w http.ResponseWriter, body []byte) { |
| + return func(w http.ResponseWriter, _ []byte) { |
| + w.Header().Set("Content-Type", "application/json") |
| + w.WriteHeader(status) |
| + json.NewEncoder(w).Encode(v) |
| + } |
| +} |
| + |
| +func captureFirstDeployStdout(t *testing.T) *bytes.Buffer { |
| + t.Helper() |
| + old := stdout |
| + var buf bytes.Buffer |
| + stdout = &buf |
| + t.Cleanup(func() { stdout = old }) |
| + return &buf |
| +} |
| + |
| +func membership(apps ...string) map[string]any { |
| + return map[string]any{"accounts": []map[string]any{{"name": "acme", "sqid": "s1", "role": "owner", "apps": apps}}} |
| +} |
| + |
| +var acmeAcct = apiAcct{Seg: "acme"} |
| + |
| +func TestEnsureDeployAppExistingMakesNoWrites(t *testing.T) { |
| + srv := newFirstDeployServer(t, map[string]func(http.ResponseWriter, []byte){ |
| + "GET /api/cli/apps": jsonReply(200, membership("shop")), |
| + }) |
| + buf := captureFirstDeployStdout(t) |
| + created, err := ensureDeployApp(context.Background(), newTestSession(srv.ts.URL), acmeAcct, "shop", "") |
| + if err != nil || created { |
| + t.Fatalf("created=%v err=%v, want false nil", created, err) |
| + } |
| + if w := srv.wrote(); len(w) != 0 { |
| + t.Fatalf("writes = %v, want none", w) |
| + } |
| + if srv.called("GET /api/cli/apps/acme/list") { |
| + t.Fatal("a listed app must not need the Trash listing") |
| + } |
| + _ = buf |
| +} |
| + |
| +func TestEnsureDeployAppAbsentCreatesNormalAppInRegion(t *testing.T) { |
| + srv := newFirstDeployServer(t, map[string]func(http.ResponseWriter, []byte){ |
| + "GET /api/cli/apps": jsonReply(200, membership("other")), |
| + "GET /api/cli/apps/acme/list": jsonReply(200, []map[string]any{{"app": "other"}}), |
| + "POST /api/cli/apps/acme/new": jsonReply(200, map[string]any{"account": "acme", "app": "shop", "region": "eu", "region_source": "chosen"}), |
| + }) |
| + captureFirstDeployStdout(t) |
| + created, err := ensureDeployApp(context.Background(), newTestSession(srv.ts.URL), acmeAcct, "shop", "eu") |
| + if err != nil || !created { |
| + t.Fatalf("created=%v err=%v, want true nil", created, err) |
| + } |
| + var in map[string]any |
| + if err := json.Unmarshal(srv.bodies["POST /api/cli/apps/acme/new"], &in); err != nil { |
| + t.Fatal(err) |
| + } |
| + if in["name"] != "shop" || in["region"] != "eu" { |
| + t.Fatalf("create body = %v", in) |
| + } |
| + for _, k := range []string{"place", "control_plane", "build_probe", "analytics"} { |
| + if _, ok := in[k]; ok { |
| + t.Fatalf("create body carries %q, want a normal app: %v", k, in) |
| + } |
| + } |
| +} |
| + |
| +func TestEnsureDeployAppMatchesAccountBySqidWhenExact(t *testing.T) { |
| + srv := newFirstDeployServer(t, map[string]func(http.ResponseWriter, []byte){ |
| + "GET /api/cli/apps": jsonReply(200, membership("shop")), |
| + }) |
| + captureFirstDeployStdout(t) |
| + created, err := ensureDeployApp(context.Background(), newTestSession(srv.ts.URL), apiAcct{Seg: "s1", Exact: true}, "shop", "") |
| + if err != nil || created || len(srv.wrote()) != 0 { |
| + t.Fatalf("created=%v err=%v writes=%v", created, err, srv.wrote()) |
| + } |
| +} |
| + |
| +func TestEnsureDeployAppMembershipCasesDoNotCreate(t *testing.T) { |
| + cases := map[string]map[string]func(http.ResponseWriter, []byte){ |
| + "unsupported console": {}, |
| + "not a member": {"GET /api/cli/apps": jsonReply(200, membership("shop"))}, |
| + } |
| + for name, h := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + srv := newFirstDeployServer(t, h) |
| + captureFirstDeployStdout(t) |
| + acct := acmeAcct |
| + if name == "not a member" { |
| + acct = apiAcct{Seg: "someone-else"} |
| + } |
| + created, err := ensureDeployApp(context.Background(), newTestSession(srv.ts.URL), acct, "fresh", "") |
| + if err != nil || created { |
| + t.Fatalf("created=%v err=%v, want false nil", created, err) |
| + } |
| + if w := srv.wrote(); len(w) != 0 { |
| + t.Fatalf("writes = %v", w) |
| + } |
| + if srv.called("GET /api/cli/apps/acme/list") || srv.called("GET /api/cli/apps/someone-else/list") { |
| + t.Fatal("no membership means no further lookups") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestEnsureDeployAppMembershipErrorDoesNotCreate(t *testing.T) { |
| + srv := newFirstDeployServer(t, map[string]func(http.ResponseWriter, []byte){ |
| + "GET /api/cli/apps": jsonReply(500, map[string]string{"error": "boom"}), |
| + }) |
| + captureFirstDeployStdout(t) |
| + created, err := ensureDeployApp(context.Background(), newTestSession(srv.ts.URL), acmeAcct, "shop", "") |
| + if err == nil || created { |
| + t.Fatalf("created=%v err=%v, want an error", created, err) |
| + } |
| + if w := srv.wrote(); len(w) != 0 { |
| + t.Fatalf("writes = %v", w) |
| + } |
| +} |
| + |
| +func TestEnsureDeployAppTrashedAppIsRefusedNotRecreated(t *testing.T) { |
| + srv := newFirstDeployServer(t, map[string]func(http.ResponseWriter, []byte){ |
| + "GET /api/cli/apps": jsonReply(200, membership()), |
| + "GET /api/cli/apps/acme/list": jsonReply(200, []map[string]any{ |
| + {"app": "shop", "deleted_at": "2026-10-01T00:00:00Z", "purge_after": "2026-11-01T00:00:00Z"}, |
| + }), |
| + }) |
| + captureFirstDeployStdout(t) |
| + created, err := ensureDeployApp(context.Background(), newTestSession(srv.ts.URL), acmeAcct, "shop", "") |
| + if !errors.Is(err, errDeployAppExists) || created { |
| + t.Fatalf("created=%v err=%v, want errDeployAppExists", created, err) |
| + } |
| + if w := srv.wrote(); len(w) != 0 { |
| + t.Fatalf("writes = %v, a trashed app must be neither recreated nor restored", w) |
| + } |
| +} |
| + |
| +func TestEnsureDeployAppListFailureStopsBeforeCreate(t *testing.T) { |
| + for name, reply := range map[string]func(http.ResponseWriter, []byte){ |
| + "500": jsonReply(500, map[string]string{"error": "boom"}), |
| + "404": jsonReply(404, map[string]string{"error": "gone"}), |
| + "bad json": func(w http.ResponseWriter, _ []byte) { io.WriteString(w, "not json") }, |
| + "forbidden": jsonReply(403, map[string]string{"error": "no"}), |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + srv := newFirstDeployServer(t, map[string]func(http.ResponseWriter, []byte){ |
| + "GET /api/cli/apps": jsonReply(200, membership()), |
| + "GET /api/cli/apps/acme/list": reply, |
| + }) |
| + captureFirstDeployStdout(t) |
| + created, err := ensureDeployApp(context.Background(), newTestSession(srv.ts.URL), acmeAcct, "shop", "") |
| + if !errors.Is(err, errDeployAppListFailed) || created { |
| + t.Fatalf("created=%v err=%v, want errDeployAppListFailed", created, err) |
| + } |
| + if errors.Unwrap(err) == nil { |
| + t.Fatal("the underlying failure must stay reachable") |
| + } |
| + if w := srv.wrote(); len(w) != 0 { |
| + t.Fatalf("writes = %v", w) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestEnsureDeployAppCreateRefusalIsPreserved(t *testing.T) { |
| + srv := newFirstDeployServer(t, map[string]func(http.ResponseWriter, []byte){ |
| + "GET /api/cli/apps": jsonReply(200, membership()), |
| + "GET /api/cli/apps/acme/list": jsonReply(200, []map[string]any{}), |
| + "POST /api/cli/apps/acme/new": jsonReply(403, map[string]string{"error": "plan limit reached"}), |
| + }) |
| + captureFirstDeployStdout(t) |
| + created, err := ensureDeployApp(context.Background(), newTestSession(srv.ts.URL), acmeAcct, "shop", "") |
| + if err == nil || created || !strings.Contains(err.Error(), "plan limit reached") { |
| + t.Fatalf("created=%v err=%v, want the server's refusal", created, err) |
| + } |
| +} |
| + |
| +func instanceHandlers(domain string, createStatus int) map[string]func(http.ResponseWriter, []byte) { |
| + return map[string]func(http.ResponseWriter, []byte){ |
| + "PUT /api/cli/apps/acme/shop/instances-manifest": jsonReply(200, map[string]any{"app": "shop", "domain": domain, "channel": "stable"}), |
| + "POST /api/cli/apps/acme/shop/instances": func(w http.ResponseWriter, body []byte) { |
| + var in struct{ Host, Channel string } |
| + json.Unmarshal(body, &in) |
| + if createStatus != http.StatusCreated { |
| + jsonReply(createStatus, map[string]string{"error": "host not allowed"})(w, body) |
| + return |
| + } |
| + jsonReply(201, map[string]any{"host": in.Host, "channel": in.Channel, "kind": "instance"})(w, body) |
| + }, |
| + } |
| +} |
| + |
| +func TestCreateDeployInstanceDefaultHostAndWireShape(t *testing.T) { |
| + srv := newFirstDeployServer(t, instanceHandlers("acme.example.test", http.StatusCreated)) |
| + captureFirstDeployStdout(t) |
| + rec, err := createDeployInstance(context.Background(), newTestSession(srv.ts.URL), acmeAcct, "shop", "canary", "", "first deploy") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if rec.Host != "shop.acme.example.test" || rec.Channel != "canary" { |
| + t.Fatalf("rec = %+v", rec) |
| + } |
| + // Enable carries no options at all: an existing manifest is preserved. |
| + if got := strings.TrimSpace(string(srv.bodies["PUT /api/cli/apps/acme/shop/instances-manifest"])); got != "{}" { |
| + t.Fatalf("instances-manifest body = %s, want {}", got) |
| + } |
| + var in map[string]any |
| + json.Unmarshal(srv.bodies["POST /api/cli/apps/acme/shop/instances"], &in) |
| + if in["host"] != "shop.acme.example.test" || in["channel"] != "canary" || in["kind"] != "instance" || in["message"] != "first deploy" { |
| + t.Fatalf("create body = %v", in) |
| + } |
| + for _, k := range []string{"region", "environment", "addrs", "probe", "scope"} { |
| + if _, ok := in[k]; ok { |
| + t.Fatalf("create body carries %q: %v", k, in) |
| + } |
| + } |
| +} |
| + |
| +func TestCreateDeployInstanceExplicitHostGoesToTheDoor(t *testing.T) { |
| + srv := newFirstDeployServer(t, instanceHandlers("acme.example.test", http.StatusCreated)) |
| + captureFirstDeployStdout(t) |
| + rec, err := createDeployInstance(context.Background(), newTestSession(srv.ts.URL), acmeAcct, "shop", "stable", "www.custom.test", "") |
| + if err != nil || rec.Host != "www.custom.test" { |
| + t.Fatalf("rec=%+v err=%v: the door, not the helper, validates an explicit host", rec, err) |
| + } |
| +} |
| + |
| +func TestCreateDeployInstanceEmptyChannelMutatesNothing(t *testing.T) { |
| + srv := newFirstDeployServer(t, instanceHandlers("acme.example.test", http.StatusCreated)) |
| + captureFirstDeployStdout(t) |
| + _, err := createDeployInstance(context.Background(), newTestSession(srv.ts.URL), acmeAcct, "shop", "", "", "") |
| + if !errors.Is(err, errDeployChannelRequired) { |
| + t.Fatalf("err = %v", err) |
| + } |
| + if len(srv.calls) != 0 { |
| + t.Fatalf("calls = %v, want none", srv.calls) |
| + } |
| +} |
| + |
| +func TestCreateDeployInstanceMissingDomainStopsBeforeCreate(t *testing.T) { |
| + srv := newFirstDeployServer(t, instanceHandlers("", http.StatusCreated)) |
| + captureFirstDeployStdout(t) |
| + _, err := createDeployInstance(context.Background(), newTestSession(srv.ts.URL), acmeAcct, "shop", "stable", "", "") |
| + if !errors.Is(err, errDeployDomainMissing) { |
| + t.Fatalf("err = %v", err) |
| + } |
| + if srv.called("POST /api/cli/apps/acme/shop/instances") { |
| + t.Fatal("no domain, no default host, no create") |
| + } |
| +} |
| + |
| +func TestCreateDeployInstanceServerErrorsPreserved(t *testing.T) { |
| + t.Run("create refused", func(t *testing.T) { |
| + srv := newFirstDeployServer(t, instanceHandlers("acme.example.test", http.StatusUnprocessableEntity)) |
| + captureFirstDeployStdout(t) |
| + _, err := createDeployInstance(context.Background(), newTestSession(srv.ts.URL), acmeAcct, "shop", "stable", "bad.host", "") |
| + if err == nil || !strings.Contains(err.Error(), "host not allowed") { |
| + t.Fatalf("err = %v, want the server's refusal", err) |
| + } |
| + }) |
| + t.Run("enable refused", func(t *testing.T) { |
| + h := instanceHandlers("acme.example.test", http.StatusCreated) |
| + h["PUT /api/cli/apps/acme/shop/instances-manifest"] = jsonReply(409, map[string]string{"error": "not now"}) |
| + srv := newFirstDeployServer(t, h) |
| + captureFirstDeployStdout(t) |
| + _, err := createDeployInstance(context.Background(), newTestSession(srv.ts.URL), acmeAcct, "shop", "stable", "", "") |
| + if err == nil || !strings.Contains(err.Error(), "not now") { |
| + t.Fatalf("err = %v", err) |
| + } |
| + if srv.called("POST /api/cli/apps/acme/shop/instances") { |
| + t.Fatal("a refused enable must stop the create") |
| + } |
| + }) |
| +} |
| + |
| +func TestParseDeployEnv(t *testing.T) { |
| + if got, err := parseDeployEnv(nil); got != nil || err != nil { |
| + t.Fatalf("nil list = %v, %v", got, err) |
| + } |
| + if got, err := parseDeployEnv([]string{}); got != nil || err != nil { |
| + t.Fatalf("empty list = %v, %v", got, err) |
| + } |
| + got, err := parseDeployEnv([]string{"A=1", "B=x=y", "A=2", "C="}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := map[string]appconfig.Var{ |
| + "A": {Kind: "env", Value: "2"}, |
| + "B": {Kind: "env", Value: "x=y"}, |
| + "C": {Kind: "env", Value: ""}, |
| + } |
| + if len(got) != len(want) { |
| + t.Fatalf("got %v", got) |
| + } |
| + for k, v := range want { |
| + if got[k] != v { |
| + t.Fatalf("%s = %+v, want %+v", k, got[k], v) |
| + } |
| + } |
| +} |
| + |
| +func TestParseDeployEnvErrorsNeverEchoValues(t *testing.T) { |
| + const secret = "s3cr3t-token-value" |
| + for name, args := range map[string][]string{ |
| + "no equals": {"A=1", "justasecret" + secret}, |
| + "empty key": {"=" + secret}, |
| + "bad name": {"1BAD=" + secret}, |
| + "dash name": {"BAD-NAME=" + secret}, |
| + "quote": {"A=" + secret + `"`}, |
| + "backslash": {"A=" + secret + `\`}, |
| + "newline": {"A=" + secret + "\nB=2"}, |
| + "nul": {"A=" + secret + "\x00"}, |
| + "single quote": {"A=" + secret + "'"}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + got, err := parseDeployEnv(args) |
| + if err == nil || got != nil { |
| + t.Fatalf("got %v, %v, want a refusal", got, err) |
| + } |
| + if strings.Contains(err.Error(), secret) || strings.Contains(err.Error(), "BAD") { |
| + t.Fatalf("error echoes the argument: %q", err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDeployEnvBundle(t *testing.T) { |
| + rec := func(host, env string) apiInstanceRecord { return apiInstanceRecord{Host: host, Environment: env} } |
| + t.Run("first deploy is the default bundle", func(t *testing.T) { |
| + if got, err := deployEnvBundle(nil, nil); got != "" || err != nil { |
| + t.Fatalf("got %q, %v", got, err) |
| + } |
| + }) |
| + t.Run("default bundle is supported", func(t *testing.T) { |
| + got, err := deployEnvBundle([]apiInstanceRecord{rec("a.test", ""), rec("b.test", "")}, []string{"a.test", "b.test"}) |
| + if got != "" || err != nil { |
| + t.Fatalf("got %q, %v", got, err) |
| + } |
| + }) |
| + t.Run("scoped named bundle", func(t *testing.T) { |
| + recs := []apiInstanceRecord{rec("a.test", "staging"), rec("b.test", "staging"), rec("c.test", "prod")} |
| + got, err := deployEnvBundle(recs, []string{"A.test", "b.test"}) |
| + if got != "staging" || err != nil { |
| + t.Fatalf("got %q, %v, want staging (unwatched hosts are ignored)", got, err) |
| + } |
| + }) |
| + t.Run("mixed bundles refused", func(t *testing.T) { |
| + recs := []apiInstanceRecord{rec("a.test", "staging"), rec("b.test", "")} |
| + if got, err := deployEnvBundle(recs, []string{"a.test", "b.test"}); !errors.Is(err, errDeployEnvMixed) || got != "" { |
| + t.Fatalf("got %q, %v", got, err) |
| + } |
| + recs = []apiInstanceRecord{rec("a.test", "staging"), rec("b.test", "prod")} |
| + if _, err := deployEnvBundle(recs, []string{"a.test", "b.test"}); !errors.Is(err, errDeployEnvMixed) { |
| + t.Fatalf("err = %v", err) |
| + } |
| + }) |
| + t.Run("missing host refused", func(t *testing.T) { |
| + recs := []apiInstanceRecord{rec("a.test", "staging")} |
| + if _, err := deployEnvBundle(recs, []string{"a.test", "gone.test"}); !errors.Is(err, errDeployEnvHostMissing) { |
| + t.Fatalf("err = %v", err) |
| + } |
| + if _, err := deployEnvBundle(nil, []string{"a.test"}); !errors.Is(err, errDeployEnvHostMissing) { |
| + t.Fatalf("watched host with no records: err = %v", err) |
| + } |
| + }) |
| + t.Run("records but no watched hosts refused", func(t *testing.T) { |
| + if _, err := deployEnvBundle([]apiInstanceRecord{rec("a.test", "staging")}, nil); !errors.Is(err, errDeployEnvNoWatchedHost) { |
| + t.Fatalf("err = %v", err) |
| + } |
| + }) |
| +} |
| + |
| +func TestEnsureDeployAppPlainSqidAndAmbiguousAccount(t *testing.T) { |
| + for _, ambiguous := range []bool{false, true} { |
| + entries := []map[string]any{{"name": "acme", "sqid": "s1", "apps": []string{}}} |
| + if ambiguous { |
| + entries = append(entries, map[string]any{"name": "s1", "sqid": "s2", "apps": []string{}}) |
| + } |
| + srv := newFirstDeployServer(t, map[string]func(http.ResponseWriter, []byte){ |
| + "GET /api/cli/apps": jsonReply(200, map[string]any{"accounts": entries}), |
| + "GET /api/cli/apps/s1/list": jsonReply(200, []any{}), |
| + "POST /api/cli/apps/s1/new": jsonReply(200, map[string]string{"app": "shop", "account": "s1"}), |
| + }) |
| + captureFirstDeployStdout(t) |
| + created, err := ensureDeployApp(context.Background(), newTestSession(srv.ts.URL), apiAcct{Seg: "s1"}, "shop", "") |
| + if err != nil || created == ambiguous { |
| + t.Fatalf("ambiguous=%v created=%v err=%v", ambiguous, created, err) |
| + } |
| + if ambiguous && len(srv.wrote()) != 0 { |
| + t.Fatal("ambiguous account was mutated") |
| + } |
| + } |
| +} |
diff --git a/docs/site/cli.md b/docs/site/cli.md| index 74ec7036d..dda2867a1 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -331,6 +331,12 @@ A host behind a password gate ([carlos gate](/docs/cli#carlos-gate)) is watched |
| carlos deploy --app hello ./hello |
| ``` |
| +`carlos deploy --app hello --env PORT=8080 ./hello` creates the app and its first instance if they are missing, then deploys your built binary and waits for it to serve. Existing instances stay unchanged. Use `--region` to choose a new app’s region; for an existing app, it checks the region. |
| + |
| +Repeat `--env KEY=value` to set ordinary variables before shipping. They go into the environment bundle shared by the selected instances. If those instances use different bundles, select one with `--host`. Values are not printed, but remain in shell history; use `carlos secrets set` for secrets. |
| + |
| +The console must support instances and provide a platform domain. Trashed apps are not restored. If setup fails partway through, the app, instance or variables already created remain. Fix the reported error and retry. |
| + |
| Signed-in only. With saved project defaults you can run `carlos deploy` with |
| no arguments and no questions. A first run at a terminal fills the blanks by |
| asking. If your account owns no apps yet, it offers to claim one named after |
diff --git a/docs/site/plans.md b/docs/site/plans.md| index c91feb5d8..05715b662 100644 |
| --- a/docs/site/plans.md |
| +++ b/docs/site/plans.md |
| @@ -211,7 +211,7 @@ Where billing is on, an account's owners buy and change their plan on the accoun |
| ### Buying a plan |
| -Under **Choose a plan**, pick a currency (`usd`, `eur` or `gbp`), a plan, and any packs, then press **Continue to payment**. You go to Stripe to pay. When you come back, the page shows your new plan as soon as the payment is confirmed. Prices are for a year, and tax is added where it applies. |
| +Under **Choose a plan**, pick a currency (`usd`, `eur` or `gbp`), a plan, and any packs, then press **Continue to payment**. You go to Stripe to pay. When you come back, the page shows your new plan as soon as the payment is confirmed. Prices are for a year, and tax is added where it applies. Business customers can add a VAT number at checkout. Stripe then applies reverse charge where the sale qualifies. |
| The currency is fixed by the first purchase. After that the page says which currency the account pays in, and changing it means asking an operator. |
diff --git a/docs/superpowers/notes/census-proposal-first-deploy-493.md b/docs/superpowers/notes/census-proposal-first-deploy-493.md| new file mode 100644 |
| index 000000000..e7a54c484 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-first-deploy-493.md |
| @@ -0,0 +1,23 @@ |
| +# Census approval: first-deploy-493 |
| + |
| +Ruling `census-ruling-first-deploy-493`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `deploy.go` `runDeploy` | body | unchanged (1) | Sequences existing console APIs for confirmed-missing app and first instance creation, with repeatable environment values; local artifact preflight before these new writes. Existing config artifact stat read retained. | |
| + |
| +Envelopes re-pinned: `.`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `deploy.go` `runDeploy`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-edge-asset-cache-1;basis=takes --assets and --no-assets, refuses both together and bad folders before anything runs (deployAssets), reads the folders saved in .carlos/config for the session's console through configAssets (the config walk the CLI already makes), and saves a new list there as it saves the other deploy settings; read site unchanged (1), none added;rev3=census-ruling-gated-deploy-watch-164;basis=the static-deploy branch passes its watch targets through passGatedTargets (a console POST for a gate pass per gated host) and passes the gated-host set to watchDeployed; no new local read, read site unchanged (1), none added;rev3=census-ruling-region-labels;basis=builds a host-to-label map (hostPlaces) from the instance list it already read and passes it to the static watch targets and watchDeployed, so the watch lines say where; no read added |
| + |
| +New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| + |
| +- new `deploy_first_preflight.go:deployArtifactPreflight`: reads +file:Open, +file:Stat; written legacy, accepted-legacy, frozen |
| + |
| +Seal: `43d1824141f0ce7024cc3740ab5feac3f3539322f8afb856c9ca2f10d5095e95` → `6b9aa3f2b21250d40b910ad1d29362687ec57ba5e895157670b785c0c3978f52`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-first-deploy-493.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/notes/census-proposal-managed-fleets-1b.md b/docs/superpowers/notes/census-proposal-managed-fleets-1b.md| index 445724176..e19b63813 100644 |
| --- a/docs/superpowers/notes/census-proposal-managed-fleets-1b.md |
| +++ b/docs/superpowers/notes/census-proposal-managed-fleets-1b.md |
| @@ -72,6 +72,6 @@ New dispositions, which census-propose wrote and the reviewer checks against the |
| - reads `internal/registry/registry.go:scanRoute`: +registry:Assigned, +registry:FleetLabel, +registry:Moved; keeps legacy, task accepted-legacy |
| - reads `internal/registry/remote_dispatch.go:Registry.dispatchRemote`: +registry:Assigned, +registry:At ×2, +registry:Fleet ×2, +registry:Host, +registry:Label ×2, +registry:Moved, +registry:Number64; keeps hint, task E2 |
| -Seal: `43d1824141f0ce7024cc3740ab5feac3f3539322f8afb856c9ca2f10d5095e95` → `708f30f964eeadb3e585196de9a6135c4e3db12611b1e0140cdebb6b4d5c8bb8`. |
| +Seal: `6b9aa3f2b21250d40b910ad1d29362687ec57ba5e895157670b785c0c3978f52` → `1b3188c3fb086cc2bfe8cff5aafb4f0d0d26fd1bd977ff2a167f400248737889`. |
| Overlay: `internal/provision/testdata/plan14-root-reads-managed-fleets-1b.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-checkout-tax-id.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-checkout-tax-id.md| new file mode 100644 |
| index 000000000..a97dabc37 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-checkout-tax-id.md |
| @@ -0,0 +1,23 @@ |
| +# Review brief: branch checkout-tax-id, round 1 of 3 |
| + |
| +Repo carlos/platform, branch `checkout-tax-id`, the commit that adds this brief (named in your prompt). |
| +Under review: the diff `origin/main...HEAD`: PrepareCheckout adds `tax_id_collection[enabled]=true` and `customer_update[name]=auto` so EU business customers can enter a VAT number and Stripe Tax applies reverse charge (Paul's tax setup, 2026-10-31). Confirmed against the Stripe sandbox: a session with these parameters opens with tax_id_collection {enabled: true, required: never}. |
| + |
| +## What to check |
| + |
| +1. Prepared requests stay byte-stable: only newly prepared Checkout requests carry the new fields; a stored request is resent verbatim (Plan 6b Invariant: prepared bytes never change under a key). |
| +2. `customer_update[name]=auto` does not overwrite anything the console relies on (the customer name the console set, if any) in a way that breaks billing. |
| +3. The house-coupon path, the expiry path and every other Prepare* are unchanged. |
| +4. Docs sentence accuracy. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3 with file:line, failure scenario and fix. End with exactly one verdict: **READY**, **READY AFTER FIXES**, or **NOT READY**. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites. |
diff --git a/docs/superpowers/reviews/first-deploy-493-brief.md b/docs/superpowers/reviews/first-deploy-493-brief.md| new file mode 100644 |
| index 000000000..b7df8655b |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/first-deploy-493-brief.md |
| @@ -0,0 +1,7 @@ |
| +# Review first-deploy-493, round 2 of 3 |
| +Repo /home/paulca/amadan.net/carlos/platform-first-deploy-493. Review working diff against origin/main plus untracked deploy_first*.go. Do not edit files, do not create a plan file, no agents, no tests/full suites, no network or production mutations. Return findings directly. Opus independent review of Codex author + Sonnet helpers. |
| +Prior round: design consultation at /home/paulca/.cache/first-deploy-493/design-review.txt. It identified API constraints but no ranked blocking findings. Implemented safe absence proof, existing APIs, region selection, validation and copy approval. Deliberate choices: --env uses same set semantics as env set (last duplicate wins), named bundles selected from watched hosts, existing successful instance-list deploy avoids account-list call; first binary instance for zero records, static host flow preserved. Partial writes retained and documented. Server errors and races stop with honest error, retry is user action. No blanket retries or authorization widening. Custom host goes through instanceCreate validation. |
| +Request: #493 first deploy creates missing app and instance and accepts --env K=V. Existing deployments should continue working. |
| +Read AGENTS stopping rules and docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md. Check real API response shapes, service token compatibility, empty/truncated list behavior, account identity/Trash/concurrency, preflight before writes, environment scope and confidentiality, channel/region/host semantics, static/temp regressions, no production operations. New strings approved by Paul in copy-review/result.json. |
| +Also independently rule each census unit and the root package envelope. Read docs/superpowers/notes/census-proposal-first-deploy-493.md (may be being generated; if absent use /home/paulca/.cache/first-deploy-493/census-card.txt), and changed functions reachable from them. Units runDeploy and deployArtifactPreflight. Compare authority before/after; no root path may become tenant-controlled. Return explicit verdicts with file:line for both units and envelope. |
| +Severity P1 unsafe/nonworking/failing test blocks. P2 wrong/missing fix without reopening review. P3 polish follow-up only. Stop at first no-P1 review, max3 rounds globally; two recurring same-invariant rounds stop fixes. Output ranked findings with verified failure scenario, file:line and concrete fix, plus census rulings, ending READY / READY AFTER FIXES / NOT READY. Read only merged specs; no pending designs. |
diff --git a/docs/superpowers/reviews/first-deploy-493-opus.md b/docs/superpowers/reviews/first-deploy-493-opus.md| new file mode 100644 |
| index 000000000..5b9f4f110 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/first-deploy-493-opus.md |
| @@ -0,0 +1,63 @@ |
| +**Verdict: READY AFTER FIXES.** I found no P1, one P2 and five P3s. Under the stopping rules this round ends the review. Apply the P2 without reopening it; the P3s go on the follow-up list. |
| + |
| +I reviewed the working tree as it stood at about 15:00. The author was still editing `deploy.go` while I read it: the zero-record binary block gained `truncated`/`total` guards and the `channelsErr` handling. The census overlay was regenerated at 14:59:42, after the last `deploy.go` edit, so it matches this snapshot. As briefed, I ran no tests. |
| + |
| +## Findings |
| + |
| +**P2-1: existing apps with zero instances now fail under a deploy credential, before the ship.** Invariant: existing deployments keep working and service tokens stay compatible. |
| +- **Where:** `deploy.go:402-419` → `deploy_first.go:121`, `:131`. |
| +- **Scenario:** |
| + - The app already exists (`createdNow` is false) and has a pipeline (every new app gets one, `internal/console/server.go:5293`). |
| + - It has no promoted channel and no instance records. |
| + - CI runs `carlos deploy --channel canary/x` with a `deploy`-role credential. That is the only service role allowed both to list instances and to promote (`internal/console/authcli.go:565,673`). On a pipelined app it may move only `canary/<name>` (`internal/console/deployscope.go:118`). |
| + - Before this branch: ship, promote, and "no instance follows canary/x". Now: `instancesEnable` hits `PUT instances-manifest`, which no service role may call (`authcli.go:672`, `svcrole.Set{}`). `instanceCreate` is limited to the `Instance` role (`:725`). The run dies before shipping. |
| + - The window is narrow but real. |
| +- **Fix:** keep auto-creating the instance only when this run created the app (`createdNow`), or when the caller is a member. For an existing app, treat a 403 from the manifest or create door as "take the old no-instance path" and print a muted note. This narrows the new step; it is not a retry and widens no authorisation. Add a CLI test: existing app, zero records, `PUT instances-manifest` answers 403, and the deploy still ships and promotes. |
| + |
| +**P3-1:** `deploy.go:481`. On a truncated list, the refusal passes the app name into `{host}` and drops the `deploy:` prefix. Use `log.Fatalf("deploy: %s", …)`. Ideally name the host, or reuse FD-C10 with the app name as approved. |
| + |
| +**P3-2:** `apimode.go:3857`. `type apiInstancesMissing` was inserted between `instanceList`'s doc comment and the func, so godoc now attaches that comment to the type. Move the type above the comment and add `Unwrap() error`. No current caller needs it: `errMembershipNotFound` checks sit on other paths, `apimode.go:5113` and `instances_cli.go:1049`. |
| + |
| +**P3-3:** `deploy_first_preflight.go:51`. The NUL check can never fire, because `os.Stat` already fails on a NUL. Drop it. |
| + |
| +**P3-4:** the `--region` preflight moved from before the capabilities read and wizard to after the save offer (`deploy.go:396`). A region mismatch now refuses after the person has answered questions. Nothing has been written by then. |
| + |
| +**P3-5:** the approved docs say "creates the app and its first instance if they are missing". In fact the instance is created only when a pipeline exists and nothing has been promoted (`deploy.go:409`). A previously promoted app with no instances keeps the old path, by design. Tighten the wording at the next copy pass. |
| + |
| +## Checks that passed |
| +- **API shapes:** |
| + - The instance list answers 404 only from the membership/app gate (`internal/console/apiinstances.go:118`). A fresh app with no manifest lists 200 and empty. |
| + - `/api/cli/apps` filters an app-scoped service token down to its own app (`internal/console/apicli.go:715`). |
| + - App create refuses app-scoped service tokens (`apicli.go:389`). |
| + - New apps get the default `edge` pipeline, so `pipeline_entry` is present (`apicli.go:840`). |
| +- **Absence proof:** `ensureDeployApp` creates nothing when there is no membership, when the account name matches more than one membership, when the name appears in the live or Trash list, or when the list fails or is unsupported. Two concurrent first deploys are settled by the server's create conflict. |
| +- **Environment:** values never appear in errors or output. The kind is `env`, the same as `env set` (`appconfig_cli.go:396`). The bundle comes from the watched hosts, mixed bundles are refused, and so is a truncated list. All of this happens before the config write. |
| +- **Static and temporary flows:** unchanged apart from the minted record being appended to `recs`. That only affects the watch labels, which are empty either way. |
| +- **Copy:** FD-C1..C15 and FD-D1 match `copy-review/result.json` exactly. The other preflight strings are reused from `cli.go:2843,2879`. |
| +- **No production operations:** test fakes bind `127.0.0.1`. |
| + |
| +## Census rulings |
| +- **`runDeploy` (`deploy.go:133`): APPROVE.** |
| + - The one local read is unchanged: `os.Stat(artifact)` at `deploy.go:329`, on a config artifact confined by `projectArtifact` (`:293`). |
| + - Every new step is a console HTTP call through existing doors, or the call into `deployArtifactPreflight`. |
| + - The basis items still hold: `deployAssets` refuses first (`:187`, `:351`), and `passGatedTargets` and `hostPlaces` are untouched. |
| + - It is a member CLI verb (`main.go:100`), and no root path reaches it. |
| +- **`deployArtifactPreflight` (`deploy_first_preflight.go:20`), new, accepted-legacy: APPROVE.** |
| + - It runs `Stat` and `Open`/`Close` on `fs.Args()`: command-line paths, or the confined config artifact. |
| + - A binary must be a regular file before `Open`, and nothing is read. |
| + - It runs as the member, its only caller is `deploy.go:376`, and there is no tenant- or box-controlled input. |
| +- **Envelope `.`: APPROVE.** |
| + - The changed functions are: |
| + - `instanceList`: error wrapping only, no new I/O. |
| + - `runDeploy`, `ensureDeployApp` and `createDeployInstance`: console API calls through the server's own gates. |
| + - `parseDeployEnv` and `deployEnvBundle`: pure. |
| + - `deployArtifactPreflight`. |
| + - None weakens a check, and no root path becomes tenant-controlled. |
| + |
| +## Author disposition |
| + |
| +Reviewed snapshot: 80b7fcc4206f69308af20f82d38c6e489eb50104. Round 1 was the design consultation; this is round 2 of the same change. No P1; review closed under AGENTS.md stopping rule 1. |
| + |
| +P2-1 applied: on an existing app only, a typed 403 from instancesEnable leaves the original instance list intact and continues to the existing ship/promote/no-instance path. A newly created app still fails on that denial. The create door's errors do not trigger fallback. No permission is expanded and no new mutation is added. TestFirstDeployCLI/restricted exercises the denial, publication, and absence of instance/config writes. |
| + |
| +P3-1 through P3-5 remain follow-ups as requested by the stopping rule. They do not reopen this review. The approved wording is unchanged. |
diff --git a/internal/billingstripe/prepared.go b/internal/billingstripe/prepared.go| index 5ecce0d52..00c1ec7bc 100644 |
| --- a/internal/billingstripe/prepared.go |
| +++ b/internal/billingstripe/prepared.go |
| @@ -41,8 +41,9 @@ func (p *Provider) PrepareCustomer(accountSqid, key string) (billing.Prepared, e |
| // PrepareCheckout encodes a Checkout Session create: subscription mode in |
| // the request's currency, its line items by price id, Adaptive Pricing |
| -// off, the billing address required and saved on the customer, automatic |
| -// tax, the provider-time expiry, the success and cancel URLs, the purchase |
| +// off, the billing address required and saved on the customer, the |
| +// customer's name saved and an optional tax id collected (so Stripe Tax can |
| +// reverse charge an EU business), automatic tax, the provider-time expiry, the success and cancel URLs, the purchase |
| // metadata on the session and on the subscription it makes, and either the |
| // resolved coupon (req.Coupon) or promotion codes. |
| func (p *Provider) PrepareCheckout(req billing.CheckoutRequest) (billing.Prepared, error) { |
| @@ -68,6 +69,15 @@ func (p *Provider) PrepareCheckout(req billing.CheckoutRequest) (billing.Prepare |
| } |
| form.Set("billing_address_collection", "required") |
| form.Set("customer_update[address]", "auto") |
| + // Optional VAT number: Stripe Tax applies reverse charge when an EU |
| + // business that gives one is eligible for it (never for a domestic sale, |
| + // which keeps VAT). tax_id_collection[required] stays unset (it |
| + // defaults to never). Stripe requires customer_update[name]=auto beside |
| + // tax_id_collection when the session has a customer, as ours always |
| + // does. These ride only on a newly prepared request: Send resends a |
| + // stored Prepared's bytes as they are. |
| + form.Set("customer_update[name]", "auto") |
| + form.Set("tax_id_collection[enabled]", "true") |
| form.Set("expires_at", strconv.FormatInt(req.ExpiresAt.Unix(), 10)) |
| return prepared(billing.PreparedCheckout, "/v1/checkout/sessions", form, req.IdempotencyKey) |
| } |
diff --git a/internal/billingstripe/prepared_test.go b/internal/billingstripe/prepared_test.go| index 4270b6c1a..47a46ea92 100644 |
| --- a/internal/billingstripe/prepared_test.go |
| +++ b/internal/billingstripe/prepared_test.go |
| @@ -259,7 +259,8 @@ func TestPrepareCheckoutCarriesResolvedCoupon(t *testing.T) { |
| "line_items[0][price]": {"price_p"}, "line_items[0][quantity]": {"1"}, |
| "line_items[1][price]": {"price_a"}, "line_items[1][quantity]": {"2"}, |
| "adaptive_pricing[enabled]": {"false"}, "billing_address_collection": {"required"}, |
| - "customer_update[address]": {"auto"}, "automatic_tax[enabled]": {"true"}, |
| + "customer_update[address]": {"auto"}, "customer_update[name]": {"auto"}, |
| + "tax_id_collection[enabled]": {"true"}, "automatic_tax[enabled]": {"true"}, |
| "expires_at": {strconv.FormatInt(providerDate.Add(time.Hour).Unix(), 10)}, |
| "success_url": {req.SuccessURL}, "cancel_url": {req.CancelURL}, |
| "allow_promotion_codes": {"true"}, |
| @@ -292,6 +293,65 @@ func TestPrepareCheckoutCarriesResolvedCoupon(t *testing.T) { |
| } |
| } |
| +// A Checkout create prepared before tax_id_collection existed is stored |
| +// with its bytes and resent as they are: Send never re-encodes a Prepared, |
| +// so the new fields reach only newly prepared requests. |
| +func TestSendStoredCheckoutWithoutTaxIDFieldsIsUnchanged(t *testing.T) { |
| + var c capture |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + got := c.add(r) |
| + fmt.Fprint(w, okBody(got.path)) |
| + })) |
| + defer srv.Close() |
| + p := prepProvider(t, srv.URL, nil) |
| + |
| + // The body PrepareCheckout produced before this change, frozen. |
| + stored := billing.Prepared{ |
| + Kind: billing.PreparedCheckout, Method: http.MethodPost, Path: "/v1/checkout/sessions", Key: "key-checkout-1", |
| + Body: []byte("adaptive_pricing%5Benabled%5D=false&allow_promotion_codes=true&automatic_tax%5Benabled%5D=true" + |
| + "&billing_address_collection=required&cancel_url=https%3A%2F%2Fconsole.example.com%2Fbilling" + |
| + "¤cy=usd&customer=cus_1&customer_update%5Baddress%5D=auto&expires_at=1792933200" + |
| + "&line_items%5B0%5D%5Bprice%5D=price_p&line_items%5B0%5D%5Bquantity%5D=1" + |
| + "&line_items%5B1%5D%5Bprice%5D=price_a&line_items%5B1%5D%5Bquantity%5D=2" + |
| + "&metadata%5Baccount_sqid%5D=bab&metadata%5Bcheckout_intent%5D=ci_1&metadata%5Bcurrency%5D=usd" + |
| + "&metadata%5Bprice_book%5D=example-v1&mode=subscription" + |
| + "&subscription_data%5Bmetadata%5D%5Baccount_sqid%5D=bab&subscription_data%5Bmetadata%5D%5Bcheckout_intent%5D=ci_1" + |
| + "&subscription_data%5Bmetadata%5D%5Bcurrency%5D=usd&subscription_data%5Bmetadata%5D%5Bprice_book%5D=example-v1" + |
| + "&success_url=https%3A%2F%2Fconsole.example.com%2Fbilling%3Fdone%3D1"), |
| + } |
| + want := string(stored.Body) |
| + if _, err := p.Send(context.Background(), stored); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := c.last(); string(got.body) != want || got.key != "key-checkout-1" { |
| + t.Errorf("stored create was altered:\n got %q\nwant %q", got.body, want) |
| + } |
| + if string(stored.Body) != want { |
| + t.Errorf("Send changed the stored body") |
| + } |
| + |
| + // A newly prepared request carries the new fields, and differs from the |
| + // stored one by exactly those two. |
| + fresh, err := p.PrepareCheckout(checkoutRequest()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fv, _ := url.ParseQuery(string(fresh.Body)) |
| + sv, _ := url.ParseQuery(want) |
| + for _, k := range []string{"customer_update[name]", "tax_id_collection[enabled]"} { |
| + if fv.Get(k) == "" || sv.Has(k) { |
| + t.Errorf("%s: fresh %q, stored %q", k, fv.Get(k), sv.Get(k)) |
| + } |
| + fv.Del(k) |
| + } |
| + if fv.Encode() != sv.Encode() { |
| + t.Errorf("fresh and stored differ by more than the new fields:\n %s\n %s", fv.Encode(), sv.Encode()) |
| + } |
| + if fv.Has("tax_id_collection[required]") { |
| + t.Errorf("tax id collection must stay optional") |
| + } |
| +} |
| + |
| func TestSendVerbatimOneRequest(t *testing.T) { |
| var c capture |
| var mode atomic.Value |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index d426e1b9f..5f9b7c710 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -46,4 +46,5 @@ plan14-root-reads-fleet-routes-followups.tsv 1379d066c8dd2335d95d5f6e9c7bce65ff5 |
| plan14-root-reads-tunnel-websockets.tsv 949bc734a293366e6b2700244af5110dd6e84b5432023e991c09e806afd62483 |
| plan14-root-reads-console-protection-tab.tsv eaeb153ab7a7a849edc9c6e92f2ac5c709c6e39044a647971cf1fa5ebcb660c8 |
| plan14-root-reads-devbox-mode.tsv 43d1824141f0ce7024cc3740ab5feac3f3539322f8afb856c9ca2f10d5095e95 |
| -plan14-root-reads-managed-fleets-1b.tsv 708f30f964eeadb3e585196de9a6135c4e3db12611b1e0140cdebb6b4d5c8bb8 |
| +plan14-root-reads-first-deploy-493.tsv 6b9aa3f2b21250d40b910ad1d29362687ec57ba5e895157670b785c0c3978f52 |
| +plan14-root-reads-managed-fleets-1b.tsv 1b3188c3fb086cc2bfe8cff5aafb4f0d0d26fd1bd977ff2a167f400248737889 |
diff --git a/internal/provision/testdata/plan14-root-reads-first-deploy-493.tsv b/internal/provision/testdata/plan14-root-reads-first-deploy-493.tsv| new file mode 100644 |
| index 000000000..cba534f05 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-first-deploy-493.tsv |
| @@ -0,0 +1,8 @@ |
| +# Census overlay first-deploy-493, written by census-propose (#369). census-ruling-first-deploy-493, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-first-deploy-493.md. |
| +# 1 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +@legacy dc432cd1d82ad3c26f62b50049f7a738a07aaf9afe2dbab4d145e0d60eb67e59 deploy.go runDeploy legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-edge-asset-cache-1;basis=takes --assets and --no-assets, refuses both together and bad folders before anything runs (deployAssets), reads the folders saved in .carlos/config for the session's console through configAssets (the config walk the CLI already makes), and saves a new list there as it saves the other deploy settings; read site unchanged (1), none added;rev3=census-ruling-gated-deploy-watch-164;basis=the static-deploy branch passes its watch targets through passGatedTargets (a console POST for a gate pass per gated host) and passes the gated-host set to watchDeployed; no new local read, read site unchanged (1), none added;rev3=census-ruling-region-labels;basis=builds a host-to-label map (hostPlaces) from the instance list it already read and passes it to the static watch targets and watchDeployed, so the watch lines say where; no read added;rev3=census-ruling-first-deploy-493;basis=Sequences existing console APIs for confirmed-missing app and first instance creation, with repeatable environment values; local artifact preflight before these new writes. Existing config artifact stat read retained. file:Stat@9052 78b4df11f549fefa38eea6581bd465255dba4d891db1bddace4c5178a56d075d |
| +@legacy a946e716ca8becb86501be46be0f2fc2155e385b9544a8716106359832addfe3 deploy_first_preflight.go deployArtifactPreflight legacy accepted-legacy accepted-legacy;rev3=census-ruling-first-deploy-493;basis=Checks user-supplied deploy artifact paths with Stat and Open before setup mutations. These are the same member CLI paths subsequently read by runShipAPI; no root command uses this helper, no new root input authority. file:Open@1072,file:Stat@726 77e6482e548dc54d670aa86445ed16226fafe245a0ebacbb025d8f87ab19c0d2 |
| +deploy.go runDeploy legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-edge-asset-cache-1;basis=takes --assets and --no-assets, refuses both together and bad folders before anything runs (deployAssets), reads the folders saved in .carlos/config for the session's console through configAssets (the config walk the CLI already makes), and saves a new list there as it saves the other deploy settings; read site unchanged (1), none added;rev3=census-ruling-gated-deploy-watch-164;basis=the static-deploy branch passes its watch targets through passGatedTargets (a console POST for a gate pass per gated host) and passes the gated-host set to watchDeployed; no new local read, read site unchanged (1), none added;rev3=census-ruling-region-labels;basis=builds a host-to-label map (hostPlaces) from the instance list it already read and passes it to the static watch targets and watchDeployed, so the watch lines say where; no read added;rev3=census-ruling-first-deploy-493;basis=Sequences existing console APIs for confirmed-missing app and first instance creation, with repeatable environment values; local artifact preflight before these new writes. Existing config artifact stat read retained. file:Stat@9052 78b4df11f549fefa38eea6581bd465255dba4d891db1bddace4c5178a56d075d |
| +deploy_first_preflight.go deployArtifactPreflight legacy accepted-legacy accepted-legacy;rev3=census-ruling-first-deploy-493;basis=Checks user-supplied deploy artifact paths with Stat and Open before setup mutations. These are the same member CLI paths subsequently read by runShipAPI; no root command uses this helper, no new root input authority. file:Open@1072,file:Stat@726 77e6482e548dc54d670aa86445ed16226fafe245a0ebacbb025d8f87ab19c0d2 |
| +@coverage . 66e25cd79780b2c5a193def2149433a3e2cc75f47fda9d08649fc7a1f6ede1a0 |
diff --git a/internal/provision/testdata/plan14-root-reads-managed-fleets-1b.tsv b/internal/provision/testdata/plan14-root-reads-managed-fleets-1b.tsv| index c19e284ee..379d87626 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-managed-fleets-1b.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-managed-fleets-1b.tsv |
| @@ -73,7 +73,7 @@ internal/activator/activator.go Service.doWake legacy accepted-legacy accepted-l |
| internal/activator/backend_exec.go ExecBackend.restorePlain legacy accepted-legacy accepted-legacy;rev3=census-ruling-seeded-instances;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): body of the frozen ExecBackend.Restore, which is now its dispatcher, with the seed marker reconciled before the warm-cache check; same staging fallback and replica restore;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: first asks haRestore(ctx, rt) (+whole:Route x2: rt to haRestore and to restoreHA); an HA host restores through restoreHA (hawake.go, a new unit) and never through the warm cache or the staging fallback; an error there fails the restore; a non-HA host takes the unchanged path;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (Task 3, rule 6 start rule): the +whole:Route sites are calls taking rt: reconcileAssignment before the seed-marker check (a labelled row's copy not kept under rt.Assigned is moved into <DataDir>/.superseded/<host>/, never deleted), startAllowed on the warm-cache, restored and fresh paths (a labelled row may refuse with ErrNothingToRestore), and establishAssignment after a restore and before a fresh boot (writes the <db>.assigned marker). Task 6a's record clear after a restore is removed. An unlabelled row (Assigned "") takes none of these. Agent, not root; it refuses more, never less. file:Stat@1179,registry:Host@370,whole:Route@1036,whole:Route@1116,whole:Route@1392,whole:Route@243,whole:Route@323,whole:Route@390,whole:Route@5629,whole:Route@5719,whole:Route@6296,whole:Route@6527,whole:Route@659 35c21389c435c3f11579e2e9e38f2b0e7a00203f77ef539024b84539134b7385 |
| internal/edge/edge.go Edge.Reload legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-design-edge-rate-limit-358;basis=each route's upstream entry gains rate: e.parseRateSettings(t), the row's rate_limit column parsed once per reload; the one added site is that whole:Route pass of t (parseRateSettings is a new unit, classified in the decisions overlay); no other read added;rev3=census-ruling-certwarm-wake;basis=the single reload hook call becomes runReloadHooks(), which runs every registered hook in order (#386); no read added, same 57 sites (56 before #358 landed on main);rev3=census-ruling-edge-asset-cache-3;basis=each tenant reverse proxy built in the switch (the tunnel, fleet, socket and TCP arms, every *httputil.ReverseProxy) is installed behind assetScrubbedProxy, which hands the proxy an assetInformationalScrub writer so an app's 1xx (103) loses the asset cache's reserved headers (X-Carlos-Asset-Fill, -Fill-Ack, -Expires, Carlos-Cache) on every local path, as the backhaul already does (final review F6); a type check of the proxy it just built and a wrapper around it; static and status handlers untouched; read sites unchanged (57), offsets moved; no read added;rev3=census-ruling-alias-wake-338;basis=#338 follow-up: after the path fold, a resolved platform alias takes its source's own upstream entry (same proxy, route, hibernating: the existing activator wake, lease and fence), keeping its own prefix map (none for a minted apex) and never inheriting the source's (Astra r2 P1); a refused alias, or one whose source has no entry, is dropped from the map (not served, not Allowed); the attached-hostname fold clears platformAlias;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: the activator-managed test (generation proxy, hib, no-activator 404) is Route.ActivatorOwned instead of Kind and Hibernate inline, so a resident rootfs instance goes through the activator; binary rows unchanged;rev3=census-ruling-edge-roll-blip;basis=the tcpProxy and multiProxy calls pass e.hold (the per-Edge localHold set once in newEdge): a loopback TCP upstream that refuses is redialled for up to 13 s and a probed route with a local upstream waits for prober readmission instead of answering 502/503 (#434 part B); edge-side dial policy only, no read added, same 52 sites;rev3=census-ruling-regional-domains-447;basis=#447 Task 5: after the alias fold, reads the regional_domains rows (e.reg.ListRegional; an error aborts the reload as every registry read here does) and applies them with foldRegional against the routes slice the same reload read; the added reads are that one registry list and the routes already read;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Tasks 4 and 6: the forward case (fleetProxy toward the binding's FleetBox, throttled refusal); one refusal check before the switch from FleetArmVerdict (sidecar not judged; a non-ready forward row refused; a forward row always judged by FleetServeEligible, any other row only where tunnels are on; an alias of a refused source refused with it); the accountless note; path rows of a forward host not folded; no alias folded onto a refused row; refusedHosts held through every fold. ListFleets and FleetChannelAuth read before the loop (+registry:FleetBox, +registry:Host x7, +whole:Route x3). Serving only; the hub's agent, not root. Review R1 finding 2: the switch reads verdict.Served (FleetArmVerdict) by host; the forward case and the fleet-placed case take their fleet from it (served.Fleet) instead of FleetPlacement(t.Region), and an admitted forward row not Served continues rather than falling through (+registry:Host, -registry:Region); the same rows take the same arms; no read added. Review R2: the switch is on DispatchArm(t, viaFleet, tunnels) (the order moved there unchanged: forward only when in Arm, own Tunnel, fleet, socket, addrs, static, status, else continue), the fleet cases read verdict.Arm (renamed from Served), and the platform-alias fold is foldPlatformAliases with the same take (source entry, own paths, alias marks) and the same refusal log (-registry:Kind x2, -registry:Socket, -registry:Tunnel, +whole:Route: those reads moved into DispatchArm); same rows, same arms, same entries; no read added.;rev3=census-ruling-fleet-routes-followups;basis=the owners map is now e.reg.FleetOwners() instead of ListFleets folded inline: the same fresh-connection ListFleets read and the same name->account map (-registry:Account, -registry:Name, -whole:Fleet x2 move into Registry.FleetOwners); no read added; same error path (abort the reload);rev3=census-ruling-tunnel-websockets;basis=The ArmTunnel arm now records its tenancy (Account, App, Tunnel) copied from the row t that Reload already lists; no new registry query, no file read. Also the reload mutex taken first and held to return, five nil-in-production test hooks, and the sweepUpgrades call after the swap, which reads only the map Reload has just built (spec 7, Tasks 3 and 4).;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (Task 5, rule 3): the two fleet proxy builds pass the row to fleetBoxOf(t) instead of reading t.FleetBox (-registry:FleetBox x2, +whole:Route x2); fleetBoxOf answers FleetLabel as authoritative when set, else FleetBox; an authoritative box has no fallback to another of the fleet's channels (503 errFleetDark instead). The edge in the agent, not root; it routes to fewer channels, never more. registry:Account@9444,registry:Alias@24246,registry:Alias@24333,registry:Alias@24913,registry:App@9460,registry:Health@13185,registry:Health@13311,registry:Host@10771,registry:Host@10828,registry:Host@10864,registry:Host@11607,registry:Host@13794,registry:Host@13889,registry:Host@14177,registry:Host@14203,registry:Host@14255,registry:Host@18708,registry:Host@20615,registry:Host@20923,registry:Host@20950,registry:Host@21765,registry:Host@22337,registry:Host@24667,registry:Host@24716,registry:Host@4701,registry:Host@4755,registry:Host@4805,registry:Host@5826,registry:Kind@17044,registry:Kind@17066,registry:Prefix@22312,registry:Socket@11671,registry:Socket@20931,registry:Status@4626,registry:Target@22324,registry:Tunnel@9304,registry:Tunnel@9475,registry:Version@17025,registry:Version@17127,whole:RegionalDomain@25555,whole:Route@10919,whole:Route@11027,whole:Route@11727,whole:Route@14328,whole:Route@14392,whole:Route@14443,whole:Route@20983,whole:Route@20990,whole:Route@21086,whole:Route@22200,whole:Route@23368,whole:Route@25547,whole:Route@294,whole:Route@3381,whole:Route@3439,whole:Route@5855,whole:Route@6731,whole:Route@6839,whole:Route@9366,whole:RouteAlias@24217,whole:RoutePath@21743 006faba36713e6d70771282762d0ede361ea9de04106470884b7d0bf6ffc8153 |
| internal/registry/fleets.go Registry.migrateFleets legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-fleet-secrets-key;basis=fleet secrets key (#366): four more idempotent migration statements: ALTER TABLE fleets ADD COLUMN for secrets_pubkey, secrets_key_fp, secrets_key_set_at, secrets_key_set_by (duplicate column ignored) and CREATE UNIQUE INDEX IF NOT EXISTS fleets_secrets_key_fp ON fleets (secrets_key_fp) WHERE secrets_key_fp != ''; CREATE TABLE IF NOT EXISTS fleet_secrets_key_fps (fp primary key, fleet, account, at), the permanent reservation of every registered fingerprint to its fleet, and an idempotent backfill INSERT ... SELECT of the fleets rows' current non-empty fingerprints ON CONFLICT(fp) DO NOTHING; fixed SQL, no new read of any input;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (Task 6b): two more idempotent statements, ALTER TABLE fleet_boxes ADD COLUMN draining_since INTEGER and labelled_at INTEGER (duplicate column ignored), the +file:Exec and +registry:sql sites. Fixed SQL, no input. Registry side, not root. file:Exec@1207,file:Exec@1699,file:Exec@1933,file:Exec@2471,file:Exec@2686,file:Exec@313,file:Exec@57,file:Exec@735,registry:sql@1207,registry:sql@1699,registry:sql@1933,registry:sql@2471,registry:sql@2686,registry:sql@313,registry:sql@57,registry:sql@735 7d2d5e945297abc2a6c97c2b75895e5c6602200a2bea505c4858f7d5a2d0da86 |
| -@coverage . 5fe34eb66eed4348b733bdfa8883c55185c213bda95c0265bbe87321f5fcf397 |
| +@coverage . 586fbf0be31dca252bf0105a58bb26de6b6416a9c41e5bb67f0cde48d4135a63 |
| @coverage internal/activator e4b12ea58c39000f84f3c687891933573b64d0cbcf4c45e22f3cb39a9124b651 |
| @coverage internal/edge 6c7b58a499079da5fcb4d110135ee546b3917cb808453764619bce513c15d8b1 |
| @coverage internal/host 5b39a530b7b83006a11b2740aa5589c0caf3ecf84966786b09290c8fe508e0b9 |