From e8c773659a2a6772e19e74db80c28025953198a4 Mon Sep 17 00:00:00 2001 From: Ted Huang Date: Sat, 21 Nov 2026 00:14:32 -0500 Subject: [PATCH] deploy: name the previous release on deployment detail and offer it as a create preview Deployment detail now carries previous_release: the latest earlier deployment on the same channel and resource that has a Hub-succeeded job and a different version, with its artifact digest and whether the artifact is still in the Hub catalog. Returning to it is an ordinary create preview with those inputs, so it goes through the same canary and verification. Detail schema_version moves to 4. Web shows a Previous release block (create form for admins, fetch link when the artifact is gone). CLI `deployment show` prints the exact preview or fetch command. The rollout status MCP view includes previous_release. The rollout text no longer says there is no rollback, and the copy guard keeps that sentence out. Detail and action previews read the deployment list once and share it between eligibility and the previous release. Co-Authored-By: Claude Opus 5.5 --- cmd/clawctl-hub/deploymentcmd.go | 25 ++++++- cmd/clawctl-hub/deploymentreadcmd_test.go | 31 ++++++++ docs/API-SURFACE.md | 4 +- docs/FEATURE-INVENTORY.md | 4 +- internal/operator/deployment.go | 74 ++++++++++++++++++-- internal/operator/deployment_actions.go | 6 +- internal/operator/deployment_actions_test.go | 55 +++++++++++++++ internal/operator/deployment_test.go | 14 +++- internal/operatoragent/tools.go | 1 + internal/operatorclient/deployments.go | 8 +++ internal/operatorclient/deployments_test.go | 21 ++++++ internal/rollout/expand.go | 2 +- internal/rollout/expand_test.go | 2 +- internal/web/deployment_actions_web_test.go | 46 ++++++++++++ internal/web/interface_copy_test.go | 1 + internal/web/rollout.go | 3 +- internal/web/templates/deployment.html | 23 ++++++ 17 files changed, 300 insertions(+), 20 deletions(-) diff --git a/cmd/clawctl-hub/deploymentcmd.go b/cmd/clawctl-hub/deploymentcmd.go index 3e9c4141..b52d10fa 100644 --- a/cmd/clawctl-hub/deploymentcmd.go +++ b/cmd/clawctl-hub/deploymentcmd.go @@ -524,11 +524,32 @@ func writeDeploymentDetail(out io.Writer, result operator.DeploymentDetailResult return err } } - _, err := fmt.Fprintf(out, + if _, err := fmt.Fprintf(out, "actions: continue=%s (%d) retry=%s (%d) abandon=%s (%d)\n", deploymentEligibilityLabel(result.Actions.Continue), result.Actions.Continue.AffectedTargets, deploymentEligibilityLabel(result.Actions.Retry), result.Actions.Retry.AffectedTargets, - deploymentEligibilityLabel(result.Actions.Abandon), result.Actions.Abandon.AffectedTargets) + deploymentEligibilityLabel(result.Actions.Abandon), result.Actions.Abandon.AffectedTargets); err != nil { + return err + } + return writeDeploymentPreviousRelease(out, item.Channel, result.PreviousRelease) +} + +func writeDeploymentPreviousRelease(out io.Writer, channel string, previous *operator.DeploymentPreviousRelease) error { + if previous == nil { + _, err := fmt.Fprintln(out, "previous release: none") + return err + } + if _, err := fmt.Fprintf(out, "previous release: %s (deployment %s, artifact %s)\n", + terminalSafe(previous.Version), terminalSafe(previous.DeploymentID), terminalSafe(previous.ArtifactSHA256)); err != nil { + return err + } + if !previous.ArtifactAvailable { + _, err := fmt.Fprintf(out, " artifact missing on Hub; fetch it first: clawctl-hub artifact fetch openclaw@%s --confirm-version %s --reason REASON --idempotency-key KEY\n", + terminalSafe(previous.Version), terminalSafe(previous.Version)) + return err + } + _, err := fmt.Fprintf(out, " deploy it: clawctl-hub deployment preview --channel %s --version %s --artifact %s\n", + terminalSafe(channel), terminalSafe(previous.Version), terminalSafe(previous.ArtifactSHA256)) return err } diff --git a/cmd/clawctl-hub/deploymentreadcmd_test.go b/cmd/clawctl-hub/deploymentreadcmd_test.go index 54eaeec8..dab61f73 100644 --- a/cmd/clawctl-hub/deploymentreadcmd_test.go +++ b/cmd/clawctl-hub/deploymentreadcmd_test.go @@ -570,3 +570,34 @@ func TestDeploymentPreviewTextShowsEachTargetsCurrentVersion(t *testing.T) { t.Fatalf("preview text:\n%s", out.String()) } } + +func TestDeploymentDetailTextGivesThePreviousReleaseNextStep(t *testing.T) { + sha := strings.Repeat("a", 64) + previous := &operator.DeploymentPreviousRelease{DeploymentID: "deployment-previous", Version: "2026.9.1", + ArtifactSHA256: sha, ArtifactAvailable: true} + for _, test := range []struct { + name string + previous *operator.DeploymentPreviousRelease + want []string + }{ + {"available", previous, []string{ + `previous release: "2026.9.1" (deployment "deployment-previous", artifact "` + sha + `")`, + `deploy it: clawctl-hub deployment preview --channel "canary" --version "2026.9.1" --artifact "` + sha + `"`, + }}, + {"artifact missing", &operator.DeploymentPreviousRelease{DeploymentID: "deployment-previous", Version: "2026.9.1", ArtifactSHA256: sha}, + []string{`artifact missing on Hub; fetch it first: clawctl-hub artifact fetch openclaw@"2026.9.1" --confirm-version "2026.9.1"`}}, + {"none", nil, []string{"previous release: none"}}, + } { + t.Run(test.name, func(t *testing.T) { + var out bytes.Buffer + if err := writeDeploymentPreviousRelease(&out, "canary", test.previous); err != nil { + t.Fatal(err) + } + for _, want := range test.want { + if !strings.Contains(out.String(), want) { + t.Errorf("missing %q in:\n%s", want, out.String()) + } + } + }) + } +} diff --git a/docs/API-SURFACE.md b/docs/API-SURFACE.md index 1552ea15..37658e3c 100644 --- a/docs/API-SURFACE.md +++ b/docs/API-SURFACE.md @@ -108,7 +108,7 @@ verifier 不是第二個判斷,是一條用單一 bearer 控管的遠端執行 | `GET` | `/v1/operator/artifact-fetches/{id}` | Fetch operation detail | `artifact fetch show ` 預設走 discovery HTTP | queued/running/succeeded/failed、phase、monotonic progress、attempt、result digest/size 或 bounded failure | | `GET` | `/v1/operator/updates` | Updates 的概觀/Artifacts/Canary/Stable 共用 in-process service | —;strict Go operator client 已交付 | `schema_version=5`;channel/status/version/limit/cursor;同一 evaluation instant 組合 metadata-only artifacts、safe members、`last_observed_version`+Hub-trusted `last_observation_received_at`、latest deployment、rollout plan 與 stable promotion gate。Stable 的 promotion 帶 `independent_required`、通過 target 數,以及每台 machine 與 job 的十一種 typed state 與下一步;不把沒有 freshness threshold 的歷史 evidence 稱為 current | | `GET` | `/v1/operator/deployments` | All/Active/Paused-Stuck/Finished ledger submenu 共用 in-process operator service;New 另做 isolated metadata-only catalog scan,只列 `available_unverified` 且具有可信 record 的候選材料 | `deployment list` 預設走 discovery HTTP;`--db` 僅 stopped-service break-glass | channel/state/stuck filters、1..100 limit、filter-bound live keyset cursor;safe summary;真正 deployment preview/apply 仍完整驗 artifact bytes | -| `GET` | `/v1/operator/deployments/{id}` | Deployment detail 共用 safe DTO | `deployment show` 預設走 discovery HTTP | `schema_version=3`;targets、material summary、batch/revision 與三個 action eligibility;revision 耗盡會明列 blocker。每個已開單 target 帶 `independent`(八種 verdict 之一、rows、live_producers),其中 `live_producers` 對該 target 的工作單按 distinct verifier 身分計數,不按規則列或重派次數;沒有開單的 target 為 `null`——沒有工作單就沒有東西可驗,與「有工作單但沒人驗」是兩件事,後者是 `absent`。另有 deployment 層的 `independent` rollup:`opened_targets`、`passed_targets`、逐 target 的 `live_producers` 加總與固定列出全部八種 verdict 的 target 計數,全部由 targets 推導,strict client 對不上就拒收整個回應。這個 rollup 只描述該 deployment;stable promotion 另依 latest canary lineage、派工、完整規則組與 exact release version 計算 gate。不回 raw spec/created_by | +| `GET` | `/v1/operator/deployments/{id}` | Deployment detail 共用 safe DTO | `deployment show` 預設走 discovery HTTP | `schema_version=4`;另帶 `previous_release`:同 channel、同資源、比這張早、至少一張 Hub succeeded 工作單、且版號不同的最新 deployment(`deployment_id`、`version`、`artifact_sha256`、`artifact_available`);沒有就是 `null`。回到上一版就是用這三個值走一般的 create preview,同樣經過 canary 與驗證。targets、material summary、batch/revision 與三個 action eligibility;revision 耗盡會明列 blocker。每個已開單 target 帶 `independent`(八種 verdict 之一、rows、live_producers),其中 `live_producers` 對該 target 的工作單按 distinct verifier 身分計數,不按規則列或重派次數;沒有開單的 target 為 `null`——沒有工作單就沒有東西可驗,與「有工作單但沒人驗」是兩件事,後者是 `absent`。另有 deployment 層的 `independent` rollup:`opened_targets`、`passed_targets`、逐 target 的 `live_producers` 加總與固定列出全部八種 verdict 的 target 計數,全部由 targets 推導,strict client 對不上就拒收整個回應。這個 rollup 只描述該 deployment;stable promotion 另依 latest canary lineage、派工、完整規則組與 exact release version 計算 gate。不回 raw spec/created_by | | `POST` | `/v1/operator/deployments/preview` | 新增部署 settings → review | `deployment preview` 與 create 前自動 preview | `schema_version=5`;重新驗 artifact bytes,固定 target snapshot、promotion decision 與 `preview_digest`。每台 target 帶 `current_version`(最新觀測到正在跑的 OpenClaw 版號;沒有觀測為 `null`),並計入 `preview_digest`:預覽後任一台版本變了,套用回 `412 DEPLOYMENT_PREVIEW_STALE`,要重新預覽。Stable promotion 逐台回 `independent_targets`(machine/job、十一種 state、typed next step)及通過數;任一 effective successful canary target 未通過便 fail closed | | `POST` | `/v1/operator/deployments` | typed channel/version confirm | `deployment create` preview→apply | `admin`;fresh `201`、成功 replay `200`;拒絕 replay 保留原錯誤 status;artifact/policy stale 與 idempotency conflict 明確分開 | | `POST` | `/v1/operator/deployments/{id}/continuation-preview` | detail → Continue review | continue 前自動 preview | `operate`;`schema_version=4`;精確下一批或 finish outcome,回 control/opened-batch precondition;若含 stable promotion,使用與 create preview 相同的 typed 獨立證據 gate | @@ -466,7 +466,7 @@ machine `/v1/` plane discriminator 必須是 literal,避免 wildcard 在 root | deployment continue | ✅ | ✅ | ✅ HTTP | control revision + opened-batch CAS、idempotency、atomic audit;stable promotion 沿用同一份獨立證據 gate | | deployment retry | ✅ | ✅ | ✅ HTTP | 只預選 exact terminal-failure targets;新 attempt 有 lineage | | deployment abandon | ✅ | ✅ | ✅ HTTP | full-ID confirmation + terminal-job gate + unopened impact | -| deployment list / detail | ✅ | ✅ | ✅ HTTP | safe DTO 供 CLI/UI 共用;detail 是 `schema_version=3`,每個已開單 target 帶八種獨立 verdict 之一,另有由 targets 推導的 rollup;不曝 raw spec/created_by | +| deployment list / detail | ✅ | ✅ | ✅ HTTP | safe DTO 供 CLI/UI 共用;detail 是 `schema_version=4`,每個已開單 target 帶八種獨立 verdict 之一,另有由 targets 推導的 rollup 與 `previous_release`;不曝 raw spec/created_by | | noop protocol drill | ✅ Diagnostics submenu+preview/confirm | ✅ preview/apply | ✅ HTTP/break-glass | 固定 noop spec、不改機器設定;atomic desired/job/receipt/audit,建立後進入 job detail | | global job list / detail / evidence | ✅ | ✅ safe projection+typed evidence | ✅ `job list/show/evidence` HTTP | creation-ceiling pagination 仍是 live keyset;raw evidence 已改為 typed bounded disclosure(`schema_version=6`,agent/Hub event producer、role/authority、row provenance、兩個 clocks 與 independence 明標,另有八種 verdict、expected/observed version 的獨立證據段與派工段);sampleagent3 的 fleet-peer verifier 已用獨立 bearer 與 failure domain 寫入正式帳本 | | audit ledger | ✅ | ✅ safe projection | ✅ `audit [list]` HTTP | 完整 exact filters、creation-ceiling cursor 與 bounded denial sampling 已交付 | diff --git a/docs/FEATURE-INVENTORY.md b/docs/FEATURE-INVENTORY.md index 90e07e25..9089e12e 100644 --- a/docs/FEATURE-INVENTORY.md +++ b/docs/FEATURE-INVENTORY.md @@ -119,7 +119,7 @@ resolver 在 `cmd/clawctl-hub/verifier_api.go`。 | 42 | `GET /apps/artifacts/{id}` | HTML | 讀取/完整驗證 | Artifact safe detail;完整重算 SHA-256 後才可顯示 `ready` | | 43 | `GET /apps/artifact-fetches/{id}` | HTML | 讀取 | Durable fetch operation safe detail | | 44 | `GET /deployments` | HTML | 讀取 | Deployment list | -| 45 | `GET /deployments/{id}` | HTML | 讀取 | Deployment detail;targets 表加一欄跨故障域證據(每個已開單 target 的 verdict、rows、distinct 可用 producer),表頭一行數出「已開單的 N 台中有幾台被第二個 producer 回報通過」。沒開單的 target 留空,不給 verdict | +| 45 | `GET /deployments/{id}` | HTML | 讀取 | Deployment detail;Previous release 區塊把上一版帶進 create preview(admin);targets 表加一欄跨故障域證據(每個已開單 target 的 verdict、rows、distinct 可用 producer),表頭一行數出「已開單的 N 台中有幾台被第二個 producer 回報通過」。沒開單的 target 留空,不給 verdict | | 46 | `GET /updates` | HTML | 讀取/preview | 共用 native Updates model 的 artifacts、channel 成員、最近部署與 rollout gate | | 47 | `GET /reports/tickets` | HTML | 讀取 | Ticket ledger | | 48 | `GET /reports/tickets.csv` | CSV | 讀取/下載 | Browser export,不是 stable JSON API | @@ -161,7 +161,7 @@ resolver 在 `cmd/clawctl-hub/verifier_api.go`。 | 84 | `GET /v1/operator/artifact-fetches/{id}` | JSON | 讀取 | Operation phase/progress/result 或 bounded failure code/detail | | 85 | `GET /v1/operator/updates` | JSON | 讀取/preview | `schema_version=5`;Artifacts、channel members、latest deployment、rollout plan,以及逐 canary target 顯示十一種獨立證據狀態與下一步的 stable promotion gate | | 86 | `GET /v1/operator/deployments` | JSON | 讀取 | canonical safe list;channel/state/stuck filters、live keyset cursor | -| 87 | `GET /v1/operator/deployments/{id}` | JSON | 讀取 | canonical safe detail(`schema_version=3`);targets、material summary、action eligibility;每個已開單 target 帶 `independent`(八種 verdict 之一/rows/distinct live_producers),未開單 target 為 `null`;另有 deployment 層 rollup(opened/passed targets、逐 target live producers 加總、八種 verdict 的 target 計數),由 targets 推導而非另一份真相;不回 raw spec/created_by | +| 87 | `GET /v1/operator/deployments/{id}` | JSON | 讀取 | canonical safe detail(`schema_version=4`);另帶 `previous_release`:同 channel、同資源、比這張早、至少一張 Hub succeeded 工作單、且版號不同的最新 deployment(`deployment_id`、`version`、`artifact_sha256`、`artifact_available`);沒有就是 `null`。回到上一版就是用這三個值走一般的 create preview,同樣經過 canary 與驗證。targets、material summary、action eligibility;每個已開單 target 帶 `independent`(八種 verdict 之一/rows/distinct live_producers),未開單 target 為 `null`;另有 deployment 層 rollup(opened/passed targets、逐 target live producers 加總、八種 verdict 的 target 計數),由 targets 推導而非另一份真相;不回 raw spec/created_by | | 88 | `POST /v1/operator/deployments/preview` | JSON | 是,preview | `schema_version=5`;create preview;重新驗 artifact bytes,固定 targets(含每台 `current_version`,計入 digest)與 promote verdict;stable 逐台要求 active fleet peer 在最新派工後送齊三條必要規則,且 `current_release` 的結構化版號等於 canary exact version | | 89 | `POST /v1/operator/deployments` | JSON | 是 | create apply;fresh `201`、成功 replay `200`;拒絕 replay 保留原錯誤 status/code | | 90 | `POST /v1/operator/deployments/{id}/continuation-preview` | JSON | 是,preview | continue/finish preview | diff --git a/internal/operator/deployment.go b/internal/operator/deployment.go index 67bd2a07..295259ae 100644 --- a/internal/operator/deployment.go +++ b/internal/operator/deployment.go @@ -46,7 +46,7 @@ func TerminalJobOutcome(state deploy.JobState) string { } const ( - DeploymentReadSchemaVersion = 3 + DeploymentReadSchemaVersion = 4 DeploymentPreviewSchemaVersion = 5 DefaultDeploymentReadLimit = 50 MaxDeploymentReadLimit = 100 @@ -294,6 +294,19 @@ type DeploymentDetailResult struct { Targets []DeploymentTargetSummary `json:"targets"` Independent DeploymentIndependentSummary `json:"independent"` Actions DeploymentActionEligibilitySet `json:"actions"` + // PreviousRelease is the release this deployment replaced on its channel. + // Nil means the channel has no earlier succeeded release of another version. + PreviousRelease *DeploymentPreviousRelease `json:"previous_release"` +} + +// DeploymentPreviousRelease names the latest earlier deployment on the same +// channel and resource that has a Hub-succeeded job and a different version. +// Deploying it again is an ordinary create preview with these inputs. +type DeploymentPreviousRelease struct { + DeploymentID string `json:"deployment_id"` + Version string `json:"version"` + ArtifactSHA256 string `json:"artifact_sha256"` + ArtifactAvailable bool `json:"artifact_available"` } type DeploymentCreatePreviewRequest struct { @@ -472,7 +485,11 @@ func (s *Service) DeploymentDetail(deploymentID string, evaluatedAt time.Time) ( if err != nil { return DeploymentDetailResult{}, err } - actions, err := s.deploymentActionEligibility(view, summary.Material, evaluatedAt) + views, err := s.store.ListDeployments(evaluatedAt) + if err != nil { + return DeploymentDetailResult{}, err + } + actions, err := s.deploymentActionEligibility(view, summary.Material, views, evaluatedAt) if err != nil { return DeploymentDetailResult{}, err } @@ -484,9 +501,54 @@ func (s *Service) DeploymentDetail(deploymentID string, evaluatedAt time.Time) ( return DeploymentDetailResult{ SchemaVersion: DeploymentReadSchemaVersion, Consistency: DeploymentReadConsistencyLive, EvaluatedAt: evaluatedAt, Item: summary, Targets: targets, Independent: independent, Actions: actions, + PreviousRelease: s.deploymentPreviousRelease(view, summary.Material, views), }, nil } +func (s *Service) deploymentPreviousRelease(view store.DeploymentView, material DeploymentMaterialSummary, + views []store.DeploymentView, +) *DeploymentPreviousRelease { + if material.Status != DeploymentMaterialRecorded || material.Version == nil { + return nil + } + var found *store.DeploymentView + var foundMaterial DeploymentMaterialSummary + for i := range views { + candidate := &views[i] + if candidate.DeploymentID == view.DeploymentID || candidate.Channel != view.Channel || + candidate.ResourceKind != view.ResourceKind || candidate.ResourceID != view.ResourceID || + candidate.Counts[deploy.Succeeded] == 0 || !deploymentCreatedBefore(*candidate, view) || + (found != nil && !deploymentCreatedBefore(*found, *candidate)) { + continue + } + candidateMaterial := projectDeploymentMaterial(candidate.ResourceKind, candidate.ResourceID, candidate.Spec) + if candidateMaterial.Status != DeploymentMaterialRecorded || candidateMaterial.Version == nil || + candidateMaterial.ArtifactDigest == nil || *candidateMaterial.Version == *material.Version { + continue + } + found, foundMaterial = candidate, candidateMaterial + } + if found == nil { + return nil + } + release := &DeploymentPreviousRelease{ + DeploymentID: found.DeploymentID, Version: *foundMaterial.Version, + ArtifactSHA256: strings.TrimPrefix(*foundMaterial.ArtifactDigest, "sha256:"), + } + if strings.TrimSpace(s.artifactsDir) != "" { + _, err := artifact.SelectOpenClawArtifact(s.artifactsDir, release.Version, release.ArtifactSHA256) + release.ArtifactAvailable = err == nil + } + return release +} + +func deploymentCreatedBefore(a, b store.DeploymentView) bool { + if !a.CreatedAt.Equal(b.CreatedAt) { + return a.CreatedAt.Before(b.CreatedAt) + } + return a.DeploymentID < b.DeploymentID +} + // attachDeploymentIndependentVerdicts gives every opened target a verdict and // counts them. A target whose job has no independent row gets absent rather // than nil: the job exists, the ledger was read, and nothing was found. Only a @@ -867,7 +929,9 @@ func projectDeploymentTargets(view store.DeploymentView) ([]DeploymentTargetSumm return result, nil } -func (s *Service) deploymentActionEligibility(view store.DeploymentView, material DeploymentMaterialSummary, now time.Time) (DeploymentActionEligibilitySet, error) { +func (s *Service) deploymentActionEligibility(view store.DeploymentView, material DeploymentMaterialSummary, + views []store.DeploymentView, now time.Time, +) (DeploymentActionEligibilitySet, error) { set := DeploymentActionEligibilitySet{ Continue: DeploymentActionEligibility{Outcome: "open_next_batch", Blockers: []string{}}, SkipFailedBatch: DeploymentActionEligibility{Outcome: "open_next_batch", Blockers: []string{}}, @@ -951,10 +1015,6 @@ func (s *Service) deploymentActionEligibility(view store.DeploymentView, materia set.Retry.Blockers = append(set.Retry.Blockers, "stable_promotion_locked") } } - views, err := s.store.ListDeployments(now) - if err != nil { - return DeploymentActionEligibilitySet{}, err - } for _, candidate := range views { if candidate.DeploymentID != view.DeploymentID && (candidate.State == store.DeploymentRunning || candidate.State == store.DeploymentPaused) && diff --git a/internal/operator/deployment_actions.go b/internal/operator/deployment_actions.go index e6fc3627..3e2afc26 100644 --- a/internal/operator/deployment_actions.go +++ b/internal/operator/deployment_actions.go @@ -580,7 +580,11 @@ func (s *Service) deploymentActionSnapshot(ctx context.Context, action, deployme if err != nil { return deploymentActionSnapshot{}, err } - actions, err := s.deploymentActionEligibility(view, summary.Material, evaluatedAt) + views, err := s.store.ListDeployments(evaluatedAt) + if err != nil { + return deploymentActionSnapshot{}, err + } + actions, err := s.deploymentActionEligibility(view, summary.Material, views, evaluatedAt) if err != nil { return deploymentActionSnapshot{}, err } diff --git a/internal/operator/deployment_actions_test.go b/internal/operator/deployment_actions_test.go index 30c42852..8d9d365a 100644 --- a/internal/operator/deployment_actions_test.go +++ b/internal/operator/deployment_actions_test.go @@ -13,6 +13,7 @@ import ( "github.com/teddashh/AI-Intune/internal/artifact" "github.com/teddashh/AI-Intune/internal/deploy" + "github.com/teddashh/AI-Intune/internal/model" "github.com/teddashh/AI-Intune/internal/operatorauth" "github.com/teddashh/AI-Intune/internal/store" ) @@ -839,3 +840,57 @@ func TestCreateApplyWithAnUnsupportedChannelSaysBadChannelNotStalePreview(t *tes } } } + +func TestDeploymentPreviousReleaseIsTheLatestEarlierSucceededOtherVersionOnTheChannel(t *testing.T) { + svc, st, _, record, created, jobs := deploymentActionFixture(t, 1, 1) + markDeploymentJobTerminal(t, st, jobs[0].JobID, deploy.Succeeded) + base, err := st.DeploymentView(created.DeploymentID, time.Now().UTC()) + if err != nil { + t.Fatal(err) + } + t0 := base.CreatedAt + variant := func(id, channel, version, sha string, at time.Time, succeeded int) store.DeploymentView { + v := base + v.DeploymentID, v.Channel, v.CreatedAt = id, channel, at + v.Counts = map[deploy.JobState]int{deploy.Succeeded: succeeded, deploy.Failed: 1} + spec, err := json.Marshal(model.OpenClawSpec{Kind: "openclaw", Version: version, + Artifact: &model.ArtifactRef{SHA256: sha, Size: record.Size}}) + if err != nil { + t.Fatal(err) + } + v.Spec = string(spec) + return v + } + other := strings.Repeat("b", 64) + current := variant("deployment-current", "canary", "2026.10.1", other, t0.Add(10*time.Minute), 0) + views := []store.DeploymentView{ + current, + variant("deployment-oldest", "canary", "2026.8.1", other, t0, 1), + variant("deployment-previous", "canary", deploymentTestVersion, record.SHA256, t0.Add(time.Minute), 1), + variant("deployment-never-succeeded", "canary", "2026.9.9", other, t0.Add(2*time.Minute), 0), + variant("deployment-same-version", "canary", "2026.10.1", other, t0.Add(3*time.Minute), 1), + variant("deployment-other-channel", "stable", "2026.9.7", other, t0.Add(4*time.Minute), 1), + variant("deployment-later", "canary", "2026.11.1", other, t0.Add(20*time.Minute), 1), + } + material := projectDeploymentMaterial(current.ResourceKind, current.ResourceID, current.Spec) + got := svc.deploymentPreviousRelease(current, material, views) + want := &DeploymentPreviousRelease{DeploymentID: "deployment-previous", Version: deploymentTestVersion, + ArtifactSHA256: record.SHA256, ArtifactAvailable: true} + if got == nil || *got != *want { + t.Fatalf("previous=%+v want %+v", got, want) + } + + views[2] = variant("deployment-previous", "canary", deploymentTestVersion, other, t0.Add(time.Minute), 1) + if got := svc.deploymentPreviousRelease(current, material, views); got == nil || got.ArtifactAvailable { + t.Fatalf("missing artifact reported available: %+v", got) + } + oldest := views[1] + if got := svc.deploymentPreviousRelease(oldest, projectDeploymentMaterial(oldest.ResourceKind, oldest.ResourceID, oldest.Spec), views); got != nil { + t.Fatalf("earliest release has a previous release: %+v", got) + } + + detail, err := svc.DeploymentDetail(created.DeploymentID, time.Now().UTC()) + if err != nil || detail.SchemaVersion != 4 || detail.PreviousRelease != nil { + t.Fatalf("single deployment detail=%+v err=%v", detail.PreviousRelease, err) + } +} diff --git a/internal/operator/deployment_test.go b/internal/operator/deployment_test.go index da030cd0..fc3a29dc 100644 --- a/internal/operator/deployment_test.go +++ b/internal/operator/deployment_test.go @@ -110,7 +110,7 @@ func TestProjectDeploymentPromotionKeepsCanaryNotSucceededOutOfThePassedCount(t // action preview that may finish a stable deployment, and Updates. Old strict // clients reject unknown fields, so all three schema versions move together. func TestIndependentPromotionFieldsComeWithNewSchemaVersions(t *testing.T) { - if DeploymentReadSchemaVersion != 3 || DeploymentPreviewSchemaVersion != 5 || + if DeploymentReadSchemaVersion != 4 || DeploymentPreviewSchemaVersion != 5 || DeploymentActionSchemaVersion != 4 || UpdateReadSchemaVersion != 5 { t.Fatalf("schema versions read=%d preview=%d action=%d updates=%d", DeploymentReadSchemaVersion, DeploymentPreviewSchemaVersion, @@ -291,9 +291,13 @@ func TestDeploymentActionEligibilityCountsOnlyTerminalFailuresForRetry(t *testin {MachineID: "failed", JobID: "failed-job", JobState: deploy.Failed, TerminalAt: &terminal, StuckKind: "terminal_failure"}, {MachineID: "silent", JobID: "silent-job", JobState: deploy.Running, StuckKind: "no_event"}, }} + views, err := st.ListDeployments(now) + if err != nil { + t.Fatal(err) + } actions, err := New(st).deploymentActionEligibility(view, DeploymentMaterialSummary{ Status: DeploymentMaterialRecorded, Version: &version, ArtifactDigest: &artifactDigest, - }, now) + }, views, now) if err != nil { t.Fatal(err) } @@ -329,9 +333,13 @@ func TestDeploymentActionEligibilityBlocksExhaustedControlRevision(t *testing.T) OpenedBatch: 2, TotalBatches: 3, } version, digest := "2026.9.2", "sha256:"+strings.Repeat("a", 64) + views, err := st.ListDeployments(time.Now().UTC()) + if err != nil { + t.Fatal(err) + } actions, err := New(st).deploymentActionEligibility(view, DeploymentMaterialSummary{ Status: DeploymentMaterialRecorded, Version: &version, ArtifactDigest: &digest, - }, time.Now().UTC()) + }, views, time.Now().UTC()) if err != nil { t.Fatal(err) } diff --git a/internal/operatoragent/tools.go b/internal/operatoragent/tools.go index 1450a202..bd670e92 100644 --- a/internal/operatoragent/tools.go +++ b/internal/operatoragent/tools.go @@ -859,6 +859,7 @@ func rolloutView(detail operator.DeploymentDetailResult) map[string]any { "opened_batch": detail.Item.OpenedBatch, "total_batches": detail.Item.TotalBatches, "canary": rollout.AssessCanary(canaryFromDetail(detail)), + "previous_release": detail.PreviousRelease, } } diff --git a/internal/operatorclient/deployments.go b/internal/operatorclient/deployments.go index a3fdcf7a..120b68e1 100644 --- a/internal/operatorclient/deployments.go +++ b/internal/operatorclient/deployments.go @@ -427,6 +427,14 @@ func validateDeploymentDetailResult(result operator.DeploymentDetailResult, depl retryTargets, continueAffected, openedFailed); err != nil { return err } + if previous := result.PreviousRelease; previous != nil { + if validateDeploymentClientIdentifier("previous_release.deployment_id", previous.DeploymentID, 256) != nil || + validateDeploymentClientIdentifier("previous_release.version", previous.Version, 128) != nil || + !artifact.ValidSHA256Hex(previous.ArtifactSHA256) || previous.DeploymentID == result.Item.DeploymentID || + (result.Item.Material.Version != nil && previous.Version == *result.Item.Material.Version) { + return errors.New("operator client: invalid deployment previous_release") + } + } return nil } diff --git a/internal/operatorclient/deployments_test.go b/internal/operatorclient/deployments_test.go index d0d581be..7b2b4911 100644 --- a/internal/operatorclient/deployments_test.go +++ b/internal/operatorclient/deployments_test.go @@ -648,6 +648,18 @@ func TestDeploymentClientRejectsPoisonedDetailTargetsAndActions(t *testing.T) { {"null verdict rollup", func(result *operator.DeploymentDetailResult) { result.Independent.Verdicts = nil }}, + {"previous release is this deployment", func(result *operator.DeploymentDetailResult) { + result.PreviousRelease = &operator.DeploymentPreviousRelease{DeploymentID: result.Item.DeploymentID, + Version: "2026.1.1", ArtifactSHA256: strings.Repeat("a", 64)} + }}, + {"previous release artifact is not a sha256", func(result *operator.DeploymentDetailResult) { + result.PreviousRelease = &operator.DeploymentPreviousRelease{DeploymentID: "deployment-0", + Version: "2026.1.1", ArtifactSHA256: "not-a-digest"} + }}, + {"previous release has the same version", func(result *operator.DeploymentDetailResult) { + result.PreviousRelease = &operator.DeploymentPreviousRelease{DeploymentID: "deployment-0", + Version: *result.Item.Material.Version, ArtifactSHA256: strings.Repeat("a", 64)} + }}, {"noncanonical exhausted blocker order", func(result *operator.DeploymentDetailResult) { deploymentClientMakeRunning(result, result.EvaluatedAt.Add(-time.Minute), false) deploymentClientMarkExhausted(result) @@ -666,6 +678,15 @@ func TestDeploymentClientRejectsPoisonedDetailTargetsAndActions(t *testing.T) { } } +func TestDeploymentClientAcceptsAPreviousRelease(t *testing.T) { + result := deploymentClientTestDetail() + result.PreviousRelease = &operator.DeploymentPreviousRelease{DeploymentID: "deployment-0", + Version: "2026.1.1", ArtifactSHA256: strings.Repeat("a", 64), ArtifactAvailable: true} + if err := validateDeploymentDetailResult(result, result.Item.DeploymentID); err != nil { + t.Fatalf("previous release rejected: %v", err) + } +} + func TestDeploymentClientAcceptsCanonicalExhaustedRevisionBlockers(t *testing.T) { result := deploymentClientTestDetail() deploymentClientMarkExhausted(&result) diff --git a/internal/rollout/expand.go b/internal/rollout/expand.go index cbd9ba1d..d04c4a7c 100644 --- a/internal/rollout/expand.go +++ b/internal/rollout/expand.go @@ -24,7 +24,7 @@ const ( // RollbackSentences is the honest rollback contract for a canary rollout. // Nothing in this package rolls a fleet back. Callers show this text as-is. var RollbackSentences = []string{ - "There is no automatic fleet rollback to the previous artifact.", + "Previous release deploys the version this channel ran before as a new deployment, with the same preview, canary, and verification.", "Abandon stops opening further jobs. Machines whose jobs already succeeded keep that result.", "failed means Hub closed a reversible job as returned to the previous version. manual_intervention has no rollback evidence. rejected means the machine did not apply the job. lease_expired means the agent stopped reporting and the machine contents are unknown.", "A new deployment pauses after its canary batch is succeeded. Expansion is an explicit Continue from the UI, CLI, or rollout_expand. Deployments created before that hold still let the driver open the next batch. Plain Continue refuses a failed batch. skip failed batch is a separate labelled action with its own preview digest and a recorded reason. MCP tools do not send that skip.", diff --git a/internal/rollout/expand_test.go b/internal/rollout/expand_test.go index 012a7560..ad44a635 100644 --- a/internal/rollout/expand_test.go +++ b/internal/rollout/expand_test.go @@ -140,7 +140,7 @@ func TestAssessCanaryRollbackTextIsStable(t *testing.T) { } } joined := strings.Join(got.Rollback, "\n") - for _, want := range []string{"no automatic fleet rollback", "manual_intervention", "lease_expired", "rollout_expand", "promotion gate", "finish_work"} { + for _, want := range []string{"Previous release deploys the version this channel ran before", "manual_intervention", "lease_expired", "rollout_expand", "promotion gate", "finish_work"} { if !strings.Contains(joined, want) { t.Fatalf("rollback missing %q: %s", want, joined) } diff --git a/internal/web/deployment_actions_web_test.go b/internal/web/deployment_actions_web_test.go index 990d1c9d..1bfa1ad1 100644 --- a/internal/web/deployment_actions_web_test.go +++ b/internal/web/deployment_actions_web_test.go @@ -13,6 +13,7 @@ import ( "github.com/teddashh/AI-Intune/internal/deploy" "github.com/teddashh/AI-Intune/internal/operator" + "github.com/teddashh/AI-Intune/internal/operatorauth" "github.com/teddashh/AI-Intune/internal/store" ) @@ -683,3 +684,48 @@ func TestDeploymentCreateReviewShowsCurrentToTargetVersion(t *testing.T) { } } } + +func TestDeploymentDetailOffersThePreviousReleaseThroughTheCreatePreview(t *testing.T) { + s, _ := newServer(t) + names, err := operatorauth.NamesForPrefix("example.com/cap/clawctl") + if err != nil { + t.Fatal(err) + } + sha := strings.Repeat("a", 64) + render := func(previous *operator.DeploymentPreviousRelease, granted operatorauth.CapabilityNames) string { + rec := httptest.NewRecorder() + req := requestWithCapabilities(http.MethodGet, "/deployments/deployment-current", granted) + s.render(rec, req, "deployment.html", page{ + Title: "deployment", Deployment: &deploymentPage{ + Summary: operator.DeploymentSummary{DeploymentID: "deployment-current", Channel: "canary"}, + PreviousRelease: previous, + }, + }) + return rec.Body.String() + } + available := &operator.DeploymentPreviousRelease{DeploymentID: "deployment-previous", Version: "2026.9.1", + ArtifactSHA256: sha, ArtifactAvailable: true} + body := render(available, names) + for _, want := range []string{ + `
`, + `name="channel" value="canary"`, `name="version" value="2026.9.1"`, `name="artifact_sha256" value="` + sha + `"`, + `name="batch_size" value="1"`, `name="execution_timeout_seconds" value="600"`, `name="irreversible" value="false"`, + "Preview 2026.9.1", `href="/deployments/deployment-previous"`, + } { + if !strings.Contains(body, want) { + t.Errorf("previous release missing %q", want) + } + } + if body := render(available, operatorauth.CapabilityNames{Operate: names.Operate}); strings.Contains(body, `action="/deployments/preview"`) { + t.Error("operator without admin sees the create form") + } + missing := *available + missing.ArtifactAvailable = false + if body := render(&missing, names); strings.Contains(body, `action="/deployments/preview"`) || + !strings.Contains(body, `取得 OpenClaw 2026.9.1`) { + t.Errorf("missing artifact view: %s", body) + } + if body := render(nil, names); !strings.Contains(body, "這個 channel 沒有更早的成功版本。") { + t.Errorf("no previous release view: %s", body) + } +} diff --git a/internal/web/interface_copy_test.go b/internal/web/interface_copy_test.go index b9f15f81..5f5f77dd 100644 --- a/internal/web/interface_copy_test.go +++ b/internal/web/interface_copy_test.go @@ -17,6 +17,7 @@ import ( ) var forbiddenInterfaceCopy = []string{ + "There is no automatic fleet rollback", "They do not prove that a provider will accept the next request", "An administrator can start a sign-in", "Human admin required", diff --git a/internal/web/rollout.go b/internal/web/rollout.go index 24f7928b..c9a440d2 100644 --- a/internal/web/rollout.go +++ b/internal/web/rollout.go @@ -53,6 +53,7 @@ type deploymentActionEligibility struct { type deploymentPage struct { Summary operator.DeploymentSummary + PreviousRelease *operator.DeploymentPreviousRelease Version string Status string JobCounts []deploymentJobCount @@ -269,7 +270,7 @@ func (s *Server) deployment(w http.ResponseWriter, r *http.Request) { return } dp := &deploymentPage{ - Summary: detail.Item, Version: deploymentMaterialVersion(detail.Item.Material), + Summary: detail.Item, PreviousRelease: detail.PreviousRelease, Version: deploymentMaterialVersion(detail.Item.Material), Status: deploymentStatus(detail.Item), JobCounts: deploymentSafeJobCounts(detail.Item.DeploymentID, detail.Item.JobStateCounts), JobsURL: deploymentJobsURL(detail.Item.DeploymentID), RestartCount: hubRestartCount(events), diff --git a/internal/web/templates/deployment.html b/internal/web/templates/deployment.html index 0491be2e..24cad60a 100644 --- a/internal/web/templates/deployment.html +++ b/internal/web/templates/deployment.html @@ -123,6 +123,29 @@

Retry terminal failures

{{end}} {{end}} +

Previous release

+ {{with $d.PreviousRelease}} +

上一版 {{.Version}}({{short .DeploymentID 8}})。

+ {{if .ArtifactAvailable}} + {{if $.Access.CanAdmin}} + + + + + + + + + +
+ {{end}} + {{else}} +

Artifact 不在 Hub。先取得 OpenClaw {{.Version}},再回到這裡預覽。

+ {{end}} + {{else}} +

這個 channel 沒有更早的成功版本。

+ {{end}} +

Abandon

{{$d.Abandon.Reason}}

{{if $d.Abandon.Eligible}}