oficina / equipo Public

places: confirmed site places, place card, tools and Places page

Migration 0108: chat_places and chat_project_places (team records,
owner-only writes, audited) and chat_cards.place; every project's
site_app is kept as an unplaced binding that confirms nothing.

A merged website with no place raises a place card (or says why in the
task's lane); its candidates come only from the primary's reach, ranked
by code (Carloku account named like the namespace first). Tools take a
candidate id, never a console, account or app. Only the card's owner's
tap confirms; confirming sends nothing to CARLOS. The publish card is a
snapshot of place, binding, mode and destination: a moved one is settled
and asked again; the step, dispatch and every check are bound to it, per
phase of its mode (setup records the creation attempt, mint records the
key's step, publish needs the held key). A done setup or mint without a
held key raises a mint card (the recovery route). places, propose_place,
publish_site and site_status (recorded data only) for the coordinator;
a read-only Settings > Places page. New copy is drafted and pending.

Mutation checks (CGO_ENABLED=0, thintest and chat):
place-card owner check off KILLED FinishLine:159 (the card-person check
alone is unreachable over the API: cards are looked up by person);
publish snapshot compare off KILLED FinishLine:175; check destination
compare off KILLED FinishLine:197; mint step deploying before its mint
check KILLED MintRecovery:325; setup attempt not recorded KILLED
FinishLine:201; binding revision unchecked KILLED FinishLine:242;
namespace rank off KILLED TestSiteCandidatesRank; reach checked after the
place card KILLED PreviewNotHeldBelow19:1260; mint barred after a done
publish KILLED MintRecovery:308; candidate-still-reachable check off
KILLED; recovery card off KILLED MintRecovery:308. Migration: empty
site_app copied KILLED :57; revision 0 KILLED :52.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 38b32aa502fd2f0fd8e901b717f89a7433aedec1 parent 20fb73b
30 files changed, +2,154 −170
  • .rastrillo/budgets.txt +6 −6
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +41 −0
  • internal/equipo/app.go +1 −0
  • internal/equipo/chat/days.go +2 −2
  • internal/equipo/chat/models.go +1 −1
  • internal/equipo/chat/places.go +553 −0
  • internal/equipo/chat/places_models.go +51 −0
  • internal/equipo/chat/places_test.go +84 −0
  • internal/equipo/chat/places_tools.go +375 −0
  • internal/equipo/chat/projects.go +12 −0
  • internal/equipo/chat/publish.go +331 −118
  • internal/equipo/chat/runners.go +3 −3
  • internal/equipo/chat/stream.go +1 −1
  • internal/equipo/chat/tasks.go +14 −4
  • internal/equipo/chat/tools.go +16 −1
  • internal/equipo/chat_page.go +24 −1
  • internal/equipo/copy.go +42 −0
  • internal/equipo/migrations/0108_places.sql +14 −0
  • internal/equipo/migrations/schema.sql +5 −0
  • internal/equipo/places_migration_test.go +59 −0
  • internal/equipo/settings_hub.go +59 −3
  • internal/equipo/templates/chat.html +1 −1
  • internal/equipo/templates/settings_hub.html +2 −0
  • internal/thintest/assistant_job_contract_test.go +2 −2
  • internal/thintest/assistant_outcome_contract_test.go +8 −7
  • internal/thintest/assistant_team_contract_test.go +3 −3
  • internal/thintest/merge_contract_test.go +32 −0
  • internal/thintest/places_contract_test.go +369 −0
  • internal/thintest/publish_contract_test.go +41 −17
  • internal/thintest/tools_contract_test.go +2 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 12bbad0a..c1b687fe 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -14,8 +14,8 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr
time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI.
time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage.
-size internal/equipo 22600 - Stuck tasks' Retry and timeline (2026-11-25), merge_credential and amadan_unreachable copy (2026-11-26); measured 22600 source lines.
-size internal/wire 7088 - Native task evidence fields, merge_credential and amadan_unreachable reasons (2026-11-26); measured 7088 source lines.
+size internal/equipo 22722 - Places slice 1 (2026-11-26): the place card on the web, the read-only Places page and its drafted copy; measured 22722 source lines.
+size internal/wire 7460 - Protocol 31 places (2026-11-26): reach, carlos health, place-bound publish dispatch and checks, place tools and card; measured 7460 source lines.
size internal/equipotest - 12017 Task 21 repairs historical migration and conversation fixtures after Plan 3, and the Rastrillo upgrade contract comparing served assets with what Assets serves; measured 0/12017 source/test lines.
time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded);
time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s).
@@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full
perf GET /releases/* skip Verified runner release file downloads, not browser GET screens.
perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen.
time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s;
-size internal/runner/thin 28724 23336 Protocol 30 scanner health and stuck-task tools, merge credential fallback and write scope (2026-11-26); measured 28724/23336.
+size internal/runner/thin 29434 23679 Protocol 31 places (2026-11-26): carlos version guard, reach, place-bound setup, mint and key publish with their tests; measured 29434/23679.
time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes.
time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing.
time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s).
@@ -56,7 +56,7 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device
perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen.
-size internal/equipo/chat 34839 9685 Native task hosted projection and stable completion time with regressions; measured 34839/9685 (2026-11-26).
+size internal/equipo/chat 36068 9769 Places slice 1 (2026-11-26): place records, cards, per-phase publish authority and the four place tools; measured 36068/9769.
perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}.
perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}.
perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections.
@@ -70,8 +70,8 @@ perf GET /api/v1/tasks/{id}/files/{file} skip Research kept images: bearer-only
perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one image, shown on the task page; a file, not a screen.
perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section.
time cmd/equipo-runner 60s TestReleaseRunnerHasNoFakeWorker builds the release runner and the thin package under testbuild (about 12s locally).
-size internal/headless - 11437 Grant scenarios for a named repository (hub #48); the sign-in's account email at 1280 and 390; measured 11437 test lines.
-size internal/thintest - 35085 Stuck-task contracts plus paused-job fixed-clock coverage at three hours (2026-11-26); measured 35085 test lines.
+size internal/headless - 11440 Grant scenarios for a named repository (hub #48); the sign-in's account email at 1280 and 390; the live site run waits for a confirmed place (2026-11-26); measured 11440 test lines.
+size internal/thintest - 35513 Places slice 1 contracts: finish line, mint recovery, refusals (2026-11-26); measured 35513 test lines.
perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}.
perf GET /api/v1/usage skip Thin v1 person API: bearer-only JSON for devices; the browser reads usage through /usage.
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index ae2e6956..e1472cf4 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -6910,6 +6910,47 @@ records remain unchanged.
| `work.tl.coordinator_retried` | The coordinator started %s again. | Copy specialist | Runtime; COPY APPROVED (Paul, 2026-11-25, copy-review 6haczxo74hoyyuf7xkojgqd27e, unchanged) |
| `work.reason.merge_credential` | the runner has no Amadan credential for this repository | Copy specialist | Runtime; COPY APPROVED (Paul, 2026-11-25, copy-review 6wxwi7zo3fph5nu4nm6eipptfq, unchanged) |
| `work.reason.amadan_unreachable` | Amadan could not be reached to confirm Equipo may merge here | Copy specialist | Runtime; COPY APPROVED (Paul, 2026-11-25, copy-review 6wxwi7zo3fph5nu4nm6eipptfq, unchanged) |
+| `chat.card.place_question` | Publish %s on %s, in account %s? | Copy specialist | COPY REVIEW PENDING |
+| `chat.card.place_option` | %s, account %s | Copy specialist | COPY REVIEW PENDING |
+| `chat.card.place_chose` | Saved. Nothing goes live until you tap Publish. | Copy specialist | COPY REVIEW PENDING |
+| `chat.card.place_chose_not_now` | Not saved. | Copy specialist | COPY REVIEW PENDING |
+| `chat.card.publish_place_question` | Publish %s to %s on %s, account %s? | Copy specialist | COPY REVIEW PENDING |
+| `chat.card.publish_setup_note` | This first publish creates the app and a deploy key for it, using your CARLOS login on your runner. | Copy specialist | COPY REVIEW PENDING |
+| `chat.card.publish_mint_note` | This makes a new deploy key for the site with your CARLOS login on your runner, then publishes with it. | Copy specialist | COPY REVIEW PENDING |
+| `chat.card.publish_stale` | Where this site goes changed, so I asked again. | Copy specialist | COPY REVIEW PENDING |
+| `chat.publish_blocked` | [%s](%s) is merged, but I can’t publish it yet: %s. | Copy specialist | COPY REVIEW PENDING |
+| `chat.publish_unproven` | Could not publish [%s](%s): an app called %s is already in that account and Equipo has no record of making it, so I left it alone. | Copy specialist | COPY REVIEW PENDING |
+| `places.missing.no_place` | no place is chosen for its site | Copy specialist | COPY REVIEW PENDING |
+| `places.missing.no_runner` | you have no runner to publish from | Copy specialist | COPY REVIEW PENDING |
+| `places.missing.runner_outdated` | your runner needs an Equipo update first | Copy specialist | COPY REVIEW PENDING |
+| `places.missing.carlos_outdated` | the CARLOS command line tool on your runner is missing or older than v0.43.0 | Copy specialist | COPY REVIEW PENDING |
+| `places.missing.no_login` | your runner is not signed in to CARLOS with an account you own | Copy specialist | COPY REVIEW PENDING |
+| `places.missing.no_deploy` | your runner has no deploy key for the site and no CARLOS login to make one | Copy specialist | COPY REVIEW PENDING |
+| `places.missing.not_owner` | only a team owner can publish a site | Copy specialist | COPY REVIEW PENDING |
+| `work.reason.carlos_outdated` | the CARLOS command line tool on the runner is missing or older than v0.43.0 | Copy specialist | COPY REVIEW PENDING |
+| `work.reason.publish_secrets` | the site was not published because its secret scan found something that looks like a secret | Copy specialist | COPY REVIEW PENDING |
+| `work.reason.publish_scanner` | the site was not published because its secret scan could not be completed | Copy specialist | COPY REVIEW PENDING |
+| `work.reason.publish_key_missing` | the runner no longer holds the site’s deploy key | Copy specialist | COPY REVIEW PENDING |
+| `work.reason.publish_mint_failed` | the site’s deploy key could not be made | Copy specialist | COPY REVIEW PENDING |
+| `work.reason.publish_app_missing` | the app this site’s first publish should have made is not there | Copy specialist | COPY REVIEW PENDING |
+| `work.reason.publish_app_unproven` | an app with this name is in the account, but Equipo has no record of making it | Copy specialist | COPY REVIEW PENDING |
+| `chat.activity.places` | Checking where sites go… | Copy specialist | COPY REVIEW PENDING |
+| `chat.activity.propose_place` | Asking where the site goes… | Copy specialist | COPY REVIEW PENDING |
+| `chat.activity.publish_site` | Offering to publish the site… | Copy specialist | COPY REVIEW PENDING |
+| `chat.activity.site_status` | Checking the site… | Copy specialist | COPY REVIEW PENDING |
+| `settings.places` | Places | Copy specialist | COPY REVIEW PENDING |
+| `settings.places_about` | Where your team’s sites go. | Copy specialist | COPY REVIEW PENDING |
+| `places.title` | Places | Copy specialist | COPY REVIEW PENDING |
+| `places.empty` | No places yet. When a merged website needs one, Equipo asks you where it goes. | Copy specialist | COPY REVIEW PENDING |
+| `places.site_line` | %s: %s on %s, account %s. | Copy specialist | COPY REVIEW PENDING |
+| `places.site_live` | Live at %s, published %s. | Copy specialist | COPY REVIEW PENDING |
+| `places.site_unconfirmed` | The last publish, %s, could not be confirmed. | Copy specialist | COPY REVIEW PENDING |
+| `places.site_not_yet` | Not published yet. | Copy specialist | COPY REVIEW PENDING |
+| `places.unplaced` | %s: app %s, no place chosen yet. | Copy specialist | COPY REVIEW PENDING |
+| `places.pending` | %s: waiting for you to choose where its site goes. | Copy specialist | COPY REVIEW PENDING |
+| `places.deploy_held` | Its deploy key is %s. | Copy specialist | COPY REVIEW PENDING |
+| `places.deploy_lost` | A deploy key named %s may still be live on CARLOS without Equipo holding it. You can revoke it in the CARLOS console. | Copy specialist | COPY REVIEW PENDING |
+| `places.deploy_none` | No deploy key yet: the first publish makes one. | Copy specialist | COPY REVIEW PENDING |
## Task 21
diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index fca880fe..3175a28f 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -393,6 +393,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
r.Get("/conversation/settings", a.settingsHub)
r.Get("/conversation/settings/thinking", a.settingsSectionHandler("thinking"))
r.Get("/conversation/settings/housekeeping", a.settingsSectionHandler("housekeeping"))
+ r.Get("/conversation/settings/places", a.settingsSectionHandler("places"))
r.Get("/conversation/connections", movedTo("/conversation/settings/connections"))
r.Get("/conversation/settings/connections", a.connectionsView)
r.Get("/conversation/settings/connections/add", a.connectionsAdd)
diff --git a/internal/equipo/chat/days.go b/internal/equipo/chat/days.go
index 687a473b..54452c9b 100644
--- a/internal/equipo/chat/days.go
+++ b/internal/equipo/chat/days.go
@@ -232,7 +232,7 @@ func (s *Store) StillOpen(ctx context.Context, person string, before time.Time)
}
var cards []cardRecord
if err := tx.Where("person = ? AND (held IS NULL OR held = ?) AND "+personLane, person, false).
- Where(tx.Where("kind IN ? AND state = ?", []string{wire.CardQuestion, wire.CardAccess, wire.CardMerge, wire.CardDirection, wire.CardMergeShips, wire.CardMergePolicy, wire.CardSpecialist, wire.CardResearchSources, wire.CardResearchInventory, wire.CardPublish}, wire.CardOpen).
+ Where(tx.Where("kind IN ? AND state = ?", []string{wire.CardQuestion, wire.CardAccess, wire.CardMerge, wire.CardDirection, wire.CardMergeShips, wire.CardMergePolicy, wire.CardSpecialist, wire.CardResearchSources, wire.CardResearchInventory, wire.CardPublish, wire.CardPlace}, wire.CardOpen).
Or("kind = ? AND state = ?", wire.CardHome, wire.CardHomeAsk).
Or("kind = ? AND task_id IN (SELECT id FROM chat_tasks WHERE creator = ? AND stage IN ?)", wire.CardTask, person, Underway)).
Order("created_at, id").Find(&cards).Error; err != nil {
@@ -303,7 +303,7 @@ type Rollup struct {
// person's: merge or wait, a direction, a policy question, a question,
// adding a specialist, the pages Research reads and the addresses it
// reads from, and publishing a merged website.
-var decisionKinds = []string{wire.CardMerge, wire.CardDirection, wire.CardMergeShips, wire.CardMergePolicy, wire.CardQuestion, wire.CardSpecialist, wire.CardResearchSources, wire.CardResearchInventory, wire.CardPublish}
+var decisionKinds = []string{wire.CardMerge, wire.CardDirection, wire.CardMergeShips, wire.CardMergePolicy, wire.CardQuestion, wire.CardSpecialist, wire.CardResearchSources, wire.CardResearchInventory, wire.CardPublish, wire.CardPlace}
// Rollup reads [from, to) for the day boxes.
func (s *Store) Rollup(ctx context.Context, person string, from, to time.Time) (out Rollup, err error) {
diff --git a/internal/equipo/chat/models.go b/internal/equipo/chat/models.go
index 3b0444a9..c0e12f6e 100644
--- a/internal/equipo/chat/models.go
+++ b/internal/equipo/chat/models.go
@@ -11,7 +11,7 @@ import (
)
// Models are the tables this package owns, for the migration check.
-var Models = append([]any{&projectNameRecord{}, &cardVisibility{}, &cardThreadRecord{}, &copyAttemptRecord{}, &copyReviewRecord{}, &copyFeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}, &connectTurnRecord{}, &carriedRecord{}, &zoneRecord{}}, push.Models...)
+var Models = append([]any{&projectNameRecord{}, &cardVisibility{}, &cardThreadRecord{}, &copyAttemptRecord{}, &copyReviewRecord{}, &copyFeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}, &connectTurnRecord{}, &carriedRecord{}, &zoneRecord{}, &placeRecord{}, &projectPlaceRecord{}}, push.Models...)
type turnRecord struct {
CreateRepo string
diff --git a/internal/equipo/chat/places.go b/internal/equipo/chat/places.go
new file mode 100644
index 00000000..85f4895c
--- /dev/null
+++ b/internal/equipo/chat/places.go
@@ -0,0 +1,553 @@
+package chat
+
+import (
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "slices"
+ "sort"
+ "strings"
+
+ "gorm.io/gorm"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Places (spec 2026-11-26-places-config.md, slice 1). A site place is a
+// console and account the team confirmed; a project's binding names its
+// app there. Only an owner's tap on a place card confirms one, choosing
+// among candidates code derived from the creator's primary's reach: a
+// tool names a candidate id, never a console, account or app. Confirming
+// sends nothing to CARLOS. A publish card's tap is bound to a snapshot of
+// the place, the binding, the mode and the destination, carried through
+// the step, the dispatch and each final check (publish.go).
+
+// placeOption is one candidate on a place card with the hash its tap is
+// bound to.
+type placeOption struct {
+ wire.PlaceCandidate
+ Hash string `json:"hash"`
+}
+
+// placeProposal is a place card's stored proposal (cardRecord.Place).
+type placeProposal struct {
+ Kind string `json:"kind"`
+ ProjectID string `json:"project_id"`
+ TaskID string `json:"task_id,omitempty"`
+ Candidates []placeOption `json:"candidates"`
+}
+
+func optionHash(c wire.PlaceCandidate) string {
+ sum := sha256.Sum256([]byte("place-option/v1\n" + c.ID + "\n" + c.Console + "\n" + c.Sqid + "\n" + c.Account))
+ return hex.EncodeToString(sum[:])
+}
+
+// repoNamespace is the forge namespace a repository lives in
+// (amadan.net/paulca/nearys: paulca).
+func repoNamespace(repo string) string {
+ parts := strings.Split(repo, "/")
+ if len(parts) < 3 {
+ return ""
+ }
+ return parts[len(parts)-2]
+}
+
+// siteCandidates ranks the accounts the hello's logins own, with fixed
+// rules: the flagship account named like the repository's namespace;
+// else, when there is exactly one, the only owned account; then the rest,
+// flagship first, then by console and name. At most wire.MaxPlaceOptions.
+func siteCandidates(h wire.Hello, repo string) []wire.PlaceCandidate {
+ if h.Capabilities == nil || h.Capabilities.Reach == nil {
+ return nil
+ }
+ var all []wire.PlaceCandidate
+ for _, l := range h.Capabilities.Reach.Logins {
+ for _, a := range l.Accounts {
+ all = append(all, wire.PlaceCandidate{ID: wire.CandidateID(l.Console, a.Sqid), Console: l.Console, ConsoleLabel: wire.ConsoleLabel(l.Console), Account: a.Name, Sqid: a.Sqid})
+ }
+ }
+ ns := repoNamespace(repo)
+ rank := func(c wire.PlaceCandidate) int {
+ switch {
+ case c.Console == wire.FlagshipConsole && ns != "" && c.Account == ns:
+ return 0
+ case len(all) == 1:
+ return 1
+ case c.Console == wire.FlagshipConsole:
+ return 2
+ }
+ return 3
+ }
+ sort.SliceStable(all, func(i, j int) bool {
+ a, b := all[i], all[j]
+ if rank(a) != rank(b) {
+ return rank(a) < rank(b)
+ }
+ if a.Console != b.Console {
+ return a.Console < b.Console
+ }
+ return a.Account < b.Account
+ })
+ if len(all) > wire.MaxPlaceOptions {
+ all = all[:wire.MaxPlaceOptions]
+ }
+ return all
+}
+
+// siteBinding is the project's site binding and its place: nil, nil
+// when it has none; the place nil while the binding is unplaced (an app
+// kept from before places).
+func (t *txn) siteBinding(projectID string) (*projectPlaceRecord, *placeRecord, error) {
+ var b projectPlaceRecord
+ err := t.db.Where("project_id = ? AND kind = ?", projectID, wire.PlaceSite).First(&b).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, nil, nil
+ }
+ if err != nil {
+ return nil, nil, err
+ }
+ if b.PlaceID == "" {
+ return &b, nil, nil
+ }
+ var p placeRecord
+ if err := t.db.Where("id = ?", b.PlaceID).First(&p).Error; err != nil {
+ return nil, nil, err
+ }
+ return &b, &p, nil
+}
+
+// placedSite is the project's confirmed site place and binding, or nils.
+func (t *txn) placedSite(projectID string) (*projectPlaceRecord, *placeRecord, error) {
+ b, p, err := t.siteBinding(projectID)
+ if err != nil || b == nil || p == nil || p.State != wire.PlaceConfirmed || b.App == "" {
+ return nil, nil, err
+ }
+ return b, p, nil
+}
+
+// Reasons a site cannot be published now (siteMode's missing), each a
+// copy key places.missing.<reason>.
+const (
+ missingNoPlace = "no_place"
+ missingNoRunner = "no_runner"
+ missingRunnerOutdated = "runner_outdated"
+ missingCarlos = "carlos_outdated"
+ missingNoLogin = "no_login"
+ missingNoDeploy = "no_deploy"
+ missingNotOwner = "not_owner"
+)
+
+// siteReach is the person's primary's reach and carlos health, and the
+// reason none can be used: no primary, one below protocol 31 or a carlos
+// that is unreadable or too old.
+func (t *txn) siteReach(person string) (*wire.Reach, string, error) {
+ primary, err := t.s.authority.PrimaryRunner(t.db, person)
+ if err != nil {
+ return nil, "", err
+ }
+ if primary == "" {
+ return nil, missingNoRunner, nil
+ }
+ rs, err := t.runners(person)
+ if err != nil {
+ return nil, "", err
+ }
+ i := slices.IndexFunc(rs, func(r runnerInfo) bool { return r.ID == primary })
+ if i < 0 {
+ return nil, missingNoRunner, nil
+ }
+ if rs[i].Protocol < wire.ProtocolPlaces {
+ return nil, missingRunnerOutdated, nil
+ }
+ h, err := t.hello(person)
+ if err != nil {
+ return nil, "", err
+ }
+ if h.Capabilities == nil || h.Capabilities.Tools == nil || h.Capabilities.Tools.Carlos != wire.CarlosOK {
+ return nil, missingCarlos, nil
+ }
+ r := h.Capabilities.Reach
+ if r == nil {
+ r = &wire.Reach{}
+ }
+ return r, "", nil
+}
+
+// reachLogin reports whether the reach holds an owner login on the
+// console that owns the account sqid.
+func reachLogin(r *wire.Reach, console, sqid string) bool {
+ for _, l := range r.Logins {
+ if l.Console == console {
+ for _, a := range l.Accounts {
+ if a.Sqid == sqid {
+ return true
+ }
+ }
+ }
+ }
+ return false
+}
+
+// reachDeploy is the deploy key the reach holds for exactly this app at
+// this console and account, if any (never a lost one).
+func reachDeploy(r *wire.Reach, console, sqid, app string) (wire.ReachDeploy, bool) {
+ for _, d := range r.Deploys {
+ if d.Console == console && d.Account == sqid && d.App == app && !d.Lost {
+ return d, true
+ }
+ }
+ return wire.ReachDeploy{}, false
+}
+
+// siteMode is how the person's primary may publish the bound site now:
+// setup (the app was never created: the owner's login creates it and
+// mints its key), mint (it was, and no key is held: the login only mints
+// one), publish (the key is held); else "" and what is missing.
+func (t *txn) siteMode(person string, b projectPlaceRecord, p placeRecord) (string, string, error) {
+ if err := t.isOwner(person); err != nil {
+ if errors.Is(err, ErrForbidden) {
+ return "", missingNotOwner, nil
+ }
+ return "", "", err
+ }
+ r, missing, err := t.siteReach(person)
+ if err != nil || missing != "" {
+ return "", missing, err
+ }
+ if b.AppCreatedAt == nil {
+ if reachLogin(r, p.Console, p.AccountSqid) {
+ return wire.SiteSetup, "", nil
+ }
+ return "", missingNoLogin, nil
+ }
+ if _, ok := reachDeploy(r, p.Console, p.AccountSqid, b.App); ok {
+ return wire.SitePublish, "", nil
+ }
+ if reachLogin(r, p.Console, p.AccountSqid) {
+ return wire.SiteMint, "", nil
+ }
+ return "", missingNoDeploy, nil
+}
+
+// publishSnapshot is what a publish card's tap allows, stored on the card
+// and copied to the step: the merged commit, the place and binding at
+// their revisions, the destination, the mode and, for setup and mint, the
+// key's name. Every final check compares it with the records then.
+type publishSnapshot struct {
+ SHA string `json:"sha"`
+ Place string `json:"place"`
+ PlaceRevision int64 `json:"place_revision"`
+ Binding string `json:"binding"`
+ BindingRevision int64 `json:"binding_revision"`
+ Console string `json:"console"`
+ Sqid string `json:"sqid"`
+ Name string `json:"name"`
+ App string `json:"app"`
+ Mode string `json:"mode"`
+ DeployName string `json:"deploy_name,omitempty"`
+ Destination string `json:"destination"`
+}
+
+// sameTarget reports whether two snapshots allow the same thing (the key
+// name aside, minted afresh for every card).
+func (a publishSnapshot) sameTarget(b publishSnapshot) bool {
+ a.DeployName, b.DeployName = "", ""
+ return a == b
+}
+
+// deployName is a fresh deploy key name for app: eq-, the app without
+// site-, a hyphen and four random characters, within CARLOS's 32.
+func deployName(app string) string {
+ slug := strings.TrimPrefix(app, "site-")
+ if len(slug) > 24 {
+ slug = strings.TrimRight(slug[:24], "-")
+ }
+ return "eq-" + slug + "-" + strings.ToLower(rand.Text())[:4]
+}
+
+// siteSnapshot is the snapshot a publish of k's merged commit would be
+// bound to now, or the reason there is none.
+func (t *txn) siteSnapshot(k taskRecord) (*publishSnapshot, string, error) {
+ b, p, err := t.placedSite(k.ProjectID)
+ if err != nil {
+ return nil, "", err
+ }
+ if b == nil {
+ return nil, missingNoPlace, nil
+ }
+ mode, missing, err := t.siteMode(k.Creator, *b, *p)
+ if err != nil || missing != "" {
+ return nil, missing, err
+ }
+ s := publishSnapshot{SHA: k.MergedSHA, Place: p.ID, PlaceRevision: p.Revision, Binding: b.ID, BindingRevision: b.Revision, Console: p.Console, Sqid: p.AccountSqid, Name: p.AccountName, App: b.App, Mode: mode, Destination: wire.SiteDestination(p.Console, p.AccountSqid, p.AccountName, b.App)}
+ if mode != wire.SitePublish {
+ s.DeployName = deployName(b.App)
+ }
+ return &s, "", nil
+}
+
+func decodeSnapshot(raw string) *publishSnapshot {
+ var s publishSnapshot
+ if raw == "" || json.Unmarshal([]byte(raw), &s) != nil || s.Destination == "" {
+ return nil
+ }
+ return &s
+}
+
+func encodeSnapshot(s publishSnapshot) string {
+ raw, _ := json.Marshal(s)
+ return string(raw)
+}
+
+// stepSnapshot is the snapshot a publish step was placed with.
+func stepSnapshot(raw string) *publishSnapshot {
+ var r struct {
+ Snapshot *publishSnapshot `json:"snapshot"`
+ }
+ if raw == "" || json.Unmarshal([]byte(raw), &r) != nil || r.Snapshot == nil || r.Snapshot.Destination == "" {
+ return nil
+ }
+ return r.Snapshot
+}
+
+// raisePlace puts a place card for the project's site in person's
+// conversation: the candidates the primary's reach offers, first (when
+// named and offered) first, then Not now. task names the merged task the
+// proposal is for, "" for none. ok false when there is nothing to offer.
+func (t *txn) raisePlace(person, lane, turn string, pr projectRecord, task, first string) (cardRecord, bool, error) {
+ h, err := t.hello(person)
+ if err != nil {
+ return cardRecord{}, false, err
+ }
+ cands := siteCandidates(h, pr.Repo)
+ if i := slices.IndexFunc(cands, func(c wire.PlaceCandidate) bool { return c.ID == first }); i > 0 {
+ c := cands[i]
+ cands = append([]wire.PlaceCandidate{c}, slices.Delete(cands, i, i+1)...)
+ }
+ if len(cands) == 0 {
+ return cardRecord{}, false, nil
+ }
+ prop := placeProposal{Kind: wire.PlaceSite, ProjectID: pr.ID, TaskID: task}
+ opts := make([]string, 0, len(cands)+1)
+ for _, c := range cands {
+ prop.Candidates = append(prop.Candidates, placeOption{PlaceCandidate: c, Hash: optionHash(c)})
+ opts = append(opts, c.ID)
+ }
+ opts = append(opts, wire.ChoiceNotNow)
+ rawOpts, _ := json.Marshal(opts)
+ rawProp, _ := json.Marshal(prop)
+ best := cands[0]
+ question := t.words("chat.card.place_question", mdLabel(projectTitle(pr)), best.ConsoleLabel, best.Account)
+ if question == "" {
+ question = projectTitle(pr)
+ }
+ now := t.now()
+ c := cardRecord{ID: newID("c_"), Person: person, Kind: wire.CardPlace, State: wire.CardOpen, TurnID: turn, ProjectID: pr.ID, TaskID: task, Name: projectTitle(pr), Question: question, Options: string(rawOpts), Place: string(rawProp), Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: lane}
+ if err := t.db.Create(&c).Error; err != nil {
+ return cardRecord{}, false, err
+ }
+ if err := t.auditPlace(person, "place.proposed", pr.ID, best.Console, best.Account, c.ID); err != nil {
+ return cardRecord{}, false, err
+ }
+ return c, true, t.cardEvent(c)
+}
+
+// projectTitle is a project's name for people.
+func projectTitle(pr projectRecord) string {
+ if title := pr.shownTitle(); title != "" {
+ return title
+ }
+ return ProjectName(pr.Repo)
+}
+
+// openPlaceCardFor reports whether a place card for the task is open.
+func (t *txn) openPlaceCardFor(task string) (bool, error) {
+ var n int64
+ err := t.db.Model(&cardRecord{}).Where("task_id = ? AND kind = ? AND state = ?", task, wire.CardPlace, wire.CardOpen).Count(&n).Error
+ return n > 0, err
+}
+
+func (t *txn) openPlaceCard(projectID string) (bool, error) {
+ var n int64
+ err := t.db.Model(&cardRecord{}).Where("project_id = ? AND kind = ? AND state = ?", projectID, wire.CardPlace, wire.CardOpen).Count(&n).Error
+ return n > 0, err
+}
+
+// answerPlace is an owner's answer on a place card for their own
+// conversation: a candidate the card offered, its hash as stored, still
+// in their primary's reach now, confirms the place and binds the project
+// (Not now leaves it). Nothing is sent to CARLOS. When the card was for a
+// merged task, its publish card follows.
+func (t *txn) answerPlace(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) {
+ if err := t.hkForbid("place"); err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ v, err := t.cardView(c)
+ if err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ var prop placeProposal
+ if json.Unmarshal([]byte(c.Place), &prop) != nil || prop.Kind != wire.PlaceSite {
+ return wire.Card{}, v, ErrCardConflict
+ }
+ if c.State != wire.CardOpen || c.Revision != in.Revision {
+ return wire.Card{}, v, ErrCardConflict
+ }
+ if c.Person != person {
+ return wire.Card{}, wire.Card{}, ErrForbidden
+ }
+ if err := t.isOwner(person); err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ var pr projectRecord
+ if err := t.db.Where("id = ?", prop.ProjectID).First(&pr).Error; err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ if in.Choice == wire.ChoiceNotNow {
+ // A merged task's preview held for this card goes with Not now.
+ var held bool
+ var k taskRecord
+ if prop.TaskID != "" {
+ if k, err = t.loadTask(prop.TaskID); err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ steps, err := t.steps(k.ID)
+ if err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ if held, err = t.previewHeld(k, steps); err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ }
+ c.State, c.Choice = wire.CardAnswered, in.Choice
+ if err := t.saveCard(&c); err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ if held {
+ if err := t.releasePreview(k); err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ }
+ if err := t.auditPlace(person, "place.declined", pr.ID, "", "", c.ID); err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ out, err := t.cardView(c)
+ return out, wire.Card{}, err
+ }
+ i := slices.IndexFunc(prop.Candidates, func(o placeOption) bool { return o.ID == in.Choice })
+ if i < 0 {
+ return wire.Card{}, wire.Card{}, ErrInvalid
+ }
+ opt := prop.Candidates[i]
+ if opt.Hash != optionHash(opt.PlaceCandidate) || opt.ID != wire.CandidateID(opt.Console, opt.Sqid) {
+ return wire.Card{}, v, ErrCardConflict
+ }
+ // Still reachable now: the candidate is in the primary's current reach.
+ h, err := t.hello(person)
+ if err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ if !slices.ContainsFunc(siteCandidates(h, pr.Repo), func(c wire.PlaceCandidate) bool { return c == opt.PlaceCandidate }) {
+ return wire.Card{}, v, ErrCardConflict
+ }
+ b, place, err := t.siteBinding(pr.ID)
+ if err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ if place != nil {
+ // The project's site was placed meanwhile (slice 1 has no change).
+ return wire.Card{}, v, ErrCardConflict
+ }
+ p, err := t.confirmPlace(person, c, opt)
+ if err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ if _, err := t.bindSite(pr, b, p); err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ c.State, c.Choice = wire.CardAnswered, in.Choice
+ if err := t.saveCard(&c); err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ if prop.TaskID != "" {
+ k, err := t.loadTask(prop.TaskID)
+ if err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ if k.Creator == person && k.ProjectID == pr.ID {
+ if _, _, err := t.offerSite(&k, "", "owner:"+person); err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ }
+ }
+ out, err := t.cardView(c)
+ return out, wire.Card{}, err
+}
+
+// confirmPlace is the confirmed place for the option: the existing one at
+// that destination, else a new one, confirmed by person.
+func (t *txn) confirmPlace(person string, c cardRecord, opt placeOption) (placeRecord, error) {
+ var p placeRecord
+ err := t.db.Where("kind = ? AND adapter = ? AND console = ? AND account_sqid = ?", wire.PlaceSite, wire.AdapterCarlosApp, opt.Console, opt.Sqid).First(&p).Error
+ now := t.now()
+ switch {
+ case errors.Is(err, gorm.ErrRecordNotFound):
+ p = placeRecord{ID: newID("pl_"), Kind: wire.PlaceSite, Adapter: wire.AdapterCarlosApp, Console: opt.Console, AccountSqid: opt.Sqid, AccountName: opt.Account, State: wire.PlaceConfirmed, Revision: 1, ProposedBy: "coordinator:" + c.Person, ProposedAt: &c.CreatedAt, ConfirmedBy: person, ConfirmedAt: &now, CreatedAt: now, UpdatedAt: now}
+ if err := t.db.Create(&p).Error; err != nil {
+ return p, err
+ }
+ case err != nil:
+ return p, err
+ case p.State != wire.PlaceConfirmed || p.AccountName != opt.Account:
+ p.State, p.AccountName, p.ConfirmedBy, p.ConfirmedAt, p.Revision, p.UpdatedAt = wire.PlaceConfirmed, opt.Account, person, &now, p.Revision+1, now
+ if err := t.db.Model(&placeRecord{}).Where("id = ?", p.ID).Select("state", "account_name", "confirmed_by", "confirmed_at", "revision", "updated_at").Updates(&p).Error; err != nil {
+ return p, err
+ }
+ }
+ return p, t.auditPlace(person, "place.confirmed", c.ProjectID, p.Console, p.AccountName, p.ID)
+}
+
+// bindSite binds the project's site to place p: an unplaced binding (an
+// app kept from before places) keeps its app and gains the place; none
+// gets the app projectSite mints. Its revision moves either way; nothing
+// says the app was created.
+func (t *txn) bindSite(pr projectRecord, b *projectPlaceRecord, p placeRecord) (projectPlaceRecord, error) {
+ now := t.now()
+ if b != nil {
+ b.PlaceID, b.Revision, b.UpdatedAt = p.ID, b.Revision+1, now
+ err := t.db.Model(&projectPlaceRecord{}).Where("id = ? AND place_id = ''", b.ID).Select("place_id", "revision", "updated_at").Updates(b).Error
+ return *b, err
+ }
+ app, ok, err := t.projectSite(pr)
+ if err != nil {
+ return projectPlaceRecord{}, err
+ }
+ if !ok {
+ return projectPlaceRecord{}, ErrCardConflict
+ }
+ nb := projectPlaceRecord{ID: newID("pp_"), ProjectID: pr.ID, Kind: wire.PlaceSite, PlaceID: p.ID, App: app, Revision: 1, CreatedAt: now, UpdatedAt: now}
+ return nb, t.db.Create(&nb).Error
+}
+
+// auditPlace writes one audit row for a place action, with no credential.
+func (t *txn) auditPlace(actor, kind, project, console, account, what string) error {
+ if t.s.authority.Audit == nil {
+ return nil
+ }
+ return t.s.authority.Audit(t.db, actor, kind, project+"/"+console+"/"+account+":"+what)
+}
+
+// placeCardView fills a place card's candidates.
+func placeCardView(v *wire.Card, c cardRecord) {
+ var prop placeProposal
+ if json.Unmarshal([]byte(c.Place), &prop) != nil {
+ return
+ }
+ out := &wire.CardPlaceView{Kind: prop.Kind, Project: prop.ProjectID, Candidates: []wire.PlaceCandidate{}}
+ for _, o := range prop.Candidates {
+ out.Candidates = append(out.Candidates, o.PlaceCandidate)
+ }
+ v.Place = out
+}
diff --git a/internal/equipo/chat/places_models.go b/internal/equipo/chat/places_models.go
new file mode 100644
index 00000000..19d9b2d9
--- /dev/null
+++ b/internal/equipo/chat/places_models.go
@@ -0,0 +1,51 @@
+package chat
+
+import "time"
+
+// placeRecord is a confirmed destination of the team (spec 2026-11-26
+// places, slice 1): one kind, one adapter, a console host and an account.
+// A team record, never scope.Owned: the same for every member, written
+// only by an owner's tap.
+type placeRecord struct {
+ ID string `gorm:"primaryKey"`
+ Kind string `gorm:"uniqueIndex:chat_place_destination,priority:1"`
+ Adapter string `gorm:"uniqueIndex:chat_place_destination,priority:2"`
+ Console string `gorm:"uniqueIndex:chat_place_destination,priority:3"`
+ AccountSqid string `gorm:"uniqueIndex:chat_place_destination,priority:4"`
+ AccountName string
+ State string
+ Revision int64
+ ProposedBy string
+ ProposedAt *time.Time
+ ConfirmedBy string
+ ConfirmedAt *time.Time
+ CreatedAt time.Time
+ UpdatedAt time.Time
+}
+
+func (placeRecord) TableName() string { return "chat_places" }
+
+// projectPlaceRecord binds a project to a place of one kind: for a site,
+// the app code minted for it; AppCreatedAt and AppCreatedStep when and by
+// which step a creation was attempted (allowed, not proven: setup is
+// never offered again); the deploy key a runner was allowed to mint for
+// it (name, runner, who, when, by which step; never the secret).
+type projectPlaceRecord struct {
+ ID string `gorm:"primaryKey"`
+ ProjectID string `gorm:"uniqueIndex:chat_project_place_kind,priority:1"`
+ Kind string `gorm:"uniqueIndex:chat_project_place_kind,priority:2"`
+ PlaceID string
+ App string
+ Revision int64
+ AppCreatedAt *time.Time
+ AppCreatedStep string
+ DeployName string
+ DeployRunner string
+ DeployMintedBy string
+ DeployMintedAt *time.Time
+ DeployStep string
+ CreatedAt time.Time
+ UpdatedAt time.Time
+}
+
+func (projectPlaceRecord) TableName() string { return "chat_project_places" }
diff --git a/internal/equipo/chat/places_test.go b/internal/equipo/chat/places_test.go
new file mode 100644
index 00000000..a7282dee
--- /dev/null
+++ b/internal/equipo/chat/places_test.go
@@ -0,0 +1,84 @@
+package chat
+
+import (
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+func reachOf(logins ...wire.ReachLogin) wire.Hello {
+ return wire.Hello{Capabilities: &wire.Capabilities{Reach: &wire.Reach{Logins: logins}}}
+}
+
+// siteCandidates' fixed rules (places spec §2): the flagship account named
+// like the repository's namespace first (amadan.net/paulca/nearys:
+// Carloku, account paulca; oficina projects: account oficina); else the
+// only owned account; then flagship, then console and name; at most six;
+// never an account the reach does not own.
+func TestSiteCandidatesRank(t *testing.T) {
+ carloku := wire.ReachLogin{Console: wire.FlagshipConsole, Accounts: []wire.ReachAccount{{Name: "oficina", Sqid: "bcdfg"}, {Name: "paulca", Sqid: "kmnpq"}}}
+ tito := wire.ReachLogin{Console: wire.TitoConsole, Accounts: []wire.ReachAccount{{Name: "paulca", Sqid: "rstuv"}}}
+ names := func(cs []wire.PlaceCandidate) []string {
+ var out []string
+ for _, c := range cs {
+ out = append(out, c.ConsoleLabel+"/"+c.Account)
+ }
+ return out
+ }
+ for name, c := range map[string]struct {
+ h wire.Hello
+ repo string
+ want []string
+ }{
+ "nearys": {reachOf(tito, carloku), "amadan.net/paulca/nearys", []string{"Carloku/paulca", "Carloku/oficina", "Tito/paulca"}},
+ "oficina": {reachOf(carloku, tito), "amadan.net/oficina/equipo", []string{"Carloku/oficina", "Carloku/paulca", "Tito/paulca"}},
+ "no match": {reachOf(tito, carloku), "amadan.net/someone/site", []string{"Carloku/oficina", "Carloku/paulca", "Tito/paulca"}},
+ "only account": {reachOf(tito), "amadan.net/someone/site", []string{"Tito/paulca"}},
+ "tito match?": {reachOf(tito), "amadan.net/paulca/nearys", []string{"Tito/paulca"}},
+ "none": {wire.Hello{}, "amadan.net/paulca/nearys", nil},
+ } {
+ got := siteCandidates(c.h, c.repo)
+ if len(got) != len(c.want) {
+ t.Fatalf("%s: %v", name, names(got))
+ }
+ for i := range got {
+ if names(got)[i] != c.want[i] || got[i].ID != wire.CandidateID(got[i].Console, got[i].Sqid) {
+ t.Fatalf("%s: %v", name, names(got))
+ }
+ }
+ }
+ var many []wire.ReachAccount
+ for _, s := range []string{"bcd", "bce", "bcf", "bcg", "bch", "bcj", "bck", "bcm"} {
+ many = append(many, wire.ReachAccount{Name: "a" + s, Sqid: s})
+ }
+ if got := siteCandidates(reachOf(wire.ReachLogin{Console: wire.FlagshipConsole, Accounts: many}), "amadan.net/x/y"); len(got) != wire.MaxPlaceOptions {
+ t.Fatalf("%d candidates", len(got))
+ }
+}
+
+// A snapshot's target is everything but the key name, minted afresh for
+// every card.
+func TestPublishSnapshotTarget(t *testing.T) {
+ a := publishSnapshot{SHA: "e", Place: "pl_1", PlaceRevision: 1, Binding: "pp_1", BindingRevision: 1, Console: wire.FlagshipConsole, Sqid: "kmnpq", Name: "paulca", App: "site-nearys-abcdef", Mode: wire.SiteSetup, DeployName: "eq-nearys-abcdef-aaaa", Destination: "d"}
+ b := a
+ b.DeployName = "eq-nearys-abcdef-bbbb"
+ if !a.sameTarget(b) {
+ t.Fatal("the key name moved the target")
+ }
+ for _, f := range []func(s *publishSnapshot){
+ func(s *publishSnapshot) { s.PlaceRevision++ },
+ func(s *publishSnapshot) { s.BindingRevision++ },
+ func(s *publishSnapshot) { s.Mode = wire.SiteMint },
+ func(s *publishSnapshot) { s.Sqid = "bcdfg" },
+ func(s *publishSnapshot) { s.SHA = "f" },
+ } {
+ c := a
+ f(&c)
+ if a.sameTarget(c) {
+ t.Fatalf("%+v counted the same", c)
+ }
+ }
+ if n := deployName("site-" + "abcdefghijklmnopqrstuvwxyz0"); len(n) > 32 || !wire.ValidDeployName(n) {
+ t.Fatalf("deploy name %q", n)
+ }
+}
diff --git a/internal/equipo/chat/places_tools.go b/internal/equipo/chat/places_tools.go
new file mode 100644
index 00000000..6887dae7
--- /dev/null
+++ b/internal/equipo/chat/places_tools.go
@@ -0,0 +1,375 @@
+package chat
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "slices"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "gorm.io/gorm"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// The coordinator's place tools (protocol 31). places and site_status are
+// read-only and answer quoted data; propose_place raises a place card and
+// publish_site a publish card (or a place card first), and only the
+// person's tap confirms or publishes. No tool takes a console, account or
+// app: a place is chosen by a candidate id code derived.
+
+// What the model reads back; people never see these.
+const (
+ toolPlaceProposed = "Proposed: a card in the person's conversation asks where the site goes. Only an owner's tap confirms it and nothing is published or created until they also tap Publish. Tell them in one line; do not ask again."
+ toolPlaceExists = "This project's site already has a confirmed place; call places to see it. Use publish_site to offer publishing."
+ toolPlaceOpen = "The person already has a card about where this site goes. Wait for their tap."
+ toolPlaceUnknown = "That candidate is not one this person's runner can reach now; call places for the current candidates."
+ toolPlaceNoProject = "No such project; call status for the projects."
+ toolSiteOffered = "Offered: a card in the person's conversation asks whether to publish the merged site to the place it names. Only their tap publishes. Tell them in one line, and never say it is live until the task shows its address."
+ toolSiteProposed = "There is no confirmed place for this site yet: a card asks the person where it goes first, and the publish card follows their choice. Tell them in one line."
+ toolSiteNotWebsite = "Not offered: this task is not a website Equipo merged with an approved Review of its site config (release/preview.json). read_task shows where it stands."
+ toolSiteNothingDue = "Not offered: a publish card is already open for this task, or its merged commit is being published or was published. read_task shows where it stands."
+ toolSiteMissing = "Not offered: it cannot be published now (missing: %s). The person was told why in their conversation; say it in one line in plain words and do not ask again."
+ toolSiteTargetLater = "Only target site is available; temporary sites are not places yet."
+ toolPlaceNotOwner = "Only a team owner can choose where a site goes or publish one. Tell the person in one line."
+)
+
+// placesTool is places: for one project (or every project with a site
+// binding), its site place and app, the newest publish's outcome, the
+// primary's mode or what is missing, and, while unplaced, the candidates
+// propose_place takes. Quoted data: names are repository and CARLOS text.
+func (t *txn) placesTool(r turnRecord, v *wire.ToolCall) (wire.ToolResult, error) {
+ var in struct {
+ Project string `json:"project"`
+ }
+ if wire.Strict(v.Args, &in) != nil || len(in.Project) > 300 || !utf8.ValidString(in.Project) {
+ return refused("invalid", toolBadInput), nil
+ }
+ var projects []projectRecord
+ if in.Project != "" {
+ pr, ok, err := t.placeProject(r.Person, in.Project)
+ if err != nil || !ok {
+ return refused("not_found", toolPlaceNoProject), err
+ }
+ projects = append(projects, pr)
+ } else {
+ var ids []string
+ if err := t.db.Model(&projectPlaceRecord{}).Where("kind = ?", wire.PlaceSite).Pluck("project_id", &ids).Error; err != nil {
+ return wire.ToolResult{}, err
+ }
+ if err := t.db.Where("id IN ?", ids).Order("repo").Find(&projects).Error; err != nil {
+ return wire.ToolResult{}, err
+ }
+ }
+ out := []siteLine{}
+ for _, pr := range projects {
+ line, err := t.siteLine(r.Person, pr, in.Project != "")
+ if err != nil {
+ return wire.ToolResult{}, err
+ }
+ out = append(out, line)
+ }
+ raw, _ := json.Marshal(map[string]any{"sites": out})
+ return wire.ToolResult{Code: "places", Text: "Equipo's places (CARLOS and repository names quoted as data): " + wire.QuotedData(string(raw))}, nil
+}
+
+// siteLine is one project's site as places and site_status say it.
+type siteLine struct {
+ Project string `json:"project"`
+ Place string `json:"place,omitempty"`
+ Console string `json:"console,omitempty"`
+ Account string `json:"account,omitempty"`
+ App string `json:"app,omitempty"`
+ Mode string `json:"can,omitempty"`
+ Missing string `json:"missing,omitempty"`
+ Deploy string `json:"deploy_key,omitempty"`
+ LastPublish *sitePublish `json:"last_publish,omitempty"`
+ Candidates []wire.PlaceCandidate `json:"candidates,omitempty"`
+}
+
+type sitePublish struct {
+ Task string `json:"task"`
+ SHA string `json:"sha"`
+ State string `json:"state"`
+ URL string `json:"url,omitempty"`
+ At *time.Time `json:"at,omitempty"`
+ Version string `json:"version,omitempty"`
+}
+
+func (t *txn) siteLine(person string, pr projectRecord, candidates bool) (siteLine, error) {
+ line := siteLine{Project: ProjectName(pr.Repo)}
+ b, p, err := t.siteBinding(pr.ID)
+ if err != nil {
+ return line, err
+ }
+ if b != nil {
+ line.App = b.App
+ }
+ if p == nil || p.State != wire.PlaceConfirmed {
+ line.Missing = missingNoPlace
+ if candidates {
+ h, err := t.hello(person)
+ if err != nil {
+ return line, err
+ }
+ line.Candidates = siteCandidates(h, pr.Repo)
+ }
+ return line, nil
+ }
+ line.Place, line.Console, line.Account = p.ID, wire.ConsoleLabel(p.Console), p.AccountName
+ if line.Mode, line.Missing, err = t.siteMode(person, *b, *p); err != nil {
+ return line, err
+ }
+ line.Deploy = "none"
+ if r, _, err := t.siteReach(person); err != nil {
+ return line, err
+ } else if r != nil {
+ for _, d := range r.Deploys {
+ if d.Console == p.Console && d.Account == p.AccountSqid && d.App == b.App {
+ line.Deploy = "held"
+ if d.Lost {
+ line.Deploy = "lost"
+ }
+ if !d.Lost {
+ break
+ }
+ }
+ }
+ }
+ last, err := t.lastPublish(pr.ID)
+ line.LastPublish = last
+ return line, err
+}
+
+// lastPublish is the newest publish step of the project's tasks.
+func (t *txn) lastPublish(projectID string) (*sitePublish, error) {
+ var s stepRecord
+ err := t.db.Joins("JOIN chat_tasks ON chat_tasks.id = chat_steps.task_id").Where("chat_tasks.project_id = ? AND chat_steps.specialist = ?", projectID, wire.SpecialistPublish).Order("chat_steps.created_at DESC").Limit(1).Find(&s).Error
+ if err != nil || s.ID == "" {
+ return nil, err
+ }
+ out := &sitePublish{Task: s.TaskID, SHA: short(s.CandidateSHA), State: s.State, At: s.FinishedAt}
+ if p := decodePublish(s.Publish); p != nil {
+ if p.Outcome != "" {
+ out.State = p.Outcome
+ }
+ out.URL, out.Version = p.URL, p.Version
+ }
+ return out, nil
+}
+
+// placeProject is the project a place tool names, by the one exact
+// resolver (namedProject) or its repository.
+func (t *txn) placeProject(person, name string) (projectRecord, bool, error) {
+ p, err := t.namedProject(person, name)
+ if err != nil || p != nil {
+ if p == nil {
+ return projectRecord{}, false, err
+ }
+ return *p, true, nil
+ }
+ var pr projectRecord
+ err = t.db.Where("repo = ? AND state = ?", NormalizeRepo(name), wire.ProjectActive).Limit(1).Find(&pr).Error
+ return pr, err == nil && pr.ID != "", err
+}
+
+// proposePlaceTool is propose_place: an owner's coordinator raises a
+// place card for a project's site, with a candidate places listed first.
+func (t *txn) proposePlaceTool(r turnRecord, v *wire.ToolCall) (wire.ToolResult, error) {
+ var in struct {
+ Kind string `json:"kind"`
+ Project string `json:"project"`
+ Candidate string `json:"candidate"`
+ }
+ if wire.Strict(v.Args, &in) != nil || in.Kind != wire.PlaceSite || in.Project == "" || len(in.Project) > 300 || !wire.ValidCandidateID(in.Candidate) {
+ return refused("invalid", toolBadInput), nil
+ }
+ if err := t.isOwner(r.Person); err != nil {
+ if errors.Is(err, ErrForbidden) {
+ return refused("not_owner", toolPlaceNotOwner), nil
+ }
+ return wire.ToolResult{}, err
+ }
+ pr, ok, err := t.placeProject(r.Person, in.Project)
+ if err != nil || !ok {
+ return refused("not_found", toolPlaceNoProject), err
+ }
+ if _, p, err := t.siteBinding(pr.ID); err != nil || p != nil {
+ return refused("already_placed", toolPlaceExists), err
+ }
+ if open, err := t.openPlaceCard(pr.ID); err != nil || open {
+ return refused("already_proposed", toolPlaceOpen), err
+ }
+ h, err := t.hello(r.Person)
+ if err != nil {
+ return wire.ToolResult{}, err
+ }
+ found := false
+ for _, c := range siteCandidates(h, pr.Repo) {
+ found = found || c.ID == in.Candidate
+ }
+ if !found {
+ return refused("unknown_candidate", toolPlaceUnknown), nil
+ }
+ if _, ok, err := t.raisePlace(r.Person, r.Lane, r.ID, pr, "", in.Candidate); err != nil || !ok {
+ return refused("unknown_candidate", toolPlaceUnknown), err
+ }
+ return wire.ToolResult{Code: "proposed", Text: toolPlaceProposed}, nil
+}
+
+// publishSiteTool is publish_site: for the person's own merged website
+// task, the publish card (or the place card first), as offerPublish would
+// have raised it; also for an older merged task that was never asked.
+func (t *txn) publishSiteTool(r turnRecord, v *wire.ToolCall) (wire.ToolResult, error) {
+ var in struct {
+ Task string `json:"task"`
+ Target string `json:"target"`
+ }
+ if wire.Strict(v.Args, &in) != nil || strings.TrimSpace(in.Task) == "" || len(in.Task) > 100 {
+ return refused("invalid", toolBadInput), nil
+ }
+ if in.Target != "" && in.Target != wire.PlaceSite {
+ return refused("target_later", toolSiteTargetLater), nil
+ }
+ k, err := t.loadTask(strings.TrimSpace(in.Task))
+ if errors.Is(err, ErrNotFound) {
+ return refused("not_found", toolNoTask), nil
+ }
+ if err != nil {
+ return wire.ToolResult{}, err
+ }
+ if k.Creator != r.Person {
+ return refused("not_yours", toolNotYours), nil
+ }
+ if err := t.isOwner(r.Person); err != nil {
+ if errors.Is(err, ErrForbidden) {
+ return refused("not_owner", toolPlaceNotOwner), nil
+ }
+ return wire.ToolResult{}, err
+ }
+ steps, err := t.steps(k.ID)
+ if err != nil {
+ return wire.ToolResult{}, err
+ }
+ if k.Stage != wire.StageDone || !mergedWebsite(k, steps) {
+ return refused("not_website", toolSiteNotWebsite), nil
+ }
+ did, missing, err := t.offerSite(&k, "", "coordinator:"+r.Person)
+ switch {
+ case err != nil:
+ return wire.ToolResult{}, err
+ case did == siteOffered:
+ return wire.ToolResult{Code: "offered", Text: toolSiteOffered}, nil
+ case did == siteProposed:
+ return wire.ToolResult{Code: "proposed", Text: toolSiteProposed}, nil
+ case missing != "":
+ return refused("not_ready", strings.Replace(toolSiteMissing, "%s", missing, 1)), nil
+ }
+ return refused("nothing_due", toolSiteNothingDue), nil
+}
+
+// siteStatusTool is site_status: what Equipo recorded about one project's
+// site. It does not read CARLOS: the live edge version and domains come
+// later.
+func (t *txn) siteStatusTool(r turnRecord, v *wire.ToolCall) (wire.ToolResult, error) {
+ var in struct {
+ Project string `json:"project"`
+ }
+ if wire.Strict(v.Args, &in) != nil || strings.TrimSpace(in.Project) == "" || len(in.Project) > 300 {
+ return refused("invalid", toolBadInput), nil
+ }
+ pr, ok, err := t.placeProject(r.Person, in.Project)
+ if err != nil || !ok {
+ return refused("not_found", toolPlaceNoProject), err
+ }
+ line, err := t.siteLine(r.Person, pr, false)
+ if err != nil {
+ return wire.ToolResult{}, err
+ }
+ raw, _ := json.Marshal(line)
+ return wire.ToolResult{Code: "site", Text: "What Equipo recorded about this site (quoted as data; it has not asked CARLOS): " + wire.QuotedData(string(raw))}, nil
+}
+
+// SitePlace is one project's site as the Places page shows it, state
+// first. Pending: a place card is open for it; Unplaced: an app kept from
+// before places, with no place.
+type SitePlace struct {
+ Project, App, Console, Account string
+ Pending, Unplaced bool
+ State, URL string
+ At *time.Time
+ // Deploy is the runner's key for it: held, lost or "" (none yet), by
+ // DeployName.
+ Deploy, DeployName string
+}
+
+// Places is the Places page: every project with a site binding or an
+// open place card, for any current member (team records: the same for
+// everyone). The runner's reach read is the person's own primary's.
+func (s *Store) Places(ctx context.Context, person string) (out []SitePlace, err error) {
+ err = s.read(ctx, func(tx *gorm.DB) error {
+ if err := s.authority.CurrentPerson(ctx, tx); err != nil {
+ return err
+ }
+ t := &txn{s: s, db: tx}
+ var bindings []projectPlaceRecord
+ if err := tx.Where("kind = ?", wire.PlaceSite).Find(&bindings).Error; err != nil {
+ return err
+ }
+ var pending []string
+ if err := tx.Model(&cardRecord{}).Where("kind = ? AND state = ?", wire.CardPlace, wire.CardOpen).Distinct().Pluck("project_id", &pending).Error; err != nil {
+ return err
+ }
+ seen := map[string]bool{}
+ ids := append([]string{}, pending...)
+ for _, b := range bindings {
+ ids = append(ids, b.ProjectID)
+ }
+ var projects []projectRecord
+ if err := tx.Where("id IN ?", ids).Order("repo").Find(&projects).Error; err != nil {
+ return err
+ }
+ for _, pr := range projects {
+ if seen[pr.ID] {
+ continue
+ }
+ seen[pr.ID] = true
+ line := SitePlace{Project: projectTitle(pr), Pending: slices.Contains(pending, pr.ID)}
+ b, p, err := t.siteBinding(pr.ID)
+ if err != nil {
+ return err
+ }
+ if b != nil {
+ line.App = b.App
+ }
+ if p == nil {
+ line.Unplaced = b != nil
+ out = append(out, line)
+ continue
+ }
+ line.Console, line.Account = wire.ConsoleLabel(p.Console), p.AccountName
+ if last, err := t.lastPublish(pr.ID); err != nil {
+ return err
+ } else if last != nil {
+ line.State, line.URL, line.At = last.State, last.URL, last.At
+ }
+ if r, _, err := t.siteReach(person); err != nil {
+ return err
+ } else if r != nil {
+ for _, d := range r.Deploys {
+ if d.Console == p.Console && d.Account == p.AccountSqid && d.App == b.App && (line.Deploy == "" || !d.Lost) {
+ line.Deploy, line.DeployName = "held", d.Name
+ if d.Lost {
+ line.Deploy = "lost"
+ }
+ }
+ }
+ }
+ out = append(out, line)
+ }
+ return nil
+ })
+ return out, err
+}
diff --git a/internal/equipo/chat/projects.go b/internal/equipo/chat/projects.go
index 5b938ae9..f1ff8922 100644
--- a/internal/equipo/chat/projects.go
+++ b/internal/equipo/chat/projects.go
@@ -103,6 +103,9 @@ type cardRecord struct {
// Detail its one sentence more than Result.
HandoffID string `gorm:"index:chat_card_handoff"`
Detail string
+ // Place is a place card's proposal (placeProposal JSON); '' on every
+ // other card.
+ Place string
// CarryOn: a paused job card offers Carry on now, on
// CarryOnConnection (the offer's connection id), which pins it.
CarryOn bool
@@ -330,6 +333,10 @@ func (t *txn) cardView(c cardRecord) (wire.Card, error) {
return v, err
}
}
+ if c.Kind == wire.CardPlace {
+ v.Name = c.Name
+ placeCardView(&v, c)
+ }
if c.Kind == wire.CardSpecialist {
sv, err := t.specialistCard(c.ID)
if err != nil {
@@ -744,6 +751,11 @@ func (s *Store) Answer(ctx context.Context, person, id string, in wire.AnswerCar
out.Card, current = card, cur
return e
}
+ if c.Kind == wire.CardPlace {
+ card, cur, e := t.answerPlace(person, c, in)
+ out.Card, current = card, cur
+ return e
+ }
if c.Kind == wire.CardMergeShips || c.Kind == wire.CardMergePolicy || c.Kind == wire.CardMergeReceipt {
var card, cur wire.Card
var e error
diff --git a/internal/equipo/chat/publish.go b/internal/equipo/chat/publish.go
index 70b68635..85f48364 100644
--- a/internal/equipo/chat/publish.go
+++ b/internal/equipo/chat/publish.go
@@ -14,17 +14,19 @@ import (
)
// Publishing a merged website (oficina/equipo discussion 11; Paul,
-// 2026-11-12): Merge stays what merge authority makes it. After Equipo
-// merged a task whose Review found a static site config
+// 2026-11-12; places, 2026-11-26): Merge stays what merge authority makes
+// it. After Equipo merged a task whose Review found a static site config
// (release/preview.json), the creator gets a separate publish card for
-// the merged commit; only their Publish places a publish step, on their
-// primary, which must say it can publish sites at protocol 16. The app is
-// minted by code once per project, site-<slug>-<six random characters>,
-// the slug from the repository's name (never model text), and stored on
-// the project, which no other project can share; every later publish
-// uses the stored name. authorizePublish decides the step's
-// start and its deploy, which is bound to the export it reported built.
-// Every request, answer, decision, build and outcome is audited.
+// the merged commit, naming the project's confirmed site place
+// (places.go); with none, a place card comes first. Only their Publish,
+// while an owner, places a publish step, on their primary at protocol 31,
+// bound to the card's snapshot: place, binding, destination and mode.
+// The app is minted by code once per project, site-<slug>-<six random
+// characters>, the slug from the repository's name (never model text),
+// and no other project can share it. authorizePublish decides the step's
+// start and each final check, per phase of its mode, the deploy bound to
+// the export it reported built. Every request, answer, decision, build
+// and outcome is audited.
// siteSlug is a repository's name in lower-case letters and digits, every
// other run of characters one hyphen, at most siteSlugMax long ("" when
@@ -76,8 +78,16 @@ func decodePublish(raw string) *wire.PublishResult {
return &p
}
-func encodePublish(p wire.PublishResult) string {
- raw, _ := json.Marshal(p)
+// publishRecord is a publish step's stored word: the result so far and
+// the snapshot its creator's tap allowed.
+type publishRecord struct {
+ wire.PublishResult
+ Snapshot *publishSnapshot `json:"snapshot,omitempty"`
+}
+
+// encodePublish stores p with the snapshot prev carried, if any.
+func encodePublish(p wire.PublishResult, prev string) string {
+ raw, _ := json.Marshal(publishRecord{PublishResult: p, Snapshot: stepSnapshot(prev)})
return string(raw)
}
@@ -92,25 +102,6 @@ func website(steps []stepRecord, cand string) bool {
return false
}
-// primarySites reports whether person's primary speaks wire.ProtocolPublish
-// and says it is paired with a site host.
-func (t *txn) primarySites(person string) (bool, error) {
- primary, err := t.s.authority.PrimaryRunner(t.db, person)
- if err != nil || primary == "" {
- return false, err
- }
- rs, err := t.runners(person)
- if err != nil {
- return false, err
- }
- for _, r := range rs {
- if r.ID == primary {
- return r.Protocol >= wire.ProtocolPublish && r.Hello.Capabilities != nil && r.Hello.Capabilities.Sites, nil
- }
- }
- return false, nil
-}
-
// projectSite is the project's app: the stored one, else one minted now
// and stored on the project (chat_project_site_app is unique, so no two
// projects ever hold one app). ok is false when none is usable.
@@ -139,16 +130,9 @@ func (t *txn) projectSite(pr projectRecord) (string, bool, error) {
return "", false, nil
}
-// storedSite is the project's stored app, "" before one was minted.
-func storedSite(pr projectRecord) string {
- if pr.SiteApp == nil {
- return ""
- }
- return *pr.SiteApp
-}
-
// offerPublish asks the creator, once per merged commit, whether to
-// publish a merged website. It never publishes anything itself.
+// publish a merged website, at its merge (m, the merge step): never
+// silently nothing. It publishes nothing itself.
func (t *txn) offerPublish(k *taskRecord, m *stepRecord) error {
if t.hk != nil || wire.NormalKind(k.Kind) == wire.KindExplore || k.MergedSHA == "" || k.PublishAsked == k.MergedSHA {
return nil
@@ -157,37 +141,131 @@ func (t *txn) offerPublish(k *taskRecord, m *stepRecord) error {
if err != nil || !website(steps, m.CandidateSHA) {
return err
}
- if ok, err := t.primarySites(k.Creator); err != nil || !ok {
- return err
+ _, _, err = t.offerSite(k, "", "runner:"+m.RunnerID)
+ return err
+}
+
+// mergedWebsite reports whether k is a website Equipo merged, Review
+// having approved the merged candidate with its site config.
+func mergedWebsite(k taskRecord, steps []stepRecord) bool {
+ if wire.NormalKind(k.Kind) == wire.KindExplore || k.MergedSHA == "" || k.MergedInto == "" || k.CancelRequested {
+ return false
}
+ for _, s := range steps {
+ if s.Specialist == wire.SpecialistMerge && s.State == wire.StepDone && s.MergeSHA == k.MergedSHA {
+ return website(steps, s.CandidateSHA)
+ }
+ }
+ return false
+}
+
+// Outcomes of offerSite.
+const (
+ siteOffered = "offered"
+ siteProposed = "proposed"
+)
+
+// offerSite asks the creator about publishing k's merged commit: the
+// publish card bound to a snapshot when the project's site is placed and
+// the primary can do it now; else a place card (an owner, with a
+// candidate to offer; first names the coordinator's candidate); else it
+// says, once per commit and reason, what is missing. It returns what it
+// did and the reason, "" for each when nothing was due (a card is open or
+// a publish of the commit is under way).
+func (t *txn) offerSite(k *taskRecord, first, actor string) (string, string, error) {
var pr projectRecord
if err := t.db.Where("id = ?", k.ProjectID).First(&pr).Error; err != nil {
- return err
+ return "", "", err
}
- app, ok, err := t.projectSite(pr)
- if err != nil || !ok {
- return err
+ if open, err := t.openPublishCard(k.ID); err != nil || open {
+ return "", "", err
+ }
+ // A primary that cannot publish at all is said first: no place card
+ // is raised for it.
+ if _, why, err := t.siteReach(k.Creator); err != nil || why != "" {
+ if err != nil {
+ return "", "", err
+ }
+ return "", why, t.sayPublishBlocked(k, why)
+ }
+ snap, missing, err := t.siteSnapshot(*k)
+ if err != nil {
+ return "", "", err
+ }
+ if missing == missingNoPlace {
+ if open, err := t.openPlaceCard(pr.ID); err != nil || open {
+ return "", "", err
+ }
+ if t.isOwner(k.Creator) == nil {
+ _, ok, err := t.raisePlace(k.Creator, k.Lane, "", pr, k.ID, first)
+ if err != nil {
+ return "", "", err
+ }
+ if ok {
+ return siteProposed, "", nil
+ }
+ missing = missingNoLogin
+ } else {
+ missing = missingNotOwner
+ }
+ }
+ if missing != "" {
+ return "", missing, t.sayPublishBlocked(k, missing)
+ }
+ steps, err := t.steps(k.ID)
+ if err != nil {
+ return "", "", err
+ }
+ if publishBlocked(steps, k.MergedSHA, snap.Mode) {
+ return "", "", nil
}
k.PublishAsked = k.MergedSHA
if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Update("publish_asked", k.MergedSHA).Error; err != nil {
+ return "", "", err
+ }
+ if err := t.raisePublish(k, *snap); err != nil {
+ return "", "", err
+ }
+ return siteOffered, "", t.auditPublish(actor, "publish.requested", k.ID, snap.App, k.MergedSHA, snap.Mode+"@"+snap.Place)
+}
+
+// sayPublishBlocked says in the task's lane why its merged website was
+// not offered for publishing, once per merged commit and reason.
+func (t *txn) sayPublishBlocked(k *taskRecord, missing string) error {
+ reason := t.words("places.missing." + missing)
+ text := t.words("chat.publish_blocked", mdLabel(k.Title), TaskLink(k.ID), reason)
+ if reason == "" || text == "" {
+ return nil
+ }
+ idem := "publish-why:" + k.ID + ":" + short(k.MergedSHA) + ":" + missing
+ var n int64
+ if err := t.db.Model(&messageRecord{}).Where("person = ? AND idempotency_key = ?", k.Creator, idem).Count(&n).Error; err != nil || n > 0 {
+ return err
+ }
+ m := messageRecord{ID: newID("m_"), Person: k.Creator, IdempotencyKey: idem, Role: wire.RoleCoordinator, Text: text, Revision: 1, CreatedAt: t.now(), Lane: k.Lane}
+ if err := t.db.Create(&m).Error; err != nil {
return err
}
- if err := t.raisePublish(k, app); err != nil {
+ if err := t.auditPublish("instance", "publish.not_offered", k.ID, "", k.MergedSHA, missing); err != nil {
return err
}
- return t.auditPublish("runner:"+m.RunnerID, "publish.requested", k.ID, app, k.MergedSHA, "")
+ return t.messageEvent(m)
}
// raisePublish puts a publish card for the task's merged commit in its
-// creator's conversation.
-func (t *txn) raisePublish(k *taskRecord, app string) error {
+// creator's conversation, bound to snap: it names the app and the place,
+// and says what a setup or a mint does with the owner's login.
+func (t *txn) raisePublish(k *taskRecord, snap publishSnapshot) error {
now := t.now()
- question := t.words("chat.card.publish_question", mdLabel(k.Title), app)
+ question := t.words("chat.card.publish_place_question", mdLabel(k.Title), snap.App, wire.ConsoleLabel(snap.Console), snap.Name)
+ if extra := t.words("chat.card.publish_" + snap.Mode + "_note"); extra != "" && question != "" {
+ question += " " + extra
+ }
if question == "" {
question = k.Title
}
opts, _ := json.Marshal([]string{wire.ChoicePublish, wire.ChoiceNotNow})
- c := cardRecord{ID: newID("c_"), Person: k.Creator, Kind: wire.CardPublish, State: wire.CardOpen, ProjectID: k.ProjectID, TaskID: k.ID, Name: k.Title, Question: question, Options: string(opts), Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: k.Lane}
+ c := cardRecord{ID: newID("c_"), Person: k.Creator, Kind: wire.CardPublish, State: wire.CardOpen, ProjectID: k.ProjectID, TaskID: k.ID, Name: k.Title, Question: question, Options: string(opts), Place: encodeSnapshot(snap), Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: k.Lane}
if err := t.db.Create(&c).Error; err != nil {
return err
}
@@ -195,9 +273,10 @@ func (t *txn) raisePublish(k *taskRecord, app string) error {
}
// answerPublish is the creator's answer on a publish card, valid only
-// while it still asks about the task's merged commit and nothing was
-// published for it yet: Publish places the publish step, Not now leaves
-// it.
+// while it still asks about the task's merged commit and they are an
+// owner: Publish places the publish step bound to the card's snapshot,
+// once the snapshot is what the records say now; one that moved settles
+// the card and asks again. Not now leaves it.
func (t *txn) answerPublish(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) {
if err := t.hkForbid("publish"); err != nil {
return wire.Card{}, wire.Card{}, err
@@ -226,15 +305,8 @@ func (t *txn) answerPublish(person string, c cardRecord, in wire.AnswerCard) (wi
if err != nil {
return wire.Card{}, wire.Card{}, err
}
- var pr projectRecord
- if err := t.db.Where("id = ?", k.ProjectID).First(&pr).Error; err != nil {
- return wire.Card{}, wire.Card{}, err
- }
- app, free, err := t.projectSite(pr)
- if err != nil {
- return wire.Card{}, wire.Card{}, err
- }
- if k.Stage != wire.StageDone || k.MergedSHA == "" || k.PublishAsked != k.MergedSHA || !free || publishing(steps, k.MergedSHA) {
+ snap := decodeSnapshot(c.Place)
+ if snap == nil || k.Stage != wire.StageDone || k.MergedSHA == "" || k.PublishAsked != k.MergedSHA || snap.SHA != k.MergedSHA || publishBlocked(steps, k.MergedSHA, snap.Mode) {
return wire.Card{}, v, ErrCardConflict
}
held, err := t.previewHeld(k, steps)
@@ -242,10 +314,25 @@ func (t *txn) answerPublish(person string, c cardRecord, in wire.AnswerCard) (wi
return wire.Card{}, wire.Card{}, err
}
if in.Choice == wire.ChoicePublish {
- if ok, err := t.primarySites(k.Creator); err != nil {
+ now, _, err := t.siteSnapshot(k)
+ if err != nil {
return wire.Card{}, wire.Card{}, err
- } else if !ok {
- return wire.Card{}, v, ErrCardConflict
+ }
+ if now == nil || !now.sameTarget(*snap) {
+ // The place, the binding, the runner's reach or the mode moved
+ // since the card was raised: it is settled, and asked again.
+ c.State = wire.CardResolved
+ if err := t.saveCard(&c); err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ if err := t.auditPublish(person, "publish.stale", k.ID, snap.App, k.MergedSHA, c.ID); err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ if _, _, err := t.offerSite(&k, "", "owner:"+person); err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ out, err := t.cardView(c)
+ return out, wire.Card{}, err
}
}
c.State, c.Choice = wire.CardAnswered, in.Choice
@@ -259,16 +346,17 @@ func (t *txn) answerPublish(person string, c cardRecord, in wire.AnswerCard) (wi
}
}
if in.Choice == wire.ChoiceNotNow {
- if err := t.auditPublish(person, "publish.declined", k.ID, app, k.MergedSHA, ""); err != nil {
+ if err := t.auditPublish(person, "publish.declined", k.ID, snap.App, k.MergedSHA, ""); err != nil {
return wire.Card{}, wire.Card{}, err
}
out, err := t.cardView(c)
return out, wire.Card{}, err
}
- if err := t.auditPublish(person, "publish.approved", k.ID, app, k.MergedSHA, ""); err != nil {
+ if err := t.auditPublish(person, "publish.approved", k.ID, snap.App, k.MergedSHA, snap.Mode+"@"+snap.Place+":"+shortDigest(snap.Destination)); err != nil {
return wire.Card{}, wire.Card{}, err
}
- s := stepRecord{Specialist: wire.SpecialistPublish, Person: k.Creator, CandidateSHA: k.MergedSHA, DecidedBy: decidedPerson + person, Publish: encodePublish(wire.PublishResult{App: app})}
+ raw, _ := json.Marshal(publishRecord{PublishResult: wire.PublishResult{App: snap.App}, Snapshot: snap})
+ s := stepRecord{Specialist: wire.SpecialistPublish, Person: k.Creator, CandidateSHA: k.MergedSHA, DecidedBy: decidedPerson + person, Publish: string(raw)}
if err := t.nextStep(&k, steps, s); err != nil {
return wire.Card{}, wire.Card{}, err
}
@@ -276,26 +364,34 @@ func (t *txn) answerPublish(person string, c cardRecord, in wire.AnswerCard) (wi
return out, wire.Card{}, err
}
-// publishing reports whether a publish step of sha is under way or ended
-// with an outcome (one that failed may be asked for again).
-func publishing(steps []stepRecord, sha string) bool {
+// publishBlocked reports whether a publish of sha in mode may not be
+// asked for now: one is under way, or one ended with an outcome (one
+// that failed may be asked for again). A mint is the exception: it may
+// follow a done publish of the commit, which left no deploy key.
+func publishBlocked(steps []stepRecord, sha, mode string) bool {
for _, s := range steps {
- if s.Specialist == wire.SpecialistPublish && s.CandidateSHA == sha && (!wire.StepTerminal(s.State) || s.State == wire.StepDone || s.Withdrawn) {
+ if s.Specialist != wire.SpecialistPublish || s.CandidateSHA != sha {
+ continue
+ }
+ if !wire.StepTerminal(s.State) {
+ return true
+ }
+ if (s.State == wire.StepDone || s.Withdrawn) && mode != wire.SiteMint {
return true
}
}
return false
}
-// authorizePublish decides a publish step's start and its deploy check:
-// the current attempt, on the creator's primary at protocol 16, of a task
+// authorizePublish decides a publish step's start and each final check:
+// the current attempt, on the creator's primary at protocol 31, of a task
// Equipo merged at exactly this commit into its default branch and did
// not cancel, whose creator is still an owner and placed it from the
-// card; the project still a website bound to this app; a deploy check
-// also needs the recorded built digest, and exactly it. Every decision is
-// audited.
-func (t *txn) authorizePublish(l Lease, s *stepRecord, purpose, digest string) (string, error) {
- refused, err := t.publishRefusal(l, s, purpose, digest)
+// card; the place and binding still what the tap saw (sitePhase); a
+// final check also needs the recorded built digest, exactly it, and the
+// destination. Every decision is audited.
+func (t *txn) authorizePublish(l Lease, s *stepRecord, purpose, digest, destination string) (string, error) {
+ refused, err := t.publishRefusal(l, s, purpose, digest, destination)
if err != nil {
return "", err
}
@@ -310,8 +406,8 @@ func (t *txn) authorizePublish(l Lease, s *stepRecord, purpose, digest string) (
return refused, t.auditPublish("runner:"+l.Runner.RunnerID, "publish.authorize", s.TaskID, app, s.CandidateSHA, s.ID+"/"+strconv.FormatInt(s.Attempt, 10)+":"+purpose+":"+outcome+":"+shortDigest(digest))
}
-func (t *txn) publishRefusal(l Lease, s *stepRecord, purpose, digest string) (string, error) {
- if l.Protocol < wire.ProtocolPublish || purpose != "" && purpose != wire.LeasePurposePublish {
+func (t *txn) publishRefusal(l Lease, s *stepRecord, purpose, digest, destination string) (string, error) {
+ if l.Protocol < wire.ProtocolPlaces || purpose != "" && purpose != wire.LeasePurposePublish && purpose != wire.LeasePurposeMint {
return "withdrawn", nil
}
primary, err := t.s.authority.PrimaryRunner(t.db, s.Person)
@@ -329,55 +425,137 @@ func (t *txn) publishRefusal(l Lease, s *stepRecord, purpose, digest string) (st
if err != nil {
return "", err
}
- var merge *stepRecord
- for i := range steps {
- if steps[i].Specialist == wire.SpecialistMerge && steps[i].State == wire.StepDone && steps[i].MergeSHA == k.MergedSHA {
- merge = &steps[i]
- }
- }
- if merge == nil || !website(steps, merge.CandidateSHA) {
+ if !mergedWebsite(k, steps) {
return "withdrawn", nil
}
// The creator's own Publish stands behind it: the task's newest
- // publish card asks about this merged commit and is answered Publish.
+ // publish card asks about this merged commit, is answered Publish and
+ // carries the step's snapshot.
var c cardRecord
if err := t.db.Where("task_id = ? AND kind = ? AND person = ?", k.ID, wire.CardPublish, k.Creator).Order("created_at DESC, rowid DESC").Limit(1).Find(&c).Error; err != nil {
return "", err
}
- if c.ID == "" || k.PublishAsked != k.MergedSHA || c.State != wire.CardAnswered || c.Choice != wire.ChoicePublish {
+ snap, card := stepSnapshot(s.Publish), decodeSnapshot(c.Place)
+ if c.ID == "" || k.PublishAsked != k.MergedSHA || c.State != wire.CardAnswered || c.Choice != wire.ChoicePublish || snap == nil || card == nil || *snap != *card || snap.SHA != s.CandidateSHA {
return "withdrawn", nil
}
- var pr projectRecord
- if err := t.db.Where("id = ?", k.ProjectID).First(&pr).Error; err != nil {
+ p := decodePublish(s.Publish)
+ if p == nil || p.App != snap.App {
+ return "withdrawn", nil
+ }
+ if purpose != "" {
+ if p.Digest == "" {
+ return wire.RefusedPublishNotBuilt, nil
+ }
+ if digest != p.Digest || destination != snap.Destination {
+ return "withdrawn", nil
+ }
+ }
+ return t.sitePhase(k, s, *snap, purpose, l.Runner.RunnerID)
+}
+
+// sitePhase decides one phase of a publish step's approved mode, which
+// never changes: the place and binding at the snapshot's revisions and
+// destination, and what that phase needs now.
+//
+// - setup: its start and deploy check need no creation attempt recorded
+// (or this step's) and the owner's login; the allowed deploy check
+// records the attempt, with this step's id, so setup is never offered
+// again. Its mint check needs that attempt to be this step's.
+// - mint: its start and mint check need an attempt, no held key, the
+// login and no other step's mint; the allowed mint check records this
+// step as the key's. Its deploy check needs that, whatever the reach
+// says by then (the key it minted may not be in a hello yet).
+// - publish: every phase needs the held key.
+func (t *txn) sitePhase(k taskRecord, s *stepRecord, snap publishSnapshot, purpose, runner string) (string, error) {
+ b, pl, err := t.placedSite(k.ProjectID)
+ if err != nil {
return "", err
}
- p := decodePublish(s.Publish)
- if app := storedSite(pr); p == nil || app == "" || p.App != app {
+ if b == nil || b.ID != snap.Binding || b.Revision != snap.BindingRevision || b.App != snap.App || pl.ID != snap.Place || pl.Revision != snap.PlaceRevision || pl.Console != snap.Console || pl.AccountSqid != snap.Sqid || pl.AccountName != snap.Name || wire.SiteDestination(pl.Console, pl.AccountSqid, pl.AccountName, b.App) != snap.Destination {
return "withdrawn", nil
}
- if purpose != wire.LeasePurposePublish {
- return "", nil
+ r, missing, err := t.siteReach(k.Creator)
+ if err != nil {
+ return "", err
}
- if p.Digest == "" {
- return wire.RefusedPublishNotBuilt, nil
+ if missing != "" {
+ return "withdrawn", nil
}
- if digest != p.Digest {
+ login := reachLogin(r, snap.Console, snap.Sqid)
+ _, held := reachDeploy(r, snap.Console, snap.Sqid, snap.App)
+ now := t.now()
+ switch snap.Mode {
+ case wire.SiteSetup:
+ switch purpose {
+ case "", wire.LeasePurposePublish:
+ if !login || b.AppCreatedAt != nil && b.AppCreatedStep != s.ID {
+ return "withdrawn", nil
+ }
+ if purpose == wire.LeasePurposePublish && b.AppCreatedAt == nil {
+ if err := t.db.Model(&projectPlaceRecord{}).Where("id = ? AND app_created_at IS NULL", b.ID).Updates(map[string]any{"app_created_at": now, "app_created_step": s.ID}).Error; err != nil {
+ return "", err
+ }
+ if err := t.auditPlace("runner:"+runner, "site.create_allowed", k.ProjectID, snap.Console, snap.Name, snap.App+"/"+s.ID); err != nil {
+ return "", err
+ }
+ }
+ case wire.LeasePurposeMint:
+ if !login || b.AppCreatedStep != s.ID || b.DeployStep != "" && b.DeployStep != s.ID {
+ return "withdrawn", nil
+ }
+ return "", t.allowMint(k, s, snap, *b, runner)
+ }
+ case wire.SiteMint:
+ switch purpose {
+ case "":
+ if !login || held || b.AppCreatedAt == nil || b.DeployStep != "" && b.DeployStep != s.ID {
+ return "withdrawn", nil
+ }
+ case wire.LeasePurposeMint:
+ if !login || held || b.AppCreatedAt == nil || b.DeployStep != "" && b.DeployStep != s.ID {
+ return "withdrawn", nil
+ }
+ return "", t.allowMint(k, s, snap, *b, runner)
+ case wire.LeasePurposePublish:
+ if b.DeployStep != s.ID {
+ return "withdrawn", nil
+ }
+ }
+ case wire.SitePublish:
+ if purpose == wire.LeasePurposeMint || !held || b.AppCreatedAt == nil {
+ return "withdrawn", nil
+ }
+ default:
return "withdrawn", nil
}
return "", nil
}
+// allowMint records that this step may mint the binding's deploy key, by
+// the snapshot's name, on this runner, for the creator: once per step.
+func (t *txn) allowMint(k taskRecord, s *stepRecord, snap publishSnapshot, b projectPlaceRecord, runner string) error {
+ if b.DeployStep == s.ID {
+ return nil
+ }
+ now := t.now()
+ if err := t.db.Model(&projectPlaceRecord{}).Where("id = ?", b.ID).Updates(map[string]any{"deploy_name": snap.DeployName, "deploy_runner": runner, "deploy_minted_by": k.Creator, "deploy_minted_at": now, "deploy_step": s.ID}).Error; err != nil {
+ return err
+ }
+ return t.auditPlace("runner:"+runner, "site.deploy_mint_allowed", k.ProjectID, snap.Console, snap.Name, snap.App+"/"+snap.DeployName+"/"+s.ID)
+}
+
// publishBuilt records a running publish report's export, once per
// attempt, from the primary at protocol 16.
func publishBuilt(l Lease, role string, s *stepRecord, v *wire.StepReport) bool {
b, p := v.Publish, decodePublish(s.Publish)
- if s.Specialist != wire.SpecialistPublish || b == nil || p == nil || b.Phase != wire.PublishBuilt || p.Digest != "" || role != wire.RolePrimary || l.Protocol < wire.ProtocolPublish {
+ if s.Specialist != wire.SpecialistPublish || b == nil || p == nil || b.Phase != wire.PublishBuilt || p.Digest != "" || role != wire.RolePrimary || l.Protocol < wire.ProtocolPlaces {
return false
}
if !previewDigest.MatchString(b.Digest) || b.Files < 1 || b.Files > 2000 || b.Bytes < 0 || b.Bytes > 50<<20 {
return false
}
- s.Publish = encodePublish(wire.PublishResult{Phase: wire.PublishBuilt, App: p.App, Digest: b.Digest, Files: b.Files, Bytes: b.Bytes})
+ s.Publish = encodePublish(wire.PublishResult{Phase: wire.PublishBuilt, App: p.App, Digest: b.Digest, Files: b.Files, Bytes: b.Bytes}, s.Publish)
return true
}
@@ -390,7 +568,7 @@ var siteURL = regexp.MustCompile(`^https://site-[a-z0-9-]+\.[a-z0-9-]+(\.[a-z0-9
// false ignores it.
func acceptPublishDone(l Lease, role string, s *stepRecord, v *wire.StepReport) (string, bool) {
d, built := v.Publish, decodePublish(s.Publish)
- if d == nil || built == nil || built.Digest == "" || d.Phase != wire.PublishDone || role != wire.RolePrimary || l.Protocol < wire.ProtocolPublish || !v.Termination || v.CandidateSHA != s.CandidateSHA {
+ if d == nil || built == nil || built.Digest == "" || d.Phase != wire.PublishDone || role != wire.RolePrimary || l.Protocol < wire.ProtocolPlaces || !v.Termination || v.CandidateSHA != s.CandidateSHA {
return "", false
}
// An unconfirmed outcome may come without the digest (a restart that
@@ -398,7 +576,7 @@ func acceptPublishDone(l Lease, role string, s *stepRecord, v *wire.StepReport)
if d.App != built.App || d.Digest != built.Digest && (d.Outcome != wire.PublishUnconfirmed || d.Digest != "") {
return "", false
}
- out := wire.PublishResult{Phase: wire.PublishDone, App: built.App, Digest: built.Digest, Files: built.Files, Bytes: built.Bytes, Outcome: d.Outcome, Version: clipVersion(d.Version)}
+ out := wire.PublishResult{Phase: wire.PublishDone, App: built.App, Digest: built.Digest, Files: built.Files, Bytes: built.Bytes, Outcome: d.Outcome, Version: clipVersion(d.Version), DeployHeld: d.DeployHeld}
ownURL := d.URL != "" && len(d.URL) <= 200 && siteURL.MatchString(d.URL) && strings.HasPrefix(d.URL, "https://"+built.App+".")
switch d.Outcome {
case wire.PublishPublished:
@@ -413,7 +591,7 @@ func acceptPublishDone(l Lease, role string, s *stepRecord, v *wire.StepReport)
default:
return "", false
}
- return encodePublish(out), true
+ return encodePublish(out, s.Publish), true
}
// publishEnded says how a publish step ended in its creator's
@@ -436,6 +614,10 @@ func (t *txn) publishEnded(k *taskRecord, s *stepRecord) error {
// The account already holds the name: nothing was deployed, and
// asking again would only meet it again.
key, args = "chat.publish_taken", []any{mdLabel(k.Title), TaskLink(k.ID), app}
+ case s.Reason == reasonAppUnproven:
+ // The app is there but this runner has no proof it made it:
+ // nothing is minted or deployed, and it is not asked again.
+ key, args = "chat.publish_unproven", []any{mdLabel(k.Title), TaskLink(k.ID), app}
}
if args == nil {
args = []any{mdLabel(k.Title), TaskLink(k.ID)}
@@ -463,13 +645,36 @@ func (t *txn) publishEnded(k *taskRecord, s *stepRecord) error {
if err := t.touchPublishCards(*k); err != nil {
return err
}
- if s.State != wire.StepDone && app != "" && s.Reason != "publish_app_taken" {
+ snap := stepSnapshot(s.Publish)
+ if snap != nil && snap.Mode == wire.SiteMint && s.Reason == reasonAppMissing {
+ // The mint found no app at all: the attempt created nothing, so
+ // the next card is a setup again (a new tap).
+ if err := t.db.Model(&projectPlaceRecord{}).Where("id = ?", snap.Binding).Updates(map[string]any{"app_created_at": nil, "app_created_step": "", "deploy_name": "", "deploy_runner": "", "deploy_minted_by": "", "deploy_minted_at": nil, "deploy_step": ""}).Error; err != nil {
+ return err
+ }
+ }
+ switch {
+ case s.State != wire.StepDone && app != "" && s.Reason != "publish_app_taken" && s.Reason != reasonAppUnproven:
// Nothing was published: the creator may ask for it again.
- return t.raisePublish(k, app)
+ _, _, err := t.offerSite(k, "", "runner:"+s.RunnerID)
+ return err
+ case s.State == wire.StepDone && snap != nil && snap.Mode != wire.SitePublish && (p == nil || !p.DeployHeld):
+ // Published, but no deploy key is held for it: the creator is
+ // asked to mint one (the recovery route; a new tap).
+ _, _, err := t.offerSite(k, "", "runner:"+s.RunnerID)
+ return err
}
return nil
}
+// Reasons a mint refused before minting: the app is definitely absent
+// (the setup attempt created nothing), or present without this runner's
+// proof that it made it (never adopted).
+const (
+ reasonAppMissing = "publish_app_missing"
+ reasonAppUnproven = "publish_app_unproven"
+)
+
// settlePublish ends a publish attempt that started but cannot run on and
// gave no outcome: once its export was recorded as built it may have
// deployed, so it is done and could not be confirmed; before that nothing
@@ -479,7 +684,7 @@ func (t *txn) settlePublish(k *taskRecord, s *stepRecord) error {
now := t.now()
s.Terminated, s.FinishedAt, s.Withdrawn = true, &now, false
if p := decodePublish(s.Publish); p != nil && p.Digest != "" {
- s.State, s.Reason, s.Publish = wire.StepDone, "withdrawn", encodePublish(wire.PublishResult{Phase: wire.PublishDone, App: p.App, Digest: p.Digest, Files: p.Files, Bytes: p.Bytes, Outcome: wire.PublishUnconfirmed})
+ s.State, s.Reason, s.Publish = wire.StepDone, "withdrawn", encodePublish(wire.PublishResult{Phase: wire.PublishDone, App: p.App, Digest: p.Digest, Files: p.Files, Bytes: p.Bytes, Outcome: wire.PublishUnconfirmed}, s.Publish)
} else {
s.State, s.Reason = wire.StepCancelled, "withdrawn"
}
@@ -490,11 +695,12 @@ func (t *txn) settlePublish(k *taskRecord, s *stepRecord) error {
}
// fencePublishes settles every queued or running publish step placed on
-// a runner that connects below wire.ProtocolPublish: its dispatch is
+// a runner that connects below wire.ProtocolPlaces (a publish is bound
+// to its place since 31): its dispatch is
// retired, one it may hold is cancelled, and the step ends
// runner_outdated. Nothing is published by it.
func (t *txn) fencePublishes(l Lease) error {
- if l.Protocol >= wire.ProtocolPublish {
+ if l.Protocol >= wire.ProtocolPlaces {
return nil
}
var held []stepRecord
@@ -592,11 +798,10 @@ func (t *txn) siteView(k taskRecord, steps []stepRecord) (*wire.TaskSite, error)
if err != nil {
return nil, err
}
- var pr projectRecord
- if err := t.db.Where("id = ?", k.ProjectID).First(&pr).Error; err != nil {
- return nil, err
+ v := &wire.TaskSite{SHA: k.PublishAsked, State: wire.SiteAsked}
+ if snap := decodeSnapshot(c.Place); snap != nil {
+ v.App = snap.App
}
- v := &wire.TaskSite{App: storedSite(pr), SHA: k.PublishAsked, State: wire.SiteAsked}
if c.State == wire.CardAnswered && c.Choice == wire.ChoiceNotNow {
v.State = wire.SiteDeclined
}
@@ -605,13 +810,18 @@ func (t *txn) siteView(k taskRecord, steps []stepRecord) (*wire.TaskSite, error)
// previewHeld reports whether the task's devbox preview stays up after
// the task ended (forgetTask's KeepPreview): its merged website's Publish
-// is asked, on an open publish card, and no publish step was placed for
-// the merged commit yet. A publish asked again after a failed one holds
+// is asked, on an open publish card or, before it, an open place card for
+// the task, and no publish step was placed for the merged commit yet. A publish asked again after a failed one holds
// nothing: its preview went with the first answer. Only a devbox preview
// on a runner at wire.ProtocolAssistant or later is held: an older one
// never hears KeepPreview and takes its link down with the task.
func (t *txn) previewHeld(k taskRecord, steps []stepRecord) (bool, error) {
- if k.MergedSHA == "" || k.PublishAsked != k.MergedSHA {
+ // A place card for the task holds it too: the publish card follows it.
+ placing, err := t.openPlaceCardFor(k.ID)
+ if err != nil {
+ return false, err
+ }
+ if k.MergedSHA == "" || k.PublishAsked != k.MergedSHA && !placing {
return false, nil
}
runner := ""
@@ -627,6 +837,9 @@ func (t *txn) previewHeld(k taskRecord, steps []stepRecord) (bool, error) {
if err := t.db.Model(&runnerSessionRecord{}).Where("runner_id = ?", runner).Pluck("protocol", &protocol).Error; err != nil || len(protocol) == 0 || protocol[0] < wire.ProtocolAssistant {
return false, err
}
+ if placing {
+ return true, nil
+ }
return t.openPublishCard(k.ID)
}
diff --git a/internal/equipo/chat/runners.go b/internal/equipo/chat/runners.go
index 3114cd85..ac2c8289 100644
--- a/internal/equipo/chat/runners.go
+++ b/internal/equipo/chat/runners.go
@@ -596,7 +596,7 @@ func (t *txn) withdraw(k *taskRecord, s *stepRecord) error {
// an automatic merge on a connection below wire.ProtocolMergeFacts is
// refused, and purpose merge_request decides the merge again, right before
// the hub request, on every call.
-func (s *Store) Authorize(ctx context.Context, l Lease, stepID string, attempt int64, purpose, digest string) (refused string, err error) {
+func (s *Store) Authorize(ctx context.Context, l Lease, stepID string, attempt int64, purpose, digest, destination string) (refused string, err error) {
err = s.tx(ctx, func(t *txn) error {
if _, err := t.current(l); err != nil {
return err
@@ -643,12 +643,12 @@ func (s *Store) Authorize(ctx context.Context, l Lease, stepID string, attempt i
return nil
}
if st.Specialist == wire.SpecialistPublish {
- r, err := t.authorizePublish(l, &st, purpose, digest)
+ r, err := t.authorizePublish(l, &st, purpose, digest, destination)
if err != nil || r != "" {
refused = r
return err
}
- } else if purpose == wire.LeasePurposePublish {
+ } else if purpose == wire.LeasePurposePublish || purpose == wire.LeasePurposeMint {
refused = "withdrawn"
return nil
}
diff --git a/internal/equipo/chat/stream.go b/internal/equipo/chat/stream.go
index 9765e472..6deddbc1 100644
--- a/internal/equipo/chat/stream.go
+++ b/internal/equipo/chat/stream.go
@@ -192,7 +192,7 @@ func (rc *runnerConn) read(ctx context.Context) websocket.StatusCode {
case v.StepID != "" && v.Publication != "":
refused, err = store.AuthorizePublication(ctx, rc.lease, v.StepID, v.Attempt, v.Publication)
case v.StepID != "":
- refused, err = store.Authorize(ctx, rc.lease, v.StepID, v.Attempt, v.Purpose, v.Digest)
+ refused, err = store.Authorize(ctx, rc.lease, v.StepID, v.Attempt, v.Purpose, v.Digest, v.Destination)
default:
err = store.Confirm(ctx, rc.lease)
}
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go
index 8f907e6f..768d9858 100644
--- a/internal/equipo/chat/tasks.go
+++ b/internal/equipo/chat/tasks.go
@@ -1125,10 +1125,20 @@ func (t *txn) dispatchStep(k *taskRecord, s *stepRecord) error {
cmd.CandidateSHA = s.CandidateSHA
}
if s.Specialist == wire.SpecialistPublish {
- // The app derived from the project, and the branch the merged
- // commit went into (protocol 15; Encode refuses it below).
- if p := decodePublish(s.Publish); p != nil {
- cmd.Publish = &wire.PublishDispatch{App: p.App, Into: k.MergedInto}
+ // The confirmed place the creator's tap was bound to, its app and
+ // mode, and the branch the merged commit went into (protocol 31;
+ // Encode refuses it below). A step whose place, binding or reach
+ // moved since is sent with no target: the runner refuses it and
+ // its start check withdraws it.
+ snap := stepSnapshot(s.Publish)
+ if snap != nil {
+ refused, err := t.sitePhase(*k, s, *snap, "", s.RunnerID)
+ if err != nil {
+ return err
+ }
+ if refused == "" {
+ cmd.Publish = &wire.PublishDispatch{App: snap.App, Into: k.MergedInto, Console: snap.Console, Account: snap.Sqid, AccountName: snap.Name, Place: snap.Place, PlaceRevision: snap.PlaceRevision, BindingRevision: snap.BindingRevision, Destination: snap.Destination, Mode: snap.Mode, DeployName: snap.DeployName}
+ }
}
}
if s.Specialist == wire.SpecialistReview {
diff --git a/internal/equipo/chat/tools.go b/internal/equipo/chat/tools.go
index ac78940b..1f585ea6 100644
--- a/internal/equipo/chat/tools.go
+++ b/internal/equipo/chat/tools.go
@@ -323,6 +323,10 @@ func (t *txn) mutationOp(person string, v *wire.ToolCall) (string, error) {
return kind + ":" + strings.TrimSpace(a.Task), nil
case "task_retry":
return kind + ":" + strings.TrimSpace(a.Task) + ":" + strings.TrimSpace(a.Step), nil
+ case "place_proposal":
+ return kind + ":" + strings.ToLower(strings.TrimSpace(a.Project)), nil
+ case "site_offer":
+ return kind + ":" + strings.TrimSpace(a.Task), nil
}
return "", nil
}
@@ -449,7 +453,7 @@ func (t *txn) sameProject(projectID, repo string) bool {
// turn retries a task's step kind and offers a task's merge at most once.
func onceInAttempt(op string) bool {
kind, _, _ := strings.Cut(op, ":")
- return kind == "ask" || kind == "home" || kind == "finding" || kind == "star" || kind == "task_retry" || kind == "retry_offer"
+ return kind == "ask" || kind == "home" || kind == "finding" || kind == "star" || kind == "task_retry" || kind == "retry_offer" || kind == "place_proposal" || kind == "site_offer"
}
// madeTask is the task a record_task call recorded (or replayed).
@@ -483,6 +487,9 @@ var madeCodes = map[string][]string{
wire.ToolOfferRetry: {"offered"},
// A refused retry started nothing.
wire.ToolRetryStep: {"retrying"},
+ // A refused proposal or offer raised no card.
+ wire.ToolProposePlace: {"proposed"},
+ wire.ToolPublishSite: {"offered", "proposed"},
}
func mutated(tool, code string) bool {
@@ -658,6 +665,14 @@ func (t *txn) runTool(l Lease, v *wire.ToolCall) (wire.ToolResult, error) {
return t.toolResearch(l, r, v)
case wire.ToolAskPerson:
return t.askTool(r, v)
+ case wire.ToolPlaces:
+ return t.placesTool(r, v)
+ case wire.ToolProposePlace:
+ return t.proposePlaceTool(r, v)
+ case wire.ToolPublishSite:
+ return t.publishSiteTool(r, v)
+ case wire.ToolSiteStatus:
+ return t.siteStatusTool(r, v)
}
return refused("unknown_tool", toolUnknown), nil
}
diff --git a/internal/equipo/chat_page.go b/internal/equipo/chat_page.go
index c8a3b8fe..69a7e431 100644
--- a/internal/equipo/chat_page.go
+++ b/internal/equipo/chat_page.go
@@ -110,8 +110,14 @@ type chatCard struct {
Job string
// Task is a task card's task.
Task *taskLine
+ // PlaceChoices are a place card's candidates in the card's order, each
+ // labelled from code-derived console and account words.
+ PlaceChoices []placeChoice
}
+// placeChoice is one button of a place card.
+type placeChoice struct{ ID, Label string }
+
// notebookLine is one notebook entry on the Notebook page: the note, its
// source and day, and whether it quotes the person.
type notebookLine struct {
@@ -209,8 +215,25 @@ func cardView(c wire.Card, choices []string, tasks map[string]wire.Task) chatCar
case wire.CardPublish:
// Publishing a merged website: Publish or Not now, then the site.
v.Line, v.Open = c.Question, c.State == wire.CardOpen
- if c.State == wire.CardAnswered {
+ switch c.State {
+ case wire.CardAnswered:
v.Note = copyText("chat.card.publish_chose_" + c.Choice)
+ case wire.CardResolved:
+ v.Note = copyText("chat.card.publish_stale")
+ }
+ case wire.CardPlace:
+ // Where a project's site goes: one button per candidate, Not now.
+ v.Line, v.Open = c.Question, c.State == wire.CardOpen
+ if c.Place != nil {
+ for _, cand := range c.Place.Candidates {
+ v.PlaceChoices = append(v.PlaceChoices, placeChoice{ID: cand.ID, Label: fmt.Sprintf(copyText("chat.card.place_option"), cand.ConsoleLabel, cand.Account)})
+ }
+ }
+ if c.State == wire.CardAnswered {
+ v.Note = copyText("chat.card.place_chose_not_now")
+ if c.Choice != wire.ChoiceNotNow {
+ v.Note = copyText("chat.card.place_chose")
+ }
}
case wire.CardDirection:
v.Line, v.Open = c.Question, c.State == wire.CardOpen
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index 70c8347e..6be4666b 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -2356,6 +2356,48 @@ var pageCopy = map[string]string{
"work.reason.publish_config": "this version cannot use release/preview.json", // COPY APPROVED (Paul, 2026-11-12, copy-review jadya3tfrmkf7t3ym2nqhpgira, unchanged)
"work.reason.publish_too_large": "the site exceeds 2,000 files, 10 MiB per file or 50 MiB in total", // COPY APPROVED (Paul, 2026-11-12, copy-review jadya3tfrmkf7t3ym2nqhpgira, unchanged)
"work.reason.publish_failed": "the Carloku deploy failed", // COPY APPROVED (Paul, 2026-11-12, copy-review jadya3tfrmkf7t3ym2nqhpgira, unchanged)
+ // Places (spec 2026-11-26-places-config.md, slice 1): drafts for Paul's review.
+ "chat.card.place_question": "Publish %s on %s, in account %s?", // COPY REVIEW PENDING
+ "chat.card.place_option": "%s, account %s", // COPY REVIEW PENDING
+ "chat.card.place_chose": "Saved. Nothing goes live until you tap Publish.", // COPY REVIEW PENDING
+ "chat.card.place_chose_not_now": "Not saved.", // COPY REVIEW PENDING
+ "chat.card.publish_place_question": "Publish %s to %s on %s, account %s?", // COPY REVIEW PENDING
+ "chat.card.publish_setup_note": "This first publish creates the app and a deploy key for it, using your CARLOS login on your runner.", // COPY REVIEW PENDING
+ "chat.card.publish_mint_note": "This makes a new deploy key for the site with your CARLOS login on your runner, then publishes with it.", // COPY REVIEW PENDING
+ "chat.card.publish_stale": "Where this site goes changed, so I asked again.", // COPY REVIEW PENDING
+ "chat.publish_blocked": "[%s](%s) is merged, but I can’t publish it yet: %s.", // COPY REVIEW PENDING
+ "chat.publish_unproven": "Could not publish [%s](%s): an app called %s is already in that account and Equipo has no record of making it, so I left it alone.", // COPY REVIEW PENDING
+ "places.missing.no_place": "no place is chosen for its site", // COPY REVIEW PENDING
+ "places.missing.no_runner": "you have no runner to publish from", // COPY REVIEW PENDING
+ "places.missing.runner_outdated": "your runner needs an Equipo update first", // COPY REVIEW PENDING
+ "places.missing.carlos_outdated": "the CARLOS command line tool on your runner is missing or older than v0.43.0", // COPY REVIEW PENDING
+ "places.missing.no_login": "your runner is not signed in to CARLOS with an account you own", // COPY REVIEW PENDING
+ "places.missing.no_deploy": "your runner has no deploy key for the site and no CARLOS login to make one", // COPY REVIEW PENDING
+ "places.missing.not_owner": "only a team owner can publish a site", // COPY REVIEW PENDING
+ "work.reason.carlos_outdated": "the CARLOS command line tool on the runner is missing or older than v0.43.0", // COPY REVIEW PENDING
+ "work.reason.publish_secrets": "the site was not published because its secret scan found something that looks like a secret", // COPY REVIEW PENDING
+ "work.reason.publish_scanner": "the site was not published because its secret scan could not be completed", // COPY REVIEW PENDING
+ "work.reason.publish_key_missing": "the runner no longer holds the site’s deploy key", // COPY REVIEW PENDING
+ "work.reason.publish_mint_failed": "the site’s deploy key could not be made", // COPY REVIEW PENDING
+ "work.reason.publish_app_missing": "the app this site’s first publish should have made is not there", // COPY REVIEW PENDING
+ "work.reason.publish_app_unproven": "an app with this name is in the account, but Equipo has no record of making it", // COPY REVIEW PENDING
+ "chat.activity.places": "Checking where sites go…", // COPY REVIEW PENDING
+ "chat.activity.propose_place": "Asking where the site goes…", // COPY REVIEW PENDING
+ "chat.activity.publish_site": "Offering to publish the site…", // COPY REVIEW PENDING
+ "chat.activity.site_status": "Checking the site…", // COPY REVIEW PENDING
+ "settings.places": "Places", // COPY REVIEW PENDING
+ "settings.places_about": "Where your team’s sites go.", // COPY REVIEW PENDING
+ "places.title": "Places", // COPY REVIEW PENDING
+ "places.empty": "No places yet. When a merged website needs one, Equipo asks you where it goes.", // COPY REVIEW PENDING
+ "places.site_line": "%s: %s on %s, account %s.", // COPY REVIEW PENDING
+ "places.site_live": "Live at %s, published %s.", // COPY REVIEW PENDING
+ "places.site_unconfirmed": "The last publish, %s, could not be confirmed.", // COPY REVIEW PENDING
+ "places.site_not_yet": "Not published yet.", // COPY REVIEW PENDING
+ "places.unplaced": "%s: app %s, no place chosen yet.", // COPY REVIEW PENDING
+ "places.pending": "%s: waiting for you to choose where its site goes.", // COPY REVIEW PENDING
+ "places.deploy_held": "Its deploy key is %s.", // COPY REVIEW PENDING
+ "places.deploy_lost": "A deploy key named %s may still be live on CARLOS without Equipo holding it. You can revoke it in the CARLOS console.", // COPY REVIEW PENDING
+ "places.deploy_none": "No deploy key yet: the first publish makes one.", // COPY REVIEW PENDING
// Paused work (spec 2026-11-24-paused-work-design.md), Luna's review.
"work.stage.paused": "Paused", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-24)
diff --git a/internal/equipo/migrations/0108_places.sql b/internal/equipo/migrations/0108_places.sql
new file mode 100644
index 00000000..05f4fcee
--- /dev/null
+++ b/internal/equipo/migrations/0108_places.sql
@@ -0,0 +1,14 @@
+-- Places (spec 2026-11-26-places-config.md, slice 1, protocol 31): the
+-- team's confirmed destinations and each project's binding to one. Team
+-- records, the same for every member. A binding holds the site's app and
+-- the metadata of the deploy key its runner holds, never the secret.
+CREATE TABLE chat_places (id text PRIMARY KEY, kind text, adapter text, console text, account_sqid text, account_name text, state text, revision integer, proposed_by text, proposed_at datetime, confirmed_by text, confirmed_at datetime, created_at datetime, updated_at datetime);
+CREATE UNIQUE INDEX chat_place_destination ON chat_places(kind, adapter, console, account_sqid);
+CREATE TABLE chat_project_places (id text PRIMARY KEY, project_id text, kind text, place_id text, app text, revision integer, app_created_at datetime, app_created_step text, deploy_name text, deploy_runner text, deploy_minted_by text, deploy_minted_at datetime, deploy_step text, created_at datetime, updated_at datetime);
+CREATE UNIQUE INDEX chat_project_place_kind ON chat_project_places(project_id, kind);
+-- Every project's minted app is kept as its site binding's app, with no
+-- place: an unplaced binding confirms nothing and created nothing.
+INSERT INTO chat_project_places (id, project_id, kind, place_id, app, revision, created_at, updated_at) SELECT 'pp_' || id, id, 'site', '', site_app, 1, created_at, updated_at FROM chat_projects WHERE site_app IS NOT NULL AND site_app != '';
+-- A place card's proposal (wire.CardPlaceView JSON with each candidate's
+-- hash); '' on every other card.
+ALTER TABLE chat_cards ADD COLUMN place text;
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index b766173e..24fb10bc 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -777,3 +777,8 @@ ALTER TABLE chat_cards ADD COLUMN carry_on numeric;
ALTER TABLE chat_cards ADD COLUMN carry_on_connection text;
ALTER TABLE chat_releases ADD COLUMN connection text;
ALTER TABLE chat_steps ADD COLUMN coordinator_attempt integer;
+CREATE TABLE chat_places (id text PRIMARY KEY, kind text, adapter text, console text, account_sqid text, account_name text, state text, revision integer, proposed_by text, proposed_at datetime, confirmed_by text, confirmed_at datetime, created_at datetime, updated_at datetime);
+CREATE UNIQUE INDEX chat_place_destination ON chat_places(kind, adapter, console, account_sqid);
+CREATE TABLE chat_project_places (id text PRIMARY KEY, project_id text, kind text, place_id text, app text, revision integer, app_created_at datetime, app_created_step text, deploy_name text, deploy_runner text, deploy_minted_by text, deploy_minted_at datetime, deploy_step text, created_at datetime, updated_at datetime);
+CREATE UNIQUE INDEX chat_project_place_kind ON chat_project_places(project_id, kind);
+ALTER TABLE chat_cards ADD COLUMN place text;
diff --git a/internal/equipo/places_migration_test.go b/internal/equipo/places_migration_test.go
new file mode 100644
index 00000000..b89513a9
--- /dev/null
+++ b/internal/equipo/places_migration_test.go
@@ -0,0 +1,59 @@
+package equipo
+
+import (
+ "context"
+ "testing"
+
+ "amadan.net/rastrillo/rastrillo/migrate"
+)
+
+// Migration 0108 keeps every project's minted site app as its site
+// binding's app, with no place, created nothing and no key: a project
+// without an app gets no binding.
+func TestPlacesMigrationCopiesSiteApps(t *testing.T) {
+ ctx := context.Background()
+ var before []migrate.Migration
+ var places migrate.Migration
+ for _, m := range Schema.All() {
+ if m.ID == "equipo/0108_places" {
+ places = m
+ break
+ }
+ before = append(before, m)
+ }
+ if places.SQL == "" {
+ t.Fatal("no migration 0108")
+ }
+ d, err := migrate.Replay(ctx, before)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer d.Close()
+ if _, err := d.ExecContext(ctx, `INSERT INTO chat_projects (id, repo, state, site_app, created_at, updated_at) VALUES ('p1', 'amadan.net/paulca/old', 'active', 'site-old-abcdef', '2026-11-01', '2026-11-02'), ('p2', 'amadan.net/paulca/nearys', 'active', NULL, '2026-11-01', '2026-11-01'), ('p3', 'amadan.net/paulca/blank', 'active', '', '2026-11-01', '2026-11-01')`); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := d.ExecContext(ctx, places.SQL); err != nil {
+ t.Fatal(err)
+ }
+ rows, err := d.QueryContext(ctx, `SELECT project_id, kind, place_id, app, revision, app_created_at IS NULL, coalesce(deploy_name, '') FROM chat_project_places ORDER BY project_id`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rows.Close()
+ var got []string
+ for rows.Next() {
+ var project, kind, place, app, deploy string
+ var revision int64
+ var uncreated bool
+ if err := rows.Scan(&project, &kind, &place, &app, &revision, &uncreated, &deploy); err != nil {
+ t.Fatal(err)
+ }
+ if kind != "site" || place != "" || revision != 1 || !uncreated || deploy != "" {
+ t.Fatalf("binding %s %s %q rev %d created %t deploy %q", project, kind, place, revision, !uncreated, deploy)
+ }
+ got = append(got, project+"="+app)
+ }
+ if len(got) != 1 || got[0] != "p1=site-old-abcdef" {
+ t.Fatalf("bindings %v", got)
+ }
+}
diff --git a/internal/equipo/settings_hub.go b/internal/equipo/settings_hub.go
index f402d936..b1ef1c52 100644
--- a/internal/equipo/settings_hub.go
+++ b/internal/equipo/settings_hub.go
@@ -1,6 +1,9 @@
package equipo
import (
+ "fmt"
+
+ "amadan.net/oficina/equipo/internal/equipo/chat"
"amadan.net/oficina/equipo/internal/wire"
"net/http"
"net/url"
@@ -50,6 +53,7 @@ var settingsSections = []settingsLink{
{Key: "machines", Href: "/conversation/settings/machines", CopyKey: "runner.title", Icon: "monitor"},
{Key: "housekeeping", Href: "/conversation/settings/housekeeping", CopyKey: "settings.housekeeping", Icon: "list-checks"},
{Key: "copy", Href: "/conversation/settings/copy", CopyKey: "copy.title", Icon: "type"},
+ {Key: "places", Href: "/conversation/settings/places", CopyKey: "settings.places", Icon: "list-checks"},
{Key: "notebook", Href: "/conversation/settings/notebook", CopyKey: "settings.notebook_open", Icon: "notebook"},
{Key: "teams", Href: "/teams", CopyKey: "settings.teams_open", Icon: "users"},
}
@@ -59,9 +63,11 @@ var settingsSections = []settingsLink{
// section's own data.
type settingsHubView struct {
CopyProjects []wire.Project
- Section string
- Root bool
- Thinking thinkingView
+ // Places are the Places page's lines, state first (read-only).
+ Places []placeView
+ Section string
+ Root bool
+ Thinking thinkingView
}
// settingsPage is a page in the Settings section: the app's rail shows
@@ -128,6 +134,13 @@ func (a *application) settingsSection(w http.ResponseWriter, r *http.Request, se
return
}
data.Settings.Thinking = thinkingView{ThinkingWords: words, JSON: thinkingJSON(words.Sets)}
+ case "places":
+ places, err := a.store.Chat().Places(ctx, address)
+ if err != nil {
+ a.failure(w, r, chatError(err))
+ return
+ }
+ data.Settings.Places = placeViews(places)
case "housekeeping":
h, err := a.store.Chat().Housekeeping(ctx, address)
if err != nil {
@@ -171,3 +184,46 @@ func deref(n *int) int {
}
return *n
}
+
+// placeView is one project's lines on the Places page: what it is, then
+// where it stands, then its deploy key.
+type placeView struct{ Line, State, Deploy string }
+
+// placeViews says each site in the page's words; names come from CARLOS
+// and the repository and are escaped by the template.
+func placeViews(places []chat.SitePlace) []placeView {
+ out := make([]placeView, 0, len(places))
+ for _, p := range places {
+ var v placeView
+ switch {
+ case p.Console == "" && p.Pending:
+ v.Line = fmt.Sprintf(copyText("places.pending"), p.Project)
+ case p.Console == "":
+ v.Line = fmt.Sprintf(copyText("places.unplaced"), p.Project, p.App)
+ default:
+ v.Line = fmt.Sprintf(copyText("places.site_line"), p.Project, p.App, p.Console, p.Account)
+ when := ""
+ if p.At != nil {
+ when = p.At.UTC().Format("2 January 2006, 15:04 UTC")
+ }
+ switch {
+ case p.State == wire.PublishPublished && p.URL != "":
+ v.State = fmt.Sprintf(copyText("places.site_live"), p.URL, when)
+ case p.State == wire.PublishUnconfirmed:
+ v.State = fmt.Sprintf(copyText("places.site_unconfirmed"), when)
+ default:
+ v.State = copyText("places.site_not_yet")
+ }
+ switch p.Deploy {
+ case "held":
+ v.Deploy = fmt.Sprintf(copyText("places.deploy_held"), p.DeployName)
+ case "lost":
+ v.Deploy = fmt.Sprintf(copyText("places.deploy_lost"), p.DeployName)
+ default:
+ v.Deploy = copyText("places.deploy_none")
+ }
+ }
+ out = append(out, v)
+ }
+ return out
+}
diff --git a/internal/equipo/templates/chat.html b/internal/equipo/templates/chat.html
index 8fa928e8..38a17bb0 100644
--- a/internal/equipo/templates/chat.html
+++ b/internal/equipo/templates/chat.html
@@ -16,7 +16,7 @@
{{else if eq .Kind "specialist"}}<p equipo-card-line>{{.Line}}</p>{{with .Specialist}}{{range .Capabilities}}<p equipo-card-note data-capability="{{.ID}}">{{.Words}}</p>{{end}}<p equipo-card-note data-specialist-brief>{{printf (copy "chat.card.specialist_brief") .Brief}}</p>{{end}}{{if .Open}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}">{{template "card-job" .}}{{template "project-name-confirm" .}}{{range .Options}}<button rst-btn="{{if eq . "add"}}primary{{end}}" name="choice" value="{{.}}" type="submit" data-specialist-choice="{{.}}">{{copy (printf "chat.card.%s" .)}}</button>{{end}}</form>{{else}}{{with .Note}}<p equipo-card-note>{{.}}</p>{{end}}{{end}}
{{else if eq .Kind "research_sources"}}<p equipo-card-line>{{.Line}}</p>{{with .Name}}<p equipo-card-note data-research-task>{{printf (copy "chat.card.research_for") .}}</p>{{end}}{{with .Research}}<p equipo-card-note data-research-question>{{printf (copy "chat.card.research_looks_for") .Question}}</p><ul equipo-card-list data-research-urls>{{range .URLs}}<li><code>{{.}}</code></li>{{end}}</ul>{{end}}{{if .Open}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}">{{template "card-job" .}}{{template "project-name-confirm" .}}{{range .Options}}<button rst-btn="{{if eq . "allow"}}primary{{end}}" name="choice" value="{{.}}" type="submit" data-research-choice="{{.}}">{{copy (printf "chat.card.%s" .)}}</button>{{end}}</form>{{else}}{{with .Note}}<p equipo-card-note>{{.}}</p>{{end}}{{end}}
{{else if eq .Kind "research_inventory"}}<p equipo-card-line>{{.Line}}</p>{{with .Inventory}}<ul equipo-card-list data-research-addresses>{{range .Addresses}}<li><code>{{.}}</code></li>{{end}}</ul>{{end}}{{if .Open}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}">{{template "card-job" .}}<button rst-btn="primary" name="choice" value="confirm" type="submit" data-inventory-confirm>{{copy "chat.card.inventory_confirm"}}</button></form>{{else}}{{with .Note}}<p equipo-card-note>{{.}}</p>{{end}}{{end}}
-{{else if eq .Kind "publish"}}<p equipo-card-line>{{.Line}}</p>{{with .Site}}{{if .URL}}<p equipo-card-note><a href="{{.URL}}" rel="noopener" target="_blank" data-site-link>{{copy "chat.card.site_link"}}</a></p>{{end}}{{end}}{{if .Open}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}">{{template "card-job" .}}{{template "project-name-confirm" .}}{{range .Options}}<button rst-btn="{{if eq . "publish"}}primary{{end}}" name="choice" value="{{.}}" type="submit" data-publish-choice="{{.}}">{{copy (printf "chat.card.%s" .)}}</button>{{end}}</form>{{else}}{{with .Note}}<p equipo-card-note>{{.}}</p>{{end}}{{end}}
+{{else if eq .Kind "place"}}<p equipo-card-line>{{.Line}}</p>{{if .Open}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}">{{template "card-job" .}}{{range $i, $c := .PlaceChoices}}<button rst-btn="{{if eq $i 0}}primary{{end}}" name="choice" value="{{$c.ID}}" type="submit" data-place-choice="{{$c.ID}}">{{$c.Label}}</button>{{end}}<button rst-btn name="choice" value="not_now" type="submit" data-place-choice="not_now">{{copy "chat.card.not_now"}}</button></form>{{else}}{{with .Note}}<p equipo-card-note>{{.}}</p>{{end}}{{end}}{{else if eq .Kind "publish"}}<p equipo-card-line>{{.Line}}</p>{{with .Site}}{{if .URL}}<p equipo-card-note><a href="{{.URL}}" rel="noopener" target="_blank" data-site-link>{{copy "chat.card.site_link"}}</a></p>{{end}}{{end}}{{if .Open}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}">{{template "card-job" .}}{{template "project-name-confirm" .}}{{range .Options}}<button rst-btn="{{if eq . "publish"}}primary{{end}}" name="choice" value="{{.}}" type="submit" data-publish-choice="{{.}}">{{copy (printf "chat.card.%s" .)}}</button>{{end}}</form>{{else}}{{with .Note}}<p equipo-card-note>{{.}}</p>{{end}}{{end}}
{{else if eq .Kind "merge"}}<p equipo-card-line>{{.Line}}</p>{{with .PreviewURL}}<p equipo-card-note><a href="{{.}}" rel="noopener" target="_blank" data-preview-link>{{copy "chat.card.preview_link"}}</a></p>{{end}}{{if .Open}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}">{{template "card-job" .}}{{template "project-name-confirm" .}}{{range .Options}}<button rst-btn="{{if eq . "merge"}}primary{{end}}" name="choice" value="{{.}}" type="submit" data-merge-choice="{{.}}">{{copy (printf "chat.card.%s" .)}}</button>{{end}}</form>{{else}}{{with .Note}}<p equipo-card-note>{{.}}</p>{{end}}{{end}}
{{else if or (eq .Kind "merge_ships") (eq .Kind "merge_policy") (eq .Kind "merge_receipt")}}{{if eq .Kind "merge_receipt"}}<div equipo-card-line equipo-markdown data-merge-receipt>{{chatMarkdown .Line}}</div>{{else}}<p equipo-card-line>{{.Line}}</p>{{end}}{{if .Open}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}">{{template "card-job" .}}{{template "project-name-confirm" .}}{{range .Options}}<button rst-btn="{{if or (eq . "save") (eq . "not_ships")}}primary{{end}}" name="choice" value="{{.}}" type="submit" data-merge-choice="{{.}}">{{copy (printf "chat.card.%s" .)}}</button>{{end}}</form>{{else}}{{with .Note}}<p equipo-card-note>{{.}}</p>{{end}}{{end}}
{{else if .Access}}{{template "access-card" .}}
diff --git a/internal/equipo/templates/settings_hub.html b/internal/equipo/templates/settings_hub.html
index 5c9a2a92..b6b1913b 100644
--- a/internal/equipo/templates/settings_hub.html
+++ b/internal/equipo/templates/settings_hub.html
@@ -26,6 +26,8 @@
<label for="copy-tooling">{{copy "copy.tooling"}}</label><input rst-input id="copy-tooling" name="tooling" pattern="[a-f0-9]{40}" required>
<label for="copy-references">{{copy "copy.references"}}</label><textarea rst-input id="copy-references" name="references" maxlength="4000"></textarea>
<button rst-btn type="submit">{{copy "copy.recover"}}</button></form></details>
+{{else if eq .Settings.Section "places"}}{{template "settings-head" (dict "Title" "places.title" "Lede" "settings.places_about")}}
+{{with .Settings.Places}}<ul equipo-places>{{range .}}<li equipo-place><p equipo-place-line>{{.Line}}</p>{{with .State}}<p equipo-place-state>{{.}}</p>{{end}}{{with .Deploy}}<p equipo-place-deploy>{{.}}</p>{{end}}</li>{{end}}</ul>{{else}}<p equipo-places-empty>{{copy "places.empty"}}</p>{{end}}
{{else if eq .Settings.Section "housekeeping"}}{{template "settings-head" (dict "Title" "settings.housekeeping" "Lede" "housekeeping.settings.lede")}}
{{with .HousekeepingSettings}}{{template "housekeeping-settings" .}}{{end}}
{{end}}
diff --git a/internal/thintest/assistant_job_contract_test.go b/internal/thintest/assistant_job_contract_test.go
index 0d023bda..00f15ac7 100644
--- a/internal/thintest/assistant_job_contract_test.go
+++ b/internal/thintest/assistant_job_contract_test.go
@@ -455,11 +455,11 @@ func (o *teamRig) jobThroughStates() (request, id, cancelled string) {
t.Fatalf("start refused %q", refused)
}
o.publishReport("jt-built", d, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40})
- if refused := o.lease(o.runner, "jt-deploy", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA}); refused != "" {
+ if refused := o.lease(o.runner, "jt-deploy", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA, Destination: d.Publish.Destination}); refused != "" {
t.Fatalf("deploy refused %q", refused)
}
site := "https://" + d.Publish.App + ".bds.oncarlos.com/"
- o.publishReport("jt-published", d, wire.StepDone, &wire.PublishResult{Phase: wire.PublishDone, App: d.Publish.App, URL: site, Version: "s-eeeeeeeeeeee-x-1", Digest: digestA, Outcome: wire.PublishPublished})
+ o.publishReport("jt-published", d, wire.StepDone, &wire.PublishResult{Phase: wire.PublishDone, App: d.Publish.App, URL: site, Version: "s-eeeeeeeeeeee-x-1", Digest: digestA, Outcome: wire.PublishPublished, DeployHeld: true})
done := o.jobOf(request, "done", func(c wire.AssistantCard) bool { return c.State == wire.JobDone })
status, detail = jobWords(wire.JobDone)
if done.Result != status || done.Detail != detail || !slices.Equal(done.Links, []wire.CardLink{{Label: equipo.RunnerCopy("assistant.outcome.publish_site"), URL: site}, o.equipoLink(request)}) {
diff --git a/internal/thintest/assistant_outcome_contract_test.go b/internal/thintest/assistant_outcome_contract_test.go
index a4aae998..29d1aaff 100644
--- a/internal/thintest/assistant_outcome_contract_test.go
+++ b/internal/thintest/assistant_outcome_contract_test.go
@@ -738,11 +738,11 @@ func TestContractAssistantLaneLeaksNoMachinery(t *testing.T) {
t.Fatalf("start refused %q", refused)
}
o.publishReport("ol-built", d, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40})
- if refused := o.lease(o.runner, "ol-deploy", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA}); refused != "" {
+ if refused := o.lease(o.runner, "ol-deploy", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA, Destination: d.Publish.Destination}); refused != "" {
t.Fatalf("deploy refused %q", refused)
}
site := "https://" + d.Publish.App + ".bds.oncarlos.com/"
- o.publishReport("ol-published", d, wire.StepDone, &wire.PublishResult{Phase: wire.PublishDone, App: d.Publish.App, URL: site, Version: "s-eeeeeeeeeeee-x-1", Digest: digestA, Outcome: wire.PublishPublished})
+ o.publishReport("ol-published", d, wire.StepDone, &wire.PublishResult{Phase: wire.PublishDone, App: d.Publish.App, URL: site, Version: "s-eeeeeeeeeeee-x-1", Digest: digestA, Outcome: wire.PublishPublished, DeployHeld: true})
o.assistantCard("published", func(c wire.AssistantCard) bool {
return isPublishOutcome(c) && len(c.Links) == 1 && c.Links[0].URL == site
})
@@ -1069,11 +1069,11 @@ func TestContractOutcomePublish(t *testing.T) {
if ids, after, _ := o.updates(); !slices.Equal(ids, told) || !slices.Equal(after, notes) {
t.Fatalf("updates while publishing %v %q, before %v %q", ids, after, told, notes)
}
- if refused := o.lease(o.runner, "op-deploy", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA}); refused != "" {
+ if refused := o.lease(o.runner, "op-deploy", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA, Destination: d.Publish.Destination}); refused != "" {
t.Fatalf("deploy refused %q", refused)
}
site := "https://" + k.Site.App + ".bds.oncarlos.com/"
- o.publishReport("op-published", d, wire.StepDone, &wire.PublishResult{Phase: wire.PublishDone, App: k.Site.App, URL: site, Version: "s-eeeeeeeeeeee-x-1", Digest: digestA, Outcome: wire.PublishPublished})
+ o.publishReport("op-published", d, wire.StepDone, &wire.PublishResult{Phase: wire.PublishDone, App: k.Site.App, URL: site, Version: "s-eeeeeeeeeeee-x-1", Digest: digestA, Outcome: wire.PublishPublished, DeployHeld: true})
done := o.assistantCard("published", func(c wire.AssistantCard) bool {
return c.ID == card.ID && c.Result == equipo.RunnerCopy("assistant.outcome.publish_published")
})
@@ -1245,7 +1245,8 @@ func TestContractPublishNeedsOwnerAnswer(t *testing.T) {
// cannot keep a preview past its task (Encode drops KeepPreview, and it
// takes the link down), so a merged website it previewed holds nothing:
// the forget_task asks for no retention and no card shows the link once
-// the task is done, though Publish is asked.
+// the task is done. Publish is not asked of it (places need protocol 31):
+// the task says why instead.
func TestContractPreviewNotHeldBelow19(t *testing.T) {
r := newToolRigAt(t, wire.ProtocolAssistant-1)
r.sitesOn(wire.ProtocolAssistant-1, true)
@@ -1255,8 +1256,8 @@ func TestContractPreviewNotHeldBelow19(t *testing.T) {
t.Fatal("old runner received a preview without injection defences")
}
r.mergeFromCard("p18-m", id, base, cand, strings.Repeat("e", 40))
- if _, ok := r.publishCard(id); !ok {
- t.Fatal("Publish not asked")
+ if _, ok := r.publishCard(id); ok || r.audits("publish.not_offered") != 1 {
+ t.Fatal("Publish asked of a protocol 18 runner, or not said why")
}
if n := r.rows("SELECT count(*) FROM runner_commands WHERE kind = ? AND body LIKE ?", wire.FrameForgetTask, `%"keep_preview":true%`); n != 0 {
t.Fatalf("%d forget_task commands keep the preview on a protocol 18 runner", n)
diff --git a/internal/thintest/assistant_team_contract_test.go b/internal/thintest/assistant_team_contract_test.go
index 1a6dffcf..441ad13f 100644
--- a/internal/thintest/assistant_team_contract_test.go
+++ b/internal/thintest/assistant_team_contract_test.go
@@ -588,7 +588,7 @@ func TestContractTeamStatus(t *testing.T) {
d := o.publishDispatch()
o.publishReport("s-built", d, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40})
site := "https://" + d.Publish.App + ".bds.oncarlos.com/"
- o.publishReport("s-done", d, wire.StepDone, &wire.PublishResult{Phase: wire.PublishDone, App: d.Publish.App, URL: site, Digest: digestA, Outcome: wire.PublishPublished})
+ o.publishReport("s-done", d, wire.StepDone, &wire.PublishResult{Phase: wire.PublishDone, App: d.Publish.App, URL: site, Digest: digestA, Outcome: wire.PublishPublished, DeployHeld: true})
live := one("live")
if !strings.Contains(live, equipo.RunnerCopy("assistant.team.stage.done")) || !strings.Contains(live, strings.ReplaceAll(equipo.RunnerCopy("assistant.team.published"), "%s", site)) || strings.Contains(live, link) {
t.Fatalf("published %q", live)
@@ -1966,11 +1966,11 @@ func TestContractOutcomePublishInThread(t *testing.T) {
t.Fatalf("start refused %q", refused)
}
o.publishReport("pt-built", d, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40})
- if refused := o.lease(o.runner, "pt-deploy", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA}); refused != "" {
+ if refused := o.lease(o.runner, "pt-deploy", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA, Destination: d.Publish.Destination}); refused != "" {
t.Fatalf("deploy refused %q", refused)
}
site := "https://" + d.Publish.App + ".bds.oncarlos.com/"
- o.publishReport("pt-published", d, wire.StepDone, &wire.PublishResult{Phase: wire.PublishDone, App: d.Publish.App, URL: site, Version: "s-eeeeeeeeeeee-x-1", Digest: digestA, Outcome: wire.PublishPublished})
+ o.publishReport("pt-published", d, wire.StepDone, &wire.PublishResult{Phase: wire.PublishDone, App: d.Publish.App, URL: site, Version: "s-eeeeeeeeeeee-x-1", Digest: digestA, Outcome: wire.PublishPublished, DeployHeld: true})
var said, lane string
o.until("the publish result", func() bool {
return o.inst.DB.Writer().QueryRow("SELECT id, coalesce(lane, '') FROM chat_messages WHERE idempotency_key = ?", "publish:"+d.StepID+":"+itoa(int(d.Attempt))).Scan(&said, &lane) == nil
diff --git a/internal/thintest/merge_contract_test.go b/internal/thintest/merge_contract_test.go
index e451cb87..278ef64e 100644
--- a/internal/thintest/merge_contract_test.go
+++ b/internal/thintest/merge_contract_test.go
@@ -8,6 +8,7 @@ import (
"slices"
"strings"
"testing"
+ "time"
"amadan.net/oficina/equipo/internal/equipo"
"amadan.net/oficina/equipo/internal/wire"
@@ -36,6 +37,37 @@ func (r *toolRig) mergedStep(key string, d *wire.DispatchCommand, sha string) {
r.t.Helper()
r.step(key+"-run", wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning, BaseSHA: d.BaseSHA, CandidateSHA: d.CandidateSHA})
r.step(key, wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepDone, BaseSHA: d.BaseSHA, CandidateSHA: d.CandidateSHA, Termination: true, Findings: []wire.Finding{}, MergeSHA: sha, Into: "main", Strategy: wire.MergeCommit})
+ if r.placeOnMerge {
+ r.confirmPlace(d.TaskID)
+ }
+}
+
+// confirmPlace answers the task's place card, if the merge raised one
+// (in whatever lane), with its best candidate (sitesOn's Carloku
+// account).
+func (r *toolRig) confirmPlace(task string) {
+ r.t.Helper()
+ deadline := time.Now().Add(2 * time.Second)
+ for time.Now().Before(deadline) {
+ var id, options string
+ var revision int64
+ err := r.inst.DB.Writer().QueryRow("SELECT id, options, revision FROM chat_cards WHERE kind = ? AND task_id = ? AND state = ?", wire.CardPlace, task, wire.CardOpen).Scan(&id, &options, &revision)
+ if err == nil {
+ var opts []string
+ if json.Unmarshal([]byte(options), &opts) != nil || len(opts) == 0 {
+ r.t.Fatalf("place card options %s", options)
+ }
+ if _, err := r.client.Answer(r.ctx, id, opts[0], revision); err != nil {
+ r.t.Fatalf("place card: %v", err)
+ }
+ return
+ }
+ var n int
+ if r.inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_cards WHERE kind = ? AND task_id = ?", wire.CardPublish, task).Scan(&n) == nil && n > 0 {
+ return
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
}
// replies are the coordinator's messages so far, as text.
diff --git a/internal/thintest/places_contract_test.go b/internal/thintest/places_contract_test.go
new file mode 100644
index 00000000..20b811d7
--- /dev/null
+++ b/internal/thintest/places_contract_test.go
@@ -0,0 +1,369 @@
+package thintest
+
+import (
+ "encoding/json"
+ "net/http"
+ "regexp"
+ "slices"
+ "strconv"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// reachHello says hello again as a primary at protocol 31 with a current
+// carlos signed in to Carloku (accounts oficina and paulca) and Tito
+// (account tito), holding deploys.
+func (r *toolRig) reachHello(key string, deploys []wire.ReachDeploy) {
+ r.t.Helper()
+ hello := primaryAt(toolHello(r.runner.Welcome.Generation), wire.ProtocolCurrent)
+ hello.Capabilities.Previews, hello.Capabilities.PreviewHost = true, &wire.PreviewHost{Kind: wire.PreviewHostDevbox, Domain: "docs-t1.example.ts.net"}
+ hello.Capabilities.Tools = &wire.ToolHealth{Scanner: wire.ToolHealthy, Carlos: wire.CarlosOK, CarlosVersion: "v0.43.3"}
+ hello.Capabilities.Reach = &wire.Reach{Logins: []wire.ReachLogin{
+ {Console: wire.FlagshipConsole, Accounts: []wire.ReachAccount{{Name: "oficina", Sqid: "bcdfg"}, {Name: "paulca", Sqid: "kmnpq"}}},
+ {Console: wire.TitoConsole, Accounts: []wire.ReachAccount{{Name: "tito", Sqid: "rstuv"}}},
+ }, Deploys: deploys}
+ if err := r.runner.Send(r.ctx, "h-reach-"+key, wire.FrameHello, hello); err != nil {
+ r.t.Fatal(err)
+ }
+ if refused := r.lease(r.runner, "h-reach-ping-"+key, wire.LeaseCheck{}); refused != "" {
+ r.t.Fatalf("ping refused %q", refused)
+ }
+}
+
+// placesData is the quoted data a places tool answered.
+func placesData(t *testing.T, res wire.ToolResult) map[string]any {
+ t.Helper()
+ _, quoted, ok := strings.Cut(res.Text, "): ")
+ raw, err := strconv.Unquote(quoted)
+ var out map[string]any
+ if !ok || err != nil || json.Unmarshal([]byte(raw), &out) != nil {
+ t.Fatalf("places data %q", res.Text)
+ }
+ return out
+}
+
+func (r *toolRig) cardKind(kind, task string) (wire.Card, bool) {
+ r.t.Helper()
+ snap, err := r.client.Snapshot(r.ctx)
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ var out wire.Card
+ found := false
+ for _, c := range snap.Cards {
+ if c.Kind == kind && c.TaskID == task {
+ out, found = c, true
+ }
+ }
+ return out, found
+}
+
+// TestContractPlacesFinishLine is slice 1's finish line (places spec §7):
+// a website merged while the runner could not publish is not offered and
+// says why. Once the runner's carlos can, the coordinator's publish_site
+// raises a place card whose candidates come only from the runner's reach
+// (the tool takes a candidate id, never a console or account); only the
+// owner's own tap confirms one, and confirming publishes nothing. The
+// publish card names the app and the place and says the first publish
+// creates the app and its deploy key with the owner's login; a card whose
+// place moved before the tap is settled and asked again. Publish places a
+// setup step bound to the place, carried in the dispatch; its deploy and
+// mint checks are bound to the destination; the task then shows the
+// confirmed address. The next merged website publishes with the held key,
+// and a binding that moved after the tap withdraws it.
+func TestContractPlacesFinishLine(t *testing.T) {
+ r := newToolRigAt(t, wire.ProtocolCurrent)
+ ctx := r.ctx
+ // Merged while the runner says nothing of its carlos: not offered, and
+ // the task's lane says why.
+ r.sitesOn(wire.ProtocolCurrent, false)
+ base, cand, merged := strings.Repeat("1", 40), strings.Repeat("2", 40), strings.Repeat("e", 40)
+ id, _ := r.websiteReady("f", "Quick website", base, cand, true)
+ r.previewDispatch(cand)
+ r.mergeFromCard("f-m", id, base, cand, merged)
+ want := "[Quick website](/tasks/" + id + ") is merged, but I can’t publish it yet: the CARLOS command line tool on your runner is missing or older than v0.43.0."
+ r.wait("why it was not offered", func(c *Conversation) bool {
+ for _, m := range c.Replies() {
+ if m.Text == want {
+ return true
+ }
+ }
+ return false
+ })
+ if _, ok := r.cardKind(wire.CardPublish, id); ok {
+ t.Fatal("offered on a runner that cannot publish")
+ }
+ if r.audits("publish.not_offered") != 1 {
+ t.Fatal("not offered, not audited")
+ }
+
+ // The runner's carlos is current and signed in now.
+ r.reachHello("1", []wire.ReachDeploy{})
+ res := r.call("p1", wire.ToolPlaces, map[string]string{"project": "sample"})
+ if res.IsError || res.Code != "places" {
+ t.Fatalf("places %+v", res)
+ }
+ data := placesData(t, res)
+ sites := data["sites"].([]any)
+ line := sites[0].(map[string]any)
+ cands := line["candidates"].([]any)
+ if line["missing"] != "no_place" || len(cands) != 3 {
+ t.Fatalf("places %v", line)
+ }
+ first, paulca := cands[0].(map[string]any), cands[1].(map[string]any)
+ if first["account"] != "oficina" || first["console_label"] != "Carloku" || paulca["account"] != "paulca" || cands[2].(map[string]any)["console_label"] != "Tito" {
+ t.Fatalf("candidates %v", cands)
+ }
+ // A tool can name only a candidate id: not a console, an account or
+ // an app, and not an id the reach does not hold.
+ if res := r.call("p2", wire.ToolProposePlace, map[string]any{"kind": "site", "project": "sample", "candidate": paulca["id"], "console": "console.evil.example"}); !res.IsError || res.Code != "invalid" {
+ t.Fatalf("a console accepted: %+v", res)
+ }
+ if res := r.call("p3", wire.ToolProposePlace, map[string]any{"kind": "site", "project": "sample", "candidate": "pc_000000000000"}); !res.IsError || res.Code != "unknown_candidate" {
+ t.Fatalf("an unknown candidate accepted: %+v", res)
+ }
+ if res := r.call("p4", wire.ToolPublishSite, map[string]string{"task": id, "target": "temporary_site"}); !res.IsError || res.Code != "target_later" {
+ t.Fatalf("a temporary site offered: %+v", res)
+ }
+ res = r.call("p5", wire.ToolPublishSite, map[string]string{"task": id})
+ if res.IsError || res.Code != "proposed" {
+ t.Fatalf("publish_site %+v", res)
+ }
+ place, ok := r.cardKind(wire.CardPlace, id)
+ if !ok || place.State != wire.CardOpen || place.Question != "Publish Sample on Carloku, in account oficina?" || place.Place == nil || len(place.Place.Candidates) != 3 || !slices.Equal(place.Options, []string{first["id"].(string), paulca["id"].(string), cands[2].(map[string]any)["id"].(string), wire.ChoiceNotNow}) {
+ t.Fatalf("place card %+v %+v", place, place.Place)
+ }
+ if r.heldKinds(wire.FrameDispatch) != 0 {
+ t.Fatal("proposing dispatched something")
+ }
+ if page := r.get(r.inst.Cookie(), "/conversation", 200); !strings.Contains(page, `equipo-card="place"`) || !strings.Contains(page, `data-place-choice="`+paulca["id"].(string)+`">Carloku, account paulca</button>`) || !strings.Contains(page, `>Tito, account tito</button>`) {
+ t.Fatal("the conversation page lacks the place card's buttons")
+ }
+ // Only the card's owner answers it, at its revision, with one of its
+ // candidates.
+ mate := personToolRig(t, r, "mate@example.com", equipo.RoleOwner)
+ if _, err := mate.client.Answer(ctx, place.ID, paulca["id"].(string), place.Revision); Status(err) != http.StatusNotFound {
+ t.Fatalf("teammate answered: %v", err)
+ }
+ if _, err := r.client.Answer(ctx, place.ID, paulca["id"].(string), place.Revision+1); Status(err) != http.StatusConflict {
+ t.Fatalf("stale answer: %v", err)
+ }
+ if _, err := r.client.Answer(ctx, place.ID, "pc_000000000000", place.Revision); Status(err) != http.StatusUnprocessableEntity {
+ t.Fatalf("another candidate: %v", err)
+ }
+ // An owner no more: refused, and nothing is confirmed.
+ if _, err := r.inst.DB.Writer().Exec("UPDATE members SET role = 'member' WHERE address = ?", Owner); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := r.client.Answer(ctx, place.ID, paulca["id"].(string), place.Revision); Status(err) != http.StatusForbidden || r.rows("SELECT count(*) FROM chat_places") != 0 {
+ t.Fatalf("a member confirmed a place: %v", err)
+ }
+ if _, err := r.inst.DB.Writer().Exec("UPDATE members SET role = 'owner' WHERE address = ?", Owner); err != nil {
+ t.Fatal(err)
+ }
+ out, err := r.client.Answer(ctx, place.ID, paulca["id"].(string), place.Revision)
+ if err != nil || out.Card.State != wire.CardAnswered {
+ t.Fatalf("confirm %+v %v", out.Card, err)
+ }
+ if r.audits("place.confirmed") != 1 || r.heldKinds(wire.FrameDispatch) != 0 {
+ t.Fatal("confirming was not audited, or published")
+ }
+ pub, ok := r.cardKind(wire.CardPublish, id)
+ app := ""
+ if pub.Site != nil {
+ app = pub.Site.App
+ }
+ if !ok || !regexp.MustCompile(`^site-sample-[a-z2-7]{6}$`).MatchString(app) || pub.Question != "Publish Quick website to "+app+" on Carloku, account paulca? This first publish creates the app and a deploy key for it, using your CARLOS login on your runner." {
+ t.Fatalf("publish card %+v %+v", pub, pub.Site)
+ }
+
+ // The place moves before the tap: that card is settled and asked again.
+ if err := r.inst.DB.G.Exec("UPDATE chat_places SET revision = revision + 1").Error; err != nil {
+ t.Fatal(err)
+ }
+ if out, err := r.client.Answer(ctx, pub.ID, wire.ChoicePublish, pub.Revision); err != nil || out.Card.State != wire.CardResolved {
+ t.Fatalf("a moved place published: %+v %v", out.Card, err)
+ }
+ if r.heldKinds(wire.FrameDispatch) != 0 {
+ t.Fatal("a stale card dispatched")
+ }
+ again, _ := r.cardKind(wire.CardPublish, id)
+ if again.ID == pub.ID || again.State != wire.CardOpen {
+ t.Fatalf("not asked again: %+v", again)
+ }
+ if _, err := r.client.Answer(ctx, again.ID, wire.ChoicePublish, again.Revision); err != nil {
+ t.Fatal(err)
+ }
+ d := r.publishDispatch()
+ dest := wire.SiteDestination(wire.FlagshipConsole, "kmnpq", "paulca", app)
+ if d.Publish == nil || d.Publish.Console != wire.FlagshipConsole || d.Publish.Account != "kmnpq" || d.Publish.AccountName != "paulca" || d.Publish.App != app || d.Publish.Mode != wire.SiteSetup || d.Publish.Destination != dest || d.Publish.PlaceRevision != 2 || d.CandidateSHA != merged {
+ t.Fatalf("dispatch %+v", d.Publish)
+ }
+ if refused := r.lease(r.runner, "f-start", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused != "" {
+ t.Fatalf("start refused %q", refused)
+ }
+ r.publishReport("f-built", d, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40})
+ if refused := r.lease(r.runner, "f-tito", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA, Destination: wire.SiteDestination(wire.TitoConsole, "rstuv", "tito", app)}); refused == "" {
+ t.Fatal("a deploy to another place allowed")
+ }
+ for i, purpose := range []string{wire.LeasePurposePublish, wire.LeasePurposeMint} {
+ if refused := r.lease(r.runner, "f-check-"+itoa(i), wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: purpose, Digest: digestA, Destination: dest}); refused != "" {
+ t.Fatalf("%s refused %q", purpose, refused)
+ }
+ }
+ site := "https://" + app + ".bds.oncarlos.com/"
+ r.publishReport("f-published", d, wire.StepDone, &wire.PublishResult{Phase: wire.PublishDone, App: app, URL: site, Version: "s-eeeeeeeeeeee-x-1", Digest: digestA, Outcome: wire.PublishPublished, DeployHeld: true})
+ k, _ := r.client.Task(ctx, id)
+ if k.Site == nil || k.Site.State != wire.SitePublished || k.Site.URL != site {
+ last := k.Steps[len(k.Steps)-1]
+ t.Fatalf("the task shows %+v; step %s %s %+v", k.Site, last.State, last.Reason, last.Publish)
+ }
+ if r.audits("site.create_allowed") != 1 || r.audits("site.deploy_mint_allowed") != 1 {
+ t.Fatal("the setup's authority uses were not audited")
+ }
+ // site_status says what Equipo recorded, from the runner's reach.
+ r.reachHello("2", []wire.ReachDeploy{{Console: wire.FlagshipConsole, Account: "kmnpq", App: app, Name: d.Publish.DeployName, Fingerprint: "0123456789abcdef"}})
+ status := placesData(t, r.call("p6", wire.ToolSiteStatus, map[string]string{"project": "sample"}))
+ if status["app"] != app || status["account"] != "paulca" || status["console"] != "Carloku" || status["can"] != wire.SitePublish || status["deploy_key"] != "held" || status["last_publish"].(map[string]any)["url"] != site {
+ t.Fatalf("site_status %v", status)
+ }
+
+ // The Places page says it, state first, read-only.
+ page := r.get(r.inst.Cookie(), "/conversation/settings/places", 200)
+ for _, want := range []string{"Sample: " + app + " on Carloku, account paulca.", "Live at " + site + ", published ", "Its deploy key is " + d.Publish.DeployName + "."} {
+ if !strings.Contains(page, want) {
+ t.Fatalf("the Places page lacks %q", want)
+ }
+ }
+ if strings.Contains(page, `action="/conversation/settings/places`) {
+ t.Fatal("the Places page writes")
+ }
+
+ // The next merged website publishes with the held key, no note.
+ cand2, merged2 := strings.Repeat("3", 40), strings.Repeat("f", 40)
+ id2, _ := r.websiteReady("g", "Opening hours", base, cand2, true)
+ r.previewDispatch(cand2)
+ r.mergeFromCard("g-m", id2, base, cand2, merged2)
+ pub2, ok := r.cardKind(wire.CardPublish, id2)
+ if !ok || pub2.Question != "Publish Opening hours to "+app+" on Carloku, account paulca?" {
+ t.Fatalf("second publish card %+v", pub2)
+ }
+ if _, err := r.client.Answer(ctx, pub2.ID, wire.ChoicePublish, pub2.Revision); err != nil {
+ t.Fatal(err)
+ }
+ d2 := r.publishDispatch()
+ if d2.Publish.Mode != wire.SitePublish || d2.Publish.DeployName != "" || d2.Publish.Destination != dest {
+ t.Fatalf("second dispatch %+v", d2.Publish)
+ }
+ // The binding moves after the tap: the step is withdrawn at its start.
+ if err := r.inst.DB.G.Exec("UPDATE chat_project_places SET revision = revision + 1").Error; err != nil {
+ t.Fatal(err)
+ }
+ if refused := r.lease(r.runner, "g-start", wire.LeaseCheck{StepID: d2.StepID, Attempt: d2.Attempt}); refused != "withdrawn" {
+ t.Fatalf("a moved binding started: %q", refused)
+ }
+}
+
+// TestContractPlaceNotNowAndRefusals: Not now confirms nothing; a member's
+// coordinator cannot propose a place or offer a publish; a task that is
+// not a merged website is not offered.
+func TestContractPlaceNotNowAndRefusals(t *testing.T) {
+ r := newToolRigAt(t, wire.ProtocolCurrent)
+ r.sitesOn(wire.ProtocolCurrent, false)
+ base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
+ id, _ := r.websiteReady("n", "Quick website", base, cand, true)
+ if res := r.call("n0", wire.ToolPublishSite, map[string]string{"task": id}); !res.IsError || res.Code != "not_website" {
+ t.Fatalf("offered before the merge: %+v", res)
+ }
+ r.previewDispatch(cand)
+ r.mergeFromCard("n-m", id, base, cand, strings.Repeat("e", 40))
+ r.reachHello("1", []wire.ReachDeploy{})
+ if res := r.call("n1", wire.ToolPublishSite, map[string]string{"task": id}); res.Code != "proposed" {
+ t.Fatalf("publish_site %+v", res)
+ }
+ place, _ := r.cardKind(wire.CardPlace, id)
+ if out, err := r.client.Answer(r.ctx, place.ID, wire.ChoiceNotNow, place.Revision); err != nil || out.Card.State != wire.CardAnswered {
+ t.Fatalf("not now %+v %v", out, err)
+ }
+ if n := r.rows("SELECT count(*) FROM chat_places"); n != 0 || r.audits("place.declined") != 1 {
+ t.Fatal("Not now confirmed a place, or was not audited")
+ }
+ if _, ok := r.cardKind(wire.CardPublish, id); ok {
+ t.Fatal("Not now offered a publish")
+ }
+ if page := r.get(r.inst.Cookie(), "/conversation/settings/places", 200); !strings.Contains(page, "No places yet.") {
+ t.Fatal("the empty Places page")
+ }
+}
+
+// TestContractPlaceMintRecovery: a setup that published but holds no key
+// is followed by a mint card for the same merged commit (the recovery
+// route); its tap places a mint step whose mint check records it as the
+// key's step and whose deploy check then holds even when a hello with the
+// new key arrives between them. A publish check before the mint is
+// refused; a setup is never offered again; a mint that found no app at
+// all makes the next card a setup.
+func TestContractPlaceMintRecovery(t *testing.T) {
+ r := newToolRigAt(t, wire.ProtocolCurrent)
+ ctx := r.ctx
+ r.reachHello("1", []wire.ReachDeploy{})
+ base, cand, merged := strings.Repeat("1", 40), strings.Repeat("2", 40), strings.Repeat("e", 40)
+ id, _ := r.websiteReady("m", "Quick website", base, cand, true)
+ r.previewDispatch(cand)
+ r.placeOnMerge = true
+ r.mergeFromCard("m-m", id, base, cand, merged)
+ pub, _ := r.cardKind(wire.CardPublish, id)
+ if _, err := r.client.Answer(ctx, pub.ID, wire.ChoicePublish, pub.Revision); err != nil {
+ t.Fatal(err)
+ }
+ d := r.publishDispatch()
+ dest := d.Publish.Destination
+ r.lease(r.runner, "m-start", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt})
+ r.publishReport("m-built", d, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40})
+ if refused := r.lease(r.runner, "m-deploy", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA, Destination: dest}); refused != "" {
+ t.Fatalf("deploy refused %q", refused)
+ }
+ site := "https://" + d.Publish.App + ".bds.oncarlos.com/"
+ // Published, but the mint was lost: no key held.
+ r.publishReport("m-published", d, wire.StepDone, &wire.PublishResult{Phase: wire.PublishDone, App: d.Publish.App, URL: site, Digest: digestA, Outcome: wire.PublishPublished})
+ r.reachHello("2", []wire.ReachDeploy{{Console: wire.FlagshipConsole, Account: "bcdfg", App: d.Publish.App, Name: d.Publish.DeployName, Lost: true}})
+ mint, ok := r.cardKind(wire.CardPublish, id)
+ if !ok || mint.ID == pub.ID || mint.State != wire.CardOpen || !strings.HasSuffix(mint.Question, "This makes a new deploy key for the site with your CARLOS login on your runner, then publishes with it.") {
+ t.Fatalf("no mint card: %+v", mint)
+ }
+ if k, _ := r.client.Task(ctx, id); k.Site == nil || k.Site.URL != site {
+ t.Fatalf("the published address went: %+v", k.Site)
+ }
+ if _, err := r.client.Answer(ctx, mint.ID, wire.ChoicePublish, mint.Revision); err != nil {
+ t.Fatal(err)
+ }
+ m := r.publishDispatch()
+ if m.Publish.Mode != wire.SiteMint || m.Publish.DeployName == "" || m.Publish.DeployName == d.Publish.DeployName || m.Publish.Destination != dest {
+ t.Fatalf("mint dispatch %+v", m.Publish)
+ }
+ if refused := r.lease(r.runner, "mm-start", wire.LeaseCheck{StepID: m.StepID, Attempt: m.Attempt}); refused != "" {
+ t.Fatalf("mint start refused %q", refused)
+ }
+ r.publishReport("mm-built", m, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40})
+ if refused := r.lease(r.runner, "mm-early", wire.LeaseCheck{StepID: m.StepID, Attempt: m.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA, Destination: dest}); refused == "" {
+ t.Fatal("a mint step deployed before its mint check")
+ }
+ if refused := r.lease(r.runner, "mm-mint", wire.LeaseCheck{StepID: m.StepID, Attempt: m.Attempt, Purpose: wire.LeasePurposeMint, Digest: digestA, Destination: dest}); refused != "" {
+ t.Fatalf("mint refused %q", refused)
+ }
+ // The new key reaches a hello before the deploy check.
+ r.reachHello("3", []wire.ReachDeploy{{Console: wire.FlagshipConsole, Account: "bcdfg", App: m.Publish.App, Name: m.Publish.DeployName, Fingerprint: "0123456789abcdef"}})
+ if refused := r.lease(r.runner, "mm-deploy", wire.LeaseCheck{StepID: m.StepID, Attempt: m.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA, Destination: dest}); refused != "" {
+ t.Fatalf("deploy after the mint refused %q", refused)
+ }
+ if n := r.rows("SELECT count(*) FROM chat_project_places WHERE deploy_step = ? AND deploy_name = ? AND deploy_minted_by = ?", m.StepID, m.Publish.DeployName, Owner); n != 1 {
+ t.Fatal("the mint is not recorded on the binding")
+ }
+ r.publishReport("mm-published", m, wire.StepDone, &wire.PublishResult{Phase: wire.PublishDone, App: m.Publish.App, URL: site, Digest: digestA, Outcome: wire.PublishPublished, DeployHeld: true})
+ if c, _ := r.cardKind(wire.CardPublish, id); c.State == wire.CardOpen {
+ t.Fatalf("asked again with the key held: %+v", c)
+ }
+}
diff --git a/internal/thintest/publish_contract_test.go b/internal/thintest/publish_contract_test.go
index 3895273e..25a730e1 100644
--- a/internal/thintest/publish_contract_test.go
+++ b/internal/thintest/publish_contract_test.go
@@ -13,11 +13,19 @@ import (
)
// sitesOn says hello again as a primary at protocol that is paired with
-// a CARLOS devbox for previews and, when sites, with Carloku for sites.
+// a CARLOS devbox for previews and, when sites, a current carlos signed in
+// to Carloku owning account oficina (protocol 31: places). With sites, a
+// merge then confirms that place on its place card (placeOnMerge), so a
+// test about the publish card meets one.
func (r *toolRig) sitesOn(protocol int, sites bool) {
r.t.Helper()
hello := primaryAt(toolHello(r.runner.Welcome.Generation), protocol)
- hello.Capabilities.Previews, hello.Capabilities.PreviewHost, hello.Capabilities.Sites = true, &wire.PreviewHost{Kind: wire.PreviewHostDevbox, Domain: "docs-t1.example.ts.net"}, sites
+ hello.Capabilities.Previews, hello.Capabilities.PreviewHost = true, &wire.PreviewHost{Kind: wire.PreviewHostDevbox, Domain: "docs-t1.example.ts.net"}
+ if sites {
+ hello.Capabilities.Tools = &wire.ToolHealth{Scanner: wire.ToolHealthy, Carlos: wire.CarlosOK, CarlosVersion: "v0.43.3"}
+ hello.Capabilities.Reach = &wire.Reach{Logins: []wire.ReachLogin{{Console: wire.FlagshipConsole, Accounts: []wire.ReachAccount{{Name: "oficina", Sqid: "bcdfg"}, {Name: "paulca", Sqid: "kmnpq"}}}}, Deploys: []wire.ReachDeploy{}}
+ r.placeOnMerge = protocol >= wire.ProtocolPlaces
+ }
if err := r.runner.Send(r.ctx, "h-sites-"+itoa(int(time.Now().UnixNano()%1e9)), wire.FrameHello, hello); err != nil {
r.t.Fatal(err)
}
@@ -152,7 +160,7 @@ func TestContractPublishSite(t *testing.T) {
t.Fatalf("minted app %+v", pub.Site)
}
app := pub.Site.App
- if pub.State != wire.CardOpen || pub.Name != "Quick website" || !slices.Equal(pub.Options, []string{wire.ChoicePublish, wire.ChoiceNotNow}) || pub.Site == nil || *pub.Site != (wire.CardSite{App: app, SHA: merged, State: wire.SiteAsked}) || pub.Question != "Publish Quick website on the web as "+app+"?" {
+ if pub.State != wire.CardOpen || pub.Name != "Quick website" || !slices.Equal(pub.Options, []string{wire.ChoicePublish, wire.ChoiceNotNow}) || pub.Site == nil || *pub.Site != (wire.CardSite{App: app, SHA: merged, State: wire.SiteAsked}) || pub.Question != "Publish Quick website to "+app+" on Carloku, account oficina? This first publish creates the app and a deploy key for it, using your CARLOS login on your runner." {
t.Fatalf("publish card %+v %+v", pub, pub.Site)
}
k, _ := r.client.Task(ctx, id)
@@ -178,28 +186,41 @@ func TestContractPublishSite(t *testing.T) {
t.Fatalf("publish %+v %v", out.Card, err)
}
d := r.publishDispatch()
- if d.CandidateSHA != merged || d.Person != Owner || d.Repo != "amadan.net/oficina/sample" || d.Publish == nil || *d.Publish != (wire.PublishDispatch{App: app, Into: "main"}) || d.Attempt != 1 {
+ dest := wire.SiteDestination(wire.FlagshipConsole, "bcdfg", "oficina", app)
+ if d.CandidateSHA != merged || d.Person != Owner || d.Repo != "amadan.net/oficina/sample" || d.Publish == nil || d.Attempt != 1 || !strings.HasPrefix(d.Publish.Place, "pl_") || !regexp.MustCompile(`^eq-sample-[a-z2-7]{6}-[a-z2-7]{4}$`).MatchString(d.Publish.DeployName) {
t.Fatalf("publish dispatch %+v %+v", d, d.Publish)
}
+ if want := (wire.PublishDispatch{App: app, Into: "main", Console: wire.FlagshipConsole, Account: "bcdfg", AccountName: "oficina", Place: d.Publish.Place, PlaceRevision: 1, BindingRevision: 1, Destination: dest, Mode: wire.SiteSetup, DeployName: d.Publish.DeployName}); *d.Publish != want {
+ t.Fatalf("publish dispatch %+v\nwant %+v", *d.Publish, want)
+ }
if _, err := r.client.Answer(ctx, pub.ID, wire.ChoicePublish, out.Card.Revision); Status(err) != http.StatusConflict {
t.Fatalf("answered twice: %v", err)
}
if refused := r.lease(r.runner, "w-start", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused != "" {
t.Fatalf("start refused %q", refused)
}
- if refused := r.lease(r.runner, "w-early", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA}); refused != wire.RefusedPublishNotBuilt {
+ if refused := r.lease(r.runner, "w-early", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA, Destination: dest}); refused != wire.RefusedPublishNotBuilt {
t.Fatalf("deploy before built: %q", refused)
}
r.publishReport("w-built", d, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40})
- if refused := r.lease(r.runner, "w-other", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestB}); refused == "" {
+ if refused := r.lease(r.runner, "w-other", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestB, Destination: dest}); refused == "" {
t.Fatal("another export's deploy allowed")
}
+ if refused := r.lease(r.runner, "w-elsewhere", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA, Destination: wire.SiteDestination(wire.FlagshipConsole, "kmnpq", "paulca", app)}); refused == "" {
+ t.Fatal("a deploy to another destination allowed")
+ }
+ if refused := r.lease(r.runner, "w-mint-early", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposeMint, Digest: digestA, Destination: dest}); refused == "" {
+ t.Fatal("a setup's mint allowed before its deploy check")
+ }
if refused := r.lease(r.runner, "w-preview", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePreview, Digest: digestA}); refused == "" {
t.Fatal("a preview check allowed on a publish step")
}
- if refused := r.lease(r.runner, "w-deploy", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA}); refused != "" {
+ if refused := r.lease(r.runner, "w-deploy", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA, Destination: dest}); refused != "" {
t.Fatalf("deploy refused %q", refused)
}
+ if refused := r.lease(r.runner, "w-mint", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposeMint, Digest: digestA, Destination: dest}); refused != "" {
+ t.Fatalf("mint refused %q", refused)
+ }
site := "https://" + app + ".bds.oncarlos.com/"
for name, p := range map[string]wire.PublishResult{
"another app": {Phase: wire.PublishDone, App: "site-other", URL: "https://site-other.bds.oncarlos.com/", Digest: digestA, Outcome: wire.PublishPublished},
@@ -212,7 +233,7 @@ func TestContractPublishSite(t *testing.T) {
t.Fatalf("%s counted: %+v", name, k.Site)
}
}
- r.publishReport("w-published", d, wire.StepDone, &wire.PublishResult{Phase: wire.PublishDone, App: app, URL: site, Version: "s-eeeeeeeeeeee-x-1", Digest: digestA, Outcome: wire.PublishPublished})
+ r.publishReport("w-published", d, wire.StepDone, &wire.PublishResult{Phase: wire.PublishDone, App: app, URL: site, Version: "s-eeeeeeeeeeee-x-1", Digest: digestA, Outcome: wire.PublishPublished, DeployHeld: true})
k, _ = r.client.Task(ctx, id)
shape(t, "api/task-published.json", k)
last := k.Steps[len(k.Steps)-1]
@@ -232,7 +253,10 @@ func TestContractPublishSite(t *testing.T) {
t.Fatalf("%s audited %d times", kind, got)
}
}
- if r.audits("publish.authorize") != 4 {
+ if r.audits("place.proposed") != 1 || r.audits("place.confirmed") != 1 || r.audits("site.create_allowed") != 1 || r.audits("site.deploy_mint_allowed") != 1 {
+ t.Fatal("the place and the site's setup were not audited")
+ }
+ if r.audits("publish.authorize") != 7 {
t.Fatalf("authorize audited %d times", r.audits("publish.authorize"))
}
if page := r.get(r.inst.Cookie(), "/conversation", 200); !strings.Contains(page, `equipo-card="publish"`) || !strings.Contains(page, "Publishing.") {
@@ -244,8 +268,8 @@ func TestContractPublishSite(t *testing.T) {
// whose Review found no static site config, nor on a primary that does
// not say it can publish sites (paired with none, or below protocol 16).
func TestContractPublishNotOffered(t *testing.T) {
- r := newToolRigAt(t, wire.ProtocolPublish)
- r.sitesOn(wire.ProtocolPublish, true)
+ r := newToolRigAt(t, wire.ProtocolCurrent)
+ r.sitesOn(wire.ProtocolCurrent, true)
base := strings.Repeat("1", 40)
id, _ := r.websiteReady("n", "Fix the README", base, strings.Repeat("2", 40), false)
r.mergeFromCard("n-m", id, base, strings.Repeat("2", 40), strings.Repeat("e", 40))
@@ -253,8 +277,8 @@ func TestContractPublishNotOffered(t *testing.T) {
if c, ok := r.publishCard(id); ok {
t.Fatalf("offered without a site: %+v", c)
}
- off := newToolRigAt(t, wire.ProtocolPublish)
- off.sitesOn(wire.ProtocolPublish, false)
+ off := newToolRigAt(t, wire.ProtocolCurrent)
+ off.sitesOn(wire.ProtocolCurrent, false)
id2, _ := off.websiteReady("o", "Quick website", base, strings.Repeat("3", 40), true)
off.previewDispatch(strings.Repeat("3", 40))
off.mergeFromCard("o-m", id2, base, strings.Repeat("3", 40), strings.Repeat("f", 40))
@@ -276,8 +300,8 @@ func TestContractPublishNotOffered(t *testing.T) {
// TestContractPublishNotNow: Not now publishes nothing and says so on the
// task; the creator's publish is then refused by the card.
func TestContractPublishNotNow(t *testing.T) {
- r := newToolRigAt(t, wire.ProtocolPublish)
- r.sitesOn(wire.ProtocolPublish, true)
+ r := newToolRigAt(t, wire.ProtocolCurrent)
+ r.sitesOn(wire.ProtocolCurrent, true)
base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
id, _ := r.websiteReady("x", "Quick website", base, cand, true)
r.previewDispatch(cand)
@@ -308,8 +332,8 @@ func TestContractPublishNotNow(t *testing.T) {
// account already holds the app's name is a failure the card shows; the
// creator is told, and not asked again.
func TestContractPublishNameTaken(t *testing.T) {
- r := newToolRigAt(t, wire.ProtocolPublish)
- r.sitesOn(wire.ProtocolPublish, true)
+ r := newToolRigAt(t, wire.ProtocolCurrent)
+ r.sitesOn(wire.ProtocolCurrent, true)
base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
id, _ := r.websiteReady("y", "Quick website", base, cand, true)
r.previewDispatch(cand)
diff --git a/internal/thintest/tools_contract_test.go b/internal/thintest/tools_contract_test.go
index 1720b6bc..2352c86c 100644
--- a/internal/thintest/tools_contract_test.go
+++ b/internal/thintest/tools_contract_test.go
@@ -21,6 +21,8 @@ type toolRig struct {
// held are frames other than tool results that arrived during a call,
// for expect.
held []heldFrame
+ // placeOnMerge: a merge confirms the place card it raises (sitesOn).
+ placeOnMerge bool
}
type heldFrame struct {