oficina / equipo Public

push: review fixes (Fable 5.2 on 2ea81007) and the CARLOS verb's outcomes

One APNs token belongs to one credential: Register and RegisterActivity
take it from any other (its registration, waiting rows, activity tokens).
Setting a card aside runs no push rule, and once-only alerts are decided
once per person in push_once, outside the pruned outbox (0095 marks
cards already open). An ended task's activity token is taken while its
end waits, which then goes at once; an update with no token is never
written and the activity hears the whole state when its token arrives.
Tokens and payloads are sealed at rest with the instance key, so neither
is ever SQL text, and transport errors are scrubbed. Row IDs are UUIDs
(apns-id). Registration sets the badge and remembers open tasks, so
their outcomes push. Only revocation or removal forgets a device; an
expired credential drops the row, a failed lookup retries.

Smaller: a 4 KB guard in Render, Enqueue and the sender; push work runs
in a savepoint and never fails the engine's write; the needs-you Live
Activity update is urgent but silent (the card alert is the one sound);
room is made only when a start is written; EQUIPO_ALLOW_LOGGED_PUSH with
CARLOS_PUSH refuses boot; a send has a 30 s deadline; logged push logs
nothing derived from a token.

CARLOS (design/platform-push-submission §4, awaiting Paul): the request
and answer are CarlosRequestOf and CarlosResult behind the FromCarlos
seam (CARLOS_PUSH=submit still refuses boot); Judge acts on every
outcome: platform holds wait Retry-After without an attempt and end the
pass, refusals fail, Apple 429 holds the device, Apple 5xx waits 15
minutes, gone reasons forget the token unless the registration is newer
than a 410's timestamp, expired rows drop unsent.

Copy: copyPushBoth and the revised push section of the API doc reviewed
by Luna; push.activity.needs_you removed (no longer used).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 18eee15fd0ec9c2642f186019d4d33cdbd498c41 parent 2ea8100
28 files changed, +1,701 −311
  • .rastrillo/budgets.txt +3 −3
  • docs/api/equipo-v1.md +3 −3
  • docs/api/equipo-v1.openapi.json +2 −2
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +2 −2
  • internal/equipo/chat/projects.go +10 −3
  • internal/equipo/chat/push.go +271 −101
  • internal/equipo/chat/push_test.go +242 −10
  • internal/equipo/chat/roster.go +2 −1
  • internal/equipo/chat_wiring.go +11 −4
  • internal/equipo/copy.go +8 −8
  • internal/equipo/mailer.go +7 −1
  • internal/equipo/migrations/0095_push.sql +7 −2
  • internal/equipo/migrations/schema.sql +1 −0
  • internal/equipo/migrations_test.go +46 −0
  • internal/equipo/personapi/devices.go +37 −0
  • internal/equipo/push/outcome_test.go +388 −0
  • internal/equipo/push/payload.go +3 −0
  • internal/equipo/push/push.go +93 −18
  • internal/equipo/push/rules.go +22 −9
  • internal/equipo/push/rules_test.go +5 −4
  • internal/equipo/push/sender.go +175 −39
  • internal/equipo/push/sender_test.go +93 −38
  • internal/equipo/push/store.go +142 −34
  • internal/equipo/push/testdata/activity-needs.json +0 −5
  • internal/equipo/push/transport.go +96 −19
  • internal/equipo/push_config_test.go +12 −0
  • internal/plan3test/plan3_release_test.go +1 −1
  • internal/plan3test/push_device_test.go +19 −4

CI passed — run details

CI log
=== prepare ===
ci-box: machine: aarch64, 32 CPUs, 62 GiB memory, kernel 7.0.0-1017-aws
ci-box: python 3.12.3; Docker version 29.1.3, build 29.1.3-0ubuntu3~24.04.2
ci-box: user namespaces allowed: 233151
ci-box: cgroup: cgroup2fs
ci-box: disk /home/ci/work/repos/oficina__equipo/wt/push__server: Type  Size Avail | ext4   96G   86G
ci-box: disk /home/ci/.cache/equipo-ci-box: Type  Size Avail | ext4   96G   86G
ci-box: bwrap: fetched and verified in 0.3s
ci-box: claude: fetched and verified in 1.6s
ci-box: codex: fetched and verified in 3.4s
ci-box: codex-code-mode-host: fetched and verified in 1.4s
ci-box: libwrap: fetched and verified in 0.4s
ci-box: socat: fetched and verified in 0.3s
npm warn deprecated node-domexception@1.0.0: Use your platform's native DOMException instead
ci-box: image pulled in 9.9s
ci-box: pi: installed and verified in 7.4s
ci-box: opencode: installed and verified in 1.9s
ci-box: chromium 156.0.8078.79-1~deb13u1: 76 packages fetched, verified and unpacked in 8.7s
ci-box: clone deepened in 3.0s
ci-box: file times set from content: 2749 files, 176 directories
ci-box: ready in 16.2s
=== copy ===
EQUIPO_RELEASE_COPY_CHECK=1 CGO_ENABLED=0 go test ./internal/equipotest -run '^TestReleaseCopyReviewed$' -count=1
ok  	amadan.net/oficina/equipo/internal/equipotest	0.242s
=== compile ===
go build ./...
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py compile
+ go build -tags testbuild ./...
  3.7s
+ go list -export -test -tags testbuild -f  ./...
  3.8s
+ go list -export -test -tags browser,testbuild -f  ./internal/equipo ./internal/headless ./internal/idtest ./internal/plan3test ./internal/thintest
  2.9s
go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 -version
staticcheck 2026.1 (v0.7.0)
go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 -version
Go: go1.26.11
Scanner: govulncheck@v1.8.0
DB: https://vuln.go.dev
DB updated: 2026-11-11 02:51:11 +0000 UTC

go run github.com/zricethezav/gitleaks/v8@v8.30.1 version
version is set by build process
=== check ===
--- shard 0 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-work: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestHeadless$/^4c_rebase$|^TestHeadless$/^4b_ask$|^TestHeadless$/^4c_checks_card$|^TestHeadless$/^4_step_crash$' ./internal/headless

receipt: test step 1m27.047s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m25.568s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m25.57s amadan.net/oficina/equipo/internal/headless TestHeadless
machine: 32 CPUs, load 54.90, cpu waiting 35.43%, memory waiting 0.00%, io waiting 0.52%
--- shard 1 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-review: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestHeadless$/^4_review$|^TestHeadless$/^2b_access$|^TestHeadless$/^runner_crash$|^TestHeadless$/^2b_first_message$|^TestHeadless$/^4_checks_honest$|^TestHeadless$/^7_stream_resume$|^TestHeadless$/^2b_notebook$|^TestHeadless$/^2b_move_in$|^TestHeadless$/^2b_desk_failure$|^TestHeadless$/^cancel$' ./internal/headless

receipt: test step 1m29.767s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m28.206s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m28.21s amadan.net/oficina/equipo/internal/headless TestHeadless
machine: 32 CPUs, load 52.75, cpu waiting 35.39%, memory waiting 0.00%, io waiting 0.50%
--- shard 2 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-connections: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestHeadlessConnections$|^TestHeadlessTokenPasteEndToEnd$|^TestHeadlessTokenConnection$' ./internal/headless

receipt: test step 1m31.388s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m29.667s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m18.51s amadan.net/oficina/equipo/internal/headless TestHeadlessConnections
receipt: slow test 6.12s amadan.net/oficina/equipo/internal/headless TestHeadlessTokenPasteEndToEnd
receipt: slow test 5.04s amadan.net/oficina/equipo/internal/headless TestHeadlessTokenConnection
machine: 32 CPUs, load 52.75, cpu waiting 35.14%, memory waiting 0.00%, io waiting 0.48%
--- shard 3 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-mac: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestMacWorker$|^TestHeadlessAttachments$|^TestHeadlessPrewarm$|^TestHeadless$/^1_first_token$|^TestHeadless$/^6_quick_messages$|^TestHeadless$/^8_instance_restart$|^TestHeadless$/^3_runner_offline$' ./internal/headless

receipt: test step 1m26.378s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m24.872s amadan.net/oficina/equipo/internal/headless
receipt: slow test 43.37s amadan.net/oficina/equipo/internal/headless TestMacWorker
receipt: slow test 21.2s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 10.69s amadan.net/oficina/equipo/internal/headless TestHeadlessAttachments
receipt: slow test 9.61s amadan.net/oficina/equipo/internal/headless TestHeadlessPrewarm
machine: 32 CPUs, load 54.90, cpu waiting 35.43%, memory waiting 0.00%, io waiting 0.52%
--- shard 4 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-guards: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestHeadlessCopyRotation$|^TestHeadlessPolicyGuards$|^TestHeadlessRunnerKillLeavesNoCopies$|^TestHeadlessNewHouseRuleStartsFresh$|^TestHeadless$/^3_engineering$|^TestHeadless$/^3_step_cancel$|^TestHeadless$/^3_step_contained$|^TestHeadless$/^3_empty_repo$|^TestHeadless$/^3_empty_engineering$|^TestHeadless$/^3_empty_merge$|^TestHeadless$/^3_empty_merge_rebuilt$|^TestHeadless$/^3_empty_fix_round$' ./internal/headless

receipt: test step 1m43.469s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m41.603s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m5.16s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 11.54s amadan.net/oficina/equipo/internal/headless TestHeadlessRunnerKillLeavesNoCopies
receipt: slow test 10.22s amadan.net/oficina/equipo/internal/headless TestHeadlessCopyRotation
receipt: slow test 8.78s amadan.net/oficina/equipo/internal/headless TestHeadlessPolicyGuards
receipt: slow test 5.9s amadan.net/oficina/equipo/internal/headless TestHeadlessNewHouseRuleStartsFresh
machine: 32 CPUs, load 47.77, cpu waiting 30.57%, memory waiting 0.00%, io waiting 0.39%
--- shard 5 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-rest: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -skip '^TestHeadless$/^4c_rebase$|^TestHeadless$/^4b_ask$|^TestHeadless$/^4c_checks_card$|^TestHeadless$/^4_step_crash$|^TestHeadless$/^4_review$|^TestHeadless$/^2b_access$|^TestHeadless$/^runner_crash$|^TestHeadless$/^2b_first_message$|^TestHeadless$/^4_checks_honest$|^TestHeadless$/^7_stream_resume$|^TestHeadless$/^2b_notebook$|^TestHeadless$/^2b_move_in$|^TestHeadless$/^2b_desk_failure$|^TestHeadless$/^cancel$|^TestHeadlessConnections$|^TestHeadlessTokenPasteEndToEnd$|^TestHeadlessTokenConnection$|^TestMacWorker$|^TestHeadlessAttachments$|^TestHeadlessPrewarm$|^TestHeadless$/^1_first_token$|^TestHeadless$/^6_quick_messages$|^TestHeadless$/^8_instance_restart$|^TestHeadless$/^3_runner_offline$|^TestHeadlessCopyRotation$|^TestHeadlessPolicyGuards$|^TestHeadlessRunnerKillLeavesNoCopies$|^TestHeadlessNewHouseRuleStartsFresh$|^TestHeadless$/^3_engineering$|^TestHeadless$/^3_step_cancel$|^TestHeadless$/^3_step_contained$|^TestHeadless$/^3_empty_repo$|^TestHeadless$/^3_empty_engineering$|^TestHeadless$/^3_empty_merge$|^TestHeadless$/^3_empty_merge_rebuilt$|^TestHeadless$/^3_empty_fix_round$' ./internal/headless

receipt: test step 3m14.29s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 3m12.628s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m51.83s amadan.net/oficina/equipo/internal/headless TestHeadlessAssistant
receipt: slow test 23.56s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 11.26s amadan.net/oficina/equipo/internal/headless TestHeadlessResearchHandoff
receipt: slow test 7.97s amadan.net/oficina/equipo/internal/headless TestHeadlessClaudeSignIn
receipt: slow test 7.28s amadan.net/oficina/equipo/internal/headless TestHeadlessTurnBatching
machine: 32 CPUs, load 13.41, cpu waiting 6.92%, memory waiting 0.00%, io waiting 0.08%
--- shard 6 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane thintest: ./internal/thintest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^Test([^C]|C[^o]|Co[^n]|Con[^t])|^TestContract(Assistant|Outcome|Team|Handoff|HostAllowlist|HostIsPerPerson|Look|Use[A-Z]|RemoteCall|LanesRunAtOnce|NoMergeQuestionWhenGateMerges|PreviewHeldUntilPublishAnswer|PreviewNotHeldBelow19|PublishNeedsOwnerAnswer)' ./internal/thintest

receipt: test step 1m59.105s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m57.588s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 7.85s amadan.net/oficina/equipo/internal/thintest TestContractTeamJobSettledStates
receipt: slow test 6.71s amadan.net/oficina/equipo/internal/thintest TestExplorePreviewsOff
receipt: slow test 3.74s amadan.net/oficina/equipo/internal/thintest TestContractPreviewHeldUntilPublishAnswer
receipt: slow test 3.44s amadan.net/oficina/equipo/internal/thintest TestContractTeamNudgePersonNeeds
receipt: slow test 2.49s amadan.net/oficina/equipo/internal/thintest TestResearchDoneFallsBack
machine: 32 CPUs, load 35.42, cpu waiting 23.60%, memory waiting 0.00%, io waiting 0.30%
--- shard 7 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane thintest-contract: ./internal/thintest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -skip '^Test([^C]|C[^o]|Co[^n]|Con[^t])|^TestContract(Assistant|Outcome|Team|Handoff|HostAllowlist|HostIsPerPerson|Look|Use[A-Z]|RemoteCall|LanesRunAtOnce|NoMergeQuestionWhenGateMerges|PreviewHeldUntilPublishAnswer|PreviewNotHeldBelow19|PublishNeedsOwnerAnswer)' ./internal/thintest

receipt: test step 1m22.135s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m20.514s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 9.14s amadan.net/oficina/equipo/internal/thintest TestContractPreviewNotScheduled
receipt: slow test 4.99s amadan.net/oficina/equipo/internal/thintest TestContractPublishNotOffered
receipt: slow test 4.34s amadan.net/oficina/equipo/internal/thintest TestContractMacRecheckMergeAuthority
receipt: slow test 2.34s amadan.net/oficina/equipo/internal/thintest TestContractPublishNotNow
receipt: slow test 2.33s amadan.net/oficina/equipo/internal/thintest TestContractPublishNameTaken
machine: 32 CPUs, load 54.37, cpu waiting 35.06%, memory waiting 0.00%, io waiting 0.57%
--- shard 8 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane runner-thin: ./internal/runner/thin
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m ./internal/runner/thin
cache miss: amadan.net/oficina/equipo/internal/runner/thin: its inputs changed
budget note: internal/runner/thin took 4m34.906s, over the 45s its record on line 44 allows; reported only, timing fails on CI

receipt: test step 4m47.693s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 4m34.906s amadan.net/oficina/equipo/internal/runner/thin
receipt: slow test 36.99s amadan.net/oficina/equipo/internal/runner/thin TestModelsEngineeringProbesThenRunsTheStrongest
receipt: slow test 36.98s amadan.net/oficina/equipo/internal/runner/thin TestModelsProbeAnsweredByAnotherModel
receipt: slow test 36.79s amadan.net/oficina/equipo/internal/runner/thin TestModelsUnhealthyRetriedOnDemand
receipt: slow test 18.47s amadan.net/oficina/equipo/internal/runner/thin TestModelsProbeRunsInsideTheAdmission
receipt: slow test 6.73s amadan.net/oficina/equipo/internal/runner/thin TestOpenCodeStepsRealOpenCode
machine: 32 CPUs, load 3.60, cpu waiting 1.44%, memory waiting 0.00%, io waiting 0.01%
--- shard 9 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane runner-bug: ./internal/runner
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestDirectBugWorkflow$|^TestEnrolKeepsTheRole$' ./internal/runner
cache miss: amadan.net/oficina/equipo/internal/runner: its inputs changed

receipt: test step 49.04s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 47.878s amadan.net/oficina/equipo/internal/runner
receipt: slow test 27.85s amadan.net/oficina/equipo/internal/runner TestDirectBugWorkflow
receipt: slow test 20.03s amadan.net/oficina/equipo/internal/runner TestEnrolKeepsTheRole
machine: 32 CPUs, load 45.74, cpu waiting 29.43%, memory waiting 0.00%, io waiting 0.98%
--- shard 10 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane runner-plans: ./internal/runner
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestPlanWorkflowCandidateOrder$|^TestPlanWorkflowFeature$|^TestCoordinatorRecoveryCallRefusalKeepsServing$|^TestCoordinatorRefusalMatrix$' ./internal/runner
cache miss: amadan.net/oficina/equipo/internal/runner: its inputs changed

receipt: test step 57.993s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 55.994s amadan.net/oficina/equipo/internal/runner
receipt: slow test 45.93s amadan.net/oficina/equipo/internal/runner TestPlanWorkflowCandidateOrder
receipt: slow test 40.33s amadan.net/oficina/equipo/internal/runner TestPlanWorkflowFeature
receipt: slow test 8.4s amadan.net/oficina/equipo/internal/runner TestCoordinatorRecoveryCallRefusalKeepsServing
receipt: slow test 1.64s amadan.net/oficina/equipo/internal/runner TestCoordinatorRefusalMatrix
machine: 32 CPUs, load 51.26, cpu waiting 32.96%, memory waiting 0.00%, io waiting 0.86%
--- shard 11 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane runner-rest: ./internal/runner
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -skip '^TestDirectBugWorkflow$|^TestEnrolKeepsTheRole$|^TestPlanWorkflowCandidateOrder$|^TestPlanWorkflowFeature$|^TestCoordinatorRecoveryCallRefusalKeepsServing$|^TestCoordinatorRefusalMatrix$' ./internal/runner
cache miss: amadan.net/oficina/equipo/internal/runner: its inputs changed

receipt: test step 35.445s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 34.506s amadan.net/oficina/equipo/internal/runner
receipt: slow test 5.12s amadan.net/oficina/equipo/internal/runner TestDirectFaultIsolation
receipt: slow test 3.22s amadan.net/oficina/equipo/internal/runner TestClaimRefusalsBackOff
receipt: slow test 3.13s amadan.net/oficina/equipo/internal/runner TestCoordinatorRecoveryRefusedKeepsServing
receipt: slow test 2.67s amadan.net/oficina/equipo/internal/runner TestToolVerbUnderFakeHarness
receipt: slow test 1.61s amadan.net/oficina/equipo/internal/runner TestReportPostsRetryExactRequest
machine: 32 CPUs, load 28.97, cpu waiting 19.23%, memory waiting 0.00%, io waiting 1.24%
--- shard 12 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: equipotest-a started 30s late; cpu waiting 36.4%, load 21.30
test lane equipotest-a: ./internal/equipotest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^Test[A-D]|^TestQ' ./internal/equipotest

receipt: test step 1m5.624s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m3.654s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 26.62s amadan.net/oficina/equipo/internal/equipotest TestAuthorityCoreIntegration
receipt: slow test 26.52s amadan.net/oficina/equipo/internal/equipotest TestBootstrapNamesOwnersSetting
receipt: slow test 24.51s amadan.net/oficina/equipo/internal/equipotest TestAccountLabelMigration
receipt: slow test 22s amadan.net/oficina/equipo/internal/equipotest TestBudgetConfigurationFailuresAreAtomic
receipt: slow test 21.93s amadan.net/oficina/equipo/internal/equipotest TestAuthorityGrantReferences
machine: 32 CPUs, load 50.45, cpu waiting 34.29%, memory waiting 0.00%, io waiting 0.45%
--- shard 13 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: equipotest-e started 30s late; cpu waiting 36.4%, load 21.30
test lane equipotest-e: ./internal/equipotest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^Test[E-P]' ./internal/equipotest

receipt: test step 1m14.632s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m12.535s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 19.06s amadan.net/oficina/equipo/internal/equipotest TestProjectsReopen
receipt: slow test 18.95s amadan.net/oficina/equipo/internal/equipotest TestProjectOwnersAreMembers
receipt: slow test 18.93s amadan.net/oficina/equipo/internal/equipotest TestProjectBindingUniqueness
receipt: slow test 18.92s amadan.net/oficina/equipo/internal/equipotest TestProjectsFailuresRollBack
receipt: slow test 18.86s amadan.net/oficina/equipo/internal/equipotest TestProjectRejectsUnsafeBinding
machine: 32 CPUs, load 44.66, cpu waiting 29.60%, memory waiting 0.00%, io waiting 0.38%
--- shard 14 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: equipotest-r started 30s late; cpu waiting 36.4%, load 21.30
test lane equipotest-r: ./internal/equipotest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestR' ./internal/equipotest

receipt: test step 1m11.763s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m6.958s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 15.53s amadan.net/oficina/equipo/internal/equipotest TestReleaseStampContract
receipt: slow test 12.96s amadan.net/oficina/equipo/internal/equipotest TestRosterChangesAffectExistingSession
receipt: slow test 10.04s amadan.net/oficina/equipo/internal/equipotest TestRosterRemovalWhileAssigned
receipt: slow test 10s amadan.net/oficina/equipo/internal/equipotest TestRosterRemovalRollsBack
receipt: slow test 6.93s amadan.net/oficina/equipo/internal/equipotest TestRosterAuditFailureRollsBack
machine: 32 CPUs, load 47.77, cpu waiting 31.54%, memory waiting 0.00%, io waiting 0.41%
--- shard 15 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: equipotest-rest started 30s late; cpu waiting 36.4%, load 21.30
test lane equipotest-rest: ./internal/equipotest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -skip '^Test[A-D]|^TestQ|^Test[E-P]|^TestR' ./internal/equipotest

receipt: test step 1m7.221s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m5.268s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 24.21s amadan.net/oficina/equipo/internal/equipotest TestSigninNoProof
receipt: slow test 23.7s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedExistingTeam
receipt: slow test 23.67s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedRollback
receipt: slow test 22.02s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedOnce
receipt: slow test 21.93s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsUpgrade
machine: 32 CPUs, load 50.45, cpu waiting 33.50%, memory waiting 0.00%, io waiting 0.44%
--- shard 16 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: plan3test started 30s late; cpu waiting 36.4%, load 21.30
test lane plan3test: ./internal/plan3test
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m ./internal/plan3test

receipt: test step 51.493s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 49.675s amadan.net/oficina/equipo/internal/plan3test
receipt: slow test 3.56s amadan.net/oficina/equipo/internal/plan3test TestPlan3Upgrade
receipt: slow test 3.48s amadan.net/oficina/equipo/internal/plan3test TestCoordinatorAcceptance3B
receipt: slow test 1.56s amadan.net/oficina/equipo/internal/plan3test TestConversationQuestionRace
receipt: slow test 1.34s amadan.net/oficina/equipo/internal/plan3test TestCoordinatorAcceptance3A
receipt: slow test 1.24s amadan.net/oficina/equipo/internal/plan3test TestCoordinatorDefinitiveRefusalReleasesQueue
machine: 32 CPUs, load 54.37, cpu waiting 35.06%, memory waiting 0.00%, io waiting 0.57%
--- shard 17 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: rest started 30s late; cpu waiting 36.4%, load 21.30
test lane rest: ./cmd/equipo ./cmd/equipo-runner ./cmd/equipo-tool-proxy ./internal/advice ./internal/attach ./internal/attach/attachtest ./internal/chatmarkdown ./internal/chatsend ./internal/chatstream ./internal/coordinator ./internal/coordinatorcontract ./internal/coordinatormail ./internal/copydesk ./internal/equipo ./internal/equipo/activity ./internal/equipo/assist ./internal/equipo/chat ./internal/equipo/conversation ./internal/equipo/conversation/chatstate ./internal/equipo/housekeeping ./internal/equipo/icons ./internal/equipo/identity ./internal/equipo/kernel ./internal/equipo/library ./internal/equipo/mergegate ./internal/equipo/notifications ./internal/equipo/oficina ./internal/equipo/oficina/oficinatest ./internal/equipo/oficinaid ./internal/equipo/ownermode ./internal/equipo/personapi ./internal/equipo/planning ./internal/equipo/push ./internal/equipo/setup ./internal/equipo/team ./internal/equipo/teamcontract ./internal/equipo/triage ./internal/fakeclaude ./internal/fakecodex ./internal/fakeopencode ./internal/fakepi ./internal/idtest ./internal/ownermodetest ./internal/release ./internal/runner/checks ./internal/runner/connect ./internal/runner/containment ./internal/runner/containment/sysunix ./internal/runner/egress ./internal/runner/forge ./internal/runner/forge/forgetest ./internal/runner/heartbeat ./internal/runner/mac ./internal/runner/mcpresource ./internal/runner/metered ./internal/runner/planflow ./internal/runner/provider ./internal/runner/provider/claude ./internal/runner/provider/codex ./internal/runner/provider/gotoolchain ./internal/runner/provider/opencode ./internal/runner/provider/pi ./internal/runner/setup ./internal/runner/transporttest ./internal/runner/webread ./internal/runner/workspace ./internal/runnerproto ./internal/schedule ./internal/sealbox ./internal/specialist ./internal/stagingtest ./internal/taskplan ./internal/testci ./internal/toolproxy ./internal/websource ./internal/wire ./internal/wire/wireschema ./internal/wire/wiretest ./tools/drive
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m ./cmd/equipo ./cmd/equipo-runner ./cmd/equipo-tool-proxy ./internal/advice ./internal/attach ./internal/attach/attachtest ./internal/chatmarkdown ./internal/chatsend ./internal/chatstream ./internal/coordinator ./internal/coordinatorcontract ./internal/coordinatormail ./internal/copydesk ./internal/equipo ./internal/equipo/activity ./internal/equipo/assist ./internal/equipo/chat ./internal/equipo/conversation ./internal/equipo/conversation/chatstate ./internal/equipo/housekeeping ./internal/equipo/icons ./internal/equipo/identity ./internal/equipo/kernel ./internal/equipo/library ./internal/equipo/mergegate ./internal/equipo/notifications ./internal/equipo/oficina ./internal/equipo/oficina/oficinatest ./internal/equipo/oficinaid ./internal/equipo/ownermode ./internal/equipo/personapi ./internal/equipo/planning ./internal/equipo/push ./internal/equipo/setup ./internal/equipo/team ./internal/equipo/teamcontract ./internal/equipo/triage ./internal/fakeclaude ./internal/fakecodex ./internal/fakeopencode ./internal/fakepi ./internal/idtest ./internal/ownermodetest ./internal/release ./internal/runner/checks ./internal/runner/connect ./internal/runner/containment ./internal/runner/containment/sysunix ./internal/runner/egress ./internal/runner/forge ./internal/runner/forge/forgetest ./internal/runner/heartbeat ./internal/runner/mac ./internal/runner/mcpresource ./internal/runner/metered ./internal/runner/planflow ./internal/runner/provider ./internal/runner/provider/claude ./internal/runner/provider/codex ./internal/runner/provider/gotoolchain ./internal/runner/provider/opencode ./internal/runner/provider/pi ./internal/runner/setup ./internal/runner/transporttest ./internal/runner/webread ./internal/runner/workspace ./internal/runnerproto ./internal/schedule ./internal/sealbox ./internal/specialist ./internal/stagingtest ./internal/taskplan ./internal/testci ./internal/toolproxy ./internal/websource ./internal/wire ./internal/wire/wireschema ./internal/wire/wiretest ./tools/drive
cache miss: amadan.net/oficina/equipo/internal/copydesk: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/provider/opencode: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/equipo/team: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/webread: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/forge: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runnerproto: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/workspace: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/wire/wireschema: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/testci: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/checks: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/containment: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/provider/pi: its inputs changed
--- FAIL amadan.net/oficina/equipo/internal/runner/provider/claude TestClaudeFailureDiagnostics
=== RUN   TestClaudeFailureDiagnostics
--- FAIL: TestClaudeFailureDiagnostics (0.65s)

--- FAIL amadan.net/oficina/equipo/internal/runner/provider/claude TestClaudeFailureDiagnostics/partial
=== RUN   TestClaudeFailureDiagnostics/partial
    live_turn_test.go:66: opaque failure: {"Reason":"protocol_rejected","LastFrame":"malformed","Stderr":"empty","ExitCode":null,"Signal":null,"EgressDenials":null}
--- FAIL: TestClaudeFailureDiagnostics/partial (0.13s)

--- FAIL amadan.net/oficina/equipo/internal/runner/provider/claude (package output)
FAIL
rastrillo-budget/v1 ran 23.856s
FAIL	amadan.net/oficina/equipo/internal/runner/provider/claude	24.542s

budget note: internal/equipo took 20.98s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/equipo/chat took 11.527s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/idtest took 41.148s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/release took 22.788s, over the 10s the default allows (measured on the run this cached result came from); reported only, timing fails on CI
budget note: internal/runner/containment took 47.673s, over the 15s its record on line 40 allows; reported only, timing fails on CI

receipt: test step 2m29.803s against a 60s target (the gate's other steps are not in this figure)
receipt: 21 packages ran, 39 cached, 18 without tests, 1 failed
receipt: slow package 1m3.412s amadan.net/oficina/equipo/internal/runner/provider/opencode
receipt: slow package 51.745s amadan.net/oficina/equipo/internal/runner/provider/pi
receipt: slow package 48.985s amadan.net/oficina/equipo/internal/runner/checks
receipt: slow package 47.673s amadan.net/oficina/equipo/internal/runner/containment
receipt: slow package 41.148s amadan.net/oficina/equipo/internal/idtest
receipt: slow test 25.03s amadan.net/oficina/equipo/internal/runner/provider/opencode TestOpenCodeAcceptanceHostileRepository
receipt: slow test 20.59s amadan.net/oficina/equipo/internal/runner/containment TestEngineeringOfflineGo
receipt: slow test 15.34s amadan.net/oficina/equipo/cmd/equipo-runner TestReleaseRunnerHasNoFakeWorker
receipt: slow test 12.19s amadan.net/oficina/equipo/internal/idtest TestIDCallbackGuardAndPendingNonce
receipt: slow test 10.47s amadan.net/oficina/equipo/internal/runner/containment TestEngineeringMissingModuleCache
rastrillo: budget test: go test failed
exit status 1
+ go test -tags testbuild -timeout 15m -v -run '^TestClaudeFailureDiagnostics$/^partial$' -count=1 ./internal/runner/provider/claude   (retry, once)
##############################################################################
FLAKE ./internal/runner/provider/claude:TestClaudeFailureDiagnostics/partial rest 18eee15fd0ec9c2642f186019d4d33cdbd498c41 0.13s 15.48
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 15.48, cpu waiting 8.45%, memory waiting 0.00%, io waiting 0.10%
--- shard 18 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-headless-chat: ./internal/headless
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^TestBrowserChat$|^TestBrowserChatSendStaysOnPage$|^TestBrowserComposer$|^TestBrowserComposerReconcile$|^TestBrowserComposerFocus$|^TestBrowserComposerDock$|^TestBrowserDraftStreamsFormatted$|^TestBrowserDraftIsTheMessage$' ./internal/headless
rastrillo: budget test: go test failed
--- FAIL amadan.net/oficina/equipo/internal/headless TestBrowserChat
=== RUN   TestBrowserChat
time=2026-11-20T08:36:44.424Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-20T08:36:44.425Z level=INFO msg="startup phase done" phase=state_lock took=225µs
time=2026-11-20T08:36:44.425Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-20T08:36:44.425Z level=INFO msg="startup phase done" phase=claim_roots took=166µs
time=2026-11-20T08:36:44.425Z level=INFO msg="startup phase" phase=sweep
time=2026-11-20T08:36:44.466Z level=INFO msg="startup phase done" phase=sweep took=40.894ms
time=2026-11-20T08:36:44.469Z level=INFO msg="startup phase" phase=credentials
time=2026-11-20T08:36:44.469Z level=INFO msg="startup phase done" phase=credentials took=220µs
time=2026-11-20T08:36:44.469Z level=INFO msg="startup phase" phase=open_state
time=2026-11-20T08:36:44.525Z level=INFO msg="startup phase done" phase=open_state took=56.031ms
time=2026-11-20T08:36:44.526Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-20T08:36:44.526Z level=INFO msg=connecting host=127.0.0.1:41337 protocol=28
time=2026-11-20T08:36:44.528Z level=INFO msg=connected host=127.0.0.1:41337 took=1.579ms
time=2026-11-20T08:36:44.528Z level=INFO msg="capabilities gathering"
time=2026-11-20T08:36:44.529Z level=INFO msg="capabilities gathered" took=1.47ms tags=linux,claude,go
time=2026-11-20T08:36:44.531Z level=INFO msg="hello sent" protocol=28
time=2026-11-20T08:36:44.546Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-20T08:36:46.673Z level=INFO msg="connection checked" connection=claude-1 state=healthy
    browser_test.go:46: waiting for [...document.querySelectorAll('[equipo-message="incoming"] [equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes('fake coordinator')): context deadline exceeded (last evaluation: context deadline exceeded)
--- FAIL: TestBrowserChat (6.22s)

--- FAIL amadan.net/oficina/equipo/internal/headless TestBrowserChatSendStaysOnPage
=== RUN   TestBrowserChatSendStaysOnPage
time=2026-11-20T08:36:50.645Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-20T08:36:50.645Z level=INFO msg="startup phase done" phase=state_lock took=252µs
time=2026-11-20T08:36:50.645Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-20T08:36:50.646Z level=INFO msg="startup phase done" phase=claim_roots took=174µs
time=2026-11-20T08:36:50.646Z level=INFO msg="startup phase" phase=sweep
time=2026-11-20T08:36:50.681Z level=INFO msg="startup phase done" phase=sweep took=35.708ms
time=2026-11-20T08:36:50.682Z level=INFO msg="startup phase" phase=credentials
time=2026-11-20T08:36:50.682Z level=INFO msg="startup phase done" phase=credentials took=205µs
time=2026-11-20T08:36:50.682Z level=INFO msg="startup phase" phase=open_state
time=2026-11-20T08:36:50.726Z level=INFO msg="startup phase done" phase=open_state took=44.585ms
time=2026-11-20T08:36:50.727Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-20T08:36:50.728Z level=INFO msg=connecting host=127.0.0.1:43413 protocol=28
time=2026-11-20T08:36:50.729Z level=INFO msg=connected host=127.0.0.1:43413 took=1.494ms
time=2026-11-20T08:36:50.730Z level=INFO msg="capabilities gathering"
time=2026-11-20T08:36:50.730Z level=INFO msg="capabilities gathered" took=691µs tags=linux,claude,go
time=2026-11-20T08:36:50.732Z level=INFO msg="hello sent" protocol=28
time=2026-11-20T08:36:50.736Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-20T08:36:52.918Z level=INFO msg="connection checked" connection=claude-1 state=healthy
    browser_test.go:108: waiting for [...document.querySelectorAll('[equipo-message="incoming"] [equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes('fake coordinator')): context deadline exceeded (last evaluation: <nil>)
--- FAIL: TestBrowserChatSendStaysOnPage (6.24s)

--- FAIL amadan.net/oficina/equipo/internal/headless TestBrowserDraftIsTheMessage
=== RUN   TestBrowserDraftIsTheMessage
time=2026-11-20T08:36:56.872Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-20T08:36:56.873Z level=INFO msg="startup phase done" phase=state_lock took=251µs
time=2026-11-20T08:36:56.873Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-20T08:36:56.873Z level=INFO msg="startup phase done" phase=claim_roots took=119µs
time=2026-11-20T08:36:56.873Z level=INFO msg="startup phase" phase=sweep
time=2026-11-20T08:36:56.936Z level=INFO msg="startup phase done" phase=sweep took=63.719ms
time=2026-11-20T08:36:56.940Z level=INFO msg="startup phase" phase=credentials
time=2026-11-20T08:36:56.940Z level=INFO msg="startup phase done" phase=credentials took=268µs
time=2026-11-20T08:36:56.940Z level=INFO msg="startup phase" phase=open_state
time=2026-11-20T08:36:57.020Z level=INFO msg="startup phase done" phase=open_state took=79.679ms
time=2026-11-20T08:36:57.020Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-20T08:36:57.022Z level=INFO msg=connecting host=127.0.0.1:33271 protocol=28
time=2026-11-20T08:36:57.026Z level=INFO msg=connected host=127.0.0.1:33271 took=4.286ms
time=2026-11-20T08:36:57.026Z level=INFO msg="capabilities gathering"
time=2026-11-20T08:36:57.026Z level=INFO msg="capabilities gathered" took=465µs tags=linux,claude,go
time=2026-11-20T08:36:57.029Z level=INFO msg="hello sent" protocol=28
time=2026-11-20T08:36:57.038Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-20T08:36:58.953Z level=INFO msg="connection checked" connection=claude-1 state=healthy
    browser_thinking_test.go:106: waiting for !!window.__m: context deadline exceeded (last evaluation: context deadline exceeded)
--- FAIL: TestBrowserDraftIsTheMessage (8.20s)

--- FAIL amadan.net/oficina/equipo/internal/headless (package output)
FAIL
rastrillo-budget/v1 ran 48.745s
FAIL	amadan.net/oficina/equipo/internal/headless	49.113s


receipt: test step 50.292s against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 0 cached, 0 without tests, 1 failed
receipt: slow package 48.745s amadan.net/oficina/equipo/internal/headless
receipt: slow test 15.15s amadan.net/oficina/equipo/internal/headless TestBrowserDraftStreamsFormatted
receipt: slow test 8.2s amadan.net/oficina/equipo/internal/headless TestBrowserDraftIsTheMessage
receipt: slow test 7.8s amadan.net/oficina/equipo/internal/headless TestBrowserComposer
receipt: slow test 6.24s amadan.net/oficina/equipo/internal/headless TestBrowserChatSendStaysOnPage
receipt: slow test 6.22s amadan.net/oficina/equipo/internal/headless TestBrowserChat
exit status 1
+ go test -tags browser,testbuild -timeout 15m -run '^TestBrowserChat$|^TestBrowserChatSendStaysOnPage$|^TestBrowserComposer$|^TestBrowserComposerReconcile$|^TestBrowserComposerFocus$|^TestBrowserComposerDock$|^TestBrowserDraftStreamsFormatted$|^TestBrowserDraftIsTheMessage$' -v -run '^TestBrowserChat$|^TestBrowserChatSendStaysOnPage$|^TestBrowserDraftIsTheMessage$' -count=1 ./internal/headless   (retry, once)
##############################################################################
FLAKE ./internal/headless:TestBrowserChat browser-headless-chat 18eee15fd0ec9c2642f186019d4d33cdbd498c41 6.22s 49.28
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
##############################################################################
FLAKE ./internal/headless:TestBrowserChatSendStaysOnPage browser-headless-chat 18eee15fd0ec9c2642f186019d4d33cdbd498c41 6.24s 49.28
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
##############################################################################
FLAKE ./internal/headless:TestBrowserDraftIsTheMessage browser-headless-chat 18eee15fd0ec9c2642f186019d4d33cdbd498c41 8.20s 49.28
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 44.66, cpu waiting 28.66%, memory waiting 0.00%, io waiting 0.37%
--- shard 19 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-headless-work: ./internal/headless
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^TestBrowserTaskCard$|^TestBrowserReceiptFollowsReview$|^TestBrowserRailFollowsWork$|^TestBrowserTaskThread$|^TestBrowserAskAfterMerge$|^TestBrowserReceiptsDesktop$|^TestBrowserReceiptsTouch$' ./internal/headless
--- FAIL amadan.net/oficina/equipo/internal/headless TestBrowserRailFollowsWork
=== RUN   TestBrowserRailFollowsWork
time=2026-11-20T08:36:41.894Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-20T08:36:41.894Z level=INFO msg="startup phase done" phase=state_lock took=105µs
time=2026-11-20T08:36:41.894Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-20T08:36:41.894Z level=INFO msg="startup phase done" phase=claim_roots took=82µs
time=2026-11-20T08:36:41.894Z level=INFO msg="startup phase" phase=sweep
time=2026-11-20T08:36:41.921Z level=INFO msg="startup phase done" phase=sweep took=26.554ms
time=2026-11-20T08:36:41.921Z level=INFO msg="startup phase" phase=credentials
time=2026-11-20T08:36:41.921Z level=INFO msg="startup phase done" phase=credentials took=224µs
time=2026-11-20T08:36:41.921Z level=INFO msg="startup phase" phase=open_state
time=2026-11-20T08:36:41.963Z level=INFO msg="startup phase done" phase=open_state took=41.407ms
time=2026-11-20T08:36:41.963Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-20T08:36:41.964Z level=INFO msg=connecting host=127.0.0.1:44837 protocol=28
time=2026-11-20T08:36:41.966Z level=INFO msg=connected host=127.0.0.1:44837 took=1.838ms
time=2026-11-20T08:36:41.966Z level=INFO msg="capabilities gathering"
rastrillo: budget test: go test failed
time=2026-11-20T08:36:41.966Z level=INFO msg="capabilities gathered" took=445µs tags=linux,claude,go
time=2026-11-20T08:36:41.967Z level=INFO msg="hello sent" protocol=28
time=2026-11-20T08:36:41.973Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-20T08:36:43.095Z level=INFO msg="connection checked" connection=claude-1 state=healthy
time=2026-11-20T08:36:52.014Z level=INFO msg="kept sessions" kept=1 bytes=2770 expired=0
time=2026-11-20T08:36:56.165Z level=INFO msg="kept sessions" kept=2 bytes=4922 expired=0
time=2026-11-20T08:36:56.985Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-20T08:36:56.985Z level=INFO msg="startup phase done" phase=state_lock took=64µs
time=2026-11-20T08:36:56.985Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-20T08:36:56.985Z level=INFO msg="startup phase done" phase=claim_roots took=85µs
time=2026-11-20T08:36:56.985Z level=INFO msg="startup phase" phase=sweep
time=2026-11-20T08:36:57.046Z level=INFO msg="startup phase done" phase=sweep took=60.989ms
time=2026-11-20T08:36:57.046Z level=INFO msg="startup phase" phase=credentials
time=2026-11-20T08:36:57.047Z level=INFO msg="startup phase done" phase=credentials took=454µs
time=2026-11-20T08:36:57.047Z level=INFO msg="startup phase" phase=open_state
time=2026-11-20T08:36:57.138Z level=INFO msg="startup phase done" phase=open_state took=91.448ms
time=2026-11-20T08:36:57.138Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-20T08:36:57.139Z level=INFO msg=connecting host=127.0.0.1:36401 protocol=28
time=2026-11-20T08:36:57.146Z level=INFO msg=connected host=127.0.0.1:36401 took=6.659ms
time=2026-11-20T08:36:57.146Z level=INFO msg="capabilities gathering"
time=2026-11-20T08:36:57.147Z level=INFO msg="capabilities gathered" took=666µs tags=linux,claude,go
time=2026-11-20T08:36:57.152Z level=INFO msg="hello sent" protocol=28
time=2026-11-20T08:36:57.154Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-20T08:36:59.013Z level=INFO msg="connection checked" connection=claude-1 state=healthy
    browser_review_test.go:57: waiting for document.querySelector('#rail [data-specialist="engineering"]')?.dataset.state==='working' && document.querySelector('#rail [data-specialist="engineering"]').querySelector('[equipo-nav-task]')?.textContent==='Slow sidebar change' && document.querySelector('#nav-tasks [data-count]')?.textContent==='1': context deadline exceeded (last evaluation: context deadline exceeded)
time=2026-11-20T08:37:03.421Z level=WARN msg="step account" err="context canceled"
time=2026-11-20T08:37:03.423Z level=WARN msg="step sweep" err="context canceled"
time=2026-11-20T08:37:03.423Z level=WARN msg="kept sessions" err="context canceled"
--- FAIL: TestBrowserRailFollowsWork (22.10s)

--- FAIL amadan.net/oficina/equipo/internal/headless (package output)
FAIL
rastrillo-budget/v1 ran 1m32.902s
FAIL	amadan.net/oficina/equipo/internal/headless	93.211s


receipt: test step 1m34.329s against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 0 cached, 0 without tests, 1 failed
receipt: slow package 1m32.902s amadan.net/oficina/equipo/internal/headless
receipt: slow test 25.12s amadan.net/oficina/equipo/internal/headless TestBrowserTaskThread
receipt: slow test 22.1s amadan.net/oficina/equipo/internal/headless TestBrowserRailFollowsWork
receipt: slow test 14.39s amadan.net/oficina/equipo/internal/headless TestBrowserReceiptFollowsReview
receipt: slow test 10.94s amadan.net/oficina/equipo/internal/headless TestBrowserAskAfterMerge
receipt: slow test 10.21s amadan.net/oficina/equipo/internal/headless TestBrowserTaskCard
exit status 1
+ go test -tags browser,testbuild -timeout 15m -run '^TestBrowserTaskCard$|^TestBrowserReceiptFollowsReview$|^TestBrowserRailFollowsWork$|^TestBrowserTaskThread$|^TestBrowserAskAfterMerge$|^TestBrowserReceiptsDesktop$|^TestBrowserReceiptsTouch$' -v -run '^TestBrowserRailFollowsWork$' -count=1 ./internal/headless   (retry, once)
##############################################################################
FLAKE ./internal/headless:TestBrowserRailFollowsWork browser-headless-work 18eee15fd0ec9c2642f186019d4d33cdbd498c41 22.10s 50.45
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 38.24, cpu waiting 23.60%, memory waiting 0.00%, io waiting 0.30%
--- shard 20 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-headless-connections: ./internal/headless
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^TestBrowserConnections|^TestBrowserPasteBox$|^TestBrowserPasteCopiesItsBox$' ./internal/headless

receipt: test step 1m46.159s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m44.705s amadan.net/oficina/equipo/internal/headless
receipt: slow test 16.83s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsConversation
receipt: slow test 14.2s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsAdd
receipt: slow test 13.18s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsAddPage
receipt: slow test 10.74s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsMeteredLimitRequired
receipt: slow test 10.49s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsOpenCodeGoLimitRequired
machine: 32 CPUs, load 44.66, cpu waiting 28.66%, memory waiting 0.00%, io waiting 0.37%
--- shard 21 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-headless-rest: ./internal/headless
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserAskAfterMerge|TestBrowserChat|TestBrowserChatSendStaysOnPage|TestBrowserComposer|TestBrowserComposerDock|TestBrowserComposerFocus|TestBrowserComposerReconcile|TestBrowserConnectionsAdd|TestBrowserConnectionsAddPage|TestBrowserConnectionsConversation|TestBrowserConnectionsCopyLink|TestBrowserConnectionsEndedNote|TestBrowserConnectionsMeteredLimitRequired|TestBrowserConnectionsOpenCodeGoLimitRequired|TestBrowserConnectionsSignIn|TestBrowserConnectionsSignInSwitch|TestBrowserConnectionsToken|TestBrowserCopyContinue|TestBrowserCopySettingAndFlag|TestBrowserDraftIsTheMessage|TestBrowserDraftStreamsFormatted|TestBrowserEmptyExplore|TestBrowserMoveIn|TestBrowserNotebook|TestBrowserNotebookLook|TestBrowserPasteBox|TestBrowserPasteBoxLook|TestBrowserPasteCopiesItsBox|TestBrowserRailFollowsWork|TestBrowserReceiptFollowsReview|TestBrowserReceiptsDesktop|TestBrowserReceiptsTouch|TestBrowserRefreshRace|TestBrowserStalePageReloads|TestBrowserTaskCard|TestBrowserTaskThread|TestBrowserThinkingAndCards|TestBrowserUsageAndAdvice|TestBrowserWaitingTurns|TestNotebookScreenshots)$' -skip '^TestBrowserChat$|^TestBrowserChatSendStaysOnPage$|^TestBrowserComposer$|^TestBrowserComposerReconcile$|^TestBrowserComposerFocus$|^TestBrowserComposerDock$|^TestBrowserDraftStreamsFormatted$|^TestBrowserDraftIsTheMessage$|^TestBrowserTaskCard$|^TestBrowserReceiptFollowsReview$|^TestBrowserRailFollowsWork$|^TestBrowserTaskThread$|^TestBrowserAskAfterMerge$|^TestBrowserReceiptsDesktop$|^TestBrowserReceiptsTouch$|^TestBrowserConnections|^TestBrowserPasteBox$|^TestBrowserPasteCopiesItsBox$' ./internal/headless
rastrillo: budget test: go test failed
--- FAIL amadan.net/oficina/equipo/internal/headless TestBrowserThinkingAndCards
=== RUN   TestBrowserThinkingAndCards
time=2026-11-20T08:36:17.473Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-20T08:36:17.474Z level=INFO msg="startup phase done" phase=state_lock took=144µs
time=2026-11-20T08:36:17.474Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-20T08:36:17.474Z level=INFO msg="startup phase done" phase=claim_roots took=166µs
time=2026-11-20T08:36:17.474Z level=INFO msg="startup phase" phase=sweep
time=2026-11-20T08:36:17.502Z level=INFO msg="startup phase done" phase=sweep took=28.321ms
time=2026-11-20T08:36:17.502Z level=INFO msg="startup phase" phase=credentials
time=2026-11-20T08:36:17.502Z level=INFO msg="startup phase done" phase=credentials took=156µs
time=2026-11-20T08:36:17.502Z level=INFO msg="startup phase" phase=open_state
time=2026-11-20T08:36:17.542Z level=INFO msg="startup phase done" phase=open_state took=39.836ms
time=2026-11-20T08:36:17.543Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-20T08:36:17.544Z level=INFO msg=connecting host=127.0.0.1:32875 protocol=28
time=2026-11-20T08:36:17.545Z level=INFO msg=connected host=127.0.0.1:32875 took=963µs
time=2026-11-20T08:36:17.545Z level=INFO msg="capabilities gathering"
time=2026-11-20T08:36:17.546Z level=INFO msg="capabilities gathered" took=452µs tags=linux,claude,go
time=2026-11-20T08:36:17.546Z level=INFO msg="hello sent" protocol=28
time=2026-11-20T08:36:17.551Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-20T08:36:18.755Z level=INFO msg="connection checked" connection=claude-1 state=healthy
    browser_cards_test.go:66: waiting for (()=>{const l=document.querySelector('[equipo-thinking] [equipo-activity]');return !!l && l.textContent==='Adding oficina/sample…'})(): context deadline exceeded (last evaluation: <nil>)
--- FAIL: TestBrowserThinkingAndCards (6.82s)

--- FAIL amadan.net/oficina/equipo/internal/headless TestBrowserEmptyExplore
=== RUN   TestBrowserEmptyExplore
time=2026-11-20T08:37:21.368Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-20T08:37:21.369Z level=INFO msg="startup phase done" phase=state_lock took=149µs
time=2026-11-20T08:37:21.369Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-20T08:37:21.369Z level=INFO msg="startup phase done" phase=claim_roots took=149µs
time=2026-11-20T08:37:21.369Z level=INFO msg="startup phase" phase=sweep
time=2026-11-20T08:37:21.402Z level=INFO msg="startup phase done" phase=sweep took=32.966ms
time=2026-11-20T08:37:21.402Z level=INFO msg="startup phase" phase=credentials
time=2026-11-20T08:37:21.402Z level=INFO msg="startup phase done" phase=credentials took=191µs
time=2026-11-20T08:37:21.402Z level=INFO msg="startup phase" phase=open_state
time=2026-11-20T08:37:21.446Z level=INFO msg="startup phase done" phase=open_state took=43.676ms
time=2026-11-20T08:37:21.447Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-20T08:37:21.448Z level=INFO msg=connecting host=127.0.0.1:33069 protocol=28
time=2026-11-20T08:37:21.450Z level=INFO msg=connected host=127.0.0.1:33069 took=2.027ms
time=2026-11-20T08:37:21.450Z level=INFO msg="capabilities gathering"
time=2026-11-20T08:37:21.451Z level=INFO msg="capabilities gathered" took=360µs tags=linux,claude,go
time=2026-11-20T08:37:21.451Z level=INFO msg="hello sent" protocol=28
time=2026-11-20T08:37:21.458Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-20T08:37:22.578Z level=INFO msg="connection checked" connection=claude-1 state=healthy
    browser_receipts_test.go:169: waiting for [...document.querySelectorAll('[equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes("I'm your coordinator")): context deadline exceeded (last evaluation: <nil>)
--- FAIL: TestBrowserEmptyExplore (5.95s)

--- FAIL amadan.net/oficina/equipo/internal/headless (package output)
FAIL
rastrillo-budget/v1 ran 1m25.137s
FAIL	amadan.net/oficina/equipo/internal/headless	85.479s


receipt: test step 1m26.632s against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 0 cached, 0 without tests, 1 failed
receipt: slow package 1m25.137s amadan.net/oficina/equipo/internal/headless
receipt: slow test 12.61s amadan.net/oficina/equipo/internal/headless TestBrowserStalePageReloads
receipt: slow test 11.27s amadan.net/oficina/equipo/internal/headless TestBrowserMoveIn
receipt: slow test 10.44s amadan.net/oficina/equipo/internal/headless TestBrowserWaitingTurns
receipt: slow test 8.25s amadan.net/oficina/equipo/internal/headless TestBrowserRefreshRace
receipt: slow test 7.92s amadan.net/oficina/equipo/internal/headless TestBrowserNotebookLook
exit status 1
+ go test -tags browser,testbuild -timeout 15m -run '^(TestBrowserAskAfterMerge|TestBrowserChat|TestBrowserChatSendStaysOnPage|TestBrowserComposer|TestBrowserComposerDock|TestBrowserComposerFocus|TestBrowserComposerReconcile|TestBrowserConnectionsAdd|TestBrowserConnectionsAddPage|TestBrowserConnectionsConversation|TestBrowserConnectionsCopyLink|TestBrowserConnectionsEndedNote|TestBrowserConnectionsMeteredLimitRequired|TestBrowserConnectionsOpenCodeGoLimitRequired|TestBrowserConnectionsSignIn|TestBrowserConnectionsSignInSwitch|TestBrowserConnectionsToken|TestBrowserCopyContinue|TestBrowserCopySettingAndFlag|TestBrowserDraftIsTheMessage|TestBrowserDraftStreamsFormatted|TestBrowserEmptyExplore|TestBrowserMoveIn|TestBrowserNotebook|TestBrowserNotebookLook|TestBrowserPasteBox|TestBrowserPasteBoxLook|TestBrowserPasteCopiesItsBox|TestBrowserRailFollowsWork|TestBrowserReceiptFollowsReview|TestBrowserReceiptsDesktop|TestBrowserReceiptsTouch|TestBrowserRefreshRace|TestBrowserStalePageReloads|TestBrowserTaskCard|TestBrowserTaskThread|TestBrowserThinkingAndCards|TestBrowserUsageAndAdvice|TestBrowserWaitingTurns|TestNotebookScreenshots)$' -skip '^TestBrowserChat$|^TestBrowserChatSendStaysOnPage$|^TestBrowserComposer$|^TestBrowserComposerReconcile$|^TestBrowserComposerFocus$|^TestBrowserComposerDock$|^TestBrowserDraftStreamsFormatted$|^TestBrowserDraftIsTheMessage$|^TestBrowserTaskCard$|^TestBrowserReceiptFollowsReview$|^TestBrowserRailFollowsWork$|^TestBrowserTaskThread$|^TestBrowserAskAfterMerge$|^TestBrowserReceiptsDesktop$|^TestBrowserReceiptsTouch$|^TestBrowserConnections|^TestBrowserPasteBox$|^TestBrowserPasteCopiesItsBox$' -v -run '^TestBrowserEmptyExplore$|^TestBrowserThinkingAndCards$' -count=1 ./internal/headless   (retry, once)
##############################################################################
FLAKE ./internal/headless:TestBrowserEmptyExplore browser-headless-rest 18eee15fd0ec9c2642f186019d4d33cdbd498c41 5.95s 54.90
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
##############################################################################
FLAKE ./internal/headless:TestBrowserThinkingAndCards browser-headless-rest 18eee15fd0ec9c2642f186019d4d33cdbd498c41 6.82s 54.90
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 41.49, cpu waiting 26.88%, memory waiting 0.00%, io waiting 0.34%
--- shard 22 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-rest: ./internal/equipo
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserPreviewBlocksNavigation)$' ./internal/equipo

receipt: test step 1.944s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 567ms amadan.net/oficina/equipo/internal/equipo
receipt: slow test 570ms amadan.net/oficina/equipo/internal/equipo TestBrowserPreviewBlocksNavigation
browser lane browser-rest: ./internal/idtest
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserOficinaIDDoor)$' ./internal/idtest

receipt: test step 2.947s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1.73s amadan.net/oficina/equipo/internal/idtest
receipt: slow test 1.73s amadan.net/oficina/equipo/internal/idtest TestBrowserOficinaIDDoor
browser lane browser-rest: ./internal/plan3test
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestTeamsHierarchyBrowser)$' ./internal/plan3test

receipt: test step 3.216s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1.933s amadan.net/oficina/equipo/internal/plan3test
receipt: slow test 1.93s amadan.net/oficina/equipo/internal/plan3test TestTeamsHierarchyBrowser
browser lane browser-rest: ./internal/thintest
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserAccessEmojiByline|TestBrowserAccessFinalOutcomes|TestBrowserAccessRequest|TestBrowserAccessReview|TestBrowserActivitySubjects|TestBrowserAutonomySettings|TestBrowserCoordinatorQueue|TestBrowserHousekeeping|TestBrowserInnerGallery|TestBrowserInnerScreens|TestBrowserInstantThinking|TestBrowserInstantThinkingQueued|TestBrowserMachines|TestBrowserPhoneIndex|TestBrowserPlacementQuestionAndPending|TestBrowserProjectPlacement|TestBrowserProjectsList|TestBrowserReportActionFeedback|TestBrowserReportNextSteps|TestBrowserReportThread|TestBrowserRollup|TestBrowserRosterAlignment|TestBrowserRosterDecisionStates|TestBrowserRosterQuietDay|TestBrowserRosterReports|TestBrowserRosterSetAside|TestBrowserRosterSubchat|TestBrowserRosterThinking|TestBrowserRosterVisual|TestBrowserSettingsHousekeepingGroups|TestBrowserSettingsMenu|TestBrowserSettingsRail|TestBrowserSettingsSaveBar|TestBrowserSettingsShots|TestBrowserSettingsStayOnPage|TestBrowserSettingsTeams|TestBrowserShipsButtons|TestBrowserSpecialistRows|TestBrowserSpendFollowsAnswers|TestBrowserTaskRows|TestBrowserTeamPanel|TestBrowserThinkingCycles|TestBrowserThinkingLinesClear|TestBrowserThinkingWords|TestBrowserTokenRowEmail|TestBrowserTrackStarCentre)$' ./internal/thintest

receipt: test step 2m59.154s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 2m57.63s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 17.14s amadan.net/oficina/equipo/internal/thintest TestBrowserAccessRequest
receipt: slow test 14.32s amadan.net/oficina/equipo/internal/thintest TestBrowserSettingsTeams
receipt: slow test 10.74s amadan.net/oficina/equipo/internal/thintest TestBrowserPlacementQuestionAndPending
receipt: slow test 9.03s amadan.net/oficina/equipo/internal/thintest TestBrowserThinkingCycles
receipt: slow test 8.1s amadan.net/oficina/equipo/internal/thintest TestBrowserInnerScreens
machine: 32 CPUs, load 14.32, cpu waiting 7.39%, memory waiting 0.00%, io waiting 0.08%
--- shard 23 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
shard 23: make test-quarantine
python3 scripts/ci-test.py quarantine
quarantine: 12 tests from scripts/ci-quarantine.txt; a failure is retried once, and a pass on the retry is reported as a flake
+ go test -tags testbuild -timeout 15m -v -run '^TestHeadlessConnections$/^A5_cancel_and_sign_out$|^TestHeadlessConnections$/^C4_claude_sign_in$|^TestHeadlessConnections$/^C5_engineering_failover$|^TestHeadlessConnections$/^C5_engineering_to_codex$|^TestHeadlessConnections$/^C5_engineering_waits$' ./internal/headless   (58s)
ok ./internal/headless TestHeadlessConnections/A5_cancel_and_sign_out 5.27s
ok ./internal/headless TestHeadlessConnections/C4_claude_sign_in 1.46s
ok ./internal/headless TestHeadlessConnections/C5_engineering_failover 10.55s
ok ./internal/headless TestHeadlessConnections/C5_engineering_to_codex 11.26s
ok ./internal/headless TestHeadlessConnections/C5_engineering_waits 27.39s
+ go test -tags testbuild -timeout 15m -v -run '^TestHeadlessConnections$/^C5_review_auth$|^TestHeadlessConnections$/^C5_review_failover$|^TestHeadlessConnections$/^C5_review_on_codex$|^TestHeadlessConnections$/^C5_review_other_family_first$' ./internal/headless   (64s)
ok ./internal/headless TestHeadlessConnections/C5_review_auth 19.53s
ok ./internal/headless TestHeadlessConnections/C5_review_failover 13.76s
ok ./internal/headless TestHeadlessConnections/C5_review_on_codex 12.32s
ok ./internal/headless TestHeadlessConnections/C5_review_other_family_first 16.79s
+ go test -tags testbuild -timeout 15m -v -run '^TestMixedVersions$' ./internal/headless   (24s)
ok ./internal/headless TestMixedVersions 22.45s
+ go test -tags testbuild -timeout 15m -v -run '^TestCheckSandboxDeniedPathsTampering$' ./internal/runner/checks   (1s)
ok ./internal/runner/checks TestCheckSandboxDeniedPathsTampering 0.78s
+ go test -tags testbuild -timeout 15m -v -run '^TestRunnerCancelAndSupersede$' ./internal/runner/thin   (1s)
ok ./internal/runner/thin TestRunnerCancelAndSupersede 0.05s
quarantine: 0 flaked (passed on the retry), 0 failed
machine: 32 CPUs, load 54.07, cpu waiting 34.31%, memory waiting 0.00%, io waiting 0.75%
--- shard 24 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
shard 24: make runner-host
python3 scripts/runner-prerequisites.py
CGO_ENABLED=0 RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py retried runner-host -run 'TestDirect|TestProvider|TestCheckSandbox' -count=1 ./internal/runner/provider/... ./internal/runner/checks
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -no-time -run 'TestDirect|TestProvider|TestCheckSandbox' -count=1 ./internal/runner/provider/... ./internal/runner/checks

receipt: test step 11.245s against a 60s target (the gate's other steps are not in this figure)
receipt: 4 packages ran, 0 cached, 3 without tests, 0 failed
receipt: slow package 7.633s amadan.net/oficina/equipo/internal/runner/checks
receipt: slow package 187ms amadan.net/oficina/equipo/internal/runner/provider/claude
receipt: slow package 67ms amadan.net/oficina/equipo/internal/runner/provider/codex
receipt: slow package 1ms amadan.net/oficina/equipo/internal/runner/provider
receipt: slow package 1ms amadan.net/oficina/equipo/internal/runner/provider/opencode
receipt: slow test 5.44s amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPathsGoFixture
receipt: slow test 1.74s amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPaths
receipt: slow test 360ms amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPathsCache
receipt: slow test 190ms amadan.net/oficina/equipo/internal/runner/provider/claude TestDirectJournalAdapterBarrier
receipt: slow test 70ms amadan.net/oficina/equipo/internal/runner/provider/codex TestDirectJournalAdapterBarrier
CGO_ENABLED=0 RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py retried runner-host -run '^TestNamespace' -count=1 ./internal/runner/containment
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -no-time -run '^TestNamespace' -count=1 ./internal/runner/containment

receipt: test step 3.394s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 2.982s amadan.net/oficina/equipo/internal/runner/containment
receipt: slow test 280ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceReadOnlyScratch
receipt: slow test 180ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryUnavailableProof
receipt: slow test 120ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceDirectPolicyAdmission
receipt: slow test 110ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceReapsOrphans
receipt: slow test 100ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryMalformedRecord
machine: 32 CPUs, load 12.75, cpu waiting 7.79%, memory waiting 0.00%, io waiting 1.74%
--- shard 25 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: runner-dead-references started 30s late; cpu waiting 36.4%, load 21.30
shard 25: make runner-dead-references lanes-check build vet fmt-check budget migration-check
python3 scripts/runner-dead-references.py
reference scan: 2463 text files, 2842 matches, 0 failures
python3 scripts/ci-test.py check
lanes: 18 lanes and 5 browser lanes run every test once; 20-check@29
CGO_ENABLED=0 go build ./...
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -o /dev/null ./cmd/equipo-runner
go vet ./...
go vet -tags testbuild ./internal/runner/thin ./internal/headless
GOOS=darwin GOARCH=arm64 go vet ./cmd/equipo-runner/... ./internal/runner/... ./internal/wire/... ./internal/release/...
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size
budget size: 88 directories within budget
CGO_ENABLED=0 go test ./internal/equipo -run '^TestMigrationModels$' -count=1
ok  	amadan.net/oficina/equipo/internal/equipo	2.463s
machine: 32 CPUs, load 54.07, cpu waiting 34.31%, memory waiting 0.00%, io waiting 0.75%
--- shard 26 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: staticcheck started 30s late; cpu waiting 36.4%, load 21.30
shard 26: make staticcheck
go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 -tags browser,perf,testbuild ./...
machine: 32 CPUs, load 45.74, cpu waiting 26.71%, memory waiting 0.00%, io waiting 1.05%
--- shard 27 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: govulncheck started 30s late; cpu waiting 36.4%, load 21.30
shard 27: make govulncheck
go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./...
=== Symbol Results ===

No vulnerabilities found.

Your code is affected by 0 vulnerabilities.
This scan also found 0 vulnerabilities in packages you import and 5
vulnerabilities in modules you require, but your code doesn't appear to call
these vulnerabilities.
Use '-show verbose' for more details.
machine: 32 CPUs, load 28.97, cpu waiting 20.73%, memory waiting 0.00%, io waiting 1.20%
--- shard 28 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: gitleaks started 30s late; cpu waiting 36.7%, load 21.30
shard 28: make gitleaks
8:36AM INF Unknown SCM platform. Use --platform to include links in findings. host=amadan.net
8:37AM INF 1026 commits scanned.
8:37AM INF scanned ~60174734 bytes (60.17 MB) in 21s
8:37AM INF no leaks found
machine: 32 CPUs, load 49.28, cpu waiting 30.47%, memory waiting 0.00%, io waiting 0.95%
=== perf ===
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -no-time -require TestPerfScreens,TestPerfBoot -tags perf -count=1 -p 1 -parallel 1 -run '^TestPerf' ./...
perf: GET /: median 1.044ms, worst 1.084ms, budget 150ms
perf: GET /api/runner/protocol: median 91µs, worst 102µs, budget 150ms
perf: GET /api/v1/account-setups/{id}: median 552µs, worst 585µs, budget 150ms
perf: GET /api/v1/accounts: median 415µs, worst 462µs, budget 150ms
perf: GET /api/v1/auth/devices: median 424µs, worst 455µs, budget 150ms
perf: GET /api/v1/budgets: median 470µs, worst 486µs, budget 150ms
perf: GET /api/v1/capabilities: median 239µs, worst 256µs, budget 150ms
perf: GET /api/v1/cards/{id}: median 1.158ms, worst 1.216ms, budget 150ms
perf: GET /api/v1/connections: median 547µs, worst 587µs, budget 150ms
perf: GET /api/v1/connections/{id}: median 509µs, worst 548µs, budget 150ms
perf: GET /api/v1/conversation: median 915µs, worst 1ms, budget 150ms
perf: GET /api/v1/conversation/cards: median 1.435ms, worst 1.481ms, budget 150ms
perf: GET /api/v1/coordinator: median 1.745ms, worst 1.881ms, budget 150ms
perf: GET /api/v1/invites/{id}: median 457µs, worst 487µs, budget 150ms
perf: GET /api/v1/journey: median 10.098ms, worst 10.326ms, budget 150ms
perf: GET /api/v1/me: median 488µs, worst 511µs, budget 150ms
perf: GET /api/v1/me/settings: median 582µs, worst 613µs, budget 150ms
perf: GET /api/v1/needs-you: median 9.871ms, worst 12.762ms, budget 150ms
perf: GET /api/v1/notifications: median 1.657ms, worst 1.737ms, budget 150ms
perf: GET /api/v1/onboarding: median 409µs, worst 430µs, budget 150ms
perf: GET /api/v1/people: median 436µs, worst 450µs, budget 150ms
perf: GET /api/v1/playbooks: median 590µs, worst 615µs, budget 150ms
perf: GET /api/v1/playbooks/{id}: median 535µs, worst 592µs, budget 150ms
perf: GET /api/v1/playbooks/{id}/template-diff: median 849µs, worst 884µs, budget 150ms
perf: GET /api/v1/preferences: median 740µs, worst 808µs, budget 150ms
perf: GET /api/v1/projects/{id}: median 459µs, worst 499µs, budget 150ms
perf: GET /api/v1/projects/{id}/settings: median 571µs, worst 581µs, budget 150ms
perf: GET /api/v1/roster: median 471µs, worst 511µs, budget 150ms
perf: GET /api/v1/runners/{id}: median 395µs, worst 425µs, budget 150ms
perf: GET /api/v1/specialists: median 7.959ms, worst 8.07ms, budget 150ms
perf: GET /api/v1/specialists/{id}: median 7.848ms, worst 7.917ms, budget 150ms
perf: GET /api/v1/specialists/{id}/template-diff: median 819µs, worst 838µs, budget 150ms
perf: GET /api/v1/tasks/{id}/plan: median 1.068ms, worst 1.161ms, budget 150ms
perf: GET /api/v1/tasks/{id}/thread: median 697µs, worst 720µs, budget 150ms
perf: GET /api/v1/teams: median 408µs, worst 433µs, budget 150ms
perf: GET /api/v1/templates: median 573µs, worst 589µs, budget 150ms
perf: GET /api/v1/templates/{id}: median 432µs, worst 499µs, budget 150ms
perf: GET /auth/callback: median 78µs, worst 101µs, budget 150ms
perf: GET /auth/devices/{id}: median 3.142ms, worst 3.22ms, budget 150ms
perf: GET /auth/verify: median 77µs, worst 116µs, budget 150ms
perf: GET /connections: median 3.466ms, worst 3.522ms, budget 150ms
perf: GET /conversation: median 7.044ms, worst 7.289ms, budget 150ms
perf: GET /conversation/connections: median 247µs, worst 265µs, budget 150ms
perf: GET /conversation/notebook: median 232µs, worst 271µs, budget 150ms
perf: GET /conversation/settings: median 3.759ms, worst 3.896ms, budget 150ms
perf: GET /conversation/settings/autonomy: median 3.483ms, worst 3.528ms, budget 150ms
perf: GET /conversation/settings/connections: median 6.215ms, worst 8.603ms, budget 150ms
perf: GET /conversation/settings/connections/add: median 6.249ms, worst 6.51ms, budget 150ms
perf: GET /conversation/settings/copy: median 3.419ms, worst 3.535ms, budget 150ms
perf: GET /conversation/settings/housekeeping: median 3.955ms, worst 4.04ms, budget 150ms
perf: GET /conversation/settings/machines: median 4.194ms, worst 4.297ms, budget 150ms
perf: GET /conversation/settings/machines/add: median 4.18ms, worst 4.25ms, budget 150ms
perf: GET /conversation/settings/notebook: median 3.2ms, worst 3.291ms, budget 150ms
perf: GET /conversation/settings/thinking: median 3.757ms, worst 3.781ms, budget 150ms
perf: GET /housekeeping: median 3.636ms, worst 3.675ms, budget 150ms
perf: GET /invites/new: median 615µs, worst 627µs, budget 150ms
perf: GET /invites/{id}: median 657µs, worst 710µs, budget 150ms
perf: GET /jobs: median 3.259ms, worst 4.521ms, budget 150ms
perf: GET /jobs/{id}: median 4.324ms, worst 4.543ms, budget 150ms
perf: GET /journey: median 11.234ms, worst 11.377ms, budget 150ms
perf: GET /nav/rail: median 2.869ms, worst 2.98ms, budget 150ms
perf: GET /needs-you: median 10.93ms, worst 11.114ms, budget 150ms
perf: GET /onboarding: median 3.928ms, worst 4.048ms, budget 150ms
perf: GET /people: median 3.242ms, worst 3.323ms, budget 150ms
perf: GET /playbook-suggestions/{suggestion}: median 4.716ms, worst 4.789ms, budget 150ms
perf: GET /playbooks: median 4.41ms, worst 7.047ms, budget 150ms
perf: GET /playbooks/new: median 4.355ms, worst 4.497ms, budget 150ms
perf: GET /playbooks/{id}: median 5.014ms, worst 5.193ms, budget 150ms
perf: GET /playbooks/{id}/edit: median 4.962ms, worst 5.037ms, budget 150ms
perf: GET /playbooks/{id}/template-diff: median 4.132ms, worst 4.19ms, budget 150ms
perf: GET /preferences: median 3.958ms, worst 4.017ms, budget 150ms
perf: GET /preferences/sources/{source}: median 3.752ms, worst 3.792ms, budget 150ms
perf: GET /projects: median 4.897ms, worst 5.05ms, budget 150ms
perf: GET /projects/accounts: median 3.394ms, worst 3.496ms, budget 150ms
perf: GET /projects/new: median 3.414ms, worst 3.522ms, budget 150ms
perf: GET /projects/{id}: median 10.475ms, worst 13.062ms, budget 150ms
perf: GET /projects/{id}/edit: median 3.586ms, worst 3.705ms, budget 150ms
perf: GET /runners/enrol: median 4.217ms, worst 4.325ms, budget 150ms
perf: GET /settings: median 3.342ms, worst 3.386ms, budget 150ms
perf: GET /settings/coordinator: median 5.235ms, worst 5.372ms, budget 150ms
perf: GET /settings/devices: median 3.132ms, worst 3.188ms, budget 150ms
perf: GET /settings/recovery: median 3.253ms, worst 3.319ms, budget 150ms
perf: GET /settings/recovery/release: median 3.257ms, worst 3.385ms, budget 150ms
perf: GET /settings/thinking: median 249µs, worst 270µs, budget 150ms
perf: GET /signin: median 304µs, worst 369µs, budget 150ms
perf: GET /specialists/new: median 3.191ms, worst 3.237ms, budget 150ms
perf: GET /specialists/{key}: median 10.178ms, worst 10.729ms, budget 150ms
perf: GET /specialists/{key}/edit: median 3.542ms, worst 3.681ms, budget 150ms
perf: GET /specialists/{key}/template-diff: median 3.607ms, worst 3.691ms, budget 150ms
perf: GET /tasks: median 4.955ms, worst 4.99ms, budget 150ms
perf: GET /tasks/new: median 3.05ms, worst 3.099ms, budget 150ms
perf: GET /tasks/{id}: median 5.235ms, worst 5.346ms, budget 150ms
perf: GET /tasks/{id}/merge: median 4.488ms, worst 4.63ms, budget 150ms
perf: GET /tasks/{id}/move: median 4.349ms, worst 4.47ms, budget 150ms
perf: GET /tasks/{id}/plan: median 5.474ms, worst 5.542ms, budget 150ms
perf: GET /tasks/{id}/preview: median 1.469ms, worst 1.504ms, budget 150ms
perf: GET /tasks/{id}/questions/{question}: median 4.85ms, worst 4.943ms, budget 150ms
perf: GET /tasks/{id}/rendered-change: median 4.589ms, worst 6.631ms, budget 150ms
perf: GET /tasks/{id}/rendered-change/{hash}.png: median 4.111ms, worst 4.278ms, budget 150ms
perf: GET /tasks/{id}/thread: median 7.572ms, worst 7.797ms, budget 150ms
perf: GET /team/{specialist}: median 4.15ms, worst 4.244ms, budget 150ms
perf: GET /teams: median 9.535ms, worst 9.719ms, budget 150ms
perf: GET /templates: median 3.288ms, worst 3.35ms, budget 150ms
perf: GET /usage: median 3.94ms, worst 4.017ms, budget 150ms
perf: GET /work: median 2.913ms, worst 3.017ms, budget 150ms
perf: cold boot: median 256ms of [255.412562ms 256.408147ms 257.344192ms], budget 500ms

receipt: test step 37.923s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 84 without tests, 0 failed
receipt: slow package 8.755s amadan.net/oficina/equipo/internal/equipotest
receipt: slow package 0s amadan.net/oficina/equipo/cmd/equipo-runner
receipt: slow package 0s amadan.net/oficina/equipo/cmd/equipo-tool-proxy
receipt: slow package 0s amadan.net/oficina/equipo/internal/advice
receipt: slow package 0s amadan.net/oficina/equipo/internal/attach
receipt: slow test 7.93s amadan.net/oficina/equipo/internal/equipotest TestPerfScreens
receipt: slow test 820ms amadan.net/oficina/equipo/internal/equipotest TestPerfBoot
=== cache ===
ci-box: build cache /home/ci/work/repos/oficina__equipo/cache/go-build: 4.07 GiB in 23557 files
ci-box: module cache /home/ci/work/repos/oficina__equipo/cache/go-mod: 0.84 GiB in 27329 files
ci-box: build cache over 4.0 GiB: dropped 1.47 GiB this job did not read, kept 2.61 GiB
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 22ca9f97..0b5d80d0 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -14,7 +14,7 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr
time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI.
time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage.
-size internal/equipo 21451 - Native slice 2: push registrations, the push outbox and its rules, set aside; measured 21451/3196 source/test lines.
+size internal/equipo 21464 - Native slice 2: push registrations, the push outbox and its rules, set aside, and the review fixes (one token a credential, sealed at rest, CARLOS outcomes); measured 21464/3301 source/test lines.
size internal/wire 6768 - Native slice 2: push registrations, the push outbox and its rules, set aside; measured 6768/2972 source/test lines.
size internal/equipotest - 12013 Task 21 repairs historical migration and conversation fixtures after Plan 3; measured 0/12013 source/test lines.
time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded);
@@ -30,7 +30,7 @@ size internal/runner/provider 5598 - Fable follow-up: base and diagnostic gates,
time internal/plan3test 300s Initial cap for combined browser and runner acceptance; measure at both usable stops.
-size internal/plan3test - 11431 Plan 3 release-boundary and copy-inventory contracts in one package, and native slice 2 push registration lifetime; measured 940/11431 source/test lines.
+size internal/plan3test - 11446 Plan 3 release-boundary and copy-inventory contracts in one package, and native slice 2 push registration lifetime; measured 940/11446 source/test lines.
time internal/runner/forge 20s Plan 3 CI repair measured 10.527s for the full package (controller CI 10.407s).
time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full package (controller CI 10.709s);
@@ -56,7 +56,7 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device
perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen.
-size internal/equipo/chat 31703 - Native slice 2: push registrations, the push outbox and its rules, set aside; measured 31703/6180 source/test lines.
+size internal/equipo/chat 31881 - Native slice 2: push registrations, the push outbox and its rules, set aside, and the review fixes (one token a credential, sealed at rest, CARLOS outcomes); measured 31881/6818 source/test lines.
perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}.
perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}.
perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections.
diff --git a/docs/api/equipo-v1.md b/docs/api/equipo-v1.md
index e3e7a3bb..8ffe18c3 100644
--- a/docs/api/equipo-v1.md
+++ b/docs/api/equipo-v1.md
@@ -129,16 +129,16 @@ Register the device with `POST /api/v1/push-registrations` and the device's bear
{"token":"<APNs token, hex>","environment":"production","platform":"ios","start_token":"<Live Activity push-to-start token, hex>"}
```
-`environment` is `production` or `development`. `platform` is `ios` or `macos`. Only `ios` sends `start_token`. The registration belongs to the device credential that sends it. A new registration replaces the previous one. It returns `200` with `environment`, `platform`, `live_activities` and `updated_at`, never a token. The registration is deleted when the device is revoked, when its person leaves the team, or when Apple answers `Unregistered` or `BadDeviceToken`.
+`environment` is `production` or `development`. `platform` is `ios` or `macos`. Only `ios` sends `start_token`. The registration belongs to the device credential that sends it. A new registration replaces the previous one. A token belongs to one device credential at a time. Registering it removes it from any other device credential and anything waiting for that credential. It returns `200` with `environment`, `platform`, `live_activities` and `updated_at`, never a token. The registration is deleted when the device is revoked, when its person leaves the team, or when Apple says the token is no longer valid (`Unregistered`, `ExpiredToken`, `BadDeviceToken` or `DeviceTokenNotForTopic`).
The server decides on pushes in the same transaction as the change, so a change that does not happen pushes nothing:
- an alert when a card waits on you, with the card's question. `apns-collapse-id` is the card's ID and `equipo` is `{"kind":"card","card_id":"<card ID>","task_id":"<task ID or empty>"}`;
- an alert when the coordinator replies while you have no `/events` stream open, with the reply's first line and `{"kind":"reply","turn_id":"<turn ID>"}`;
- a passive alert when a task you started ends, or when one of its steps stops and waits for Retry, with `{"kind":"task","task_id":"<task ID>"}`;
-- the badge showing your Needs you count whenever that count changes.
+- the badge showing your Needs you count when the device registers and whenever that count changes.
-Alerts that wait on you have the category `needs_you`. Each task you started gets a Live Activity, at most three at once for you: those of the three most recently started tasks. It starts by push-to-start when work starts, with `attributes-type` `EquipoTaskAttributes` and attributes `{"task_id":"<task ID>"}`. Its content state has `task_id`, `title`, `stage`, `specialist`, `activity`, `needs_you`, `tone` (`positive`, `warning` or `negative`) and, at the end, `outcome` (`done`, `cancelled`, or `replaced` when a newer task took its place). It updates when the stage, step or `needs_you` changes, urgently and with an alert when the task starts needing you, and at most once a minute for a new activity line. Send each running activity's own token with `POST /api/v1/push-registrations/activities`, `{"task_id":"tk...","token":"<hex>"}`, which returns `204`. The server forgets it when the activity ends.
+Alerts that wait on you have the category `needs_you`. Each task you started gets a Live Activity, at most three at once for you: those of the three most recently started tasks. It starts by push-to-start when work starts, with `attributes-type` `EquipoTaskAttributes` and attributes `{"task_id":"<task ID>"}`. Its content state has `task_id`, `title`, `stage`, `specialist`, `activity`, `needs_you`, `tone` (`positive`, `warning` or `negative`) and, at the end, `outcome` (`done`, `cancelled`, or `replaced` when a newer task took its place). It updates when the stage, step or `needs_you` changes, and at most once a minute for a new activity line. When the task starts needing you, the update is urgent but has no alert: the decision card's alert is the only sound. Send each running activity's own token with `POST /api/v1/push-registrations/activities`, `{"task_id":"tk...","token":"<hex>"}`, which returns `204`. When the token is received, the activity gets the task's full current state. After the task ends, the token is accepted only while the activity's end notification is waiting to be sent. The server then sends the end notification immediately. After that, it returns `409 task_ended`. The server forgets the token when the activity ends.
## Talk to the Assistant
diff --git a/docs/api/equipo-v1.openapi.json b/docs/api/equipo-v1.openapi.json
index f348a7e0..6320e411 100644
--- a/docs/api/equipo-v1.openapi.json
+++ b/docs/api/equipo-v1.openapi.json
@@ -13491,7 +13491,7 @@
"post": {
"operationId": "post_push_registrations",
"summary": "Register this device for push notifications",
- "description": "A device bearer only (a browser session is 401). Send the APNs device `token` (hex), its `environment` (`production` or `development`), the app's `platform` (`ios` or `macos`) and, on iPhone, the Live Activity push-to-start `start_token`. The registration belongs to the paired device credential that sends it and replaces its earlier one. It is deleted when the device is revoked, when its person leaves the team, or when Apple reports the token `Unregistered` or `BadDeviceToken`. Tokens are never echoed, logged or audited. The answer is 200 with the registration, without its tokens. Pushes: an alert when a card waits on you (collapse ID the card, `equipo.card_id` to open it), when the coordinator replies while no `/events` stream is open (the reply's first line, `equipo.turn_id`), and a passive alert when a task you started ends or a step of it stops (`equipo.task_id`); the badge is your Needs you count; for each task you started, at most three, a Live Activity (`attributes-type` `EquipoTaskAttributes`, attributes `{task_id}`, content state `LiveActivityState`) starts when work starts, updates on its stage, step or needs-you change and at most once a minute for its activity line, and ends with the outcome.",
+ "description": "A device bearer only (a browser session is 401). Send the APNs device `token` (hex), its `environment` (`production` or `development`), the app's `platform` (`ios` or `macos`) and, on iPhone, the Live Activity push-to-start `start_token`. The registration belongs to the paired device credential that sends it and replaces its earlier one; a token belongs to one credential at a time, so registering it removes it from any other (with what waited for that credential). It is deleted when the device is revoked, when its person leaves the team, or when Apple reports the token `Unregistered`, `ExpiredToken`, `BadDeviceToken` or `DeviceTokenNotForTopic`. Tokens are never echoed, logged or audited. The answer is 200 with the registration, without its tokens. Pushes: an alert when a card waits on you (collapse ID the card, `equipo.card_id` to open it), when the coordinator replies while no `/events` stream is open (the reply's first line, `equipo.turn_id`), and a passive alert when a task you started ends or a step of it stops (`equipo.task_id`); the badge is your Needs you count, sent when the device registers and whenever it changes; for each task you started, at most three, a Live Activity (`attributes-type` `EquipoTaskAttributes`, attributes `{task_id}`, content state `LiveActivityState`) starts when work starts, updates on its stage, step or needs-you change (urgent, without an alert, when it starts needing you) and at most once a minute for its activity line, and ends with the outcome.",
"security": [
{
"personBearer": []
@@ -13555,7 +13555,7 @@
"post": {
"operationId": "post_push_registrations_activities",
"summary": "Register a running Live Activity's update token",
- "description": "A device bearer only. Send the `task_id` the Live Activity follows (a task you started that has not ended; another's is 404, an ended one 409 `task_ended`) and the activity's own push `token` (hex). Updates and the end go to it; the server forgets it when the activity ends. 204.",
+ "description": "A device bearer only. Send the `task_id` the Live Activity follows (a task you started; another's is 404) and the activity's own push `token` (hex). The activity then gets the task's current state in full. Once the task ended, the token is accepted only while the activity's end waits to be sent (the end then goes at once), else 409 `task_ended`. Updates and the end go to it; the server forgets it when the activity ends. 204.",
"security": [
{
"personBearer": []
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index 6ef65a37..c45bab0c 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -6752,6 +6752,7 @@ records remain unchanged.
| `copyMissingSMTP` | A configured mail sender is required. Enable CARLOS mail submission or configure CARLOS_SMTP_HOST and CARLOS_SMTP_FROM, unless local logged mail is enabled. | boot error when Equipo has no mail channel: neither CARLOS mail submission nor CARLOS_SMTP_HOST and CARLOS_SMTP_FROM (mail submission, 2026-11-17; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-17) |
| `copyLoggedPushPublic` | Unset EQUIPO_ALLOW_LOGGED_PUSH on a public origin. It is only allowed on loopback or staging. | boot error: EQUIPO_ALLOW_LOGGED_PUSH on a public origin (native slice 2 push, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
| `copyCarlosPushUnavailable` | CARLOS push submission is not available in this version of Equipo. Unset CARLOS_PUSH. | boot error: CARLOS_PUSH=submit before this build has the CARLOS push client (native slice 2 push, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
+| `copyPushBoth` | Set EQUIPO_ALLOW_LOGGED_PUSH or CARLOS_PUSH, not both. | boot error: EQUIPO_ALLOW_LOGGED_PUSH and CARLOS_PUSH both set (native slice 2 push, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
| `push.card.title` | Needs you | notification title when a card waits on the person (body: the card's question) (native slice 2 push, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
| `push.card.body` | A decision is waiting for you. | notification body when the waiting card has no question (native slice 2 push, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
| `push.reply.title` | Coordinator replied | notification title when the coordinator replied while no stream was open (body: the reply's first line) (native slice 2 push, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
@@ -6759,9 +6760,8 @@ records remain unchanged.
| `push.task.cancelled` | Cancelled. | passive notification body when that task is cancelled (title: the task) (native slice 2 push, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
| `push.task.failed` | A step failed. Open the task to retry the step. | passive notification body when a step of that task failed and waits for Retry (title: the task) (native slice 2 push, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
| `push.activity.started` | Work has started. | alert with a task's Live Activity starting (title: the task) (native slice 2 push, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
-| `push.activity.needs_you` | Needs you. | alert when a running task's Live Activity turns amber because it needs the person (title: the task) (native slice 2 push, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
| `docs/api/equipo-v1.md / Talk to your Coordinator from a device: set aside` | Set a card aside with `POST /api/v1/cards/{id}/visibility`, sending `{"aside":true,"revision":2}`, or `false` to bring it back. It never answers, cancels or starts anything, and the card stays in Needs you. It returns `200` with the card. Its `aside` is `true` while you have set it aside. An outdated revision or a card that no longer waits on you returns `409 card_stale` with the current card. | API doc: Set aside for a device (native slice 2, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | Document section; COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
-| `docs/api/equipo-v1.md / Receive pushes on a device` | ## Receive pushes on a device<br><br>Register the device with `POST /api/v1/push-registrations` and the device's bearer token:<br><br>```json<br>{"token":"&lt;APNs token, hex&gt;","environment":"production","platform":"ios","start_token":"&lt;Live Activity push-to-start token, hex&gt;"}<br>```<br><br>`environment` is `production` or `development`. `platform` is `ios` or `macos`. Only `ios` sends `start_token`. The registration belongs to the device credential that sends it. A new registration replaces the previous one. It returns `200` with `environment`, `platform`, `live_activities` and `updated_at`, never a token. The registration is deleted when the device is revoked, when its person leaves the team, or when Apple answers `Unregistered` or `BadDeviceToken`.<br><br>The server decides on pushes in the same transaction as the change, so a change that does not happen pushes nothing:<br><br>- an alert when a card waits on you, with the card's question. `apns-collapse-id` is the card's ID and `equipo` is `{"kind":"card","card_id":"&lt;card ID&gt;","task_id":"&lt;task ID or empty&gt;"}`;<br>- an alert when the coordinator replies while you have no `/events` stream open, with the reply's first line and `{"kind":"reply","turn_id":"&lt;turn ID&gt;"}`;<br>- a passive alert when a task you started ends, or when one of its steps stops and waits for Retry, with `{"kind":"task","task_id":"&lt;task ID&gt;"}`;<br>- the badge showing your Needs you count whenever that count changes.<br><br>Alerts that wait on you have the category `needs_you`. Each task you started gets a Live Activity, at most three at once for you: those of the three most recently started tasks. It starts by push-to-start when work starts, with `attributes-type` `EquipoTaskAttributes` and attributes `{"task_id":"&lt;task ID&gt;"}`. Its content state has `task_id`, `title`, `stage`, `specialist`, `activity`, `needs_you`, `tone` (`positive`, `warning` or `negative`) and, at the end, `outcome` (`done`, `cancelled`, or `replaced` when a newer task took its place). It updates when the stage, step or `needs_you` changes, urgently and with an alert when the task starts needing you, and at most once a minute for a new activity line. Send each running activity's own token with `POST /api/v1/push-registrations/activities`, `{"task_id":"tk...","token":"&lt;hex&gt;"}`, which returns `204`. The server forgets it when the activity ends. | API doc: push registrations, what pushes and the Live Activity content state (native slice 2, 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | Document section; COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
+| `docs/api/equipo-v1.md / Receive pushes on a device` | ## Receive pushes on a device<br><br>Register the device with `POST /api/v1/push-registrations` and the device's bearer token:<br><br>```json<br>{"token":"&lt;APNs token, hex&gt;","environment":"production","platform":"ios","start_token":"&lt;Live Activity push-to-start token, hex&gt;"}<br>```<br><br>`environment` is `production` or `development`. `platform` is `ios` or `macos`. Only `ios` sends `start_token`. The registration belongs to the device credential that sends it. A new registration replaces the previous one. A token belongs to one device credential at a time. Registering it removes it from any other device credential and anything waiting for that credential. It returns `200` with `environment`, `platform`, `live_activities` and `updated_at`, never a token. The registration is deleted when the device is revoked, when its person leaves the team, or when Apple says the token is no longer valid (`Unregistered`, `ExpiredToken`, `BadDeviceToken` or `DeviceTokenNotForTopic`).<br><br>The server decides on pushes in the same transaction as the change, so a change that does not happen pushes nothing:<br><br>- an alert when a card waits on you, with the card's question. `apns-collapse-id` is the card's ID and `equipo` is `{"kind":"card","card_id":"&lt;card ID&gt;","task_id":"&lt;task ID or empty&gt;"}`;<br>- an alert when the coordinator replies while you have no `/events` stream open, with the reply's first line and `{"kind":"reply","turn_id":"&lt;turn ID&gt;"}`;<br>- a passive alert when a task you started ends, or when one of its steps stops and waits for Retry, with `{"kind":"task","task_id":"&lt;task ID&gt;"}`;<br>- the badge showing your Needs you count when the device registers and whenever that count changes.<br><br>Alerts that wait on you have the category `needs_you`. Each task you started gets a Live Activity, at most three at once for you: those of the three most recently started tasks. It starts by push-to-start when work starts, with `attributes-type` `EquipoTaskAttributes` and attributes `{"task_id":"&lt;task ID&gt;"}`. Its content state has `task_id`, `title`, `stage`, `specialist`, `activity`, `needs_you`, `tone` (`positive`, `warning` or `negative`) and, at the end, `outcome` (`done`, `cancelled`, or `replaced` when a newer task took its place). It updates when the stage, step or `needs_you` changes, and at most once a minute for a new activity line. When the task starts needing you, the update is urgent but has no alert: the decision card's alert is the only sound. Send each running activity's own token with `POST /api/v1/push-registrations/activities`, `{"task_id":"tk...","token":"&lt;hex&gt;"}`, which returns `204`. When the token is received, the activity gets the task's full current state. After the task ends, the token is accepted only while the activity's end notification is waiting to be sent. The server then sends the end notification immediately. After that, it returns `409 task_ended`. The server forgets the token when the activity ends. | API doc: push registrations, what pushes and the Live Activity content state (native slice 2, 2026-11-20, revised after review 2026-11-20; Luna, codex gpt-5.6-luna, house rules) | Document section; COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20) |
## Task 21
diff --git a/internal/equipo/chat/projects.go b/internal/equipo/chat/projects.go
index 8870fa38..173090e8 100644
--- a/internal/equipo/chat/projects.go
+++ b/internal/equipo/chat/projects.go
@@ -352,7 +352,12 @@ func (t *txn) cardView(c cardRecord) (wire.Card, error) {
return v, nil
}
-func (t *txn) cardEvent(c cardRecord) error {
+func (t *txn) cardEvent(c cardRecord) error { return t.cardEventPush(c, true) }
+
+// cardEventPush is cardEvent; pushes false for a change that is no card
+// change to its person's devices (setting it aside), which runs no push
+// rule.
+func (t *txn) cardEventPush(c cardRecord, pushes bool) error {
if c.Held {
// Quiet hours: the conversation hears of it at its visible time.
return nil
@@ -371,8 +376,10 @@ func (t *txn) cardEvent(c cardRecord) error {
if err := t.event(c.Lane, c.Person, wire.EventCard, "card", c.ID, c.Revision, c.TurnID, "", 0, v); err != nil {
return err
}
- if err := t.pushCard(c, v); err != nil {
- return err
+ if pushes {
+ if err := t.pushCard(c, v); err != nil {
+ return err
+ }
}
// A hand-off's team card is the Assistant's too. A card in a job
// thread goes to the thread's stream, never the person's.
diff --git a/internal/equipo/chat/push.go b/internal/equipo/chat/push.go
index 3ee094b1..c4702c71 100644
--- a/internal/equipo/chat/push.go
+++ b/internal/equipo/chat/push.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
+ "slices"
"amadan.net/oficina/equipo/internal/equipo/push"
"amadan.net/oficina/equipo/internal/wire"
@@ -14,6 +15,12 @@ import (
// transaction of the change that pushes (push.Rules decides), for the
// person's registered devices that are still current. The outbox is
// written only while the instance has a push transport (SetPush).
+//
+// A push is never worth an engine write: the push work of a change runs
+// in a savepoint (pushSafe), and when it fails (a lookup, a seal, a reply
+// that cannot be read) only it is rolled back and logged, without tokens
+// or text, and the change commits without its pushes. Tokens and
+// payloads are sealed at rest (push.Box), so neither is ever SQL text.
// SetPush turns the outbox on: the serve path does, once it built a
// transport; a seed, a one-shot or a test that does not never writes it.
@@ -29,35 +36,50 @@ func (s *Store) wakePush() {
}
}
+// pushBox seals push's tokens and payloads with the instance key.
+func (s *Store) pushBox() push.Box {
+ return push.Box{Seal: s.authority.Seal, Open: s.authority.Open}
+}
+
// PushSender drains this store's outbox through tr.
func (s *Store) PushSender(tr push.Transport) *push.Sender {
- return &push.Sender{Transport: tr, Now: s.now, Check: s.pushCurrent,
+ return &push.Sender{Transport: tr, Now: s.now, Check: s.pushCurrent, Box: s.pushBox(),
Write: func(ctx context.Context, fn func(*gorm.DB) error) error {
return s.tx(ctx, func(t *txn) error { return fn(t.db) })
},
- Errorf: func(msg string, args ...any) {
- if l := s.logger.Load(); l != nil {
- l.Warn(msg, args...)
- }
- }}
+ Errorf: s.pushWarn}
+}
+
+func (s *Store) pushWarn(msg string, args ...any) {
+ if l := s.logger.Load(); l != nil {
+ l.Warn(msg, args...)
+ }
}
// pushCurrent: the person is an active member and the device credential
-// still valid (Authority.PushDevice). Anything else, a lookup error
-// included, is no push.
+// still valid (Authority.PushDevice). push.ErrGone when the person left
+// or the device was revoked; push.ErrNotCurrent when it cannot take a
+// push now; another error is a lookup that failed.
func (s *Store) pushCurrent(tx *gorm.DB, person, credential string) error {
var n int64
if err := tx.Raw("SELECT count(*) FROM members WHERE address = ? AND active = 1", person).Scan(&n).Error; err != nil {
return err
}
- if n != 1 || s.authority.PushDevice == nil {
- return ErrForbidden
+ if n != 1 {
+ return push.ErrGone
+ }
+ if s.authority.PushDevice == nil {
+ return push.ErrNotCurrent
}
return s.authority.PushDevice(tx, person, credential)
}
// RegisterPush is POST /api/v1/push-registrations: the device credential's
-// registration, replacing its earlier one. Audited without its tokens.
+// registration, replacing its earlier one and taking its tokens from any
+// other credential. Audited without its tokens. With the outbox on, the
+// device hears the badge at once, and what the person's open tasks show
+// now is remembered, so their outcomes push even when this is the first
+// device the person registered.
func (s *Store) RegisterPush(ctx context.Context, person, credential string, in wire.RegisterPush) (out wire.PushRegistration, err error) {
if credential == "" {
return out, ErrForbidden
@@ -72,17 +94,57 @@ func (s *Store) RegisterPush(ctx context.Context, person, credential string, in
if err := s.pushCurrent(t.db, person, credential); err != nil {
return ErrForbidden
}
- if out, err = push.Register(t.db, person, credential, in, t.now()); err != nil {
+ if out, err = push.Register(t.db, s.pushBox(), person, credential, in, t.now()); err != nil {
+ return err
+ }
+ if err := s.authority.Audit(t.db, person, "push.register", credential); err != nil {
return err
}
- return s.authority.Audit(t.db, person, "push.register", credential)
+ if !s.pushOn.Load() {
+ return nil
+ }
+ if err := t.pushSeed(person); err != nil {
+ return err
+ }
+ device, err := push.Device(t.db, person, credential)
+ if err != nil {
+ return err
+ }
+ _, err = t.enqueuePush(person, device, push.Badge())
+ return err
})
return out, err
}
+// pushSeed remembers what the person's open tasks show now, keeping what
+// their Live Activities were told.
+func (t *txn) pushSeed(person string) error {
+ var rows []taskRecord
+ if err := t.db.Where("creator = ? AND stage NOT IN ?", person, []string{wire.StageDone, wire.StageCancelled}).Order("created_at, id").Limit(wire.MaxTaskList).Find(&rows).Error; err != nil {
+ return err
+ }
+ for _, k := range rows {
+ v, err := t.taskView(k)
+ if err != nil {
+ return err
+ }
+ m, err := push.LoadMemory(t.db, person, k.ID)
+ if err != nil {
+ return err
+ }
+ if err := push.SaveMemory(t.db, person, k.ID, m.Remember(pushTaskOf(v, t.s.authority.Copy)), t.now()); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
// RegisterActivity is POST /api/v1/push-registrations/activities: a
-// running Live Activity's token for a task the person started that has
-// not ended.
+// running Live Activity's token for a task the person started. Once the
+// task ended it is taken only while a push for it still waits to go to
+// the device (its activity's end), which then goes at once; before, the
+// activity hears the task's whole state now, which it may have missed
+// while the server had no token for it.
func (s *Store) RegisterActivity(ctx context.Context, person, credential string, in wire.RegisterActivity) error {
if credential == "" {
return ErrForbidden
@@ -100,18 +162,82 @@ func (s *Store) RegisterActivity(ctx context.Context, person, credential string,
} else if err != nil {
return err
}
- if wire.FinalStage(k.Stage) {
- return ErrTaskEnded
+ ended := wire.FinalStage(k.Stage)
+ if ended {
+ waiting, err := push.Waiting(t.db, credential, k.ID)
+ if err != nil {
+ return err
+ }
+ if !waiting {
+ return ErrTaskEnded
+ }
}
- if err := push.RegisterActivity(t.db, person, credential, k.ID, in.Token, t.now()); errors.Is(err, push.ErrInvalid) {
+ if err := push.RegisterActivity(t.db, s.pushBox(), person, credential, k.ID, in.Token, t.now()); errors.Is(err, push.ErrInvalid) {
return ErrInvalid
} else if err != nil {
return err
}
- return s.authority.Audit(t.db, person, "push.activity", credential+" "+k.ID)
+ if err := s.authority.Audit(t.db, person, "push.activity", credential+" "+k.ID); err != nil {
+ return err
+ }
+ if ended {
+ t.pushed = true
+ return push.Hurry(t.db, credential, k.ID, t.now())
+ }
+ if !s.pushOn.Load() {
+ return nil
+ }
+ return t.pushCatchUp(person, credential, k)
})
}
+// pushCatchUp sends a running activity its task's whole state, to the
+// device whose token just arrived, and remembers the activity running.
+func (t *txn) pushCatchUp(person, credential string, k taskRecord) error {
+ v, err := t.taskView(k)
+ if err != nil {
+ return err
+ }
+ after := pushTaskOf(v, t.s.authority.Copy)
+ device, err := push.Device(t.db, person, credential)
+ if err != nil {
+ return err
+ }
+ if _, err := t.enqueuePush(person, device, push.CatchUp(after)); err != nil {
+ return err
+ }
+ m, err := push.LoadMemory(t.db, person, k.ID)
+ if err != nil {
+ return err
+ }
+ now := t.now()
+ next := m.Remember(after)
+ if !m.Live() {
+ next.Started, next.Ended = &now, false
+ }
+ return push.SaveMemory(t.db, person, k.ID, next, now)
+}
+
+// pushSafe runs a change's push work in a savepoint while the outbox is
+// on: its failure rolls back only the push work, is logged, and never
+// fails the change.
+func (t *txn) pushSafe(what string, fn func() error) error {
+ if !t.s.pushOn.Load() {
+ return nil
+ }
+ if err := t.db.SavePoint("push").Error; err != nil {
+ t.s.pushWarn("push skipped", "change", what, "err", err)
+ return nil
+ }
+ if err := fn(); err != nil {
+ if rerr := t.db.RollbackTo("push").Error; rerr != nil {
+ return rerr
+ }
+ t.s.pushWarn("push skipped", "change", what, "err", err)
+ }
+ return nil
+}
+
// pushDevices are the person's current registrations, none while the
// outbox is off.
func (t *txn) pushDevices(person string) ([]push.Registration, error) {
@@ -132,8 +258,11 @@ func (t *txn) pushDevices(person string) ([]push.Registration, error) {
}
// enqueuePush writes an intent's rows, one a device that can take it,
-// and reports how many.
+// and reports how many. A payload over APNs' limit is no push.
func (t *txn) enqueuePush(person string, devices []push.Registration, in push.Intent) (int, error) {
+ if len(devices) == 0 {
+ return 0, nil
+ }
badge := 0
if in.Kind == push.KindBadge {
n, err := t.needsYouCount(person)
@@ -144,6 +273,10 @@ func (t *txn) enqueuePush(person string, devices []push.Registration, in push.In
}
now := t.now()
raw, typ, err := push.Render(in, t.s.authority.Copy, badge, now)
+ if errors.Is(err, push.ErrTooLarge) {
+ t.s.pushWarn("push too large", "rule", in.Rule, "task", in.TaskID)
+ return 0, nil
+ }
if err != nil {
return 0, err
}
@@ -152,7 +285,7 @@ func (t *txn) enqueuePush(person string, devices []push.Registration, in push.In
target := push.TargetDevice
switch in.Kind {
case push.KindActivityStart:
- if d.Platform != wire.PlatformIOS || d.StartToken == "" {
+ if !startable(d) {
continue
}
target = push.TargetStart
@@ -161,13 +294,17 @@ func (t *txn) enqueuePush(person string, devices []push.Registration, in push.In
if err != nil {
return written, err
}
- if d.Platform != wire.PlatformIOS || !has && d.StartToken == "" {
+ // An update needs the activity's own token: without it the row
+ // would only be dropped, and the activity hears the whole state
+ // when its token arrives (pushCatchUp). An end waits a while
+ // for the token.
+ if d.Platform != wire.PlatformIOS || !has && (in.Kind == push.KindActivityUpdate || d.StartToken == "") {
continue
}
target = push.TargetActivity
}
- r := push.OutboxRecord{Person: person, Credential: d.Credential, Kind: in.Kind, Target: target, TaskID: in.TaskID, PushType: typ, Priority: in.Priority, CollapseID: in.CollapseID, Payload: string(raw), NextAt: now, CreatedAt: now, UpdatedAt: now}
- if err := push.Enqueue(t.db, r, in.Dedupe, in.Coalesce); err != nil {
+ r := push.OutboxRecord{Person: person, Credential: d.Credential, Kind: in.Kind, Target: target, TaskID: in.TaskID, PushType: typ, Priority: in.Priority, CollapseID: in.CollapseID, Dedupe: in.Dedupe, Payload: string(raw), NextAt: now, CreatedAt: now, UpdatedAt: now}
+ if err := push.Enqueue(t.db, t.s.pushBox(), r, in.Coalesce); err != nil {
return written, err
}
written++
@@ -178,6 +315,11 @@ func (t *txn) enqueuePush(person string, devices []push.Registration, in push.In
return written, nil
}
+// startable: the device can start a Live Activity by push.
+func startable(d push.Registration) bool {
+ return d.Platform == wire.PlatformIOS && d.StartToken != ""
+}
+
// needsYouCount is the person's Needs you count (GET /needs-you), for the
// badge. An error stays an error: never a zero.
func (t *txn) needsYouCount(person string) (int, error) {
@@ -198,28 +340,47 @@ func (t *txn) needsYouCount(person string) (int, error) {
return n, nil
}
-// pushIntents writes each intent for the person's devices.
-func (t *txn) pushIntents(person string, devices []push.Registration, intents []push.Intent) error {
+// pushIntents writes each intent for the person's devices, and reports
+// the rows written. A once-only intent is decided once for the person,
+// devices or not (push_once), and never again.
+func (t *txn) pushIntents(person string, devices []push.Registration, intents []push.Intent) (int, error) {
+ written := 0
for _, in := range intents {
- if _, err := t.enqueuePush(person, devices, in); err != nil {
- return err
+ if in.Dedupe != "" {
+ first, err := push.Once(t.db, person, in.Dedupe, t.now())
+ if err != nil {
+ return written, err
+ }
+ if !first {
+ continue
+ }
+ }
+ n, err := t.enqueuePush(person, devices, in)
+ if err != nil {
+ return written, err
}
+ written += n
}
- return nil
+ return written, nil
}
-// pushCard: a card that waits on its person opened.
+// pushCard: a card that waits on its person opened. Its alert is decided
+// even with no device registered, so a card opened before a device was
+// never alerts later.
func (t *txn) pushCard(c cardRecord, v wire.Card) error {
- devices, err := t.pushDevices(c.Person)
- if err != nil || len(devices) == 0 {
- return err
- }
- alerted, err := push.Alerted(t.db, c.Person, "card:"+c.ID)
- if err != nil {
+ return t.pushSafe("card", func() error {
+ card := push.Card{ID: c.ID, Kind: c.Kind, State: c.State, Lane: c.Lane, Question: v.Question, TaskID: c.TaskID, AccessFinal: v.Access != nil && wire.AccessFinal(v.Access.State)}
+ intents := push.Decide(push.Change{Kind: push.ChangeCard, Now: t.now(), Card: card})
+ if len(intents) == 0 {
+ return nil
+ }
+ devices, err := t.pushDevices(c.Person)
+ if err != nil {
+ return err
+ }
+ _, err = t.pushIntents(c.Person, devices, intents)
return err
- }
- card := push.Card{ID: c.ID, Kind: c.Kind, State: c.State, Lane: c.Lane, Question: v.Question, TaskID: c.TaskID, Alerted: alerted, AccessFinal: v.Access != nil && wire.AccessFinal(v.Access.State)}
- return t.pushIntents(c.Person, devices, push.Decide(push.Change{Kind: push.ChangeCard, Now: t.now(), Card: card}))
+ })
}
// pushReply: the coordinator's turn ended.
@@ -227,49 +388,57 @@ func (t *txn) pushReply(r turnRecord) error {
if r.State != wire.TurnReplied || r.ReplyID == "" {
return nil
}
- devices, err := t.pushDevices(r.Person)
- if err != nil || len(devices) == 0 {
- return err
- }
- var m messageRecord
- if err := t.db.Where("id = ? AND person = ?", r.ReplyID, r.Person).Take(&m).Error; err != nil {
+ return t.pushSafe("reply", func() error {
+ devices, err := t.pushDevices(r.Person)
+ if err != nil || len(devices) == 0 {
+ return err
+ }
+ var m messageRecord
+ if err := t.db.Where("id = ? AND person = ?", r.ReplyID, r.Person).Take(&m).Error; err != nil {
+ return err
+ }
+ reply := push.Reply{TurnID: r.ID, Lane: r.Lane, Kind: r.Kind, State: r.State, Text: m.Text}
+ _, err = t.pushIntents(r.Person, devices, push.Decide(push.Change{Kind: push.ChangeReply, Now: t.now(), Reply: reply, Streaming: t.s.hub.Streaming(r.Person)}))
return err
- }
- reply := push.Reply{TurnID: r.ID, Lane: r.Lane, Kind: r.Kind, State: r.State, Text: m.Text}
- return t.pushIntents(r.Person, devices, push.Decide(push.Change{Kind: push.ChangeReply, Now: t.now(), Reply: reply, Streaming: t.s.hub.Streaming(r.Person)}))
+ })
}
// pushTask: a task was written; its creator's devices hear what changed.
func (t *txn) pushTask(v wire.Task) error {
- devices, err := t.pushDevices(v.Creator)
- if err != nil || len(devices) == 0 {
- return err
- }
- before, err := push.LoadMemory(t.db, v.Creator, v.ID)
- if err != nil {
- return err
- }
- after := pushTaskOf(v, t.s.authority.Copy)
- now := t.now()
- next := before.Remember(after)
- for _, in := range push.Decide(push.Change{Kind: push.ChangeTask, Now: now, Before: before, After: after}) {
- if in.Kind == push.KindActivityStart {
- if err := t.pushMakeRoom(v.Creator, devices); err != nil {
- return err
- }
+ return t.pushSafe("task", func() error {
+ devices, err := t.pushDevices(v.Creator)
+ if err != nil || len(devices) == 0 {
+ return err
}
- n, err := t.enqueuePush(v.Creator, devices, in)
+ before, err := push.LoadMemory(t.db, v.Creator, v.ID)
if err != nil {
return err
}
- switch {
- case in.Kind == push.KindActivityStart && n > 0:
- next.Started, next.Ended = &now, false
- case in.Kind == push.KindActivityEnd:
- next.Ended = true
+ after := pushTaskOf(v, t.s.authority.Copy)
+ now := t.now()
+ next := before.Remember(after)
+ for _, in := range push.Decide(push.Change{Kind: push.ChangeTask, Now: now, Before: before, After: after}) {
+ if in.Kind == push.KindActivityStart {
+ if !slices.ContainsFunc(devices, startable) {
+ continue
+ }
+ if err := t.pushMakeRoom(v.Creator, devices); err != nil {
+ return err
+ }
+ }
+ n, err := t.pushIntents(v.Creator, devices, []push.Intent{in})
+ if err != nil {
+ return err
+ }
+ switch {
+ case in.Kind == push.KindActivityStart && n > 0:
+ next.Started, next.Ended = &now, false
+ case in.Kind == push.KindActivityEnd:
+ next.Ended = true
+ }
}
- }
- return push.SaveMemory(t.db, v.Creator, v.ID, next, now)
+ return push.SaveMemory(t.db, v.Creator, v.ID, next, now)
+ })
}
// pushMakeRoom ends the oldest Live Activities so a new one is at most
@@ -297,36 +466,37 @@ func (t *txn) pushMakeRoom(person string, devices []push.Registration) error {
return nil
}
-// pushLine: a running step of a task reported an activity line.
+// pushLine: a running step of a task reported an activity line. Only a
+// line some device was sent is remembered as told.
func (t *txn) pushLine(s stepRecord, line wire.ActivityLine) error {
- if !t.s.pushOn.Load() {
- return nil
- }
- var k taskRecord
- if err := t.db.Where("id = ?", s.TaskID).Take(&k).Error; err != nil {
- return err
- }
- devices, err := t.pushDevices(k.Creator)
- if err != nil || len(devices) == 0 {
- return err
- }
- before, err := push.LoadMemory(t.db, k.Creator, k.ID)
- if err != nil || !before.Live() {
- return err
- }
- after := before.Task(k.ID)
- after.Activity = activityLine(line, t.s.authority.Copy)
- now := t.now()
- intents := push.Decide(push.Change{Kind: push.ChangeLine, Now: now, Before: before, After: after})
- if len(intents) == 0 {
- return nil
- }
- if err := t.pushIntents(k.Creator, devices, intents); err != nil {
- return err
- }
- next := before.Remember(after)
- next.LineAt = &now
- return push.SaveMemory(t.db, k.Creator, k.ID, next, now)
+ return t.pushSafe("line", func() error {
+ var k taskRecord
+ if err := t.db.Where("id = ?", s.TaskID).Take(&k).Error; err != nil {
+ return err
+ }
+ devices, err := t.pushDevices(k.Creator)
+ if err != nil || len(devices) == 0 {
+ return err
+ }
+ before, err := push.LoadMemory(t.db, k.Creator, k.ID)
+ if err != nil || !before.Live() {
+ return err
+ }
+ after := before.Task(k.ID)
+ after.Activity = activityLine(line, t.s.authority.Copy)
+ now := t.now()
+ intents := push.Decide(push.Change{Kind: push.ChangeLine, Now: now, Before: before, After: after})
+ if len(intents) == 0 {
+ return nil
+ }
+ n, err := t.pushIntents(k.Creator, devices, intents)
+ if err != nil || n == 0 {
+ return err
+ }
+ next := before.Remember(after)
+ next.LineAt = &now
+ return push.SaveMemory(t.db, k.Creator, k.ID, next, now)
+ })
}
// pushTaskOf is a task as its Live Activity shows it: the step working
diff --git a/internal/equipo/chat/push_test.go b/internal/equipo/chat/push_test.go
index 882a9399..05e1cd49 100644
--- a/internal/equipo/chat/push_test.go
+++ b/internal/equipo/chat/push_test.go
@@ -2,6 +2,7 @@ package chat
import (
"context"
+ "encoding/base64"
"encoding/json"
"errors"
"strings"
@@ -17,6 +18,7 @@ import (
const (
pushDevice = "aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11"
pushStart = "bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22"
+ pushMac = "dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44"
)
// pushRig is a housekeeping rig with the outbox on, owner's iPhone
@@ -40,11 +42,35 @@ func newPushRig(t *testing.T) *pushRig {
r.audits = append(r.audits, actor+" "+kind+" "+record)
return nil
}
+ // Sealing as the instance key does, for the tests: what it seals never
+ // shows the token or the text.
+ r.s.authority.Seal = func(domain string, v any) (string, error) {
+ b, err := json.Marshal(v)
+ return domain + ":" + base64.StdEncoding.EncodeToString(b), err
+ }
+ r.s.authority.Open = func(domain, sealed string, v any) error {
+ raw, ok := strings.CutPrefix(sealed, domain+":")
+ if !ok {
+ return errors.New("sealed for another domain")
+ }
+ b, err := base64.StdEncoding.DecodeString(raw)
+ if err != nil {
+ return err
+ }
+ return json.Unmarshal(b, v)
+ }
r.s.SetPush(true)
r.register(hkOwner, "cr_phone", wire.RegisterPush{Token: pushDevice, Environment: wire.APNsProduction, Platform: wire.PlatformIOS, StartToken: pushStart})
+ r.clear()
return r
}
+// clear forgets the rows written so far (a registration's badge).
+func (r *pushRig) clear() {
+ r.t.Helper()
+ r.must(r.s.db.G.Where("1 = 1").Delete(&push.OutboxRecord{}).Error)
+}
+
func (r *pushRig) register(person, credential string, in wire.RegisterPush) {
r.t.Helper()
if _, err := r.s.RegisterPush(r.ctx, person, credential, in); err != nil {
@@ -52,15 +78,25 @@ func (r *pushRig) register(person, credential string, in wire.RegisterPush) {
}
}
-// outbox is the rows written, oldest first, as "kind rule-ish" strings:
-// kind and collapse ID.
+// outbox is the rows written, oldest first, their payloads opened.
func (r *pushRig) outbox() []push.OutboxRecord {
r.t.Helper()
var out []push.OutboxRecord
r.must(r.s.db.G.Order("created_at, kind, collapse_id").Find(&out).Error)
+ for i := range out {
+ p, err := r.s.pushBox().OpenPayload(out[i].Payload)
+ r.must(err)
+ out[i].Payload = p
+ }
return out
}
+// activity sends the running activity's own token for the task, as the
+// app does once the activity started.
+func (r *pushRig) activity(credential, task string) error {
+ return r.s.RegisterActivity(r.ctx, hkOwner, credential, wire.RegisterActivity{TaskID: task, Token: pushStart})
+}
+
func kinds(rows []push.OutboxRecord) string {
var out []string
for _, row := range rows {
@@ -152,15 +188,21 @@ func TestPushTaskLifecycle(t *testing.T) {
if s := p.APS.ContentState; s.TaskID != "tk1" || s.Specialist != wire.SpecialistEngineering || s.Activity != "work.activity.working" || s.Tone != wire.TonePositive {
t.Fatalf("content state %+v", s)
}
+ // The activity's own token arrives: it hears the whole state at once.
+ r.must(r.activity("cr_phone", "tk1"))
+ if rows = r.outbox(); kinds(rows[1:]) != push.KindActivityUpdate || rows[1].Priority != 10 || rows[1].Target != push.TargetActivity {
+ t.Fatalf("catch-up %+v", rows[1:])
+ }
r.stage(&k, wire.StageInReview)
- if rows = r.outbox(); kinds(rows[1:]) != push.KindActivityUpdate || rows[1].Priority != 5 || rows[1].Target != push.TargetActivity {
- t.Fatalf("update %+v", rows[1:])
+ if rows = r.outbox(); kinds(rows[2:]) != push.KindActivityUpdate || rows[2].Priority != 5 || rows[2].Target != push.TargetActivity {
+ t.Fatalf("update %+v", rows[2:])
}
r.step(&k, "s1", wire.SpecialistEngineering, wire.StepDone)
r.stage(&k, wire.StageReadyToMerge)
rows = r.outbox()
last := rows[len(rows)-2:]
- if kinds(last) != "activity_update badge" || last[0].Priority != 10 || last[1].Payload != `{"aps":{"badge":1}}` {
+ // Urgent and silent: a card, if any, is the one sound.
+ if kinds(last) != "activity_update badge" || last[0].Priority != 10 || strings.Contains(last[0].Payload, `"alert"`) || last[1].Payload != `{"aps":{"badge":1}}` {
t.Fatalf("needs you %+v", last)
}
r.stage(&k, wire.StageDone)
@@ -213,20 +255,28 @@ func TestPushActivityLineOnceAMinute(t *testing.T) {
return t.pushLine(s, wire.ActivityLine{Kind: wire.ActivityRead, Subject: subject, At: r.now})
}))
}
+ // No token yet: the line goes nowhere, and is not remembered as told.
+ line("README.md")
+ if kinds(r.outbox()) != push.KindActivityStart {
+ t.Fatalf("a line with no activity token %s", kinds(r.outbox()))
+ }
+ r.must(r.activity("cr_phone", "tk1"))
line("README.md")
r.now = r.now.Add(20 * time.Second)
line("main.go")
r.now = r.now.Add(time.Minute)
line("go.mod")
rows := r.outbox()
- if kinds(rows) != "activity_start activity_update activity_update" || !strings.Contains(rows[1].Payload, "work.activity.read") || !strings.Contains(rows[2].Payload, "go.mod") {
+ if kinds(rows) != "activity_start activity_update activity_update activity_update" || !strings.Contains(rows[2].Payload, "work.activity.read") || !strings.Contains(rows[3].Payload, "go.mod") {
t.Fatalf("lines %s", kinds(rows))
}
}
-func (r *pushRig) card(id, state string) cardRecord {
+func (r *pushRig) card(id, state string) cardRecord { return r.cardFor(hkOwner, id, state) }
+
+func (r *pushRig) cardFor(person, id, state string) cardRecord {
r.t.Helper()
- c := cardRecord{ID: id, Person: hkOwner, Kind: wire.CardQuestion, State: state, Question: "Which branch should the fix go on?", Options: `["main","release"]`, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now}
+ c := cardRecord{ID: id, Person: person, Kind: wire.CardQuestion, State: state, Question: "Which branch should the fix go on?", Options: `["main","release"]`, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now}
r.must(r.tx(func(t *txn) error {
if err := t.db.Create(&c).Error; err != nil {
return err
@@ -258,13 +308,35 @@ func TestPushCardOpensOnce(t *testing.T) {
if len(r.outbox()) != 1 {
t.Fatal("an answered card alerted")
}
+ // The mark outlives the outbox: pruned rows do not make it alert again.
+ r.must(r.s.db.G.Where("1 = 1").Delete(&push.OutboxRecord{}).Error)
+ r.must(r.tx(func(t *txn) error { return t.cardEvent(c) }))
+ if len(r.outbox()) != 0 {
+ t.Fatal("the card alerted again once its row was pruned")
+ }
+ // A card that opened before the person had a device never alerts.
+ r.cardFor(hkMember, "c3", wire.CardOpen)
+ r.register(hkMember, "cr_member", wire.RegisterPush{Token: pushMac, Environment: wire.APNsProduction, Platform: wire.PlatformMacOS})
+ r.must(r.tx(func(t *txn) error {
+ var c cardRecord
+ if err := t.db.Where("id = ?", "c3").Take(&c).Error; err != nil {
+ return err
+ }
+ return t.cardEvent(c)
+ }))
+ for _, row := range r.outbox() {
+ if row.Kind == push.KindAlert {
+ t.Fatal("a card older than the device alerted", row.CollapseID)
+ }
+ }
}
// TestPushNeverToRemovedOrRevoked: a person off the roster, or a device
// revoked, gets no row at all.
func TestPushNeverToRemovedOrRevoked(t *testing.T) {
r := newPushRig(t)
- r.register(hkOwner, "cr_mac", wire.RegisterPush{Token: pushDevice, Environment: wire.APNsProduction, Platform: wire.PlatformMacOS})
+ r.register(hkOwner, "cr_mac", wire.RegisterPush{Token: pushMac, Environment: wire.APNsProduction, Platform: wire.PlatformMacOS})
+ r.clear()
r.revoked["cr_mac"] = true
r.card("c1", wire.CardOpen)
rows := r.outbox()
@@ -352,8 +424,13 @@ func TestRegisterPushAuthority(t *testing.T) {
}
k := r.load("tk_mine")
r.stage(&k, wire.StageCancelled)
+ // Its end waits for the device: the token is still taken.
+ if err := act("tk_mine"); err != nil {
+ t.Fatal("an ended task whose end waits", err)
+ }
+ r.must(r.s.db.G.Model(&push.OutboxRecord{}).Where("1 = 1").Update("state", push.StateSent).Error)
if err := act("tk_mine"); !errors.Is(err, ErrTaskEnded) {
- t.Fatal("an ended task", err)
+ t.Fatal("an ended task with nothing waiting", err)
}
}
@@ -380,6 +457,8 @@ func TestSetAsideKeepsNeedsYou(t *testing.T) {
c := cardRecord{ID: "c1", Person: hkOwner, Kind: wire.CardQuestion, State: wire.CardOpen, TaskID: "tk1", Question: "Merge it?", Options: `["yes","no"]`, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now}
r.must(r.s.db.G.Create(&c).Error)
before := len(r.outbox())
+ // c1 opened with no alert decided (as one opened before push): setting
+ // it aside runs no push rule, so it does not alert now.
out, err := r.s.SetCardVisibility(r.ctx, hkOwner, "c1", wire.SetCardVisibility{Aside: true, Revision: 1})
if err != nil || !out.Aside || out.Revision != 1 {
t.Fatalf("aside %+v %v", out, err)
@@ -392,6 +471,9 @@ func TestSetAsideKeepsNeedsYou(t *testing.T) {
if row.Kind == push.KindBadge {
t.Fatal("setting aside moved the badge")
}
+ if row.Kind == push.KindAlert {
+ t.Fatal("setting aside alerted", row.CollapseID)
+ }
}
if out, err := r.s.SetCardVisibility(r.ctx, hkOwner, "c1", wire.SetCardVisibility{Aside: false, Revision: 7}); !errors.Is(err, ErrCardConflict) || out.ID != "c1" || !out.Aside {
t.Fatalf("stale %+v %v", out, err)
@@ -404,3 +486,153 @@ func TestSetAsideKeepsNeedsYou(t *testing.T) {
t.Fatal("another person's card", err)
}
}
+
+// TestPushTokenMovesToNewCredential: A signs out offline and B pairs on
+// the same phone. Its token is B's alone: A's card questions never reach
+// B's lock screen, and A's queued pushes go nowhere.
+func TestPushTokenMovesToNewCredential(t *testing.T) {
+ r := newPushRig(t)
+ r.card("c_before", wire.CardOpen)
+ r.register(hkMember, "cr_b", wire.RegisterPush{Token: pushDevice, Environment: wire.APNsProduction, Platform: wire.PlatformIOS, StartToken: pushStart})
+ r.card("c_a", wire.CardOpen)
+ r.cardFor(hkMember, "c_b", wire.CardOpen)
+ for _, row := range r.outbox() {
+ switch {
+ case row.Credential == "cr_phone" && row.State == push.StatePending:
+ t.Fatalf("A's push still waits for the phone: %+v", row)
+ case row.Person == hkOwner && row.Credential == "cr_b":
+ t.Fatalf("A's push went to B: %+v", row)
+ }
+ }
+ var regs []push.Registration
+ r.must(r.s.db.G.Find(&regs).Error)
+ if len(regs) != 1 || regs[0].Credential != "cr_b" || regs[0].Person != hkMember {
+ t.Fatalf("registrations %+v", regs)
+ }
+ got := map[string]bool{}
+ for _, row := range r.outbox() {
+ got[row.Credential+" "+row.CollapseID] = true
+ }
+ if !got["cr_b c_b"] {
+ t.Fatalf("B's card did not alert B: %v", got)
+ }
+}
+
+// TestPushActivityTokenAfterEnd: a short task cancelled before its
+// activity's token arrived still ends its activity: the token is taken
+// while the end waits, and the end goes at once. An update with no token
+// is never written, and the activity hears the whole state when its token
+// arrives.
+func TestPushActivityTokenAfterEnd(t *testing.T) {
+ r := newPushRig(t)
+ k := r.task("tk1", "Fix login", hkOwner)
+ r.step(&k, "s1", wire.SpecialistEngineering, wire.StepRunning)
+ r.stage(&k, wire.StageInReview)
+ if kinds(r.outbox()) != push.KindActivityStart {
+ t.Fatalf("an update with no token was written: %s", kinds(r.outbox()))
+ }
+ r.stage(&k, wire.StageCancelled)
+ var end push.OutboxRecord
+ r.must(r.s.db.G.Where("kind = ?", push.KindActivityEnd).Take(&end).Error)
+ r.must(r.s.db.G.Model(&end).Updates(map[string]any{"attempts": 3, "next_at": r.now.Add(time.Hour)}).Error)
+ if err := r.activity("cr_phone", "tk1"); err != nil {
+ t.Fatal("the end waits, yet the token was refused:", err)
+ }
+ r.must(r.s.db.G.Where("id = ?", end.ID).Take(&end).Error)
+ if end.State != push.StatePending || end.NextAt.After(r.now) {
+ t.Fatalf("the end did not go at once: %+v", end)
+ }
+ if has, err := push.HasActivity(r.s.db.G, "cr_phone", "tk1"); err != nil || !has {
+ t.Fatal("token not kept", err)
+ }
+
+ k2 := r.task("tk2", "Add search", hkOwner)
+ r.step(&k2, "s2", wire.SpecialistEngineering, wire.StepRunning)
+ r.stage(&k2, wire.StageInReview)
+ n := len(r.outbox())
+ r.must(r.activity("cr_phone", "tk2"))
+ rows := r.outbox()[n:]
+ if kinds(rows) != push.KindActivityUpdate || !strings.Contains(rows[0].Payload, `"stage":"in_review"`) || rows[0].Target != push.TargetActivity {
+ t.Fatalf("catch-up %+v", rows)
+ }
+}
+
+// TestPushFirstDeviceHearsOutcomes: a task already waiting on the person
+// when their first device registers sets the badge at once, and its merge
+// still pushes Done and the badge.
+func TestPushFirstDeviceHearsOutcomes(t *testing.T) {
+ r := newPushRig(t)
+ k := r.task("tk1", "Fix login", hkMember)
+ r.stage(&k, wire.StageReadyToMerge)
+ r.register(hkMember, "cr_m", wire.RegisterPush{Token: pushMac, Environment: wire.APNsProduction, Platform: wire.PlatformMacOS})
+ rows := r.outbox()
+ if len(rows) != 1 || rows[0].Credential != "cr_m" || rows[0].Payload != `{"aps":{"badge":1}}` {
+ t.Fatalf("registration badge %+v", rows)
+ }
+ r.clear()
+ r.stage(&k, wire.StageDone)
+ rows = r.outbox()
+ if kinds(rows) != "badge passive" || rows[0].Payload != `{"aps":{"badge":0}}` || !strings.Contains(rows[1].Payload, "push.task.done") {
+ t.Fatalf("outcome %s %+v", kinds(rows), rows)
+ }
+}
+
+// TestPushNeverFailsTheWrite: push bookkeeping that fails rolls back alone
+// and the change commits; nothing pushes.
+func TestPushNeverFailsTheWrite(t *testing.T) {
+ r := newPushRig(t)
+ k := r.task("tk1", "Fix login", hkOwner)
+ r.must(r.s.db.G.Exec("DROP TABLE push_tasks").Error)
+ r.step(&k, "s1", wire.SpecialistEngineering, wire.StepRunning)
+ if got := r.load("tk1"); got.Revision != k.Revision {
+ t.Fatalf("the task write did not commit: revision %d, want %d", got.Revision, k.Revision)
+ }
+ if len(r.outbox()) != 0 {
+ t.Fatal("a failed push left rows")
+ }
+ // A reply whose message cannot be read: the turn is still saved.
+ r.must(r.tx(func(t *txn) error {
+ turn := turnRecord{ID: "t1", Person: hkOwner, State: wire.TurnRunning, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now}
+ if err := t.db.Create(&turn).Error; err != nil {
+ return err
+ }
+ turn.State, turn.ReplyID = wire.TurnReplied, "m_missing"
+ return t.saveTurn(&turn)
+ }))
+ var turn turnRecord
+ r.must(r.s.db.G.Where("id = ?", "t1").Take(&turn).Error)
+ if turn.State != wire.TurnReplied {
+ t.Fatal("the turn was not saved")
+ }
+ // Push work that wrote before it failed (the card's once-only mark,
+ // then no outbox) is undone, and the card is still written.
+ r.must(r.s.db.G.Exec("DROP TABLE push_outbox").Error)
+ r.card("c1", wire.CardOpen)
+ if r.count("SELECT count(*) FROM chat_cards WHERE id = 'c1'") != 1 || r.count("SELECT count(*) FROM push_once") != 0 {
+ t.Fatal("a failed push kept its part, or lost the card")
+ }
+}
+
+// TestPushStartsOnlyWhereItCan: with no device that can start a Live
+// Activity (a Mac only), a dispatch ends no older activity to make room.
+func TestPushStartsOnlyWhereItCan(t *testing.T) {
+ r := newPushRig(t)
+ for _, id := range []string{"tk1", "tk2", "tk3"} {
+ k := r.task(id, "Task "+id, hkOwner)
+ r.step(&k, "s"+id, wire.SpecialistEngineering, wire.StepRunning)
+ }
+ r.must(r.s.db.G.Where("credential = ?", "cr_phone").Delete(&push.Registration{}).Error)
+ r.register(hkOwner, "cr_mac", wire.RegisterPush{Token: pushMac, Environment: wire.APNsProduction, Platform: wire.PlatformMacOS})
+ r.clear()
+ k := r.task("tk4", "Task tk4", hkOwner)
+ r.step(&k, "stk4", wire.SpecialistEngineering, wire.StepRunning)
+ for _, row := range r.outbox() {
+ if row.Kind == push.KindActivityEnd {
+ t.Fatalf("ended %s to make room for an activity that never starts", row.TaskID)
+ }
+ }
+ live, err := push.LiveTasks(r.s.db.G, hkOwner)
+ if err != nil || len(live) != 3 {
+ t.Fatalf("live %+v %v", live, err)
+ }
+}
diff --git a/internal/equipo/chat/roster.go b/internal/equipo/chat/roster.go
index a0230162..3d321efa 100644
--- a/internal/equipo/chat/roster.go
+++ b/internal/equipo/chat/roster.go
@@ -133,7 +133,8 @@ func (t *txn) setCardAside(person, id string, revision int64, aside bool) (c car
if err := s.authority.Audit(t.db, person, "card.visibility", id); err != nil {
return err
}
- return t.cardEvent(c)
+ // Setting aside is no news to the person's devices: no push rule.
+ return t.cardEventPush(c, false)
}()
}
diff --git a/internal/equipo/chat_wiring.go b/internal/equipo/chat_wiring.go
index b0d71238..f59bbf75 100644
--- a/internal/equipo/chat_wiring.go
+++ b/internal/equipo/chat_wiring.go
@@ -12,6 +12,7 @@ import (
"amadan.net/oficina/equipo/internal/equipo/assist"
"amadan.net/oficina/equipo/internal/equipo/chat"
"amadan.net/oficina/equipo/internal/equipo/personapi"
+ "amadan.net/oficina/equipo/internal/equipo/push"
"amadan.net/oficina/equipo/internal/wire"
"gorm.io/gorm"
)
@@ -45,11 +46,17 @@ func (s *Store) Chat() *chat.Store {
Audit: func(tx *gorm.DB, actor, kind, record string) error {
return appendAudit(tx, Actor{Address: actor}, kind, record)
},
- // A push goes only to a device credential still valid now.
+ // A push goes only to a device credential still valid now; only
+ // a revoked one (or its person signed out everywhere) is gone.
PushDevice: func(tx *gorm.DB, person, credential string) error {
- p, err := s.personDevices().VerifyAt(tx, credential, "")
- if err != nil || p.Address != person {
- return ErrForbidden
+ state, err := s.personDevices().PushState(tx, credential, person)
+ switch {
+ case err != nil:
+ return err
+ case state == personapi.PushGone:
+ return push.ErrGone
+ case state != personapi.PushCurrent:
+ return push.ErrNotCurrent
}
return nil
},
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index 48d18b23..384130d9 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -25,6 +25,7 @@ const (
copyLoggedPushPublic = "Unset EQUIPO_ALLOW_LOGGED_PUSH on a public origin. It is only allowed on loopback or staging." // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)
copyCarlosPushUnavailable = "CARLOS push submission is not available in this version of Equipo. Unset CARLOS_PUSH." // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)
+ copyPushBoth = "Set EQUIPO_ALLOW_LOGGED_PUSH or CARLOS_PUSH, not both." // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)
copyRunnerPending = "Waiting for you to approve this machine in your browser."
copyRunnerRateLimited = "Too many attempts. Wait before trying again."
@@ -2014,14 +2015,13 @@ var pageCopy = map[string]string{
"form.last-owner": copyLastOwner,
"form.account-label-exists": copyAccountLabelExists,
- "push.card.title": "Needs you", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)
- "push.card.body": "A decision is waiting for you.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)
- "push.reply.title": "Coordinator replied", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)
- "push.task.done": "Done.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)
- "push.task.cancelled": "Cancelled.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)
- "push.task.failed": "A step failed. Open the task to retry the step.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)
- "push.activity.started": "Work has started.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)
- "push.activity.needs_you": "Needs you.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)
+ "push.card.title": "Needs you", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)
+ "push.card.body": "A decision is waiting for you.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)
+ "push.reply.title": "Coordinator replied", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)
+ "push.task.done": "Done.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)
+ "push.task.cancelled": "Cancelled.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)
+ "push.task.failed": "A step failed. Open the task to retry the step.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)
+ "push.activity.started": "Work has started.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)
"nav.account": "Account",
"brand": copyBrand,
diff --git a/internal/equipo/mailer.go b/internal/equipo/mailer.go
index 4793d170..48cf6e76 100644
--- a/internal/equipo/mailer.go
+++ b/internal/equipo/mailer.go
@@ -38,8 +38,14 @@ func Mailer(cfg Config, logger *slog.Logger) (mail.Sender, error) {
// sends nothing. EQUIPO_ALLOW_LOGGED_PUSH (admitted by LoadConfig on
// loopback or staging only) logs every push; CARLOS_PUSH=submit is the
// CARLOS platform's push submission (push.FromCarlos, a seam until the
-// platform verb exists); neither is no push at all (nil, nil).
+// platform verb exists); both refuse boot; neither is no push at all
+// (nil, nil).
func Pusher(cfg Config, logger *slog.Logger, getenv func(string) string) (push.Transport, error) {
+ if cfg.AllowLoggedPush && getenv(push.CarlosPushEnv) != "" {
+ // Never one silently over the other.
+ //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go.
+ return nil, errors.New(copyPushBoth)
+ }
if cfg.AllowLoggedPush {
if cfg.validate() != nil {
//lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go.
diff --git a/internal/equipo/migrations/0095_push.sql b/internal/equipo/migrations/0095_push.sql
index 7d5b3c61..4cf9d522 100644
--- a/internal/equipo/migrations/0095_push.sql
+++ b/internal/equipo/migrations/0095_push.sql
@@ -1,7 +1,10 @@
-- Push for the native apps (slice 2): each paired device credential's
-- APNs registration, running Live Activities' update tokens, the outbox
--- the engine writes in the transaction of a change, and what each
--- person's devices were last told about a task they started.
+-- the engine writes in the transaction of a change, what each person's
+-- devices were last told about a task they started, and each once-only
+-- push decided for a person. Tokens and payloads are sealed. Cards open
+-- before push existed count as alerted: they opened before any device
+-- could hear of them.
CREATE TABLE push_registrations (credential text PRIMARY KEY, person text, token text, environment text, platform text, start_token text, created_at datetime, updated_at datetime);
CREATE INDEX push_registration_person ON push_registrations(person);
CREATE TABLE push_activities (credential text, task_id text, person text, token text, created_at datetime, PRIMARY KEY (credential, task_id));
@@ -12,3 +15,5 @@ CREATE INDEX push_outbox_dedupe ON push_outbox(dedupe);
CREATE INDEX push_outbox_credential ON push_outbox(credential);
CREATE INDEX push_outbox_person ON push_outbox(person);
CREATE TABLE push_tasks (person text, task_id text, title text, tone text, stage text, needs_you text, specialist text, step_id text, activity text, started_at datetime, ended numeric, line_at datetime, updated_at datetime, PRIMARY KEY (person, task_id));
+CREATE TABLE push_once (person text, key text, created_at datetime, PRIMARY KEY (person, key));
+INSERT INTO push_once (person, key, created_at) SELECT person, 'card:' || id, CURRENT_TIMESTAMP FROM chat_cards WHERE state IN ('open', 'ask');
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 0719da5f..9aa2f83f 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -745,3 +745,4 @@ CREATE INDEX push_outbox_dedupe ON push_outbox(dedupe);
CREATE INDEX push_outbox_credential ON push_outbox(credential);
CREATE INDEX push_outbox_person ON push_outbox(person);
CREATE TABLE push_tasks (person text, task_id text, title text, tone text, stage text, needs_you text, specialist text, step_id text, activity text, started_at datetime, ended numeric, line_at datetime, updated_at datetime, PRIMARY KEY (person, task_id));
+CREATE TABLE push_once (person text, key text, created_at datetime, PRIMARY KEY (person, key));
diff --git a/internal/equipo/migrations_test.go b/internal/equipo/migrations_test.go
index fca99a26..2df747e2 100644
--- a/internal/equipo/migrations_test.go
+++ b/internal/equipo/migrations_test.go
@@ -138,3 +138,49 @@ func TestAssistantLaneMigrationKeepsKeys(t *testing.T) {
t.Fatal("a second Coordinator message with a historical key")
}
}
+
+// Cards already waiting when push arrives opened before any device could
+// hear of them: 0095 marks them alerted, so a later write of one (setting
+// it aside included) never alerts it late. Others are not marked.
+func TestPushMigrationMarksOpenCards(t *testing.T) {
+ ctx := context.Background()
+ all := Schema.All()
+ at := -1
+ for i, m := range all {
+ if m.ID == "equipo/0095_push" {
+ at = i
+ }
+ }
+ if at < 0 {
+ t.Fatal("no 0095_push")
+ }
+ d, err := migrate.Replay(ctx, all[:at])
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer d.Close()
+ for id, state := range map[string]string{"c_open": "open", "c_ask": "ask", "c_answered": "answered"} {
+ if _, err = d.ExecContext(ctx, "INSERT INTO chat_cards(id, person, kind, state, revision) VALUES (?, 'ana@example.com', 'question', ?, 1)", id, state); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err = d.ExecContext(ctx, all[at].SQL); err != nil {
+ t.Fatal(err)
+ }
+ rows, err := d.QueryContext(ctx, "SELECT key FROM push_once WHERE person = 'ana@example.com' ORDER BY key")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rows.Close()
+ var keys []string
+ for rows.Next() {
+ var k string
+ if err := rows.Scan(&k); err != nil {
+ t.Fatal(err)
+ }
+ keys = append(keys, k)
+ }
+ if strings.Join(keys, " ") != "card:c_ask card:c_open" {
+ t.Fatalf("marked %v", keys)
+ }
+}
diff --git a/internal/equipo/personapi/devices.go b/internal/equipo/personapi/devices.go
index 9bc6d8d8..09db92ca 100644
--- a/internal/equipo/personapi/devices.go
+++ b/internal/equipo/personapi/devices.go
@@ -470,6 +470,43 @@ func (s *DeviceStore) VerifyAt(tx *gorm.DB, id, token string) (p PersonPrincipal
}
return PersonPrincipal{Address: row.Person, CredentialID: row.ID, SessionEpoch: row.SessionEpoch}, nil
}
+
+// What PushState says of a device credential, for a push to it.
+const (
+ PushCurrent = "current" // valid: it takes pushes
+ PushGone = "gone" // revoked, never exchanged, another person's or instance's, or signed out everywhere: never again
+ PushExpired = "expired" // its token expired: not now, but its registration stays
+)
+
+// PushState is VerifyAt for a push: it tells a device gone for good from
+// one only expired, and an error is a lookup that failed, never either.
+func (s *DeviceStore) PushState(tx *gorm.DB, id, person string) (string, error) {
+ var row DeviceRecord
+ if e := tx.Where("id=?", id).Take(&row).Error; errors.Is(e, gorm.ErrRecordNotFound) {
+ return PushGone, nil
+ } else if e != nil {
+ return "", e
+ }
+ instance, e := s.Instance(tx)
+ if e != nil {
+ return "", e
+ }
+ if instance != row.InstanceID || row.ExchangedAt == nil || row.RevokedAt != nil || row.Person != person {
+ return PushGone, nil
+ }
+ m, e := s.Member(tx, row.Person)
+ if e != nil {
+ return "", e
+ }
+ if !m.Active || row.SessionEpoch < m.SessionEpoch {
+ return PushGone, nil
+ }
+ if !s.Now().Before(row.TokenExpiresAt) {
+ return PushExpired, nil
+ }
+ return PushCurrent, nil
+}
+
func (s *DeviceStore) Verify(ctx context.Context, token string) (p PersonPrincipal, err error) {
err = s.Write(WithoutRequest(ctx), func(tx *gorm.DB) error {
var e error
diff --git a/internal/equipo/push/outcome_test.go b/internal/equipo/push/outcome_test.go
new file mode 100644
index 00000000..ce2a4b7d
--- /dev/null
+++ b/internal/equipo/push/outcome_test.go
@@ -0,0 +1,388 @@
+package push
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "log"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+ "gorm.io/gorm"
+ "gorm.io/gorm/logger"
+)
+
+var uuidShape = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`)
+
+// TestRowIDIsAnAPNsID: every row's ID, sent as apns-id, is a canonical
+// lowercase UUID (Apple answers 400 BadMessageId to anything else).
+func TestRowIDIsAnAPNsID(t *testing.T) {
+ seen := map[string]bool{}
+ for range 200 {
+ id := NewID()
+ if !uuidShape.MatchString(id) || seen[id] {
+ t.Fatalf("id %q", id)
+ }
+ seen[id] = true
+ }
+ r := newRig(t)
+ r.enqueue(KindAlert, TargetDevice, "c1", false)
+ if id := r.rows()[0].ID; !uuidShape.MatchString(id) {
+ t.Fatalf("row id %q", id)
+ }
+}
+
+// TestJudge: what each answer of the CARLOS verb (design §4.2) does to
+// its row.
+func TestJudge(t *testing.T) {
+ for name, c := range map[string]struct {
+ res Result
+ err error
+ want Verdict
+ }{
+ "delivered": {Result{Status: 200}, nil, Verdict{Act: ActSent}},
+ "no answer": {Result{}, errors.New("reset"), Verdict{Act: ActRetry, Wait: Backoff(3)}},
+ "Unregistered": {Result{Status: 410, Reason: ReasonUnregistered}, nil, Verdict{Act: ActGone}},
+ "ExpiredToken": {Result{Status: 410, Reason: ReasonExpiredToken}, nil, Verdict{Act: ActGone}},
+ "BadDeviceToken": {Result{Status: 400, Reason: ReasonBadDeviceToken}, nil, Verdict{Act: ActGone}},
+ "DeviceTokenNotForTopic": {Result{Status: 400, Reason: ReasonDeviceTokenNotForTopic}, nil, Verdict{Act: ActGone}},
+ "Apple throttles a device": {Result{Status: 429, Reason: "TooManyRequests"}, nil, Verdict{Act: ActRetry, Wait: Backoff(3), Device: true}},
+ "Apple 500": {Result{Status: 500}, nil, Verdict{Act: ActRetry, Wait: 4 * AppleRetry}},
+ "Apple 503": {Result{Status: 503}, nil, Verdict{Act: ActRetry, Wait: 4 * AppleRetry}},
+ "another Apple 4xx": {Result{Status: 400, Reason: "BadCollapseId"}, nil, Verdict{Act: ActFail}},
+ "BAD_REQUEST": {Result{Refused: 400, Code: "BAD_REQUEST"}, nil, Verdict{Act: ActFail}},
+ "PAYLOAD_TOO_LARGE": {Result{Refused: 400, Code: "PAYLOAD_TOO_LARGE"}, nil, Verdict{Act: ActFail}},
+ "401": {Result{Refused: 401}, nil, Verdict{Act: ActFail}},
+ "TOPIC_NOT_ALLOWED": {Result{Refused: 403, Code: "TOPIC_NOT_ALLOWED"}, nil, Verdict{Act: ActFail}},
+ "ENVIRONMENT_NOT_ARMED": {Result{Refused: 403, Code: "ENVIRONMENT_NOT_ARMED"}, nil, Verdict{Act: ActFail}},
+ "PAUSED": {Result{Refused: 429, Code: "PAUSED", RetryAfter: 300 * time.Second}, nil, Verdict{Act: ActHold, Wait: 300 * time.Second, Stop: true}},
+ "RATE": {Result{Refused: 429, Code: "RATE", RetryAfter: time.Second}, nil, Verdict{Act: ActHold, Wait: time.Second, Stop: true}},
+ "PUSHER_UNAVAILABLE": {Result{Refused: 503, Code: "PUSHER_UNAVAILABLE", RetryAfter: 5 * time.Second}, nil, Verdict{Act: ActHold, Wait: 5 * time.Second, Stop: true}},
+ "APNS_UNAVAILABLE": {Result{Refused: 503, Code: "APNS_UNAVAILABLE", RetryAfter: 60 * time.Second}, nil, Verdict{Act: ActHold, Wait: 60 * time.Second, Stop: true}},
+ "a platform 410 is not gone": {Result{Refused: 410, Code: "X"}, nil, Verdict{Act: ActFail}},
+ "a platform 503 without a code": {Result{Refused: 503, RetryAfter: 5 * time.Second}, nil, Verdict{Act: ActHold, Wait: 5 * time.Second, Stop: true}},
+ } {
+ if got := Judge(c.res, c.err, 2); got != c.want {
+ t.Errorf("%s: %+v, want %+v", name, got, c.want)
+ }
+ }
+ if Judge(Result{Status: 500}, nil, 0).Wait != AppleRetry {
+ t.Fatal("Apple's trouble is retried after 15 minutes first")
+ }
+}
+
+// carlos answers each send as the CARLOS verb would, through CarlosResult.
+func (r *rig) carlos(status int, retryAfter, body string) {
+ r.answer = func(Message) (Result, error) { return CarlosResult(status, retryAfter, []byte(body)) }
+}
+
+// TestSenderCarlosOutcomes: the sender acts on every CARLOS outcome. A
+// platform hold (PAUSED, RATE, PUSHER_UNAVAILABLE, APNS_UNAVAILABLE)
+// waits its Retry-After without spending an attempt and ends the pass;
+// a refusal fails the row; Apple throttling one device holds its other
+// rows; Apple's own trouble waits 15 minutes.
+func TestSenderCarlosOutcomes(t *testing.T) {
+ for code, wait := range map[string]time.Duration{"PAUSED": 300 * time.Second, "RATE": time.Second, "PUSHER_UNAVAILABLE": 5 * time.Second, "APNS_UNAVAILABLE": 60 * time.Second} {
+ r := newRig(t)
+ r.enqueue(KindAlert, TargetDevice, "c1", false)
+ r.enqueue(KindAlert, TargetDevice, "c2", false)
+ status := 429
+ if strings.HasSuffix(code, "UNAVAILABLE") {
+ status = 503
+ }
+ r.carlos(status, jsonInt(int64(wait/time.Second)), `{"code":"`+code+`"}`)
+ if r.drain() != 0 || len(r.sent) != 1 {
+ t.Fatalf("%s: the pass went on after a hold: %d sends", code, len(r.sent))
+ }
+ var row OutboxRecord
+ r.must(r.d.G.Where("id = ?", r.sent[0].ID).Take(&row).Error)
+ if row.State != StatePending || row.Attempts != 0 || !row.NextAt.Equal(at.Add(wait)) || row.Reason != code {
+ t.Fatalf("%s: row %+v", code, row)
+ }
+ }
+ for _, refusal := range []struct {
+ status int
+ body string
+ }{{400, `{"code":"BAD_REQUEST"}`}, {400, `{"code":"PAYLOAD_TOO_LARGE"}`}, {401, "unauthorized\n"}, {403, `{"code":"TOPIC_NOT_ALLOWED"}`}, {403, `{"code":"ENVIRONMENT_NOT_ARMED"}`}} {
+ r := newRig(t)
+ r.enqueue(KindAlert, TargetDevice, "c1", false)
+ r.carlos(refusal.status, "", refusal.body)
+ r.drain()
+ var n int64
+ r.d.G.Model(&Registration{}).Count(&n)
+ if row := r.rows()[0]; row.State != StateFailed || n != 1 {
+ t.Fatalf("%d %s: row %+v, registrations %d", refusal.status, refusal.body, row, n)
+ }
+ }
+
+ r := newRig(t)
+ r.enqueue(KindAlert, TargetDevice, "c1", false)
+ r.enqueue(KindAlert, TargetDevice, "c2", false)
+ r.carlos(200, "", `{"status":429,"apns_id":"x","reason":"TooManyRequests"}`)
+ r.must(r.d.G.Model(&OutboxRecord{}).Where("collapse_id = ?", "c2").Update("next_at", at.Add(time.Second)).Error)
+ r.drain()
+ for _, row := range r.rows() {
+ if row.State != StatePending || row.NextAt.Before(at.Add(Backoff(1))) {
+ t.Fatalf("Apple throttled the device but %s did not wait: %+v", row.CollapseID, row)
+ }
+ }
+
+ r = newRig(t)
+ r.enqueue(KindAlert, TargetDevice, "c1", false)
+ r.carlos(200, "", `{"status":503,"apns_id":"x","reason":"ServiceUnavailable"}`)
+ r.drain()
+ if row := r.rows()[0]; row.State != StatePending || !row.NextAt.Equal(at.Add(AppleRetry)) || row.Attempts != 1 {
+ t.Fatalf("Apple 503 %+v", row)
+ }
+
+ for _, body := range []string{`{"status":410,"apns_id":"x","reason":"ExpiredToken","timestamp":` + jsonInt(at.Add(time.Hour).UnixMilli()) + `}`, `{"status":400,"apns_id":"x","reason":"DeviceTokenNotForTopic"}`} {
+ r := newRig(t)
+ r.enqueue(KindAlert, TargetDevice, "c1", false)
+ r.carlos(200, "", body)
+ r.drain()
+ var n int64
+ r.d.G.Model(&Registration{}).Count(&n)
+ if n != 0 {
+ t.Fatalf("%s kept the registration", body)
+ }
+ }
+ // A 410 whose token Apple last knew before this registration: the
+ // registration is newer, and stays.
+ r = newRig(t)
+ r.enqueue(KindAlert, TargetDevice, "c1", false)
+ r.carlos(200, "", `{"status":410,"apns_id":"x","reason":"Unregistered","timestamp":`+jsonInt(at.Add(-time.Hour).UnixMilli())+`}`)
+ r.drain()
+ var n int64
+ r.d.G.Model(&Registration{}).Count(&n)
+ if n != 1 {
+ t.Fatal("a registration newer than Apple's 410 was deleted")
+ }
+}
+
+func jsonInt(n int64) string { b, _ := json.Marshal(n); return string(b) }
+
+// TestCarlosRequest: a message as the verb takes it (design §4.1): the
+// field names, apns_id the row's UUID, expiration in Unix seconds, the
+// payload a compact object, and nothing over the limits.
+func TestCarlosRequest(t *testing.T) {
+ m := Message{ID: NewID(), Token: devToken, Environment: wire.APNsProduction, Topic: Topic, PushType: TypeAlert, Priority: 10, CollapseID: "c1", Expiration: at, Payload: []byte("{\n \"aps\": {\"badge\": 3}\n}")}
+ raw, err := CarlosRequestOf(m)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got map[string]any
+ if err := json.Unmarshal(raw, &got); err != nil {
+ t.Fatal(err)
+ }
+ want := map[string]any{"device_token": devToken, "topic": Topic, "push_type": "alert", "priority": float64(10), "collapse_id": "c1", "expiration": float64(at.Unix()), "apns_id": m.ID, "environment": "production", "payload": map[string]any{"aps": map[string]any{"badge": float64(3)}}}
+ if g, _ := json.Marshal(got); string(g) != func() string { w, _ := json.Marshal(want); return string(w) }() {
+ t.Fatalf("request %s", raw)
+ }
+ if !bytes.Contains(raw, []byte(`"payload":{"aps":{"badge":3}}`)) {
+ t.Fatalf("payload not compacted: %s", raw)
+ }
+ // The limit is on the payload as sent, compacted: spaces do not count.
+ fits := `{"aps":{"alert":{"body":"` + strings.Repeat("x", MaxPayload-40) + `"}}}`
+ m.Payload = []byte(strings.ReplaceAll(fits, ":", " : "))
+ if raw, err := CarlosRequestOf(m); err != nil || !bytes.Contains(raw, []byte(fits)) {
+ t.Fatal("a payload that fits once compacted", err)
+ }
+ m.Payload = []byte(`{"aps":{"alert":{"body":"` + strings.Repeat("x", MaxPayload) + `"}}}`)
+ if _, err := CarlosRequestOf(m); !errors.Is(err, ErrTooLarge) {
+ t.Fatal("an oversized payload", err)
+ }
+ m.Payload = []byte(`["not an object"]`)
+ if _, err := CarlosRequestOf(m); err == nil {
+ t.Fatal("a payload that is not an object")
+ }
+}
+
+// TestCarlosResult: the verb's answers read back: Apple's answer on a
+// 200 (with a 410's timestamp in milliseconds), the platform's code and
+// Retry-After otherwise, a 401's plain text without a code.
+func TestCarlosResult(t *testing.T) {
+ r, err := CarlosResult(200, "", []byte(`{"status":410,"apns_id":"a1","reason":"Unregistered","timestamp":1763683200000}`))
+ if err != nil || r.Status != 410 || r.APNsID != "a1" || !r.Timestamp.Equal(time.UnixMilli(1763683200000)) || !r.Apple() || !r.Gone() {
+ t.Fatalf("Apple's 410 %+v %v", r, err)
+ }
+ r, err = CarlosResult(429, "300", []byte(`{"code":"PAUSED"}`))
+ if err != nil || r.Refused != 429 || r.Code != "PAUSED" || r.RetryAfter != 300*time.Second || r.Apple() {
+ t.Fatalf("PAUSED %+v %v", r, err)
+ }
+ if r, err = CarlosResult(401, "", []byte("unauthorized")); err != nil || r.Refused != 401 || r.Code != "" || r.Apple() {
+ t.Fatalf("401 %+v %v", r, err)
+ }
+ if _, err := CarlosResult(200, "", []byte("{}")); err == nil {
+ t.Fatal("a 200 without Apple's answer")
+ }
+}
+
+// TestSenderCheckOutcomes: only a device gone for good (revoked, its
+// person removed) loses its registration; one not current now (expired)
+// has the row dropped and stays registered; a failed lookup sends nothing
+// and keeps the row for a later pass.
+func TestSenderCheckOutcomes(t *testing.T) {
+ for name, c := range map[string]struct {
+ err error
+ state string
+ regs int64
+ }{
+ "gone": {ErrGone, StateDropped, 0},
+ "expired": {ErrNotCurrent, StateDropped, 1},
+ "lookup err": {errors.New("database is locked"), StatePending, 1},
+ } {
+ r := newRig(t)
+ r.enqueue(KindAlert, TargetDevice, "c1", false)
+ r.s.Check = func(*gorm.DB, string, string) error { return c.err }
+ r.drain()
+ var n int64
+ r.d.G.Model(&Registration{}).Count(&n)
+ if row := r.rows()[0]; len(r.sent) != 0 || row.State != c.state || n != c.regs {
+ t.Fatalf("%s: sent %d, row %+v, registrations %d", name, len(r.sent), row, n)
+ }
+ }
+}
+
+// TestSenderExpiredAndOversized: a row past its expiration is dropped
+// unsent; a payload over 4 KB is never sent.
+func TestSenderExpiredAndOversized(t *testing.T) {
+ r := newRig(t)
+ r.enqueue(KindActivityUpdate, TargetDevice, "", false)
+ r.now = at.Add(time.Hour)
+ r.drain()
+ if row := r.rows()[0]; len(r.sent) != 0 || row.State != StateDropped || row.Reason != "expired" {
+ t.Fatalf("expired %+v", row)
+ }
+ r = newRig(t)
+ sealed, err := testBox.seal(domainPayload, `{"aps":{"alert":{"body":"`+strings.Repeat("x", MaxPayload)+`"}}}`)
+ r.must(err)
+ r.must(r.d.G.Create(&OutboxRecord{ID: NewID(), Person: "p@example.com", Credential: "cr1", Kind: KindAlert, Target: TargetDevice, PushType: TypeAlert, Priority: 10, Payload: sealed, State: StatePending, NextAt: at, CreatedAt: at, UpdatedAt: at}).Error)
+ r.drain()
+ if row := r.rows()[0]; len(r.sent) != 0 || row.State != StateFailed || row.Reason != "payload_too_large" {
+ t.Fatalf("oversized %+v", row)
+ }
+ big := Intent{Kind: KindActivityUpdate, TaskID: "tk1", State: &wire.LiveActivityState{TaskID: "tk1", Activity: strings.Repeat("y", MaxPayload)}}
+ if _, _, err := Render(big, copyStub, 0, at); !errors.Is(err, ErrTooLarge) {
+ t.Fatal("Render wrote an oversized payload", err)
+ }
+ r.must(r.d.G.Transaction(func(tx *gorm.DB) error {
+ if err := Enqueue(tx, testBox, OutboxRecord{Credential: "cr1", Payload: strings.Repeat("z", MaxPayload+1)}, false); !errors.Is(err, ErrTooLarge) {
+ t.Error("Enqueue kept an oversized payload", err)
+ }
+ return nil
+ }))
+}
+
+// TestSenderTimeoutAndScrub: a send has the sender's deadline, and a
+// transport's error or answer never brings the token into a log or row.
+func TestSenderTimeoutAndScrub(t *testing.T) {
+ r := newRig(t)
+ r.enqueue(KindAlert, TargetDevice, "c1", false)
+ r.s.Timeout = 50 * time.Millisecond
+ var logged []string
+ r.s.Errorf = func(msg string, args ...any) {
+ for _, a := range args {
+ if e, ok := a.(error); ok {
+ logged = append(logged, e.Error())
+ }
+ }
+ }
+ r.s.Transport = transportFunc(func(ctx context.Context, m Message) (Result, error) {
+ deadline, ok := ctx.Deadline()
+ if !ok || time.Until(deadline) > 50*time.Millisecond {
+ t.Error("no send deadline")
+ }
+ <-ctx.Done()
+ return Result{Reason: "dial " + strings.ToUpper(m.Token)}, errors.New("POST https://api.push.apple.com/3/device/" + m.Token + ": " + ctx.Err().Error())
+ })
+ r.drain()
+ row := r.rows()[0]
+ if row.State != StatePending || row.Attempts != 1 || len(logged) != 1 {
+ t.Fatalf("row %+v, logged %v", row, logged)
+ }
+ if strings.Contains(strings.ToLower(logged[0]+row.Reason), devToken) || !strings.Contains(logged[0], "deadline exceeded") {
+ t.Fatalf("token reached the log or row: %q %q", logged[0], row.Reason)
+ }
+}
+
+// TestTokensNeverSQLText: registering, keeping an activity token,
+// writing a push and sending it never puts a token or a payload's text
+// into a statement, as the database's slow and failed query log would
+// print it; at rest they are sealed.
+func TestTokensNeverSQLText(t *testing.T) {
+ r := newRig(t)
+ var sql bytes.Buffer
+ logged := r.d.G.Session(&gorm.Session{Logger: logger.New(log.New(&sql, "", 0), logger.Config{LogLevel: logger.Info})})
+ r.s.Write = func(ctx context.Context, fn func(*gorm.DB) error) error {
+ return logged.WithContext(ctx).Transaction(fn)
+ }
+ const text = "Merge the login fix on main?"
+ r.must(logged.Transaction(func(tx *gorm.DB) error {
+ if _, err := Register(tx, testBox, "p@example.com", "cr1", wire.RegisterPush{Token: devToken, Environment: wire.APNsProduction, Platform: wire.PlatformIOS, StartToken: startToken}, at); err != nil {
+ return err
+ }
+ if err := RegisterActivity(tx, testBox, "p@example.com", "cr1", "tk1", actToken, at); err != nil {
+ return err
+ }
+ return Enqueue(tx, testBox, OutboxRecord{Person: "p@example.com", Credential: "cr1", Kind: KindAlert, Target: TargetDevice, PushType: TypeAlert, Priority: 10, Payload: `{"aps":{"alert":{"body":"` + text + `"}}}`, NextAt: at, CreatedAt: at, UpdatedAt: at}, false)
+ }))
+ if r.drain() != 1 || string(r.sent[0].Payload) != `{"aps":{"alert":{"body":"`+text+`"}}}` || r.sent[0].Token != devToken {
+ t.Fatalf("sent %+v", r.sent)
+ }
+ for _, secret := range []string{devToken, startToken, actToken, text} {
+ if strings.Contains(sql.String(), secret) {
+ t.Fatalf("%q is SQL text", secret)
+ }
+ }
+ if !strings.Contains(sql.String(), "push_outbox") {
+ t.Fatal("the statements were not captured")
+ }
+}
+
+// TestRegisterTakesTokens: a token another credential holds (the phone
+// signed out offline and paired again) leaves that credential: its
+// registration, what waits for it, and its activity tokens holding it.
+func TestRegisterTakesTokens(t *testing.T) {
+ r := newRig(t)
+ // A token that will not open (sealed under another key) stops nothing.
+ r.must(r.d.G.Create(&Registration{Credential: "cr_old", Person: "o@example.com", Token: "not sealed here", CreatedAt: at, UpdatedAt: at}).Error)
+ r.must(r.d.G.Transaction(func(tx *gorm.DB) error {
+ return RegisterActivity(tx, testBox, "p@example.com", "cr1", "tk1", actToken, at)
+ }))
+ r.enqueue(KindAlert, TargetDevice, "c1", false)
+ r.must(r.d.G.Transaction(func(tx *gorm.DB) error {
+ _, err := Register(tx, testBox, "q@example.com", "cr2", wire.RegisterPush{Token: startToken, Environment: wire.APNsProduction, Platform: wire.PlatformIOS}, at)
+ return err
+ }))
+ var regs []Registration
+ r.must(r.d.G.Find(&regs).Error)
+ if len(regs) != 2 || regs[0].Credential != "cr2" && regs[1].Credential != "cr2" || r.rows()[0].State != StateDropped {
+ t.Fatalf("cr1 kept the token: %+v", regs)
+ }
+ for _, reg := range regs {
+ if reg.Credential == "cr1" {
+ t.Fatal("cr1 kept the token")
+ }
+ }
+ // cr1 registers again with its own token and keeps an activity's;
+ // that activity token, registered by cr2, leaves cr1 alone.
+ r.must(r.d.G.Transaction(func(tx *gorm.DB) error {
+ if _, err := Register(tx, testBox, "p@example.com", "cr1", wire.RegisterPush{Token: devToken, Environment: wire.APNsProduction, Platform: wire.PlatformIOS}, at); err != nil {
+ return err
+ }
+ return RegisterActivity(tx, testBox, "p@example.com", "cr1", "tk1", actToken, at)
+ }))
+ r.must(r.d.G.Transaction(func(tx *gorm.DB) error {
+ return RegisterActivity(tx, testBox, "q@example.com", "cr2", "tk2", actToken, at)
+ }))
+ var acts []ActivityToken
+ r.must(r.d.G.Find(&acts).Error)
+ r.must(r.d.G.Find(&regs).Error)
+ if len(acts) != 1 || acts[0].Credential != "cr2" || len(regs) != 3 {
+ t.Fatalf("activity tokens %+v, registrations %d", acts, len(regs))
+ }
+}
diff --git a/internal/equipo/push/payload.go b/internal/equipo/push/payload.go
index 3901a901..f5de160d 100644
--- a/internal/equipo/push/payload.go
+++ b/internal/equipo/push/payload.go
@@ -91,6 +91,9 @@ func Render(in Intent, copy func(string) string, badge int, now time.Time) ([]by
}
}
raw, err := json.Marshal(p)
+ if err == nil && len(raw) > MaxPayload {
+ return nil, typ, ErrTooLarge
+ }
return raw, typ, err
}
diff --git a/internal/equipo/push/push.go b/internal/equipo/push/push.go
index 4d58782d..a20f6f57 100644
--- a/internal/equipo/push/push.go
+++ b/internal/equipo/push/push.go
@@ -42,8 +42,8 @@ const (
)
// Message is one push as the transport sends it. ID is the outbox row's,
-// stable across retries: the transport sends it as apns-id and as its
-// idempotency key, so a retried send is the same notification.
+// a canonical lowercase UUID stable across retries: the transport sends it
+// as apns-id, so a retried send is the same notification.
type Message struct {
ID string
Token string
@@ -56,35 +56,52 @@ type Message struct {
Payload []byte
}
-// Result is Apple's answer to one send: the HTTP status, the reason Apple
-// gave on a refusal (BadDeviceToken, Unregistered, ...) and the apns-id it
-// answered with.
+// Result is one send's answer. When Apple answered, Status is Apple's HTTP
+// status, Reason the reason it gave on a refusal (BadDeviceToken,
+// Unregistered, ...), APNsID the apns-id it answered with and Timestamp,
+// on a 410, when it last knew the token valid. When the platform refused
+// or could not reach Apple (CARLOS's non-200 answers), Refused is the
+// platform's HTTP status, Code its code (PAUSED, RATE, ...), and
+// RetryAfter its Retry-After.
type Result struct {
- Status int
- Reason string
- APNsID string
+ Status int
+ Reason string
+ APNsID string
+ Timestamp time.Time
+ Refused int
+ Code string
+ RetryAfter time.Duration
}
// Apple's reasons that mean the token is gone for good.
const (
- ReasonUnregistered = "Unregistered"
- ReasonBadDeviceToken = "BadDeviceToken"
+ ReasonUnregistered = "Unregistered"
+ ReasonExpiredToken = "ExpiredToken"
+ ReasonBadDeviceToken = "BadDeviceToken"
+ ReasonDeviceTokenNotForTopic = "DeviceTokenNotForTopic"
)
+// Apple reports whether Apple answered (the platform neither
+// refused the push nor failed to reach Apple).
+func (r Result) Apple() bool { return r.Refused == 0 && r.Code == "" }
+
// Gone reports whether Apple's answer means the token will never work
// again: the registration (or activity token) is deleted.
func (r Result) Gone() bool {
- return r.Status == 410 || r.Reason == ReasonUnregistered || r.Reason == ReasonBadDeviceToken
-}
-
-// Retryable reports whether the send should be tried again later: Apple
-// throttled it or failed on its side.
-func (r Result) Retryable() bool {
- return r.Status == 429 || r.Status >= 500
+ if !r.Apple() {
+ return false
+ }
+ switch r.Reason {
+ case ReasonUnregistered, ReasonExpiredToken, ReasonBadDeviceToken, ReasonDeviceTokenNotForTopic:
+ return true
+ }
+ return r.Status == 410
}
// Transport delivers one push. An error is a delivery that did not reach
-// Apple (retried); a Result is Apple's answer, whatever it was.
+// Apple or the platform (retried); a Result is their answer, whatever it
+// was. An error's text must never carry the token: the sender scrubs it
+// anyway before it is logged.
type Transport interface {
Send(ctx context.Context, m Message) (Result, error)
}
@@ -92,3 +109,61 @@ type Transport interface {
// ErrNoActivity: an activity update or end with no running activity's
// token on file yet.
var ErrNoActivity = errors.New("push: no activity token")
+
+// The device checks' answers (Sender.Check, the engine's own): ErrGone,
+// the device was revoked or its person removed, so its registration is
+// deleted; ErrNotCurrent, it cannot take a push now (its credential
+// expired) but stays registered. Any other error is a lookup that failed:
+// the row is tried again later.
+var (
+ ErrGone = errors.New("push: device revoked or person removed")
+ ErrNotCurrent = errors.New("push: device not current")
+)
+
+// Box seals the tokens and payloads push keeps at rest, with the instance
+// key (Authority.Seal and Open), so neither reaches SQL text, and so
+// neither reaches the database's slow or failed query log.
+type Box struct {
+ Seal func(domain string, v any) (string, error)
+ Open func(domain, sealed string, v any) error
+}
+
+// Sealing domains.
+const (
+ domainToken = "push.token"
+ domainPayload = "push.payload"
+)
+
+func (b Box) seal(domain, v string) (string, error) {
+ if v == "" {
+ return "", nil
+ }
+ if b.Seal == nil {
+ return "", ErrNoBox
+ }
+ return b.Seal(domain, v)
+}
+
+func (b Box) open(domain, sealed string) (string, error) {
+ if sealed == "" {
+ return "", nil
+ }
+ if b.Open == nil {
+ return "", ErrNoBox
+ }
+ var v string
+ err := b.Open(domain, sealed, &v)
+ return v, err
+}
+
+// OpenPayload is a row's payload as sent.
+func (b Box) OpenPayload(sealed string) (string, error) { return b.open(domainPayload, sealed) }
+
+// ErrNoBox: push has no instance key to seal with; nothing is kept.
+var ErrNoBox = errors.New("push: no sealing")
+
+// MaxPayload is APNs' (and the CARLOS verb's) limit on a payload, minified.
+const MaxPayload = 4096
+
+// ErrTooLarge is a payload over MaxPayload: it is never written or sent.
+var ErrTooLarge = errors.New("push: payload too large")
diff --git a/internal/equipo/push/rules.go b/internal/equipo/push/rules.go
index 902c2ef8..34703b24 100644
--- a/internal/equipo/push/rules.go
+++ b/internal/equipo/push/rules.go
@@ -32,13 +32,12 @@ type Change struct {
After Task
}
-// Card is a card as the rules read it. Alerted: this card already pushed
-// its alert to the person (it opens once).
+// Card is a card as the rules read it. It alerts once in its life: its
+// alert's once-only key (Dedupe) is decided once for the person.
type Card struct {
ID, Kind, State, Lane, Question, TaskID string
// AccessFinal: an access card whose request already ended.
AccessFinal bool
- Alerted bool
}
// Reply is a saved turn and its reply's text.
@@ -82,7 +81,8 @@ func (m Memory) Remember(k Task) Memory {
func (m Memory) Live() bool { return m.Started != nil && !m.Ended }
// Intent is one push a rule asks for: its kind, priority and collapse ID,
-// a once-only key (Dedupe) or Coalesce (a newer one replaces one not yet
+// a once-only key (Dedupe: the push is decided once for the person, ever)
+// or Coalesce (a newer one replaces one not yet
// sent), its words (literal Title and Body, else copy keys), where a tap
// goes (Data), and a Live Activity's state.
type Intent struct {
@@ -121,7 +121,7 @@ type Rule struct {
var Rules = []Rule{
// A card that waits on the person opens: an alert, collapsed by card.
{"card_opens", func(c Change) bool {
- return c.Kind == ChangeCard && c.Card.Lane == wire.LaneCoordinator && waits(c.Card) && !c.Card.Alerted
+ return c.Kind == ChangeCard && c.Card.Lane == wire.LaneCoordinator && waits(c.Card)
}, func(c Change) Intent {
in := Intent{Kind: KindAlert, Priority: 10, CollapseID: c.Card.ID, Dedupe: "card:" + c.Card.ID, TitleKey: "push.card.title", Body: Clip(c.Card.Question), Category: CategoryNeedsYou, Data: wire.PushData{Kind: wire.PushCard, CardID: c.Card.ID, TaskID: c.Card.TaskID}}
if in.Body == "" {
@@ -155,7 +155,7 @@ var Rules = []Rule{
{"badge", func(c Change) bool {
return c.Kind == ChangeTask && c.Before.Seen && c.Before.NeedsYou != c.After.NeedsYou
}, func(c Change) Intent {
- return Intent{Kind: KindBadge, Priority: 5, CollapseID: "badge", Coalesce: true, Data: wire.PushData{Kind: wire.PushBadge}}
+ return Badge()
}},
// It was dispatched: its Live Activity starts, by push-to-start.
{"activity_start", func(c Change) bool {
@@ -163,15 +163,17 @@ var Rules = []Rule{
}, func(c Change) Intent {
return Intent{Kind: KindActivityStart, Priority: 10, TaskID: c.After.ID, Title: Clip(c.After.Title), BodyKey: "push.activity.started", State: state(c.After, "")}
}},
- // Its stage, step or needs-you changed: an update, urgent and with an
- // alert when it now needs the person.
+ // Its stage, step or needs-you changed: an update, urgent when it now
+ // needs the person. Never with an alert: what needs the person sounds
+ // once, by its card's alert (or a failed step's passive one), not
+ // again on the Lock Screen's activity.
{"activity_update", func(c Change) bool {
b, a := c.Before, c.After
return c.Kind == ChangeTask && b.Live() && !a.Final() && (b.Stage != a.Stage || b.StepID != a.StepID || b.Specialist != a.Specialist || b.NeedsYou != a.NeedsYou)
}, func(c Change) Intent {
in := Intent{Kind: KindActivityUpdate, Priority: 5, TaskID: c.After.ID, State: state(c.After, "")}
if c.After.NeedsYou != "" && c.After.NeedsYou != c.Before.NeedsYou {
- in.Priority, in.Title, in.BodyKey = 10, Clip(c.After.Title), "push.activity.needs_you"
+ in.Priority = 10
}
return in
}},
@@ -203,6 +205,17 @@ func Decide(c Change) []Intent {
return out
}
+// Badge is the person's Needs you count, the newest replacing any unsent.
+func Badge() Intent {
+ return Intent{Rule: "badge", Kind: KindBadge, Priority: 5, CollapseID: "badge", Coalesce: true, Data: wire.PushData{Kind: wire.PushBadge}}
+}
+
+// CatchUp is a running activity's whole state, sent when its own token
+// arrives: what it missed while the server had no token for it.
+func CatchUp(k Task) Intent {
+ return Intent{Rule: "activity_token", Kind: KindActivityUpdate, Priority: 10, TaskID: k.ID, State: state(k, "")}
+}
+
// Replace ends the Live Activity of a task to make room for a newer one.
func Replace(k Task) Intent {
return Intent{Rule: "activity_cap", Kind: KindActivityEnd, Priority: 5, TaskID: k.ID, State: state(k, wire.PushOutcomeReplaced)}
diff --git a/internal/equipo/push/rules_test.go b/internal/equipo/push/rules_test.go
index 5e4419a9..f389eb68 100644
--- a/internal/equipo/push/rules_test.go
+++ b/internal/equipo/push/rules_test.go
@@ -30,8 +30,9 @@ func only(t *testing.T, c Change, want ...string) []Intent {
func started() *time.Time { s := at.Add(-time.Hour); return &s }
// TestRuleCardOpens: a card that waits on the person alerts once, by its
-// card, urgently, with its question; receipts, other lanes, ended access
-// requests, answered cards and cards already alerted do not.
+// card, urgently, with its question (its key decided once for the
+// person); receipts, other lanes, ended access requests and answered
+// cards do not.
func TestRuleCardOpens(t *testing.T) {
open := Card{ID: "c1", Kind: wire.CardMerge, State: wire.CardOpen, Question: "Merge the login fix?", TaskID: "tk1"}
in := only(t, Change{Kind: ChangeCard, Card: open}, "card_opens")[0]
@@ -56,7 +57,6 @@ func TestRuleCardOpens(t *testing.T) {
"assistant": {ID: "c", Kind: wire.CardMerge, State: wire.CardOpen, Lane: wire.LaneAssistant},
"job thread": {ID: "c", Kind: wire.CardMerge, State: wire.CardOpen, Lane: wire.JobLane("h1")},
"access done": {ID: "c", Kind: wire.CardAccess, State: wire.CardOpen, AccessFinal: true},
- "alerted": {ID: "c", Kind: wire.CardMerge, State: wire.CardOpen, Alerted: true},
} {
if got := rules(Change{Kind: ChangeCard, Card: c}); len(got) != 0 {
t.Errorf("%s pushed %v", name, got)
@@ -138,7 +138,8 @@ func TestRuleTaskLifecycle(t *testing.T) {
if got[0].Kind != KindBadge || got[0].CollapseID != "badge" || !got[0].Coalesce {
t.Fatalf("badge %+v", got[0])
}
- if in := got[1]; in.Priority != 10 || in.BodyKey != "push.activity.needs_you" || in.State.NeedsYou != wire.NeedsMerge || in.State.Tone != wire.ToneWarning {
+ // Urgent but silent: the card's alert is the one sound.
+ if in := got[1]; in.Priority != 10 || in.Title != "" || in.TitleKey != "" || in.BodyKey != "" || in.State.NeedsYou != wire.NeedsMerge || in.State.Tone != wire.ToneWarning {
t.Fatalf("needs you update %+v", in)
}
diff --git a/internal/equipo/push/sender.go b/internal/equipo/push/sender.go
index 1a221064..479ebe8a 100644
--- a/internal/equipo/push/sender.go
+++ b/internal/equipo/push/sender.go
@@ -3,6 +3,7 @@ package push
import (
"context"
"errors"
+ "strings"
"time"
"gorm.io/gorm"
@@ -10,25 +11,32 @@ import (
// Sender drains the outbox through a Transport. Write runs one write
// transaction; Check re-checks, inside it, that the person is on the
-// roster and the device credential is still valid (an error: never send).
+// roster and the device credential is still valid: nil, ErrGone (the
+// registration is deleted), ErrNotCurrent (the row is dropped, the
+// registration kept) or a lookup error (the row is tried again later).
type Sender struct {
Write func(context.Context, func(*gorm.DB) error) error
Transport Transport
Check func(tx *gorm.DB, person, credential string) error
+ Box Box
Now func() time.Time
+ // Timeout bounds one send; zero is SendTimeout.
+ Timeout time.Duration
// Errorf reports what a pass could not do; never a token or payload.
Errorf func(msg string, args ...any)
}
-// Sending limits: rows a pass reads, how long a claim holds, the retry
-// backoff and the attempts before a row fails, and how long ended rows
-// are kept (a card's once-only alert key with them).
+// Sending limits: rows a pass reads, how long a claim holds, one send's
+// deadline, the retry backoff and the attempts before a row fails, Apple's
+// own trouble's first wait, and how long ended rows are kept.
const (
PassSize = 50
Lease = time.Minute
+ SendTimeout = 30 * time.Second
FirstRetry = 5 * time.Second
MaxRetry = 10 * time.Minute
MaxAttempts = 8
+ AppleRetry = 15 * time.Minute
Keep = 7 * 24 * time.Hour
)
@@ -41,6 +49,53 @@ func Backoff(n int) time.Duration {
return min(d, MaxRetry)
}
+// What the sender does with a row after a send.
+const (
+ ActSent = "sent" // Apple accepted it
+ ActRetry = "retry" // try again after Wait, an attempt counted
+ ActHold = "hold" // the platform asked to wait Wait; not an attempt
+ ActGone = "gone" // Apple says the token is gone: forget it, fail
+ ActFail = "fail" // never retried: a bug in the request or a refusal
+)
+
+// Verdict is what a send's answer means for its row: the action, the
+// wait before the next try, whether the device's other rows wait too
+// (Apple throttling that device), and whether the pass stops (the
+// platform is paused, over its rate or unavailable: every other row would
+// be refused the same).
+type Verdict struct {
+ Act string
+ Wait time.Duration
+ Device bool
+ Stop bool
+}
+
+// Judge reads one send's answer (the CARLOS verb's, platform-push-
+// submission design §4.2), n being the attempts already made.
+func Judge(res Result, err error, n int) Verdict {
+ switch {
+ case err != nil:
+ return Verdict{Act: ActRetry, Wait: Backoff(n + 1)}
+ case !res.Apple():
+ if res.Refused == 429 || res.Refused == 503 {
+ return Verdict{Act: ActHold, Wait: max(res.RetryAfter, time.Second), Stop: true}
+ }
+ // 400 BAD_REQUEST or PAYLOAD_TOO_LARGE, 401, 403 TOPIC_NOT_ALLOWED
+ // or ENVIRONMENT_NOT_ARMED: retrying sends the same refusal.
+ return Verdict{Act: ActFail}
+ case res.Status >= 200 && res.Status < 300:
+ return Verdict{Act: ActSent}
+ case res.Gone():
+ return Verdict{Act: ActGone}
+ case res.Status == 429:
+ return Verdict{Act: ActRetry, Wait: Backoff(n + 1), Device: true}
+ case res.Status >= 500:
+ // Apple's guidance: not at once, after 15 minutes, then backoff.
+ return Verdict{Act: ActRetry, Wait: AppleRetry << min(n, 3)}
+ }
+ return Verdict{Act: ActFail}
+}
+
// Drain sends every due row once, and reports how many Apple accepted.
func (s *Sender) Drain(ctx context.Context) (sent int, err error) {
now := s.Now()
@@ -58,88 +113,142 @@ func (s *Sender) Drain(ctx context.Context) (sent int, err error) {
if ctx.Err() != nil {
return sent, ctx.Err()
}
- ok, err := s.one(ctx, r)
+ v, err := s.one(ctx, r)
if err != nil {
s.errorf("push not sent", "id", r.ID, "err", err)
- continue
}
- if ok {
+ if v.Act == ActSent {
sent++
}
+ if v.Stop {
+ break
+ }
}
return sent, nil
}
// one claims a row, sends it and records the answer.
-func (s *Sender) one(ctx context.Context, r OutboxRecord) (bool, error) {
+func (s *Sender) one(ctx context.Context, r OutboxRecord) (Verdict, error) {
var m Message
claimed := false
err := s.Write(ctx, func(tx *gorm.DB) error {
now := s.Now()
- lease := now.Add(Lease)
- res := tx.Model(&OutboxRecord{}).Where("id = ? AND state = ? AND (lease_until IS NULL OR lease_until < ?)", r.ID, StatePending, now).Select("lease_until").Updates(map[string]any{"lease_until": lease})
+ res := tx.Model(&OutboxRecord{}).Where("id = ? AND state = ? AND (lease_until IS NULL OR lease_until < ?)", r.ID, StatePending, now).Select("lease_until").Updates(map[string]any{"lease_until": now.Add(Lease)})
if res.Error != nil || res.RowsAffected != 1 {
return res.Error
}
+ if !now.Before(Expiration(r.Kind, r.CreatedAt)) {
+ return finish(tx, r.ID, StateDropped, Result{Reason: "expired"}, now)
+ }
if err := s.Check(tx, r.Person, r.Credential); err != nil {
- // Removed or revoked: never sent, and the device forgotten.
- if err := ForgetCredential(tx, r.Credential); err != nil {
- return err
+ switch {
+ case errors.Is(err, ErrGone):
+ // Revoked or removed: never sent, and the device forgotten.
+ if err := ForgetCredential(tx, r.Credential); err != nil {
+ return err
+ }
+ return finish(tx, r.ID, StateDropped, Result{Reason: "not_current"}, now)
+ case errors.Is(err, ErrNotCurrent):
+ return finish(tx, r.ID, StateDropped, Result{Reason: "not_current"}, now)
}
- return finish(tx, r.ID, StateDropped, Result{Reason: "not_current"}, now)
+ // A lookup failed: the claim lapses and a later pass tries.
+ return err
}
token, env, err := s.token(tx, r)
if errors.Is(err, ErrNoActivity) {
if r.Kind == KindActivityEnd && r.Attempts+1 < MaxAttempts {
// The app may not have sent the activity's token yet.
- return retry(tx, r, now, Result{Reason: "no_token"})
+ return retry(tx, r, now, Backoff(r.Attempts+1), true, Result{Reason: "no_token"})
}
return finish(tx, r.ID, StateDropped, Result{Reason: "no_token"}, now)
}
if err != nil {
return err
}
+ payload, err := s.Box.OpenPayload(r.Payload)
+ if err != nil {
+ return err
+ }
+ if len(payload) > MaxPayload {
+ return finish(tx, r.ID, StateFailed, Result{Reason: "payload_too_large"}, now)
+ }
claimed = true
- m = Message{ID: r.ID, Token: token, Environment: env, Topic: TopicFor(r.PushType), PushType: r.PushType, Priority: r.Priority, CollapseID: r.CollapseID, Expiration: Expiration(r.Kind, r.CreatedAt), Payload: []byte(r.Payload)}
+ m = Message{ID: r.ID, Token: token, Environment: env, Topic: TopicFor(r.PushType), PushType: r.PushType, Priority: r.Priority, CollapseID: r.CollapseID, Expiration: Expiration(r.Kind, r.CreatedAt), Payload: []byte(payload)}
return nil
})
if err != nil || !claimed {
- return false, err
+ return Verdict{}, err
+ }
+ timeout := s.Timeout
+ if timeout <= 0 {
+ timeout = SendTimeout
}
- result, sendErr := s.Transport.Send(ctx, m)
- ok := false
+ sendCtx, cancel := context.WithTimeout(ctx, timeout)
+ result, sendErr := s.Transport.Send(sendCtx, m)
+ cancel()
+ if sendErr != nil {
+ sendErr = scrubbed(sendErr, m.Token)
+ }
+ result.Reason = scrub(result.Reason, m.Token)
+ result.Code = scrub(result.Code, m.Token)
+ v := Judge(result, sendErr, r.Attempts)
err = s.Write(context.WithoutCancel(ctx), func(tx *gorm.DB) error {
now := s.Now()
- switch {
- case sendErr != nil || result.Retryable():
+ switch v.Act {
+ case ActHold:
+ return retry(tx, r, now, v.Wait, false, result)
+ case ActRetry:
if r.Attempts+1 >= MaxAttempts {
return finish(tx, r.ID, StateFailed, result, now)
}
- return retry(tx, r, now, result)
- case result.Gone():
- if err := s.forgetToken(tx, r); err != nil {
+ if v.Device {
+ // Apple throttles this device: its other rows wait too.
+ if err := tx.Model(&OutboxRecord{}).Where("credential = ? AND state = ? AND lease_until IS NULL AND next_at < ?", r.Credential, StatePending, now.Add(v.Wait)).Select("next_at").Updates(map[string]any{"next_at": now.Add(v.Wait)}).Error; err != nil {
+ return err
+ }
+ }
+ return retry(tx, r, now, v.Wait, true, result)
+ case ActGone:
+ if err := s.forgetToken(tx, r, result.Timestamp); err != nil {
return err
}
return finish(tx, r.ID, StateFailed, result, now)
- case result.Status >= 200 && result.Status < 300:
- ok = true
+ case ActSent:
if r.Kind == KindActivityEnd {
if err := tx.Where("credential = ? AND task_id = ?", r.Credential, r.TaskID).Delete(&ActivityToken{}).Error; err != nil {
return err
}
}
return finish(tx, r.ID, StateSent, result, now)
- default:
- return finish(tx, r.ID, StateFailed, result, now)
}
+ return finish(tx, r.ID, StateFailed, result, now)
})
if sendErr != nil && err == nil {
err = sendErr
}
- return ok, err
+ return v, err
+}
+
+// scrub takes a token out of text a transport gave back.
+func scrub(text, token string) string {
+ if token == "" || text == "" {
+ return text
+ }
+ i := strings.Index(strings.ToLower(text), strings.ToLower(token))
+ for i >= 0 {
+ text = text[:i] + "[token]" + text[i+len(token):]
+ i = strings.Index(strings.ToLower(text), strings.ToLower(token))
+ }
+ return text
+}
+
+// scrubbed is a transport's error with the token taken out of its text;
+// only the text survives, never the error's own fields.
+func scrubbed(err error, token string) error {
+ return errors.New(scrub(err.Error(), token))
}
-// token is the row's token as the device registered it now.
+// token is the row's token as the device registered it now, opened.
func (s *Sender) token(tx *gorm.DB, r OutboxRecord) (token, env string, err error) {
var reg Registration
if err := tx.Where("credential = ? AND person = ?", r.Credential, r.Person).Take(&reg).Error; err != nil {
@@ -148,42 +257,69 @@ func (s *Sender) token(tx *gorm.DB, r OutboxRecord) (token, env string, err erro
}
return "", "", err
}
+ sealed := reg.Token
switch r.Target {
case TargetStart:
if reg.StartToken == "" {
return "", "", ErrNoActivity
}
- return reg.StartToken, reg.Environment, nil
+ sealed = reg.StartToken
case TargetActivity:
var a ActivityToken
err := tx.Where("credential = ? AND task_id = ?", r.Credential, r.TaskID).Take(&a).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return "", "", ErrNoActivity
}
- return a.Token, reg.Environment, err
+ if err != nil {
+ return "", "", err
+ }
+ sealed = a.Token
}
- return reg.Token, reg.Environment, nil
+ token, err = s.Box.open(domainToken, sealed)
+ return token, reg.Environment, err
}
// forgetToken deletes the token Apple said is gone: the device's
-// registration, its push-to-start token, or one activity's.
-func (s *Sender) forgetToken(tx *gorm.DB, r OutboxRecord) error {
+// registration, its push-to-start token, or one activity's. A device
+// registration newer than Apple's timestamp (a 410's last-valid time) is
+// a later one, and stays.
+func (s *Sender) forgetToken(tx *gorm.DB, r OutboxRecord, apple time.Time) error {
switch r.Target {
case TargetStart:
return tx.Model(&Registration{}).Where("credential = ?", r.Credential).Select("start_token").Updates(map[string]any{"start_token": ""}).Error
case TargetActivity:
return tx.Where("credential = ? AND task_id = ?", r.Credential, r.TaskID).Delete(&ActivityToken{}).Error
}
+ if !apple.IsZero() {
+ var n int64
+ if err := tx.Model(&Registration{}).Where("credential = ? AND updated_at > ?", r.Credential, apple).Count(&n).Error; err != nil || n > 0 {
+ return err
+ }
+ }
return ForgetCredential(tx, r.Credential)
}
-// retry puts a row back for later, keeping Apple's answer if it gave one.
-func retry(tx *gorm.DB, r OutboxRecord, now time.Time, res Result) error {
- return tx.Model(&OutboxRecord{}).Where("id = ?", r.ID).Select("attempts", "next_at", "lease_until", "updated_at", "status", "reason").Updates(map[string]any{"attempts": r.Attempts + 1, "next_at": now.Add(Backoff(r.Attempts + 1)), "lease_until": nil, "updated_at": now, "status": res.Status, "reason": res.Reason}).Error
+// retry puts a row back for wait, keeping the answer if there was one;
+// counted, it was an attempt.
+func retry(tx *gorm.DB, r OutboxRecord, now time.Time, wait time.Duration, counted bool, res Result) error {
+ attempts := r.Attempts
+ if counted {
+ attempts++
+ }
+ return tx.Model(&OutboxRecord{}).Where("id = ?", r.ID).Select("attempts", "next_at", "lease_until", "updated_at", "status", "reason").Updates(map[string]any{"attempts": attempts, "next_at": now.Add(wait), "lease_until": nil, "updated_at": now, "status": res.Status, "reason": reasonOf(res)}).Error
+}
+
+// reasonOf is what a row keeps of an answer: Apple's reason, else the
+// platform's code.
+func reasonOf(res Result) string {
+ if res.Reason != "" {
+ return res.Reason
+ }
+ return res.Code
}
func finish(tx *gorm.DB, id, state string, res Result, now time.Time) error {
- fields := map[string]any{"state": state, "status": res.Status, "reason": res.Reason, "apns_id": res.APNsID, "lease_until": nil, "updated_at": now, "attempts": gorm.Expr("attempts + 1")}
+ fields := map[string]any{"state": state, "status": res.Status, "reason": reasonOf(res), "apns_id": res.APNsID, "lease_until": nil, "updated_at": now, "attempts": gorm.Expr("attempts + 1")}
if state == StateSent {
fields["sent_at"] = now
}
diff --git a/internal/equipo/push/sender_test.go b/internal/equipo/push/sender_test.go
index e4eee551..15ab6fa0 100644
--- a/internal/equipo/push/sender_test.go
+++ b/internal/equipo/push/sender_test.go
@@ -3,6 +3,10 @@ package push
import (
"bytes"
"context"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
"errors"
"io"
"log/slog"
@@ -22,6 +26,26 @@ const (
actToken = "cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33"
)
+// testBox seals as the instance key does for the tests' purposes: what
+// it seals never shows the token or the text.
+var testBox = Box{
+ Seal: func(domain string, v any) (string, error) {
+ b, err := json.Marshal(v)
+ return domain + ":" + base64.StdEncoding.EncodeToString(b), err
+ },
+ Open: func(domain, sealed string, v any) error {
+ raw, ok := strings.CutPrefix(sealed, domain+":")
+ if !ok {
+ return errors.New("sealed for another domain")
+ }
+ b, err := base64.StdEncoding.DecodeString(raw)
+ if err != nil {
+ return err
+ }
+ return json.Unmarshal(b, v)
+ },
+}
+
type rig struct {
t *testing.T
d *db.DB
@@ -52,14 +76,15 @@ func newRig(t *testing.T) *rig {
}),
Check: func(_ *gorm.DB, person, credential string) error {
if person != "p@example.com" || !r.current[credential] {
- return errors.New("not current")
+ return ErrGone
}
return nil
},
+ Box: testBox,
Now: func() time.Time { return r.now },
}
r.must(d.G.Transaction(func(tx *gorm.DB) error {
- _, err := Register(tx, "p@example.com", "cr1", wire.RegisterPush{Token: devToken, Environment: wire.APNsDevelopment, Platform: wire.PlatformIOS, StartToken: startToken}, at)
+ _, err := Register(tx, testBox, "p@example.com", "cr1", wire.RegisterPush{Token: devToken, Environment: wire.APNsDevelopment, Platform: wire.PlatformIOS, StartToken: startToken}, at)
return err
}))
return r
@@ -76,14 +101,22 @@ func (r *rig) must(err error) {
}
}
-func (r *rig) enqueue(kind, target, collapse, dedupe string, coalesce bool) {
+func (r *rig) enqueue(kind, target, collapse string, coalesce bool) {
r.t.Helper()
typ := TypeAlert
if strings.HasPrefix(kind, "activity") {
typ = TypeLiveActivity
}
row := OutboxRecord{Person: "p@example.com", Credential: "cr1", Kind: kind, Target: target, TaskID: "tk1", PushType: typ, Priority: 10, CollapseID: collapse, Payload: `{"aps":{}}`, NextAt: r.now, CreatedAt: r.now, UpdatedAt: r.now}
- r.must(r.d.G.Transaction(func(tx *gorm.DB) error { return Enqueue(tx, row, dedupe, coalesce) }))
+ r.must(r.d.G.Transaction(func(tx *gorm.DB) error { return Enqueue(tx, testBox, row, coalesce) }))
+}
+
+// opened is a token or payload as sealed at rest, opened.
+func (r *rig) opened(domain, sealed string) string {
+ r.t.Helper()
+ v, err := testBox.open(domain, sealed)
+ r.must(err)
+ return v
}
func (r *rig) rows() []OutboxRecord {
@@ -106,13 +139,13 @@ func (r *rig) drain() int {
// type, and Apple's answer kept; a second pass sends nothing.
func TestSenderSendsOnceAndRecordsApple(t *testing.T) {
r := newRig(t)
- r.enqueue(KindAlert, TargetDevice, "c1", "card:c1", false)
+ r.enqueue(KindAlert, TargetDevice, "c1", false)
if r.drain() != 1 || r.drain() != 0 || len(r.sent) != 1 {
t.Fatalf("sent %d", len(r.sent))
}
m := r.sent[0]
row := r.rows()[0]
- if m.ID != row.ID || m.Token != devToken || m.Topic != Topic || m.Environment != wire.APNsDevelopment || m.CollapseID != "c1" || m.Priority != 10 {
+ if !uuidShape.MatchString(m.ID) || m.ID != row.ID || m.Token != devToken || m.Topic != Topic || m.Environment != wire.APNsDevelopment || m.CollapseID != "c1" || m.Priority != 10 {
t.Fatalf("message %+v", m)
}
if row.State != StateSent || row.Status != 200 || row.APNsID != "apple-"+row.ID || row.SentAt == nil || row.Attempts != 1 {
@@ -125,7 +158,7 @@ func TestSenderSendsOnceAndRecordsApple(t *testing.T) {
// again; Apple's throttling is retried the same way.
func TestSenderRetryIsTheSamePush(t *testing.T) {
r := newRig(t)
- r.enqueue(KindAlert, TargetDevice, "c1", "card:c1", false)
+ r.enqueue(KindAlert, TargetDevice, "c1", false)
calls := 0
r.answer = func(m Message) (Result, error) {
calls++
@@ -166,11 +199,11 @@ func TestSenderRetryIsTheSamePush(t *testing.T) {
// TestSenderGivesUp: after MaxAttempts failed deliveries the row fails.
func TestSenderGivesUp(t *testing.T) {
r := newRig(t)
- r.enqueue(KindAlert, TargetDevice, "c1", "", false)
+ r.enqueue(KindAlert, TargetDevice, "c1", false)
r.answer = func(Message) (Result, error) { return Result{Status: 503, Reason: "ServiceUnavailable"}, nil }
for i := 0; i < MaxAttempts; i++ {
- r.now = r.now.Add(MaxRetry)
r.drain()
+ r.now = r.now.Add(2 * time.Hour)
}
if row := r.rows()[0]; row.State != StateFailed || row.Status != 503 || len(r.sent) != MaxAttempts {
t.Fatalf("row %+v after %d sends", row, len(r.sent))
@@ -183,8 +216,8 @@ func TestSenderGivesUp(t *testing.T) {
func TestSenderForgetsGoneTokens(t *testing.T) {
for _, reason := range []string{ReasonUnregistered, ReasonBadDeviceToken} {
r := newRig(t)
- r.enqueue(KindAlert, TargetDevice, "c1", "", false)
- r.enqueue(KindAlert, TargetDevice, "c2", "", false)
+ r.enqueue(KindAlert, TargetDevice, "c1", false)
+ r.enqueue(KindAlert, TargetDevice, "c2", false)
r.answer = func(Message) (Result, error) { return Result{Status: 400, Reason: reason}, nil }
r.drain()
var n int64
@@ -199,16 +232,18 @@ func TestSenderForgetsGoneTokens(t *testing.T) {
}
}
r := newRig(t)
- r.enqueue(KindActivityStart, TargetStart, "", "", false)
+ r.enqueue(KindActivityStart, TargetStart, "", false)
r.answer = func(Message) (Result, error) { return Result{Status: 410, Reason: ReasonUnregistered}, nil }
r.drain()
var reg Registration
r.must(r.d.G.Take(&reg).Error)
- if reg.StartToken != "" || reg.Token != devToken || r.sent[0].Token != startToken || r.sent[0].Topic != Topic+".push-type.liveactivity" {
+ if reg.StartToken != "" || r.opened(domainToken, reg.Token) != devToken || r.sent[0].Token != startToken || r.sent[0].Topic != Topic+".push-type.liveactivity" {
t.Fatalf("start token %+v", reg)
}
- r.must(r.d.G.Transaction(func(tx *gorm.DB) error { return RegisterActivity(tx, "p@example.com", "cr1", "tk1", actToken, at) }))
- r.enqueue(KindActivityUpdate, TargetActivity, "", "", false)
+ r.must(r.d.G.Transaction(func(tx *gorm.DB) error {
+ return RegisterActivity(tx, testBox, "p@example.com", "cr1", "tk1", actToken, at)
+ }))
+ r.enqueue(KindActivityUpdate, TargetActivity, "", false)
r.drain()
var acts int64
r.d.G.Model(&ActivityToken{}).Count(&acts)
@@ -221,7 +256,7 @@ func TestSenderForgetsGoneTokens(t *testing.T) {
// (revoked, its person removed) is never sent to; its registration goes.
func TestSenderNeverSendsToRevokedOrRemoved(t *testing.T) {
r := newRig(t)
- r.enqueue(KindAlert, TargetDevice, "c1", "", false)
+ r.enqueue(KindAlert, TargetDevice, "c1", false)
r.current["cr1"] = false
r.drain()
var n int64
@@ -235,15 +270,17 @@ func TestSenderNeverSendsToRevokedOrRemoved(t *testing.T) {
// waits for the app's token a while, and a delivered end forgets it.
func TestSenderActivityTokens(t *testing.T) {
r := newRig(t)
- r.enqueue(KindActivityUpdate, TargetActivity, "", "", false)
- r.enqueue(KindActivityEnd, TargetActivity, "", "", false)
+ r.enqueue(KindActivityUpdate, TargetActivity, "", false)
+ r.enqueue(KindActivityEnd, TargetActivity, "", false)
r.drain()
rows := r.rows()
// Ordered by kind: the end, then the update.
if len(r.sent) != 0 || rows[1].State != StateDropped || rows[1].Reason != "no_token" || rows[0].State != StatePending || rows[0].Attempts != 1 {
t.Fatalf("rows %+v", rows)
}
- r.must(r.d.G.Transaction(func(tx *gorm.DB) error { return RegisterActivity(tx, "p@example.com", "cr1", "tk1", actToken, at) }))
+ r.must(r.d.G.Transaction(func(tx *gorm.DB) error {
+ return RegisterActivity(tx, testBox, "p@example.com", "cr1", "tk1", actToken, at)
+ }))
r.now = r.now.Add(FirstRetry)
r.drain()
var acts int64
@@ -257,7 +294,7 @@ func TestSenderActivityTokens(t *testing.T) {
// process) is not sent again until its lease ends.
func TestSenderClaimsOnce(t *testing.T) {
r := newRig(t)
- r.enqueue(KindAlert, TargetDevice, "c1", "", false)
+ r.enqueue(KindAlert, TargetDevice, "c1", false)
lease := r.now.Add(Lease)
r.must(r.d.G.Model(&OutboxRecord{}).Where("1 = 1").Update("lease_until", lease).Error)
if r.drain() != 0 || len(r.sent) != 0 {
@@ -269,26 +306,43 @@ func TestSenderClaimsOnce(t *testing.T) {
}
}
-// TestEnqueueDedupeAndCoalesce: a once-only key writes one row a device;
-// a coalescing push replaces the unsent one with the same collapse ID.
-func TestEnqueueDedupeAndCoalesce(t *testing.T) {
+// TestEnqueueCoalesceAndOnce: a coalescing push replaces the unsent one
+// with the same collapse ID; a once-only key is decided once for a
+// person, kept apart from the outbox (pruned rows do not forget it).
+func TestEnqueueCoalesceAndOnce(t *testing.T) {
r := newRig(t)
- r.enqueue(KindAlert, TargetDevice, "c1", "card:c1", false)
- r.enqueue(KindAlert, TargetDevice, "c1", "card:c1", false)
- r.enqueue(KindBadge, TargetDevice, "badge", "", true)
- r.enqueue(KindBadge, TargetDevice, "badge", "", true)
- if n := len(r.rows()); n != 2 {
+ r.enqueue(KindBadge, TargetDevice, "badge", true)
+ r.enqueue(KindBadge, TargetDevice, "badge", true)
+ if n := len(r.rows()); n != 1 {
t.Fatalf("%d rows", n)
}
r.drain()
- r.enqueue(KindBadge, TargetDevice, "badge", "", true)
- if n := len(r.rows()); n != 3 {
+ r.enqueue(KindBadge, TargetDevice, "badge", true)
+ if n := len(r.rows()); n != 2 {
t.Fatalf("a sent badge was overwritten: %d rows", n)
}
- alerted, err := Alerted(r.d.G, "p@example.com", "card:c1")
- if err != nil || !alerted {
- t.Fatal("alerted", err)
+ r.must(r.d.G.Transaction(func(tx *gorm.DB) error {
+ for i, want := range []bool{true, false} {
+ first, err := Once(tx, "p@example.com", "card:c1", at)
+ if err != nil || first != want {
+ t.Errorf("once %d: %v %v", i, first, err)
+ }
+ }
+ return nil
+ }))
+ r.now = r.now.Add(Keep + time.Hour)
+ r.drain()
+ for _, row := range r.rows() {
+ if row.State == StateSent {
+ t.Fatal("ended rows not pruned")
+ }
}
+ r.must(r.d.G.Transaction(func(tx *gorm.DB) error {
+ if first, err := Once(tx, "p@example.com", "card:c1", r.now); first || err != nil {
+ t.Error("pruning forgot the alert", err)
+ }
+ return nil
+ }))
}
// TestRegisterValidates: hex tokens of a sane length, the two
@@ -316,7 +370,7 @@ func TestRegisterValidates(t *testing.T) {
}
r := newRig(t)
r.must(r.d.G.Transaction(func(tx *gorm.DB) error {
- out, err := Register(tx, "p@example.com", "cr1", good, at)
+ out, err := Register(tx, testBox, "p@example.com", "cr1", good, at)
if out.LiveActivities || out.Platform != wire.PlatformMacOS {
t.Errorf("registration %+v", out)
}
@@ -338,7 +392,8 @@ func TestLoggedTransportKeepsTokensOut(t *testing.T) {
if err != nil || res.Status != 200 {
t.Fatal(res, err)
}
- if strings.Contains(buf.String(), devToken) || strings.Contains(buf.String(), "login fix") || !strings.Contains(buf.String(), "pu1") {
+ sum := sha256.Sum256([]byte(devToken))
+ if strings.Contains(buf.String(), devToken) || strings.Contains(buf.String(), hex.EncodeToString(sum[:4])) || strings.Contains(buf.String(), "login fix") || !strings.Contains(buf.String(), "pu1") {
t.Fatalf("log %s", buf.String())
}
}
@@ -358,10 +413,10 @@ func TestCarlosSeam(t *testing.T) {
// it (two processes in a deploy overlap) is not sent twice.
func TestSenderClaimRace(t *testing.T) {
r := newRig(t)
- r.enqueue(KindAlert, TargetDevice, "c1", "", false)
+ r.enqueue(KindAlert, TargetDevice, "c1", false)
row := r.rows()[0]
r.must(r.d.G.Model(&OutboxRecord{}).Where("id = ?", row.ID).Update("lease_until", r.now.Add(Lease)).Error)
- if ok, err := r.s.one(context.Background(), row); ok || err != nil || len(r.sent) != 0 {
- t.Fatalf("sent a row another sender claimed: %v %v", ok, err)
+ if v, err := r.s.one(context.Background(), row); v.Act != "" || err != nil || len(r.sent) != 0 {
+ t.Fatalf("sent a row another sender claimed: %v %v", v, err)
}
}
diff --git a/internal/equipo/push/store.go b/internal/equipo/push/store.go
index efd79715..488c70ad 100644
--- a/internal/equipo/push/store.go
+++ b/internal/equipo/push/store.go
@@ -3,6 +3,7 @@ package push
import (
"crypto/rand"
"errors"
+ "fmt"
"strings"
"time"
@@ -13,10 +14,12 @@ import (
// Models are the push tables, for the migration check (chat.Models
// carries them).
-var Models = []any{&Registration{}, &ActivityToken{}, &OutboxRecord{}, &MemoryRecord{}}
+var Models = []any{&Registration{}, &ActivityToken{}, &OutboxRecord{}, &MemoryRecord{}, &OnceRecord{}}
// Registration is a paired device's push registration, one per device
-// credential: a new one replaces it.
+// credential: a new one replaces it, and one APNs token belongs to one
+// credential (the newest to register it). Token and StartToken are sealed
+// (Box); Registrations from Devices hold them sealed.
type Registration struct {
Credential string `gorm:"primaryKey"`
Person string `gorm:"index:push_registration_person"`
@@ -31,7 +34,7 @@ type Registration struct {
func (Registration) TableName() string { return "push_registrations" }
// ActivityToken is a running Live Activity's own update token, on one
-// device, for one task.
+// device, for one task; Token is sealed.
type ActivityToken struct {
Credential string `gorm:"primaryKey"`
TaskID string `gorm:"primaryKey"`
@@ -54,7 +57,8 @@ const (
// OutboxRecord is one push to one device. The token is not copied here:
// the sender reads it from the registration when it sends, so a revoked
-// device or a replaced token never receives an old row.
+// device or a replaced token never receives an old row. ID is a canonical
+// lowercase UUID, sent as apns-id; Payload is sealed (Box).
type OutboxRecord struct {
ID string `gorm:"primaryKey"`
Person string `gorm:"index:push_outbox_person"`
@@ -102,6 +106,18 @@ type MemoryRecord struct {
func (MemoryRecord) TableName() string { return "push_tasks" }
+// OnceRecord marks a once-only push (a card's alert, a reply's, a task's
+// outcome) as decided for a person, whether or not a device took it. It
+// is kept while the person is, never pruned with the outbox, so a card
+// alerts once in its life.
+type OnceRecord struct {
+ Person string `gorm:"primaryKey"`
+ Key string `gorm:"primaryKey"`
+ CreatedAt time.Time
+}
+
+func (OnceRecord) TableName() string { return "push_once" }
+
// ErrInvalid is a registration the server refuses.
var ErrInvalid = errors.New("push: invalid registration")
@@ -132,25 +148,103 @@ func Validate(in wire.RegisterPush) error {
return nil
}
-// Register replaces the credential's registration.
-func Register(tx *gorm.DB, person, credential string, in wire.RegisterPush, now time.Time) (wire.PushRegistration, error) {
+// Register replaces the credential's registration. A token another
+// credential holds (the phone signed out offline and paired again, maybe
+// as someone else) is taken from it: that credential's registration, what
+// waits for it and its activity tokens holding the token go.
+func Register(tx *gorm.DB, box Box, person, credential string, in wire.RegisterPush, now time.Time) (wire.PushRegistration, error) {
if err := Validate(in); err != nil {
return wire.PushRegistration{}, err
}
- r := Registration{Credential: credential, Person: person, Token: strings.ToLower(in.Token), Environment: in.Environment, Platform: in.Platform, StartToken: strings.ToLower(in.StartToken), CreatedAt: now, UpdatedAt: now}
- err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "credential"}}, DoUpdates: clause.AssignmentColumns([]string{"person", "token", "environment", "platform", "start_token", "updated_at"})}).Create(&r).Error
- return wire.PushRegistration{Environment: r.Environment, Platform: r.Platform, LiveActivities: r.StartToken != "", UpdatedAt: now}, err
+ token, start := strings.ToLower(in.Token), strings.ToLower(in.StartToken)
+ mine := map[string]bool{token: true}
+ if start != "" {
+ mine[start] = true
+ }
+ if err := takeTokens(tx, box, credential, mine); err != nil {
+ return wire.PushRegistration{}, err
+ }
+ sealed, err := box.seal(domainToken, token)
+ if err != nil {
+ return wire.PushRegistration{}, err
+ }
+ sealedStart, err := box.seal(domainToken, start)
+ if err != nil {
+ return wire.PushRegistration{}, err
+ }
+ r := Registration{Credential: credential, Person: person, Token: sealed, Environment: in.Environment, Platform: in.Platform, StartToken: sealedStart, CreatedAt: now, UpdatedAt: now}
+ err = tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "credential"}}, DoUpdates: clause.AssignmentColumns([]string{"person", "token", "environment", "platform", "start_token", "updated_at"})}).Create(&r).Error
+ return wire.PushRegistration{Environment: r.Environment, Platform: r.Platform, LiveActivities: start != "", UpdatedAt: now}, err
}
-// RegisterActivity keeps a running activity's update token.
-func RegisterActivity(tx *gorm.DB, person, credential, task, token string, now time.Time) error {
+// takeTokens forgets every other credential's registration holding one of
+// the tokens, and every other credential's activity token that is one.
+// Tokens are sealed, so they are compared opened, in Go: never in SQL. A
+// token that will not open cannot be this one, and never stops a
+// registration.
+func takeTokens(tx *gorm.DB, box Box, credential string, tokens map[string]bool) error {
+ var regs []Registration
+ if err := tx.Where("credential <> ?", credential).Find(&regs).Error; err != nil {
+ return err
+ }
+ for _, r := range regs {
+ for _, sealed := range []string{r.Token, r.StartToken} {
+ t, err := box.open(domainToken, sealed)
+ if err == nil && t != "" && tokens[t] {
+ if err := ForgetCredential(tx, r.Credential); err != nil {
+ return err
+ }
+ break
+ }
+ }
+ }
+ var acts []ActivityToken
+ if err := tx.Where("credential <> ?", credential).Find(&acts).Error; err != nil {
+ return err
+ }
+ for _, a := range acts {
+ t, err := box.open(domainToken, a.Token)
+ if err == nil && tokens[t] {
+ if err := tx.Where("credential = ? AND task_id = ?", a.Credential, a.TaskID).Delete(&ActivityToken{}).Error; err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+// RegisterActivity keeps a running activity's update token, taken from
+// any other credential that held it.
+func RegisterActivity(tx *gorm.DB, box Box, person, credential, task, token string, now time.Time) error {
if !hexToken(token) || task == "" {
return ErrInvalid
}
- a := ActivityToken{Credential: credential, TaskID: task, Person: person, Token: strings.ToLower(token), CreatedAt: now}
+ token = strings.ToLower(token)
+ if err := takeTokens(tx, box, credential, map[string]bool{token: true}); err != nil {
+ return err
+ }
+ sealed, err := box.seal(domainToken, token)
+ if err != nil {
+ return err
+ }
+ a := ActivityToken{Credential: credential, TaskID: task, Person: person, Token: sealed, CreatedAt: now}
return tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "credential"}, {Name: "task_id"}}, DoUpdates: clause.AssignmentColumns([]string{"person", "token", "created_at"})}).Create(&a).Error
}
+// Waiting reports whether a push for the task still waits to go to the
+// device (an activity's end waiting for its token).
+func Waiting(tx *gorm.DB, credential, task string) (bool, error) {
+ var n int64
+ err := tx.Model(&OutboxRecord{}).Where("credential = ? AND task_id = ? AND state = ?", credential, task, StatePending).Count(&n).Error
+ return n > 0, err
+}
+
+// Hurry makes what waits for the device about the task due now: its
+// activity's token just arrived.
+func Hurry(tx *gorm.DB, credential, task string, now time.Time) error {
+ return tx.Model(&OutboxRecord{}).Where("credential = ? AND task_id = ? AND state = ? AND lease_until IS NULL", credential, task, StatePending).Select("next_at").Updates(map[string]any{"next_at": now}).Error
+}
+
// ForgetCredential deletes a device's registration, its activity tokens
// and what still waits to go to it: the device was revoked, or Apple said
// its token is gone.
@@ -167,7 +261,7 @@ func ForgetCredential(tx *gorm.DB, credential string) error {
// ForgetPerson deletes everything push holds for a person removed from the
// roster.
func ForgetPerson(tx *gorm.DB, person string) error {
- for _, m := range []any{&Registration{}, &ActivityToken{}, &MemoryRecord{}} {
+ for _, m := range []any{&Registration{}, &ActivityToken{}, &MemoryRecord{}, &OnceRecord{}} {
if err := tx.Where("person = ?", person).Delete(m).Error; err != nil {
return err
}
@@ -175,13 +269,21 @@ func ForgetPerson(tx *gorm.DB, person string) error {
return tx.Model(&OutboxRecord{}).Where("person = ? AND state = ?", person, StatePending).Select("state", "reason", "lease_until").Updates(map[string]any{"state": StateDropped, "reason": "forgotten", "lease_until": nil}).Error
}
-// Devices are the person's registrations, oldest first.
+// Devices are the person's registrations, oldest first, their tokens
+// sealed.
func Devices(tx *gorm.DB, person string) ([]Registration, error) {
var out []Registration
err := tx.Where("person = ?", person).Order("created_at, credential").Find(&out).Error
return out, err
}
+// Device is one credential's registration, its tokens sealed.
+func Device(tx *gorm.DB, person, credential string) ([]Registration, error) {
+ var out []Registration
+ err := tx.Where("person = ? AND credential = ?", person, credential).Find(&out).Error
+ return out, err
+}
+
// HasActivity reports whether a device has a running activity's token for
// the task.
func HasActivity(tx *gorm.DB, credential, task string) (bool, error) {
@@ -217,35 +319,41 @@ func LiveTasks(tx *gorm.DB, person string) ([]MemoryRecord, error) {
return out, err
}
-// Enqueue writes one row: none when its once-only key was already used
-// for the device; over an unsent one with the same collapse ID when it
-// coalesces.
-func Enqueue(tx *gorm.DB, r OutboxRecord, dedupe string, coalesce bool) error {
- if dedupe != "" {
- var n int64
- if err := tx.Model(&OutboxRecord{}).Where("credential = ? AND dedupe = ?", r.Credential, dedupe).Count(&n).Error; err != nil {
- return err
- }
- if n > 0 {
- return nil
- }
- r.Dedupe = dedupe
+// Enqueue writes one row, its payload sealed: over an unsent one with
+// the same collapse ID when it coalesces.
+func Enqueue(tx *gorm.DB, box Box, r OutboxRecord, coalesce bool) error {
+ if len(r.Payload) > MaxPayload {
+ return ErrTooLarge
+ }
+ sealed, err := box.seal(domainPayload, r.Payload)
+ if err != nil {
+ return err
}
+ r.Payload = sealed
if coalesce {
res := tx.Model(&OutboxRecord{}).Where("credential = ? AND collapse_id = ? AND state = ? AND lease_until IS NULL", r.Credential, r.CollapseID, StatePending).Select("payload", "priority", "next_at", "updated_at").Updates(map[string]any{"payload": r.Payload, "priority": r.Priority, "next_at": r.NextAt, "updated_at": r.UpdatedAt})
if res.Error != nil || res.RowsAffected > 0 {
return res.Error
}
}
- r.ID = "pu" + strings.ToLower(rand.Text())
+ r.ID = NewID()
r.State = StatePending
return tx.Create(&r).Error
}
-// Alerted reports whether a once-only push already went to any of the
-// person's devices.
-func Alerted(tx *gorm.DB, person, dedupe string) (bool, error) {
- var n int64
- err := tx.Model(&OutboxRecord{}).Where("person = ? AND dedupe = ?", person, dedupe).Count(&n).Error
- return n > 0, err
+// NewID is a row ID: a random (version 4) UUID, canonical and lowercase,
+// as apns-id must be.
+func NewID() string {
+ var b [16]byte
+ _, _ = rand.Read(b[:])
+ b[6] = b[6]&0x0f | 0x40
+ b[8] = b[8]&0x3f | 0x80
+ return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
+}
+
+// Once marks a once-only push decided for the person, and reports
+// whether this is the first time.
+func Once(tx *gorm.DB, person, key string, now time.Time) (bool, error) {
+ res := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&OnceRecord{Person: person, Key: key, CreatedAt: now})
+ return res.RowsAffected == 1, res.Error
}
diff --git a/internal/equipo/push/testdata/activity-needs.json b/internal/equipo/push/testdata/activity-needs.json
index 51922596..7aa14c88 100644
--- a/internal/equipo/push/testdata/activity-needs.json
+++ b/internal/equipo/push/testdata/activity-needs.json
@@ -1,10 +1,5 @@
{
"aps": {
- "alert": {
- "title": "Fix login",
- "body": "[push.activity.needs_you]"
- },
- "sound": "default",
"timestamp": 1795176000,
"event": "update",
"content-state": {
diff --git a/internal/equipo/push/transport.go b/internal/equipo/push/transport.go
index b05636a7..126d92ac 100644
--- a/internal/equipo/push/transport.go
+++ b/internal/equipo/push/transport.go
@@ -1,18 +1,21 @@
package push
import (
+ "bytes"
"context"
- "crypto/sha256"
- "encoding/hex"
+ "encoding/json"
"errors"
"log/slog"
+ "strconv"
+ "strings"
+ "time"
)
// Logged is the local and staging transport: it sends nothing and logs
// that a push would have gone, with its kind and size but never its
-// token or payload (a payload can quote a person's card). Boot allows it
-// only on loopback or a staging origin (EQUIPO_ALLOW_LOGGED_PUSH), as
-// EQUIPO_ALLOW_LOGGED_MAIL is for mail.
+// token, anything derived from it, or its payload (a payload can quote a
+// person's card). Boot allows it only on loopback or a staging origin
+// (EQUIPO_ALLOW_LOGGED_PUSH), as EQUIPO_ALLOW_LOGGED_MAIL is for mail.
type Logged struct {
Logger *slog.Logger
// Sent sees each message (tests and the local drive); nil is none.
@@ -25,10 +28,7 @@ func (l Logged) Send(_ context.Context, m Message) (Result, error) {
l.Sent(m)
}
if l.Logger != nil {
- // The token's digest prefix tells two devices apart in the log
- // without being a token.
- sum := sha256.Sum256([]byte(m.Token))
- l.Logger.Info("push logged", "id", m.ID, "type", m.PushType, "priority", m.Priority, "collapse", m.CollapseID, "environment", m.Environment, "device", hex.EncodeToString(sum[:4]), "bytes", len(m.Payload))
+ l.Logger.Info("push logged", "id", m.ID, "type", m.PushType, "priority", m.Priority, "collapse", m.CollapseID, "environment", m.Environment, "bytes", len(m.Payload))
}
return Result{Status: 200, APNsID: m.ID}, nil
}
@@ -41,20 +41,97 @@ const CarlosPushEnv = "CARLOS_PUSH"
// transport this build does not have yet.
var ErrCarlosPushUnavailable = errors.New("push: CARLOS push submission is not available in this build")
-// FromCarlos is the CARLOS platform push submission transport: the
-// control-socket verb POST /v1/push and rastrillo's push client, as mail's
-// submit (mail.FromCarlos).
+// FromCarlos is the CARLOS platform push submission transport: POST
+// /v1/push on the instance's control socket ($CARLOS_CONTROL_SOCKET) with
+// Authorization: Bearer $CARLOS_ADMIN_TOKEN, as mail's submit
+// (mail.FromCarlos). The contract (carlos/platform, design/platform-push-
+// submission, docs/superpowers/specs/2026-11-20-platform-push-submission-
+// design.md §4, awaiting Paul) is here already: the body is
+// CarlosRequestOf(m), the answer CarlosResult(status, Retry-After, body),
+// and the Sender acts on every outcome (Judge).
//
-// SEAM (2026-11-20): neither the CARLOS verb nor the rastrillo client
-// exists yet (carlos/platform branch platform-push-submission has no
-// draft). When they land, build the rastrillo client here from the
-// process environment (socket, token) and return it as a Transport: it
-// must send Message.ID as its idempotency key, and report Apple's status,
-// reason and apns-id in Result. Until then CARLOS_PUSH=submit refuses
-// boot rather than dropping pushes silently.
+// SEAM (2026-11-20): neither the CARLOS verb nor rastrillo's push client
+// exists yet. When they land, build the client here from the process
+// environment and return it as a Transport: it sends CarlosRequestOf(m)
+// and returns CarlosResult of the answer, retrying nothing itself (the
+// outbox retries). Until then CARLOS_PUSH=submit refuses boot rather than
+// dropping pushes silently.
func FromCarlos(getenv func(string) string) (Transport, error) {
if getenv(CarlosPushEnv) != "submit" {
return nil, nil
}
return nil, ErrCarlosPushUnavailable
}
+
+// CarlosMaxBody is the verb's limit on a request body.
+const CarlosMaxBody = 8 << 10
+
+// CarlosRequest is the verb's request body (§4.1).
+type CarlosRequest struct {
+ DeviceToken string `json:"device_token"`
+ Topic string `json:"topic"`
+ PushType string `json:"push_type"`
+ Priority int `json:"priority"`
+ CollapseID string `json:"collapse_id,omitempty"`
+ Expiration *int64 `json:"expiration,omitempty"`
+ APNsID string `json:"apns_id,omitempty"`
+ Environment string `json:"environment"`
+ Payload json.RawMessage `json:"payload"`
+}
+
+// CarlosRequestOf is a message as the verb takes it: the payload a
+// compact JSON object of at most MaxPayload bytes, the whole body at most
+// CarlosMaxBody.
+func CarlosRequestOf(m Message) ([]byte, error) {
+ var payload bytes.Buffer
+ if err := json.Compact(&payload, m.Payload); err != nil || payload.Len() == 0 || payload.Bytes()[0] != '{' {
+ return nil, errors.New("push: payload is not a JSON object")
+ }
+ if payload.Len() > MaxPayload {
+ return nil, ErrTooLarge
+ }
+ r := CarlosRequest{DeviceToken: m.Token, Topic: m.Topic, PushType: m.PushType, Priority: m.Priority, CollapseID: m.CollapseID, APNsID: m.ID, Environment: m.Environment, Payload: payload.Bytes()}
+ if !m.Expiration.IsZero() {
+ at := m.Expiration.Unix()
+ r.Expiration = &at
+ }
+ raw, err := json.Marshal(r)
+ if err == nil && len(raw) > CarlosMaxBody {
+ return nil, ErrTooLarge
+ }
+ return raw, err
+}
+
+// carlosAnswer is the verb's answer body: Apple's answer on a 200
+// (status, apns_id, reason, timestamp in milliseconds on a 410), the
+// platform's code otherwise.
+type carlosAnswer struct {
+ Status int `json:"status"`
+ APNsID string `json:"apns_id"`
+ Reason string `json:"reason"`
+ Timestamp int64 `json:"timestamp"`
+ Code string `json:"code"`
+}
+
+// CarlosResult reads the verb's answer (§4.2): a 200 is Apple's answer,
+// passed through; anything else is the platform's refusal, its code (a
+// 401's body is plain text: no code) and Retry-After in seconds.
+func CarlosResult(status int, retryAfter string, body []byte) (Result, error) {
+ var a carlosAnswer
+ if status == 200 {
+ if err := json.Unmarshal(body, &a); err != nil || a.Status == 0 {
+ return Result{}, errors.New("push: CARLOS answered 200 without Apple's answer")
+ }
+ r := Result{Status: a.Status, Reason: a.Reason, APNsID: a.APNsID}
+ if a.Timestamp > 0 {
+ r.Timestamp = time.UnixMilli(a.Timestamp).UTC()
+ }
+ return r, nil
+ }
+ _ = json.Unmarshal(body, &a)
+ r := Result{Refused: status, Code: a.Code}
+ if n, err := strconv.Atoi(strings.TrimSpace(retryAfter)); err == nil && n > 0 {
+ r.RetryAfter = time.Duration(n) * time.Second
+ }
+ return r, nil
+}
diff --git a/internal/equipo/push_config_test.go b/internal/equipo/push_config_test.go
index 921d0026..2fba36ee 100644
--- a/internal/equipo/push_config_test.go
+++ b/internal/equipo/push_config_test.go
@@ -45,3 +45,15 @@ func TestPusherChannels(t *testing.T) {
t.Fatalf("submit: %v", err)
}
}
+
+// TestPusherRefusesBoth: logged push and CARLOS submission together refuse
+// boot, never one silently over the other.
+func TestPusherRefusesBoth(t *testing.T) {
+ cfg := Config{Origin: "http://127.0.0.1:4321", InstanceKey: "k", AllowLoggedPush: true}
+ for _, v := range []string{"submit", "anything"} {
+ _, err := Pusher(cfg, nil, func(k string) string { return map[string]string{push.CarlosPushEnv: v}[k] })
+ if err == nil || err.Error() != copyPushBoth {
+ t.Fatalf("%s: %v", v, err)
+ }
+ }
+}
diff --git a/internal/plan3test/plan3_release_test.go b/internal/plan3test/plan3_release_test.go
index f83b4241..3c355d0e 100644
--- a/internal/plan3test/plan3_release_test.go
+++ b/internal/plan3test/plan3_release_test.go
@@ -189,7 +189,7 @@ func plan3CopyInventory(t *testing.T) {
acceptedMail := key == "copyMissingSMTP" && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Luna, 2026-11-17)")
// Luna's delegated pass on native slice 2's push strings and API
// prose (Paul, 2026-11-20: Luna's verdicts are the review).
- acceptedPush := slices.Contains([]string{"copyLoggedPushPublic", "copyCarlosPushUnavailable", "push.card.title", "push.card.body", "push.reply.title", "push.task.done", "push.task.cancelled", "push.task.failed", "push.activity.started", "push.activity.needs_you", "docs/api/equipo-v1.md / Talk to your Coordinator from a device: set aside", "docs/api/equipo-v1.md / Receive pushes on a device"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)")
+ acceptedPush := slices.Contains([]string{"copyLoggedPushPublic", "copyCarlosPushUnavailable", "copyPushBoth", "push.card.title", "push.card.body", "push.reply.title", "push.task.done", "push.task.cancelled", "push.task.failed", "push.activity.started", "docs/api/equipo-v1.md / Talk to your Coordinator from a device: set aside", "docs/api/equipo-v1.md / Receive pushes on a device"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)")
acceptedCopy := strings.TrimSuffix(cells[3], " |") == "COPY ACCEPTED BY DELEGATION (Copy, record-bound) sha256:"+copydesk.Hash(rows[key])
if !acceptedInjection && !acceptedMail && !acceptedPush && !acceptedAccess && !acceptedPlacementEdges && !acceptedPlacement && !acceptedReportActions && !acceptedRoster && !acceptedCopy && !strings.Contains(cells[3], "COPY REVIEW REQUIRED") && !acceptedAll && !acceptedGuide && !acceptedRound2 && !acceptedStarter && !acceptedDelegation && !approvedPublish && !approvedAssistant && !approvedJobs && !approvedOficina {
t.Fatal("entry has no copy review status or applicable acceptance", key)
diff --git a/internal/plan3test/push_device_test.go b/internal/plan3test/push_device_test.go
index a3908b2d..2a5653dd 100644
--- a/internal/plan3test/push_device_test.go
+++ b/internal/plan3test/push_device_test.go
@@ -1,8 +1,10 @@
package plan3test
import (
+ "errors"
"strings"
"testing"
+ "time"
"amadan.net/oficina/equipo/internal/equipo"
"amadan.net/oficina/equipo/internal/equipo/push"
@@ -50,12 +52,25 @@ func TestPushRegistrationLifetime(t *testing.T) {
if err := pushCurrent(t, f, cred.ID); err != nil {
t.Fatal("a current device refused", err)
}
+ // Sealed at rest with the instance key: no token in the table.
+ if f.count(t, "SELECT count(*) FROM push_registrations WHERE lower(token) LIKE ? OR lower(start_token) LIKE ?", "%"+pushToken+"%", "%"+pushToken+"%") != 0 {
+ t.Fatal("a token kept in the clear")
+ }
+ // Only revocation or removal is gone: an expired credential is not
+ // current now, and keeps its registration.
+ var expires time.Time
+ must(t, f.DB.G.Raw("SELECT token_expires_at FROM person_devices WHERE id = ?", cred.ID).Scan(&expires).Error)
+ must(t, f.DB.G.Exec("UPDATE person_devices SET token_expires_at = ? WHERE id = ?", time.Now().Add(-time.Hour).UTC(), cred.ID).Error)
+ if err := pushCurrent(t, f, cred.ID); !errors.Is(err, push.ErrNotCurrent) {
+ t.Fatal("an expired device", err)
+ }
+ must(t, f.DB.G.Exec("UPDATE person_devices SET token_expires_at = ? WHERE id = ?", expires, cred.ID).Error)
expectHTTP(t, deviceRequest(t, f, cred.Token, "DELETE", "/api/v1/auth/devices/"+cred.ID, `{}`, "revoke", `"3"`), 200)
if f.count(t, "SELECT count(*) FROM push_registrations") != 0 {
t.Fatal("a revoked device kept its registration")
}
- if pushCurrent(t, f, cred.ID) == nil {
- t.Fatal("a revoked device may still be pushed")
+ if err := pushCurrent(t, f, cred.ID); !errors.Is(err, push.ErrGone) {
+ t.Fatal("a revoked device may still be pushed", err)
}
second := approvedDevice(t, f)
@@ -64,7 +79,7 @@ func TestPushRegistrationLifetime(t *testing.T) {
if f.count(t, "SELECT count(*) FROM push_registrations") != 0 {
t.Fatal("a removed person kept a registration")
}
- if pushCurrent(t, f, second.ID) == nil {
- t.Fatal("a removed person's device may still be pushed")
+ if err := pushCurrent(t, f, second.ID); !errors.Is(err, push.ErrGone) {
+ t.Fatal("a removed person's device may still be pushed", err)
}
}