carlos / platform Public

Copy a shipped release between consoles (#1389)

Production can now run the exact bytes staging tested, without a rebuild.

- carlos releases pull <version> --app <a> --out <dir> copies a release's
  manifest and files out of a console, checking each file's size and
  sha256; a per-directory lock and no-replace publish keep a directory
  with manifest.json complete.
- carlos ship --from-release <dir> ships it into another console under
  the same version and settings, sending expect_artifacts; the console
  hashes what arrives and stores nothing if any file differs. Each
  console writes its own manifest and signs its own pointers.
- Console: GET .../releases/{version}/manifest and .../artifacts/{file}
  for publish and deploy credentials; linked tokens refused.
- Docs: "Staging tests X, production promotes X" CI recipe; release runs
  once per instance per deploy, not once per copy.

Reviewed by Astra per task and whole-branch; root-read and record-write
census approved by Astra (#280); copy by Luna under Paul's delegation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Prompts:

  <task-notification>
  <task-id>b321ki5bz</task-id>
  <tool-use-id>toolu_012FARTVjY1KbbVF7csraNUz</tool-use-id>
  <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a88005ac-72e4-481c-884f-581940b8c2c5/tasks/b321ki5bz.output</output-file>
  <status>killed</status>
  <summary>Background command "until [ -f /home/paulca/amadan.net/carlos/platform/.claude/worktrees/release-copy-across-consoles/.superpowers/sdd/2026-11-25-release-copy-across-consoles/task-1-report.md ]; do sleep 20; done; echo report-written" was stopped after reaching its background time limit</summary>
  <note>If the work in progress still needs it, start it again with `run_in_background` and a longer `timeout`. If it already had the longest `timeout` allowed, do not restart it. Either way, report that it was stopped.</note>
  </task-notification>

  <task-notification>
  <task-id>a42023144c00d694c</task-id>
  <tool-use-id>toolu_01Boj8YsnNawNw6FuhorJcXT</tool-use-id>
  <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a88005ac-72e4-481c-884f-581940b8c2c5/tasks/a42023144c00d694c.output</output-file>
  <status>completed</status>
  <summary>Agent "Implement Task 1: read doors" finished</summary>
  <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note>
  <result>Status: DONE_WITH_CONCERNS
  
  Commit: 7688f618 console: read doors for a release's manifest and artifacts
  
  Tests: the 7 targeted tests (6 new, plus TestDeployReachesExactlyItsDoors) failed before the change (404s and the deploy-doors mismatch) and pass now. TestParity, TestDeployIsBoundToItsApp and the console tests that read through the test store also pass. gofmt and vet are clean.
  
  Concerns:
  1. The brief expects `..bad/manifest` to give 400, but `release.ValidVersion` accepts `..bad`. I kept ValidVersion: the test now expects 404 for `..bad` and checks the 400 with `bad!v` instead.
  2. The console test store (`deletableStore`) could not stream, so `OpenObjectStreaming` failed in tests. I added an opt-in streaming `Open` to it in `view_test.go`; only the new tests turn it on, so other tests read as before.
  3. I read the brief's "deploy token bound to `other`" as the fixture's token for `hello` asking for the existing app `other` (404).
  4. `git commit` warned that a `packed-refs.lock` already existed, but the commit landed and the tree is clean. The lock predates my commit, so I left it alone.
  
  Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/release-copy-across-consoles/.superpowers/sdd/2026-11-25-release-copy-across-consoles/task-1-report.md</result>
  <usage><subagent_tokens>106544</subagent_tokens><tool_uses>36</tool_uses><duration_ms>859613</duration_ms></usage>
  </task-notification>

  … and 18 more, on the branch's Prompts tab.

Squashed from release-copy-across-consoles into main.
claude agent, operated by paul@keymail.dev 65951fbbdedcb1c5dffc925ff1148d947e14b5f9 parent bac71e0
35 files changed, +2,729 −29
  • .superpowers/sdd/2026-11-25-release-copy-across-consoles/luna-apply-report.md +11 −0
  • cli.go +11 −0
  • commands.go +3 −2
  • docs/parity.md +3 −2
  • docs/site/cli.md +69 −1
  • docs/site/stateless-replicas.md +1 −1
  • docs/superpowers/notes/census-proposal-release-copy-across-consoles.md +29 −0
  • docs/superpowers/plans/2026-11-25-release-copy-across-consoles.md +221 −0
  • internal/console/apicli.go +5 −18
  • internal/console/apirelease_read.go +125 −0
  • internal/console/apirelease_read_test.go +190 −0
  • internal/console/apiship_expect.go +136 −0
  • internal/console/apiship_expect_test.go +228 −0
  • internal/console/apiship_rootfs.go +4 −0
  • internal/console/claim_invariant_fixtures_test.go +4 −0
  • internal/console/claim_invariant_probes_read_test.go +4 −0
  • internal/console/deploydoors_test.go +3 −0
  • internal/console/linkedpolicy.go +2 −0
  • internal/console/links_auth_test.go +1 −0
  • internal/console/routedecls.go +6 −0
  • internal/console/server.go +6 −2
  • internal/console/testdata/claim-routes.txt +2 −0
  • internal/console/view_test.go +23 −0
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/release_copy_census_test.go +40 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-release-copy-across-consoles.tsv +20 −0
  • parity/cli.tsv +1 −0
  • parity/parity.tsv +1 −0
  • release_copy_e2e_test.go +352 −0
  • release_pull.go +358 −0
  • release_pull_test.go +367 −0
  • ship_from_release.go +364 −0
  • ship_from_release_test.go +133 −0
  • testdata/clireg-golden.jsonl +4 −2

CI failed — run details

CI log
=== gate ===
go: downloading go1.26.10 (linux/arm64)
go version go1.26.10 linux/arm64
opentofu: arm64, tofu 1.13.9, aws 6.73.0, archive 2.8.1
  tofu: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/tofu_1.13.9_linux_arm64.tar.gz
  tofu: downloaded, digest verified
  aws: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/terraform-provider-aws_6.73.0_linux_arm64.zip
  aws: downloaded, digest verified
  archive: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/terraform-provider-archive_2.8.1_linux_arm64.zip
  archive: downloaded, digest verified
  installed in /tmp/carlos-opentofu-2PJAEZ
.amadan/test-gate.sh
go: downloading github.com/aws/aws-sdk-go-v2 v1.44.0
go: downloading github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.68.0
go: downloading github.com/aws/aws-sdk-go-v2/service/costexplorer v1.67.5
go: downloading github.com/aws/aws-sdk-go-v2/service/s3 v1.105.0
go: downloading github.com/aws/smithy-go v1.28.1
go: downloading github.com/benbjohnson/litestream v0.5.14
go: downloading github.com/superfly/ltx v0.5.1
go: downloading golang.org/x/net v0.62.0
go: downloading modernc.org/sqlite v1.55.0
go: downloading github.com/aws/aws-sdk-go-v2/service/sns v1.43.0
go: downloading github.com/aws/aws-sdk-go-v2/service/acm v1.45.0
go: downloading github.com/aws/aws-sdk-go-v2/service/ec2 v1.324.0
go: downloading github.com/aws/aws-sdk-go-v2/service/iam v1.58.2
go: downloading github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi v1.37.0
go: downloading github.com/aws/aws-sdk-go-v2/service/route53 v1.64.1
go: downloading github.com/aws/aws-sdk-go-v2/service/sts v1.45.6
go: downloading golang.org/x/sys v0.49.0
go: downloading golang.org/x/crypto v0.58.0
go: downloading github.com/aws/aws-sdk-go-v2/service/sesv2 v1.66.6
go: downloading github.com/pion/stun/v3 v3.1.5
go: downloading github.com/pion/turn/v4 v4.1.4
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.40
go: downloading github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.40
go: downloading github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.38
go: downloading github.com/klauspost/compress v1.20.2
go: downloading golang.org/x/text v0.43.0
go: downloading github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.40
go: downloading golang.org/x/sync v0.24.0
go: downloading github.com/prometheus/client_golang v1.17.0
go: downloading github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.20.18
go: downloading github.com/lmittmann/tint v1.1.3
go: downloading github.com/prometheus/client_model v0.5.0
go: downloading github.com/beorn7/perks v1.0.1
go: downloading github.com/prometheus/procfs v0.12.0
go: downloading github.com/prometheus/common v0.45.0
go: downloading google.golang.org/protobuf v1.36.10
go: downloading github.com/cespare/xxhash/v2 v2.3.0
go: downloading github.com/pion/transport/v4 v4.0.2
go: downloading github.com/pion/dtls/v3 v3.1.4
go: downloading github.com/wlynxg/anet v0.0.5
go: downloading golang.org/x/crypto/x509roots/fallback v0.0.0-20260209214922-2f26647a795e
go: downloading modernc.org/sqlite v1.55.0
go: downloading github.com/klauspost/compress v1.20.2
go: downloading github.com/aws/aws-sdk-go-v2/service/ecs v1.91.0
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading github.com/pion/dtls/v3 v3.1.4
go: downloading modernc.org/libc v1.74.1
go: downloading modernc.org/libc v1.74.1
go: downloading github.com/dustin/go-humanize v1.0.1
go: downloading github.com/google/uuid v1.6.0
go: downloading modernc.org/memory v1.11.0
go: downloading modernc.org/mathutil v1.7.1
go: downloading modernc.org/memory v1.11.0
go: downloading github.com/google/uuid v1.6.0
go: downloading github.com/dustin/go-humanize v1.0.1
go: downloading modernc.org/mathutil v1.7.1
=== launchctx (4 s, from +0 s)
ok  	amadan.net/carlos/platform.git/launchctx	0.016s
?   	amadan.net/carlos/platform.git/launchctx/controlname	[no test files]
?   	amadan.net/carlos/platform.git/launchctx/wireid	[no test files]
=== vet (172 s, from +0 s)
go: downloading modernc.org/sqlite v1.55.0
go: downloading github.com/aws/aws-sdk-go-v2/service/ecs v1.91.0
go: downloading github.com/klauspost/compress v1.20.2
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading golang.org/x/crypto/x509roots/fallback v0.0.0-20260209214922-2f26647a795e
go: downloading github.com/pion/dtls/v3 v3.1.4
go: downloading modernc.org/libc v1.74.1
go: downloading github.com/dustin/go-humanize v1.0.1
go: downloading modernc.org/memory v1.11.0
go: downloading github.com/google/uuid v1.6.0
go: downloading modernc.org/mathutil v1.7.1
go: downloading github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec
=== vet-tags (177 s, from +0 s)
go: downloading github.com/klauspost/compress v1.20.2
go: downloading golang.org/x/crypto/x509roots/fallback v0.0.0-20260209214922-2f26647a795e
go: downloading modernc.org/sqlite v1.55.0
go: downloading github.com/aws/aws-sdk-go-v2/service/ecs v1.91.0
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading github.com/pion/dtls/v3 v3.1.4
go: downloading modernc.org/libc v1.74.1
go: downloading github.com/dustin/go-humanize v1.0.1
go: downloading modernc.org/memory v1.11.0
go: downloading modernc.org/mathutil v1.7.1
go: downloading github.com/google/uuid v1.6.0
go: downloading github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec
=== gofmt (1 s, from +0 s)
gofmt -l .: clean
=== rest (387 s, from +14 s)
ok  	github.com/carlosframework/platform/cmd/carlos-media	124.734s
?   	github.com/carlosframework/platform/cmd/changelog	[no test files]
ok  	github.com/carlosframework/platform/cmd/console	205.423s
ok  	github.com/carlosframework/platform/cmd/mediaimage	40.533s
ok  	github.com/carlosframework/platform/cmd/moveprobe	14.848s
ok  	github.com/carlosframework/platform/cmd/pricebook-export	0.060s
ok  	github.com/carlosframework/platform/cmd/rootfswitness	0.169s
ok  	github.com/carlosframework/platform/cmd/runsc-assets	0.185s
ok  	github.com/carlosframework/platform/cmd/zddprobe	0.915s
ok  	github.com/carlosframework/platform/internal/agentsock	0.099s
ok  	github.com/carlosframework/platform/internal/alerting	0.033s
ok  	github.com/carlosframework/platform/internal/analytics	0.333s
ok  	github.com/carlosframework/platform/internal/appconfig	42.011s
ok  	github.com/carlosframework/platform/internal/apperr	0.361s
ok  	github.com/carlosframework/platform/internal/applog	0.483s
ok  	github.com/carlosframework/platform/internal/apppolicy	2.309s
ok  	github.com/carlosframework/platform/internal/assetcache	0.497s
ok  	github.com/carlosframework/platform/internal/awsinv	0.020s
ok  	github.com/carlosframework/platform/internal/awsmanaged	0.653s
ok  	github.com/carlosframework/platform/internal/awsregiongroup	0.697s
ok  	github.com/carlosframework/platform/internal/awsterminations	0.023s
ok  	github.com/carlosframework/platform/internal/backupswords	0.024s
ok  	github.com/carlosframework/platform/internal/billing	0.153s
ok  	github.com/carlosframework/platform/internal/billing/billingtest	0.108s
ok  	github.com/carlosframework/platform/internal/billingstripe	1.956s
ok  	github.com/carlosframework/platform/internal/boxchoice	0.035s
ok  	github.com/carlosframework/platform/internal/boxid	1.754s
?   	github.com/carlosframework/platform/internal/boxid/boxidtest	[no test files]
?   	github.com/carlosframework/platform/internal/boxid/internal/signtest	[no test files]
ok  	github.com/carlosframework/platform/internal/boxroles	0.012s
ok  	github.com/carlosframework/platform/internal/boxself	0.217s
ok  	github.com/carlosframework/platform/internal/boxvolumes	0.066s
ok  	github.com/carlosframework/platform/internal/caps	3.807s
ok  	github.com/carlosframework/platform/internal/certwarm	0.017s
ok  	github.com/carlosframework/platform/internal/cgroup	1.415s
ok  	github.com/carlosframework/platform/internal/changelog	4.216s
ok  	github.com/carlosframework/platform/internal/clamd	0.065s
?   	github.com/carlosframework/platform/internal/cliflag	[no test files]
ok  	github.com/carlosframework/platform/internal/clireg	0.013s
ok  	github.com/carlosframework/platform/internal/codehealth	14.573s
ok  	github.com/carlosframework/platform/internal/compute	0.016s
ok  	github.com/carlosframework/platform/internal/consolefleet	0.012s
?   	github.com/carlosframework/platform/internal/controlname	[no test files]
?   	github.com/carlosframework/platform/internal/controlsock	[no test files]
ok  	github.com/carlosframework/platform/internal/dbdoor	11.293s
ok  	github.com/carlosframework/platform/internal/dbdoor/dbdoortest	0.039s
ok  	github.com/carlosframework/platform/internal/dbquery	0.024s
ok  	github.com/carlosframework/platform/internal/dbreads	3.330s
?   	github.com/carlosframework/platform/internal/dbreads/dbreadstest	[no test files]
ok  	github.com/carlosframework/platform/internal/dbverify	0.021s
ok  	github.com/carlosframework/platform/internal/demo	0.029s
ok  	github.com/carlosframework/platform/internal/demobuild	2.812s
ok  	github.com/carlosframework/platform/internal/democlaim	0.397s
ok  	github.com/carlosframework/platform/internal/devbox	15.781s
ok  	github.com/carlosframework/platform/internal/dnsrec	0.020s
ok  	github.com/carlosframework/platform/internal/docsite	0.113s
ok  	github.com/carlosframework/platform/internal/domainreg	0.020s
ok  	github.com/carlosframework/platform/internal/domains	65.044s
ok  	github.com/carlosframework/platform/internal/doorkey	0.050s
ok  	github.com/carlosframework/platform/internal/economics	0.014s
ok  	github.com/carlosframework/platform/internal/edgefence	0.107s
ok  	github.com/carlosframework/platform/internal/edgeguard	0.192s
?   	github.com/carlosframework/platform/internal/edgeproof	[no test files]
ok  	github.com/carlosframework/platform/internal/edgesfile	0.107s
ok  	github.com/carlosframework/platform/internal/egressaddr	0.017s
ok  	github.com/carlosframework/platform/internal/execsandbox	96.597s
ok  	github.com/carlosframework/platform/internal/fileacl	0.010s
ok  	github.com/carlosframework/platform/internal/fleetapi	1.971s
ok  	github.com/carlosframework/platform/internal/fleetstore	0.012s
ok  	github.com/carlosframework/platform/internal/fxrate	0.024s
ok  	github.com/carlosframework/platform/internal/gate	4.018s
ok  	github.com/carlosframework/platform/internal/genselect	0.069s
ok  	github.com/carlosframework/platform/internal/geo	0.085s
ok  	github.com/carlosframework/platform/internal/geoip	0.105s
ok  	github.com/carlosframework/platform/internal/groupadmission	0.016s
ok  	github.com/carlosframework/platform/internal/grouprollaws	16.786s
ok  	github.com/carlosframework/platform/internal/hadeparture	0.044s
ok  	github.com/carlosframework/platform/internal/hafresh	0.026s
ok  	github.com/carlosframework/platform/internal/hairpin	0.251s
ok  	github.com/carlosframework/platform/internal/historyreadback	0.852s
ok  	github.com/carlosframework/platform/internal/hostactors	20.072s
ok  	github.com/carlosframework/platform/internal/hostbox	22.228s
ok  	github.com/carlosframework/platform/internal/hostclaim	2.338s
ok  	github.com/carlosframework/platform/internal/hostenv	0.066s
ok  	github.com/carlosframework/platform/internal/hostevidence	0.028s
ok  	github.com/carlosframework/platform/internal/hostexec	22.662s
ok  	github.com/carlosframework/platform/internal/hostfence	0.173s
ok  	github.com/carlosframework/platform/internal/hostfiles	23.967s
ok  	github.com/carlosframework/platform/internal/hostfloor	0.063s
ok  	github.com/carlosframework/platform/internal/hostguard	1.563s
ok  	github.com/carlosframework/platform/internal/hostops	8.398s
?   	github.com/carlosframework/platform/internal/hostops/fencerelease	[no test files]
ok  	github.com/carlosframework/platform/internal/hostops/internal/fencerelease	0.007s
ok  	github.com/carlosframework/platform/internal/hostquarantine	0.013s
ok  	github.com/carlosframework/platform/internal/hostrelocate	1.867s
ok  	github.com/carlosframework/platform/internal/hostresolve	0.748s
ok  	github.com/carlosframework/platform/internal/hostwrite	0.011s
ok  	github.com/carlosframework/platform/internal/infraview	0.011s
ok  	github.com/carlosframework/platform/internal/ingresshealth	0.020s
ok  	github.com/carlosframework/platform/internal/ingresshealth/awstg	0.007s
ok  	github.com/carlosframework/platform/internal/instancectl	55.466s
ok  	github.com/carlosframework/platform/internal/instanceexec	8.889s
ok  	github.com/carlosframework/platform/internal/instancefs	0.031s
ok  	github.com/carlosframework/platform/internal/instancekey	0.009s
ok  	github.com/carlosframework/platform/internal/instanceupdates	0.024s
ok  	github.com/carlosframework/platform/internal/interactive	0.716s
ok  	github.com/carlosframework/platform/internal/launchd	0.011s
ok  	github.com/carlosframework/platform/internal/layout	21.507s
ok  	github.com/carlosframework/platform/internal/layout/pubclass	102.750s
ok  	github.com/carlosframework/platform/internal/lbhealth	0.025s
2026/11/25 11:35:28 INFO replica sync db=source.db replica=file txid.replica=0000000000000000 txid.db=0000000000000001
2026/11/25 11:35:28 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000001 maxTXID=0000000000000001 size=1041
2026/11/25 11:35:28 INFO replica sync db=source.db replica=file txid.replica=0000000000000001 txid.db=0000000000000002
2026/11/25 11:35:28 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000002 maxTXID=0000000000000002 size=1072
2026/11/25 11:35:28 INFO replica sync db=source.db replica=file txid.replica=0000000000000002 txid.db=0000000000000003
2026/11/25 11:35:28 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000003 maxTXID=0000000000000003 size=1234
2026/11/25 11:35:28 INFO replica sync db=source.db replica=file txid.replica=0000000000000003 txid.db=0000000000000003
2026/11/25 11:35:28 INFO replica sync db=source.db replica=file txid.replica=0000000000000000 txid.db=0000000000000001
2026/11/25 11:35:28 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000001 maxTXID=0000000000000001 size=1041
2026/11/25 11:35:28 INFO replica sync db=source.db replica=file txid.replica=0000000000000001 txid.db=0000000000000002
2026/11/25 11:35:28 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000002 maxTXID=0000000000000002 size=1072
2026/11/25 11:35:28 INFO replica sync db=source.db replica=file txid.replica=0000000000000002 txid.db=0000000000000003
2026/11/25 11:35:28 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000003 maxTXID=0000000000000003 size=1234
2026/11/25 11:35:28 INFO replica sync db=source.db replica=file txid.replica=0000000000000003 txid.db=0000000000000003
2026/11/25 11:35:28 INFO replica sync db=source.db replica=file txid.replica=0000000000000000 txid.db=0000000000000001
2026/11/25 11:35:28 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000001 maxTXID=0000000000000001 size=1041
2026/11/25 11:35:28 INFO replica sync db=source.db replica=file txid.replica=0000000000000001 txid.db=0000000000000002
2026/11/25 11:35:28 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000002 maxTXID=0000000000000002 size=1072
2026/11/25 11:35:28 INFO replica sync db=source.db replica=file txid.replica=0000000000000002 txid.db=0000000000000003
2026/11/25 11:35:28 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000003 maxTXID=0000000000000003 size=1234
2026/11/25 11:35:28 INFO replica sync db=source.db replica=file txid.replica=0000000000000003 txid.db=0000000000000003
2026/11/25 11:35:29 INFO replica sync db=source.db replica=file txid.replica=0000000000000000 txid.db=0000000000000001
2026/11/25 11:35:29 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000001 maxTXID=0000000000000001 size=1041
2026/11/25 11:35:29 INFO replica sync db=source.db replica=file txid.replica=0000000000000001 txid.db=0000000000000002
2026/11/25 11:35:29 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000002 maxTXID=0000000000000002 size=1072
2026/11/25 11:35:29 INFO replica sync db=source.db replica=file txid.replica=0000000000000002 txid.db=0000000000000003
2026/11/25 11:35:29 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000003 maxTXID=0000000000000003 size=1234
2026/11/25 11:35:29 INFO replica sync db=source.db replica=file txid.replica=0000000000000003 txid.db=0000000000000003
2026/11/25 11:35:29 INFO replica sync db=source.db replica=file txid.replica=0000000000000000 txid.db=0000000000000001
2026/11/25 11:35:29 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000001 maxTXID=0000000000000001 size=1041
2026/11/25 11:35:29 INFO replica sync db=source.db replica=file txid.replica=0000000000000001 txid.db=0000000000000002
2026/11/25 11:35:29 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000002 maxTXID=0000000000000002 size=1072
2026/11/25 11:35:29 INFO replica sync db=source.db replica=file txid.replica=0000000000000002 txid.db=0000000000000003
2026/11/25 11:35:29 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000003 maxTXID=0000000000000003 size=1234
2026/11/25 11:35:29 INFO replica sync db=source.db replica=file txid.replica=0000000000000003 txid.db=0000000000000003
2026/11/25 11:35:29 INFO replica sync db=source.db replica=file txid.replica=0000000000000000 txid.db=0000000000000001
2026/11/25 11:35:29 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000001 maxTXID=0000000000000001 size=1041
2026/11/25 11:35:29 INFO replica sync db=source.db replica=file txid.replica=0000000000000001 txid.db=0000000000000002
2026/11/25 11:35:29 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000002 maxTXID=0000000000000002 size=1072
2026/11/25 11:35:29 INFO replica sync db=source.db replica=file txid.replica=0000000000000002 txid.db=0000000000000003
2026/11/25 11:35:29 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000003 maxTXID=0000000000000003 size=1234
2026/11/25 11:35:29 INFO replica sync db=source.db replica=file txid.replica=0000000000000003 txid.db=0000000000000003
2026/11/25 11:35:29 INFO replica sync db=source.db replica=file txid.replica=0000000000000000 txid.db=0000000000000001
2026/11/25 11:35:29 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000001 maxTXID=0000000000000001 size=1041
2026/11/25 11:35:29 INFO replica sync db=source.db replica=file txid.replica=0000000000000001 txid.db=0000000000000002
2026/11/25 11:35:29 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000002 maxTXID=0000000000000002 size=1072
2026/11/25 11:35:29 INFO replica sync db=source.db replica=file txid.replica=0000000000000002 txid.db=0000000000000003
2026/11/25 11:35:29 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000003 maxTXID=0000000000000003 size=1234
2026/11/25 11:35:29 INFO replica sync db=source.db replica=file txid.replica=0000000000000003 txid.db=0000000000000003
2026/11/25 11:35:29 INFO replica sync db=source.db replica=file txid.replica=0000000000000000 txid.db=0000000000000001
2026/11/25 11:35:29 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000001 maxTXID=0000000000000001 size=1041
2026/11/25 11:35:29 INFO replica sync db=source.db replica=file txid.replica=0000000000000001 txid.db=0000000000000002
2026/11/25 11:35:29 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000002 maxTXID=0000000000000002 size=1072
2026/11/25 11:35:29 INFO replica sync db=source.db replica=file txid.replica=0000000000000002 txid.db=0000000000000003
2026/11/25 11:35:29 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000003 maxTXID=0000000000000003 size=1234
2026/11/25 11:35:29 INFO replica sync db=source.db replica=file txid.replica=0000000000000003 txid.db=0000000000000003
2026/11/25 11:35:29 lease: one.example: acquired in 3ms (client 0s, lock read and write 3ms)
2026/11/25 11:35:29 lease: /tmp/TestHeldCheckpointVacuumRestoreAndTransfer4293988531/001/source.db: continuity with the last clean close not proven; snapshot 1-0000000000000002 written before serving
2026/11/25 11:35:29 lease: one.example: acquired in 7ms (client 0s, lock read and write 7ms)
2026/11/25 11:35:29 lease: one.example: acquired in 19ms (client 0s, lock read and write 18ms)
2026/11/25 11:35:29 ERROR shutdown sync failed after timeout system=store db=source.db attempts=1 duration=12.124µs error="write ltx file: synthetic replica write refusal"
2026/11/25 11:35:29 lease: one.example: acquired in 1ms (client 0s, lock read and write 1ms)
2026/11/25 11:35:32 lease: one.example: acquired in 3ms (client 0s, lock read and write 3ms)
2026/11/25 11:35:32 lease: one.example: acquired in 127ms (client 0s, lock read and write 127ms)
2026/11/25 11:35:33 lease: one.example: acquired in 13ms (client 0s, lock read and write 13ms)
2026/11/25 11:35:33 ERROR shutdown sync failed after timeout system=store db=source.db attempts=1 duration=21.809µs error="write ltx file: context canceled"
2026/11/25 11:35:33 lease: one.example: acquired in 6ms (client 0s, lock read and write 6ms)
2026/11/25 11:35:33 ERROR shutdown sync failed after timeout system=store db=001 attempts=1 duration=209.857µs error="calc pos: max ltx file: operation error S3: ListObjectsV2, context canceled"
2026/11/25 11:35:33 lease: one.example: acquired in 1ms (client 0s, lock read and write 1ms)
2026/11/25 11:35:33 ERROR shutdown sync failed after timeout system=store db=source.db attempts=1 duration=53.411µs error="write ltx file: synthetic final tail upload failure"
2026/11/25 11:35:33 lease: one.example: acquired in 1ms (client 0s, lock read and write 1ms)
2026/11/25 11:35:34 lease: one.example: acquired in 6ms (client 0s, lock read and write 6ms)
2026/11/25 11:35:35 INFO replica sync db=source.db replica=file txid.replica=0000000000000000 txid.db=0000000000000001
2026/11/25 11:35:35 INFO ltx file uploaded db=source.db replica=file level=0 minTXID=0000000000000001 maxTXID=0000000000000001 size=1042
2026/11/25 11:35:35 INFO replica sync db=source.db replica=file txid.replica=0000000000000001 txid.db=0000000000000001
2026/11/25 11:35:35 lease: one.example: acquired in 8ms (client 0s, lock read and write 8ms)
2026/11/25 11:35:35 lease: one.example: acquired in 4ms (client 0s, lock read and write 4ms)
2026/11/25 11:35:37 lease: one.example: acquired in 1ms (client 0s, lock read and write 1ms)
2026/11/25 11:35:38 lease: one.example: acquired in 1ms (client 0s, lock read and write 1ms)
2026/11/25 11:35:38 lease: /tmp/TestFullImageBudgetScalesWithDatabaseSize3066029693/001/app.db: continuity with the last clean close not proven; snapshot 1-0000000000000003 written before serving
2026/11/25 11:35:39 lease: one.example: acquired in 2ms (client 0s, lock read and write 2ms)
2026/11/25 11:35:39 lease: one.example: acquired in 2ms (client 0s, lock read and write 1ms)
2026/11/25 11:35:39 lease: one.example: acquired in 13ms (client 0s, lock read and write 13ms)
2026/11/25 11:35:39 ERROR compaction failed system=store db=app.db level=9 error="upload refused"
2026/11/25 11:35:39 ERROR monitor error system=store db=app.db replica=file error="write ltx file: upload refused" consecutive_errors=1 backoff=1s
2026/11/25 11:35:40 ERROR shutdown sync failed after timeout system=store db=app.db attempts=1 duration=26.425µs error="write ltx file: upload refused"
2026/11/25 11:35:40 lease: one.example: acquired in 5ms (client 0s, lock read and write 5ms)
2026/11/25 11:35:40 lease: one.example: acquired in 1ms (client 0s, lock read and write 1ms)
2026/11/25 11:35:40 ERROR compaction failed system=store db=app.db level=2 error="write ltx file: upload refused"
2026/11/25 11:35:41 ERROR monitor error system=store db=app.db replica=file error="write ltx file: upload refused" consecutive_errors=1 backoff=1s
2026/11/25 11:35:41 ERROR shutdown sync failed after timeout system=store db=app.db attempts=1 duration=51.765µs error="write ltx file: upload refused"
2026/11/25 11:35:41 lease: one.example: acquired in 6ms (client 0s, lock read and write 6ms)
2026/11/25 11:35:41 lease: one.example: acquired in 1ms (client 0s, lock read and write 1ms)
2026/11/25 11:35:41 ERROR compaction failed system=store db=app.db level=9 error="fetch dst level info: cannot determine L9 max ltx file for \"/tmp/TestPinnedReplicateRetriesATransientReplicaRead1406677080/001/app.db\": listing failed once"
2026/11/25 11:35:41 lease: one.example: acquired in 11ms (client 0s, lock read and write 7ms)
2026/11/25 11:35:42 lease: one.example: acquired in 1ms (client 0s, lock read and write 1ms)
2026/11/25 11:35:42 lease: /tmp/TestReplicateAfterUnreplicatedWALRestartRestoresWhole501059133831/001/app.db: continuity with the last clean close not proven; snapshot 1-0000000000000003 written before serving
2026/11/25 11:35:42 lease: one.example: acquired in 6ms (client 0s, lock read and write 6ms)
2026/11/25 11:35:43 lease: one.example: acquired in 17ms (client 6ms, lock read and write 11ms)
2026/11/25 11:35:43 lease: /tmp/TestReplicateAfterUnreplicatedWALRestartRestoresWhole200002255744891/001/app.db: continuity with the last clean close not proven; snapshot 1-0000000000000003 written before serving
2026/11/25 11:35:43 lease: one.example: acquired in 1ms (client 0s, lock read and write 1ms)
2026/11/25 11:35:44 lease: one.example: acquired in 11ms (client 0s, lock read and write 11ms)
2026/11/25 11:35:44 lease: one.example: acquired in 1ms (client 0s, lock read and write 1ms)
2026/11/25 11:35:46 lease: one.example: acquired in 3ms (client 0s, lock read and write 2ms)
2026/11/25 11:35:46 lease: one.example: acquired in 1ms (client 0s, lock read and write 1ms)
2026/11/25 11:35:47 lease: /tmp/TestReplicateWithoutLocalMetadataRestoresWhole3521486139/001/app.db: continuity with the last clean close not proven; snapshot 1-0000000000000003 written before serving
2026/11/25 11:35:47 lease: one.example: acquired in 2ms (client 0s, lock read and write 2ms)
2026/11/25 11:35:48 lease: one.example: acquired in 2ms (client 0s, lock read and write 2ms)
2026/11/25 11:35:48 lease: one.example: acquired in 1ms (client 0s, lock read and write 1ms)
2026/11/25 11:35:49 lease: one.example: acquired in 10ms (client 0s, lock read and write 10ms)
2026/11/25 11:35:51 lease: one.example: acquired in 2ms (client 0s, lock read and write 2ms)
2026/11/25 11:35:51 lease: /tmp/TestCheckpointAcrossGapRestoresWhole3814958986/001/app.db: continuity with the last clean close not proven; snapshot 1-0000000000000003 written before serving
2026/11/25 11:35:51 lease: inst/example.com: acquired in 1ms (client 0s, lock read and write 1ms)
2026/11/25 11:35:51 lease: inst/x.example.com: acquired in 1ms (client 0s, lock read and write 1ms)
2026/11/25 11:35:51 lease: inst/x.example.com: acquired in 2ms (client 0s, lock read and write 2ms)
2026/11/25 11:35:51 lease: : this process did not run for 1s (pause limit 300ms): giving the lease up unrenewed; it expires at 2026-11-25T11:35:54Z
2026/11/25 11:35:56 lease: one.example: acquired in 6ms (client 1ms, lock read and write 5ms)
2026/11/25 11:35:58 lease: one.example: this process did not run for 1.502s (pause limit 400ms): giving the lease up unrenewed; it expires at 2026-11-25T11:36:00Z
2026/11/25 11:35:59 lease: one.example: acquired in 6ms (client 0s, lock read and write 5ms)
2026/11/25 11:36:00 lease: one.example: acquired in 6ms (client 0s, lock read and write 5ms)
2026/11/25 11:36:01 lease: one.example: acquired in 1ms (client 0s, lock read and write 1ms)
--- FAIL: TestWriteFenceEndsWithTheReplicator (0.01s)
    fence_test.go:935: the fence still takes ticks after Close
FAIL
FAIL	github.com/carlosframework/platform/internal/lease	144.117s
ok  	github.com/carlosframework/platform/internal/lease/leasetest	1.244s
ok  	github.com/carlosframework/platform/internal/lease/locktest	0.039s
ok  	github.com/carlosframework/platform/internal/ledger	0.066s
ok  	github.com/carlosframework/platform/internal/mail	0.908s
ok  	github.com/carlosframework/platform/internal/mailer	0.795s
ok  	github.com/carlosframework/platform/internal/mailsubmit	1.461s
ok  	github.com/carlosframework/platform/internal/mailwire	0.011s
ok  	github.com/carlosframework/platform/internal/maintenance	0.227s
ok  	github.com/carlosframework/platform/internal/maintenanceexec	8.859s
ok  	github.com/carlosframework/platform/internal/maintenanceguard	0.262s
ok  	github.com/carlosframework/platform/internal/media	1.901s
ok  	github.com/carlosframework/platform/internal/media/mediatest	0.004s
ok  	github.com/carlosframework/platform/internal/mediaaws	59.959s
ok  	github.com/carlosframework/platform/internal/mediahandler	41.863s
ok  	github.com/carlosframework/platform/internal/mediajobs	0.913s
ok  	github.com/carlosframework/platform/internal/medialocal	9.906s
ok  	github.com/carlosframework/platform/internal/metrics	0.144s
ok  	github.com/carlosframework/platform/internal/minorunits	0.007s
ok  	github.com/carlosframework/platform/internal/moves	53.421s
ok  	github.com/carlosframework/platform/internal/moves/archive	2.581s
ok  	github.com/carlosframework/platform/internal/moves/offlinerun	0.065s
ok  	github.com/carlosframework/platform/internal/namedunits	0.050s
ok  	github.com/carlosframework/platform/internal/objstore	1.785s
ok  	github.com/carlosframework/platform/internal/ops	13.681s
ok  	github.com/carlosframework/platform/internal/pageindex	3.636s
ok  	github.com/carlosframework/platform/internal/parity	0.129s
?   	github.com/carlosframework/platform/internal/parity/cmd/parity-doc	[no test files]
ok  	github.com/carlosframework/platform/internal/park	0.716s
ok  	github.com/carlosframework/platform/internal/perf	0.202s
ok  	github.com/carlosframework/platform/internal/plans	0.114s
ok  	github.com/carlosframework/platform/internal/privatefile	0.019s
ok  	github.com/carlosframework/platform/internal/provision	238.603s
ok  	github.com/carlosframework/platform/internal/proxyproto	0.933s
ok  	github.com/carlosframework/platform/internal/publicrelease	0.039s
ok  	github.com/carlosframework/platform/internal/ratelimit	0.248s
ok  	github.com/carlosframework/platform/internal/regionlabel	0.059s
ok  	github.com/carlosframework/platform/internal/regionname	0.015s
ok  	github.com/carlosframework/platform/internal/registrar	0.018s
ok  	github.com/carlosframework/platform/internal/registrar/openprovider	0.580s
?   	github.com/carlosframework/platform/internal/registrar/registrartest	[no test files]
ok  	github.com/carlosframework/platform/internal/registry	83.360s
ok  	github.com/carlosframework/platform/internal/relay	7.513s
ok  	github.com/carlosframework/platform/internal/release	85.199s
ok  	github.com/carlosframework/platform/internal/replicagen	0.009s
ok  	github.com/carlosframework/platform/internal/replicas	0.057s
ok  	github.com/carlosframework/platform/internal/reqrec	5.631s
ok  	github.com/carlosframework/platform/internal/rollout	11.205s
ok  	github.com/carlosframework/platform/internal/rolloutwords	0.046s
ok  	github.com/carlosframework/platform/internal/rootaws	102.726s
ok  	github.com/carlosframework/platform/internal/rootfsimage	1.308s
ok  	github.com/carlosframework/platform/internal/rootparticipation	0.102s
ok  	github.com/carlosframework/platform/internal/rootstate	0.048s
ok  	github.com/carlosframework/platform/internal/runs	0.814s
ok  	github.com/carlosframework/platform/internal/s3compat	0.040s
ok  	github.com/carlosframework/platform/internal/s3fake	1.574s
ok  	github.com/carlosframework/platform/internal/safefile	0.032s
ok  	github.com/carlosframework/platform/internal/schedule	22.808s
ok  	github.com/carlosframework/platform/internal/seeds	0.072s
ok  	github.com/carlosframework/platform/internal/sim/litestreamfacts	5.022s
ok  	github.com/carlosframework/platform/internal/sim/mediajobs	51.366s
ok  	github.com/carlosframework/platform/internal/sim/regionha	21.574s
ok  	github.com/carlosframework/platform/internal/status	0.414s
ok  	github.com/carlosframework/platform/internal/steering	0.239s
ok  	github.com/carlosframework/platform/internal/stopevidence	0.353s
ok  	github.com/carlosframework/platform/internal/storecfg	0.341s
ok  	github.com/carlosframework/platform/internal/svcrole	0.015s
ok  	github.com/carlosframework/platform/internal/systemd	5.520s
?   	github.com/carlosframework/platform/internal/systemdshow	[no test files]
ok  	github.com/carlosframework/platform/internal/team	3.910s
ok  	github.com/carlosframework/platform/internal/teamcontract	0.128s
ok  	github.com/carlosframework/platform/internal/telemetry	0.025s
ok  	github.com/carlosframework/platform/internal/termfence	2.989s
ok  	github.com/carlosframework/platform/internal/timerspec	0.041s
ok  	github.com/carlosframework/platform/internal/tsidentity	4.189s
ok  	github.com/carlosframework/platform/internal/tunnelclient	0.422s
ok  	github.com/carlosframework/platform/internal/unixdial	0.011s
ok  	github.com/carlosframework/platform/internal/updatewords	0.074s
ok  	github.com/carlosframework/platform/internal/upstreamguard	0.015s
?   	github.com/carlosframework/platform/internal/upstreamguard/guardtest	[no test files]
ok  	github.com/carlosframework/platform/internal/usage	0.028s
ok  	github.com/carlosframework/platform/internal/version	0.013s
ok  	github.com/carlosframework/platform/internal/vet	3.026s
ok  	github.com/carlosframework/platform/internal/zonehost	0.011s
ok  	github.com/carlosframework/platform/internal/zonehost/route53zones	0.042s
?   	github.com/carlosframework/platform/internal/zonehost/zonehosttest	[no test files]
?   	github.com/carlosframework/platform/scripts/gitleaks-gate	[no test files]
ok  	github.com/carlosframework/platform/scripts/govulncheck-gate	0.028s
ok  	github.com/carlosframework/platform/scripts/pathmapcheck	0.057s
ok  	github.com/carlosframework/platform/scripts/region-ha-g2/fixture	5.174s
ok  	github.com/carlosframework/platform/scripts/stateless-replicas-drill	1.220s
ok  	github.com/carlosframework/platform/scripts/witness-pointer	0.021s
FAIL
=== cutover-witness (154 s, from +14 s)
ok  	github.com/carlosframework/platform	2.302s
=== internal_grouproll@0 (274 s, from +74 s)
ok  	github.com/carlosframework/platform/internal/grouproll	272.911s
=== internal_grouproll@1 (280 s, from +74 s)
ok  	github.com/carlosframework/platform/internal/grouproll	278.731s
=== internal_activator@0 (158 s, from +146 s)
ok  	github.com/carlosframework/platform/internal/activator	153.770s
=== internal_activator@1 (135 s, from +146 s)
ok  	github.com/carlosframework/platform/internal/activator	130.950s
=== internal_activator@2 (135 s, from +146 s)
ok  	github.com/carlosframework/platform/internal/activator	130.064s
=== internal_activator@3 (172 s, from +146 s)
ok  	github.com/carlosframework/platform/internal/activator	167.924s
=== internal_edge@0 (197 s, from +164 s)
ok  	github.com/carlosframework/platform/internal/edge	188.524s
=== internal_edge@1 (149 s, from +164 s)
ok  	github.com/carlosframework/platform/internal/edge	139.540s
=== internal_edge@2 (174 s, from +164 s)
ok  	github.com/carlosframework/platform/internal/edge	164.038s
=== internal_edge@3 (220 s, from +164 s)
ok  	github.com/carlosframework/platform/internal/edge	210.713s
=== root@0 (127 s, from +165 s)
ok  	github.com/carlosframework/platform	116.630s
=== root@1 (115 s, from +166 s)
ok  	github.com/carlosframework/platform	106.161s
=== root@2 (124 s, from +166 s)
ok  	github.com/carlosframework/platform	114.776s
=== root@3 (119 s, from +166 s)
ok  	github.com/carlosframework/platform	109.996s
=== root@4 (114 s, from +166 s)
ok  	github.com/carlosframework/platform	103.696s
=== internal_host@0 (148 s, from +215 s)
ok  	github.com/carlosframework/platform/internal/host	143.666s
=== internal_host@1 (143 s, from +215 s)
ok  	github.com/carlosframework/platform/internal/host	138.416s
=== internal_host@2 (206 s, from +215 s)
ok  	github.com/carlosframework/platform/internal/host	201.097s
=== internal_host@3 (257 s, from +215 s)
ok  	github.com/carlosframework/platform/internal/host	252.640s
=== internal_host@4 (145 s, from +215 s)
ok  	github.com/carlosframework/platform/internal/host	140.738s
=== internal_host@5 (274 s, from +215 s)
ok  	github.com/carlosframework/platform/internal/host	269.081s
=== internal_console@0 (158 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	151.172s
=== internal_console@1 (182 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	175.289s
=== internal_console@2 (201 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	193.564s
=== internal_console@3 (259 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	252.665s
=== internal_console@4 (194 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	185.937s
=== internal_console@5 (207 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	200.008s
=== internal_console@6 (206 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	199.101s
=== internal_console@7 (210 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	202.390s
=== internal_console@8 (245 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	238.131s
=== internal_console@9 (268 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	260.682s
=== internal_console@10 (250 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	242.510s
=== internal_console@11 (213 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	206.175s
=== internal_console@12 (319 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	311.726s
=== internal_console@13 (217 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	208.848s
=== internal_console@14 (204 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	195.469s
=== internal_console@15 (226 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	218.384s
=== internal_console@16 (208 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	199.888s
=== internal_console@17 (201 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	192.669s
=== internal_console@18 (219 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	210.208s
=== internal_console@19 (206 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	198.773s
=== internal_console@20 (212 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	204.691s
=== internal_console@21 (221 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	212.716s
=== internal_console@22 (220 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	212.192s
=== internal_console@23 (231 s, from +222 s)
ok  	github.com/carlosframework/platform/internal/console	222.911s
=== lists: internal_console 221 s, internal_edge 163 s, internal_activator 145 s, internal_host 215 s, root 164 s, internal_grouproll 73 s
=== cpu: the gate used 12752 cpu-seconds in 541 s, about 23.6 of 32 cores; the machine as a whole was 79% busy

Failure summary:
--- rest
--- FAIL: TestWriteFenceEndsWithTheReplicator (0.01s)
    fence_test.go:935: the fence still takes ticks after Close
FAIL	github.com/carlosframework/platform/internal/lease	144.117s

FAILED: rest
make: *** [Makefile:23: test] Error 1
=== opentofu ===
opentofu: 37 test files in 11 suites, OpenTofu v1.13.9
  initialised in 15 s
  ok      18 s  infra/modules/box-fence-writer/tests/writer.tftest.hcl  Success! 1 passed, 0 failed.
  ok      30 s  infra/modules/deployment-buckets/tests/data_lifecycle.tftest.hcl  Success! 3 passed, 0 failed.
  ok      21 s  infra/modules/deployment-buckets/tests/db_reads.tftest.hcl  Success! 1 passed, 0 failed.
  ok      21 s  infra/modules/deployment-buckets/tests/evidence.tftest.hcl  Success! 1 passed, 0 failed.
  ok      30 s  infra/modules/deployment-buckets/tests/fence_writers.tftest.hcl  Success! 3 passed, 0 failed.
  ok      24 s  infra/modules/deployment-buckets/tests/media_results.tftest.hcl  Success! 2 passed, 0 failed.
  ok      94 s  infra/modules/media-engine/tests/media_engine.tftest.hcl  Success! 24 passed, 0 failed.
  ok      34 s  infra/modules/pdf-host/tests/computed.tftest.hcl  Success! 2 passed, 0 failed.
  ok      61 s  infra/modules/pdf-host/tests/pdf_host.tftest.hcl  Success! 24 passed, 0 failed.
  ok      42 s  infra/modules/region-group-operator-document/tests/document.tftest.hcl  Success! 12 passed, 0 failed.
  ok      21 s  infra/modules/region-host/ingress/tests/fixed-targets/tests/targets.tftest.hcl  Success! 2 passed, 0 failed.
  ok      69 s  infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl  Success! 30 passed, 0 failed.
  ok      47 s  infra/modules/region-host/tests/alert_publish.tftest.hcl  Success! 18 passed, 0 failed.
  ok      45 s  infra/modules/region-host/tests/alerts_topic.tftest.hcl  Success! 16 passed, 0 failed.
  ok      15 s  infra/modules/region-host/tests/analytics_prune.tftest.hcl  Success! 2 passed, 0 failed.
  ok      16 s  infra/modules/region-host/tests/console_mail.tftest.hcl  Success! 4 passed, 0 failed.
  ok       8 s  infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl  Success! 1 passed, 0 failed.
  ok      72 s  infra/modules/region-host/tests/group.tftest.hcl  Success! 32 passed, 0 failed.
  ok      12 s  infra/modules/region-host/tests/group_alarms.tftest.hcl  Success! 4 passed, 0 failed.
  ok      12 s  infra/modules/region-host/tests/group_iam.tftest.hcl  Success! 4 passed, 0 failed.
  ok       6 s  infra/modules/region-host/tests/group_isolation.tftest.hcl  Success! 1 passed, 0 failed.
  ok      39 s  infra/modules/region-host/tests/group_operator.tftest.hcl  Success! 13 passed, 0 failed.
  ok      10 s  infra/modules/region-host/tests/group_user_data.tftest.hcl  Success! 3 passed, 0 failed.
  ok      30 s  infra/modules/region-host/tests/health_alarms.tftest.hcl  Success! 10 passed, 0 failed.
  ok      15 s  infra/modules/region-host/tests/ingress_drain_read.tftest.hcl  Success! 4 passed, 0 failed.
  ok       7 s  infra/modules/region-host/tests/instance_metadata.tftest.hcl  Success! 1 passed, 0 failed.
  ok      24 s  infra/modules/region-host/tests/mailer.tftest.hcl  Success! 6 passed, 0 failed.
  ok      12 s  infra/modules/region-host/tests/mailer_group.tftest.hcl  Success! 2 passed, 0 failed.
  ok      15 s  infra/modules/region-host/tests/managed_fleets/group_refusal.tftest.hcl  Success! 2 passed, 0 failed.
  ok     102 s  infra/modules/region-host/tests/managed_fleets/managed_fleets.tftest.hcl  Success! 46 passed, 0 failed.
  ok      67 s  infra/modules/region-host/tests/store_conversion.tftest.hcl  Success! 27 passed, 0 failed.
  ok      17 s  infra/modules/region-host/tests/store_scanning.tftest.hcl  Success! 4 passed, 0 failed.
  ok      27 s  infra/modules/region-host/tests/store_versioning.tftest.hcl  Success! 11 passed, 0 failed.
  ok      18 s  infra/modules/region-host/tests/user_data_ignored.tftest.hcl  Success! 3 passed, 0 failed.
  ok      13 s  infra/modules/region-remote-host/tests/data_lifecycle.tftest.hcl  Success! 3 passed, 0 failed.
  ok      15 s  infra/modules/region-remote-host/tests/no_deployment_bucket.tftest.hcl  Success! 5 passed, 0 failed.
  ok      26 s  infra/modules/scanner-host/tests/scanner_host.tftest.hcl  Success! 14 passed, 0 failed.
opentofu: 37 files in 210 s
opentofu: PASS

amadan: step gate failed: exit status 2

amadan: job failed at step gate — its output is above, not at the tail of this log

landed from release-copy-across-consoles

diff --git a/.superpowers/sdd/2026-11-25-release-copy-across-consoles/luna-apply-report.md b/.superpowers/sdd/2026-11-25-release-copy-across-consoles/luna-apply-report.md
new file mode 100644
index 000000000..b24b78848
--- /dev/null
+++ b/.superpowers/sdd/2026-11-25-release-copy-across-consoles/luna-apply-report.md
@@ -0,0 +1,11 @@
+# Luna apply report
+
+Applied verbatim: rows 1-14 and 16. Skipped: 15 (stale), 17 (no-op).
+- 1,2 release_pull.go:40-41 (call site drops len(m.Artifacts); m now unused, assignment is `_`)
+- 3,4,5 ship_from_release.go:33,39,155
+- 6,7,8 internal/console/apiship_expect.go:44,48,51 (row 8 call site passes key, e.Size, rootfsSize)
+- 9,10,11 internal/console/apiship_expect.go:76,78,80 (successor lines; helpers moved code)
+- 12 parity/parity.tsv:41, make parity-doc regenerated docs/parity.md
+- 13,14,16 docs/site/cli.md:309,312,1072 (curly apostrophes in prose only)
+Tests updated: release_pull_test.go, release_copy_e2e_test.go, internal/console/apiship_expect_test.go.
+Results: go vet ok; console TestAPIShip|TestAPIRelease ok; root targeted tests ok; docsite, parity ok; code-health PASS (below-record notes only); darwin and windows builds ok.
diff --git a/cli.go b/cli.go
index 26f6018cd..a3666090c 100644
--- a/cli.go
+++ b/cli.go
@@ -2506,10 +2506,21 @@ func runShip(args []string) {
check := fs.Bool("check", false, "run the rootfs image here with Docker or Podman, the way a box would, and ship nothing")
var envVars shipCheckEnvFlag
fs.Var(&envVars, "env", shipEnvFlagHelp)
+ fromRelease := fs.String("from-release", "", "a directory written by carlos releases pull. ships its files and settings unchanged")
fs.Usage = flagUsage(fs, "")
fs.Parse(args)
// --env is refused before anything else happens, on every ship.
checkEnv, err := shipEnvRefusal(fs, *check, envVars)
+ // A pulled release (ship_from_release.go) is its own body, taken before
+ // anything below can refuse a ship with no file arguments.
+ if err == nil && *fromRelease != "" {
+ if err = runShipFromRelease(fs, fromReleaseOpts{
+ dir: *fromRelease, app: *app, console: *consoleFlag, acctRaw: acctRaw, acctIDRaw: acctIDRaw,
+ programChange: *programChange, messageFlags: messageFlags,
+ }); err == nil {
+ return
+ }
+ }
if err != nil {
log.Fatal(err)
}
diff --git a/commands.go b/commands.go
index 7a3365eb2..6e893d059 100644
--- a/commands.go
+++ b/commands.go
@@ -322,8 +322,8 @@ func channelsCommand() *clireg.Node {
}
}
-// releasesCommand is `carlos releases`, moved from main's switch. Two
-// sub-verbs, `retention` and `authorize`: the `carlos version target`
+// releasesCommand is `carlos releases`, moved from main's switch. Three
+// sub-verbs, `retention`, `authorize` and `pull`: the `carlos version target`
// judgment call: flags-only verbs stay flat until a word genuinely names a
// different action, and a policy write or a signature is not a listing.
// Anything else lists. The sub-verbs skip the update hint, as channels'.
@@ -335,6 +335,7 @@ func releasesCommand() *clireg.Node {
Children: []*clireg.Node{
noHint(raw("retention", cust, runReleasesRetention)),
noHint(raw("authorize", clireg.Operator, runReleasesAuthorize)),
+ noHint(rawErr("pull", cust, runReleasesPull)),
},
DefaultLeaf: &clireg.Node{Audience: cust, Run: clireg.RawArgs(runReleases)},
DefaultOn: clireg.OnAbsent | clireg.OnFlag | clireg.OnWord,
diff --git a/docs/parity.md b/docs/parity.md
index 636c4ae54..a7988f9da 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -13,9 +13,9 @@ CLI rows are checked against the command registry (`parity/cli.tsv`).
| both | 48 |
| partial | 9 |
| gap | 68 |
-| cli-only | 19 |
+| cli-only | 20 |
| console-only | 18 |
-| Total | 162 |
+| Total | 163 |
## account
@@ -214,6 +214,7 @@ CLI rows are checked against the command registry (`parity/cli.tsv`).
| canary-rm | gap | `canary rm` | | [wp-instances](#wp-instances) | Deletes the canary's instance and leaves its channel. The console has no instance delete (instances-delete); its Retire is a different operation (canary-retire). |
| canary-retire | console-only | | `POST /a/{sqid}/apps/{app}/canary/retire` | | Retires the canary's channel and refuses while any host follows it. No CLI verb retires a channel: canary rm deletes the instance and leaves the channel. |
| channels | both | `channels` | `GET /a/{sqid}/apps/{app}/releases` | | |
+| releases-pull | cli-only | `releases pull` | | | Copies a shipped release out of a console and checks each named file against the manifest's recorded size and digest. |
| channels-resign | gap | `channels resign` | | [wp-settings](#wp-settings) | |
| pipeline | both | `pipeline show`<br>`pipeline init`<br>`pipeline set`<br>`pipeline add`<br>`pipeline remove` | `GET /a/{sqid}/apps/{app}/pipeline`<br>`POST /a/{sqid}/apps/{app}/pipeline`<br>`GET /a/{sqid}/apps/{app}/settings/{section}` | | |
| releases | both | `releases` | `GET /a/{sqid}/apps/{app}/releases`<br>`GET /a/{sqid}/apps/{app}/deployments` | | |
diff --git a/docs/site/cli.md b/docs/site/cli.md
index 3e5a1140c..f0d3ad3b1 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -303,6 +303,21 @@ Servers keep a copy only when your app answers with status 200, a `Cache-Control
--env KEY=VALUE gives every process in the check a variable, such as a placeholder secret or a store setting. The check never reads the app's real config or secrets. It sets CARLOS_SOCKET, CARLOS_DB, CARLOS_HOST and CARLOS_REGION itself, so --env cannot set those.
+`--from-release <dir>` ships a release that
+[carlos releases pull](/docs/cli#carlos-releases-pull) wrote into a
+directory, so another console stores the exact bytes the first one tested.
+It ships under the release’s own version, with its label, notes and other
+settings, so it takes only `--app`, `--account`, `--account-id`,
+`--console`, `--destination`, `--message`, `--no-prompt` and
+`--program-change`, and no file arguments. Every file named by the
+manifest is checked against it first, and a mismatch stops the ship before
+anything is uploaded. The console then refuses any bytes that differ from
+the release's digests, and ship checks the digests it answers with.
+
+```sh
+carlos ship --from-release ./release --app shop
+```
+
### carlos promote
Points a channel at a version you have already shipped.
@@ -603,6 +618,46 @@ removes destinations, so you don't need to edit the file yourself.
`--target` is unrelated: it names the platform (GOOS-GOARCH) a binary was
built for.
+#### Staging tests X, production promotes X
+
+To run in production the exact build that staging tested, copy the release
+from one console to the other instead of building it twice. Use two CI jobs,
+each with its own deploy credential (`CARLOS_SERVICE_TOKEN`) for `shop`.
+
+Job 1 runs against the staging console. It ships a named version, promotes
+it so staging serves it, waits until the app's `X-Carlos-Version` header
+shows that version, and runs your tests. Then it pulls the release into a directory and keeps that
+directory as a CI artifact:
+
+```sh
+export CARLOS_CONSOLE=https://staging.example.com
+carlos ship --app shop --version v12 ./bin/server
+carlos promote --app shop v12 edge
+# wait up to about 10 minutes for staging to serve v12, or fail the job
+for i in $(seq 30); do
+ curl -sI --max-time 10 https://shop.staging.example.com/ | tr -d '\r' | grep -qix 'x-carlos-version: v12' && break
+ [ "$i" = 30 ] && { echo "staging never served v12" >&2; exit 1; }
+ sleep 10
+done
+# run your tests against staging here
+carlos releases pull v12 --app shop --out release
+```
+
+Job 2 runs against the production console. It downloads the artifact, ships
+the same release and promotes it:
+
+```sh
+export CARLOS_CONSOLE=https://carlos.example.com
+carlos ship --from-release release --app shop
+carlos promote --app shop v12 edge
+```
+
+The files are byte-identical on both consoles, though the manifests differ:
+each console writes its own manifest and signs its own channel pointers.
+Production refuses any file whose digest differs from the release's, and
+stores nothing. A deploy credential can promote to `canary`,
+`edge` and `beta`, but not `stable`.
+
### carlos canary
Deploy onto a host and a channel belonging to this branch alone, so nothing
@@ -1001,7 +1056,7 @@ to run".
carlos releases --app hello
```
-There are two sub-verbs. `carlos releases retention --keep 20` sets an ambient
+There are three sub-verbs. `carlos releases retention --keep 20` sets an ambient
prune policy, and `--dry-run` shows you what it would remove before you commit
to it. The safety list always wins over the number: channel pointers,
rollback history, tagged releases, anything inside the bake window, and each
@@ -1010,6 +1065,19 @@ disappears by policy. `--off` goes back to keeping everything.
`carlos releases authorize <app> <version>` is for operators. It shows a build's manifest and file digests and, when you type yes, signs a promotion record for exactly those bytes. Every promotion writes one; this is for a build promoted before records existed, so an instance can be pinned to it or recovered onto it on a box that does not already have it.
+#### carlos releases pull
+
+Copies a shipped release out of a console into a directory: its
+`manifest.json`, exactly as the console stores it, and every file the
+manifest names. Each file is checked against the manifest’s size and sha256
+as it arrives, and a file that does not match is removed and the pull fails.
+The manifest is written last, so a directory that holds one holds the whole
+release. In CI the directory can be a build artifact handed to a later job.
+
+```sh
+carlos releases pull v12 --app shop --out ./release
+```
+
### carlos version
`carlos version` prints the build id of the binary in front of you. It is the
diff --git a/docs/site/stateless-replicas.md b/docs/site/stateless-replicas.md
index 6e1ec8535..f7b7a5a34 100644
--- a/docs/site/stateless-replicas.md
+++ b/docs/site/stateless-replicas.md
@@ -26,7 +26,7 @@ More than one copy needs an always-on release. Set --copies 1 and wait for remov
## Deploys
-A deploy runs the release command once per instance, then switches its copies one box at a time. Your migrations must allow old and new code to serve together. Each copy runs every declared worker.
+A deploy runs the release command once per instance, not once per copy, then switches its copies one box at a time. Your migrations must allow old and new code to serve together. Each copy runs every declared worker.
When a copy switches, its old build stops once the new one serves. A response still streaming from the old build when it stops is cut, as when a box stops. Websockets on the old build disconnect and their clients reconnect to a healthy copy.
diff --git a/docs/superpowers/notes/census-proposal-release-copy-across-consoles.md b/docs/superpowers/notes/census-proposal-release-copy-across-consoles.md
new file mode 100644
index 000000000..3362097f2
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-release-copy-across-consoles.md
@@ -0,0 +1,29 @@
+# Census approval: release-copy-across-consoles
+
+Ruling `census-ruling-release-copy-across-consoles`. The independent reviewer approves or rejects every change below, 7 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `cli.go` `runShip` | body | unchanged (2) | takes --from-release <dir> and, after the environment refusal and before the file-argument checks, hands the ship to runShipFromRelease (ship_from_release.go). a person's ship command run from their own machine against a console; no root read, no box state; read sites unchanged (2). |
+
+Envelopes re-pinned: `.`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `cli.go` `runShip`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-rootfs-apps-1;basis=rootfs Plan 1 Task 9: takes --rootfs, --processes, --hibernate, --jit and --check and hands a rootfs ship to runShipRootfs (ship_rootfs.go) before the binary path; the --notes-file ReadFile moved into shipNoteText (its own row, the same read of the file the person named) and the direct-mode version mint into mintDirectVersion; one read site fewer, none added; Task 12: the --hibernate flag help is RFS-1-C32's new text, the same reads;rev3=census-ruling-edge-asset-cache-1;basis=takes --assets (repeatable), checks the folders with checkShipAssets (release.ValidAssetPaths; refused on a static site) before the mode split, carries them into the API meta (sess.shipAssets) and the direct-mode manifest (shipAssetsBlock), and passes them to runShipRootfs (rootfsShipOpts.assets), which runs the same check and carries them the same two ways; after a direct-mode ship has stored a release declaring folders, directShipAssetGens runs the console ship door's backfill (provision.MintMissingAssetGens: lists the app's record keys and gives each record without an asset generation one, a CAS write in the deployment bucket as the person running the CLI) and fails naming any record it could not mint; read sites unchanged (2), none added;rev3=census-ruling-rootfs-apps-4;basis=adds the repeatable --env flag and refuses it before anything else unless --check is given (shipEnvRefusal, parseShipCheckEnv); the parsed values go into rootfsShipOpts.checkEnv. --env values reach the check's local container runtime as -e argv only, never root, never a box. No read added; read sites unchanged (2).;rev3=census-ruling-stateless-replicas-1;basis=Carry --stateless into binary/API and rootfs ship options; same two read sites, no new read.;rev3=census-ruling-platform-mail-submission;basis=Task 6: a --mail flag (only "submit" accepted, refused with one line otherwise, and refused with --rootfs), set on the manifest in direct-bucket mode and sent to the console in API mode, where a console that does not echo it is refused (ship_mail.go, apimode.go), as --stateless is. A person's ship command; no root read, no box state.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `release_pull.go:apiSession.pullArtifact`: reads +file:CreateTemp, +file:ReadAll; written legacy, accepted-legacy, frozen
+- new `release_pull.go:apiSession.releaseManifestRaw`: reads +file:ReadAll; written legacy, accepted-legacy, frozen
+- new `release_pull.go:lockPullDir`: reads +file:OpenFile; written legacy, accepted-legacy, frozen
+- new `release_pull.go:publishManifest`: reads +file:CreateTemp; written legacy, accepted-legacy, frozen
+- new `release_pull.go:pullRelease`: reads +file:Lstat; written legacy, accepted-legacy, frozen
+- new `ship_from_release.go:hashReleaseFile`: reads +file:Open; written legacy, accepted-legacy, frozen
+- new `ship_from_release.go:loadReleaseDir`: reads +file:ReadFile; written legacy, accepted-legacy, frozen
+
+Seal: `6921575b59564ed947e30c02e314dd429016c6c11a85db9b8af50b2f31d5a5db` → `892cf87db700600490e3ec9e944f9dbe7151e43bc5471090634f1735bcb9a7bd`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-release-copy-across-consoles.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/plans/2026-11-25-release-copy-across-consoles.md b/docs/superpowers/plans/2026-11-25-release-copy-across-consoles.md
new file mode 100644
index 000000000..ab85ae165
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-25-release-copy-across-consoles.md
@@ -0,0 +1,221 @@
+# Release copy across consoles (#1389 item 1) Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Ship the exact bytes a staging console tested to a production console: `carlos releases pull` copies a release out of one console, `carlos ship --from-release` ships it into another, and the target console refuses anything whose digests differ from the source's.
+
+**Architecture:** Two read doors on the source console stream the stored manifest and each artifact. The CLI verifies every byte against the manifest on the way down and again before upload. The ship door gains an optional `expect_artifacts` meta field; the console hashes what arrives and stores nothing unless it matches. The target writes and signs its own manifest and pointers; only artifact digests come from the source.
+
+**Tech Stack:** Go, `net/http` mux routes in `internal/console/routedecls.go`, `internal/release` store, `clireg` command tree.
+
+**Spec:** `.superpowers/sdd/2026-11-25-1389/DESIGN.md` (binding). Code map: `.superpowers/sdd/2026-11-25-1389/RESEARCH.md`.
+
+## Global Constraints
+
+- No tenant names in code, tests or docs. Apps are `shop` (source) and `storefront` (target); hosts `example.com`; person `paul@keymail.dev` as the existing fixtures use.
+- Locally run only targeted tests: `go test ./internal/console -run 'TestX' -count=1`, `go test . -run 'TestX' -count=1`. Full suites are CI's.
+- Must cross-compile: `GOOS=darwin go build . && GOOS=windows go build .` before each commit that touches the root package. No linux-only calls (no `syscall` statx, no `/proc`) in root-package code.
+- Tests are deterministic: no `time.Sleep`; wait on channels or fill semaphores directly.
+- Production-wired witnesses: every test goes through the real `console.NewServer` routes and the real `runShip` / `runReleasesPull` / `runPromote` entry points (or the real `carlos` binary via `sharedCarlos`). No hand-rolled handlers standing in for the console.
+- No new `svcrole`. Both read doors are `svcrole.Allow(svcrole.Publish, svcrole.Deploy)`; persons owner/member reach them as every `kindCLI` door.
+- Trust model as DESIGN.md "Trust": the target computes its own digests, writes its own manifest (`built_by`, `built_at`) and signs its own pointers. The source manifest is input only for artifact digests and release settings.
+- Wire changes are additive: `expect_artifacts` is optional; a request without it behaves exactly as today.
+- New code goes in new files. `apimode.go` is over the file-lines cap; `runShip` must not exceed its `fatal` allowance (23) or 300 code lines. Run `make code-health` before handing off.
+- New CLI commands return errors (`rawErr`), never `log.Fatal`.
+- User-facing strings below are drafts: plain sentences, no em dashes, lowercase after a full stop as the surrounding CLI does. The controller runs the copy pass; keep each string in one place (a const or one `fmt.Errorf`) so the pass edits one line.
+- `parity/parity.tsv` row and `docs/site/cli.md` entry land in the same task as the command (`make parity-doc` after editing the table).
+
+## Review Focus
+
+1. **A target console too old to know `expect_artifacts`** ignores it and stores whatever arrived. The CLI must still fail loudly by comparing the response's `artifacts` with the source manifest. Pinned by `TestCompareShippedArtifacts` (Task 4).
+2. **A hostile or odd `File` name in a pulled manifest** (`../x`, `a/b`, `a\b`, `manifest.json`, empty). Pull and ship must refuse it before touching the filesystem. Pinned by `TestValidPulledFile` (Task 3), used by both commands.
+3. **An interrupted pull** leaves files but no `manifest.json`. Pulling again into the same dir should finish the job, not fail. Pinned by `TestReleasesPullFinishesAnIncompleteDir` (Task 3).
+4. **Target app name differs from source app name.** The copy must work and the target manifest names the target app. Pinned by using `shop` on A and `storefront` on B in the e2e (Task 4).
+5. **A forged digest on a version the target already has** must be refused, not answered with the identical-reship 200. Pinned by `TestAPIShipExpectRefusesForgedOnExistingVersion` (Task 2).
+
+---
+
+### Task 1: Console read doors
+
+**Files:**
+- Create: `internal/console/apirelease_read.go`
+- Modify: `internal/console/routedecls.go` (two entries beside `GET /api/cli/apps/{account}/{app}/releases`, ~line 597)
+- Modify: `internal/console/server.go` (new `releaseReads` field; make it where `shipSem` is made, ~line 2044)
+- Modify: `internal/console/deploydoors_test.go` (add both patterns to `deployDoors`)
+- Test: `internal/console/apirelease_read_test.go`
+
+**Interfaces:**
+- Produces (wire):
+ - `GET /api/cli/apps/{account}/{app}/releases/{version}/manifest` → 200, `Content-Type: application/json`, body = exact stored bytes of `release.ManifestKey(acct, app, version)`.
+ - `GET /api/cli/apps/{account}/{app}/releases/{version}/artifacts/{file}` → 200, `Content-Type: application/octet-stream`, `Content-Length: <manifest size>`, `X-Content-SHA256: <manifest sha256>`, body streamed from `release.ArtifactKey(acct, app, version, file)`.
+- Produces (Go): `func (s *Server) handleAPIReleaseManifest(w http.ResponseWriter, r *http.Request)`, `func (s *Server) handleAPIReleaseArtifact(w http.ResponseWriter, r *http.Request)`, `Server.releaseReads chan struct{}` (cap `releaseReadsMax = 4`).
+
+Key logic, both handlers: `s.apiAccountApp(w, r)` first (app binding and 404s as today); `release.ValidVersion(version)` else 400 `invalid version`; `release.GetManifestRaw(ctx, s.cfg.Releases, acct.Sqid, app, version)`: `errors.Is(err, os.ErrNotExist)` → 404 `release not found`, other error → 502 `could not read the release` (log it). Manifest door: 30 s context, write raw bytes.
+
+Artifact door: find the artifact whose `File == r.PathValue("file")` (compare to `File`, not the map key; rootfs is `rootfs.squashfs`), else 404 `file not in this release`. Take a `releaseReads` slot non-blocking; full → `retryAfter(w, 2*time.Second)` and 429 `too many release downloads at once. try again shortly`. Open with `release.OpenObjectStreaming`, set headers, `SetWriteDeadline(now + releaseReadDeadline)` with `const releaseReadDeadline = 75 * time.Minute` (rootfs ship's own bound), `io.Copy(w, io.LimitReader(body, a.Size))`; a short copy is logged only (the CLI's hash check refuses it). Context: `r.Context()` with `releaseReadDeadline`. No audit row (reads, like `GET .../releases`).
+
+- [ ] **Step 1: Write the failing tests** in `apirelease_read_test.go`, all on `deployFixture` (app `hello`, v1 and v2, deploy token `tok`) unless noted. Note: the fixture's existing app name `hello` is fine; new apps are `shop`.
+ - `TestAPIReleaseManifestReturnsStoredBytes`: GET `.../bab/hello/releases/v1/manifest` with the deploy token → 200, `application/json`, body `bytes.Equal` to the raw from `release.GetManifestRaw(ctx, fx.rel, "bab", "hello", "v1")`.
+ - `TestAPIReleaseArtifactStreamsBytes`: GET `.../v1/artifacts/linux-arm64` → 200, body `"bin v1"`, `Content-Length` `6`, `X-Content-SHA256` = hex sha256 of `"bin v1"`.
+ - `TestAPIReleaseArtifactRefusesWhatTheManifestDoesNotName`: table → status: `artifacts/manifest.json` 404; `artifacts/linux-amd64` 404; `artifacts/..%2Fv2%2Flinux-arm64` 404; `releases/v9/manifest` 404; `releases/v9/artifacts/linux-arm64` 404; `releases/..bad/manifest` 400.
+ - `TestAPIReleaseReadRoles`: publish token (`NewServicePrincipalScoped(..., svcrole.Publish, nil, ...)`) → 200; operate token → refused (assert the same status `GET .../releases` gives an operate token, read it from that door in the test, do not hard-code); deploy token bound to `other` app on `.../other/releases/v1/manifest` → 404; the person token from `cliToken` → 200.
+ - `TestAPIReleaseArtifactRootfs`: `rootfsShipFixture`, ship a rootfs release as `TestAPIShipRootfsHappy` does, GET `.../shop/releases/<v>/artifacts/rootfs.squashfs` → bytes equal to the image; GET `.../artifacts/rootfs-linux-arm64` → 404.
+ - `TestAPIReleaseArtifactBusy`: fill `fx.srv.releaseReads` to capacity in the test, GET artifact → 429 with `Retry-After` set; drain one slot, GET → 200.
+ - `TestDeployReachesExactlyItsDoors` (existing): add both patterns to `deployDoors` with a comment `// #1389: a pipeline copies a release it may ship.`
+
+- [ ] **Step 2: Run, expect FAIL** `go test ./internal/console -run 'TestAPIRelease(Manifest|Artifact|Read)|TestDeployReachesExactlyItsDoors' -count=1` → 404s / deploy-doors mismatch.
+- [ ] **Step 3: Implement** the two handlers, the field, the two `routeDecls` entries (`Kind: kindCLI, Allow: svcrole.Allow(svcrole.Publish, svcrole.Deploy)`) with a comment naming #1389 and the design path. If `TestParityTableCoversConsoleRoutes` names them, add rows; it is not expected to (no `/api/cli` rows exist today).
+- [ ] **Step 4: Run, expect PASS** same command, plus `go test ./internal/console -run 'TestParity|TestDeployIsBoundToItsApp' -count=1`.
+- [ ] **Step 5: Commit** `console: read doors for a release's manifest and artifacts` (body names #1389).
+
+---
+
+### Task 2: Ship door honours expected artifact digests
+
+**Files:**
+- Create: `internal/console/apiship_expect.go`
+- Modify: `internal/console/apicli.go` (`shipMeta` field; two one-line calls in `handleAPIShip`)
+- Modify: `internal/console/apiship_rootfs.go` (one call in `shipRootfsParts`)
+- Test: `internal/console/apiship_expect_test.go`
+
+**Interfaces:**
+- Produces (wire): meta field `expect_artifacts`, object keyed by artifact key (`linux-arm64`…, `site.tar.gz`, `rootfs-linux-arm64`), each `{"sha256": "<64 lowercase hex>", "size": <int>}`.
+- Produces (Go):
+ - `type shipExpect struct { SHA256 string `json:"sha256"`; Size int64 `json:"size"` }`
+ - `shipMeta.ExpectArtifacts map[string]shipExpect `json:"expect_artifacts,omitempty"``
+ - `func checkShipExpectShape(kind string, expect map[string]shipExpect, rootfsSize int64) error` — nil when `expect == nil`.
+ - `func checkShipExpected(expect map[string]shipExpect, got map[string]release.Artifact) error` — nil when `expect == nil`.
+
+Placement (both before anything is written and before the `release.GetManifest` existing-version short-circuit, so a forged digest on an existing version is refused too):
+- `checkShipExpectShape`: in `handleAPIShip` right after the rootfs/non-rootfs `upload.lower(...)` block, before `CheckShipKind`. Refuse with `refuseUnread(w, 400, err.Error())` (no part read yet).
+- `checkShipExpected` binary/static: after the part loop's `len(files) == 0` check, before `s.store.AppFlags`; `jsonError(w, 400, err.Error())`.
+- `checkShipExpected` rootfs: in `shipRootfsParts` after the trailing `mr.NextPart()` EOF check, against `map[string]release.Artifact{release.RootfsArtifactKey: {SHA256: sum, Size: meta.RootfsSize}}`; the deferred `os.RemoveAll(dir)` already clears the spool.
+
+Rules and strings (`%s` is the artifact key):
+- Shape: key must be a valid part name for the kind (`targetRe` for binary, `site.tar.gz` for static, `release.RootfsArtifactKey` for rootfs) else `expect_artifacts names %s, which a %s release cannot carry`; sha256 64 lowercase hex and size > 0 else `expect_artifacts for %s needs a sha256 of 64 hex characters and a size above zero`; more keys than the kind's part cap → the first rule's message for the extra key; rootfs: size must equal `rootfs_size` else `expect_artifacts says %d bytes for rootfs-linux-arm64 but rootfs_size says %d`.
+- Match (keys checked in sorted order, first failure wins): expected but not sent → `%s was expected but not sent, so nothing was stored`; sent but not expected → `%s was sent but not expected, so nothing was stored`; differs → `%s does not match the release it was copied from, so nothing was stored`.
+
+- [ ] **Step 1: Write the failing tests** (helpers `postShip`, `metaOf`, `shipPart`, `rootfsShipFixture`, `wantRefusedUnread`, `assertNothingWritten`, `assertScratchEmpty` exist). App `shop` throughout. "Nothing stored" means `release.GetManifest` returns `os.ErrNotExist` AND `fx.rel` has no object at `release.ArtifactKey("bab", "shop", ver, "linux-arm64")`.
+ - `TestAPIShipExpectMatchingShips`: binary with correct expect → 201; stored artifact sha256/size equal the expect.
+ - `TestAPIShipExpectRefusesForgedDigest`: expect sha256 of other bytes → 400, message contains `does not match the release it was copied from`; nothing stored.
+ - `TestAPIShipExpectRefusesMissingAndExtraParts`: expect `linux-arm64`+`linux-amd64`, send only arm64 → 400 `linux-amd64 was expected but not sent`; expect only arm64, send both → 400 `linux-amd64 was sent but not expected`; nothing stored in both.
+ - `TestAPIShipExpectRefusesForgedOnExistingVersion`: ship v1 without expect (201), re-ship identical bytes as v1 with a forged expect → 400 (not 200); stored manifest unchanged.
+ - `TestAPIShipExpectStatic`: `site.tar.gz` correct → 201; forged → 400, nothing stored.
+ - `TestAPIShipExpectRootfs`: correct → 201; forged sha → 400, `assertNothingWritten`, `assertScratchEmpty`; expect size ≠ `rootfs_size` → `wantRefusedUnread` 400 with the rootfs size message.
+ - `TestAPIShipExpectMalformed`: table (bad hex, size 0, key `rootfs-linux-arm64` on a binary ship, key `../x`) → 400 with the shape messages, refused before any part is read (use `postShipUnread` byte count as the rootfs tests do).
+- [ ] **Step 2: Run, expect FAIL** `go test ./internal/console -run 'TestAPIShipExpect' -count=1`.
+- [ ] **Step 3: Implement** the type, field and two functions in `apiship_expect.go`; add the three one-line call sites.
+- [ ] **Step 4: Run, expect PASS** `go test ./internal/console -run 'TestAPIShip' -count=1` (the whole ship family, to prove no-expect ships are unchanged).
+- [ ] **Step 5: Commit** `console: ship refuses artifacts that differ from expect_artifacts`.
+
+---
+
+### Task 3: `carlos releases pull`
+
+**Files:**
+- Create: `release_pull.go`
+- Modify: `commands.go` (`releasesCommand` children: `noHint(rawErr("pull", cust, runReleasesPull))`)
+- Modify: `parity/parity.tsv` (row after `channels`: `releases-pull releases cli-only releases pull Copies a shipped release out of a console and checks every file against its digests.`), then `make parity-doc`
+- Modify: `docs/site/cli.md` (`#### carlos releases pull` under `### carlos releases`, ~line 1012)
+- Create: `release_copy_e2e_test.go` (shared fixture, Task 4 extends it)
+- Test: `release_pull_test.go`
+
+**Interfaces:**
+- Consumes: Task 1 doors.
+- Produces:
+ - `func runReleasesPull(args []string) error`
+ - `func pullRelease(ctx context.Context, sess *apiSession, a apiAcct, app, version, out string) (*release.Manifest, error)`
+ - `func (s *apiSession) releaseManifestRaw(ctx context.Context, a apiAcct, app, version string) ([]byte, error)` (via `s.c.doStream`, body capped at `releaseManifestMaxBytes = 1 << 20`; non-2xx → `apiErrorFromBody`)
+ - `func (s *apiSession) pullArtifact(ctx context.Context, a apiAcct, app, version string, art release.Artifact, dst string) error`
+ - `func validPulledFile(name string) bool` — non-empty, `name == filepath.Base(name)`, no `/` or `\`, not `.`/`..`, not `manifest.json`, no `.partial` suffix.
+ - Test fixture in `release_copy_e2e_test.go`: `type copyConsole struct { url, storeDir string; st *console.Store; rel release.Store; pub ... }` and `func newCopyConsole(t *testing.T, app string) copyConsole` (built as `TestE2ECLIThroughConsole` builds its console, plus `SeedScratchDir: filepath.Join(tmp, "seeds")`; creates `app` in `OpsAccountID` with owner `paul@keymail.dev`); `func (c copyConsole) token(t *testing.T, app string, role svcrole.Role) string` via `NewServicePrincipalScoped(OpsAccountID, "ci-"+role, app, role, []string{"canary", "edge"} for Deploy else nil, nil, ...)`; `func useConsole(t *testing.T, c copyConsole, token string)` sets `CARLOS_CONSOLE` and `CARLOS_SERVICE_TOKEN` with `t.Setenv`.
+
+Behaviour of `pullRelease`, in order: if `<out>/manifest.json` exists → `%s already holds a release. pull into a new or empty directory`; `os.MkdirAll(out, 0o755)`; fetch manifest raw; unmarshal into `release.Manifest`; refuse if `m.Version != version`, no artifacts, any `File` fails `validPulledFile` (`the release names a file %q that cannot be written safely`), or two artifacts share a `File`; pull each artifact in sorted key order; write `manifest.json` last with the exact fetched bytes (`O_CREATE|O_EXCL`, 0o644), so a dir holding `manifest.json` is always complete.
+
+`pullArtifact`: GET door, stream to `dst+".partial"` (`O_CREATE|O_TRUNC`) through `io.LimitReader(body, art.Size+1)` and sha256; mismatch or error → remove the partial, return `%s: got %d bytes with sha256 %s but the release says %d bytes with sha256 %s. the partial file was removed`; success → `os.Rename` over `dst` (overwrites a leftover from an interrupted pull). Context per artifact: `shipRootfsTimeout` for rootfs, `shipTimeout` otherwise.
+
+`runReleasesPull`: flags `appFlag`, `accountFlags`, `consoleOption`, `--out` (required); positional version via `parseInterspersed`; usage `usage: carlos releases pull <version> --app <a> --out <dir> [--account <sqid-or-name>] [--account-id <sqid>] [--console <origin>]`; `resolveMode` nil session → `carlos releases pull reads from a console. set CARLOS_CONSOLE or run carlos login`; prints `pulled %s %s into %s: %d files, every digest matches`.
+
+- [ ] **Step 1: Write the failing tests** (`release_pull_test.go`; each starts `useTempCredentials(t); clearDeploymentEnv(t)`; source is `newCopyConsole(t, "shop")`, seeded with `runShip` under a Publish token, version `v12`, label `fixing modals`):
+ - `TestReleasesPullWritesManifestAndArtifacts`: `runReleasesPull([]string{"v12", "--app", "shop", "--out", dir})` with a Deploy token → nil; `dir/manifest.json` bytes equal `release.GetManifestRaw` from A; `dir/linux-arm64` bytes equal the shipped payload; no `*.partial` left.
+ - `TestReleasesPullRefusesADirThatHoldsARelease`: pull twice into one dir → second error contains `already holds a release`.
+ - `TestReleasesPullFinishesAnIncompleteDir`: pre-write junk at `dir/linux-arm64`, no manifest → pull succeeds, bytes correct.
+ - `TestReleasesPullRemovesACorruptDownload`: after the ship, overwrite the artifact object on A's disk (`filepath.Join(a.storeDir, release.ArtifactKey(...))`, same length, one byte flipped) → error contains `the partial file was removed`; neither `linux-arm64`, `linux-arm64.partial` nor `manifest.json` in `dir`.
+ - `TestReleasesPullNeedsAConsole`: no console env, bucket env set to a temp dir → error equals the bucket-mode string.
+ - `TestValidPulledFile`: table, true for `linux-arm64`, `site.tar.gz`, `rootfs.squashfs`; false for `""`, `.`, `..`, `../x`, `a/b`, `a\b`, `manifest.json`, `linux-arm64.partial`.
+- [ ] **Step 2: Run, expect FAIL** `go test . -run 'TestReleasesPull|TestValidPulledFile' -count=1`.
+- [ ] **Step 3: Implement** `release_pull.go`, register the leaf, parity row + `make parity-doc`, and the cli.md entry: what it writes, that it checks every file, that the dir can be a CI artifact, one fenced example `carlos releases pull v12 --app shop --out ./release`.
+- [ ] **Step 4: Run, expect PASS** same command plus `go test ./internal/docsite ./internal/parity -count=1`; then `GOOS=darwin go build . && GOOS=windows go build .`.
+- [ ] **Step 5: Commit** `cli: carlos releases pull copies a release out of a console`.
+
+---
+
+### Task 4: `carlos ship --from-release` and the two-console witness
+
+**Files:**
+- Create: `ship_from_release.go`
+- Modify: `cli.go` `runShip` (one flag, one branch; no new `log.Fatal`)
+- Modify: `docs/site/cli.md` (`--from-release` paragraph under `### carlos ship`)
+- Modify: `release_copy_e2e_test.go` (the witness tests)
+- Test: `ship_from_release_test.go`
+
+**Interfaces:**
+- Consumes: Task 2 wire field; Task 3 `validPulledFile`, `copyConsole`, `newCopyConsole`, `useConsole`, `pullRelease`.
+- Produces:
+ - `type fromReleaseOpts struct { dir, app, console, acctRaw, acctIDRaw string; programChange bool; messageFlags mutationMessageFlags }` (match the types `accountFlags` returns)
+ - `func runShipFromRelease(fs *flag.FlagSet, o fromReleaseOpts) error`
+ - `func fromReleaseConflicts(fs *flag.FlagSet) error`
+ - `func loadReleaseDir(dir string) (*release.Manifest, map[string]string, error)` (parts: artifact key → local path `dir/File`)
+ - `func (s *apiSession) shipFromRelease(ctx context.Context, a apiAcct, app string, m *release.Manifest, parts map[string]string, programChange bool, message string) (apiShipResult, error)`
+ - `func compareShippedArtifacts(want map[string]release.Artifact, body []byte) error`
+
+`runShip` change: `fromRelease := fs.String("from-release", "", "a directory written by carlos releases pull. ships its files and settings unchanged")`. Branch right after `checkEnv, err := shipEnvRefusal(...)`, reusing that call's `log.Fatal`:
+```go
+if err == nil && *fromRelease != "" {
+ if err = runShipFromRelease(fs, fromReleaseOpts{...}); err == nil {
+ return
+ }
+}
+if err != nil {
+ log.Fatal(err)
+}
+```
+
+`fromReleaseConflicts`: allowed flags are `from-release app account account-id console destination d message no-prompt program-change` (drop any that `runShip`'s FlagSet does not define); the first other flag set (via `fs.Visit`, sorted) → `--from-release ships the release's own settings, so it cannot be combined with --%s`; any positional arg → `--from-release ships the files in its directory, so it takes no file arguments`.
+
+`loadReleaseDir`: read `dir/manifest.json` (missing → `%s has no manifest.json. run carlos releases pull first`); unmarshal; kind must be `binary`, `static` or `rootfs`; each `File` passes `validPulledFile`; hash each file (size + sha256) → mismatch `%s does not match manifest.json, so nothing was shipped`.
+
+`runShipFromRelease`: `fromReleaseConflicts`, then `resolveMode`; nil session → `carlos ship --from-release ships through a console. set CARLOS_CONSOLE or run carlos login`; `loadReleaseDir` BEFORE any request; resolve account/app as `runShipAPI`'s caller does; `resolveMutationMessage`; ship; print `shipped %s %s from %s, every digest matches the source` or on NoOp `already shipped %s %s with identical content, nothing to do`.
+
+`shipFromRelease` meta (one struct, `omitempty` as `apiSession.ship` and `shipRootfs` use): `version` = `m.Version`, `kind`, `label`, `notes`, `message`, `capabilities` (marshal of `m.Capabilities` when non-nil), `program_change` = `m.ProgramChange || programChange`, `swap`, `stateless`, `mail`, `assets` = `m.Assets`; rootfs adds `processes` (marshal of `m.Processes`), `hibernate`, `jit`, `rootfs_size` = `m.Artifacts[release.RootfsArtifactKey].Size`; always `expect_artifacts` from `m.Artifacts`. Parts in sorted key order via `writeFilePart`. Timeout `shipRootfsTimeout` for rootfs else `shipTimeout`. On 200/201: `checkCapabilitiesEcho(m.Capabilities, body)`, `checkStatelessEcho`, `checkMailEcho`, `checkSwapEcho`, then `compareShippedArtifacts(m.Artifacts, body)`; other statuses → `apiErrorFromBody` (so a 409 for different bytes under the same version surfaces as today).
+
+`compareShippedArtifacts`: decode `{"artifacts": {key: {sha256, size}}}`; any key missing, extra or different → `the console stored %s with a different digest than the source release. do not promote this version`.
+
+- [ ] **Step 1: Write the failing tests.**
+ `release_copy_e2e_test.go` (A = `newCopyConsole(t, "shop")`, B = `newCopyConsole(t, "storefront")`; ship to A with `runShip` under A's Publish token with `--label "fixing modals" --notes "first cut" --swap hold`; pull with A's Deploy token via `runReleasesPull`):
+ - `TestE2EReleaseCopyAcrossConsoles`: `useConsole(B, B Deploy token)`; `runShip([]string{"--from-release", dir, "--app", "storefront"})`; stdout contains `every digest matches the source`; B's `release.GetManifest(..., "storefront", "v12")` has `Artifacts` deep-equal (sha256, size, file) to A's, same label, notes, swap; B's `App == "storefront"`, `BuiltBy` starts `console-api`; `runPromote([]string{"--app", "storefront", "v12", "edge"})` succeeds and `release.Channel(ctx, B.rel, B.pub, release.OpsAccount, "storefront", "edge")` reads `v12` (B's own key signed it); a second `runShip --from-release` prints `already shipped`.
+ - `TestE2EReleaseCopyRefusesATamperedFile`: flip one byte in `dir/linux-arm64`; `runShipFromRelease` (direct, to get the error) → error contains `does not match manifest.json`; B has no manifest for `v12` and no object at `release.ArtifactKey(..., "storefront", "v12", "linux-arm64")`.
+ - `TestE2EReleaseCopyForgedExpectIsRefusedByTheConsole`: raw multipart POST (built with `mime/multipart` in the test) to B's `/api/cli/apps/bab/storefront/releases` with B's Deploy token: meta `{"version":"v12","kind":"binary","expect_artifacts":{"linux-arm64":{"sha256":<sha of other bytes>,"size":<len>}}}` and the pulled `linux-arm64` → 400; nothing stored on B.
+ - `TestE2EReleaseCopyDifferentBytesUnderTheSameVersion`: ship other bytes to B as `v12` first; `runShipFromRelease` → error (409 path); B's `v12` manifest unchanged.
+ - `TestE2EReleaseCopyRootfs`: seed A with a rootfs release through `release.ShipSpooled` (manifest with `Kind: release.KindRootfs`, a `web` process, `Hibernate: true`, artifact `rootfs-linux-arm64` → file `rootfs.squashfs` of 4 KiB); pull; ship `--from-release` to B; B's artifacts, processes and hibernate equal A's. If B's rootfs door needs more than `SeedScratchDir` to accept it, stop and report rather than stubbing.
+ `ship_from_release_test.go`:
+ - `TestShipFromReleaseRefusesOtherFlags`: with `sharedCarlos(t)` run `carlos ship --from-release <dir> --app shop --label x` and `... --app shop ./bin` → non-zero exit, stderr contains the two conflict messages.
+ - `TestCompareShippedArtifacts`: table over response bodies: identical → nil; different sha → error; extra key → error; missing key → error; body with no `artifacts` (an old console) → error.
+ - `TestLoadReleaseDirRefusesUnsafeNames`: a hand-written `manifest.json` naming `../x` → error before any file is read.
+- [ ] **Step 2: Run, expect FAIL** `go test . -run 'TestE2EReleaseCopy|TestShipFromRelease|TestCompareShippedArtifacts|TestLoadReleaseDir' -count=1`.
+- [ ] **Step 3: Implement** `ship_from_release.go` and the `runShip` change; cli.md paragraph under `### carlos ship` naming the allowed flags and that a different file stops the ship before upload.
+- [ ] **Step 4: Run, expect PASS** same command, plus `go test . -run 'TestE2ECLIThroughConsole' -count=1`, `go test ./internal/docsite -count=1`, cross-compile darwin and windows, `make code-health`.
+- [ ] **Step 5: Commit** `cli: carlos ship --from-release ships a pulled release unchanged`.
+
+---
+
+### Task 5: Docs: the CI recipe and the release-once line
+
+**Files:**
+- Modify: `docs/site/cli.md` (new `#### Staging tests X, production promotes X` after `#### Deploying one checkout to several places`, ~line 571)
+- Modify: `docs/site/stateless-replicas.md` `## Deploys` first sentence
+
+- [ ] **Step 1: Write the recipe.** Two CI jobs, one credential each: job 1 on the staging console (`CARLOS_CONSOLE=https://staging.example.com`, a deploy credential for `shop`) runs `carlos ship`, the tests, then `carlos releases pull v12 --app shop --out release`, and uploads `release/` as a CI artifact; job 2 on production (`CARLOS_CONSOLE=https://carlos.example.com`, its own deploy credential) downloads it and runs `carlos ship --from-release release --app shop` then `carlos promote --app shop v12 edge`. Say: the bytes are identical, each console writes and signs its own manifest, and production refuses a file that differs.
+- [ ] **Step 2: Edit stateless-replicas.md** so the first `## Deploys` sentence reads: `A deploy runs the release command once per instance, not once per copy, then switches its copies one box at a time.`
+- [ ] **Step 3: Run** `go test ./internal/docsite -count=1` → PASS (fenced verbs and `/docs` links resolve).
+- [ ] **Step 4: Commit** `docs: promote a tested release from staging to production`.
diff --git a/internal/console/apicli.go b/internal/console/apicli.go
index a0f6390dd..f19c892c9 100644
--- a/internal/console/apicli.go
+++ b/internal/console/apicli.go
@@ -2152,6 +2152,9 @@ type shipMeta struct {
// Assets is the release's asset folders (`carlos ship --assets`,
// edge asset cache spec). ADDITIVE: absent without the flag.
Assets *release.Assets `json:"assets,omitempty"`
+ // ExpectArtifacts is the digests a release copied from another console
+ // was copied with (apiship_expect.go). ADDITIVE: absent from a plain ship.
+ ExpectArtifacts map[string]shipExpect `json:"expect_artifacts,omitempty"`
}
// handleAPIShip answers `carlos ship`: a multipart upload of one release's
@@ -2436,22 +2439,7 @@ func (s *Server) handleAPIShip(w http.ResponseWriter, r *http.Request) {
}
upload.lower(apiShipMaxBytes)
}
- // An app's kind and hibernation are fixed by its first ship, so a
- // release of another kind, or a rootfs release with the other
- // hibernation, is refused here, before any part is read. The check is
- // advisory: release.Ship and release.ShipSpooled repeat it at
- // publication, which is what decides a race between two first ships.
- kctx, kcancel := context.WithTimeout(r.Context(), 20*time.Second)
- stub := release.Manifest{App: app, Version: ver, Kind: meta.Kind, Hibernate: meta.Hibernate}
- kerr := release.CheckShipKind(kctx, s.cfg.Releases, acct.Sqid, &stub)
- kcancel()
- if kerr != nil {
- if msg, ok := shipKindConflict(kerr); ok {
- refuseUnread(w, http.StatusConflict, msg)
- return
- }
- log.Printf("console: api ship %s/%s %s: kind check: %v", acct.Sqid, app, ver, kerr)
- refuseUnread(w, http.StatusServiceUnavailable, shipKindUnchecked)
+ if s.refuseShipPreflight(w, r, acct, app, ver, meta) {
return
}
if rootfs {
@@ -2524,8 +2512,7 @@ func (s *Server) handleAPIShip(w http.ResponseWriter, r *http.Request) {
Size: int64(len(b)),
}
}
- if len(files) == 0 {
- jsonError(w, http.StatusBadRequest, "no artifact parts in the upload")
+ if refuseShipUpload(w, files, meta.ExpectArtifacts, artifacts) {
return
}
diff --git a/internal/console/apirelease_read.go b/internal/console/apirelease_read.go
new file mode 100644
index 000000000..e20844a34
--- /dev/null
+++ b/internal/console/apirelease_read.go
@@ -0,0 +1,125 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "io"
+ "log"
+ "net/http"
+ "os"
+ "strconv"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The release read doors (#1389 item 1, design
+// .superpowers/sdd/2026-11-25-1389/DESIGN.md): the source half of copying a
+// shipped release from one console to another. A pipeline reads the stored
+// manifest and streams each artifact it names; the target console re-hashes
+// what it is sent, so these doors serve bytes and never vouch for them. No
+// audit row: they are reads, like GET .../releases.
+
+const (
+ // releaseReadsMax is how many artifact downloads may stream at once.
+ releaseReadsMax = 4
+ // releaseReadDeadline bounds one artifact download, rootfs ship's own
+ // bound: an image that may take that long to arrive may take as long to
+ // leave.
+ releaseReadDeadline = 75 * time.Minute
+)
+
+// releaseReadManifest is the shared head of both doors: the app gate, the
+// version check and the manifest read. ok false means it has answered.
+func (s *Server) releaseReadManifest(ctx context.Context, w http.ResponseWriter, r *http.Request) (*release.Manifest, []byte, *Account, string, string, bool) {
+ _, acct, app, ok := s.apiAccountApp(w, r)
+ if !ok {
+ return nil, nil, nil, "", "", false
+ }
+ version := r.PathValue("version")
+ if !release.ValidVersion(version) {
+ jsonError(w, http.StatusBadRequest, "invalid version")
+ return nil, nil, nil, "", "", false
+ }
+ m, raw, err := release.GetManifestRaw(ctx, s.cfg.Releases, acct.Sqid, app, version)
+ if errors.Is(err, os.ErrNotExist) {
+ jsonError(w, http.StatusNotFound, "release not found")
+ return nil, nil, nil, "", "", false
+ }
+ if err != nil {
+ log.Printf("console: api release read %s/%s %s: %v", acct.Sqid, app, version, err)
+ jsonError(w, http.StatusBadGateway, "could not read the release")
+ return nil, nil, nil, "", "", false
+ }
+ return m, raw, acct, app, version, true
+}
+
+// handleAPIReleaseManifest answers GET .../releases/{version}/manifest with
+// the exact bytes the store holds, so a copy can be checked against them.
+func (s *Server) handleAPIReleaseManifest(w http.ResponseWriter, r *http.Request) {
+ ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
+ defer cancel()
+ _, raw, _, _, _, ok := s.releaseReadManifest(ctx, w, r)
+ if !ok {
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(raw)
+}
+
+// handleAPIReleaseArtifact streams GET .../releases/{version}/artifacts/{file}.
+// {file} must be an artifact's File in the manifest (rootfs:
+// rootfs.squashfs), never the manifest's map key and never any other object
+// under the release's prefix.
+func (s *Server) handleAPIReleaseArtifact(w http.ResponseWriter, r *http.Request) {
+ ctx, cancel := context.WithTimeout(r.Context(), releaseReadDeadline)
+ defer cancel()
+ m, _, acct, app, version, ok := s.releaseReadManifest(ctx, w, r)
+ if !ok {
+ return
+ }
+ file := r.PathValue("file")
+ var a release.Artifact
+ found := false
+ for _, x := range m.Artifacts {
+ if x.File == file {
+ a, found = x, true
+ break
+ }
+ }
+ if !found {
+ jsonError(w, http.StatusNotFound, "file not in this release")
+ return
+ }
+ // Non-blocking, as shipSem: a full set of slots is "busy right now",
+ // not a queue behind someone else's slow download.
+ select {
+ case s.releaseReads <- struct{}{}:
+ default:
+ retryAfter(w, 2*time.Second)
+ jsonError(w, http.StatusTooManyRequests, "too many release downloads at once. try again shortly")
+ return
+ }
+ defer func() { <-s.releaseReads }()
+ body, _, err := release.OpenObjectStreaming(ctx, s.cfg.Releases, release.ArtifactKey(acct.Sqid, app, version, a.File))
+ if err != nil {
+ log.Printf("console: api release artifact %s/%s %s %s: %v", acct.Sqid, app, version, a.File, err)
+ jsonError(w, http.StatusBadGateway, "could not read the release")
+ return
+ }
+ defer body.Close()
+ if err := http.NewResponseController(w).SetWriteDeadline(time.Now().Add(releaseReadDeadline)); err != nil && !errors.Is(err, http.ErrNotSupported) {
+ log.Printf("console: api release artifact %s/%s %s %s: write deadline: %v", acct.Sqid, app, version, a.File, err)
+ }
+ h := w.Header()
+ h.Set("Content-Type", "application/octet-stream")
+ h.Set("Content-Length", strconv.FormatInt(a.Size, 10))
+ h.Set("X-Content-SHA256", a.SHA256)
+ w.WriteHeader(http.StatusOK)
+ // A short copy is only logged: the status is already sent, and the
+ // caller's own size and hash check refuses what it got.
+ if n, err := io.Copy(w, io.LimitReader(body, a.Size)); err != nil || n != a.Size {
+ log.Printf("console: api release artifact %s/%s %s %s: sent %d of %d bytes: %v", acct.Sqid, app, version, a.File, n, a.Size, err)
+ }
+}
diff --git a/internal/console/apirelease_read_test.go b/internal/console/apirelease_read_test.go
new file mode 100644
index 000000000..46442beee
--- /dev/null
+++ b/internal/console/apirelease_read_test.go
@@ -0,0 +1,190 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// The release read doors (#1389 item 1): a pipeline reads a shipped
+// release's manifest and artifacts so another console can ship the same
+// bytes.
+
+// streamReleases makes the fixture's store stream as S3 does: the artifact
+// door reads with release.OpenObjectStreaming and never buffers.
+func streamReleases(t *testing.T, fx *consoleFixture) {
+ t.Helper()
+ d, ok := fx.rel.(*deletableStore)
+ if !ok {
+ t.Fatalf("fixture store is %T, not *deletableStore", fx.rel)
+ }
+ d.streams.Store(true)
+}
+
+// releaseFixture is deployFixture over a streaming store.
+func releaseFixture(t *testing.T) (fx *consoleFixture, person, deploy string) {
+ t.Helper()
+ fx, person, deploy = deployFixture(t)
+ streamReleases(t, fx)
+ return fx, person, deploy
+}
+
+func releaseReadURL(fx *consoleFixture, app, rest string) string {
+ return fx.ts.URL + "/api/cli/apps/bab/" + app + "/releases/" + rest
+}
+
+func TestAPIReleaseManifestReturnsStoredBytes(t *testing.T) {
+ fx, _, tok := releaseFixture(t)
+ status, h, body := rawReq(t, http.MethodGet, releaseReadURL(fx, "hello", "v1/manifest"), tok, "")
+ if status != http.StatusOK {
+ t.Fatalf("manifest = %d %s, want 200", status, body)
+ }
+ if ct := h.Get("Content-Type"); ct != "application/json" {
+ t.Fatalf("Content-Type = %q, want application/json", ct)
+ }
+ _, raw, err := release.GetManifestRaw(context.Background(), fx.rel, "bab", "hello", "v1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal([]byte(body), raw) {
+ t.Fatalf("manifest body is not the stored bytes:\n got %q\nwant %q", body, raw)
+ }
+}
+
+func TestAPIReleaseArtifactStreamsBytes(t *testing.T) {
+ fx, _, tok := releaseFixture(t)
+ status, h, body := rawReq(t, http.MethodGet, releaseReadURL(fx, "hello", "v1/artifacts/linux-arm64"), tok, "")
+ if status != http.StatusOK || body != "bin v1" {
+ t.Fatalf("artifact = %d %q, want 200 %q", status, body, "bin v1")
+ }
+ sum := sha256.Sum256([]byte("bin v1"))
+ if got := h.Get("Content-Length"); got != "6" {
+ t.Fatalf("Content-Length = %q, want 6", got)
+ }
+ if got := h.Get("X-Content-SHA256"); got != hex.EncodeToString(sum[:]) {
+ t.Fatalf("X-Content-SHA256 = %q, want %q", got, hex.EncodeToString(sum[:]))
+ }
+ if ct := h.Get("Content-Type"); ct != "application/octet-stream" {
+ t.Fatalf("Content-Type = %q, want application/octet-stream", ct)
+ }
+}
+
+func TestAPIReleaseArtifactRefusesWhatTheManifestDoesNotName(t *testing.T) {
+ fx, _, tok := releaseFixture(t)
+ for _, c := range []struct {
+ rest string
+ want int
+ }{
+ {"v1/artifacts/manifest.json", http.StatusNotFound},
+ {"v1/artifacts/linux-amd64", http.StatusNotFound},
+ {"v1/artifacts/..%2Fv2%2Flinux-arm64", http.StatusNotFound},
+ {"v9/manifest", http.StatusNotFound},
+ {"v9/artifacts/linux-arm64", http.StatusNotFound},
+ // "..bad" passes release.ValidVersion (one segment, no slash, so it
+ // cannot climb out); it is simply not a release.
+ {"..bad/manifest", http.StatusNotFound},
+ {"bad!v/manifest", http.StatusBadRequest},
+ } {
+ status, _, body := rawReq(t, http.MethodGet, releaseReadURL(fx, "hello", c.rest), tok, "")
+ if status != c.want {
+ t.Errorf("%s = %d %s, want %d", c.rest, status, body, c.want)
+ }
+ }
+}
+
+func TestAPIReleaseReadRoles(t *testing.T) {
+ fx, person, deploy := releaseFixture(t)
+ manifest := releaseReadURL(fx, "hello", "v1/manifest")
+ artifact := releaseReadURL(fx, "hello", "v1/artifacts/linux-arm64")
+
+ publish, err := fx.st.NewServicePrincipalScoped(OpsAccountID, "pub", "hello", svcrole.Publish, nil, nil, "paul@keymail.dev", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, u := range []string{manifest, artifact} {
+ if status, _, body := rawReq(t, http.MethodGet, u, publish, ""); status != http.StatusOK {
+ t.Errorf("publish %s = %d %s, want 200", u, status, body)
+ }
+ if status, _, body := rawReq(t, http.MethodGet, u, person, ""); status != http.StatusOK {
+ t.Errorf("person %s = %d %s, want 200", u, status, body)
+ }
+ }
+
+ // Operate gets whatever the releases list gives it: the read doors are
+ // release metadata exactly as that list is.
+ operate, err := fx.st.NewServicePrincipalScoped(OpsAccountID, "ops", "hello", svcrole.Operate, nil, nil, "paul@keymail.dev", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ listStatus, _, _ := rawReq(t, http.MethodGet, fx.ts.URL+"/api/cli/apps/bab/hello/releases", operate, "")
+ if listStatus == http.StatusOK {
+ t.Fatalf("operate on the releases list = 200; the test's premise is gone")
+ }
+ for _, u := range []string{manifest, artifact} {
+ if status, _, body := rawReq(t, http.MethodGet, u, operate, ""); status != listStatus {
+ t.Errorf("operate %s = %d %s, want %d (the releases list's answer)", u, status, body, listStatus)
+ }
+ }
+
+ // The fixture's deploy credential is bound to hello: a sibling app's
+ // release, which exists, is the same 404 as no app at all.
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "other", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ liftShipBudget(fx)
+ if status, out := postShip(t, fx.ts.URL+"/api/cli/apps/bab/other/releases", person,
+ []shipPart{metaPart(t, "v1", "binary"), {name: "linux-arm64", body: []byte("other v1")}}); status != http.StatusCreated {
+ t.Fatalf("ship other = %d %v", status, out)
+ }
+ if status, _, body := rawReq(t, http.MethodGet, releaseReadURL(fx, "other", "v1/manifest"), deploy, ""); status != http.StatusNotFound {
+ t.Errorf("deploy bound to hello on other = %d %s, want 404", status, body)
+ }
+}
+
+func TestAPIReleaseArtifactRootfs(t *testing.T) {
+ fx := rootfsShipFixture(t)
+ streamReleases(t, fx.fx)
+ img := randomBytes(t, 3<<20)
+ if status, out := postShip(t, fx.url("shop"), fx.token, []shipPart{rootfsMeta(t, "0.1.0-1", len(img), false), {name: "rootfs-linux-arm64", body: img}}); status != http.StatusCreated {
+ t.Fatalf("ship = %d %v", status, out)
+ }
+ base := fx.fx.ts.URL + "/api/cli/apps/bab/shop/releases/0.1.0-1/artifacts/"
+ status, h, body := rawReq(t, http.MethodGet, base+release.RootfsArtifactFile, fx.token, "")
+ if status != http.StatusOK || !bytes.Equal([]byte(body), img) {
+ t.Fatalf("rootfs artifact = %d (%d bytes), want 200 and the image", status, len(body))
+ }
+ sum := sha256.Sum256(img)
+ if h.Get("X-Content-SHA256") != hex.EncodeToString(sum[:]) {
+ t.Fatalf("X-Content-SHA256 = %q", h.Get("X-Content-SHA256"))
+ }
+ // The manifest's key is not a file name.
+ if status, _, body := rawReq(t, http.MethodGet, base+"rootfs-linux-arm64", fx.token, ""); status != http.StatusNotFound {
+ t.Fatalf("by the artifact key = %d %s, want 404", status, body)
+ }
+}
+
+func TestAPIReleaseArtifactBusy(t *testing.T) {
+ fx, _, tok := releaseFixture(t)
+ for range cap(fx.srv.releaseReads) {
+ fx.srv.releaseReads <- struct{}{}
+ }
+ u := releaseReadURL(fx, "hello", "v1/artifacts/linux-arm64")
+ status, h, body := rawReq(t, http.MethodGet, u, tok, "")
+ if status != http.StatusTooManyRequests || h.Get("Retry-After") == "" {
+ t.Fatalf("full = %d %q %s, want 429 with Retry-After", status, h.Get("Retry-After"), body)
+ }
+ if want := `{"error":"too many release downloads at once. try again shortly"}` + "\n"; body != want {
+ t.Fatalf("full body = %q, want %q", body, want)
+ }
+ <-fx.srv.releaseReads
+ if status, _, body := rawReq(t, http.MethodGet, u, tok, ""); status != http.StatusOK || body != "bin v1" {
+ t.Fatalf("after a slot frees = %d %q, want 200", status, body)
+ }
+}
diff --git a/internal/console/apiship_expect.go b/internal/console/apiship_expect.go
new file mode 100644
index 000000000..9b4d2a409
--- /dev/null
+++ b/internal/console/apiship_expect.go
@@ -0,0 +1,136 @@
+package console
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "net/http"
+ "regexp"
+ "sort"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// A release copied from one console to another (#1389 item 1) carries the
+// digests it was copied with, in the meta part's expect_artifacts. The door
+// refuses an upload whose bytes differ from them, so the target stores the
+// exact bytes the source tested or nothing at all. A ship without the field
+// behaves exactly as before.
+
+// shipExpect is one artifact's expected digest and length.
+type shipExpect struct {
+ SHA256 string `json:"sha256"`
+ Size int64 `json:"size"`
+}
+
+var shipExpectSHA256 = regexp.MustCompile(`^[0-9a-f]{64}$`)
+
+// checkShipExpectShape refuses an expect_artifacts the release's kind could
+// never satisfy, before any part is read. nil when expect is nil.
+func checkShipExpectShape(kind string, expect map[string]shipExpect, rootfsSize int64) error {
+ if expect == nil {
+ return nil
+ }
+ maxKeys, valid := apiShipMaxPartsBinary, targetRe.MatchString
+ switch kind {
+ case "static":
+ maxKeys, valid = apiShipMaxPartsStatic, func(k string) bool { return k == "site.tar.gz" }
+ case release.KindRootfs:
+ maxKeys, valid = 1, func(k string) bool { return k == release.RootfsArtifactKey }
+ }
+ for i, key := range sortedExpectKeys(expect) {
+ if !valid(key) || i >= maxKeys {
+ return fmt.Errorf("the copied release names an invalid artifact %s for a %s release", key, kind)
+ }
+ e := expect[key]
+ if !shipExpectSHA256.MatchString(e.SHA256) || e.Size <= 0 {
+ return fmt.Errorf("the copied release's %s artifact needs a 64-character SHA-256 value and a size above zero", key)
+ }
+ if kind == release.KindRootfs && e.Size != rootfsSize {
+ return fmt.Errorf("the copied release's %s artifact is %d bytes, but its rootfs is %d bytes", key, e.Size, rootfsSize)
+ }
+ }
+ return nil
+}
+
+// checkShipExpected refuses an upload whose artifacts differ from expect,
+// before anything is stored. Keys are checked in sorted order over both
+// maps; the first failure wins. nil when expect is nil.
+func checkShipExpected(expect map[string]shipExpect, got map[string]release.Artifact) error {
+ if expect == nil {
+ return nil
+ }
+ keys := sortedExpectKeys(expect)
+ for k := range got {
+ if _, ok := expect[k]; !ok {
+ keys = append(keys, k)
+ }
+ }
+ sort.Strings(keys)
+ for _, k := range keys {
+ e, expected := expect[k]
+ a, sent := got[k]
+ switch {
+ case !sent:
+ return fmt.Errorf("the copied release's %s artifact was not sent, so nothing was stored", k)
+ case !expected:
+ return fmt.Errorf("the upload included unexpected artifact %s, so nothing was stored", k)
+ case a.SHA256 != e.SHA256 || a.Size != e.Size:
+ return fmt.Errorf("artifact %s does not match the source release, so nothing was stored", k)
+ }
+ }
+ return nil
+}
+
+func sortedExpectKeys(expect map[string]shipExpect) []string {
+ keys := make([]string, 0, len(expect))
+ for k := range expect {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ return keys
+}
+
+// refuseShipPreflight runs the checks a ship makes before any part is read:
+// the expect_artifacts shape, then the app's kind and hibernation, which a
+// first ship fixes. A release of another kind, or a rootfs release with the
+// other hibernation, is refused here. The kind check is advisory:
+// release.Ship and release.ShipSpooled repeat it at publication, which is
+// what decides a race between two first ships. It writes the refusal and
+// returns true when the ship must stop.
+func (s *Server) refuseShipPreflight(w http.ResponseWriter, r *http.Request, acct *Account, app, ver string, meta shipMeta) bool {
+ if err := checkShipExpectShape(meta.Kind, meta.ExpectArtifacts, meta.RootfsSize); err != nil {
+ refuseUnread(w, http.StatusBadRequest, err.Error())
+ return true
+ }
+ kctx, kcancel := context.WithTimeout(r.Context(), 20*time.Second)
+ stub := release.Manifest{App: app, Version: ver, Kind: meta.Kind, Hibernate: meta.Hibernate}
+ kerr := release.CheckShipKind(kctx, s.cfg.Releases, acct.Sqid, &stub)
+ kcancel()
+ if kerr == nil {
+ return false
+ }
+ if msg, ok := shipKindConflict(kerr); ok {
+ refuseUnread(w, http.StatusConflict, msg)
+ return true
+ }
+ log.Printf("console: api ship %s/%s %s: kind check: %v", acct.Sqid, app, ver, kerr)
+ refuseUnread(w, http.StatusServiceUnavailable, shipKindUnchecked)
+ return true
+}
+
+// refuseShipUpload refuses a ship with no artifact parts, or whose artifacts
+// differ from expect, before anything is stored. It writes the refusal and
+// returns true when the ship must stop.
+func refuseShipUpload(w http.ResponseWriter, files map[string][]byte, expect map[string]shipExpect, got map[string]release.Artifact) bool {
+ if len(files) == 0 {
+ jsonError(w, http.StatusBadRequest, "no artifact parts in the upload")
+ return true
+ }
+ if err := checkShipExpected(expect, got); err != nil {
+ jsonError(w, http.StatusBadRequest, err.Error())
+ return true
+ }
+ return false
+}
diff --git a/internal/console/apiship_expect_test.go b/internal/console/apiship_expect_test.go
new file mode 100644
index 000000000..52a7e0c8b
--- /dev/null
+++ b/internal/console/apiship_expect_test.go
@@ -0,0 +1,228 @@
+package console
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "net/http"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The ship door's expect_artifacts (#1389 item 1): a release copied from
+// another console carries the digests it was copied with, and the door
+// refuses bytes that differ from them. App shop in account bab.
+
+// expectOf is the expect_artifacts entry for b.
+func expectOf(b []byte) map[string]any {
+ sum := sha256.Sum256(b)
+ return map[string]any{"sha256": hex.EncodeToString(sum[:]), "size": len(b)}
+}
+
+// binaryExpectMeta is a binary meta part at ver with expect attached.
+func binaryExpectMeta(t *testing.T, ver string, expect map[string]any) shipPart {
+ t.Helper()
+ fields := map[string]any{"version": ver, "kind": "binary"}
+ if expect != nil {
+ fields["expect_artifacts"] = expect
+ }
+ return metaOf(t, fields)
+}
+
+// assertNotStored: no manifest for ver and no linux-arm64 artifact either.
+func assertNotStored(t *testing.T, f rootfsShipFx, ver string) {
+ t.Helper()
+ if _, err := release.GetManifest(context.Background(), f.fx.rel, "bab", "shop", ver); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("manifest for %s: err = %v, want not exist", ver, err)
+ }
+ if _, _, err := f.fx.rel.Get(context.Background(), release.ArtifactKey("bab", "shop", ver, "linux-arm64")); err == nil {
+ t.Fatalf("an artifact for %s was stored", ver)
+ }
+}
+
+func wantErrorContains(t *testing.T, what string, status int, out map[string]any, wantStatus int, want string) {
+ t.Helper()
+ if status != wantStatus || !strings.Contains(str(t, out, "error"), want) {
+ t.Fatalf("%s = %d %v, want %d containing %q", what, status, out, wantStatus, want)
+ }
+}
+
+func TestAPIShipExpectMatchingShips(t *testing.T) {
+ fx := rootfsShipFixture(t)
+ bin := randomBytes(t, 4<<10)
+ status, out := postShip(t, fx.url("shop"), fx.token, []shipPart{
+ binaryExpectMeta(t, "0.1.0-1", map[string]any{"linux-arm64": expectOf(bin)}),
+ {name: "linux-arm64", body: bin},
+ })
+ if status != http.StatusCreated {
+ t.Fatalf("ship = %d %v", status, out)
+ }
+ m, err := release.GetManifest(context.Background(), fx.fx.rel, "bab", "shop", "0.1.0-1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ sum := sha256.Sum256(bin)
+ a := m.Artifacts["linux-arm64"]
+ if a.SHA256 != hex.EncodeToString(sum[:]) || a.Size != int64(len(bin)) {
+ t.Fatalf("stored %+v, want the expected digest and size", a)
+ }
+}
+
+func TestAPIShipExpectRefusesForgedDigest(t *testing.T) {
+ fx := rootfsShipFixture(t)
+ bin := randomBytes(t, 4<<10)
+ other := randomBytes(t, 4<<10)
+ status, out := postShip(t, fx.url("shop"), fx.token, []shipPart{
+ binaryExpectMeta(t, "0.1.0-1", map[string]any{"linux-arm64": expectOf(other)}),
+ {name: "linux-arm64", body: bin},
+ })
+ wantErrorContains(t, "forged digest", status, out, http.StatusBadRequest,
+ "artifact linux-arm64 does not match the source release, so nothing was stored")
+ assertNotStored(t, fx, "0.1.0-1")
+}
+
+func TestAPIShipExpectRefusesMissingAndExtraParts(t *testing.T) {
+ fx := rootfsShipFixture(t)
+ arm := randomBytes(t, 4<<10)
+ amd := randomBytes(t, 4<<10)
+
+ status, out := postShip(t, fx.url("shop"), fx.token, []shipPart{
+ binaryExpectMeta(t, "0.1.0-1", map[string]any{"linux-arm64": expectOf(arm), "linux-amd64": expectOf(amd)}),
+ {name: "linux-arm64", body: arm},
+ })
+ wantErrorContains(t, "missing part", status, out, http.StatusBadRequest,
+ "the copied release's linux-amd64 artifact was not sent, so nothing was stored")
+ assertNotStored(t, fx, "0.1.0-1")
+
+ status, out = postShip(t, fx.url("shop"), fx.token, []shipPart{
+ binaryExpectMeta(t, "0.1.0-2", map[string]any{"linux-arm64": expectOf(arm)}),
+ {name: "linux-arm64", body: arm},
+ {name: "linux-amd64", body: amd},
+ })
+ wantErrorContains(t, "extra part", status, out, http.StatusBadRequest,
+ "the upload included unexpected artifact linux-amd64, so nothing was stored")
+ assertNotStored(t, fx, "0.1.0-2")
+}
+
+func TestAPIShipExpectRefusesForgedOnExistingVersion(t *testing.T) {
+ fx := rootfsShipFixture(t)
+ bin := randomBytes(t, 4<<10)
+ if status, out := postShip(t, fx.url("shop"), fx.token, []shipPart{
+ binaryExpectMeta(t, "0.1.0-1", nil), {name: "linux-arm64", body: bin},
+ }); status != http.StatusCreated {
+ t.Fatalf("first ship = %d %v", status, out)
+ }
+ _, before, err := release.GetManifestRaw(context.Background(), fx.fx.rel, "bab", "shop", "0.1.0-1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ status, out := postShip(t, fx.url("shop"), fx.token, []shipPart{
+ binaryExpectMeta(t, "0.1.0-1", map[string]any{"linux-arm64": expectOf(randomBytes(t, 4<<10))}),
+ {name: "linux-arm64", body: bin},
+ })
+ wantErrorContains(t, "forged re-ship", status, out, http.StatusBadRequest,
+ "does not match the source release")
+ _, after, err := release.GetManifestRaw(context.Background(), fx.fx.rel, "bab", "shop", "0.1.0-1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(before) != string(after) {
+ t.Fatalf("stored manifest changed:\n%s\n%s", before, after)
+ }
+}
+
+func TestAPIShipExpectStatic(t *testing.T) {
+ fx := rootfsShipFixture(t)
+ site := randomBytes(t, 2<<10)
+ meta := func(ver string, expect map[string]any) shipPart {
+ return metaOf(t, map[string]any{"version": ver, "kind": "static", "expect_artifacts": expect})
+ }
+ if status, out := postShip(t, fx.url("shop"), fx.token, []shipPart{
+ meta("0.1.0-1", map[string]any{"site.tar.gz": expectOf(site)}), {name: "site.tar.gz", body: site},
+ }); status != http.StatusCreated {
+ t.Fatalf("matching static ship = %d %v", status, out)
+ }
+ status, out := postShip(t, fx.url("shop"), fx.token, []shipPart{
+ meta("0.1.0-2", map[string]any{"site.tar.gz": expectOf(randomBytes(t, 2<<10))}), {name: "site.tar.gz", body: site},
+ })
+ wantErrorContains(t, "forged static", status, out, http.StatusBadRequest,
+ "artifact site.tar.gz does not match the source release, so nothing was stored")
+ if _, err := release.GetManifest(context.Background(), fx.fx.rel, "bab", "shop", "0.1.0-2"); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("forged static manifest: err = %v, want not exist", err)
+ }
+ if _, _, err := fx.fx.rel.Get(context.Background(), release.ArtifactKey("bab", "shop", "0.1.0-2", "site.tar.gz")); err == nil {
+ t.Fatal("forged static artifact was stored")
+ }
+}
+
+func TestAPIShipExpectRootfs(t *testing.T) {
+ fx := rootfsShipFixture(t)
+ img := randomBytes(t, 1<<20)
+ withExpect := func(ver string, size int, e map[string]any) shipPart {
+ fields := rootfsFields(ver, size, false)
+ fields["expect_artifacts"] = map[string]any{"rootfs-linux-arm64": e}
+ return metaOf(t, fields)
+ }
+ if status, out := postShip(t, fx.url("shop"), fx.token, []shipPart{
+ withExpect("0.1.0-1", len(img), expectOf(img)), {name: "rootfs-linux-arm64", body: img},
+ }); status != http.StatusCreated {
+ t.Fatalf("matching rootfs ship = %d %v", status, out)
+ }
+ fx.assertScratchEmpty(t)
+
+ fx.addApp(t, "blog")
+ forged := expectOf(randomBytes(t, len(img)))
+ status, out := postShip(t, fx.url("blog"), fx.token, []shipPart{
+ withExpect("0.1.0-1", len(img), forged), {name: "rootfs-linux-arm64", body: img},
+ })
+ wantErrorContains(t, "forged rootfs", status, out, http.StatusBadRequest,
+ "artifact rootfs-linux-arm64 does not match the source release, so nothing was stored")
+ fx.assertNothingWritten(t, "blog")
+ fx.assertScratchEmpty(t)
+
+ wantRefusedUnread(t, fx, "size disagrees", "blog",
+ withExpect("0.1.0-2", 8<<20, map[string]any{"sha256": strings.Repeat("a", 64), "size": 7 << 20}),
+ "rootfs-linux-arm64", http.StatusBadRequest,
+ "the copied release's rootfs-linux-arm64 artifact is 7340032 bytes, but its rootfs is 8388608 bytes")
+ fx.assertNothingWritten(t, "blog")
+ fx.assertScratchEmpty(t)
+}
+
+func TestAPIShipExpectMalformed(t *testing.T) {
+ fx := rootfsShipFixture(t)
+ good := strings.Repeat("a", 64)
+ cases := []struct {
+ what string
+ expect map[string]any
+ want string
+ }{
+ {"bad hex", map[string]any{"linux-arm64": map[string]any{"sha256": strings.Repeat("A", 64), "size": 10}},
+ "the copied release's linux-arm64 artifact needs a 64-character SHA-256 value and a size above zero"},
+ {"short hex", map[string]any{"linux-arm64": map[string]any{"sha256": "abc", "size": 10}},
+ "the copied release's linux-arm64 artifact needs a 64-character SHA-256 value and a size above zero"},
+ {"size zero", map[string]any{"linux-arm64": map[string]any{"sha256": good, "size": 0}},
+ "the copied release's linux-arm64 artifact needs a 64-character SHA-256 value and a size above zero"},
+ {"rootfs key on a binary", map[string]any{"rootfs-linux-arm64": map[string]any{"sha256": good, "size": 10}},
+ "the copied release names an invalid artifact rootfs-linux-arm64 for a binary release"},
+ {"path key", map[string]any{"../x": map[string]any{"sha256": good, "size": 10}},
+ "the copied release names an invalid artifact ../x for a binary release"},
+ }
+ for i, c := range cases {
+ ver := "0.1.0-" + string(rune('1'+i))
+ wantRefusedUnread(t, fx, c.what, "shop", binaryExpectMeta(t, ver, c.expect), "linux-arm64",
+ http.StatusBadRequest, c.want)
+ }
+
+ // More keys than a binary release's part cap: the extra key is named.
+ many := map[string]any{}
+ for _, k := range []string{"a-1", "a-2", "a-3", "a-4", "a-5", "a-6", "a-7", "a-8", "a-9"} {
+ many[k] = map[string]any{"sha256": good, "size": 10}
+ }
+ wantRefusedUnread(t, fx, "too many keys", "shop", binaryExpectMeta(t, "0.1.0-9", many), "linux-arm64",
+ http.StatusBadRequest, "the copied release names an invalid artifact a-9 for a binary release")
+ fx.assertNothingWritten(t, "shop")
+}
diff --git a/internal/console/apiship_rootfs.go b/internal/console/apiship_rootfs.go
index 78175c62f..8c9884281 100644
--- a/internal/console/apiship_rootfs.go
+++ b/internal/console/apiship_rootfs.go
@@ -238,6 +238,10 @@ func (s *Server) shipRootfsParts(w http.ResponseWriter, r *http.Request, mr *mul
jsonError(w, http.StatusBadRequest, "malformed multipart body")
return
}
+ if err := checkShipExpected(meta.ExpectArtifacts, map[string]release.Artifact{release.RootfsArtifactKey: {SHA256: sum, Size: meta.RootfsSize}}); err != nil {
+ jsonError(w, http.StatusBadRequest, err.Error())
+ return
+ }
m := release.Manifest{
Schema: 1,
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 4f4796fc0..3d84d36a5 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -906,6 +906,10 @@ var claimFixtures = map[string]claimFixture{
"route GET /api/cli/apps/{account}/{app}/releases": claimRead("lists releases"),
"route GET /api/cli/apps/{account}/{app}/releases/{version}/authorize": claimRead(
"reads one build's manifest digests"),
+ "route GET /api/cli/apps/{account}/{app}/releases/{version}/manifest": claimRead(
+ "reads one release's stored manifest bytes"),
+ "route GET /api/cli/apps/{account}/{app}/releases/{version}/artifacts/{file}": claimRead(
+ "streams one artifact the release's manifest names"),
"route GET /api/cli/apps/{account}/{app}/retention": claimRead("reads the retention policy"),
"route GET /api/cli/apps/{account}/{app}/routes": claimRead("lists registry routes"),
"route GET /api/cli/apps/{account}/{app}/schedules": claimRead("lists schedules and their box status"),
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go
index 882213357..d155f594e 100644
--- a/internal/console/claim_invariant_probes_read_test.go
+++ b/internal/console/claim_invariant_probes_read_test.go
@@ -325,6 +325,10 @@ var claimReadProbes = map[string]claimProbe{
"route GET /api/cli/apps/{account}/{app}/releases": claimAPIRead(nil, "/api/cli/apps/bab/kass/releases", `"version":"v1"`),
"route GET /api/cli/apps/{account}/{app}/releases/{version}/authorize": claimAPIRead(nil,
"/api/cli/apps/bab/kass/releases/v1/authorize", `"version":"v1"`, `"manifest_digest":"`),
+ "route GET /api/cli/apps/{account}/{app}/releases/{version}/manifest": claimAPIRead(nil,
+ "/api/cli/apps/bab/kass/releases/v1/manifest", `"app": "kass"`, `"version": "v1"`, `"file": "kass"`),
+ "route GET /api/cli/apps/{account}/{app}/releases/{version}/artifacts/{file}": claimAPIRead(nil,
+ "/api/cli/apps/bab/kass/releases/v1/artifacts/kass", "binary v1"),
"route GET /api/cli/apps/{account}/{app}/retention": claimAPIRead(nil, "/api/cli/apps/bab/titogo/retention", `"keep"`),
"route GET /api/cli/apps/{account}/{app}/routes": claimAPIRead(nil, "/api/cli/apps/bab/kass/routes", `"kass.carlosapp.dev"`),
"route GET /api/cli/apps/{account}/{app}/schedules": claimAPIRead(claimWorldSchedule, "/api/cli/apps/bab/titogo/schedules", `"sync"`),
diff --git a/internal/console/deploydoors_test.go b/internal/console/deploydoors_test.go
index 17f7bb9dc..c18ff96e1 100644
--- a/internal/console/deploydoors_test.go
+++ b/internal/console/deploydoors_test.go
@@ -36,6 +36,9 @@ var deployDoors = []string{
// Member backups §1 (#898): a pipeline reads where its app's copies
// stand. Metadata only (TestAPIInstanceBackupsRoles).
"GET /api/cli/apps/{account}/{app}/instances/{host}/backups",
+ // #1389: a pipeline copies a release it may ship.
+ "GET /api/cli/apps/{account}/{app}/releases/{version}/manifest",
+ "GET /api/cli/apps/{account}/{app}/releases/{version}/artifacts/{file}",
}
func TestDeployReachesExactlyItsDoors(t *testing.T) {
diff --git a/internal/console/linkedpolicy.go b/internal/console/linkedpolicy.go
index ea4b78fed..55c51f620 100644
--- a/internal/console/linkedpolicy.go
+++ b/internal/console/linkedpolicy.go
@@ -166,6 +166,8 @@ var linkedPolicies = map[string]linkedPolicy{
"GET /api/cli/apps/{account}/{app}/tags": linkedRefuse,
"GET /api/cli/apps/{account}/{app}/tags/{version}": linkedRefuse,
"GET /api/cli/apps/{account}/{app}/releases": linkedRefuse,
+ "GET /api/cli/apps/{account}/{app}/releases/{version}/manifest": linkedRefuse,
+ "GET /api/cli/apps/{account}/{app}/releases/{version}/artifacts/{file}": linkedRefuse,
"GET /api/cli/apps/{account}/{app}/pipeline": linkedRefuse,
"PUT /api/cli/apps/{account}/{app}/pipeline": linkedRefuse,
"GET /api/cli/apps/{account}/{app}/pending": linkedRefuse,
diff --git a/internal/console/links_auth_test.go b/internal/console/links_auth_test.go
index aa602b3e8..8a40b62ae 100644
--- a/internal/console/links_auth_test.go
+++ b/internal/console/links_auth_test.go
@@ -489,6 +489,7 @@ var linkWalkFill = map[string]string{
"customer": "bcd",
"decision": "approve",
"domain": "example.com",
+ "file": "linux-arm64",
"file...": "app.css",
"hash": "deadbeef",
"jobID": "deadbeefdeadbeef",
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go
index 1ef62ad0f..ddc6da8cc 100644
--- a/internal/console/routedecls.go
+++ b/internal/console/routedecls.go
@@ -595,6 +595,12 @@ var routeDecls = []routeDecl{
{Pattern: "GET /api/cli/apps/{account}/{app}/tags", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Publish, svcrole.Deploy), Handler: (*Server).handleAPITagsList},
{Pattern: "GET /api/cli/apps/{account}/{app}/tags/{version}", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Publish, svcrole.Deploy), Handler: (*Server).handleAPITagGet},
{Pattern: "GET /api/cli/apps/{account}/{app}/releases", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Publish, svcrole.Deploy), Handler: (*Server).handleAPIReleasesList},
+ // #1389 item 1 (.superpowers/sdd/2026-11-25-1389/DESIGN.md): one
+ // release's stored manifest and the artifacts it names, read by
+ // `carlos releases pull` to copy a release to another console. Release
+ // metadata and bytes, reached by whoever reaches the list above.
+ {Pattern: "GET /api/cli/apps/{account}/{app}/releases/{version}/manifest", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Publish, svcrole.Deploy), Handler: (*Server).handleAPIReleaseManifest},
+ {Pattern: "GET /api/cli/apps/{account}/{app}/releases/{version}/artifacts/{file}", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Publish, svcrole.Deploy), Handler: (*Server).handleAPIReleaseArtifact},
// The pipeline API (apipipeline.go, release pipelines v2). GET is
// release metadata like channels/releases above — Publish reaches it.
// PUT rewrites the policy governing every promotion into every channel
diff --git a/internal/console/server.go b/internal/console/server.go
index c5db17cc0..b011e6e50 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1463,7 +1463,11 @@ type Server struct {
// counter alone does nothing to close. Always initialized (never nil):
// unlike cliNotified below this is load-bearing in production, not a
// test hook.
- shipSem chan struct{}
+ //
+ // releaseReads bounds how many release artifact downloads
+ // (apirelease_read.go, #1389) stream AT ONCE, for shipSem's reason.
+ // Always initialized, cap releaseReadsMax.
+ shipSem, releaseReads chan struct{}
// shipStarted, when non-nil, is signalled after a ship request
// acquires shipSem, before it does any (possibly slow, possibly
// blocking) reading of the request body. Tests only, same reasoning as
@@ -2041,7 +2045,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
// human running `carlos ship` by hand, tight enough that a fleet of
// slow-loris uploads against a stolen or shared token can't pile up
// goroutines and buffers without bound.
- shipSem: make(chan struct{}, 2),
+ shipSem: make(chan struct{}, 2), releaseReads: make(chan struct{}, releaseReadsMax),
delegationZone: normalizeDelegationZone(cfg.DelegationZone),
steeringHost: normalizeSteeringHost(cfg.SteeringHost),
lookupCNAME: net.DefaultResolver.LookupCNAME,
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index 27fd5a506..27e1bfa9d 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -122,6 +122,8 @@ route GET /api/cli/apps/{account}/{app}/regions
route GET /api/cli/apps/{account}/{app}/relay
route GET /api/cli/apps/{account}/{app}/releases
route GET /api/cli/apps/{account}/{app}/releases/{version}/authorize
+route GET /api/cli/apps/{account}/{app}/releases/{version}/manifest
+route GET /api/cli/apps/{account}/{app}/releases/{version}/artifacts/{file}
route GET /api/cli/apps/{account}/{app}/retention
route GET /api/cli/apps/{account}/{app}/routes
route GET /api/cli/apps/{account}/{app}/schedules
diff --git a/internal/console/view_test.go b/internal/console/view_test.go
index c63760cfc..f1847b7fb 100644
--- a/internal/console/view_test.go
+++ b/internal/console/view_test.go
@@ -4,6 +4,7 @@ import (
"context"
"crypto/ed25519"
"fmt"
+ "io"
"os"
"path/filepath"
"reflect"
@@ -50,6 +51,28 @@ type deletableStore struct {
// store, whether it then succeeds or not: a refusal test's proof that
// a refused request wrote and listed nothing. Set with setOpWitness.
opWitness atomic.Pointer[func(op, key string)]
+ // streams, when set, makes Open stream from the DirStore underneath,
+ // as S3 does in production; unset, Open reads through Get exactly as a
+ // store with no Open would (a streaming-only read is refused). Opt-in
+ // so every other test keeps Get's etags and hooks: the release read
+ // doors (#1389) set it.
+ streams atomic.Bool
+}
+
+// getOnly hides every method of a store but release.Store's own, so
+// release.OpenObject falls back to Get through it.
+type getOnly struct{ release.Store }
+
+func (d *deletableStore) Open(ctx context.Context, key string) (io.ReadCloser, string, error) {
+ if !d.streams.Load() {
+ return release.OpenObject(ctx, getOnly{d}, key)
+ }
+ if h := d.getHook.Load(); h != nil && *h != nil {
+ if err := (*h)(ctx, key); err != nil {
+ return nil, "", err
+ }
+ }
+ return release.OpenObject(ctx, d.Store, key)
}
func (d *deletableStore) setOpWitness(h func(op, key string)) {
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index 450b4aa55..f62e55e66 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) {
if len(got) < 100 {
t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root)
}
- inventory := mediaResultsCleanupWriteCensusInventory()
+ inventory := releaseCopyWriteCensusInventory()
problems := append(censusDiff(inventory, got), censusPolicy(inventory)...)
if len(problems) > 0 {
t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n "))
diff --git a/internal/provision/release_copy_census_test.go b/internal/provision/release_copy_census_test.go
new file mode 100644
index 000000000..f36c887a2
--- /dev/null
+++ b/internal/provision/release_copy_census_test.go
@@ -0,0 +1,40 @@
+package provision
+
+// releaseCopyWriteCensusInventory is the record-write census for branch
+// release-copy-across-consoles (#1389), layered on
+// mediaResultsCleanupWriteCensusInventory. Reviewed by the branch author
+// against the source. No record write is added, moved or reclassified; two
+// key-site tables are re-pinned:
+//
+// - var routeDecls (console): two new read-only declarations, GET
+// .../releases/{version}/manifest (handleAPIReleaseManifest) and GET
+// .../releases/{version}/artifacts/{file} (handleAPIReleaseArtifact),
+// both in apirelease_read.go, kindCLI with Publish and Deploy like GET
+// .../releases. They read the release store's manifest and one artifact
+// it names, and write nothing. The instances and sidecars literals are
+// unchanged: still key-site.
+// - var linkedPolicies (console): the same two routes classified
+// linkedRefuse, as GET .../releases and GET .../releases/{version}/
+// authorize are. Literals unchanged: still key-site.
+func releaseCopyWriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), mediaResultsCleanupWriteCensusInventory()...)
+ repins := []censusEntry{
+ {"internal/console/routedecls.go", "var routeDecls", "key-site", "lit:instances,lit:sidecars", "b018a1346a71e0a7dc11b8a6824a5bee78b2706bad3a8968cd080022c6e76761"},
+ {"internal/console/linkedpolicy.go", "var linkedPolicies", "key-site", "lit:instances,lit:sidecars", "dc4e5bc8c8897a94fe75cbddc6efb0ff5aaaa4f96c6c5f552aefe66df2927c39"},
+ }
+ for _, r := range repins {
+ found := false
+ for i, e := range entries {
+ if e.File == r.File && e.Unit == r.Unit {
+ if e.Class != r.Class || e.Kinds != r.Kinds {
+ panic("release-copy re-pin changes the class or kinds of " + r.File + ":" + r.Unit)
+ }
+ entries[i], found = r, true
+ }
+ }
+ if !found {
+ panic("release-copy re-pin of an unlisted unit " + r.File + ":" + r.Unit)
+ }
+ }
+ return entries
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index ccd44f8e7..78c7ff501 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -290,3 +290,4 @@ plan14-root-reads-domain-transfers.tsv c25a6eac6ece70098b052b6451deff684c29ff8cf
plan14-root-reads-console-addr-from-install.tsv f273b5cb7bbf37b6dca4bb964a9293cbec15b14c1c0a19b9010c177f20789a86
plan14-root-reads-instance-ready-before-wake.tsv aa953b1a43009c8208e44c67f5b8127ae1914b15d8b8822bcf16b19a6abdf121
plan14-root-reads-media-results-cleanup.tsv 6921575b59564ed947e30c02e314dd429016c6c11a85db9b8af50b2f31d5a5db
+plan14-root-reads-release-copy-across-consoles.tsv 892cf87db700600490e3ec9e944f9dbe7151e43bc5471090634f1735bcb9a7bd
diff --git a/internal/provision/testdata/plan14-root-reads-release-copy-across-consoles.tsv b/internal/provision/testdata/plan14-root-reads-release-copy-across-consoles.tsv
new file mode 100644
index 000000000..a7b090b19
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-release-copy-across-consoles.tsv
@@ -0,0 +1,20 @@
+# Census overlay release-copy-across-consoles, written by census-propose (#369). census-ruling-release-copy-across-consoles, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-release-copy-across-consoles.md.
+# 1 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 7 new dispositions: 0 reads re-frozen at their disposition with the claim, 7 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy ebf147442919d1b4bdb28e77468287920641091c728f2abd9fc83b5a492c74cf cli.go runShip legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-rootfs-apps-1;basis=rootfs Plan 1 Task 9: takes --rootfs, --processes, --hibernate, --jit and --check and hands a rootfs ship to runShipRootfs (ship_rootfs.go) before the binary path; the --notes-file ReadFile moved into shipNoteText (its own row, the same read of the file the person named) and the direct-mode version mint into mintDirectVersion; one read site fewer, none added; Task 12: the --hibernate flag help is RFS-1-C32's new text, the same reads;rev3=census-ruling-edge-asset-cache-1;basis=takes --assets (repeatable), checks the folders with checkShipAssets (release.ValidAssetPaths; refused on a static site) before the mode split, carries them into the API meta (sess.shipAssets) and the direct-mode manifest (shipAssetsBlock), and passes them to runShipRootfs (rootfsShipOpts.assets), which runs the same check and carries them the same two ways; after a direct-mode ship has stored a release declaring folders, directShipAssetGens runs the console ship door's backfill (provision.MintMissingAssetGens: lists the app's record keys and gives each record without an asset generation one, a CAS write in the deployment bucket as the person running the CLI) and fails naming any record it could not mint; read sites unchanged (2), none added;rev3=census-ruling-rootfs-apps-4;basis=adds the repeatable --env flag and refuses it before anything else unless --check is given (shipEnvRefusal, parseShipCheckEnv); the parsed values go into rootfsShipOpts.checkEnv. --env values reach the check's local container runtime as -e argv only, never root, never a box. No read added; read sites unchanged (2).;rev3=census-ruling-stateless-replicas-1;basis=Carry --stateless into binary/API and rootfs ship options; same two read sites, no new read.;rev3=census-ruling-platform-mail-submission;basis=Task 6: a --mail flag (only "submit" accepted, refused with one line otherwise, and refused with --rootfs), set on the manifest in direct-bucket mode and sent to the console in API mode, where a console that does not echo it is refused (ship_mail.go, apimode.go), as --stateless is. A person's ship command; no root read, no box state.;rev3=census-ruling-release-copy-across-consoles;basis=takes --from-release <dir> and, after the environment refusal and before the file-argument checks, hands the ship to runShipFromRelease (ship_from_release.go). a person's ship command run from their own machine against a console; no root read, no box state; read sites unchanged (2). file:ReadFile@8606,file:ReadFile@8830 865c26d06b9c7115291e4ec92eae92fd1ced08d8964ff7d8ad2a0a0f8b3866d3
+@legacy bb22b6bc112fb024d5972e49d701ce00ecca9df4c4faae7b2a971ff2eac45ced release_pull.go apiSession.pullArtifact legacy accepted-legacy accepted-legacy;rev3=census-ruling-release-copy-across-consoles;basis=new (carlos releases pull, #1389): streams one artifact from the console read door into a fresh exclusive temp file (CreateTemp) in the directory the person named with --out, hashes it, and renames it into place only when size and sha256 match the manifest; ReadAll reads only a bounded error body from the console response. CLI-side, never root, never a box path. file:CreateTemp@484,file:ReadAll@360 dbfa0197ee9fc0d2337ddb4b830c455dca377e97c06429d8e8055e0f68cf9fff
+@legacy c83c53bb488c804ffa1569bc124a53a8dd8b9597ffda757bc466e5abf7c39145 release_pull.go apiSession.releaseManifestRaw legacy accepted-legacy accepted-legacy;rev3=census-ruling-release-copy-across-consoles;basis=new (#1389): ReadAll of the console manifest response body, capped at 1 MiB and bounded by a two-minute deadline. reads an HTTP body, not a file; CLI-side, never root. file:ReadAll@372 53fa5d2a9f1a58cf4dcc9139ed2c353530afd94952dfafacf95d6f363c5cfbdb
+@legacy b53c5ecf56824588aee6d73976911169273e8572f0e75528fb63ff978fbd91f0 release_pull.go lockPullDir legacy accepted-legacy accepted-legacy;rev3=census-ruling-release-copy-across-consoles;basis=new (#1389 final review finding 1): creates <out>/.carlos-pull.lock with O_CREATE|O_EXCL in the directory the person named, refuses when it exists, and removes only the lock it created. CLI-side, never root. file:OpenFile@111 fa3a7c507f7631843b88093c30a8802ef1a5da36b119a43a327fd182fcdde86a
+@legacy 09889e81a429b1a521b6fc5d8ea23ba2f0eccda910810aaf81a37fd2f3d0981d release_pull.go publishManifest legacy accepted-legacy accepted-legacy;rev3=census-ruling-release-copy-across-consoles;basis=new (#1389): writes the console manifest bytes to an exclusive temp file (CreateTemp) in --out, syncs it, and publishes it as manifest.json with a hard link that never replaces an existing file. CLI-side, never root. file:CreateTemp@78 8ba1a3335702733dc3eaf09fb6464493b688c08a1bd2d87a7d1d6ca6658aa0a9
+@legacy 2856a69cfaef976a5e9ab7984ddfcdb41d8f6c934739f70f8e220e25b33aa2a2 release_pull.go pullRelease legacy accepted-legacy accepted-legacy;rev3=census-ruling-release-copy-across-consoles;basis=new (#1389): creates --out, takes its pull lock, Lstats <out>/manifest.json to refuse a directory that already holds a release, validates every manifest file name (validPulledFile: plain names only, no manifest, lock or partial names, no Windows aliases or device names) and refuses duplicates after case and trailing dot/space normalisation, then pulls each artifact and publishes the manifest last. CLI-side, never root. file:Lstat@346 ceb5e456e55a1e31ed50b5485100cb2d30e97d7b1c5dd862f1786fa8554a4509
+@legacy e6ebdb9637603a55ac5a92e90520fa55d1b725b3297e02191c70627811c8875c ship_from_release.go hashReleaseFile legacy accepted-legacy accepted-legacy;rev3=census-ruling-release-copy-across-consoles;basis=new (#1389, carlos ship --from-release): opens one file named by a pulled manifest.json in the directory the person passed and returns its length and sha256. names reach it only after validPulledFile. CLI-side, never root. file:Open@70 1fd2348536599c426490ea9678d88a97cf096de9be4e0819046b7b64f9301152
+@legacy 0e70374328de87a0c88f0434a7ef9938a84ecee35a738fa7a72f8f8a40b2e432 ship_from_release.go loadReleaseDir legacy accepted-legacy accepted-legacy;rev3=census-ruling-release-copy-across-consoles;basis=new (#1389): reads <dir>/manifest.json from the directory the person passed with --from-release, checks kind, version and that every named file passes validPulledFile before any file is read, then hashes each file against the manifest. CLI-side, never root. file:ReadFile@93 2e828153edde2e7fef91209d520e78153f42b432bb9971d8746c68f66bcfce4d
+cli.go runShip legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-rootfs-apps-1;basis=rootfs Plan 1 Task 9: takes --rootfs, --processes, --hibernate, --jit and --check and hands a rootfs ship to runShipRootfs (ship_rootfs.go) before the binary path; the --notes-file ReadFile moved into shipNoteText (its own row, the same read of the file the person named) and the direct-mode version mint into mintDirectVersion; one read site fewer, none added; Task 12: the --hibernate flag help is RFS-1-C32's new text, the same reads;rev3=census-ruling-edge-asset-cache-1;basis=takes --assets (repeatable), checks the folders with checkShipAssets (release.ValidAssetPaths; refused on a static site) before the mode split, carries them into the API meta (sess.shipAssets) and the direct-mode manifest (shipAssetsBlock), and passes them to runShipRootfs (rootfsShipOpts.assets), which runs the same check and carries them the same two ways; after a direct-mode ship has stored a release declaring folders, directShipAssetGens runs the console ship door's backfill (provision.MintMissingAssetGens: lists the app's record keys and gives each record without an asset generation one, a CAS write in the deployment bucket as the person running the CLI) and fails naming any record it could not mint; read sites unchanged (2), none added;rev3=census-ruling-rootfs-apps-4;basis=adds the repeatable --env flag and refuses it before anything else unless --check is given (shipEnvRefusal, parseShipCheckEnv); the parsed values go into rootfsShipOpts.checkEnv. --env values reach the check's local container runtime as -e argv only, never root, never a box. No read added; read sites unchanged (2).;rev3=census-ruling-stateless-replicas-1;basis=Carry --stateless into binary/API and rootfs ship options; same two read sites, no new read.;rev3=census-ruling-platform-mail-submission;basis=Task 6: a --mail flag (only "submit" accepted, refused with one line otherwise, and refused with --rootfs), set on the manifest in direct-bucket mode and sent to the console in API mode, where a console that does not echo it is refused (ship_mail.go, apimode.go), as --stateless is. A person's ship command; no root read, no box state.;rev3=census-ruling-release-copy-across-consoles;basis=takes --from-release <dir> and, after the environment refusal and before the file-argument checks, hands the ship to runShipFromRelease (ship_from_release.go). a person's ship command run from their own machine against a console; no root read, no box state; read sites unchanged (2). file:ReadFile@8606,file:ReadFile@8830 865c26d06b9c7115291e4ec92eae92fd1ced08d8964ff7d8ad2a0a0f8b3866d3
+release_pull.go apiSession.pullArtifact legacy accepted-legacy accepted-legacy;rev3=census-ruling-release-copy-across-consoles;basis=new (carlos releases pull, #1389): streams one artifact from the console read door into a fresh exclusive temp file (CreateTemp) in the directory the person named with --out, hashes it, and renames it into place only when size and sha256 match the manifest; ReadAll reads only a bounded error body from the console response. CLI-side, never root, never a box path. file:CreateTemp@484,file:ReadAll@360 dbfa0197ee9fc0d2337ddb4b830c455dca377e97c06429d8e8055e0f68cf9fff
+release_pull.go apiSession.releaseManifestRaw legacy accepted-legacy accepted-legacy;rev3=census-ruling-release-copy-across-consoles;basis=new (#1389): ReadAll of the console manifest response body, capped at 1 MiB and bounded by a two-minute deadline. reads an HTTP body, not a file; CLI-side, never root. file:ReadAll@372 53fa5d2a9f1a58cf4dcc9139ed2c353530afd94952dfafacf95d6f363c5cfbdb
+release_pull.go lockPullDir legacy accepted-legacy accepted-legacy;rev3=census-ruling-release-copy-across-consoles;basis=new (#1389 final review finding 1): creates <out>/.carlos-pull.lock with O_CREATE|O_EXCL in the directory the person named, refuses when it exists, and removes only the lock it created. CLI-side, never root. file:OpenFile@111 fa3a7c507f7631843b88093c30a8802ef1a5da36b119a43a327fd182fcdde86a
+release_pull.go publishManifest legacy accepted-legacy accepted-legacy;rev3=census-ruling-release-copy-across-consoles;basis=new (#1389): writes the console manifest bytes to an exclusive temp file (CreateTemp) in --out, syncs it, and publishes it as manifest.json with a hard link that never replaces an existing file. CLI-side, never root. file:CreateTemp@78 8ba1a3335702733dc3eaf09fb6464493b688c08a1bd2d87a7d1d6ca6658aa0a9
+release_pull.go pullRelease legacy accepted-legacy accepted-legacy;rev3=census-ruling-release-copy-across-consoles;basis=new (#1389): creates --out, takes its pull lock, Lstats <out>/manifest.json to refuse a directory that already holds a release, validates every manifest file name (validPulledFile: plain names only, no manifest, lock or partial names, no Windows aliases or device names) and refuses duplicates after case and trailing dot/space normalisation, then pulls each artifact and publishes the manifest last. CLI-side, never root. file:Lstat@346 ceb5e456e55a1e31ed50b5485100cb2d30e97d7b1c5dd862f1786fa8554a4509
+ship_from_release.go hashReleaseFile legacy accepted-legacy accepted-legacy;rev3=census-ruling-release-copy-across-consoles;basis=new (#1389, carlos ship --from-release): opens one file named by a pulled manifest.json in the directory the person passed and returns its length and sha256. names reach it only after validPulledFile. CLI-side, never root. file:Open@70 1fd2348536599c426490ea9678d88a97cf096de9be4e0819046b7b64f9301152
+ship_from_release.go loadReleaseDir legacy accepted-legacy accepted-legacy;rev3=census-ruling-release-copy-across-consoles;basis=new (#1389): reads <dir>/manifest.json from the directory the person passed with --from-release, checks kind, version and that every named file passes validPulledFile before any file is read, then hashes each file against the manifest. CLI-side, never root. file:ReadFile@93 2e828153edde2e7fef91209d520e78153f42b432bb9971d8746c68f66bcfce4d
+@coverage . e646e9b977a13d6927fa5be50ecd2c3b1d550e64e44a082fd793ea8026f9d202
diff --git a/parity/cli.tsv b/parity/cli.tsv
index 20a0d650f..e9b52298b 100644
--- a/parity/cli.tsv
+++ b/parity/cli.tsv
@@ -220,6 +220,7 @@ relay status customer - - - - -
release-keygen box-local - - - - -
releases customer - - - - -
releases authorize operator - - - - -
+releases pull customer - - - - -
releases retention customer - - - - -
remove box-local - - - - -
restart customer - - - - -
diff --git a/parity/parity.tsv b/parity/parity.tsv
index 01e281fbc..b8e681e65 100644
--- a/parity/parity.tsv
+++ b/parity/parity.tsv
@@ -38,6 +38,7 @@ canary-list releases both canary ls GET /a/{sqid}/apps/{app}/releases
canary-rm releases gap canary rm wp-instances Deletes the canary's instance and leaves its channel. The console has no instance delete (instances-delete); its Retire is a different operation (canary-retire).
canary-retire releases console-only POST /a/{sqid}/apps/{app}/canary/retire Retires the canary's channel and refuses while any host follows it. No CLI verb retires a channel: canary rm deletes the instance and leaves the channel.
channels releases both channels GET /a/{sqid}/apps/{app}/releases
+releases-pull releases cli-only releases pull Copies a shipped release out of a console and checks each named file against the manifest's recorded size and digest.
channels-resign releases gap channels resign wp-settings
pipeline releases both pipeline show ; pipeline init ; pipeline set ; pipeline add ; pipeline remove GET /a/{sqid}/apps/{app}/pipeline ; POST /a/{sqid}/apps/{app}/pipeline ; GET /a/{sqid}/apps/{app}/settings/{section}
releases releases both releases GET /a/{sqid}/apps/{app}/releases ; GET /a/{sqid}/apps/{app}/deployments
diff --git a/release_copy_e2e_test.go b/release_copy_e2e_test.go
new file mode 100644
index 000000000..8e9f83a23
--- /dev/null
+++ b/release_copy_e2e_test.go
@@ -0,0 +1,352 @@
+// The shared fixture for copying a release between consoles (#1389 item 1):
+// each copyConsole is a REAL console.Server over its own dir store, built as
+// TestE2ECLIThroughConsole builds its one, so a pull and a ship run through
+// the same doors and gates a pipeline meets.
+package main
+
+import (
+ "bytes"
+ "context"
+ "crypto/ed25519"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "flag"
+ "io"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/console"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// copyOwner owns the fixture's account and mints its credentials.
+const copyOwner = "paul@keymail.dev"
+
+// copyConsole is one in-process console and what a test reads behind it.
+type copyConsole struct {
+ url string
+ storeDir string // the dir store's root: a release key is a path under it
+ st *console.Store
+ rel release.Store
+ pub ed25519.PublicKey
+}
+
+// newCopyConsole starts a console with app created in the ops account.
+func newCopyConsole(t *testing.T, app string) copyConsole {
+ t.Helper()
+ tmp := t.TempDir()
+ storeDir := filepath.Join(tmp, "store")
+ relStore := release.NewDirStore(storeDir)
+ seed, pubB64, err := release.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ priv, err := release.ParseSigningKey(seed, "e2e")
+ if err != nil {
+ t.Fatal(err)
+ }
+ pub, err := release.ParsePublicKey(pubB64, "e2e")
+ if err != nil {
+ t.Fatal(err)
+ }
+ cst, err := console.Open(filepath.Join(tmp, "console.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { cst.Close() })
+
+ // The origin must equal the listener's own URL, which only exists after
+ // the listener starts.
+ var srv *console.Server
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ srv.ServeHTTP(w, r)
+ }))
+ t.Cleanup(ts.Close)
+ srv, err = console.NewServer(console.Config{
+ Origin: ts.URL,
+ Keymail: "http://keymail.invalid",
+ Registry: filepath.Join(tmp, "registry.db"),
+ Releases: relStore,
+ ReleasePub: pub,
+ Key: priv,
+ AppScheme: "http",
+ SeedScratchDir: filepath.Join(tmp, "seeds"),
+ }, cst)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := cst.AddMember(console.OpsAccountID, copyOwner, console.RoleOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := cst.CreateAppIn(console.OpsAccountID, app, copyOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ return copyConsole{url: ts.URL, storeDir: storeDir, st: cst, rel: relStore, pub: pub}
+}
+
+// token mints a service credential for app with role. A deploy credential
+// may promote to canary and edge.
+func (c copyConsole) token(t *testing.T, app string, role svcrole.Role) string {
+ t.Helper()
+ var rungs []string
+ if role == svcrole.Deploy {
+ rungs = []string{"canary", "edge"}
+ }
+ tok, err := c.st.NewServicePrincipalScoped(console.OpsAccountID, "ci-"+string(role), app, role, rungs, nil, copyOwner, time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ return tok
+}
+
+// useConsole points the CLI at c as token, the way CI is configured.
+func useConsole(t *testing.T, c copyConsole, token string) {
+ t.Helper()
+ t.Setenv("CARLOS_CONSOLE", c.url)
+ t.Setenv("CARLOS_SERVICE_TOKEN", token)
+}
+
+// copySource ships shop v12 to a fresh console A, with a label, notes and a
+// swap demand for the copy to carry, and pulls it into a new directory
+// under A's deploy credential.
+func copySource(t *testing.T) (copyConsole, string) {
+ t.Helper()
+ a := newCopyConsole(t, "shop")
+ useConsole(t, a, a.token(t, "shop", svcrole.Publish))
+ bin := filepath.Join(t.TempDir(), "shop")
+ if err := os.WriteFile(bin, pullPayload, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ buf := captureStdout(t)
+ runShip([]string{"--app", "shop", "--account", release.OpsAccount, "--version", "v12",
+ "--label", "fixing modals", "--notes", "first cut", "--swap", "hold", "--target", "linux-arm64", bin})
+ if !strings.Contains(buf.String(), "shipped shop v12") {
+ t.Fatalf("ship stdout = %q, want the shipped line", buf.String())
+ }
+ dir := filepath.Join(t.TempDir(), "release")
+ useConsole(t, a, a.token(t, "shop", svcrole.Deploy))
+ if err := runReleasesPull([]string{"v12", "--app", "shop", "--out", dir}); err != nil {
+ t.Fatalf("pull: %v", err)
+ }
+ return a, dir
+}
+
+// manifestOf reads app's version from c's store.
+func manifestOf(t *testing.T, c copyConsole, app, version string) *release.Manifest {
+ t.Helper()
+ m, err := release.GetManifest(context.Background(), c.rel, release.OpsAccount, app, version)
+ if err != nil {
+ t.Fatalf("%s %s: %v", app, version, err)
+ }
+ return m
+}
+
+// noRelease fails when c stores anything for storefront v12: a manifest or
+// the linux-arm64 artifact.
+func noRelease(t *testing.T, c copyConsole) {
+ t.Helper()
+ ctx := context.Background()
+ if _, err := release.GetManifest(ctx, c.rel, release.OpsAccount, "storefront", "v12"); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("storefront v12 manifest on B: err = %v, want not found", err)
+ }
+ if _, _, err := c.rel.Get(ctx, release.ArtifactKey(release.OpsAccount, "storefront", "v12", "linux-arm64")); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("storefront v12 linux-arm64 on B: err = %v, want not found", err)
+ }
+}
+
+// fromReleaseOptsFor is runShip's options for `--from-release dir --app app`.
+func fromReleaseOptsFor(t *testing.T, dir, app string) (*flag.FlagSet, fromReleaseOpts) {
+ t.Helper()
+ fs := flag.NewFlagSet("ship", flag.ContinueOnError)
+ messageFlags := addMutationMessageFlags(fs)
+ fs.String("from-release", "", "")
+ appName := appFlag(fs, "")
+ acctRaw, acctIDRaw, _ := accountFlags(fs)
+ consoleFlag := consoleOption(fs, "")
+ programChange := fs.Bool("program-change", false, "")
+ if err := fs.Parse([]string{"--from-release", dir, "--app", app}); err != nil {
+ t.Fatal(err)
+ }
+ return fs, fromReleaseOpts{dir: dir, app: *appName, console: *consoleFlag, acctRaw: acctRaw, acctIDRaw: acctIDRaw,
+ programChange: *programChange, messageFlags: messageFlags}
+}
+
+func TestE2EReleaseCopyAcrossConsoles(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ a, dir := copySource(t)
+ b := newCopyConsole(t, "storefront")
+ useConsole(t, b, b.token(t, "storefront", svcrole.Deploy))
+ buf := captureStdout(t)
+ runShip([]string{"--from-release", dir, "--app", "storefront"})
+ if !strings.Contains(buf.String(), "every digest matches the source release") {
+ t.Fatalf("ship stdout = %q, want every digest to match", buf.String())
+ }
+ src, got := manifestOf(t, a, "shop", "v12"), manifestOf(t, b, "storefront", "v12")
+ if !reflect.DeepEqual(got.Artifacts, src.Artifacts) {
+ t.Fatalf("B's artifacts = %+v, want A's %+v", got.Artifacts, src.Artifacts)
+ }
+ if got.Label != "fixing modals" || got.Notes != "first cut" || got.Swap != release.DemandHold {
+ t.Fatalf("B's label %q notes %q swap %q, want A's", got.Label, got.Notes, got.Swap)
+ }
+ if got.Label != src.Label || got.Notes != src.Notes || got.Swap != src.Swap {
+ t.Fatalf("B's settings differ from A's: %+v vs %+v", got, src)
+ }
+ if got.App != "storefront" || !strings.HasPrefix(got.BuiltBy, "console-api") {
+ t.Fatalf("B's manifest app %q built_by %q, want B's own", got.App, got.BuiltBy)
+ }
+
+ runPromote([]string{"--app", "storefront", "v12", "edge"})
+ ptr, err := release.Channel(context.Background(), b.rel, b.pub, release.OpsAccount, "storefront", "edge")
+ if err != nil {
+ t.Fatalf("B's edge channel under B's key: %v", err)
+ }
+ if ptr.Version != "v12" {
+ t.Fatalf("B's edge = %q, want v12", ptr.Version)
+ }
+
+ buf.Reset()
+ runShip([]string{"--from-release", dir, "--app", "storefront"})
+ if !strings.Contains(buf.String(), "already shipped storefront v12") {
+ t.Fatalf("second ship stdout = %q, want already shipped", buf.String())
+ }
+}
+
+func TestE2EReleaseCopyRefusesATamperedFile(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ _, dir := copySource(t)
+ path := filepath.Join(dir, "linux-arm64")
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ data[0] ^= 0xff
+ if err := os.WriteFile(path, data, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ b := newCopyConsole(t, "storefront")
+ useConsole(t, b, b.token(t, "storefront", svcrole.Deploy))
+ err = runShipFromRelease(fromReleaseOptsFor(t, dir, "storefront"))
+ if err == nil || !strings.Contains(err.Error(), "does not match manifest.json") {
+ t.Fatalf("ship of a tampered dir = %v, want it refused", err)
+ }
+ noRelease(t, b)
+}
+
+func TestE2EReleaseCopyForgedExpectIsRefusedByTheConsole(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ _, dir := copySource(t)
+ b := newCopyConsole(t, "storefront")
+ pulled, err := os.ReadFile(filepath.Join(dir, "linux-arm64"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ other := bytes.Repeat([]byte{0x43}, len(pulled))
+ sum := sha256.Sum256(other)
+ meta, err := json.Marshal(map[string]any{
+ "version": "v12", "kind": "binary",
+ "expect_artifacts": map[string]any{"linux-arm64": map[string]any{"sha256": hex.EncodeToString(sum[:]), "size": len(other)}},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ var body bytes.Buffer
+ mw := multipart.NewWriter(&body)
+ if err := mw.WriteField("meta", string(meta)); err != nil {
+ t.Fatal(err)
+ }
+ part, err := mw.CreateFormFile("linux-arm64", "linux-arm64")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := part.Write(pulled); err != nil {
+ t.Fatal(err)
+ }
+ if err := mw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ req, err := http.NewRequest(http.MethodPost, b.url+"/api/cli/apps/"+release.OpsAccount+"/storefront/releases", &body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Content-Type", mw.FormDataContentType())
+ req.Header.Set("Authorization", "Bearer "+b.token(t, "storefront", svcrole.Deploy))
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ answer, _ := io.ReadAll(res.Body)
+ res.Body.Close()
+ if res.StatusCode != http.StatusBadRequest {
+ t.Fatalf("forged expect = %d %s, want 400", res.StatusCode, answer)
+ }
+ noRelease(t, b)
+}
+
+func TestE2EReleaseCopyDifferentBytesUnderTheSameVersion(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ _, dir := copySource(t)
+ b := newCopyConsole(t, "storefront")
+ useConsole(t, b, b.token(t, "storefront", svcrole.Deploy))
+ bin := filepath.Join(t.TempDir(), "storefront")
+ if err := os.WriteFile(bin, bytes.Repeat([]byte{0x44}, 512), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ captureStdout(t)
+ runShip([]string{"--app", "storefront", "--account", release.OpsAccount, "--version", "v12", "--target", "linux-arm64", bin})
+ before := manifestOf(t, b, "storefront", "v12")
+ err := runShipFromRelease(fromReleaseOptsFor(t, dir, "storefront"))
+ if err == nil || !strings.Contains(err.Error(), "already shipped with different content") {
+ t.Fatalf("ship --from-release over different bytes under v12 = %v, want the console's conflict", err)
+ }
+ if after := manifestOf(t, b, "storefront", "v12"); !reflect.DeepEqual(after, before) {
+ t.Fatalf("B's v12 changed: %+v, was %+v", after, before)
+ }
+}
+
+func TestE2EReleaseCopyRootfs(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ a := newCopyConsole(t, "shop")
+ image := filepath.Join(t.TempDir(), "rootfs.squashfs")
+ if err := os.WriteFile(image, bytes.Repeat([]byte{0x45}, 4<<10), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ seed := release.Manifest{
+ App: "shop", Version: "v12", Kind: release.KindRootfs, BuiltBy: "e2e",
+ Processes: map[string]release.Process{release.ProcessWeb: {Command: []string{"/bin/web"}}},
+ Hibernate: true,
+ Artifacts: map[string]release.Artifact{release.RootfsArtifactKey: {File: release.RootfsArtifactFile}},
+ }
+ if err := release.ShipSpooled(context.Background(), a.rel, release.OpsAccount, seed, map[string]string{release.RootfsArtifactKey: image}); err != nil {
+ t.Fatalf("seed A: %v", err)
+ }
+ dir := filepath.Join(t.TempDir(), "release")
+ useConsole(t, a, a.token(t, "shop", svcrole.Deploy))
+ captureStdout(t)
+ if err := runReleasesPull([]string{"v12", "--app", "shop", "--out", dir}); err != nil {
+ t.Fatalf("pull: %v", err)
+ }
+ b := newCopyConsole(t, "storefront")
+ useConsole(t, b, b.token(t, "storefront", svcrole.Deploy))
+ if err := runShipFromRelease(fromReleaseOptsFor(t, dir, "storefront")); err != nil {
+ t.Fatalf("ship --from-release rootfs: %v", err)
+ }
+ src, got := manifestOf(t, a, "shop", "v12"), manifestOf(t, b, "storefront", "v12")
+ if !reflect.DeepEqual(got.Artifacts, src.Artifacts) || !reflect.DeepEqual(got.Processes, src.Processes) || got.Hibernate != src.Hibernate {
+ t.Fatalf("B's rootfs release = %+v, want A's %+v", got, src)
+ }
+}
diff --git a/release_pull.go b/release_pull.go
new file mode 100644
index 000000000..e1a2b572b
--- /dev/null
+++ b/release_pull.go
@@ -0,0 +1,358 @@
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "io/fs"
+ "net/http"
+ "net/url"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// `carlos releases pull` (#1389 item 1): the source half of copying a
+// shipped release from one console to another, so production runs the
+// exact bytes staging tested. It writes the manifest the source stores and
+// every artifact it names into a directory, checking each file against the
+// manifest's size and sha256. `carlos ship --from-release` is the target
+// half.
+
+const (
+ // releaseManifestMaxBytes caps the manifest read: a manifest is a few
+ // KiB, and a body past this is not one.
+ releaseManifestMaxBytes = 1 << 20
+ // releaseManifestTimeout bounds the manifest read, headers and body:
+ // doStream's client has no timeout of its own.
+ releaseManifestTimeout = 2 * time.Minute
+
+ releasesPullUsage = "usage: carlos releases pull <version> --app <a> --out <dir> [--account <sqid-or-name>] [--account-id <sqid>] [--console <origin>]"
+ releasesPullNeedsConsole = "carlos releases pull needs a console. unset CARLOS_DEPLOYMENT_BUCKET and CARLOS_DEPLOYMENT_DIR, then set CARLOS_CONSOLE or run carlos login"
+ releasesPullDone = "pulled %s %s into %s. every file matches its digest"
+ releasesPullLocked = "another pull is writing to %s. if none is running, remove %s and pull again"
+
+ // pullLockName is the file a pull holds its directory with.
+ pullLockName = ".carlos-pull.lock"
+)
+
+// runReleasesPull is `carlos releases pull <version> --app <a> --out <dir>`.
+func runReleasesPull(args []string) error {
+ fs := flag.NewFlagSet("releases pull", flag.ExitOnError)
+ app := appFlag(fs, "")
+ acctRaw, acctIDRaw, _ := accountFlags(fs)
+ consoleFlag := consoleOption(fs, "console origin to read the release from (default: the only logged-in one)")
+ out := fs.String("out", "", "directory to write the manifest and artifacts into (created if missing)")
+ fs.Usage = flagUsage(fs, releasesPullUsage)
+ pos, _ := parseInterspersed(fs, args)
+ if len(pos) != 1 || strings.TrimSpace(*out) == "" {
+ fs.Usage()
+ return exitCode(2)
+ }
+ version := pos[0]
+
+ sess, err := resolveMode(*consoleFlag)
+ if err != nil {
+ return err
+ }
+ if sess == nil {
+ return errors.New(releasesPullNeedsConsole)
+ }
+ printUsing(stdout, sess)
+ ctx := context.Background()
+ acct := apiAccount(acctRaw, acctIDRaw)
+ if acct.Seg == "" {
+ if acct, err = sess.defaultAccount(ctx); err != nil {
+ return err
+ }
+ }
+ name := strings.TrimSpace(*app)
+ if name == "" {
+ if name, err = sess.defaultApp(ctx, acct, true); err != nil {
+ return err
+ }
+ if name == "" {
+ return errors.New(releasesPullUsage)
+ }
+ }
+ _, err = pullRelease(ctx, sess, acct, name, version, *out)
+ if err != nil {
+ return err
+ }
+ fmt.Fprintf(stdout, releasesPullDone+"\n", name, version, *out)
+ return nil
+}
+
+// pullRelease writes app's release version into out: every artifact first,
+// each checked against the manifest, then manifest.json with the exact
+// bytes the console stores. Every file is written to a fresh temp file in
+// out and renamed into place, and manifest.json is renamed in last, so a
+// directory holding it always holds the whole release, even after a crash;
+// a directory without it is an interrupted pull, which a second pull
+// finishes.
+func pullRelease(ctx context.Context, sess *apiSession, a apiAcct, app, version, out string) (*release.Manifest, error) {
+ if err := os.MkdirAll(out, 0o755); err != nil {
+ return nil, err
+ }
+ unlock, err := lockPullDir(out)
+ if err != nil {
+ return nil, err
+ }
+ defer unlock()
+ manifestPath := filepath.Join(out, "manifest.json")
+ if _, err := os.Lstat(manifestPath); err == nil {
+ return nil, alreadyHoldsRelease(out)
+ } else if !errors.Is(err, os.ErrNotExist) {
+ return nil, err
+ }
+ raw, err := sess.releaseManifestRaw(ctx, a, app, version)
+ if err != nil {
+ return nil, err
+ }
+ var m release.Manifest
+ if err := json.Unmarshal(raw, &m); err != nil {
+ return nil, fmt.Errorf("the console's manifest for %s %s does not parse: %w", app, version, err)
+ }
+ if m.Version != version {
+ return nil, fmt.Errorf("the console answered with release %q, not %q", m.Version, version)
+ }
+ if len(m.Artifacts) == 0 {
+ return nil, fmt.Errorf("release %s %s names no files", app, version)
+ }
+ keys := make([]string, 0, len(m.Artifacts))
+ files := map[string]bool{}
+ for k, art := range m.Artifacts {
+ if !validPulledFile(art.File) {
+ return nil, fmt.Errorf("the release names a file %q that cannot be written safely", art.File)
+ }
+ // Normalised as macOS and Windows file systems do: two names that
+ // differ only in case would land on one file there.
+ fold := pulledFileKey(art.File)
+ if files[fold] {
+ return nil, fmt.Errorf("the release names the file %q twice", art.File)
+ }
+ files[fold] = true
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ for _, k := range keys {
+ art := m.Artifacts[k]
+ if err := pullArtifactBounded(ctx, sess, a, app, version, m.IsRootfs(), art, filepath.Join(out, art.File)); err != nil {
+ return nil, err
+ }
+ }
+ if err := publishManifest(out, manifestPath, raw); err != nil {
+ if errors.Is(err, fs.ErrExist) {
+ // Another pull finished into out while this one downloaded.
+ return nil, alreadyHoldsRelease(out)
+ }
+ return nil, err
+ }
+ return &m, nil
+}
+
+// lockPullDir takes out's pull lock: it creates out/.carlos-pull.lock
+// exclusively, so two pulls never write into one directory at once, and
+// refuses when the lock already exists. unlock removes the lock this pull
+// created, and only that.
+func lockPullDir(out string) (unlock func(), err error) {
+ lock := filepath.Join(out, pullLockName)
+ f, err := os.OpenFile(lock, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
+ if errors.Is(err, fs.ErrExist) {
+ return nil, fmt.Errorf(releasesPullLocked, out, lock)
+ }
+ if err != nil {
+ return nil, err
+ }
+ if err := f.Close(); err != nil {
+ _ = os.Remove(lock)
+ return nil, err
+ }
+ return func() { _ = os.Remove(lock) }, nil
+}
+
+// alreadyHoldsRelease is the refusal of a directory with a manifest.json.
+func alreadyHoldsRelease(out string) error {
+ return fmt.Errorf("%s already holds a release. pull into a new or empty directory", out)
+}
+
+// publishManifest writes raw to a temp file in out, syncs it, and
+// publishes it as manifestPath with publishNoReplace, so manifest.json
+// never exists with partial bytes and an existing one is never replaced.
+func publishManifest(out, manifestPath string, raw []byte) error {
+ f, err := os.CreateTemp(out, "manifest.json.partial-*")
+ if err != nil {
+ return err
+ }
+ tmp := f.Name()
+ _, err = f.Write(raw)
+ if err == nil {
+ err = f.Sync()
+ }
+ if cerr := f.Close(); err == nil {
+ err = cerr
+ }
+ if err == nil {
+ err = os.Chmod(tmp, 0o644)
+ }
+ if err != nil {
+ _ = os.Remove(tmp)
+ return err
+ }
+ return publishNoReplace(tmp, manifestPath)
+}
+
+// publishNoReplace gives the complete file tmp the name dst in one step,
+// refusing (an error matching fs.ErrExist) when dst already exists, and
+// removes tmp either way. A hard link is the portable no-replace publish:
+// os.Rename replaces dst on every platform. Hard links work on Linux,
+// macOS and NTFS.
+func publishNoReplace(tmp, dst string) error {
+ err := os.Link(tmp, dst)
+ // Once dst is published, a temp name left beside it is untidy, not
+ // wrong: nothing reads it.
+ _ = os.Remove(tmp)
+ return err
+}
+
+// pullArtifactBounded is pullArtifact under the deadline its kind ships
+// under: a rootfs image may take as long to leave as it took to arrive.
+func pullArtifactBounded(ctx context.Context, sess *apiSession, a apiAcct, app, version string, rootfs bool, art release.Artifact, dst string) error {
+ limit := shipTimeout
+ if rootfs {
+ limit = shipRootfsTimeout
+ }
+ ctx, cancel := context.WithTimeout(ctx, limit)
+ defer cancel()
+ return sess.pullArtifact(ctx, a, app, version, art, dst)
+}
+
+// validPulledFile reports whether a manifest's File name can be written
+// into the pull directory as itself, on every system a pull or a ship may
+// run on: one plain name of ASCII letters, digits, '.', '_' and '-', not
+// the manifest, not the pull's lock, not a partial download's name
+// (<file>.partial, or a temp file's <file>.partial-*). Those compare
+// without case, as macOS and Windows file systems do. Names Windows would
+// read as another file or a device are refused everywhere: a trailing dot
+// (Windows drops it, so "manifest.json." is manifest.json; it also refuses
+// "." and ".."), and the device names CON, PRN, AUX, NUL, COM1-9 and
+// LPT1-9, alone or with an extension. Superscript COM and LPT digits are
+// not ASCII, so they never get this far.
+func validPulledFile(name string) bool {
+ lower := strings.ToLower(name)
+ return name != "" && plainASCIIName(name) &&
+ !strings.HasSuffix(name, ".") &&
+ !windowsDeviceName(lower) &&
+ lower != "manifest.json" && lower != pullLockName &&
+ !strings.HasSuffix(lower, ".partial") &&
+ !strings.Contains(lower, ".partial-")
+}
+
+// plainASCIIName reports whether every byte of name is an ASCII letter, a
+// digit, '.', '_' or '-'.
+func plainASCIIName(name string) bool {
+ for i := 0; i < len(name); i++ {
+ c := name[i]
+ if !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' || c == '.' || c == '_' || c == '-') {
+ return false
+ }
+ }
+ return true
+}
+
+// windowsDeviceName reports whether the lower-case name is a Windows device
+// (con, prn, aux, nul, com1-9, lpt1-9), alone or with an extension.
+func windowsDeviceName(lower string) bool {
+ stem, _, _ := strings.Cut(lower, ".")
+ switch stem {
+ case "con", "prn", "aux", "nul":
+ return true
+ }
+ return len(stem) == 4 && (strings.HasPrefix(stem, "com") || strings.HasPrefix(stem, "lpt")) &&
+ stem[3] >= '1' && stem[3] <= '9'
+}
+
+// pulledFileKey is name as macOS and Windows file systems compare it: case
+// folded, trailing dots and spaces dropped.
+func pulledFileKey(name string) string {
+ return strings.ToLower(strings.TrimRight(name, ". "))
+}
+
+// releasePath is the read doors' path for one release of app.
+func releasePath(a apiAcct, app, version, tail string) string {
+ return apiPath(a, app, "/releases/"+url.PathEscape(version)+tail)
+}
+
+// releaseManifestRaw reads GET .../releases/{version}/manifest: the exact
+// bytes the console stores.
+func (s *apiSession) releaseManifestRaw(ctx context.Context, a apiAcct, app, version string) ([]byte, error) {
+ ctx, cancel := context.WithTimeout(ctx, releaseManifestTimeout)
+ defer cancel()
+ res, err := s.c.doStream(ctx, http.MethodGet, releasePath(a, app, version, "/manifest"), nil, -1, nil)
+ if err != nil {
+ return nil, err
+ }
+ defer res.Body.Close()
+ body, err := io.ReadAll(io.LimitReader(res.Body, releaseManifestMaxBytes+1))
+ if err != nil {
+ return nil, err
+ }
+ if res.StatusCode/100 != 2 {
+ return nil, apiErrorFromBody(res.StatusCode, body)
+ }
+ if len(body) > releaseManifestMaxBytes {
+ return nil, fmt.Errorf("the console's manifest for %s %s is larger than %d bytes", app, version, releaseManifestMaxBytes)
+ }
+ return body, nil
+}
+
+// pullArtifact streams one artifact to a fresh temp file beside dst
+// (<file>.partial-*, created exclusively, so a symlink already in the
+// directory is never followed), hashing as it goes, and renames it over dst
+// only when its size and sha256 match art. A mismatch or a failed read
+// removes the temp file.
+func (s *apiSession) pullArtifact(ctx context.Context, a apiAcct, app, version string, art release.Artifact, dst string) error {
+ res, err := s.c.doStream(ctx, http.MethodGet, releasePath(a, app, version, "/artifacts/"+url.PathEscape(art.File)), nil, -1, nil)
+ if err != nil {
+ return err
+ }
+ defer res.Body.Close()
+ if res.StatusCode/100 != 2 {
+ body, _ := io.ReadAll(io.LimitReader(res.Body, releaseManifestMaxBytes))
+ return apiErrorFromBody(res.StatusCode, body)
+ }
+ f, err := os.CreateTemp(filepath.Dir(dst), filepath.Base(dst)+".partial-*")
+ if err != nil {
+ return err
+ }
+ partial := f.Name()
+ h := sha256.New()
+ n, copyErr := io.Copy(io.MultiWriter(f, h), io.LimitReader(res.Body, art.Size+1))
+ closeErr := f.Close()
+ sum := hex.EncodeToString(h.Sum(nil))
+ if copyErr != nil || closeErr != nil || n != art.Size || sum != art.SHA256 {
+ _ = os.Remove(partial)
+ mismatch := fmt.Errorf("%s: got %d bytes with sha256 %s but the release says %d bytes with sha256 %s. the partial file was removed", art.File, n, sum, art.Size, art.SHA256)
+ if cause := errors.Join(copyErr, closeErr); cause != nil {
+ return fmt.Errorf("%w: %w", mismatch, cause)
+ }
+ return mismatch
+ }
+ err = os.Chmod(partial, 0o644)
+ if err == nil {
+ err = os.Rename(partial, dst)
+ }
+ if err != nil {
+ _ = os.Remove(partial)
+ }
+ return err
+}
diff --git a/release_pull_test.go b/release_pull_test.go
new file mode 100644
index 000000000..3b8ecea12
--- /dev/null
+++ b/release_pull_test.go
@@ -0,0 +1,367 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// pullPayload is the binary every pull test ships as shop v12.
+var pullPayload = bytes.Repeat([]byte{0x42}, 1024)
+
+// shipPullSource starts the source console and ships shop v12 to it under
+// a publish credential.
+func shipPullSource(t *testing.T) copyConsole {
+ t.Helper()
+ a := newCopyConsole(t, "shop")
+ useConsole(t, a, a.token(t, "shop", svcrole.Publish))
+ bin := filepath.Join(t.TempDir(), "shop")
+ if err := os.WriteFile(bin, pullPayload, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ buf := captureStdout(t)
+ runShip([]string{"--app", "shop", "--account", release.OpsAccount, "--version", "v12", "--label", "fixing modals", "--target", "linux-arm64", bin})
+ if !strings.Contains(buf.String(), "shipped shop v12") {
+ t.Fatalf("ship stdout = %q, want the shipped line", buf.String())
+ }
+ return a
+}
+
+// pullV12 pulls shop v12 from a into dir under a deploy credential.
+func pullV12(t *testing.T, a copyConsole, dir string) error {
+ t.Helper()
+ useConsole(t, a, a.token(t, "shop", svcrole.Deploy))
+ return runReleasesPull([]string{"v12", "--app", "shop", "--out", dir})
+}
+
+// noPartials fails when dir holds a pull's temp file (<file>.partial-*).
+func noPartials(t *testing.T, dir string) {
+ t.Helper()
+ ents, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, e := range ents {
+ if strings.Contains(e.Name(), ".partial-") {
+ t.Fatalf("%s left behind in %s", e.Name(), dir)
+ }
+ }
+}
+
+func TestReleasesPullWritesManifestAndArtifacts(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ a := shipPullSource(t)
+ dir := filepath.Join(t.TempDir(), "release")
+ buf := captureStdout(t)
+ if err := pullV12(t, a, dir); err != nil {
+ t.Fatalf("pull: %v", err)
+ }
+ if want := "pulled shop v12 into " + dir + ". every file matches its digest"; !strings.Contains(buf.String(), want) {
+ t.Fatalf("pull stdout = %q, want %q", buf.String(), want)
+ }
+ _, raw, err := release.GetManifestRaw(context.Background(), a.rel, release.OpsAccount, "shop", "v12")
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := os.ReadFile(filepath.Join(dir, "manifest.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(got, raw) {
+ t.Fatalf("manifest.json = %s, want the stored bytes %s", got, raw)
+ }
+ bin, err := os.ReadFile(filepath.Join(dir, "linux-arm64"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(bin, pullPayload) {
+ t.Fatalf("linux-arm64 is %d bytes, not the shipped payload", len(bin))
+ }
+ noPartials(t, dir)
+}
+
+func TestReleasesPullRefusesADirThatHoldsARelease(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ a := shipPullSource(t)
+ dir := filepath.Join(t.TempDir(), "release")
+ if err := pullV12(t, a, dir); err != nil {
+ t.Fatalf("first pull: %v", err)
+ }
+ err := runReleasesPull([]string{"v12", "--app", "shop", "--out", dir})
+ if err == nil || !strings.Contains(err.Error(), "already holds a release") {
+ t.Fatalf("second pull = %v, want it refused as already holding a release", err)
+ }
+}
+
+func TestReleasesPullFinishesAnIncompleteDir(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ a := shipPullSource(t)
+ dir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(dir, "linux-arm64"), []byte("junk from an interrupted pull"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := pullV12(t, a, dir); err != nil {
+ t.Fatalf("pull into an incomplete dir: %v", err)
+ }
+ bin, err := os.ReadFile(filepath.Join(dir, "linux-arm64"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(bin, pullPayload) {
+ t.Fatalf("linux-arm64 = %q, want the shipped payload", bin)
+ }
+ if _, err := os.Stat(filepath.Join(dir, "manifest.json")); err != nil {
+ t.Fatalf("manifest.json: %v", err)
+ }
+ noPartials(t, dir)
+}
+
+// noLock fails when dir still holds a pull's lock.
+func noLock(t *testing.T, dir string) {
+ t.Helper()
+ if _, err := os.Lstat(filepath.Join(dir, pullLockName)); !os.IsNotExist(err) {
+ t.Fatalf("%s left behind in %s (stat: %v)", pullLockName, dir, err)
+ }
+}
+
+// A lock already in the directory refuses the pull before anything is
+// written, and the lock is left as it was.
+func TestReleasesPullRefusesALockedDir(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ a := shipPullSource(t)
+ dir := t.TempDir()
+ lock := filepath.Join(dir, pullLockName)
+ held := []byte("held by another pull")
+ if err := os.WriteFile(lock, held, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ err := pullV12(t, a, dir)
+ want := "another pull is writing to " + dir + ". if none is running, remove " + lock + " and pull again"
+ if err == nil || err.Error() != want {
+ t.Fatalf("pull into a locked dir = %v, want %q", err, want)
+ }
+ ents, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(ents) != 1 || ents[0].Name() != pullLockName {
+ var names []string
+ for _, e := range ents {
+ names = append(names, e.Name())
+ }
+ t.Fatalf("%s holds %v after a refused pull, want only the lock", dir, names)
+ }
+ if got, _ := os.ReadFile(lock); !bytes.Equal(got, held) {
+ t.Fatalf("lock = %q, want it untouched", got)
+ }
+}
+
+func TestReleasesPullRemovesItsLock(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ a := shipPullSource(t)
+ dir := filepath.Join(t.TempDir(), "release")
+ if err := pullV12(t, a, dir); err != nil {
+ t.Fatalf("pull: %v", err)
+ }
+ noLock(t, dir)
+ // A refused second pull takes the lock, finds the manifest and lets go.
+ err := runReleasesPull([]string{"v12", "--app", "shop", "--out", dir})
+ if err == nil || !strings.Contains(err.Error(), "already holds a release") {
+ t.Fatalf("second pull = %v, want it refused as already holding a release", err)
+ }
+ noLock(t, dir)
+}
+
+func TestReleasesPullRemovesACorruptDownload(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ a := shipPullSource(t)
+ obj := filepath.Join(a.storeDir, release.ArtifactKey(release.OpsAccount, "shop", "v12", "linux-arm64"))
+ corrupt := bytes.Clone(pullPayload)
+ corrupt[100] ^= 0xff
+ if err := os.WriteFile(obj, corrupt, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ dir := t.TempDir()
+ err := pullV12(t, a, dir)
+ if err == nil || !strings.Contains(err.Error(), "the partial file was removed") {
+ t.Fatalf("pull of a corrupt artifact = %v, want the partial-removed refusal", err)
+ }
+ for _, name := range []string{"linux-arm64", "linux-arm64.partial", "manifest.json"} {
+ if _, err := os.Stat(filepath.Join(dir, name)); !os.IsNotExist(err) {
+ t.Fatalf("%s is in %s after a refused pull (stat: %v)", name, dir, err)
+ }
+ }
+ noPartials(t, dir)
+ noLock(t, dir)
+}
+
+// A <file>.partial symlink left in the directory is never followed: the
+// file it points at keeps its bytes, and the pull still succeeds.
+func TestReleasesPullLeavesAPartialSymlinkAlone(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ a := shipPullSource(t)
+ outside := filepath.Join(t.TempDir(), "precious")
+ want := []byte("not yours to truncate")
+ if err := os.WriteFile(outside, want, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ dir := t.TempDir()
+ if err := os.Symlink(outside, filepath.Join(dir, "linux-arm64.partial")); err != nil {
+ t.Skipf("no symlinks here: %v", err)
+ }
+ if err := pullV12(t, a, dir); err != nil {
+ t.Fatalf("pull beside a partial symlink: %v", err)
+ }
+ got, err := os.ReadFile(outside)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(got, want) {
+ t.Fatalf("the symlink's target now holds %d bytes %q, want it untouched", len(got), got)
+ }
+ bin, err := os.ReadFile(filepath.Join(dir, "linux-arm64"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(bin, pullPayload) {
+ t.Fatalf("linux-arm64 is %d bytes, not the shipped payload", len(bin))
+ }
+ noPartials(t, dir)
+}
+
+func TestReleasesPullNeedsAConsole(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ t.Setenv("CARLOS_DEPLOYMENT_DIR", t.TempDir())
+ err := runReleasesPull([]string{"v12", "--app", "shop", "--out", t.TempDir()})
+ if err == nil || err.Error() != releasesPullNeedsConsole {
+ t.Fatalf("pull in bucket mode = %v, want %q", err, releasesPullNeedsConsole)
+ }
+}
+
+func TestPulledFileKeyCollides(t *testing.T) {
+ if pulledFileKey("linux-arm64") != pulledFileKey("Linux-ARM64. ") {
+ t.Fatalf("pulledFileKey keeps %q and %q apart; Windows would not", "linux-arm64", "Linux-ARM64. ")
+ }
+}
+
+func TestValidPulledFile(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ want bool
+ }{
+ {"linux-arm64", true},
+ {"site.tar.gz", true},
+ {"rootfs.squashfs", true},
+ {"", false},
+ {".", false},
+ {"..", false},
+ {"../x", false},
+ {"a/b", false},
+ {`a\b`, false},
+ {"manifest.json", false},
+ {"linux-arm64.partial", false},
+ {"Manifest.JSON", false},
+ {"linux-arm64.PARTIAL", false},
+ {"linux-arm64.partial-123", false},
+ {".carlos-pull.lock", false},
+ {".Carlos-Pull.LOCK", false},
+ {"manifest.json.", false},
+ {"manifest.json ", false},
+ {"linux-arm64.", false},
+ {"linux-arm64 ", false},
+ {"a<b", false},
+ {"a>b", false},
+ {"a:b", false},
+ {`a"b`, false},
+ {"a|b", false},
+ {"a?b", false},
+ {"a*b", false},
+ {"a\x00b", false},
+ {"a\x1fb", false},
+ {"a\tb", false},
+ {"con", false},
+ {"PRN", false},
+ {"Aux", false},
+ {"nul", false},
+ {"nul.txt", false},
+ {"NUL.tar.gz", false},
+ {"COM1.tar", false},
+ {"com9", false},
+ {"lpt1", false},
+ {"LPT9.log", false},
+ {"com0", true},
+ {"com10", true},
+ {"console", true},
+ {"nullable.bin", true},
+ {"auxiliary", true},
+ {".hidden", true},
+ {"linux_amd64-v2.bin", true},
+ {"COM¹", false},
+ {"lpt³.txt", false},
+ {"LPT²", false},
+ {"café", false},
+ {"a b", false},
+ {"a+b", false},
+ } {
+ if got := validPulledFile(tc.name); got != tc.want {
+ t.Errorf("validPulledFile(%q) = %v, want %v", tc.name, got, tc.want)
+ }
+ }
+}
+
+// publishNoReplace refuses a destination that already exists: its bytes
+// stay as they were, the error matches fs.ErrExist, and the temp file is
+// gone.
+func TestPublishNoReplaceRefusesAnExistingFile(t *testing.T) {
+ dir := t.TempDir()
+ dst := filepath.Join(dir, "manifest.json")
+ if err := os.WriteFile(dst, []byte("first"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ tmp := filepath.Join(dir, "manifest.json.partial-1")
+ if err := os.WriteFile(tmp, []byte("second"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := publishNoReplace(tmp, dst); !errors.Is(err, fs.ErrExist) {
+ t.Fatalf("publishNoReplace over an existing file = %v, want fs.ErrExist", err)
+ }
+ if got, _ := os.ReadFile(dst); string(got) != "first" {
+ t.Fatalf("dst = %q, want it unchanged", got)
+ }
+ if _, err := os.Stat(tmp); !os.IsNotExist(err) {
+ t.Fatalf("temp file still there (stat: %v)", err)
+ }
+}
+
+// With no destination, publishNoReplace publishes and leaves no temp file.
+func TestPublishNoReplacePublishes(t *testing.T) {
+ dir := t.TempDir()
+ dst := filepath.Join(dir, "manifest.json")
+ tmp := filepath.Join(dir, "manifest.json.partial-1")
+ if err := os.WriteFile(tmp, []byte("only"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := publishNoReplace(tmp, dst); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := os.ReadFile(dst); string(got) != "only" {
+ t.Fatalf("dst = %q, want the temp file's bytes", got)
+ }
+ noPartials(t, dir)
+}
diff --git a/ship_from_release.go b/ship_from_release.go
new file mode 100644
index 000000000..9d6122ea0
--- /dev/null
+++ b/ship_from_release.go
@@ -0,0 +1,364 @@
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "mime/multipart"
+ "net/http"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// `carlos ship --from-release <dir>` (#1389 item 1): the target half of
+// copying a shipped release from one console to another. It ships the
+// files `carlos releases pull` wrote into dir under the release's own
+// version and settings, sends the source's digests as expect_artifacts so
+// the console stores those exact bytes or nothing, and checks the digests
+// the console answers with. The target console hashes what it receives and
+// writes and signs its own manifest; only the artifact digests and the
+// release's settings come from the source manifest.
+
+const (
+ shipFromReleaseUsage = "usage: carlos ship --from-release <dir> [--app <a>] [--account <sqid-or-name>] [--account-id <sqid>] [--console <origin>] [--program-change] [--message <text>]"
+ shipFromReleaseNeedsConsole = "carlos ship --from-release needs a console. unset CARLOS_DEPLOYMENT_BUCKET and CARLOS_DEPLOYMENT_DIR, then set CARLOS_CONSOLE or run carlos login"
+ shipFromReleaseFlagConflict = "--from-release ships the release's own settings, so it cannot be combined with --%s"
+ shipFromReleaseNoFileArgs = "--from-release ships the files in its directory, so it takes no file arguments"
+ shipFromReleaseNoManifest = "%s has no manifest.json. run carlos releases pull first"
+ shipFromReleaseFileDiffers = "%s does not match manifest.json, so nothing was shipped"
+ shipFromReleaseDigestDiffer = "the console stored %s with a different digest than the source release. do not promote this version"
+ shipFromReleaseDone = "shipped %s %s from %s. every digest matches the source release"
+ shipFromReleaseNoOp = "already shipped %s %s with identical content, nothing to do"
+)
+
+// shipFromReleaseFlags are the flags --from-release may be given with:
+// where to ship, and the operator's own say on the ship. Everything else
+// is a setting the release already carries.
+var shipFromReleaseFlags = map[string]bool{
+ "from-release": true, "app": true, "a": true, "account": true, "account-id": true,
+ "console": true, "destination": true, "d": true, "message": true, "no-prompt": true,
+ "program-change": true,
+}
+
+// fromReleaseOpts is runShip's flags as --from-release reads them.
+type fromReleaseOpts struct {
+ dir, app, console string
+ acctRaw, acctIDRaw *string
+ programChange bool
+ messageFlags mutationMessageFlags
+}
+
+// fromReleaseConflicts refuses a flag the release's own settings would
+// contradict, the first in name order, then any file argument.
+func fromReleaseConflicts(fs *flag.FlagSet) error {
+ var other string
+ // fs.Visit walks the set flags in name order, so the first is named.
+ fs.Visit(func(f *flag.Flag) {
+ if other == "" && !shipFromReleaseFlags[f.Name] {
+ other = f.Name
+ }
+ })
+ if other != "" {
+ return fmt.Errorf(shipFromReleaseFlagConflict, other)
+ }
+ if fs.NArg() > 0 {
+ return errors.New(shipFromReleaseNoFileArgs)
+ }
+ return nil
+}
+
+// runShipFromRelease is `carlos ship --from-release <dir>`. dir is read and
+// every file checked against manifest.json before the console is asked
+// anything.
+func runShipFromRelease(fs *flag.FlagSet, o fromReleaseOpts) error {
+ if err := fromReleaseConflicts(fs); err != nil {
+ return err
+ }
+ sess, err := resolveMode(o.console)
+ if err != nil {
+ return err
+ }
+ if sess == nil {
+ return errors.New(shipFromReleaseNeedsConsole)
+ }
+ m, parts, err := loadReleaseDir(o.dir)
+ if err != nil {
+ return err
+ }
+ printUsing(stdout, sess)
+ ctx := context.Background()
+ acct := apiAccount(o.acctRaw, o.acctIDRaw)
+ if acct.Seg == "" {
+ if acct, err = sess.defaultAccount(ctx); err != nil {
+ return err
+ }
+ }
+ app := strings.TrimSpace(o.app)
+ if app == "" {
+ if app, err = sess.defaultApp(ctx, acct, true); err != nil {
+ return err
+ }
+ if app == "" {
+ return errors.New(shipFromReleaseUsage)
+ }
+ }
+ message, err := resolveMutationMessage(fs, o.messageFlags)
+ if err != nil {
+ return err
+ }
+ res, err := sess.shipFromRelease(ctx, acct, app, m, parts, o.programChange, message)
+ if err != nil {
+ return err
+ }
+ if res.NoOp {
+ mutedf(stdout, shipFromReleaseNoOp+"\n", app, m.Version)
+ } else {
+ fmt.Fprintf(stdout, shipFromReleaseDone+"\n", app, m.Version, o.dir)
+ }
+ if m.Swap == release.DemandHold {
+ mutedf(stdout, shipHoldNote)
+ }
+ return nil
+}
+
+// loadReleaseDir reads dir/manifest.json and checks every file it names
+// against its size and sha256. parts maps each artifact key to its file.
+func loadReleaseDir(dir string) (*release.Manifest, map[string]string, error) {
+ raw, err := os.ReadFile(filepath.Join(dir, "manifest.json"))
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, nil, fmt.Errorf(shipFromReleaseNoManifest, dir)
+ }
+ if err != nil {
+ return nil, nil, err
+ }
+ var m release.Manifest
+ if err := json.Unmarshal(raw, &m); err != nil {
+ return nil, nil, fmt.Errorf("%s: manifest.json does not parse: %w", dir, err)
+ }
+ switch m.Kind {
+ case "binary", "static", release.KindRootfs:
+ default:
+ return nil, nil, fmt.Errorf("%s: manifest.json has kind %q, not binary, static or rootfs", dir, m.Kind)
+ }
+ // An empty version would have the console mint one: the copy would land
+ // under a name the source never shipped.
+ if m.Version == "" || len(m.Artifacts) == 0 {
+ return nil, nil, fmt.Errorf("%s: manifest.json must name a version and at least one file", dir)
+ }
+ for _, art := range m.Artifacts {
+ if !validPulledFile(art.File) {
+ return nil, nil, fmt.Errorf("%s: manifest.json names a file %q that cannot be read safely", dir, art.File)
+ }
+ }
+ parts := make(map[string]string, len(m.Artifacts))
+ for key, art := range m.Artifacts {
+ path := filepath.Join(dir, art.File)
+ size, sum, err := hashReleaseFile(path)
+ if err != nil {
+ return nil, nil, err
+ }
+ if size != art.Size || sum != art.SHA256 {
+ return nil, nil, fmt.Errorf(shipFromReleaseFileDiffers, path)
+ }
+ parts[key] = path
+ }
+ return &m, parts, nil
+}
+
+// hashReleaseFile is path's length and hex sha256.
+func hashReleaseFile(path string) (int64, string, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return 0, "", err
+ }
+ defer f.Close()
+ h := sha256.New()
+ n, err := io.Copy(h, f)
+ if err != nil {
+ return 0, "", err
+ }
+ return n, hex.EncodeToString(h.Sum(nil)), nil
+}
+
+// fromReleaseMeta is the ship door's meta part for a copied release: every
+// setting the source manifest carries, and its digests as expect_artifacts.
+type fromReleaseMeta struct {
+ Version string `json:"version"`
+ Kind string `json:"kind"`
+ Label string `json:"label,omitempty"`
+ Notes string `json:"notes,omitempty"`
+ Message string `json:"message,omitempty"`
+ Capabilities json.RawMessage `json:"capabilities,omitempty"`
+ ProgramChange bool `json:"program_change,omitempty"`
+ Swap string `json:"swap,omitempty"`
+ Stateless bool `json:"stateless,omitempty"`
+ Mail string `json:"mail,omitempty"`
+ Assets *release.Assets `json:"assets,omitempty"`
+ Processes json.RawMessage `json:"processes,omitempty"`
+ Hibernate bool `json:"hibernate,omitempty"`
+ JIT bool `json:"jit,omitempty"`
+ RootfsSize int64 `json:"rootfs_size,omitempty"`
+ ExpectArtifacts map[string]shippedArtifact `json:"expect_artifacts"`
+}
+
+// shippedArtifact is one artifact's digest on the wire, both ways.
+type shippedArtifact struct {
+ SHA256 string `json:"sha256"`
+ Size int64 `json:"size"`
+}
+
+// fromReleaseMetaFor builds m's meta part.
+func fromReleaseMetaFor(m *release.Manifest, programChange bool, message string) (fromReleaseMeta, error) {
+ meta := fromReleaseMeta{
+ Version: m.Version, Kind: m.Kind, Label: m.Label, Notes: m.Notes, Message: message,
+ ProgramChange: m.ProgramChange || programChange,
+ Swap: m.Swap, Stateless: m.Stateless, Mail: m.Mail, Assets: m.Assets,
+ ExpectArtifacts: make(map[string]shippedArtifact, len(m.Artifacts)),
+ }
+ for k, a := range m.Artifacts {
+ meta.ExpectArtifacts[k] = shippedArtifact{SHA256: a.SHA256, Size: a.Size}
+ }
+ if m.Capabilities != nil {
+ b, err := json.Marshal(m.Capabilities)
+ if err != nil {
+ return meta, err
+ }
+ meta.Capabilities = b
+ }
+ if m.IsRootfs() {
+ b, err := json.Marshal(m.Processes)
+ if err != nil {
+ return meta, err
+ }
+ meta.Processes = b
+ meta.Hibernate, meta.JIT = m.Hibernate, m.JIT
+ meta.RootfsSize = m.Artifacts[release.RootfsArtifactKey].Size
+ }
+ return meta, nil
+}
+
+// shipFromRelease uploads a pulled release: the meta part, then one file
+// part per artifact in key order. On success it checks every echo a plain
+// ship checks, then that the console stored exactly the source's digests.
+func (s *apiSession) shipFromRelease(ctx context.Context, a apiAcct, app string, m *release.Manifest, parts map[string]string, programChange bool, message string) (apiShipResult, error) {
+ meta, err := fromReleaseMetaFor(m, programChange, message)
+ if err != nil {
+ return apiShipResult{}, err
+ }
+ metaJSON, err := json.Marshal(meta)
+ if err != nil {
+ return apiShipResult{}, err
+ }
+ limit := shipTimeout
+ if m.IsRootfs() {
+ limit = shipRootfsTimeout
+ }
+ ctx, cancel := context.WithTimeout(ctx, limit)
+ defer cancel()
+ keys := make([]string, 0, len(parts))
+ for k := range parts {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ status, body, err := s.c.doMultipart(ctx, apiPath(a, app, "/releases"), func(mw *multipart.Writer) error {
+ metaPart, err := mw.CreateFormField("meta")
+ if err != nil {
+ return err
+ }
+ if _, err := metaPart.Write(metaJSON); err != nil {
+ return err
+ }
+ for _, k := range keys {
+ if err := writeFilePart(mw, k, parts[k]); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return apiShipResult{}, err
+ }
+ if status != http.StatusCreated && status != http.StatusOK {
+ err := apiErrorFromBody(status, body)
+ if m.IsRootfs() && status == http.StatusBadRequest && err.Error() == shipOldConsoleKind {
+ return apiShipResult{}, errShipRootfsOldConsole
+ }
+ return apiShipResult{}, err
+ }
+ out, err := checkFromReleaseAnswer(m, body)
+ if err != nil {
+ return apiShipResult{}, err
+ }
+ return apiShipResult{NoOp: status == http.StatusOK, Version: out.Version, BuildProbe: out.BuildProbe}, nil
+}
+
+// fromReleaseAnswer is the part of a ship answer a copied release reads.
+type fromReleaseAnswer struct {
+ Version string `json:"version"`
+ BuildProbe string `json:"build_probe"`
+ Assets *release.Assets `json:"assets"`
+}
+
+// checkFromReleaseAnswer checks a successful ship answer for m: every echo
+// a plain ship checks, the asset folders, then the stored digests.
+func checkFromReleaseAnswer(m *release.Manifest, body []byte) (fromReleaseAnswer, error) {
+ var out fromReleaseAnswer
+ if err := json.Unmarshal(body, &out); err != nil {
+ return out, fmt.Errorf("ship: malformed response: %w", err)
+ }
+ var assets []string
+ if m.Assets != nil {
+ assets = m.Assets.Paths
+ }
+ for _, err := range []error{
+ checkCapabilitiesEcho(m.Capabilities, body),
+ checkStatelessEcho(m.Stateless, body),
+ checkMailEcho(m.Mail, body),
+ checkSwapEcho(m.Swap, body),
+ checkAssetsEcho(assets, out.Assets),
+ compareShippedArtifacts(m.Artifacts, body),
+ } {
+ if err != nil {
+ return out, err
+ }
+ }
+ return out, nil
+}
+
+// compareShippedArtifacts refuses a ship answer whose artifacts differ from
+// want in any key, digest or size, the first in key order. A console that
+// answers with no artifacts at all is refused too: nothing says what it
+// stored.
+func compareShippedArtifacts(want map[string]release.Artifact, body []byte) error {
+ var got struct {
+ Artifacts map[string]shippedArtifact `json:"artifacts"`
+ }
+ _ = json.Unmarshal(body, &got)
+ keys := make([]string, 0, len(want)+len(got.Artifacts))
+ for k := range want {
+ keys = append(keys, k)
+ }
+ for k := range got.Artifacts {
+ if _, ok := want[k]; !ok {
+ keys = append(keys, k)
+ }
+ }
+ sort.Strings(keys)
+ for _, k := range keys {
+ w, wok := want[k]
+ g, gok := got.Artifacts[k]
+ if !wok || !gok || g.SHA256 != w.SHA256 || g.Size != w.Size {
+ return fmt.Errorf(shipFromReleaseDigestDiffer, k)
+ }
+ }
+ return nil
+}
diff --git a/ship_from_release_test.go b/ship_from_release_test.go
new file mode 100644
index 000000000..1d4e1aa3d
--- /dev/null
+++ b/ship_from_release_test.go
@@ -0,0 +1,133 @@
+package main
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func TestShipFromReleaseRefusesOtherFlags(t *testing.T) {
+ dir := t.TempDir()
+ for _, tc := range []struct {
+ args []string
+ want string
+ }{
+ {[]string{"--app", "shop", "--label", "x"}, "--from-release ships the release's own settings, so it cannot be combined with --label"},
+ {[]string{"--app", "shop", "./bin"}, "--from-release ships the files in its directory, so it takes no file arguments"},
+ } {
+ cmd := exec.Command(sharedCarlos(t), append([]string{"ship", "--from-release", dir}, tc.args...)...)
+ cmd.Dir = t.TempDir()
+ cmd.Env = carlosTestEnv(t)
+ var stderr strings.Builder
+ cmd.Stderr = &stderr
+ err := cmd.Run()
+ if err == nil || !strings.Contains(stderr.String(), tc.want) {
+ t.Fatalf("carlos ship --from-release %v: err %v stderr %q, want %q", tc.args, err, stderr.String(), tc.want)
+ }
+ }
+}
+
+func TestCompareShippedArtifacts(t *testing.T) {
+ sha := strings.Repeat("a", 64)
+ want := map[string]release.Artifact{"linux-arm64": {File: "linux-arm64", SHA256: sha, Size: 10}}
+ for _, tc := range []struct {
+ name, body string
+ ok bool
+ }{
+ {"identical", `{"artifacts":{"linux-arm64":{"sha256":"` + sha + `","size":10}}}`, true},
+ {"different sha", `{"artifacts":{"linux-arm64":{"sha256":"` + strings.Repeat("b", 64) + `","size":10}}}`, false},
+ {"different size", `{"artifacts":{"linux-arm64":{"sha256":"` + sha + `","size":11}}}`, false},
+ {"extra key", `{"artifacts":{"linux-arm64":{"sha256":"` + sha + `","size":10},"linux-amd64":{"sha256":"` + sha + `","size":10}}}`, false},
+ {"missing key", `{"artifacts":{}}`, false},
+ {"old console", `{"result":"shipped","version":"v12"}`, false},
+ } {
+ err := compareShippedArtifacts(want, []byte(tc.body))
+ if (err == nil) != tc.ok {
+ t.Fatalf("%s: err = %v, want ok %v", tc.name, err, tc.ok)
+ }
+ if err != nil && !strings.Contains(err.Error(), "do not promote this version") {
+ t.Fatalf("%s: err = %v, want the do-not-promote sentence", tc.name, err)
+ }
+ }
+}
+
+func TestLoadReleaseDirRefusesUnsafeNames(t *testing.T) {
+ // ../x exists beside dir and matches the manifest, so only the name
+ // check stands between the manifest and a file outside dir.
+ root := t.TempDir()
+ dir := filepath.Join(root, "release")
+ if err := os.Mkdir(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ outside := []byte("outside")
+ if err := os.WriteFile(filepath.Join(root, "x"), outside, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ sum := sha256.Sum256(outside)
+ manifest := `{"schema":1,"app":"shop","version":"v12","kind":"binary","artifacts":{"linux-arm64":{"file":"../x","sha256":"` +
+ hex.EncodeToString(sum[:]) + `","size":` + strconv.Itoa(len(outside)) + `}}}`
+ if err := os.WriteFile(filepath.Join(dir, "manifest.json"), []byte(manifest), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ _, _, err := loadReleaseDir(dir)
+ if err == nil || !strings.Contains(err.Error(), `names a file "../x" that cannot be read safely`) {
+ t.Fatalf("loadReleaseDir of a manifest naming ../x = %v, want the unsafe-name refusal", err)
+ }
+}
+
+// manifest.json. is manifest.json on Windows. It is refused before any
+// file is read, even here, where it is a separate file whose bytes match.
+func TestLoadReleaseDirRefusesWindowsAliases(t *testing.T) {
+ dir := t.TempDir()
+ alias := []byte("an alias of the manifest")
+ if err := os.WriteFile(filepath.Join(dir, "manifest.json."), alias, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ sum := sha256.Sum256(alias)
+ manifest := `{"schema":1,"app":"shop","version":"v12","kind":"binary","artifacts":{"linux-arm64":{"file":"manifest.json.","sha256":"` +
+ hex.EncodeToString(sum[:]) + `","size":` + strconv.Itoa(len(alias)) + `}}}`
+ if err := os.WriteFile(filepath.Join(dir, "manifest.json"), []byte(manifest), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ _, _, err := loadReleaseDir(dir)
+ if err == nil || !strings.Contains(err.Error(), `names a file "manifest.json." that cannot be read safely`) {
+ t.Fatalf("loadReleaseDir of a manifest naming manifest.json. = %v, want the unsafe-name refusal", err)
+ }
+}
+
+func TestCheckFromReleaseAnswerAssets(t *testing.T) {
+ sha := strings.Repeat("a", 64)
+ m := &release.Manifest{
+ Version: "v12", Kind: "binary", Assets: &release.Assets{Paths: []string{"/assets/", "/img/"}},
+ Artifacts: map[string]release.Artifact{"linux-arm64": {File: "linux-arm64", SHA256: sha, Size: 10}},
+ }
+ arts := `"artifacts":{"linux-arm64":{"sha256":"` + sha + `","size":10}}`
+ for _, tc := range []struct {
+ name, body string
+ ok bool
+ }{
+ {"same folders", `{"version":"v12",` + arts + `,"assets":{"paths":["/img/","/assets/"]}}`, true},
+ {"no assets echoed", `{"version":"v12",` + arts + `}`, false},
+ {"other folders", `{"version":"v12",` + arts + `,"assets":{"paths":["/assets/"]}}`, false},
+ } {
+ _, err := checkFromReleaseAnswer(m, []byte(tc.body))
+ if (err == nil) != tc.ok {
+ t.Fatalf("%s: err = %v, want ok %v", tc.name, err, tc.ok)
+ }
+ }
+}
+
+func TestLoadReleaseDirNeedsAManifest(t *testing.T) {
+ dir := t.TempDir()
+ _, _, err := loadReleaseDir(dir)
+ if err == nil || err.Error() != dir+" has no manifest.json. run carlos releases pull first" {
+ t.Fatalf("loadReleaseDir of an empty dir = %v", err)
+ }
+}
diff --git a/testdata/clireg-golden.jsonl b/testdata/clireg-golden.jsonl
index af1d6e7a4..befe59baa 100644
--- a/testdata/clireg-golden.jsonl
+++ b/testdata/clireg-golden.jsonl
@@ -729,6 +729,8 @@
{"case":"release-keygen | -h","argv":["release-keygen","-h"],"exit":0,"stdout":"","stderr":"usage: carlos release-keygen [flags]\nflags:\n --expires <duration> how long the scoped key may sign for (max 8760h) (default: 2160h0m0s)\n --name <string> label for the scoped key; it appears in every refusal it causes\n --scope <string> mint a SCOPED key for these rungs, comma separated (canary,edge,beta) — stable is never delegable\n"}
{"case":"releases authorize | --zz-unknown-flag","argv":["releases","authorize","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"flag provided but not defined: -zz-unknown-flag\nusage: carlos releases authorize [flags]\nflags:\n --account <string> account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one; ops in direct mode)\n --account-id <string> account sqid, matched as a sqid ONLY — supersedes --account; this is the flag an ambiguity error tells you to use\n --app, -a <string> app name\n --console <string> console origin to authorize through (API mode only; default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n --registry <string> registry database (resolves --account) (default: $DIR/data/registry.db)\n --yes sign without asking\n"}
{"case":"releases authorize | -h","argv":["releases","authorize","-h"],"exit":0,"stdout":"","stderr":"usage: carlos releases authorize [flags]\nflags:\n --account <string> account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one; ops in direct mode)\n --account-id <string> account sqid, matched as a sqid ONLY — supersedes --account; this is the flag an ambiguity error tells you to use\n --app, -a <string> app name\n --console <string> console origin to authorize through (API mode only; default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n --registry <string> registry database (resolves --account) (default: $DIR/data/registry.db)\n --yes sign without asking\n"}
+{"case":"releases pull | --zz-unknown-flag","argv":["releases","pull","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"flag provided but not defined: -zz-unknown-flag\nusage: carlos releases pull <version> --app <a> --out <dir> [--account <sqid-or-name>] [--account-id <sqid>] [--console <origin>]\nflags:\n --account <string> account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one; ops in direct mode)\n --account-id <string> account sqid, matched as a sqid ONLY — supersedes --account; this is the flag an ambiguity error tells you to use\n --app, -a <string> app name\n --console <string> console origin to read the release from (default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n --out <string> directory to write the manifest and artifacts into (created if missing)\n --registry <string> registry database (resolves --account) (default: $DIR/data/registry.db)\n"}
+{"case":"releases pull | -h","argv":["releases","pull","-h"],"exit":0,"stdout":"","stderr":"usage: carlos releases pull <version> --app <a> --out <dir> [--account <sqid-or-name>] [--account-id <sqid>] [--console <origin>]\nflags:\n --account <string> account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one; ops in direct mode)\n --account-id <string> account sqid, matched as a sqid ONLY — supersedes --account; this is the flag an ambiguity error tells you to use\n --app, -a <string> app name\n --console <string> console origin to read the release from (default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n --out <string> directory to write the manifest and artifacts into (created if missing)\n --registry <string> registry database (resolves --account) (default: $DIR/data/registry.db)\n"}
{"case":"releases retention | --zz-unknown-flag","argv":["releases","retention","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"flag provided but not defined: -zz-unknown-flag\nusage: carlos releases retention [flags]\nflags:\n --account <string> account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one; ops in direct mode)\n --account-id <string> account sqid, matched as a sqid ONLY — supersedes --account; this is the flag an ambiguity error tells you to use\n --app, -a <string> app whose retention policy to read or write\n --console <string> console origin (API mode only; default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n --dry-run with --keep: list what would be pruned, write nothing\n --keep <int> retain the newest N releases (minimum 20)\n --off clear the retention policy — keep releases forever again\n --registry <string> registry database (resolves --account) (default: $DIR/data/registry.db)\n"}
{"case":"releases retention | -h","argv":["releases","retention","-h"],"exit":0,"stdout":"","stderr":"usage: carlos releases retention [flags]\nflags:\n --account <string> account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one; ops in direct mode)\n --account-id <string> account sqid, matched as a sqid ONLY — supersedes --account; this is the flag an ambiguity error tells you to use\n --app, -a <string> app whose retention policy to read or write\n --console <string> console origin (API mode only; default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n --dry-run with --keep: list what would be pruned, write nothing\n --keep <int> retain the newest N releases (minimum 20)\n --off clear the retention policy — keep releases forever again\n --registry <string> registry database (resolves --account) (default: $DIR/data/registry.db)\n"}
{"case":"releases | --help","argv":["releases","--help"],"exit":0,"stdout":"","stderr":"usage: carlos releases [flags]\nflags:\n --account <string> account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one; ops in direct mode)\n --account-id <string> account sqid, matched as a sqid ONLY — supersedes --account; this is the flag an ambiguity error tells you to use\n --app, -a <string> app name\n --console <string> console origin to read through (API mode only; default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n --registry <string> registry database (resolves --account) (default: $DIR/data/registry.db)\n"}
@@ -792,8 +794,8 @@
{"case":"services | bare","argv":["services"],"exit":1,"stdout":"","stderr":"usage: carlos services <create|ls|rotate|revoke> [flags]\n\n create --role <publish|deploy|instance|operate|service|run|admin> [--app <app>] [--account <sqid|name>] [--json] <name>\n mint a credential a SERVER holds, bound to this account —\n not to you. Unlike your own CLI token, its reach is fixed\n at mint: adding you to another account later does not widen\n it, and it draws on its own rate-limit budgets rather than\n yours.\n THE SECRET IS PRINTED EXACTLY ONCE, HERE. Only its hash is\n stored, so losing this output means rotate, not a re-run.\n --role admin INCLUDES `store grant`, which mints a\n path-scoped IAM user. It is a real handover, not a\n convenience bundle. Prefer the narrowest role that works.\n --app binds it to ONE app, which also means it cannot create\n apps. Omit --app for an account-scoped credential.\n --role run needs --app and --commands, the command\n prefixes it may run: --commands \"import classic,import sync\".\n Words are matched exactly, from the start of the command.\n --json prints one JSON object and nothing else, the bare\n secret in its \"secret\" field: carlos services create\n ... --json name | jq -r .secret\n\n ls [--account <sqid|name>]\n list every LIVE credential the account owns — name, role,\n scope, when it was minted and last rotated and used, and\n who minted it. A revoked credential does not appear; there\n is no history view here.\n\n rotate [--account <sqid|name>] [--json] <name>\n mint a FRESH secret for a credential that already exists,\n printed exactly once. This refuses the credential's NEXT\n call with the old secret. ROTATION IS NOT REVOCATION: it\n does not stop work already in flight, and a credential that\n may be COMPROMISED needs revoke. --json prints one JSON\n object, {\"name\", \"account\", \"secret\"}, and nothing else.\n\n revoke [--account <sqid|name>] <name-or-id>\n the hard stop rotate is not: the credential's next call\n fails, whatever secret it holds. Idempotent — revoking a\n name twice, or one that never existed, answers the same.\n Takes a credential's name, or the listing id `ls` shows\n (the only handle a nameless legacy credential has).\n\n --account <sqid|name> account the credential belongs to (default: your only\n account, or the configured/chosen one) —\n resolved by the console against your own\n memberships.\n --account-id <sqid> account sqid, matched as a sqid ONLY — supersedes\n --account\n --console <origin> which logged-in console to use (only needed with\n several)\n\nEvery verb here is signed-in only (carlos auth login), owner-only, and\nclosed to a service credential itself — no service credential can create,\nrotate or revoke any credential, not even itself, not even an admin one.\nService credentials are console-tracked state with no bucket-direct fallback.\n"}
{"case":"services | help","argv":["services","help"],"exit":1,"stdout":"","stderr":"usage: carlos services <create|ls|rotate|revoke> [flags]\n\n create --role <publish|deploy|instance|operate|service|run|admin> [--app <app>] [--account <sqid|name>] [--json] <name>\n mint a credential a SERVER holds, bound to this account —\n not to you. Unlike your own CLI token, its reach is fixed\n at mint: adding you to another account later does not widen\n it, and it draws on its own rate-limit budgets rather than\n yours.\n THE SECRET IS PRINTED EXACTLY ONCE, HERE. Only its hash is\n stored, so losing this output means rotate, not a re-run.\n --role admin INCLUDES `store grant`, which mints a\n path-scoped IAM user. It is a real handover, not a\n convenience bundle. Prefer the narrowest role that works.\n --app binds it to ONE app, which also means it cannot create\n apps. Omit --app for an account-scoped credential.\n --role run needs --app and --commands, the command\n prefixes it may run: --commands \"import classic,import sync\".\n Words are matched exactly, from the start of the command.\n --json prints one JSON object and nothing else, the bare\n secret in its \"secret\" field: carlos services create\n ... --json name | jq -r .secret\n\n ls [--account <sqid|name>]\n list every LIVE credential the account owns — name, role,\n scope, when it was minted and last rotated and used, and\n who minted it. A revoked credential does not appear; there\n is no history view here.\n\n rotate [--account <sqid|name>] [--json] <name>\n mint a FRESH secret for a credential that already exists,\n printed exactly once. This refuses the credential's NEXT\n call with the old secret. ROTATION IS NOT REVOCATION: it\n does not stop work already in flight, and a credential that\n may be COMPROMISED needs revoke. --json prints one JSON\n object, {\"name\", \"account\", \"secret\"}, and nothing else.\n\n revoke [--account <sqid|name>] <name-or-id>\n the hard stop rotate is not: the credential's next call\n fails, whatever secret it holds. Idempotent — revoking a\n name twice, or one that never existed, answers the same.\n Takes a credential's name, or the listing id `ls` shows\n (the only handle a nameless legacy credential has).\n\n --account <sqid|name> account the credential belongs to (default: your only\n account, or the configured/chosen one) —\n resolved by the console against your own\n memberships.\n --account-id <sqid> account sqid, matched as a sqid ONLY — supersedes\n --account\n --console <origin> which logged-in console to use (only needed with\n several)\n\nEvery verb here is signed-in only (carlos auth login), owner-only, and\nclosed to a service credential itself — no service credential can create,\nrotate or revoke any credential, not even itself, not even an admin one.\nService credentials are console-tracked state with no bucket-direct fallback.\n"}
{"case":"services | zz-unknown","argv":["services","zz-unknown"],"exit":1,"stdout":"","stderr":"usage: carlos services <create|ls|rotate|revoke> [flags]\n\n create --role <publish|deploy|instance|operate|service|run|admin> [--app <app>] [--account <sqid|name>] [--json] <name>\n mint a credential a SERVER holds, bound to this account —\n not to you. Unlike your own CLI token, its reach is fixed\n at mint: adding you to another account later does not widen\n it, and it draws on its own rate-limit budgets rather than\n yours.\n THE SECRET IS PRINTED EXACTLY ONCE, HERE. Only its hash is\n stored, so losing this output means rotate, not a re-run.\n --role admin INCLUDES `store grant`, which mints a\n path-scoped IAM user. It is a real handover, not a\n convenience bundle. Prefer the narrowest role that works.\n --app binds it to ONE app, which also means it cannot create\n apps. Omit --app for an account-scoped credential.\n --role run needs --app and --commands, the command\n prefixes it may run: --commands \"import classic,import sync\".\n Words are matched exactly, from the start of the command.\n --json prints one JSON object and nothing else, the bare\n secret in its \"secret\" field: carlos services create\n ... --json name | jq -r .secret\n\n ls [--account <sqid|name>]\n list every LIVE credential the account owns — name, role,\n scope, when it was minted and last rotated and used, and\n who minted it. A revoked credential does not appear; there\n is no history view here.\n\n rotate [--account <sqid|name>] [--json] <name>\n mint a FRESH secret for a credential that already exists,\n printed exactly once. This refuses the credential's NEXT\n call with the old secret. ROTATION IS NOT REVOCATION: it\n does not stop work already in flight, and a credential that\n may be COMPROMISED needs revoke. --json prints one JSON\n object, {\"name\", \"account\", \"secret\"}, and nothing else.\n\n revoke [--account <sqid|name>] <name-or-id>\n the hard stop rotate is not: the credential's next call\n fails, whatever secret it holds. Idempotent — revoking a\n name twice, or one that never existed, answers the same.\n Takes a credential's name, or the listing id `ls` shows\n (the only handle a nameless legacy credential has).\n\n --account <sqid|name> account the credential belongs to (default: your only\n account, or the configured/chosen one) —\n resolved by the console against your own\n memberships.\n --account-id <sqid> account sqid, matched as a sqid ONLY — supersedes\n --account\n --console <origin> which logged-in console to use (only needed with\n several)\n\nEvery verb here is signed-in only (carlos auth login), owner-only, and\nclosed to a service credential itself — no service credential can create,\nrotate or revoke any credential, not even itself, not even an admin one.\nService credentials are console-tracked state with no bucket-direct fallback.\n"}
-{"case":"ship | --zz-unknown-flag","argv":["ship","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"flag provided but not defined: -zz-unknown-flag\nusage: carlos ship [flags]\nflags:\n --account <string> account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one; ops in direct mode)\n --account-id <string> account sqid, matched as a sqid ONLY — supersedes --account; this is the flag an ambiguity error tells you to use\n --app, -a <string> app name\n --assets <value> a folder your build writes files to, for example /assets/. repeat the flag for up to 8 folders. servers near your visitors may keep copies of the files in them\n --capabilities <string> path to a JSON capability block (internal/caps) to embed in the manifest\n --check run the rootfs image here with Docker or Podman, the way a box would, and ship nothing\n --console <string> console origin to ship through (API mode only; default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n --env <value> with --check, give every process a variable as KEY=VALUE, such as a placeholder secret. repeat it for more than one\n --hibernate let this rootfs app hibernate when idle. rootfs apps are always on unless their first release opts in\n --jit let this rootfs release's processes run a JIT compiler, as Node, Bun, Deno, the JVM and Ruby's YJIT need. without it a box never lets memory be writable and executable at once\n --kind <string> binary | static (default: binary)\n --label <string> one-line human label for this release (\"fixing modals\")\n --mail <string> declare this build's mail transport. the one value is submit: the build sends through carlos's submission socket when CARLOS_MAIL=submit is set\n --message <string> Add a short note describing this change (shown alongside the recorded action).\n --no-prompt Skip the optional change description prompt.\n --notes <string> changelog fragment for this release\n --notes-file <string> file holding the changelog fragment (mutually exclusive with --notes)\n --processes <string> JSON file holding the rootfs release's processes: web, any workers, release and console\n --program-change accept that this release's Go main package differs from the app's previous release (recorded in the manifest)\n --registry <string> registry database (resolves --account) (default: $DIR/data/registry.db)\n --rootfs <string> an OCI image (a layout directory, a docker save archive or a local image name) or a directory, shipped as a rootfs release\n --stateless this release keeps no local database. CARLOS_DB, SQLite, restore and Litestream are off\n --swap <string> hold: this release stops each instance before starting it, for a migration the previous build cannot share the database with\n --target <string> GOOS-GOARCH the binary was built for (binary kind, single file) (default: linux-arm64)\n --version, -v <string> version (git short sha); omit to mint the next iteration under the app's version target\n"}
-{"case":"ship | -h","argv":["ship","-h"],"exit":0,"stdout":"","stderr":"usage: carlos ship [flags]\nflags:\n --account <string> account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one; ops in direct mode)\n --account-id <string> account sqid, matched as a sqid ONLY — supersedes --account; this is the flag an ambiguity error tells you to use\n --app, -a <string> app name\n --assets <value> a folder your build writes files to, for example /assets/. repeat the flag for up to 8 folders. servers near your visitors may keep copies of the files in them\n --capabilities <string> path to a JSON capability block (internal/caps) to embed in the manifest\n --check run the rootfs image here with Docker or Podman, the way a box would, and ship nothing\n --console <string> console origin to ship through (API mode only; default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n --env <value> with --check, give every process a variable as KEY=VALUE, such as a placeholder secret. repeat it for more than one\n --hibernate let this rootfs app hibernate when idle. rootfs apps are always on unless their first release opts in\n --jit let this rootfs release's processes run a JIT compiler, as Node, Bun, Deno, the JVM and Ruby's YJIT need. without it a box never lets memory be writable and executable at once\n --kind <string> binary | static (default: binary)\n --label <string> one-line human label for this release (\"fixing modals\")\n --mail <string> declare this build's mail transport. the one value is submit: the build sends through carlos's submission socket when CARLOS_MAIL=submit is set\n --message <string> Add a short note describing this change (shown alongside the recorded action).\n --no-prompt Skip the optional change description prompt.\n --notes <string> changelog fragment for this release\n --notes-file <string> file holding the changelog fragment (mutually exclusive with --notes)\n --processes <string> JSON file holding the rootfs release's processes: web, any workers, release and console\n --program-change accept that this release's Go main package differs from the app's previous release (recorded in the manifest)\n --registry <string> registry database (resolves --account) (default: $DIR/data/registry.db)\n --rootfs <string> an OCI image (a layout directory, a docker save archive or a local image name) or a directory, shipped as a rootfs release\n --stateless this release keeps no local database. CARLOS_DB, SQLite, restore and Litestream are off\n --swap <string> hold: this release stops each instance before starting it, for a migration the previous build cannot share the database with\n --target <string> GOOS-GOARCH the binary was built for (binary kind, single file) (default: linux-arm64)\n --version, -v <string> version (git short sha); omit to mint the next iteration under the app's version target\n"}
+{"case":"ship | --zz-unknown-flag","argv":["ship","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"flag provided but not defined: -zz-unknown-flag\nusage: carlos ship [flags]\nflags:\n --account <string> account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one; ops in direct mode)\n --account-id <string> account sqid, matched as a sqid ONLY — supersedes --account; this is the flag an ambiguity error tells you to use\n --app, -a <string> app name\n --assets <value> a folder your build writes files to, for example /assets/. repeat the flag for up to 8 folders. servers near your visitors may keep copies of the files in them\n --capabilities <string> path to a JSON capability block (internal/caps) to embed in the manifest\n --check run the rootfs image here with Docker or Podman, the way a box would, and ship nothing\n --console <string> console origin to ship through (API mode only; default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n --env <value> with --check, give every process a variable as KEY=VALUE, such as a placeholder secret. repeat it for more than one\n --from-release <string> a directory written by carlos releases pull. ships its files and settings unchanged\n --hibernate let this rootfs app hibernate when idle. rootfs apps are always on unless their first release opts in\n --jit let this rootfs release's processes run a JIT compiler, as Node, Bun, Deno, the JVM and Ruby's YJIT need. without it a box never lets memory be writable and executable at once\n --kind <string> binary | static (default: binary)\n --label <string> one-line human label for this release (\"fixing modals\")\n --mail <string> declare this build's mail transport. the one value is submit: the build sends through carlos's submission socket when CARLOS_MAIL=submit is set\n --message <string> Add a short note describing this change (shown alongside the recorded action).\n --no-prompt Skip the optional change description prompt.\n --notes <string> changelog fragment for this release\n --notes-file <string> file holding the changelog fragment (mutually exclusive with --notes)\n --processes <string> JSON file holding the rootfs release's processes: web, any workers, release and console\n --program-change accept that this release's Go main package differs from the app's previous release (recorded in the manifest)\n --registry <string> registry database (resolves --account) (default: $DIR/data/registry.db)\n --rootfs <string> an OCI image (a layout directory, a docker save archive or a local image name) or a directory, shipped as a rootfs release\n --stateless this release keeps no local database. CARLOS_DB, SQLite, restore and Litestream are off\n --swap <string> hold: this release stops each instance before starting it, for a migration the previous build cannot share the database with\n --target <string> GOOS-GOARCH the binary was built for (binary kind, single file) (default: linux-arm64)\n --version, -v <string> version (git short sha); omit to mint the next iteration under the app's version target\n"}
+{"case":"ship | -h","argv":["ship","-h"],"exit":0,"stdout":"","stderr":"usage: carlos ship [flags]\nflags:\n --account <string> account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one; ops in direct mode)\n --account-id <string> account sqid, matched as a sqid ONLY — supersedes --account; this is the flag an ambiguity error tells you to use\n --app, -a <string> app name\n --assets <value> a folder your build writes files to, for example /assets/. repeat the flag for up to 8 folders. servers near your visitors may keep copies of the files in them\n --capabilities <string> path to a JSON capability block (internal/caps) to embed in the manifest\n --check run the rootfs image here with Docker or Podman, the way a box would, and ship nothing\n --console <string> console origin to ship through (API mode only; default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n --env <value> with --check, give every process a variable as KEY=VALUE, such as a placeholder secret. repeat it for more than one\n --from-release <string> a directory written by carlos releases pull. ships its files and settings unchanged\n --hibernate let this rootfs app hibernate when idle. rootfs apps are always on unless their first release opts in\n --jit let this rootfs release's processes run a JIT compiler, as Node, Bun, Deno, the JVM and Ruby's YJIT need. without it a box never lets memory be writable and executable at once\n --kind <string> binary | static (default: binary)\n --label <string> one-line human label for this release (\"fixing modals\")\n --mail <string> declare this build's mail transport. the one value is submit: the build sends through carlos's submission socket when CARLOS_MAIL=submit is set\n --message <string> Add a short note describing this change (shown alongside the recorded action).\n --no-prompt Skip the optional change description prompt.\n --notes <string> changelog fragment for this release\n --notes-file <string> file holding the changelog fragment (mutually exclusive with --notes)\n --processes <string> JSON file holding the rootfs release's processes: web, any workers, release and console\n --program-change accept that this release's Go main package differs from the app's previous release (recorded in the manifest)\n --registry <string> registry database (resolves --account) (default: $DIR/data/registry.db)\n --rootfs <string> an OCI image (a layout directory, a docker save archive or a local image name) or a directory, shipped as a rootfs release\n --stateless this release keeps no local database. CARLOS_DB, SQLite, restore and Litestream are off\n --swap <string> hold: this release stops each instance before starting it, for a migration the previous build cannot share the database with\n --target <string> GOOS-GOARCH the binary was built for (binary kind, single file) (default: linux-arm64)\n --version, -v <string> version (git short sha); omit to mint the next iteration under the app's version target\n"}
{"case":"sidecars create | --zz-unknown-flag","argv":["sidecars","create","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"flag provided but not defined: -zz-unknown-flag\nUsage of sidecars create:\n -account string\n \taccount (sqid or name) the app belongs to (default: your only account, or the configured/chosen one)\n -account-id string\n \taccount sqid, matched as a sqid ONLY — supersedes -account\n -app string\n \tapp the sidecar belongs to\n -channel string\n \trelease channel the sidecar follows (default: the manifest's, then stable)\n -console string\n \tconsole to create through (default: the only logged-in one)\n -d value\n \talias for --destination\n -destination name\n \tuse the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n -region string\n \tregion code for the record (subject to the manifest's allow-list, or the app's own placement)\n"}
{"case":"sidecars create | -h","argv":["sidecars","create","-h"],"exit":0,"stdout":"","stderr":"Usage of sidecars create:\n -account string\n \taccount (sqid or name) the app belongs to (default: your only account, or the configured/chosen one)\n -account-id string\n \taccount sqid, matched as a sqid ONLY — supersedes -account\n -app string\n \tapp the sidecar belongs to\n -channel string\n \trelease channel the sidecar follows (default: the manifest's, then stable)\n -console string\n \tconsole to create through (default: the only logged-in one)\n -d value\n \talias for --destination\n -destination name\n \tuse the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n -region string\n \tregion code for the record (subject to the manifest's allow-list, or the app's own placement)\n"}
{"case":"sidecars enable | --zz-unknown-flag","argv":["sidecars","enable","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"flag provided but not defined: -zz-unknown-flag\nUsage of sidecars enable:\n -account string\n \taccount (sqid or name) the app belongs to (default: your only account, or the configured/chosen one; ops in direct mode)\n -account-id string\n \taccount sqid, matched as a sqid ONLY — supersedes --account; this is the flag an ambiguity error tells you to use\n -app string\n \tapp whose sidecars this enables\n -args string\n \targv the activator execs the app's own binary with, whitespace-split (strings.Fields)\n -channel string\n \trelease channel stamped into every record at create\n -console string\n \tconsole to enable through (signed-in mode only; default: the only logged-in one)\n -d value\n \talias for --destination\n -destination name\n \tuse the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n -idle string\n \tidle timeout before a hibernating sidecar sleeps (default 5m; Go duration)\n -max-run string\n \tmax run duration before the sweeper stops a sidecar (default 1h; Go duration)\n -no-hibernate\n \tthis app's sidecars never hibernate (default: they do)\n -placement string\n \t\"any\" (default) or \"no-inbound\"\n -pool string\n \tpool stamped into every record at create (store mode only)\n -regions string\n \tcomma-separated region allow-list, plain region codes only (store mode only); empty = any shape-valid region — see carlos apps place for fleet placement\n -registry string\n \tregistry database (resolves --account) (default \"$DIR/data/registry.db\")\n"}