carlos / platform Public

Merge origin/main (cbd8a0b5, checkout-tax-id) into sponsor-existing-accounts

The census chain conflicted (both sides appended a line). Resolved the
census way: main's chain taken whole, then `make census-propose
NAME=sponsor-existing-accounts` re-layered this branch's overlay on top
and appended its chain line under main's seal. The overlay's bytes are
unchanged (main did not touch internal/plans), so the internal/plans
envelope Astra approved at 1237aa42 is the one pinned.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 41b27d2c1421b53e111c8298f643a00ba72b90b3 parent 1237aa4parent cbd8a0b
35 files changed, +2,451 −88
  • apimode.go +7 −1
  • copy-review/result.json +150 −0
  • copy-review/strings.json +114 −0
  • deploy.go +80 −15
  • deploy_first.go +198 −0
  • deploy_first_cli_test.go +145 −0
  • deploy_first_copy.go +39 −0
  • deploy_first_preflight.go +63 −0
  • deploy_first_preflight_test.go +46 −0
  • deploy_first_test.go +470 −0
  • docs/site/cli.md +6 −0
  • docs/site/plans.md +1 −1
  • docs/superpowers/notes/census-proposal-first-deploy-493.md +23 −0
  • docs/superpowers/notes/census-proposal-sponsor-existing-accounts.md +1 −1
  • docs/superpowers/plans/2026-10-25-operator-pages-copy.md +2 −2
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-checkout-tax-id.md +23 −0
  • docs/superpowers/reviews/first-deploy-493-brief.md +7 −0
  • docs/superpowers/reviews/first-deploy-493-opus.md +63 −0
  • internal/billingstripe/prepared.go +12 −2
  • internal/billingstripe/prepared_test.go +61 −1
  • internal/console/auditdetail_test.go +8 −5
  • internal/console/opactivity.go +9 −4
  • internal/console/opactivity_copy.go +37 −0
  • internal/console/opactivity_group.go +260 −0
  • internal/console/opactivity_group_test.go +523 −0
  • internal/console/opactivity_test.go +4 −2
  • internal/console/opdashboard.go +20 −5
  • internal/console/opdashboard_test.go +17 −35
  • internal/console/opperson.go +2 −2
  • internal/console/opshots_test.go +12 −0
  • internal/console/static/ops.css +19 −3
  • internal/console/templates/ops_activity.html +13 −3
  • internal/console/templates/ops_dashboard.html +6 −5
  • internal/provision/testdata/plan14-root-reads-chain.tsv +2 −1
  • internal/provision/testdata/plan14-root-reads-first-deploy-493.tsv +8 −0

CI passed — run details

diff --git a/apimode.go b/apimode.go
index 0f0d248bf..697899355 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 eaa4d1df4..e01e9bc18 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 53dd875bd..5f7e15dd1 100644
--- a/docs/site/plans.md
+++ b/docs/site/plans.md
@@ -213,7 +213,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-sponsor-existing-accounts.md b/docs/superpowers/notes/census-proposal-sponsor-existing-accounts.md
index 0fceefd6a..c5616ac04 100644
--- a/docs/superpowers/notes/census-proposal-sponsor-existing-accounts.md
+++ b/docs/superpowers/notes/census-proposal-sponsor-existing-accounts.md
@@ -6,6 +6,6 @@ Envelopes re-pinned: `internal/plans`.
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.
-Seal: `43d1824141f0ce7024cc3740ab5feac3f3539322f8afb856c9ca2f10d5095e95` → `43d1824141f0ce7024cc3740ab5feac3f3539322f8afb856c9ca2f10d5095e95`.
+Seal: `6b9aa3f2b21250d40b910ad1d29362687ec57ba5e895157670b785c0c3978f52` → `6b9aa3f2b21250d40b910ad1d29362687ec57ba5e895157670b785c0c3978f52`.
Overlay: `internal/provision/testdata/plan14-root-reads-sponsor-existing-accounts.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/plans/2026-10-25-operator-pages-copy.md b/docs/superpowers/plans/2026-10-25-operator-pages-copy.md
index 9a595cb51..077fc5320 100644
--- a/docs/superpowers/plans/2026-10-25-operator-pages-copy.md
+++ b/docs/superpowers/plans/2026-10-25-operator-pages-copy.md
@@ -143,9 +143,9 @@ The bar and rail on every operator page.
| OPS-57 | templates/ops_dashboard.html | No one has signed up yet. | approved |
| OPS-58 | templates/ops_dashboard.html | Latest activity | approved |
| OPS-59 | templates/ops_dashboard.html | All activity | approved |
-| OPS-60 | templates/ops_dashboard.html (Activity reuses it) | When | approved |
+| OPS-60 | templates/ops_activity.html (the dashboard's Latest activity used it until fleet-activity-grouping) | When | approved |
| OPS-61 | templates/ops_dashboard.html (Activity reuses it) | Who | approved |
-| OPS-62 | templates/ops_dashboard.html (Activity reuses it) | What | approved |
+| OPS-62 | templates/ops_activity.html (the dashboard's Latest activity used it until fleet-activity-grouping) | What | approved |
| OPS-63 | templates/ops_dashboard.html (Activity reuses it) | App | approved |
| OPS-64 | templates/ops_dashboard.html | Nothing has happened yet. | approved |
| OPS-65 | templates/ops_dashboard.html | All boxes | approved |
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" +
+ "&currency=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/console/auditdetail_test.go b/internal/console/auditdetail_test.go
index 721a71e77..b813ca252 100644
--- a/internal/console/auditdetail_test.go
+++ b/internal/console/auditdetail_test.go
@@ -141,19 +141,22 @@ func TestAuditWhatOfOtherRows(t *testing.T) {
// TestOperatorFeedsShowWhat: on Activity, the dashboard and a person page,
// a JSON row is its summary over the escaped, indented data in a native
-// <details>, and long text is one line with its whole in title.
+// <details>, and long text is one line with its whole in title. The
+// dashboard shows each person's latest row alone, so ben's latest is the
+// JSON row and ann's the long one.
func TestOperatorFeedsShowWhat(t *testing.T) {
fx := newConsoleFixture(t)
w := seedOperatorWorld(t, fx)
long := strings.Repeat("Changed a long setting ", 4)
- for _, r := range []Activity{
- {Action: "store-apply", Detail: `{"note":"<script>alert(1)</script>"}`},
- {Action: "env-set", Detail: long},
- } {
+ jsonRow := Activity{Action: "store-apply", Detail: `{"note":"<script>alert(1)</script>"}`}
+ for _, r := range []Activity{jsonRow, {Action: "env-set", Detail: long}} {
if err := fx.st.RecordActivity(w.shop.ID, "shop", "ann@example.com", r, w.now); err != nil {
t.Fatal(err)
}
}
+ if err := fx.st.RecordActivity(w.notes.ID, "notes", "ben@example.com", jsonRow, w.now); err != nil {
+ t.Fatal(err)
+ }
for path, body := range map[string]string{
"/fleet/activity": peopleGet(t, fx, w.c, "/fleet/activity"),
"/fleet": dashGet(t, fx, w.c),
diff --git a/internal/console/opactivity.go b/internal/console/opactivity.go
index 0e3deae2c..6f870db9a 100644
--- a/internal/console/opactivity.go
+++ b/internal/console/opactivity.go
@@ -138,8 +138,10 @@ type feedView struct {
AccountName string
AccountDeleted bool
Who, WhoHref string
- Rows []FeedRow
- Pager opPager
+ // Entries is the page's rows as lines: ship and promote merged, then
+ // bursts folded (opactivity_group.go), in the rows' order.
+ Entries []activityEntry
+ Pager opPager
}
// feedDropdown is the kind filter: the current kind as its label, each
@@ -155,7 +157,8 @@ func feedDropdown(q feedQuery) opDropdown {
// handleActivity serves Activity, for signed-in operators only, behind
// operatorOnly's 404-to-everyone gate. It reads one row past the page to
-// know whether Older exists. The account filter is resolved whatever the
+// know whether Older exists. The filters narrow the rows read; the page's
+// rows are then merged and folded for display (opactivity_group.go). The account filter is resolved whatever the
// account's deleted_at (OperatorAccountBySqid), so a deleted account's
// history stays reachable from its links; a sqid with no row shows nothing.
// The person filter is resolved as the person page resolves its address
@@ -214,7 +217,9 @@ func (s *Server) handleActivity(w http.ResponseWriter, r *http.Request) {
if older {
rows = rows[:feedPageSize]
}
- v.Rows = rows
+ // Merging and folding work within the page; the cursor below is the
+ // last stored row read, so paging is the same whatever they fold.
+ v.Entries = foldBursts(mergeShipPromote(rows))
if q.Before > 0 {
v.Pager.Items = append(v.Pager.Items, opPageItem{Label: "Newest", Href: q.first().href()})
}
diff --git a/internal/console/opactivity_copy.go b/internal/console/opactivity_copy.go
new file mode 100644
index 000000000..8b63efb76
--- /dev/null
+++ b/internal/console/opactivity_copy.go
@@ -0,0 +1,37 @@
+package console
+
+// The words of the grouped activity views (opactivity_group.go): the
+// dashboard's one row per person, Activity's folded bursts and the merged
+// ship and promote row. Every human-facing string those views add lives
+// here and nowhere else. Copy review: Paul approved every string below
+// unchanged on 2026-10-31.
+const (
+ // The dashboard's Latest activity columns, in order.
+ activityHeadLastActive = "Last active"
+ activityHeadWho = "Who"
+ activityHeadActions = "Actions"
+ activityHeadLatest = "Latest"
+ activityHeadApps = "Apps"
+
+ // A person's count of actions on the dashboard.
+ activityActionsOne = "1 action"
+ activityActionsMany = "%d actions"
+
+ // A person's apps on the dashboard: the most recent app's name and how
+ // many other apps they touched.
+ activityAppsMore = "%s and %d more"
+
+ // A folded burst on Activity: how many actions, on which app, or with
+ // no app.
+ activityFoldOnApp = "%d actions on %s"
+ activityFoldBare = "%d actions"
+
+ // A ship and the promote of the same build, shown as one row: the
+ // build, the channel and the ship's source marker, such as "(cli)".
+ activityShippedPromoted = "shipped and promoted %s to %s %s"
+)
+
+// activityDashHead is the dashboard's Latest activity head row.
+var activityDashHead = []string{
+ activityHeadLastActive, activityHeadWho, activityHeadActions, activityHeadLatest, activityHeadApps,
+}
diff --git a/internal/console/opactivity_group.go b/internal/console/opactivity_group.go
new file mode 100644
index 000000000..e756e813c
--- /dev/null
+++ b/internal/console/opactivity_group.go
@@ -0,0 +1,260 @@
+package console
+
+import (
+ "fmt"
+ "strings"
+ "time"
+)
+
+// How the operator pages group audit rows for display (Paul, 2026-10-31):
+// one person's burst of actions should not hide everyone else's. Three
+// display-only rules, none of which changes a stored row:
+//
+// - a ship followed by the promote of the same build, by the same actor
+// on the same app within activityBurstGap, shows as one row
+// (mergeShipPromote): the dashboard, Activity and the person page;
+// - on Activity, a run of rows by the same actor on the same app (or
+// with no app), each within activityBurstGap of the row above it,
+// folds into one row that opens onto them (foldBursts);
+// - the dashboard's Latest activity is one row per person (dashActors).
+//
+// Everything works on rows already read, newest first by id: nothing here
+// reads the store.
+
+// activityBurstGap is the longest gap between two rows of one burst, and
+// between a ship and the promote it merges with.
+const activityBurstGap = 10 * time.Minute
+
+// activityRow is one row as an operator list shows it: a stored audit row,
+// or a ship and the promote of its build merged into one (Detail then
+// holds the merged sentence, and the row is the promote's: its id, time
+// and action). N is how many stored rows it stands for, 1 or 2.
+type activityRow struct {
+ FeedRow
+ N int
+ // Oldest is the time of the oldest stored row the line stands for:
+ // a merged ship and promote is timed at the promote (At) but began at
+ // the ship, and a burst is judged on the gap from there.
+ Oldest time.Time
+}
+
+// oldest is when the line's first stored row happened (At for a line of
+// one row).
+func (r activityRow) oldest() time.Time {
+ if r.Oldest.IsZero() {
+ return r.At
+ }
+ return r.Oldest
+}
+
+// The source markers a merged row accepts: the ship's (apicli.go's ship,
+// apiship_rootfs.go's rootfs ship) and the promote's (apicli.go's promote).
+// A console promote (no marker) or a confirmed proposal ("(proposed by
+// ...)") is never merged: the merged sentence could not say both sources.
+var (
+ activityShipSources = map[string]bool{"(cli)": true, "(cli, rootfs)": true}
+ activityPromoteSource = "(cli)"
+)
+
+// activityParseShip reads a ship row's stored Detail, "shipped <build>
+// <marker>": ok only for that exact shape with a known marker.
+func activityParseShip(r FeedRow) (build, marker string, ok bool) {
+ if r.Action != "ship" {
+ return "", "", false
+ }
+ rest, ok := strings.CutPrefix(r.Detail, "shipped ")
+ if !ok {
+ return "", "", false
+ }
+ build, marker, ok = strings.Cut(rest, " ")
+ if !ok || build == "" || !activityShipSources[marker] {
+ return "", "", false
+ }
+ return build, marker, true
+}
+
+// activityParsePromote reads a promote row's stored Detail, "promoted
+// <build> to <channel> (cli)": ok only for that exact shape.
+func activityParsePromote(r FeedRow) (build, channel string, ok bool) {
+ if r.Action != "promote" {
+ return "", "", false
+ }
+ rest, ok := strings.CutPrefix(r.Detail, "promoted ")
+ if !ok {
+ return "", "", false
+ }
+ build, rest, ok = strings.Cut(rest, " to ")
+ if !ok || build == "" || strings.ContainsAny(build, " \t\n") {
+ return "", "", false
+ }
+ channel, marker, ok := strings.Cut(rest, " ")
+ if !ok || channel == "" || marker != activityPromoteSource {
+ return "", "", false
+ }
+ return build, channel, true
+}
+
+// activityMerge is the one row a promote and the row below it (older)
+// show as, when that row is the ship of the same build by the same actor
+// on the same app of the same account, no more than activityBurstGap
+// before it.
+func activityMerge(promote, ship FeedRow) (activityRow, bool) {
+ build, channel, ok := activityParsePromote(promote)
+ if !ok {
+ return activityRow{}, false
+ }
+ shipped, marker, ok := activityParseShip(ship)
+ if !ok || shipped != build {
+ return activityRow{}, false
+ }
+ if promote.Address != ship.Address || promote.AccountSqid != ship.AccountSqid || promote.App != ship.App || promote.App == "" {
+ return activityRow{}, false
+ }
+ if gap := promote.At.Sub(ship.At); gap < 0 || gap > activityBurstGap {
+ return activityRow{}, false
+ }
+ merged := promote
+ merged.Detail = fmt.Sprintf(activityShippedPromoted, build, channel, marker)
+ return activityRow{FeedRow: merged, N: 2, Oldest: ship.At}, true
+}
+
+// mergeShipPromote is rows (newest first) as a list shows them: each
+// promote directly above the ship it merges with (activityMerge) becomes
+// one row, timed at the promote; every other row stands as it is.
+func mergeShipPromote(rows []FeedRow) []activityRow {
+ out := make([]activityRow, 0, len(rows))
+ for i := 0; i < len(rows); i++ {
+ if i+1 < len(rows) {
+ if m, ok := activityMerge(rows[i], rows[i+1]); ok {
+ out = append(out, m)
+ i++
+ continue
+ }
+ }
+ out = append(out, activityRow{FeedRow: rows[i], N: 1})
+ }
+ return out
+}
+
+// activityEntry is one line of Activity: a row, or a burst folded into
+// one (Rows holds the burst's rows, newest first, and the line is its
+// newest). Actions is the stored rows the line stands for.
+type activityEntry struct {
+ activityRow
+ Rows []activityRow
+ Actions int
+}
+
+// Folded is whether the line is a burst of two rows or more.
+func (e activityEntry) Folded() bool { return len(e.Rows) > 1 }
+
+// FoldText is a burst's What: how many actions, and on which app.
+func (e activityEntry) FoldText() string {
+ if e.App != "" {
+ return fmt.Sprintf(activityFoldOnApp, e.Actions, e.App)
+ }
+ return fmt.Sprintf(activityFoldBare, e.Actions)
+}
+
+// activitySameBurst is whether b, the row below a, continues a's burst:
+// the same actor, account and app (or both with no app), no more than
+// activityBurstGap apart. The gap is between consecutive stored rows: from
+// a's oldest (a merged line's ship) to b's newest (a merged line's
+// promote), so merging never splits a burst the stored rows make.
+func activitySameBurst(a, b activityRow) bool {
+ if a.Address != b.Address || a.AccountSqid != b.AccountSqid || a.App != b.App {
+ return false
+ }
+ gap := a.oldest().Sub(b.At)
+ if gap < 0 {
+ gap = -gap
+ }
+ return gap <= activityBurstGap
+}
+
+// foldBursts is rows (newest first) as Activity's lines, in the same
+// order: each run of rows where every row continues the burst of the one
+// above it (activitySameBurst) is one line; a run of one is a plain line.
+func foldBursts(rows []activityRow) []activityEntry {
+ var out []activityEntry
+ for i := 0; i < len(rows); {
+ j := i + 1
+ for j < len(rows) && activitySameBurst(rows[j-1], rows[j]) {
+ j++
+ }
+ e := activityEntry{activityRow: rows[i]}
+ for _, r := range rows[i:j] {
+ e.Actions += r.N
+ }
+ if j-i > 1 {
+ e.Rows = rows[i:j]
+ }
+ out = append(out, e)
+ i = j
+ }
+ return out
+}
+
+// dashActor is one person on the dashboard's Latest activity: their newest
+// row's time, how many actions they made in the window, their latest
+// action (ship and promote merged) and the apps they touched.
+type dashActor struct {
+ Address string
+ At time.Time
+ Actions int
+ Latest activityRow
+ // Apps is the most recent app's name, with how many other apps they
+ // touched; "" when no row of theirs names an app.
+ Apps string
+}
+
+// ActionsText is the Actions cell.
+func (a dashActor) ActionsText() string {
+ if a.Actions == 1 {
+ return activityActionsOne
+ }
+ return fmt.Sprintf(activityActionsMany, a.Actions)
+}
+
+// dashActors is up to limit people from rows (newest first), one each,
+// in the order of their newest row. An app is its account and name: two
+// accounts' apps of one name are two apps.
+func dashActors(rows []FeedRow, limit int) []dashActor {
+ var order []string
+ byActor := map[string][]FeedRow{}
+ for _, r := range rows {
+ if _, ok := byActor[r.Address]; !ok {
+ order = append(order, r.Address)
+ }
+ byActor[r.Address] = append(byActor[r.Address], r)
+ }
+ if len(order) > limit {
+ order = order[:limit]
+ }
+ out := make([]dashActor, 0, len(order))
+ for _, who := range order {
+ mine := byActor[who]
+ a := dashActor{Address: who, At: mine[0].At, Actions: len(mine), Latest: mergeShipPromote(mine)[0]}
+ type appKey struct{ acct, app string }
+ seen := map[appKey]bool{}
+ var recent string
+ for _, r := range mine {
+ if r.App == "" {
+ continue
+ }
+ k := appKey{r.AccountSqid, r.App}
+ if len(seen) == 0 {
+ recent = r.App
+ }
+ seen[k] = true
+ }
+ switch {
+ case len(seen) == 1:
+ a.Apps = recent
+ case len(seen) > 1:
+ a.Apps = fmt.Sprintf(activityAppsMore, recent, len(seen)-1)
+ }
+ out = append(out, a)
+ }
+ return out
+}
diff --git a/internal/console/opactivity_group_test.go b/internal/console/opactivity_group_test.go
new file mode 100644
index 000000000..3e18e09b4
--- /dev/null
+++ b/internal/console/opactivity_group_test.go
@@ -0,0 +1,523 @@
+package console
+
+import (
+ "fmt"
+ "html"
+ "net/http"
+ "regexp"
+ "slices"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+)
+
+// The grouped activity views (opactivity_group.go): the dashboard's one row
+// per person, Activity's folded bursts, and ship and promote merged on
+// every operator list. Every test here reads the pages through the real
+// handlers and templates.
+
+// dashActorCells is one row of the dashboard's Latest activity: who, the
+// Actions cell, the Latest cell's text and the Apps cell's markup.
+type dashActorCells struct{ Who, Actions, Latest, Apps string }
+
+var dashActorRow = regexp.MustCompile(`^><span class="rst-cell-mut" title="[^"]*">[^<]*</span>` +
+ `(?:<a href="[^"]*">([^<]*)</a>|<span>([^<]*)</span>)<span>([^<]*)</span>` +
+ `<span co-clip(?: title="[^"]*")?>([^<]*)</span>(<span>[^<]*</span>|<span class="rst-cell-mut">none</span>)</div>`)
+
+// dashActorRows is the dashboard's Latest activity: its head row and each
+// row parsed to its cells.
+func dashActorRows(t *testing.T, body string) (head string, rows []dashActorCells) {
+ t.Helper()
+ parts := dashRows(dashSection(t, body, "Latest activity"))
+ if len(parts) == 0 {
+ return "", nil
+ }
+ for _, r := range parts[1:] {
+ m := dashActorRow.FindStringSubmatch(r)
+ if m == nil {
+ t.Fatalf("a Latest activity row is not Last active, Who, Actions, Latest, Apps: %s", r)
+ }
+ rows = append(rows, dashActorCells{Who: html.UnescapeString(m[1] + m[2]), Actions: m[3],
+ Latest: html.UnescapeString(m[4]), Apps: html.UnescapeString(m[5])})
+ }
+ return parts[0], rows
+}
+
+// feedLine is one line of Activity: a row, or a folded burst whose What is
+// its fold text, whose When title is Title and whose rows are Inner.
+type feedLine struct {
+ feedRow
+ Fold bool
+ Title string
+ Inner []feedRow
+}
+
+var feedFoldSummary = regexp.MustCompile(`^<details co-fold><summary rst-lrow><span class="rst-cell-mut" title="([^"]*)">[^<]*</span>` +
+ `(?:<a href="([^"]*)">([^<]*)</a>|<span>([^<]*)</span>)(<a href="[^"]*">[^<]*</a>|<span class="rst-cell-mut">none</span>)` +
+ `<span co-clip>([^<]*)<span rst-caret aria-hidden="true"><svg[^>]*>.*?</svg></span></span>` +
+ `(<span>[^<]*</span>|<span class="rst-cell-mut">none</span>)</summary>$`)
+
+// feedLines is Activity's lines, newest first. It reads the template's
+// layout of one row per source line, so it is for rows with no stored
+// JSON (whose <pre> spans lines).
+func feedLines(t *testing.T, body string) []feedLine {
+ t.Helper()
+ list := dashCut(t, body, `<div rst-card co-cols="feed">`, "</main>")
+ var out []feedLine
+ var open *feedLine
+ row := func(line string) feedRow {
+ m := feedRowCells.FindStringSubmatch(strings.TrimPrefix(line, "<div rst-lrow"))
+ if m == nil {
+ t.Fatalf("a feed row is not When, Who, Account, What, App: %s", line)
+ }
+ return feedRow{Who: html.UnescapeString(m[2] + m[3]), WhoHref: html.UnescapeString(m[1]),
+ Account: m[4], What: html.UnescapeString(m[5]), App: m[6]}
+ }
+ for _, line := range strings.Split(list, "\n") {
+ line = strings.TrimSpace(line)
+ switch {
+ case strings.HasPrefix(line, "<details co-fold>"):
+ m := feedFoldSummary.FindStringSubmatch(line)
+ if m == nil {
+ t.Fatalf("a fold's summary is not When, Who, Account, its count, App: %s", line)
+ }
+ open = &feedLine{Fold: true, Title: m[1], feedRow: feedRow{Who: html.UnescapeString(m[3] + m[4]),
+ WhoHref: html.UnescapeString(m[2]), Account: m[5], What: html.UnescapeString(m[6]), App: m[7]}}
+ case line == "</details>" && open != nil: // the toolbar's dropdown closes its own
+ out = append(out, *open)
+ open = nil
+ case strings.HasPrefix(line, "<div rst-lrow>"):
+ if open != nil {
+ open.Inner = append(open.Inner, row(line))
+ } else {
+ out = append(out, feedLine{feedRow: row(line)})
+ }
+ }
+ }
+ if open != nil {
+ t.Fatal("a fold is never closed")
+ }
+ return out
+}
+
+// lineWhats is each inner row's What.
+func lineWhats(rows []feedRow) []string {
+ var out []string
+ for _, r := range rows {
+ out = append(out, r.What)
+ }
+ return out
+}
+
+// lineSummary is a line as "who: what [inner whats]", for comparing pages.
+func lineSummary(lines []feedLine) []string {
+ var out []string
+ for _, l := range lines {
+ s := l.Who + ": " + l.What
+ if l.Fold {
+ s += " [" + strings.Join(lineWhats(l.Inner), ", ") + "]"
+ }
+ out = append(out, s)
+ }
+ return out
+}
+
+// groupTitle is a row's When title for at.
+func groupTitle(at time.Time) string { return at.UTC().Format("2006-01-02 15:04 UTC") }
+
+// groupActions is the Actions cell for who's audit rows, every one of
+// them (the tests' worlds are smaller than the dashboard's window).
+func groupActions(t *testing.T, fx *consoleFixture, who string) string {
+ t.Helper()
+ ids, _ := feedAudit(t, fx, "address = ?", who)
+ if len(ids) == 1 {
+ return "1 action"
+ }
+ return fmt.Sprintf("%d actions", len(ids))
+}
+
+// groupRecord records one audit row at at, failing the test on an error.
+func groupRecord(t *testing.T, fx *consoleFixture, acct int64, app, who, action, detail string, at time.Time) {
+ t.Helper()
+ if err := fx.st.RecordActivity(acct, app, who, Activity{Action: action, Detail: detail}, at); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// groupCart gives shop's account a second app, cart.
+func groupCart(t *testing.T, fx *consoleFixture, w operatorWorld) {
+ t.Helper()
+ if _, err := fx.st.CreateAppIn(w.shop.ID, "cart", "ann@example.com", w.now); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// TestDashboardLatestActivityIsOnePersonPerRow: ann's ten-minute burst of
+// ten actions (create, config, ship and promote) no longer hides ben and
+// cat; her row counts the burst, shows her latest action with the
+// ship and promote merged, and names her most recent app and the other.
+// At most ten people show, newest first.
+func TestDashboardLatestActivityIsOnePersonPerRow(t *testing.T) {
+ fx := newConsoleFixture(t)
+ w := seedOperatorWorld(t, fx)
+ groupCart(t, fx, w)
+ t0 := w.now.Add(time.Minute)
+ groupRecord(t, fx, w.notes.ID, "notes", "ben@example.com", "rename", "Renamed notes", t0)
+ burst := []struct{ app, action, detail string }{
+ {"cart", "instance-create", "Created instance eu"},
+ {"shop", "instance-create", "Created instance uk"},
+ }
+ for i := 0; i < 6; i++ {
+ burst = append(burst, struct{ app, action, detail string }{"shop", "env-set", fmt.Sprintf("Set FOO_%d", i)})
+ }
+ burst = append(burst, struct{ app, action, detail string }{"shop", "ship", "shipped v7 (cli)"},
+ struct{ app, action, detail string }{"shop", "promote", "promoted v7 to canary/eu (cli)"})
+ for i, b := range burst {
+ groupRecord(t, fx, w.shop.ID, b.app, "ann@example.com", b.action, b.detail, t0.Add(time.Duration(i+1)*time.Minute))
+ }
+
+ head, rows := dashActorRows(t, dashGet(t, fx, w.c))
+ if want := "<span>Last active</span><span>Who</span><span>Actions</span><span>Latest</span><span>Apps</span>"; !strings.Contains(head, want) {
+ t.Errorf("Latest activity head: %s", head)
+ }
+ none := `<span class="rst-cell-mut">none</span>`
+ want := []dashActorCells{
+ {Who: "ann@example.com", Actions: groupActions(t, fx, "ann@example.com"), Latest: "shipped and promoted v7 to canary/eu (cli)", Apps: "<span>shop and 1 more</span>"},
+ {Who: "ben@example.com", Actions: groupActions(t, fx, "ben@example.com"), Latest: "Renamed notes", Apps: "<span>notes</span>"},
+ {Who: "cat@example.com", Actions: "1 action", Latest: "Signed in", Apps: none},
+ {Who: "paul@keymail.dev", Actions: "1 action", Latest: "Signed in for the first time", Apps: none},
+ }
+ if want[0].Actions != "13 actions" {
+ t.Errorf("ann has %s, want the burst's ten and the world's three", want[0].Actions)
+ }
+ if !slices.Equal(rows, want) {
+ t.Errorf("Latest activity =\n%+v\nwant\n%+v", rows, want)
+ }
+
+ // Eleven more people, each newer than ann: the ten newest show.
+ for i := 0; i < 11; i++ {
+ groupRecord(t, fx, 0, "", fmt.Sprintf("p%02d@example.com", i), "signin", "Signed in", t0.Add(time.Hour))
+ }
+ _, rows = dashActorRows(t, dashGet(t, fx, w.c))
+ if len(rows) != dashActivityPeople {
+ t.Fatalf("%d people in Latest activity, want %d", len(rows), dashActivityPeople)
+ }
+ for i, r := range rows {
+ if want := fmt.Sprintf("p%02d@example.com", 10-i); r.Who != want {
+ t.Errorf("row %d is %s, want %s", i, r.Who, want)
+ }
+ }
+}
+
+// TestActivityFoldsBursts: on Activity, ann's run of rows on shop, each
+// within ten minutes of the one above it, is one line timed at its newest,
+// opening onto the rows; her row eleven minutes before the run stays its
+// own line. Ben and cat, interleaved, never fold together. Two sign-ins in
+// a row with no app fold with no app named. Filters apply first: ben's
+// rows fold once cat's are filtered away, and cat's on shop once the
+// account filter drops ben's.
+func TestActivityFoldsBursts(t *testing.T) {
+ fx := newConsoleFixture(t)
+ w := seedOperatorWorld(t, fx)
+ t0 := w.now.Add(time.Minute)
+ ann := func(what string, at time.Duration) {
+ groupRecord(t, fx, w.shop.ID, "shop", "ann@example.com", "env-set", what, t0.Add(at))
+ }
+ ann("Early", 0)
+ ann("Burst 1", 11*time.Minute)
+ ann("Burst 2", 16*time.Minute)
+ ann("Burst 3", 21*time.Minute)
+ ann("Burst 4", 26*time.Minute)
+ groupRecord(t, fx, w.notes.ID, "notes", "ben@example.com", "rename", "Ben 1", t0.Add(27*time.Minute))
+ groupRecord(t, fx, w.shop.ID, "shop", "cat@example.com", "rename", "Cat 1", t0.Add(27*time.Minute))
+ groupRecord(t, fx, w.notes.ID, "notes", "ben@example.com", "rename", "Ben 2", t0.Add(28*time.Minute))
+ groupRecord(t, fx, w.shop.ID, "shop", "cat@example.com", "rename", "Cat 2", t0.Add(28*time.Minute))
+ groupRecord(t, fx, 0, "", "cat@example.com", "signin", "Signed in", t0.Add(30*time.Minute))
+ groupRecord(t, fx, 0, "", "cat@example.com", "signin", "Signed in", t0.Add(31*time.Minute))
+
+ lines := feedLines(t, peopleGet(t, fx, w.c, "/fleet/activity"))
+ want := []string{
+ "cat@example.com: 2 actions [Signed in, Signed in]",
+ "cat@example.com: Cat 2",
+ "ben@example.com: Ben 2",
+ "cat@example.com: Cat 1",
+ "ben@example.com: Ben 1",
+ "ann@example.com: 4 actions on shop [Burst 4, Burst 3, Burst 2, Burst 1]",
+ "ann@example.com: Early",
+ "ann@example.com: Invited dan@example.com",
+ }
+ if got := lineSummary(lines); len(got) < len(want) || !slices.Equal(got[:len(want)], want) {
+ t.Fatalf("Activity =\n%s\nwant it to start\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
+ }
+ none := `<span class="rst-cell-mut">none</span>`
+ if l := lines[0]; l.App != none || l.Account != none || l.Title != groupTitle(t0.Add(31*time.Minute)) {
+ t.Errorf("the sign-ins' fold = %+v, want no app or account, timed at the newest", l)
+ }
+ shopLink := `<a href="/fleet/activity?account=` + w.shop.Sqid + `">shop</a>`
+ if l := lines[5]; l.App != "<span>shop</span>" || l.Account != shopLink || l.WhoHref != "/fleet/people/ann@example.com" ||
+ l.Title != groupTitle(t0.Add(26*time.Minute)) {
+ t.Errorf("ann's fold = %+v, want shop's, linking ann, timed at Burst 4", l)
+ }
+
+ // A person filter: ben's two rows are now a run.
+ got := lineSummary(feedLines(t, peopleGet(t, fx, w.c, "/fleet/activity?who=ben@example.com")))
+ if want := []string{"ben@example.com: 2 actions on notes [Ben 2, Ben 1]", "ben@example.com: Made v1 live"}; len(got) < 2 || !slices.Equal(got[:2], want) {
+ t.Errorf("ben's Activity = %q, want %q", got, want)
+ }
+ // An account filter: cat's two on shop are now a run, and ann's burst
+ // still folds.
+ got = lineSummary(feedLines(t, peopleGet(t, fx, w.c, "/fleet/activity?account="+w.shop.Sqid)))
+ want = []string{
+ "cat@example.com: 2 actions on shop [Cat 2, Cat 1]",
+ "ann@example.com: 4 actions on shop [Burst 4, Burst 3, Burst 2, Burst 1]",
+ "ann@example.com: Early",
+ }
+ if len(got) < len(want) || !slices.Equal(got[:len(want)], want) {
+ t.Errorf("shop's Activity =\n%s\nwant it to start\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
+ }
+ // A kind filter: the sign-ins alone, cat's two folded.
+ got = lineSummary(feedLines(t, peopleGet(t, fx, w.c, "/fleet/activity?kind=signins")))
+ if len(got) == 0 || got[0] != "cat@example.com: 2 actions [Signed in, Signed in]" {
+ t.Errorf("the sign-ins = %q, want cat's two folded first", got)
+ }
+ for _, l := range got {
+ if strings.Contains(l, "Burst") || strings.Contains(l, "Ben") {
+ t.Errorf("the sign-ins kind shows %q", l)
+ }
+ }
+}
+
+// TestActivityFoldsWithinThePage: a burst longer than a page folds within
+// each page, and paging stays on the stored rows' ids: page one is one
+// line of fifty, Older starts after its fiftieth row, and page two folds
+// the burst's other five.
+func TestActivityFoldsWithinThePage(t *testing.T) {
+ fx := newConsoleFixture(t)
+ w := seedOperatorWorld(t, fx)
+ t0 := w.now.Add(time.Minute)
+ for i := 0; i < 55; i++ {
+ groupRecord(t, fx, w.shop.ID, "shop", "ann@example.com", "env-set", fmt.Sprintf("Set variable %02d", i), t0.Add(time.Duration(i)*time.Minute))
+ }
+ ids, details := feedAudit(t, fx, "")
+
+ body := peopleGet(t, fx, w.c, "/fleet/activity")
+ lines := feedLines(t, body)
+ if len(lines) != 1 || !lines[0].Fold || lines[0].What != "50 actions on shop" {
+ t.Fatalf("page one = %q, want one fold of fifty", lineSummary(lines))
+ }
+ if got := strings.Join(lineWhats(lines[0].Inner), "|"); got != strings.Join(details[:feedPageSize], "|") {
+ t.Errorf("page one's fold is not the newest fifty rows:\n got %s", got)
+ }
+ older := feedPagerLink(body, "Older")
+ if want := "/fleet/activity?before=" + strconv.FormatInt(ids[feedPageSize-1], 10); older != want {
+ t.Fatalf("Older = %q, want %q", older, want)
+ }
+ body = peopleGet(t, fx, w.c, older)
+ lines = feedLines(t, body)
+ if len(lines) == 0 || !lines[0].Fold || lines[0].What != "5 actions on shop" ||
+ strings.Join(lineWhats(lines[0].Inner), "|") != strings.Join(details[feedPageSize:feedPageSize+5], "|") {
+ t.Fatalf("page two = %q, want the burst's other five folded first", lineSummary(lines))
+ }
+ if got := feedPagerLink(body, "Newest"); got != "/fleet/activity" {
+ t.Errorf("page two's Newest = %q", got)
+ }
+}
+
+// TestShipAndPromoteMergeThroughTheDoors: a ship and a promote made
+// through the real CLI doors show as one row on Activity, the dashboard
+// and the person page, and neither stored row shows on its own. The
+// stored rows are unchanged.
+func TestShipAndPromoteMergeThroughTheDoors(t *testing.T) {
+ fx := newConsoleFixture(t)
+ liftShipBudget(fx)
+ c := signInOperator(t, fx)
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "titogo", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ token := cliToken(t, fx, "paul@keymail.dev", "code-group-merge")
+ if status, out := postShip(t, fx.ts.URL+"/api/cli/apps/bab/titogo/releases", token,
+ []shipPart{metaPart(t, "abc1234", "binary"), {name: "linux-arm64", body: randomBytes(t, 256)}}); status != http.StatusCreated {
+ t.Fatalf("ship = %d %v", status, out)
+ }
+ if status, out := postJSON(t, fx.ts.URL+"/api/cli/apps/bab/titogo/promote",
+ map[string]string{"version": "abc1234", "channel": "canary/x"}, token); status != http.StatusOK {
+ t.Fatalf("promote = %d %v", status, out)
+ }
+ _, stored := feedAudit(t, fx, "action IN ('ship', 'promote')")
+ if want := []string{"promoted abc1234 to canary/x (cli)", "shipped abc1234 (cli)"}; !slices.Equal(stored, want) {
+ t.Fatalf("stored rows = %q, want %q", stored, want)
+ }
+
+ merged := "<span co-clip>shipped and promoted abc1234 to canary/x (cli)</span>"
+ for path, body := range map[string]string{
+ "/fleet/activity": peopleGet(t, fx, c, "/fleet/activity"),
+ "/fleet": dashGet(t, fx, c),
+ "/fleet/people/paul@keymail.dev": personGet(t, fx, c, "paul@keymail.dev"),
+ } {
+ if strings.Count(body, merged) != 1 {
+ t.Errorf("%s does not show the ship and promote as one row", path)
+ }
+ for _, s := range stored {
+ if strings.Contains(body, ">"+s+"<") {
+ t.Errorf("%s shows %q on its own", path, s)
+ }
+ }
+ }
+ _, rows := dashActorRows(t, dashGet(t, fx, c))
+ if len(rows) == 0 || rows[0].Who != "paul@keymail.dev" || rows[0].Latest != "shipped and promoted abc1234 to canary/x (cli)" {
+ t.Errorf("the dashboard's first row = %+v, want paul's merged deploy", rows)
+ }
+}
+
+// TestShipAndPromoteMergeOnlyTheSameBuild: the merge needs the same
+// build, actor, account and app, the ship no more than ten minutes before
+// the promote, and both rows in the shape the CLI doors store. Each case
+// is thirty minutes from the next, so none merges or folds with another.
+func TestShipAndPromoteMergeOnlyTheSameBuild(t *testing.T) {
+ fx := newConsoleFixture(t)
+ w := seedOperatorWorld(t, fx)
+ groupCart(t, fx, w)
+ type row struct{ app, who, action, detail string }
+ ann := "ann@example.com"
+ // The cases that merge come last, so that they are among the twenty
+ // rows of ann's the person page shows.
+ cases := []struct {
+ name string
+ ship, prom row
+ gap time.Duration
+ merged string // "" when the two stay apart
+ }{
+ {"another build", row{"shop", ann, "ship", "shipped v4 (cli)"}, row{"shop", ann, "promote", "promoted v5 to canary/x (cli)"},
+ time.Minute, ""},
+ {"another actor", row{"shop", "cat@example.com", "ship", "shipped v6 (cli)"}, row{"shop", ann, "promote", "promoted v6 to canary/x (cli)"},
+ time.Minute, ""},
+ {"another app", row{"cart", ann, "ship", "shipped v7 (cli)"}, row{"shop", ann, "promote", "promoted v7 to canary/x (cli)"},
+ time.Minute, ""},
+ {"eleven minutes", row{"shop", ann, "ship", "shipped v8 (cli)"}, row{"shop", ann, "promote", "promoted v8 to canary/x (cli)"},
+ 11 * time.Minute, ""},
+ {"no source on the ship", row{"shop", ann, "ship", "shipped v9"}, row{"shop", ann, "promote", "promoted v9 to canary/x (cli)"},
+ time.Minute, ""},
+ {"a console promote", row{"shop", ann, "ship", "shipped v10 (cli)"}, row{"shop", ann, "promote", "promoted v10 to canary/x"},
+ time.Minute, ""},
+ {"a confirmed proposal", row{"shop", ann, "ship", "shipped v11 (cli)"}, row{"shop", ann, "promote", "promoted v11 to production (proposed by cat@example.com, 2 confirmations)"},
+ time.Minute, ""},
+ {"no channel", row{"shop", ann, "ship", "shipped v12 (cli)"}, row{"shop", ann, "promote", "promoted v12 to (cli)"},
+ time.Minute, ""},
+ {"an unclosed source", row{"shop", ann, "ship", "shipped v13 (cli"}, row{"shop", ann, "promote", "promoted v13 to canary/x (cli)"},
+ time.Minute, ""},
+ {"same build", row{"shop", ann, "ship", "shipped v1 (cli)"}, row{"shop", ann, "promote", "promoted v1 to canary/x (cli)"},
+ 9 * time.Minute, "shipped and promoted v1 to canary/x (cli)"},
+ {"ten minutes exactly", row{"shop", ann, "ship", "shipped v2 (cli)"}, row{"shop", ann, "promote", "promoted v2 to canary/x (cli)"},
+ 10 * time.Minute, "shipped and promoted v2 to canary/x (cli)"},
+ {"rootfs", row{"shop", ann, "ship", "shipped v3 (cli, rootfs)"}, row{"shop", ann, "promote", "promoted v3 to stable (cli)"},
+ time.Minute, "shipped and promoted v3 to stable (cli, rootfs)"},
+ }
+ base := w.now.Add(time.Hour)
+ for i, c := range cases {
+ at := base.Add(time.Duration(i) * 30 * time.Minute)
+ groupRecord(t, fx, w.shop.ID, c.ship.app, c.ship.who, c.ship.action, c.ship.detail, at)
+ groupRecord(t, fx, w.shop.ID, c.prom.app, c.prom.who, c.prom.action, c.prom.detail, at.Add(c.gap))
+ }
+ pages := map[string]string{
+ "/fleet/activity": peopleGet(t, fx, w.c, "/fleet/activity"),
+ "/fleet/people/ann@example.com": personGet(t, fx, w.c, "ann@example.com"),
+ }
+ for _, c := range cases {
+ for path, body := range pages {
+ if path != "/fleet/activity" && c.merged == "" {
+ continue // the person page holds only ann's newest twenty
+ }
+ shows := func(what string) bool {
+ return strings.Contains(body, ">"+html.EscapeString(what)+"<") || strings.Contains(body, `title="`+html.EscapeString(what)+`"`)
+ }
+ if c.merged != "" {
+ if !shows(c.merged) || shows(c.ship.detail) || shows(c.prom.detail) {
+ t.Errorf("%s, %s: want one row %q in place of both", c.name, path, c.merged)
+ }
+ continue
+ }
+ if !shows(c.prom.detail) {
+ t.Errorf("%s, %s: the promote %q does not show on its own", c.name, path, c.prom.detail)
+ }
+ if !shows(c.ship.detail) {
+ t.Errorf("%s, %s: the ship %q does not show on its own", c.name, path, c.ship.detail)
+ }
+ if strings.Contains(body, "shipped and promoted "+strings.Fields(strings.TrimPrefix(c.prom.detail, "promoted "))[0]+" ") {
+ t.Errorf("%s, %s: the two merged", c.name, path)
+ }
+ }
+ }
+ // The dashboard's Latest reads the same rule: ann's latest is the
+ // last case's merged row.
+ _, rows := dashActorRows(t, dashGet(t, fx, w.c))
+ if len(rows) == 0 || rows[0].Who != ann || rows[0].Latest != "shipped and promoted v3 to stable (cli, rootfs)" {
+ t.Errorf("the dashboard's first row = %+v, want ann's merged rootfs deploy", rows)
+ }
+
+ // A merged row counts as two actions in a burst: a config change, then
+ // the ship and promote, a minute apart each.
+ at := base.Add(time.Duration(len(cases)) * 30 * time.Minute)
+ groupRecord(t, fx, w.shop.ID, "shop", ann, "env-set", "Set FOO", at)
+ groupRecord(t, fx, w.shop.ID, "shop", ann, "ship", "shipped v20 (cli)", at.Add(time.Minute))
+ groupRecord(t, fx, w.shop.ID, "shop", ann, "promote", "promoted v20 to canary/x (cli)", at.Add(2*time.Minute))
+ lines := feedLines(t, peopleGet(t, fx, w.c, "/fleet/activity"))
+ want := "ann@example.com: 3 actions on shop [shipped and promoted v20 to canary/x (cli), Set FOO]"
+ if got := lineSummary(lines); len(got) == 0 || got[0] != want {
+ t.Errorf("Activity starts %q, want %q", got, want)
+ }
+
+ // The burst is judged on the stored rows' gaps, not the merged line's
+ // time (Astra, whole-branch round 1, P2): a config change, a ship nine
+ // minutes later and its promote nine minutes after that are one burst,
+ // although the promote is 18 minutes after the config change.
+ at = at.Add(30 * time.Minute)
+ groupRecord(t, fx, w.shop.ID, "shop", ann, "env-set", "Set BAR", at)
+ groupRecord(t, fx, w.shop.ID, "shop", ann, "ship", "shipped v21 (cli)", at.Add(9*time.Minute))
+ groupRecord(t, fx, w.shop.ID, "shop", ann, "promote", "promoted v21 to canary/x (cli)", at.Add(18*time.Minute))
+ lines = feedLines(t, peopleGet(t, fx, w.c, "/fleet/activity"))
+ want = "ann@example.com: 3 actions on shop [shipped and promoted v21 to canary/x (cli), Set BAR]"
+ if got := lineSummary(lines); len(got) == 0 || got[0] != want {
+ t.Errorf("nine-minute gaps around a merge: Activity starts %q, want %q", got, want)
+ }
+}
+
+// TestActivityMergeReadsOnlyTheStoredShapes: not acceptance, the parsers'
+// edges.
+func TestActivityMergeReadsOnlyTheStoredShapes(t *testing.T) {
+ for _, c := range []struct {
+ detail string
+ ok bool
+ }{
+ {"shipped v1 (cli)", true},
+ {"shipped v1 (cli, rootfs)", true},
+ {"shipped v1", false},
+ {"shipped (cli)", false},
+ {"shipped v1 (web)", false},
+ {"shipped v1 v2 (cli)", false},
+ {"Shipped v1 (cli)", false},
+ } {
+ if _, _, ok := activityParseShip(FeedRow{Action: "ship", Detail: c.detail}); ok != c.ok {
+ t.Errorf("ship %q: ok = %v, want %v", c.detail, ok, c.ok)
+ }
+ }
+ if _, _, ok := activityParseShip(FeedRow{Action: "promote", Detail: "shipped v1 (cli)"}); ok {
+ t.Error("a ship sentence on another action reads as a ship")
+ }
+ for _, c := range []struct {
+ detail string
+ ok bool
+ }{
+ {"promoted v1 to canary/x (cli)", true},
+ {"promoted v1 to canary/x", false},
+ {"promoted v1 to canary/x (cli) again", false},
+ {"promoted v1 v2 to canary/x (cli)", false},
+ {"promoted to canary/x (cli)", false},
+ {"promoted v1 to production (proposed by a@example.com, 2 confirmations)", false},
+ {"Made v1 live", false},
+ } {
+ if _, _, ok := activityParsePromote(FeedRow{Action: "promote", Detail: c.detail}); ok != c.ok {
+ t.Errorf("promote %q: ok = %v, want %v", c.detail, ok, c.ok)
+ }
+ }
+}
diff --git a/internal/console/opactivity_test.go b/internal/console/opactivity_test.go
index 83c13c1b3..381d29a1d 100644
--- a/internal/console/opactivity_test.go
+++ b/internal/console/opactivity_test.go
@@ -104,12 +104,14 @@ func feedFilterLine(body string) string {
}
// feedSeedMore records n more rows on shop's app, each with its own detail,
-// a second apart after the world's.
+// written after the world's but timed eleven minutes apart from a day
+// before it, so that no two of them fold into one burst (foldBursts).
func feedSeedMore(t *testing.T, fx *consoleFixture, w operatorWorld, n int) {
t.Helper()
for i := 0; i < n; i++ {
+ at := w.now.Add(-24*time.Hour + time.Duration(i)*(activityBurstGap+time.Minute))
if err := fx.st.RecordActivity(w.shop.ID, "shop", "ann@example.com",
- Activity{Action: "env-set", Detail: fmt.Sprintf("Set variable %03d", i)}, w.now.Add(time.Duration(i)*time.Second)); err != nil {
+ Activity{Action: "env-set", Detail: fmt.Sprintf("Set variable %03d", i)}, at); err != nil {
t.Fatal(err)
}
}
diff --git a/internal/console/opdashboard.go b/internal/console/opdashboard.go
index 49703b9c4..f6151f6d2 100644
--- a/internal/console/opdashboard.go
+++ b/internal/console/opdashboard.go
@@ -22,6 +22,17 @@ import (
// boxes: three missed snapshot periods, the boxes' own staleness rule.
const dashSummaryOld = 3 * status.SnapshotPeriod
+// Latest activity is one row per person (dashActors) among the newest
+// dashActivityWindow audit rows, up to dashActivityPeople of them. A
+// window of rows rather than of time: one indexed read of a bounded size
+// however busy the platform is, and never empty while anything has
+// happened; at twenty times the people shown, one person's burst (a
+// deploy is about ten rows) cannot crowd out the rest.
+const (
+ dashActivityWindow = 200
+ dashActivityPeople = 10
+)
+
// The words the dashboard computes (copy record OPS-21 to OPS-76).
const (
dashAllClear = "Everything is running."
@@ -307,9 +318,10 @@ type dashView struct {
Stats []opStat
Bars []dashBar
Newest []PersonRow
- Activity []FeedRow
- Boxes []dashBox
- HasFleet bool
+ // Actors is Latest activity: one row per person (dashActors).
+ Actors []dashActor
+ Boxes []dashBox
+ HasFleet bool
// HostsUnread is OPS-154 when the box reports could not be listed,
// shown in place of the Boxes rows, or when some could not be read,
// shown above the rows that were; "" otherwise.
@@ -317,6 +329,9 @@ type dashView struct {
Jobs []opJobRow
}
+// ActorsHead is Latest activity's head row.
+func (d *dashView) ActorsHead() []string { return activityDashHead }
+
// Title is the callout's heading.
func (d *dashView) Title() string {
switch len(d.Attention) {
@@ -371,10 +386,10 @@ func (s *Server) handleDashboard(w http.ResponseWriter, r *http.Request) {
} else {
d.Newest = people
}
- if feed, err := s.store.ActivityFeed(ActivityFilter{}, 0, 10); err != nil {
+ if feed, err := s.store.ActivityFeed(ActivityFilter{}, 0, dashActivityWindow); err != nil {
log.Printf("console: dashboard activity: %v", err)
} else {
- d.Activity = feed
+ d.Actors = dashActors(feed, dashActivityPeople)
}
// The dashboard's three bucket reads are independent and run at once:
diff --git a/internal/console/opdashboard_test.go b/internal/console/opdashboard_test.go
index 731617eba..5ade445f2 100644
--- a/internal/console/opdashboard_test.go
+++ b/internal/console/opdashboard_test.go
@@ -587,13 +587,13 @@ func TestDashboardBoxStatuses(t *testing.T) {
}
}
-// TestDashboardLatestActivityAndNewestPeople: the newest ten activity rows,
-// newest first, and the newest five people with their first account.
+// TestDashboardLatestActivityAndNewestPeople: Latest activity is one row
+// per person, newest first, with their count, latest action and apps; and
+// the newest five people with their first account.
func TestDashboardLatestActivityAndNewestPeople(t *testing.T) {
fx := newConsoleFixture(t)
w := seedOperatorWorld(t, fx)
- // More rows than the dashboard shows: the newest ten are these six and
- // four of the seeded ones.
+ // Six more of ann's: with the world's promote and invite, eight.
for i := 0; i < 6; i++ {
if err := fx.st.RecordActivity(w.shop.ID, "shop", "ann@example.com", Activity{Action: "rename", Detail: fmt.Sprintf("Change %d", i)}, time.Now()); err != nil {
t.Fatal(err)
@@ -601,40 +601,22 @@ func TestDashboardLatestActivityAndNewestPeople(t *testing.T) {
}
body := dashGet(t, fx, w.c)
- feed, err := fx.st.ActivityFeed(ActivityFilter{}, 0, 10)
- if err != nil {
- t.Fatal(err)
- }
- rows := dashRows(dashSection(t, body, "Latest activity"))
- if len(rows) != len(feed)+1 || len(feed) != 10 {
- t.Fatalf("%d activity rows for a feed of %d (want 10):\n%s", len(rows)-1, len(feed), dashSection(t, body, "Latest activity"))
+ head, rows := dashActorRows(t, body)
+ if want := "<span>Last active</span><span>Who</span><span>Actions</span><span>Latest</span><span>Apps</span>"; !strings.Contains(head, want) {
+ t.Errorf("activity head: %s", head)
}
- if !strings.Contains(rows[0], "<span>When</span><span>Who</span><span>What</span><span>App</span>") {
- t.Errorf("activity head: %s", rows[0])
- }
- for i, f := range feed {
- r := rows[i+1]
- if !strings.Contains(r, `<a href="/fleet/people/`+f.Address+`">`+f.Address+"</a>") || !strings.Contains(r, "<span co-clip>"+f.Detail+"</span>") {
- t.Errorf("activity row %d is not feed row %d (%s %s): %s", i+1, f.ID, f.Address, f.Detail, r)
- }
- }
- if !strings.Contains(rows[1], "Change 5") {
- t.Errorf("the newest row is not the last written: %s", rows[1])
- }
- var signin, promotes string
- for _, r := range rows[1:] {
- if strings.Contains(r, "<span co-clip>Signed in</span>") {
- signin = r
- }
- if strings.Contains(r, " live</span>") {
- promotes += r
- }
+ none := `<span class="rst-cell-mut">none</span>`
+ actors := []dashActorCells{
+ {Who: "ann@example.com", Actions: groupActions(t, fx, "ann@example.com"), Latest: "Change 5", Apps: "<span>shop</span>"},
+ {Who: "cat@example.com", Actions: "1 action", Latest: "Signed in", Apps: none},
+ {Who: "ben@example.com", Actions: groupActions(t, fx, "ben@example.com"), Latest: "Made v1 live", Apps: "<span>notes</span>"},
+ {Who: "paul@keymail.dev", Actions: "1 action", Latest: "Signed in for the first time", Apps: none},
}
- if !strings.Contains(signin, "cat@example.com") || !strings.Contains(signin, `<span class="rst-cell-mut">none</span>`) {
- t.Errorf("the sign-in row has no none for its app: %q", signin)
+ if actors[0].Actions != "9 actions" {
+ t.Errorf("ann has %s, want these six and the world's three", actors[0].Actions)
}
- if !strings.Contains(promotes, "<span>notes</span>") || !strings.Contains(promotes, "<span>shop</span>") {
- t.Errorf("the promote rows do not name their apps: %s", promotes)
+ if !slices.Equal(rows, actors) {
+ t.Errorf("Latest activity =\n%+v\nwant\n%+v", rows, actors)
}
people := dashRows(dashSection(t, body, "Newest people"))
diff --git a/internal/console/opperson.go b/internal/console/opperson.go
index e0fd45ce6..882d6777f 100644
--- a/internal/console/opperson.go
+++ b/internal/console/opperson.go
@@ -78,7 +78,7 @@ func opAgo(t time.Time) string { return humanAge(time.Since(t)) + " ago" }
type personView struct {
Person *PersonDetail
Stats []opStat
- Feed []FeedRow
+ Feed []activityRow
ActivityRef string
}
@@ -128,7 +128,7 @@ func (s *Server) handlePerson(w http.ResponseWriter, r *http.Request) {
p.Person = &personView{
Person: person,
Stats: personStats(person),
- Feed: feed,
+ Feed: mergeShipPromote(feed),
ActivityRef: feedQuery{Who: person.Address}.href(),
}
s.render(w, http.StatusOK, "ops_person", p)
diff --git a/internal/console/opshots_test.go b/internal/console/opshots_test.go
index d414a296e..8340ccbae 100644
--- a/internal/console/opshots_test.go
+++ b/internal/console/opshots_test.go
@@ -88,6 +88,18 @@ func TestOperatorScreenshots(t *testing.T) {
fx := newConsoleFixture(t)
w := seedOperatorWorld(t, fx)
seedOperatorShotExtras(t, fx)
+ // A deploy burst of ann's on shop, so Activity shows a fold and the
+ // dashboard her merged ship and promote.
+ for i, r := range []Activity{
+ {Action: "env-set", Detail: "Set API_URL"},
+ {Action: "env-set", Detail: "Set FEATURE_FLAGS"},
+ {Action: "ship", Detail: "shipped v42 (cli)"},
+ {Action: "promote", Detail: "promoted v42 to canary/eu (cli)"},
+ } {
+ if err := fx.st.RecordActivity(w.shop.ID, "shop", "ann@example.com", r, w.now.Add(time.Duration(i)*time.Minute)); err != nil {
+ t.Fatal(err)
+ }
+ }
target, err := url.Parse(fx.ts.URL)
if err != nil {
t.Fatal(err)
diff --git a/internal/console/static/ops.css b/internal/console/static/ops.css
index ffab9a27c..6ba6babb4 100644
--- a/internal/console/static/ops.css
+++ b/internal/console/static/ops.css
@@ -23,7 +23,7 @@
/* List grids: Rastrillo's [rst-lrow] lays each row out from --rst-cols,
which a list card names once. One template per operator list. */
[co-cols="people"] { --rst-cols: minmax(12rem, 2fr) minmax(8rem, 1fr) 7rem 7rem; }
-[co-cols="activity"] { --rst-cols: 6rem minmax(10rem, 1.2fr) minmax(12rem, 2fr) minmax(7rem, 1fr); }
+[co-cols="activity"] { --rst-cols: 6rem minmax(10rem, 1.2fr) 6rem minmax(12rem, 2fr) minmax(7rem, 1fr); }
[co-cols="boxes"] { --rst-cols: minmax(8rem, 1fr) 7rem 6rem minmax(9rem, 1.4fr) 8rem; }
[co-cols="jobs"] { --rst-cols: minmax(10rem, 1.5fr) 9rem 8rem 7rem 6rem minmax(10rem, 2fr); }
[co-cols="persons"] { --rst-cols: minmax(12rem, 2fr) 7rem 7rem 6rem; }
@@ -37,17 +37,21 @@
kebab, so each keeps two cells on two columns and hides the others,
head row included: one row per line, never a cell wrapped below. The
activity lists lead with When at the desktop's fixed width, so "0m ago"
- and "21h47m ago" rows keep What in one column. */
+ and "21h47m ago" rows keep What in one column. The dashboard's latest
+ activity is one row per person, so it keeps Who beside Last active.
+ Activity's folded bursts (co-fold) lay out like its rows. */
@media (max-width: 800px) {
[co-cols] > [rst-lrow] { grid-template-columns: minmax(0, 1fr) auto; }
[co-cols="activity"] > [rst-lrow],
[co-cols="feed"] > [rst-lrow],
+ [co-cols="feed"] > [co-fold] > [rst-lrow],
[co-cols="personfeed"] > [rst-lrow] { grid-template-columns: 6rem minmax(0, 1fr); }
[co-cols="people"] > [rst-lrow] > :is(:nth-child(2), :nth-child(4)),
[co-cols="persons"] > [rst-lrow] > :is(:nth-child(2), :nth-child(4)),
[co-cols="accounts"] > [rst-lrow] > :is(:nth-child(2), :nth-child(n+4)),
- [co-cols="activity"] > [rst-lrow] > :is(:nth-child(2), :nth-child(4)),
+ [co-cols="activity"] > [rst-lrow] > :nth-child(n+3),
[co-cols="feed"] > [rst-lrow] > :is(:nth-child(2), :nth-child(3), :nth-child(5)),
+ [co-cols="feed"] > [co-fold] > [rst-lrow] > :is(:nth-child(2), :nth-child(3), :nth-child(5)),
[co-cols="personfeed"] > [rst-lrow] > :is(:nth-child(2), :nth-child(4)),
[co-cols="personaccts"] > [rst-lrow] > :nth-child(n+3),
[co-cols="boxes"] > [rst-lrow] > :nth-child(n+3),
@@ -84,6 +88,18 @@
browser's default blue. */
[co-cols="feed"] a, [co-cols="activity"] a, [co-cols="personfeed"] a { color: var(--rst-accent); }
+/* A burst on Activity (co-fold): one row, the details' summary, that
+ opens onto the burst's rows, tinted so they read as its own. The rows
+ keep the list's lines between them, and the card's last line has none
+ whether the burst is open or not. */
+[co-fold] > summary { cursor: pointer; list-style: none; }
+[co-fold] > summary::-webkit-details-marker { display: none; }
+[co-fold] > summary [rst-caret] { display: inline-flex; margin-inline-start: 0.3rem; vertical-align: middle; }
+[co-fold][open] > summary [rst-caret] { transform: rotate(180deg); }
+[co-fold] > div[rst-lrow] { background: var(--rst-surface-2); }
+[co-fold]:not(:last-child) > [rst-lrow]:last-child { border-bottom: 1px solid var(--rst-line); }
+[co-fold]:last-child:not([open]) > summary { border-bottom: 0; }
+
/* An audit row's What (op_what): one line, cut with an ellipsis, its
whole text in the cell's title. A row that stored data opens onto it,
indented, wrapped and scrolling within the cell rather than widening the
diff --git a/internal/console/templates/ops_activity.html b/internal/console/templates/ops_activity.html
index 9b1d704ba..904d1b589 100644
--- a/internal/console/templates/ops_activity.html
+++ b/internal/console/templates/ops_activity.html
@@ -1,8 +1,10 @@
{{/* Activity (/fleet/activity, opactivity.go): one card of audit rows,
newest first, under a toolbar holding the kind filter and, when an
account or a person filter is on, the line naming each with its clear
- link; Newest and Older below. Everything computed in Go arrives in
- .Feed. */}}
+ link; Newest and Older below. A burst by one person on one app is one
+ line that opens onto its rows (a details, no script), and a ship
+ merged with its promote is one row (opactivity_group.go). Everything
+ computed in Go arrives in .Feed. */}}
{{define "ops_activity"}}{{template "op_top" .}}
{{template "op_page_header" (opHeader .Title "All activity across every account, newest first.")}}
{{with .Feed}}
@@ -16,11 +18,19 @@
<p co-filter>Showing only {{if .WhoHref}}<a href="{{.WhoHref}}">{{.Who}}</a>{{else}}{{.Who}}{{end}}. <a href="{{.Query.ClearWhoHref}}">Show all people</a></p>
{{- end}}
</div>
- {{- if .Rows}}
+ {{- if .Entries}}
<div rst-lrow="head"><span>When</span><span>Who</span><span>Account</span><span>What</span><span>App</span></div>
+ {{- range .Entries}}
+ {{- if .Folded}}
+ <details co-fold><summary rst-lrow><span class="rst-cell-mut" title="{{fmtTime .At}}">{{ago .At}}</span>{{template "op_who" .Address}}{{if .AccountSqid}}<a href="{{$.Feed.Query.AccountHref .AccountSqid}}">{{.AccountName}}</a>{{else}}<span class="rst-cell-mut">none</span>{{end}}<span co-clip>{{.FoldText}}<span rst-caret aria-hidden="true">{{icon "chevron-down"}}</span></span>{{if .App}}<span>{{.App}}</span>{{else}}<span class="rst-cell-mut">none</span>{{end}}</summary>
{{- range .Rows}}
<div rst-lrow><span class="rst-cell-mut" title="{{fmtTime .At}}">{{ago .At}}</span>{{template "op_who" .Address}}{{if .AccountSqid}}<a href="{{$.Feed.Query.AccountHref .AccountSqid}}">{{.AccountName}}</a>{{else}}<span class="rst-cell-mut">none</span>{{end}}{{template "op_what" .}}{{if .App}}<span>{{.App}}</span>{{else}}<span class="rst-cell-mut">none</span>{{end}}</div>
{{- end}}
+ </details>
+ {{- else}}
+ <div rst-lrow><span class="rst-cell-mut" title="{{fmtTime .At}}">{{ago .At}}</span>{{template "op_who" .Address}}{{if .AccountSqid}}<a href="{{$.Feed.Query.AccountHref .AccountSqid}}">{{.AccountName}}</a>{{else}}<span class="rst-cell-mut">none</span>{{end}}{{template "op_what" .}}{{if .App}}<span>{{.App}}</span>{{else}}<span class="rst-cell-mut">none</span>{{end}}</div>
+ {{- end}}
+ {{- end}}
{{- else}}
{{template "op_empty" (opEmpty "" "No activity matches these filters.")}}
{{- end}}
diff --git a/internal/console/templates/ops_dashboard.html b/internal/console/templates/ops_dashboard.html
index e3ab99cf3..5652573a6 100644
--- a/internal/console/templates/ops_dashboard.html
+++ b/internal/console/templates/ops_dashboard.html
@@ -1,6 +1,7 @@
{{/* The dashboard (/fleet, opdashboard.go): the approved mockup top to
bottom. The callout, the headline band, the new-people chart, newest
- people, latest activity, boxes and background jobs. Every number and
+ people, latest activity (one row per person), boxes and background
+ jobs. Every number and
word computed in Go arrives in .Dash. */}}
{{define "ops_dashboard"}}{{template "op_top" .}}
{{template "op_page_header" (opHeader .Title (printf "Who uses %s, what they do, and whether everything is running." .Brand))}}
@@ -53,11 +54,11 @@
{{else}}{{template "op_empty" (opEmpty "" "No one has signed up yet.")}}{{end}}
<div rst-box-head><h2>Latest activity</h2><a rst-btn="ghost" href="/fleet/activity">All activity</a></div>
-{{if .Activity}}
+{{if .Actors}}
<div rst-card co-cols="activity">
- <div rst-lrow="head"><span>When</span><span>Who</span><span>What</span><span>App</span></div>
- {{- range .Activity}}
- <div rst-lrow><span class="rst-cell-mut" title="{{fmtTime .At}}">{{ago .At}}</span>{{template "op_who" .Address}}{{template "op_what" .}}{{if .App}}<span>{{.App}}</span>{{else}}<span class="rst-cell-mut">none</span>{{end}}</div>
+ <div rst-lrow="head">{{range .ActorsHead}}<span>{{.}}</span>{{end}}</div>
+ {{- range .Actors}}
+ <div rst-lrow><span class="rst-cell-mut" title="{{fmtTime .At}}">{{ago .At}}</span>{{template "op_who" .Address}}<span>{{.ActionsText}}</span>{{template "op_what" .Latest}}{{if .Apps}}<span>{{.Apps}}</span>{{else}}<span class="rst-cell-mut">none</span>{{end}}</div>
{{- end}}
</div>
{{else}}{{template "op_empty" (opEmpty "" "Nothing has happened yet.")}}{{end}}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index e7e121a84..434e24c6d 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-sponsor-existing-accounts.tsv 43d1824141f0ce7024cc3740ab5feac3f3539322f8afb856c9ca2f10d5095e95
+plan14-root-reads-first-deploy-493.tsv 6b9aa3f2b21250d40b910ad1d29362687ec57ba5e895157670b785c0c3978f52
+plan14-root-reads-sponsor-existing-accounts.tsv 6b9aa3f2b21250d40b910ad1d29362687ec57ba5e895157670b785c0c3978f52
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