oficina / equipo Public

push: device registrations, the push outbox, its rules and a sender (native slice 2)

POST /api/v1/push-registrations and /push-registrations/activities bind
APNs tokens to the paired device credential; revocation, roster removal
and Apple's Unregistered/BadDeviceToken delete them. The conversation
engine writes push_outbox rows in the transaction of each change, from
one rule table (push.Rules): card alerts, unseen replies, task outcomes,
the Needs you badge and a Live Activity per started task (at most three,
lines at most once a minute). A sender drains the outbox through a
Transport with leases, backoff and the row ID as apns-id; the logged
transport is loopback/staging only and CARLOS push submission is a seam.
POST /cards/{id}/visibility sets a card aside (D5). Copy reviewed by Luna.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 66936946ef1d79ad5f698be3b071d2489a0b7417 parent b1f66f0
55 files changed, +3,517 −23
  • .rastrillo/budgets.txt +4 −4
  • cmd/equipo/main.go +4 −0
  • docs/api/equipo-v1.md +21 −0
  • docs/api/equipo-v1.openapi.json +303 −0
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +12 −0
  • internal/equipo/app.go +15 −1
  • internal/equipo/chat/http.go +6 −0
  • internal/equipo/chat/hub.go +27 −1
  • internal/equipo/chat/inner.go +1 −1
  • internal/equipo/chat/models.go +6 −2
  • internal/equipo/chat/projects.go +9 −0
  • internal/equipo/chat/push.go +373 −0
  • internal/equipo/chat/push_http.go +61 −0
  • internal/equipo/chat/push_test.go +401 −0
  • internal/equipo/chat/roster.go +43 −7
  • internal/equipo/chat/store.go +16 −1
  • internal/equipo/chat/tasks.go +3 −0
  • internal/equipo/chat_wiring.go +8 −0
  • internal/equipo/config.go +12 −0
  • internal/equipo/copy.go +12 −0
  • internal/equipo/invitations.go +3 −1
  • internal/equipo/mailer.go +24 −0
  • internal/equipo/migrations/0095_push.sql +14 −0
  • internal/equipo/migrations/schema.sql +11 −0
  • internal/equipo/person_devices.go +2 −1
  • internal/equipo/personapi/devices.go +9 −0
  • internal/equipo/push/budget_test.go +9 −0
  • internal/equipo/push/payload.go +113 −0
  • internal/equipo/push/payload_test.go +108 −0
  • internal/equipo/push/push.go +94 −0
  • internal/equipo/push/rules.go +270 −0
  • internal/equipo/push/rules_test.go +200 −0
  • internal/equipo/push/sender.go +221 −0
  • internal/equipo/push/sender_test.go +355 −0
  • internal/equipo/push/store.go +251 −0
  • internal/equipo/push/testdata/activity-end.json +17 −0
  • internal/equipo/push/testdata/activity-needs.json +20 −0
  • internal/equipo/push/testdata/activity-replaced.json +17 −0
  • internal/equipo/push/testdata/activity-start.json +24 −0
  • internal/equipo/push/testdata/activity-update.json +15 −0
  • internal/equipo/push/testdata/badge.json +5 −0
  • internal/equipo/push/testdata/card.json +16 −0
  • internal/equipo/push/testdata/reply.json +13 −0
  • internal/equipo/push/testdata/task-done.json +14 −0
  • internal/equipo/push/testdata/task-failed.json +14 −0
  • internal/equipo/push/transport.go +60 −0
  • internal/equipo/push_config_test.go +47 −0
  • internal/equipo/setup/invites.go +4 −0
  • internal/equipo/setup/roster.go +5 −0
  • internal/plan3test/plan3_release_test.go +4 −1
  • internal/plan3test/push_device_test.go +70 −0
  • internal/wire/api.go +3 −0
  • internal/wire/push.go +128 −0
  • internal/wire/wireschema/wireschema.go +15 −3
  • internal/wire/wireschema/wireschema_test.go +5 −0

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 2.1s
ci-box: codex: fetched and verified in 3.5s
ci-box: codex-code-mode-host: fetched and verified in 1.4s
ci-box: libwrap: fetched and verified in 0.3s
ci-box: socat: fetched and verified in 0.4s
npm warn deprecated node-domexception@1.0.0: Use your platform's native DOMException instead
ci-box: image pulled in 9.8s
ci-box: pi: installed and verified in 7.5s
ci-box: opencode: installed and verified in 2.2s
ci-box: chromium 156.0.8078.79-1~deb13u1: 76 packages fetched, verified and unpacked in 8.9s
ci-box: clone deepened in 3.3s
ci-box: file times set from content: 2748 files, 176 directories
ci-box: ready in 16.9s
=== 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.244s
=== compile ===
go build ./...
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py compile
+ go build -tags testbuild ./...
  4.4s
+ go list -export -test -tags testbuild -f  ./...
  4.9s
+ go list -export -test -tags browser,testbuild -f  ./internal/equipo ./internal/headless ./internal/idtest ./internal/plan3test ./internal/thintest
  3.0s
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 1m29.66s 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 1m27.356s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m27.36s amadan.net/oficina/equipo/internal/headless TestHeadless
machine: 32 CPUs, load 65.22, cpu waiting 39.18%, memory waiting 0.00%, io waiting 0.48%
--- 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 1m33.588s 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 1m30.893s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m30.89s amadan.net/oficina/equipo/internal/headless TestHeadless
machine: 32 CPUs, load 64.40, cpu waiting 39.48%, memory waiting 0.00%, io waiting 0.45%
--- 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 1m34.373s 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 1m31.583s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m20.36s amadan.net/oficina/equipo/internal/headless TestHeadlessConnections
receipt: slow test 6.28s amadan.net/oficina/equipo/internal/headless TestHeadlessTokenPasteEndToEnd
receipt: slow test 4.95s amadan.net/oficina/equipo/internal/headless TestHeadlessTokenConnection
machine: 32 CPUs, load 64.40, cpu waiting 39.04%, memory waiting 0.00%, io waiting 0.43%
--- 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 1m28.75s 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 1m26.766s amadan.net/oficina/equipo/internal/headless
receipt: slow test 44.4s amadan.net/oficina/equipo/internal/headless TestMacWorker
receipt: slow test 21.88s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 10.64s amadan.net/oficina/equipo/internal/headless TestHeadlessAttachments
receipt: slow test 9.85s amadan.net/oficina/equipo/internal/headless TestHeadlessPrewarm
machine: 32 CPUs, load 65.22, cpu waiting 39.18%, memory waiting 0.00%, io waiting 0.48%
--- 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 1m46.74s 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.504s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m6.98s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 12.42s amadan.net/oficina/equipo/internal/headless TestHeadlessRunnerKillLeavesNoCopies
receipt: slow test 10.34s amadan.net/oficina/equipo/internal/headless TestHeadlessCopyRotation
receipt: slow test 8.87s amadan.net/oficina/equipo/internal/headless TestHeadlessPolicyGuards
receipt: slow test 5.88s amadan.net/oficina/equipo/internal/headless TestHeadlessNewHouseRuleStartsFresh
machine: 32 CPUs, load 56.82, cpu waiting 33.44%, memory waiting 0.00%, io waiting 0.35%
--- 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 3m16.673s 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 3m14.589s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m53.21s amadan.net/oficina/equipo/internal/headless TestHeadlessAssistant
receipt: slow test 23.75s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 11.35s amadan.net/oficina/equipo/internal/headless TestHeadlessResearchHandoff
receipt: slow test 8.03s amadan.net/oficina/equipo/internal/headless TestHeadlessClaudeSignIn
receipt: slow test 7.31s amadan.net/oficina/equipo/internal/headless TestHeadlessTurnBatching
machine: 32 CPUs, load 15.95, cpu waiting 7.53%, memory waiting 0.00%, io waiting 0.07%
--- 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.702s 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.599s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 7.84s amadan.net/oficina/equipo/internal/thintest TestContractTeamJobSettledStates
receipt: slow test 6.77s amadan.net/oficina/equipo/internal/thintest TestExplorePreviewsOff
receipt: slow test 3.7s amadan.net/oficina/equipo/internal/thintest TestContractPreviewHeldUntilPublishAnswer
receipt: slow test 3.52s amadan.net/oficina/equipo/internal/thintest TestContractTeamNudgePersonNeeds
receipt: slow test 2.52s amadan.net/oficina/equipo/internal/thintest TestResearchDoneFallsBack
machine: 32 CPUs, load 45.94, cpu waiting 26.60%, memory waiting 0.00%, io waiting 0.27%
--- 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 1m23.973s 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 1m21.63s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 9.21s amadan.net/oficina/equipo/internal/thintest TestContractPreviewNotScheduled
receipt: slow test 4.98s amadan.net/oficina/equipo/internal/thintest TestContractPublishNotOffered
receipt: slow test 4.39s amadan.net/oficina/equipo/internal/thintest TestContractMacRecheckMergeAuthority
receipt: slow test 2.36s amadan.net/oficina/equipo/internal/thintest TestContractPreview
receipt: slow test 2.35s amadan.net/oficina/equipo/internal/thintest TestContractPublishNameTaken
machine: 32 CPUs, load 63.75, cpu waiting 39.09%, memory waiting 0.00%, io waiting 0.51%
--- 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
budget note: internal/runner/thin took 4m39.466s, over the 45s its record on line 44 allows; reported only, timing fails on CI

receipt: test step 4m44.879s 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 4m39.466s amadan.net/oficina/equipo/internal/runner/thin
receipt: slow test 37.09s 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.98s amadan.net/oficina/equipo/internal/runner/thin TestOpenCodeStepsRealOpenCode
machine: 32 CPUs, load 4.09, cpu waiting 1.73%, 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

receipt: test step 49.85s 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 48.984s amadan.net/oficina/equipo/internal/runner
receipt: slow test 28.95s amadan.net/oficina/equipo/internal/runner TestDirectBugWorkflow
receipt: slow test 20.03s amadan.net/oficina/equipo/internal/runner TestEnrolKeepsTheRole
machine: 32 CPUs, load 58.23, cpu waiting 31.11%, memory waiting 0.00%, io waiting 0.94%
--- 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

receipt: test step 59.931s 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 58.741s amadan.net/oficina/equipo/internal/runner
receipt: slow test 48.65s amadan.net/oficina/equipo/internal/runner TestPlanWorkflowCandidateOrder
receipt: slow test 42.5s amadan.net/oficina/equipo/internal/runner TestPlanWorkflowFeature
receipt: slow test 8.43s amadan.net/oficina/equipo/internal/runner TestCoordinatorRecoveryCallRefusalKeepsServing
receipt: slow test 1.63s amadan.net/oficina/equipo/internal/runner TestCoordinatorRefusalMatrix
machine: 32 CPUs, load 60.16, cpu waiting 36.64%, memory waiting 0.00%, io waiting 0.79%
--- 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

receipt: test step 35.613s 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.719s amadan.net/oficina/equipo/internal/runner
receipt: slow test 5.16s amadan.net/oficina/equipo/internal/runner TestDirectFaultIsolation
receipt: slow test 3.37s amadan.net/oficina/equipo/internal/runner TestClaimRefusalsBackOff
receipt: slow test 3.14s amadan.net/oficina/equipo/internal/runner TestCoordinatorRecoveryRefusedKeepsServing
receipt: slow test 2.36s amadan.net/oficina/equipo/internal/runner TestToolVerbUnderFakeHarness
receipt: slow test 1.61s amadan.net/oficina/equipo/internal/runner TestReportPostsRetryExactRequest
machine: 32 CPUs, load 32.81, cpu waiting 21.33%, memory waiting 0.00%, io waiting 1.15%
--- 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 34.5%, load 23.22
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 1m6.138s 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 1m4.282s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 26.65s amadan.net/oficina/equipo/internal/equipotest TestAuthorityCoreIntegration
receipt: slow test 26.53s amadan.net/oficina/equipo/internal/equipotest TestBootstrapNamesOwnersSetting
receipt: slow test 24.58s amadan.net/oficina/equipo/internal/equipotest TestAccountLabelMigration
receipt: slow test 21.95s amadan.net/oficina/equipo/internal/equipotest TestBudgetConfigurationFailuresAreAtomic
receipt: slow test 21.84s amadan.net/oficina/equipo/internal/equipotest TestAuthorityProjectKinds
machine: 32 CPUs, load 64.40, cpu waiting 38.16%, memory waiting 0.00%, io waiting 0.42%
--- 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 34.5%, load 23.22
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.484s 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.645s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 18.78s amadan.net/oficina/equipo/internal/equipotest TestProjectRetryAndRevision
receipt: slow test 18.74s amadan.net/oficina/equipo/internal/equipotest TestProjectWritesRequireCurrentOwner
receipt: slow test 18.66s amadan.net/oficina/equipo/internal/equipotest TestProjectRequestActorAndUpdate
receipt: slow test 18.63s amadan.net/oficina/equipo/internal/equipotest TestProjectsSharedAndGrouped
receipt: slow test 18.6s amadan.net/oficina/equipo/internal/equipotest TestProjectsAccountRevisionAndValidation
machine: 32 CPUs, load 56.82, cpu waiting 34.50%, memory waiting 0.00%, io waiting 0.36%
--- 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 34.5%, load 23.22
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 1m13.254s 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 1m8.293s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 15.39s amadan.net/oficina/equipo/internal/equipotest TestReleaseStampContract
receipt: slow test 13.08s amadan.net/oficina/equipo/internal/equipotest TestRosterChangesAffectExistingSession
receipt: slow test 9.98s amadan.net/oficina/equipo/internal/equipotest TestRosterRemovalRollsBack
receipt: slow test 9.87s amadan.net/oficina/equipo/internal/equipotest TestRosterRemovalWhileAssigned
receipt: slow test 6.92s amadan.net/oficina/equipo/internal/equipotest TestRosterProtectsLastOwner
machine: 32 CPUs, load 56.82, cpu waiting 35.57%, memory waiting 0.00%, io waiting 0.38%
--- 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 34.5%, load 23.22
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.794s 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.032s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 23.92s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedRollback
receipt: slow test 23.92s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedExistingTeam
receipt: slow test 23.71s amadan.net/oficina/equipo/internal/equipotest TestSigninNoProof
receipt: slow test 22.32s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsUpgrade
receipt: slow test 22.21s amadan.net/oficina/equipo/internal/equipotest TestSpecialistSettingsRollbackAndUnavailable
machine: 32 CPUs, load 61.24, cpu waiting 37.33%, memory waiting 0.00%, io waiting 0.40%
--- 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 34.5%, load 23.22
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 52.586s 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 50.536s amadan.net/oficina/equipo/internal/plan3test
receipt: slow test 3.51s amadan.net/oficina/equipo/internal/plan3test TestCoordinatorAcceptance3B
receipt: slow test 3.45s amadan.net/oficina/equipo/internal/plan3test TestPlan3Upgrade
receipt: slow test 1.51s amadan.net/oficina/equipo/internal/plan3test TestConversationQuestionRace
receipt: slow test 1.47s amadan.net/oficina/equipo/internal/plan3test TestCoordinatorAcceptance3A
receipt: slow test 1.21s amadan.net/oficina/equipo/internal/plan3test TestPersonAPIMigrationUpgrade
machine: 32 CPUs, load 65.82, cpu waiting 39.36%, memory waiting 0.00%, io waiting 0.53%
--- 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 34.5%, load 23.22
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/equipo/team: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/forge: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/webread: 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/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/opencode: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/provider/pi: its inputs changed
--- FAIL amadan.net/oficina/equipo/internal/runner/webread TestTimeouts
=== RUN   TestTimeouts
    fetch_test.go:537: s1: {Source:s1 Origin:paul Parent: URL:https://shop.example.com/slow-body Hops:[{URL:https://shop.example.com/slow-body Address:151.101.1.1 Status:200}] Address:151.101.1.1 Status:200 Type:text/plain Bytes:5 SHA256:2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824 Millis:300 Reason: File:s001.txt}
--- FAIL: TestTimeouts (0.63s)

--- FAIL amadan.net/oficina/equipo/internal/runner/webread (package output)
FAIL
rastrillo-budget/v1 ran 2.064s
FAIL	amadan.net/oficina/equipo/internal/runner/webread	2.109s

budget note: internal/equipo took 23.474s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/equipo/chat took 13.146s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/equipo/setup took 10.251s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/idtest took 43.721s, 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 50.765s, over the 15s its record on line 40 allows; reported only, timing fails on CI
budget note: internal/runner/workspace took 11.861s, over the 10s the default allows; reported only, timing fails on CI

receipt: test step 2m14.347s against a 60s target (the gate's other steps are not in this figure)
receipt: 34 packages ran, 26 cached, 18 without tests, 1 failed
receipt: slow package 1m8.815s amadan.net/oficina/equipo/internal/runner/provider/opencode
receipt: slow package 58.069s amadan.net/oficina/equipo/internal/runner/provider/pi
receipt: slow package 54.417s amadan.net/oficina/equipo/internal/runner/checks
receipt: slow package 50.765s amadan.net/oficina/equipo/internal/runner/containment
receipt: slow package 43.721s amadan.net/oficina/equipo/internal/idtest
receipt: slow test 25.26s amadan.net/oficina/equipo/internal/runner/provider/opencode TestOpenCodeAcceptanceHostileRepository
receipt: slow test 22.55s amadan.net/oficina/equipo/internal/runner/containment TestEngineeringOfflineGo
receipt: slow test 19.69s amadan.net/oficina/equipo/cmd/equipo-runner TestReleaseRunnerHasNoFakeWorker
receipt: slow test 12.1s amadan.net/oficina/equipo/internal/runner/provider/opencode TestOpenCodeP1OnlyOpenCodeReachable
receipt: slow test 11.57s amadan.net/oficina/equipo/internal/idtest TestIDCallbackGuardAndPendingNonce
rastrillo: budget test: go test failed
exit status 1
+ go test -tags testbuild -timeout 15m -v -run '^TestTimeouts$' -count=1 ./internal/runner/webread   (retry, once)
##############################################################################
FLAKE ./internal/runner/webread:TestTimeouts rest 66936946ef1d79ad5f698be3b071d2489a0b7417 0.63s 24.88
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 24.88, cpu waiting 12.83%, memory waiting 0.00%, io waiting 0.13%
--- 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
exit status 1
--- FAIL amadan.net/oficina/equipo/internal/headless TestBrowserChat
=== RUN   TestBrowserChat
time=2026-11-20T06:16:11.016Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-20T06:16:11.016Z level=INFO msg="startup phase done" phase=state_lock took=167µs
time=2026-11-20T06:16:11.016Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-20T06:16:11.016Z level=INFO msg="startup phase done" phase=claim_roots took=85µs
time=2026-11-20T06:16:11.016Z level=INFO msg="startup phase" phase=sweep
time=2026-11-20T06:16:11.050Z level=INFO msg="startup phase done" phase=sweep took=34.356ms
time=2026-11-20T06:16:11.051Z level=INFO msg="startup phase" phase=credentials
time=2026-11-20T06:16:11.051Z level=INFO msg="startup phase done" phase=credentials took=308µs
time=2026-11-20T06:16:11.051Z level=INFO msg="startup phase" phase=open_state
time=2026-11-20T06:16:11.108Z level=INFO msg="startup phase done" phase=open_state took=56.281ms
time=2026-11-20T06:16:11.108Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-20T06:16:11.109Z level=INFO msg=connecting host=127.0.0.1:39439 protocol=28
time=2026-11-20T06:16:11.111Z level=INFO msg=connected host=127.0.0.1:39439 took=1.159ms
time=2026-11-20T06:16:11.113Z level=INFO msg="capabilities gathering"
time=2026-11-20T06:16:11.115Z level=INFO msg="capabilities gathered" took=2.222ms tags=linux,claude,go
time=2026-11-20T06:16:11.116Z level=INFO msg="hello sent" protocol=28
time=2026-11-20T06:16:11.121Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-20T06:16:13.675Z 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.59s)

--- FAIL amadan.net/oficina/equipo/internal/headless TestBrowserChatSendStaysOnPage
=== RUN   TestBrowserChatSendStaysOnPage
time=2026-11-20T06:16:17.611Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-20T06:16:17.611Z level=INFO msg="startup phase done" phase=state_lock took=79µs
time=2026-11-20T06:16:17.611Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-20T06:16:17.611Z level=INFO msg="startup phase done" phase=claim_roots took=115µs
time=2026-11-20T06:16:17.611Z level=INFO msg="startup phase" phase=sweep
time=2026-11-20T06:16:17.651Z level=INFO msg="startup phase done" phase=sweep took=40.405ms
time=2026-11-20T06:16:17.651Z level=INFO msg="startup phase" phase=credentials
time=2026-11-20T06:16:17.652Z level=INFO msg="startup phase done" phase=credentials took=96µs
time=2026-11-20T06:16:17.652Z level=INFO msg="startup phase" phase=open_state
time=2026-11-20T06:16:17.713Z level=INFO msg="startup phase done" phase=open_state took=61.756ms
time=2026-11-20T06:16:17.714Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-20T06:16:17.715Z level=INFO msg=connecting host=127.0.0.1:43931 protocol=28
time=2026-11-20T06:16:17.718Z level=INFO msg=connected host=127.0.0.1:43931 took=2.297ms
time=2026-11-20T06:16:17.718Z level=INFO msg="capabilities gathering"
time=2026-11-20T06:16:17.718Z level=INFO msg="capabilities gathered" took=595µs tags=linux,claude,go
time=2026-11-20T06:16:17.722Z level=INFO msg="hello sent" protocol=28
time=2026-11-20T06:16:17.726Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-20T06:16:19.794Z 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.11s)

--- FAIL amadan.net/oficina/equipo/internal/headless TestBrowserDraftIsTheMessage
=== RUN   TestBrowserDraftIsTheMessage
time=2026-11-20T06:16:23.705Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-20T06:16:23.705Z level=INFO msg="startup phase done" phase=state_lock took=77µs
time=2026-11-20T06:16:23.705Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-20T06:16:23.705Z level=INFO msg="startup phase done" phase=claim_roots took=81µs
time=2026-11-20T06:16:23.705Z level=INFO msg="startup phase" phase=sweep
time=2026-11-20T06:16:23.736Z level=INFO msg="startup phase done" phase=sweep took=30.893ms
time=2026-11-20T06:16:23.736Z level=INFO msg="startup phase" phase=credentials
time=2026-11-20T06:16:23.736Z level=INFO msg="startup phase done" phase=credentials took=159µs
time=2026-11-20T06:16:23.736Z level=INFO msg="startup phase" phase=open_state
time=2026-11-20T06:16:23.786Z level=INFO msg="startup phase done" phase=open_state took=50.104ms
time=2026-11-20T06:16:23.787Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-20T06:16:23.788Z level=INFO msg=connecting host=127.0.0.1:45481 protocol=28
time=2026-11-20T06:16:23.790Z level=INFO msg=connected host=127.0.0.1:45481 took=2.296ms
time=2026-11-20T06:16:23.790Z level=INFO msg="capabilities gathering"
time=2026-11-20T06:16:23.792Z level=INFO msg="capabilities gathered" took=1.966ms tags=linux,claude,go
time=2026-11-20T06:16:23.793Z level=INFO msg="hello sent" protocol=28
time=2026-11-20T06:16:23.798Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-20T06:16:25.904Z level=INFO msg="connection checked" connection=claude-1 state=healthy
    browser_thinking_test.go:106: waiting for !!window.__m: context deadline exceeded (last evaluation: <nil>)
--- FAIL: TestBrowserDraftIsTheMessage (8.14s)

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


receipt: test step 51.028s 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 49.121s amadan.net/oficina/equipo/internal/headless
receipt: slow test 15.43s amadan.net/oficina/equipo/internal/headless TestBrowserDraftStreamsFormatted
receipt: slow test 8.14s amadan.net/oficina/equipo/internal/headless TestBrowserDraftIsTheMessage
receipt: slow test 7.79s amadan.net/oficina/equipo/internal/headless TestBrowserComposer
receipt: slow test 6.59s amadan.net/oficina/equipo/internal/headless TestBrowserChat
receipt: slow test 6.11s amadan.net/oficina/equipo/internal/headless TestBrowserChatSendStaysOnPage
+ 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 66936946ef1d79ad5f698be3b071d2489a0b7417 6.59s 58.23
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
##############################################################################
FLAKE ./internal/headless:TestBrowserChatSendStaysOnPage browser-headless-chat 66936946ef1d79ad5f698be3b071d2489a0b7417 6.11s 58.23
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
##############################################################################
FLAKE ./internal/headless:TestBrowserDraftIsTheMessage browser-headless-chat 66936946ef1d79ad5f698be3b071d2489a0b7417 8.14s 58.23
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 53.39, cpu waiting 32.38%, memory waiting 0.00%, io waiting 0.34%
--- 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-20T06:16:06.994Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-20T06:16:06.994Z level=INFO msg="startup phase done" phase=state_lock took=73µs
time=2026-11-20T06:16:06.994Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-20T06:16:06.994Z level=INFO msg="startup phase done" phase=claim_roots took=86µs
time=2026-11-20T06:16:06.994Z level=INFO msg="startup phase" phase=sweep
time=2026-11-20T06:16:07.025Z level=INFO msg="startup phase done" phase=sweep took=31.065ms
time=2026-11-20T06:16:07.025Z level=INFO msg="startup phase" phase=credentials
time=2026-11-20T06:16:07.026Z level=INFO msg="startup phase done" phase=credentials took=102µs
time=2026-11-20T06:16:07.026Z level=INFO msg="startup phase" phase=open_state
time=2026-11-20T06:16:07.066Z level=INFO msg="startup phase done" phase=open_state took=40.165ms
time=2026-11-20T06:16:07.066Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-20T06:16:07.067Z level=INFO msg=connecting host=127.0.0.1:39523 protocol=28
time=2026-11-20T06:16:07.068Z level=INFO msg=connected host=127.0.0.1:39523 took=940µs
time=2026-11-20T06:16:07.068Z level=INFO msg="capabilities gathering"
time=2026-11-20T06:16:07.069Z level=INFO msg="capabilities gathered" took=761µs tags=linux,claude,go
time=2026-11-20T06:16:07.069Z level=INFO msg="hello sent" protocol=28
time=2026-11-20T06:16:07.073Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-20T06:16:08.376Z level=INFO msg="connection checked" connection=claude-1 state=healthy
time=2026-11-20T06:16:17.518Z level=INFO msg="kept sessions" kept=1 bytes=2770 expired=0
time=2026-11-20T06:16:21.991Z level=INFO msg="kept sessions" kept=2 bytes=4922 expired=0
time=2026-11-20T06:16:22.822Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-20T06:16:22.823Z level=INFO msg="startup phase done" phase=state_lock took=148µs
time=2026-11-20T06:16:22.823Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-20T06:16:22.823Z level=INFO msg="startup phase done" phase=claim_roots took=154µs
time=2026-11-20T06:16:22.823Z level=INFO msg="startup phase" phase=sweep
time=2026-11-20T06:16:22.879Z level=INFO msg="startup phase done" phase=sweep took=56.585ms
time=2026-11-20T06:16:22.880Z level=INFO msg="startup phase" phase=credentials
time=2026-11-20T06:16:22.880Z level=INFO msg="startup phase done" phase=credentials took=212µs
time=2026-11-20T06:16:22.881Z level=INFO msg="startup phase" phase=open_state
time=2026-11-20T06:16:22.964Z level=INFO msg="startup phase done" phase=open_state took=83.027ms
time=2026-11-20T06:16:22.965Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-20T06:16:22.967Z level=INFO msg=connecting host=127.0.0.1:41935 protocol=28
time=2026-11-20T06:16:22.970Z level=INFO msg=connected host=127.0.0.1:41935 took=1.51ms
time=2026-11-20T06:16:22.970Z level=INFO msg="capabilities gathering"
time=2026-11-20T06:16:22.971Z level=INFO msg="capabilities gathered" took=986µs tags=linux,claude,go
time=2026-11-20T06:16:22.979Z level=INFO msg="hello sent" protocol=28
time=2026-11-20T06:16:22.986Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-20T06:16:25.175Z 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)
--- FAIL: TestBrowserRailFollowsWork (22.39s)

--- FAIL amadan.net/oficina/equipo/internal/headless (package output)
FAIL
rastrillo-budget/v1 ran 1m36.525s
FAIL	amadan.net/oficina/equipo/internal/headless	96.856s


receipt: test step 1m38.438s 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 1m36.525s amadan.net/oficina/equipo/internal/headless
receipt: slow test 26.74s amadan.net/oficina/equipo/internal/headless TestBrowserTaskThread
receipt: slow test 22.39s amadan.net/oficina/equipo/internal/headless TestBrowserRailFollowsWork
receipt: slow test 14.5s amadan.net/oficina/equipo/internal/headless TestBrowserReceiptFollowsReview
receipt: slow test 11.43s amadan.net/oficina/equipo/internal/headless TestBrowserTaskCard
receipt: slow test 11.38s amadan.net/oficina/equipo/internal/headless TestBrowserAskAfterMerge
rastrillo: budget test: go test failed
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 66936946ef1d79ad5f698be3b071d2489a0b7417 22.39s 61.24
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 45.94, cpu waiting 25.73%, memory waiting 0.00%, io waiting 0.27%
--- 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 1m47.476s 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 1m45.38s amadan.net/oficina/equipo/internal/headless
receipt: slow test 17.47s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsConversation
receipt: slow test 13.58s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsAdd
receipt: slow test 13.06s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsAddPage
receipt: slow test 10.97s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsMeteredLimitRequired
receipt: slow test 10.57s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsOpenCodeGoLimitRequired
machine: 32 CPUs, load 53.39, cpu waiting 32.38%, memory waiting 0.00%, io waiting 0.34%
--- 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 TestBrowserCopyContinue
=== RUN   TestBrowserCopyContinue
time=2026-11-20T06:16:22.113Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-20T06:16:22.113Z level=INFO msg="startup phase done" phase=state_lock took=84µs
time=2026-11-20T06:16:22.113Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-20T06:16:22.113Z level=INFO msg="startup phase done" phase=claim_roots took=86µs
time=2026-11-20T06:16:22.113Z level=INFO msg="startup phase" phase=sweep
time=2026-11-20T06:16:22.187Z level=INFO msg="startup phase done" phase=sweep took=73.904ms
time=2026-11-20T06:16:22.187Z level=INFO msg="startup phase" phase=credentials
time=2026-11-20T06:16:22.187Z level=INFO msg="startup phase done" phase=credentials took=108µs
time=2026-11-20T06:16:22.187Z level=INFO msg="startup phase" phase=open_state
time=2026-11-20T06:16:22.247Z level=INFO msg="startup phase done" phase=open_state took=59.573ms
time=2026-11-20T06:16:22.247Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-20T06:16:22.248Z level=INFO msg=connecting host=127.0.0.1:46277 protocol=28
time=2026-11-20T06:16:22.250Z level=INFO msg=connected host=127.0.0.1:46277 took=2.096ms
time=2026-11-20T06:16:22.251Z level=INFO msg="capabilities gathering"
time=2026-11-20T06:16:22.252Z level=INFO msg="capabilities gathered" took=1.057ms tags=linux,claude,go
time=2026-11-20T06:16:22.255Z level=INFO msg="hello sent" protocol=28
time=2026-11-20T06:16:22.278Z level=INFO msg=welcome protocol=28 role=primary generation=1
    browser_copy_test.go:90: waiting for !document.querySelector('[data-copy-continue]'): context deadline exceeded (last evaluation: context deadline exceeded)
--- FAIL: TestBrowserCopyContinue (6.45s)

--- FAIL amadan.net/oficina/equipo/internal/headless TestBrowserEmptyExplore
=== RUN   TestBrowserEmptyExplore
time=2026-11-20T06:17:02.197Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-20T06:17:02.197Z level=INFO msg="startup phase done" phase=state_lock took=60µs
time=2026-11-20T06:17:02.197Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-20T06:17:02.197Z level=INFO msg="startup phase done" phase=claim_roots took=76µs
time=2026-11-20T06:17:02.197Z level=INFO msg="startup phase" phase=sweep
time=2026-11-20T06:17:02.227Z level=INFO msg="startup phase done" phase=sweep took=30.389ms
time=2026-11-20T06:17:02.227Z level=INFO msg="startup phase" phase=credentials
time=2026-11-20T06:17:02.227Z level=INFO msg="startup phase done" phase=credentials took=131µs
time=2026-11-20T06:17:02.227Z level=INFO msg="startup phase" phase=open_state
time=2026-11-20T06:17:02.268Z level=INFO msg="startup phase done" phase=open_state took=40.44ms
time=2026-11-20T06:17:02.268Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-20T06:17:02.269Z level=INFO msg=connecting host=127.0.0.1:34447 protocol=28
time=2026-11-20T06:17:02.270Z level=INFO msg=connected host=127.0.0.1:34447 took=1.016ms
time=2026-11-20T06:17:02.270Z level=INFO msg="capabilities gathering"
time=2026-11-20T06:17:02.271Z level=INFO msg="capabilities gathered" took=517µs tags=linux,claude,go
time=2026-11-20T06:17:02.271Z level=INFO msg="hello sent" protocol=28
time=2026-11-20T06:17:02.277Z level=INFO msg=welcome protocol=28 role=primary generation=1
time=2026-11-20T06:17:03.306Z 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: context deadline exceeded)
--- FAIL: TestBrowserEmptyExplore (5.83s)

--- FAIL amadan.net/oficina/equipo/internal/headless (package output)
FAIL
rastrillo-budget/v1 ran 1m39.016s
FAIL	amadan.net/oficina/equipo/internal/headless	99.333s


receipt: test step 1m40.968s 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 1m39.016s amadan.net/oficina/equipo/internal/headless
receipt: slow test 15.19s amadan.net/oficina/equipo/internal/headless TestBrowserThinkingAndCards
receipt: slow test 12.83s amadan.net/oficina/equipo/internal/headless TestBrowserWaitingTurns
receipt: slow test 11.46s amadan.net/oficina/equipo/internal/headless TestBrowserStalePageReloads
receipt: slow test 10.82s amadan.net/oficina/equipo/internal/headless TestBrowserMoveIn
receipt: slow test 8.06s amadan.net/oficina/equipo/internal/headless TestBrowserRefreshRace
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 '^TestBrowserCopyContinue$|^TestBrowserEmptyExplore$' -count=1 ./internal/headless   (retry, once)
##############################################################################
FLAKE ./internal/headless:TestBrowserCopyContinue browser-headless-rest 66936946ef1d79ad5f698be3b071d2489a0b7417 6.45s 61.24
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
##############################################################################
FLAKE ./internal/headless:TestBrowserEmptyExplore browser-headless-rest 66936946ef1d79ad5f698be3b071d2489a0b7417 5.83s 61.24
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 49.67, cpu waiting 30.39%, memory waiting 0.00%, io waiting 0.32%
--- 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 2.26s 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 555ms amadan.net/oficina/equipo/internal/equipo
receipt: slow test 550ms 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.86s 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.597s amadan.net/oficina/equipo/internal/idtest
receipt: slow test 1.6s 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.198s 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.923s amadan.net/oficina/equipo/internal/plan3test
receipt: slow test 1.92s 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 3m4.317s 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 3m2.74s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 18.32s amadan.net/oficina/equipo/internal/thintest TestBrowserAccessRequest
receipt: slow test 14.33s amadan.net/oficina/equipo/internal/thintest TestBrowserSettingsTeams
receipt: slow test 10.66s amadan.net/oficina/equipo/internal/thintest TestBrowserPlacementQuestionAndPending
receipt: slow test 9.06s amadan.net/oficina/equipo/internal/thintest TestBrowserThinkingCycles
receipt: slow test 8.3s amadan.net/oficina/equipo/internal/thintest TestBrowserInnerScreens
machine: 32 CPUs, load 15.95, cpu waiting 7.78%, memory waiting 0.00%, io waiting 0.07%
--- 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.25s
ok ./internal/headless TestHeadlessConnections/C4_claude_sign_in 1.43s
ok ./internal/headless TestHeadlessConnections/C5_engineering_failover 10.31s
ok ./internal/headless TestHeadlessConnections/C5_engineering_to_codex 10.65s
ok ./internal/headless TestHeadlessConnections/C5_engineering_waits 27.31s
+ 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   (76s)
ok ./internal/headless TestHeadlessConnections/C5_review_auth 17.41s
ok ./internal/headless TestHeadlessConnections/C5_review_failover 17.81s
ok ./internal/headless TestHeadlessConnections/C5_review_on_codex 21.54s
ok ./internal/headless TestHeadlessConnections/C5_review_other_family_first 15.92s
+ go test -tags testbuild -timeout 15m -v -run '^TestMixedVersions$' ./internal/headless   (24s)
ok ./internal/headless TestMixedVersions 21.18s
+ go test -tags testbuild -timeout 15m -v -run '^TestCheckSandboxDeniedPathsTampering$' ./internal/runner/checks   (2s)
ok ./internal/runner/checks TestCheckSandboxDeniedPathsTampering 1.02s
+ go test -tags testbuild -timeout 15m -v -run '^TestRunnerCancelAndSupersede$' ./internal/runner/thin   (3s)
ok ./internal/runner/thin TestRunnerCancelAndSupersede 0.05s
quarantine: 0 flaked (passed on the retry), 0 failed
machine: 32 CPUs, load 67.81, cpu waiting 39.48%, memory waiting 0.00%, io waiting 0.61%
--- 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 12.719s 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.476s amadan.net/oficina/equipo/internal/runner/checks
receipt: slow package 169ms amadan.net/oficina/equipo/internal/runner/provider/claude
receipt: slow package 73ms 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.3s amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPathsGoFixture
receipt: slow test 1.68s amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPaths
receipt: slow test 380ms amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPathsCache
receipt: slow test 170ms amadan.net/oficina/equipo/internal/runner/provider/claude TestDirectJournalAdapterBarrier
receipt: slow test 100ms amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxToolchain
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.473s 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 3.096s amadan.net/oficina/equipo/internal/runner/containment
receipt: slow test 300ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceReadOnlyScratch
receipt: slow test 220ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryUnavailableProof
receipt: slow test 140ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryCleansScratch
receipt: slow test 120ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceDirectPolicyAdmission
receipt: slow test 110ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceExitStatus
machine: 32 CPUs, load 12.30, cpu waiting 10.42%, memory waiting 0.00%, io waiting 1.61%
--- 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 35.9%, load 23.22
shard 25: make runner-dead-references lanes-check build vet fmt-check budget migration-check
python3 scripts/runner-dead-references.py
reference scan: 2462 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.507s
machine: 32 CPUs, load 67.81, cpu waiting 39.09%, memory waiting 0.00%, io waiting 0.63%
--- 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 35.9%, load 23.22
shard 26: make staticcheck
go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 -tags browser,perf,testbuild ./...
machine: 32 CPUs, load 59.66, cpu waiting 34.10%, memory waiting 0.00%, io waiting 0.88%
--- 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 34.5%, load 23.22
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 37.87, cpu waiting 23.15%, memory waiting 0.00%, io waiting 1.11%
--- 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 35.9%, load 23.22
shard 28: make gitleaks
6:16AM INF Unknown SCM platform. Use --platform to include links in findings. host=amadan.net
6:16AM INF 1024 commits scanned.
6:16AM INF scanned ~60093190 bytes (60.09 MB) in 23.2s
6:16AM INF no leaks found
machine: 32 CPUs, load 59.66, cpu waiting 34.10%, memory waiting 0.00%, io waiting 0.88%
=== 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.097ms, worst 1.131ms, budget 150ms
perf: GET /api/runner/protocol: median 89µs, worst 109µs, budget 150ms
perf: GET /api/v1/account-setups/{id}: median 609µs, worst 655µs, budget 150ms
perf: GET /api/v1/accounts: median 423µs, worst 454µs, budget 150ms
perf: GET /api/v1/auth/devices: median 436µs, worst 485µs, budget 150ms
perf: GET /api/v1/budgets: median 499µs, worst 508µs, budget 150ms
perf: GET /api/v1/capabilities: median 253µs, worst 300µs, budget 150ms
perf: GET /api/v1/cards/{id}: median 1.254ms, worst 1.334ms, budget 150ms
perf: GET /api/v1/connections: median 574µs, worst 625µs, budget 150ms
perf: GET /api/v1/connections/{id}: median 572µs, worst 581µs, budget 150ms
perf: GET /api/v1/conversation: median 905µs, worst 941µs, budget 150ms
perf: GET /api/v1/conversation/cards: median 1.486ms, worst 1.538ms, budget 150ms
perf: GET /api/v1/coordinator: median 1.835ms, worst 1.918ms, budget 150ms
perf: GET /api/v1/invites/{id}: median 460µs, worst 541µs, budget 150ms
perf: GET /api/v1/journey: median 10.668ms, worst 11.165ms, budget 150ms
perf: GET /api/v1/me: median 487µs, worst 523µs, budget 150ms
perf: GET /api/v1/me/settings: median 577µs, worst 610µs, budget 150ms
perf: GET /api/v1/needs-you: median 9.984ms, worst 10.917ms, budget 150ms
perf: GET /api/v1/notifications: median 1.655ms, worst 1.717ms, budget 150ms
perf: GET /api/v1/onboarding: median 413µs, worst 486µs, budget 150ms
perf: GET /api/v1/people: median 425µs, worst 446µs, budget 150ms
perf: GET /api/v1/playbooks: median 601µs, worst 629µs, budget 150ms
perf: GET /api/v1/playbooks/{id}: median 524µs, worst 556µs, budget 150ms
perf: GET /api/v1/playbooks/{id}/template-diff: median 849µs, worst 912µs, budget 150ms
perf: GET /api/v1/preferences: median 765µs, worst 771µs, budget 150ms
perf: GET /api/v1/projects/{id}: median 468µs, worst 486µs, budget 150ms
perf: GET /api/v1/projects/{id}/settings: median 590µs, worst 672µs, budget 150ms
perf: GET /api/v1/roster: median 479µs, worst 564µs, budget 150ms
perf: GET /api/v1/runners/{id}: median 430µs, worst 461µs, budget 150ms
perf: GET /api/v1/specialists: median 8.017ms, worst 8.318ms, budget 150ms
perf: GET /api/v1/specialists/{id}: median 7.859ms, worst 8ms, budget 150ms
perf: GET /api/v1/specialists/{id}/template-diff: median 821µs, worst 872µs, budget 150ms
perf: GET /api/v1/tasks/{id}/plan: median 1.125ms, worst 1.151ms, budget 150ms
perf: GET /api/v1/tasks/{id}/thread: median 688µs, worst 729µs, budget 150ms
perf: GET /api/v1/teams: median 411µs, worst 445µs, budget 150ms
perf: GET /api/v1/templates: median 590µs, worst 611µs, budget 150ms
perf: GET /api/v1/templates/{id}: median 446µs, worst 485µs, budget 150ms
perf: GET /auth/callback: median 80µs, worst 105µs, budget 150ms
perf: GET /auth/devices/{id}: median 3.315ms, worst 3.386ms, budget 150ms
perf: GET /auth/verify: median 87µs, worst 108µs, budget 150ms
perf: GET /connections: median 3.686ms, worst 3.746ms, budget 150ms
perf: GET /conversation: median 8.09ms, worst 10.342ms, budget 150ms
perf: GET /conversation/connections: median 256µs, worst 274µs, budget 150ms
perf: GET /conversation/notebook: median 251µs, worst 261µs, budget 150ms
perf: GET /conversation/settings: median 3.997ms, worst 4.128ms, budget 150ms
perf: GET /conversation/settings/autonomy: median 3.631ms, worst 3.81ms, budget 150ms
perf: GET /conversation/settings/connections: median 6.293ms, worst 6.558ms, budget 150ms
perf: GET /conversation/settings/connections/add: median 6.44ms, worst 6.677ms, budget 150ms
perf: GET /conversation/settings/copy: median 3.552ms, worst 3.638ms, budget 150ms
perf: GET /conversation/settings/housekeeping: median 3.983ms, worst 4.143ms, budget 150ms
perf: GET /conversation/settings/machines: median 4.32ms, worst 4.442ms, budget 150ms
perf: GET /conversation/settings/machines/add: median 4.58ms, worst 4.758ms, budget 150ms
perf: GET /conversation/settings/notebook: median 3.484ms, worst 3.538ms, budget 150ms
perf: GET /conversation/settings/thinking: median 3.993ms, worst 4.096ms, budget 150ms
perf: GET /housekeeping: median 3.872ms, worst 4.049ms, budget 150ms
perf: GET /invites/new: median 589µs, worst 618µs, budget 150ms
perf: GET /invites/{id}: median 616µs, worst 650µs, budget 150ms
perf: GET /jobs: median 3.414ms, worst 3.555ms, budget 150ms
perf: GET /jobs/{id}: median 4.416ms, worst 4.63ms, budget 150ms
perf: GET /journey: median 11.77ms, worst 11.924ms, budget 150ms
perf: GET /nav/rail: median 2.999ms, worst 3.083ms, budget 150ms
perf: GET /needs-you: median 11.695ms, worst 14.22ms, budget 150ms
perf: GET /onboarding: median 4.076ms, worst 4.11ms, budget 150ms
perf: GET /people: median 3.395ms, worst 3.432ms, budget 150ms
perf: GET /playbook-suggestions/{suggestion}: median 4.839ms, worst 4.887ms, budget 150ms
perf: GET /playbooks: median 4.395ms, worst 4.565ms, budget 150ms
perf: GET /playbooks/new: median 4.461ms, worst 4.576ms, budget 150ms
perf: GET /playbooks/{id}: median 5.364ms, worst 5.413ms, budget 150ms
perf: GET /playbooks/{id}/edit: median 5.2ms, worst 5.489ms, budget 150ms
perf: GET /playbooks/{id}/template-diff: median 4.401ms, worst 4.487ms, budget 150ms
perf: GET /preferences: median 4.358ms, worst 4.448ms, budget 150ms
perf: GET /preferences/sources/{source}: median 4.293ms, worst 6.985ms, budget 150ms
perf: GET /projects: median 5.503ms, worst 5.671ms, budget 150ms
perf: GET /projects/accounts: median 3.578ms, worst 3.764ms, budget 150ms
perf: GET /projects/new: median 3.576ms, worst 3.685ms, budget 150ms
perf: GET /projects/{id}: median 10.675ms, worst 10.798ms, budget 150ms
perf: GET /projects/{id}/edit: median 3.68ms, worst 3.716ms, budget 150ms
perf: GET /runners/enrol: median 4.339ms, worst 4.455ms, budget 150ms
perf: GET /settings: median 3.362ms, worst 3.446ms, budget 150ms
perf: GET /settings/coordinator: median 5.643ms, worst 5.924ms, budget 150ms
perf: GET /settings/devices: median 3.286ms, worst 3.495ms, budget 150ms
perf: GET /settings/recovery: median 3.477ms, worst 6.151ms, budget 150ms
perf: GET /settings/recovery/release: median 3.45ms, worst 3.603ms, budget 150ms
perf: GET /settings/thinking: median 248µs, worst 263µs, budget 150ms
perf: GET /signin: median 329µs, worst 336µs, budget 150ms
perf: GET /specialists/new: median 3.334ms, worst 3.366ms, budget 150ms
perf: GET /specialists/{key}: median 10.751ms, worst 10.958ms, budget 150ms
perf: GET /specialists/{key}/edit: median 3.495ms, worst 3.597ms, budget 150ms
perf: GET /specialists/{key}/template-diff: median 3.573ms, worst 3.663ms, budget 150ms
perf: GET /tasks: median 5.107ms, worst 5.191ms, budget 150ms
perf: GET /tasks/new: median 3.115ms, worst 3.178ms, budget 150ms
perf: GET /tasks/{id}: median 5.295ms, worst 5.477ms, budget 150ms
perf: GET /tasks/{id}/merge: median 4.823ms, worst 7.451ms, budget 150ms
perf: GET /tasks/{id}/move: median 4.732ms, worst 4.974ms, budget 150ms
perf: GET /tasks/{id}/plan: median 5.71ms, worst 5.955ms, budget 150ms
perf: GET /tasks/{id}/preview: median 1.465ms, worst 1.626ms, budget 150ms
perf: GET /tasks/{id}/questions/{question}: median 5.036ms, worst 5.123ms, budget 150ms
perf: GET /tasks/{id}/rendered-change: median 4.573ms, worst 4.664ms, budget 150ms
perf: GET /tasks/{id}/rendered-change/{hash}.png: median 4.2ms, worst 4.37ms, budget 150ms
perf: GET /tasks/{id}/thread: median 7.693ms, worst 7.922ms, budget 150ms
perf: GET /team/{specialist}: median 4.127ms, worst 4.288ms, budget 150ms
perf: GET /teams: median 9.817ms, worst 11.687ms, budget 150ms
perf: GET /templates: median 3.442ms, worst 3.665ms, budget 150ms
perf: GET /usage: median 4.099ms, worst 4.215ms, budget 150ms
perf: GET /work: median 3.014ms, worst 3.088ms, budget 150ms
perf: cold boot: median 259ms of [258.242915ms 258.935768ms 259.873635ms], budget 500ms

receipt: test step 45.283s 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.948s 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 8.12s amadan.net/oficina/equipo/internal/equipotest TestPerfScreens
receipt: slow test 830ms amadan.net/oficina/equipo/internal/equipotest TestPerfBoot
=== cache ===
ci-box: build cache /home/ci/work/repos/oficina__equipo/cache/go-build: 4.24 GiB in 25183 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.67 GiB this job did not read, kept 2.58 GiB
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 3cb43ae3..6e1aa410 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -14,8 +14,8 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr
time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI.
time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage.
-size internal/equipo 21378 - Fable follow-up: base and diagnostic gates, preview isolation and provenance guards; measured 21378/3196 source/test lines.
-size internal/wire 6637 - Fable follow-up: base and diagnostic gates, preview isolation and provenance guards; measured 6637/2972 source/test lines.
+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/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);
time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s).
@@ -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 - 11358 Plan 3 release-boundary and copy-inventory contracts in one package; measured 940/11358 source/test lines.
+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.
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 31167 - Fable follow-up: base and diagnostic gates, preview isolation and provenance guards; measured 31167/6180 source/test lines.
+size internal/equipo/chat 31700 - Native slice 2: push registrations, the push outbox and its rules, set aside; measured 31700/6180 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/cmd/equipo/main.go b/cmd/equipo/main.go
index 5f3930a7..6b63bc68 100644
--- a/cmd/equipo/main.go
+++ b/cmd/equipo/main.go
@@ -34,6 +34,10 @@ func run(logger *slog.Logger, started time.Time) error {
if err != nil {
return err
}
+ // Pushes too: only here, where Equipo serves.
+ if cfg.Push, err = equipo.Pusher(cfg, logger, os.Getenv); err != nil {
+ return err
+ }
opts, err := rastrillo.Resolve(rastrillo.Options{DBPath: cfg.DatabaseName, Logger: logger})
if err != nil {
return err
diff --git a/docs/api/equipo-v1.md b/docs/api/equipo-v1.md
index b883b91b..e3e7a3bb 100644
--- a/docs/api/equipo-v1.md
+++ b/docs/api/equipo-v1.md
@@ -119,6 +119,27 @@ A successful answer returns `200` with `card`, `message` and `turn`. When the an
Cancel a turn in flight with `POST /api/v1/turns/{id}/cancel`. It returns `202` with the turn’s `attempt`, or `409 turn_ended` once the turn has ended. Post to a task’s thread with `POST /api/v1/tasks/{id}/thread`. Move a task to another project with `POST /api/v1/tasks/{id}/move`. The contract lists the other routes and their request bodies.
+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.
+
+## Receive pushes on a device
+
+Register the device with `POST /api/v1/push-registrations` and the device's bearer token:
+
+```json
+{"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`.
+
+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.
+
+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.
+
## Talk to the Assistant
The routes under `/api/v1/assistant` serve Base's chat with the Assistant. Every route, `events` included, takes only `Authorization: Bearer <token>` with a person device token (audience `equipo.person.v1`). A session cookie is not accepted, and a request without a bearer gets `401 unauthenticated`. Every response has `Cache-Control: no-store`. Errors have the same body as the rest of this API: `code`, `copy_key`, `request_id` and, where it applies, `current_revision`.
diff --git a/docs/api/equipo-v1.openapi.json b/docs/api/equipo-v1.openapi.json
index 0ae1655d..f348a7e0 100644
--- a/docs/api/equipo-v1.openapi.json
+++ b/docs/api/equipo-v1.openapi.json
@@ -13395,6 +13395,218 @@
"x-rejectUnknownFields": true
}
}
+ },
+ "/cards/{id}/visibility": {
+ "post": {
+ "operationId": "post_cards_id_visibility",
+ "summary": "Set a card aside, or bring it back",
+ "description": "Send `aside` and the card's current `revision`. Setting a card aside never answers, cancels or starts anything: it stays in Needs you, and the card's `aside` says it is set aside for you. The answer is 200 with the card. A stale revision, or a card that no longer waits on you, is 409 with `code` `card_stale` and the card as it is now.",
+ "security": [
+ {
+ "personBearer": []
+ }
+ ],
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 1
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "headers": {
+ "Cache-Control": {
+ "schema": {
+ "const": "no-store"
+ }
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Card"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "Conflict: the resource as it is now",
+ "headers": {
+ "Cache-Control": {
+ "schema": {
+ "const": "no-store"
+ }
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CardConflict"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/unauthenticated"
+ },
+ "default": {
+ "description": "An error, with one of the codes in `Error`",
+ "headers": {
+ "Cache-Control": {
+ "schema": {
+ "const": "no-store"
+ }
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ }
+ },
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SetCardVisibility"
+ }
+ }
+ },
+ "x-maxBytes": 32768,
+ "x-rejectUnknownFields": true
+ }
+ }
+ },
+ "/push-registrations": {
+ "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.",
+ "security": [
+ {
+ "personBearer": []
+ }
+ ],
+ "parameters": [],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "headers": {
+ "Cache-Control": {
+ "schema": {
+ "const": "no-store"
+ }
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PushRegistration"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/unauthenticated"
+ },
+ "default": {
+ "description": "An error, with one of the codes in `Error`",
+ "headers": {
+ "Cache-Control": {
+ "schema": {
+ "const": "no-store"
+ }
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ }
+ },
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RegisterPush"
+ }
+ }
+ },
+ "x-maxBytes": 32768,
+ "x-rejectUnknownFields": true
+ }
+ }
+ },
+ "/push-registrations/activities": {
+ "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.",
+ "security": [
+ {
+ "personBearer": []
+ }
+ ],
+ "parameters": [],
+ "responses": {
+ "204": {
+ "description": "No Content",
+ "headers": {
+ "Cache-Control": {
+ "schema": {
+ "const": "no-store"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/unauthenticated"
+ },
+ "default": {
+ "description": "An error, with one of the codes in `Error`",
+ "headers": {
+ "Cache-Control": {
+ "schema": {
+ "const": "no-store"
+ }
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ }
+ },
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RegisterActivity"
+ }
+ }
+ },
+ "x-maxBytes": 32768,
+ "x-rejectUnknownFields": true
+ }
+ }
}
},
"components": {
@@ -18025,6 +18237,9 @@
},
"advice": {
"$ref": "#/components/schemas/Advice"
+ },
+ "aside": {
+ "type": "boolean"
}
},
"required": [
@@ -22811,6 +23026,94 @@
],
"additionalProperties": false,
"x-go-type": "wire.ProjectAutonomy"
+ },
+ "PushRegistration": {
+ "type": "object",
+ "properties": {
+ "environment": {
+ "type": "string",
+ "enum": [
+ "production",
+ "development"
+ ]
+ },
+ "platform": {
+ "type": "string",
+ "enum": [
+ "ios",
+ "macos"
+ ]
+ },
+ "live_activities": {
+ "type": "boolean"
+ },
+ "updated_at": {
+ "type": "string",
+ "format": "date-time"
+ }
+ },
+ "required": [
+ "environment",
+ "platform",
+ "live_activities",
+ "updated_at"
+ ],
+ "additionalProperties": false,
+ "x-go-type": "wire.PushRegistration"
+ },
+ "RegisterActivity": {
+ "type": "object",
+ "properties": {
+ "task_id": {
+ "type": "string"
+ },
+ "token": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": false,
+ "x-go-type": "wire.RegisterActivity"
+ },
+ "RegisterPush": {
+ "type": "object",
+ "properties": {
+ "token": {
+ "type": "string"
+ },
+ "environment": {
+ "type": "string",
+ "enum": [
+ "production",
+ "development"
+ ]
+ },
+ "platform": {
+ "type": "string",
+ "enum": [
+ "ios",
+ "macos"
+ ]
+ },
+ "start_token": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": false,
+ "x-go-type": "wire.RegisterPush"
+ },
+ "SetCardVisibility": {
+ "type": "object",
+ "properties": {
+ "aside": {
+ "type": "boolean"
+ },
+ "revision": {
+ "type": "integer",
+ "format": "int64"
+ }
+ },
+ "additionalProperties": false,
+ "x-go-type": "wire.SetCardVisibility"
}
},
"responses": {
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index c527812c..6ef65a37 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -6750,6 +6750,18 @@ records remain unchanged.
| `access.waiting` | Waiting for your approval on Amadan… | Copy specialist | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
| `access.reopen` | Open Amadan again | Copy specialist | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-17) |
| `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) |
+| `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) |
+| `push.task.done` | Done. | passive notification body when a task the person started is done (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.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) |
## Task 21
diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index d0f35224..69ada63f 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -17,6 +17,7 @@ import (
"github.com/go-chi/chi/v5"
"amadan.net/oficina/equipo/internal/equipo/personapi"
+ "amadan.net/oficina/equipo/internal/equipo/push"
"amadan.net/oficina/equipo/internal/release"
"amadan.net/oficina/equipo/internal/wire"
"amadan.net/rastrillo/rastrillo"
@@ -32,6 +33,8 @@ import (
)
type application struct {
+ // push is the push transport (Config.Push); nil, no sender runs.
+ push push.Transport
home *oficinaid.HTTP
installAssets *release.InstallAssets
executionEnabled bool
@@ -72,6 +75,11 @@ func (a *application) startBackground() *background.Group {
defer stop()
a.store.Chat().ServeRemoteCalls(calls)
})
+ // The push sender, only where serving built a transport.
+ if a.push != nil {
+ sender := a.store.Chat().PushSender(a.push)
+ a.background.Go(func() { sender.Serve(calls, a.store.Chat().PushWake(), pushEvery) })
+ }
a.background.Loop(context.Background(), time.Minute, func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
@@ -107,6 +115,10 @@ func (a *application) startBackground() *background.Group {
return &a.background
}
+// pushEvery is how often the push sender looks for due rows without a
+// wake (retries, another process's writes).
+const pushEvery = 5 * time.Second
+
// App composes the router and embedded assets used by every harness.
func App(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger) (*http.ServeMux, error) {
r, err := Router(d, cfg, mailer, logger)
@@ -169,6 +181,8 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
"skipped", migrated.Skipped, "adopted", migrated.Adopted)
store.chatExecution, store.chatTestPeople, store.chatOrigin, store.chatAssistantHosts = cfg.ExecutionEnabled, cfg.TestPeople, cfg.Origin, cfg.AssistantHosts
+ // The push outbox is written only where a sender will drain it.
+ store.Chat().SetPush(cfg.Push != nil)
// What the Assistant's provider calls could not do, by call id only.
store.Chat().SetLogger(logger)
if cfg.OficinaConnectOrigin != "" {
@@ -213,7 +227,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
if err != nil {
return nil, err
}
- a := &application{installAssets: release.NewInstallAssets(cfg.RunnerReleaseDir, rastrillo.BuildVersion, release.BuildManifest()), executionEnabled: cfg.ExecutionEnabled, Router: chi.NewRouter(), auth: authentication, store: store, logger: logger, nonces: pow.SQLNonces(d.Writer()), origin: cfg.Origin}
+ a := &application{installAssets: release.NewInstallAssets(cfg.RunnerReleaseDir, rastrillo.BuildVersion, release.BuildManifest()), executionEnabled: cfg.ExecutionEnabled, Router: chi.NewRouter(), auth: authentication, store: store, logger: logger, nonces: pow.SQLNonces(d.Writer()), origin: cfg.Origin, push: cfg.Push}
if cfg.Home != nil {
storeID, e := oficinaid.New(d.Writer(), cfg.Origin, cfg.Home)
if e != nil {
diff --git a/internal/equipo/chat/http.go b/internal/equipo/chat/http.go
index 05155197..7f0741c4 100644
--- a/internal/equipo/chat/http.go
+++ b/internal/equipo/chat/http.go
@@ -85,6 +85,9 @@ func (h *HTTP) Mount(r chi.Router) {
r.Post("/projects", h.bearer(h.addProject))
r.Delete("/projects/{id}", h.bearer(h.removeProject))
r.Post("/cards/{id}/answer", h.bearer(h.answer))
+ r.Post("/cards/{id}/visibility", h.bearer(h.cardVisibility))
+ r.Post("/push-registrations", h.bearer(h.registerPush))
+ r.Post("/push-registrations/activities", h.bearer(h.registerActivity))
r.Get("/notebook", h.bearer(h.notebook))
r.Post("/notebook/reset", h.bearer(h.resetNotebook))
r.Delete("/notebook/corrections/{id}", h.bearer(h.removePlacementNote))
@@ -627,6 +630,9 @@ func (h *HTTP) events(w http.ResponseWriter, r *http.Request) {
// cursor, rechecking the person before each batch and ping.
func (h *HTTP) stream(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal, lane string, read func(context.Context, string, int64, int) ([]wire.Event, error)) {
ctx := personapi.WithVerifiedPrincipal(r.Context(), p)
+ if lane == wire.LaneCoordinator {
+ defer h.Store.Hub().Follow(p.Address)()
+ }
// Live-only events (a glance) come from the moment the stream opens.
live, stop := h.Store.Hub().Live(p.Address, lane)
defer stop()
diff --git a/internal/equipo/chat/hub.go b/internal/equipo/chat/hub.go
index de56ed80..ce8ac102 100644
--- a/internal/equipo/chat/hub.go
+++ b/internal/equipo/chat/hub.go
@@ -19,6 +19,9 @@ type Hub struct {
// never stored (a glance): sent to whoever is following now, and
// missed by anyone who is not.
live map[*liveSub]bool
+ // streams counts each person's open /events streams in this process
+ // (Streaming): a reply pushes only to someone not following.
+ streams map[string]int
}
type liveSub struct {
@@ -27,7 +30,7 @@ type liveSub struct {
}
func NewHub() *Hub {
- return &Hub{waiters: map[string]chan struct{}{}, runners: map[string]registration{}, closing: make(chan struct{}), live: map[*liveSub]bool{}}
+ return &Hub{waiters: map[string]chan struct{}{}, runners: map[string]registration{}, closing: make(chan struct{}), live: map[*liveSub]bool{}, streams: map[string]int{}}
}
// Live follows the person's live-only events in one lane, until stop.
@@ -44,6 +47,29 @@ func (h *Hub) Live(person, lane string) (events <-chan wire.Event, stop func())
}
}
+// Follow counts an open /events stream of the person's until done.
+func (h *Hub) Follow(person string) (done func()) {
+ h.mu.Lock()
+ h.streams[person]++
+ h.mu.Unlock()
+ return func() {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ if h.streams[person]--; h.streams[person] <= 0 {
+ delete(h.streams, person)
+ }
+ }
+}
+
+// Streaming reports whether the person has an /events stream open in this
+// process. Another process's (a deploy overlap) is not seen: a reply then
+// may push while they watch, never the other way round.
+func (h *Hub) Streaming(person string) bool {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ return h.streams[person] > 0
+}
+
// publish hands a live-only event to the person's streams in its lane
// in this process, without waiting for any.
func (h *Hub) publish(person, lane string, e wire.Event) {
diff --git a/internal/equipo/chat/inner.go b/internal/equipo/chat/inner.go
index 12e77d0f..58b55de6 100644
--- a/internal/equipo/chat/inner.go
+++ b/internal/equipo/chat/inner.go
@@ -115,7 +115,7 @@ func (t *txn) stepActivity(l Lease, v *wire.StepActivityReport) error {
return err
}
}
- return nil
+ return t.pushLine(s, lines[len(lines)-1])
}
// taskExtras fills what the screens show around a task: the creator's
diff --git a/internal/equipo/chat/models.go b/internal/equipo/chat/models.go
index b042c325..37deed9c 100644
--- a/internal/equipo/chat/models.go
+++ b/internal/equipo/chat/models.go
@@ -4,10 +4,14 @@
// event are written in one transaction.
package chat
-import "time"
+import (
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/push"
+)
// Models are the tables this package owns, for the migration check.
-var Models = []any{&cardVisibility{}, &cardThreadRecord{}, &copyAttemptRecord{}, &copyReviewRecord{}, &copyFeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}, &connectTurnRecord{}}
+var Models = append([]any{&cardVisibility{}, &cardThreadRecord{}, &copyAttemptRecord{}, &copyReviewRecord{}, &copyFeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}, &connectTurnRecord{}}, push.Models...)
type turnRecord struct {
CreateRepo string
diff --git a/internal/equipo/chat/projects.go b/internal/equipo/chat/projects.go
index 5d2dfa30..8870fa38 100644
--- a/internal/equipo/chat/projects.go
+++ b/internal/equipo/chat/projects.go
@@ -291,6 +291,12 @@ func (t *txn) cardView(c cardRecord) (wire.Card, error) {
if c.Kind == wire.CardHome {
v.Name = c.Choice
}
+ // Set aside is the card's person's presentation (D5), never its state.
+ var aside []bool
+ if err := t.db.Model(&cardVisibility{}).Where("person = ? AND card_id = ?", c.Person, c.ID).Pluck("aside", &aside).Error; err != nil {
+ return v, err
+ }
+ v.Aside = len(aside) == 1 && aside[0]
if c.Kind == wire.CardAccess || c.Kind == wire.CardMerge || c.Kind == wire.CardMergeShips || c.Kind == wire.CardMergePolicy || c.Kind == wire.CardMergeReceipt || c.Kind == wire.CardPublish {
v.Name = c.Name
}
@@ -365,6 +371,9 @@ 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
+ }
// 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.
return t.mirrorCard(c)
diff --git a/internal/equipo/chat/push.go b/internal/equipo/chat/push.go
new file mode 100644
index 00000000..97c8b8fb
--- /dev/null
+++ b/internal/equipo/chat/push.go
@@ -0,0 +1,373 @@
+package chat
+
+import (
+ "context"
+ "errors"
+ "fmt"
+
+ "amadan.net/oficina/equipo/internal/equipo/push"
+ "amadan.net/oficina/equipo/internal/wire"
+ "gorm.io/gorm"
+)
+
+// Push (native slice 2): the engine writes push_outbox rows in the
+// 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).
+
+// 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.
+func (s *Store) SetPush(on bool) { s.pushOn.Store(on) }
+
+// PushWake is woken after a commit that wrote pushes.
+func (s *Store) PushWake() <-chan struct{} { return s.pushWake }
+
+func (s *Store) wakePush() {
+ select {
+ case s.pushWake <- struct{}{}:
+ default:
+ }
+}
+
+// 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,
+ 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...)
+ }
+ }}
+}
+
+// pushCurrent: the person is an active member and the device credential
+// still valid (Authority.PushDevice). Anything else, a lookup error
+// included, is no push.
+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
+ }
+ 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.
+func (s *Store) RegisterPush(ctx context.Context, person, credential string, in wire.RegisterPush) (out wire.PushRegistration, err error) {
+ if credential == "" {
+ return out, ErrForbidden
+ }
+ if push.Validate(in) != nil {
+ return out, ErrInvalid
+ }
+ err = s.tx(ctx, func(t *txn) error {
+ if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
+ return err
+ }
+ 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 {
+ return err
+ }
+ return s.authority.Audit(t.db, person, "push.register", credential)
+ })
+ return out, err
+}
+
+// RegisterActivity is POST /api/v1/push-registrations/activities: a
+// running Live Activity's token for a task the person started that has
+// not ended.
+func (s *Store) RegisterActivity(ctx context.Context, person, credential string, in wire.RegisterActivity) error {
+ if credential == "" {
+ return ErrForbidden
+ }
+ return s.tx(ctx, func(t *txn) error {
+ if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
+ return err
+ }
+ if err := s.pushCurrent(t.db, person, credential); err != nil {
+ return ErrForbidden
+ }
+ var k taskRecord
+ if err := t.db.Where("id = ? AND creator = ?", in.TaskID, person).Take(&k).Error; errors.Is(err, gorm.ErrRecordNotFound) {
+ return ErrNotFound
+ } else if err != nil {
+ return err
+ }
+ if wire.FinalStage(k.Stage) {
+ return ErrTaskEnded
+ }
+ if err := push.RegisterActivity(t.db, 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)
+ })
+}
+
+// pushDevices are the person's current registrations, none while the
+// outbox is off.
+func (t *txn) pushDevices(person string) ([]push.Registration, error) {
+ if !t.s.pushOn.Load() || person == "" {
+ return nil, nil
+ }
+ all, err := push.Devices(t.db, person)
+ if err != nil || len(all) == 0 {
+ return nil, err
+ }
+ var out []push.Registration
+ for _, d := range all {
+ if t.s.pushCurrent(t.db, person, d.Credential) == nil {
+ out = append(out, d)
+ }
+ }
+ return out, nil
+}
+
+// enqueuePush writes an intent's rows, one a device that can take it,
+// and reports how many.
+func (t *txn) enqueuePush(person string, devices []push.Registration, in push.Intent) (int, error) {
+ badge := 0
+ if in.Kind == push.KindBadge {
+ n, err := t.needsYouCount(person)
+ if err != nil {
+ return 0, err
+ }
+ badge = n
+ }
+ now := t.now()
+ raw, typ, err := push.Render(in, t.s.authority.Copy, badge, now)
+ if err != nil {
+ return 0, err
+ }
+ written := 0
+ for _, d := range devices {
+ target := push.TargetDevice
+ switch in.Kind {
+ case push.KindActivityStart:
+ if d.Platform != wire.PlatformIOS || d.StartToken == "" {
+ continue
+ }
+ target = push.TargetStart
+ case push.KindActivityUpdate, push.KindActivityEnd:
+ has, err := push.HasActivity(t.db, d.Credential, in.TaskID)
+ if err != nil {
+ return written, err
+ }
+ if d.Platform != wire.PlatformIOS || !has && 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 {
+ return written, err
+ }
+ written++
+ }
+ if written > 0 {
+ t.pushed = true
+ }
+ return written, nil
+}
+
+// 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) {
+ var rows []taskRecord
+ if err := t.db.Where("creator = ? AND stage NOT IN ?", person, []string{wire.StageDone, wire.StageCancelled}).Limit(wire.MaxTaskList).Find(&rows).Error; err != nil {
+ return 0, err
+ }
+ n := 0
+ for _, k := range rows {
+ v, err := t.taskView(k)
+ if err != nil {
+ return 0, err
+ }
+ if v.NeedsYou != "" {
+ n++
+ }
+ }
+ 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 {
+ for _, in := range intents {
+ if _, err := t.enqueuePush(person, devices, in); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// pushCard: a card that waits on its person opened.
+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 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.
+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 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
+ }
+ }
+ n, err := t.enqueuePush(v.Creator, devices, 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)
+}
+
+// pushMakeRoom ends the oldest Live Activities so a new one is at most
+// wire.MaxLiveActivities.
+func (t *txn) pushMakeRoom(person string, devices []push.Registration) error {
+ live, err := push.LiveTasks(t.db, person)
+ if err != nil {
+ return err
+ }
+ for len(live) >= wire.MaxLiveActivities {
+ old := live[0]
+ live = live[1:]
+ m, err := push.LoadMemory(t.db, person, old.TaskID)
+ if err != nil {
+ return err
+ }
+ if _, err := t.enqueuePush(person, devices, push.Replace(m.Task(old.TaskID))); err != nil {
+ return err
+ }
+ m.Ended = true
+ if err := push.SaveMemory(t.db, person, old.TaskID, m, t.now()); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// pushLine: a running step of a task reported an activity line.
+func (t *txn) pushLine(s stepRecord, line wire.ActivityLine) 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
+ }
+ 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)
+}
+
+// pushTaskOf is a task as its Live Activity shows it: the step working
+// now (running or queued, else the last done), its newest line, and
+// Roster's tone.
+func pushTaskOf(v wire.Task, copy func(string) string) push.Task {
+ k := push.Task{ID: v.ID, Title: v.Title, Stage: v.Stage, NeedsYou: v.NeedsYou, Tone: wire.TonePositive}
+ steps := v.Steps
+ var current *wire.Step
+ for j := len(steps) - 1; j >= 0 && current == nil; j-- {
+ if steps[j].State == wire.StepRunning || steps[j].State == wire.StepQueued {
+ current = &steps[j]
+ }
+ }
+ for j := len(steps) - 1; j >= 0 && current == nil; j-- {
+ if steps[j].State == wire.StepDone {
+ current = &steps[j]
+ }
+ }
+ if current != nil {
+ k.Specialist, k.StepID = current.Specialist, current.ID
+ if current.State == wire.StepRunning {
+ k.Working = true
+ k.Activity = copy("work.activity.working")
+ if n := len(current.Activity); n > 0 {
+ k.Activity = activityLine(current.Activity[n-1], copy)
+ }
+ }
+ }
+ switch {
+ case v.Checks == wire.ChecksFailed || v.Verdict == wire.VerdictChanges:
+ k.Tone = wire.ToneNegative
+ case v.NeedsYou != "":
+ k.Tone = wire.ToneWarning
+ }
+ return k
+}
+
+// activityLine is a step's activity line in words (the web's
+// activityText).
+func activityLine(a wire.ActivityLine, copy func(string) string) string {
+ format := copy("work.activity." + a.Kind)
+ if a.Subject == "" || a.Kind == wire.ActivityOther || format == "" {
+ return copy("work.activity.working")
+ }
+ return push.Clip(fmt.Sprintf(format, a.Subject))
+}
diff --git a/internal/equipo/chat/push_http.go b/internal/equipo/chat/push_http.go
new file mode 100644
index 00000000..7673e2fa
--- /dev/null
+++ b/internal/equipo/chat/push_http.go
@@ -0,0 +1,61 @@
+package chat
+
+import (
+ "errors"
+ "net/http"
+
+ "amadan.net/oficina/equipo/internal/equipo/personapi"
+ "amadan.net/oficina/equipo/internal/wire"
+ "github.com/go-chi/chi/v5"
+)
+
+// registerPush is POST /api/v1/push-registrations: 200 with the
+// registration, without its tokens. A device bearer only.
+func (h *HTTP) registerPush(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ var in wire.RegisterPush
+ if err := readJSON(r, &in); err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ out, err := h.Store.RegisterPush(r.Context(), p.Address, p.CredentialID, in)
+ if err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, out)
+}
+
+// registerActivity is POST /api/v1/push-registrations/activities: 204.
+func (h *HTTP) registerActivity(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ var in wire.RegisterActivity
+ if err := readJSON(r, &in); err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ if err := h.Store.RegisterActivity(r.Context(), p.Address, p.CredentialID, in); err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
+
+// cardVisibility is POST /api/v1/cards/{id}/visibility: 200 with the
+// card; 409 card_stale with the card as it is when its revision moved or
+// it no longer waits on the person.
+func (h *HTTP) cardVisibility(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ var in wire.SetCardVisibility
+ if err := readJSON(r, &in); err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ out, err := h.Store.SetCardVisibility(r.Context(), p.Address, chi.URLParam(r, "id"), in)
+ if errors.Is(err, ErrCardConflict) {
+ writeJSON(w, http.StatusConflict, wire.CardConflict{Code: "card_stale", CopyKey: "api.card_stale", RequestID: r.Header.Get("Idempotency-Key"), Card: out})
+ return
+ }
+ if err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, out)
+}
diff --git a/internal/equipo/chat/push_test.go b/internal/equipo/chat/push_test.go
new file mode 100644
index 00000000..555578ac
--- /dev/null
+++ b/internal/equipo/chat/push_test.go
@@ -0,0 +1,401 @@
+package chat
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/personapi"
+ "amadan.net/oficina/equipo/internal/equipo/push"
+ "amadan.net/oficina/equipo/internal/wire"
+ "gorm.io/gorm"
+)
+
+const (
+ pushDevice = "aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11"
+ pushStart = "bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22"
+)
+
+// pushRig is a housekeeping rig with the outbox on, owner's iPhone
+// registered (credential cr_phone) and devices current until revoked.
+type pushRig struct {
+ *hkRig
+ revoked map[string]bool
+ audits []string
+}
+
+func newPushRig(t *testing.T) *pushRig {
+ t.Helper()
+ r := &pushRig{hkRig: newHKRig(t), revoked: map[string]bool{}}
+ r.s.authority.PushDevice = func(_ *gorm.DB, person, credential string) error {
+ if r.revoked[credential] || !strings.HasPrefix(credential, "cr_") {
+ return ErrForbidden
+ }
+ return nil
+ }
+ r.s.authority.Audit = func(_ *gorm.DB, actor, kind, record string) error {
+ r.audits = append(r.audits, actor+" "+kind+" "+record)
+ return nil
+ }
+ r.s.SetPush(true)
+ r.register(hkOwner, "cr_phone", wire.RegisterPush{Token: pushDevice, Environment: wire.APNsProduction, Platform: wire.PlatformIOS, StartToken: pushStart})
+ return r
+}
+
+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 {
+ r.t.Fatal(err)
+ }
+}
+
+// outbox is the rows written, oldest first, as "kind rule-ish" strings:
+// kind and collapse ID.
+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)
+ return out
+}
+
+func kinds(rows []push.OutboxRecord) string {
+ var out []string
+ for _, row := range rows {
+ out = append(out, row.Kind)
+ }
+ return strings.Join(out, " ")
+}
+
+// step saves the task with a step of its in the state given.
+func (r *pushRig) step(k *taskRecord, id, specialist, state string) {
+ r.t.Helper()
+ r.must(r.tx(func(t *txn) error {
+ s := stepRecord{ID: id, TaskID: k.ID, Idx: 1, Specialist: specialist, Person: k.Creator, State: state, Attempt: 1, Terminated: state == wire.StepFailed, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now}
+ if err := t.db.Save(&s).Error; err != nil {
+ return err
+ }
+ return t.saveTask(k)
+ }))
+ r.now = r.now.Add(time.Second)
+}
+
+func (r *pushRig) stage(k *taskRecord, stage string) {
+ r.t.Helper()
+ k.Stage = stage
+ r.must(r.tx(func(t *txn) error { return t.saveTask(k) }))
+ r.now = r.now.Add(time.Second)
+}
+
+// TestPushOutboxInEngineTransaction: the rows are written by the change's
+// own transaction, beside its event, and vanish with it when it rolls
+// back; with the outbox off nothing is written.
+func TestPushOutboxInEngineTransaction(t *testing.T) {
+ r := newPushRig(t)
+ k := r.task("tk1", "Fix login", hkOwner)
+ events := r.count("SELECT count(*) FROM chat_events")
+ boom := errors.New("boom")
+ err := r.tx(func(t *txn) error {
+ s := stepRecord{ID: "s1", TaskID: k.ID, Idx: 1, Specialist: wire.SpecialistEngineering, Person: hkOwner, State: wire.StepRunning, Attempt: 1, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now}
+ if err := t.db.Create(&s).Error; err != nil {
+ return err
+ }
+ if err := t.saveTask(&k); err != nil {
+ return err
+ }
+ var n int64
+ if err := t.db.Model(&push.OutboxRecord{}).Count(&n).Error; err != nil || n != 1 {
+ r.t.Errorf("inside the transaction: %d rows, %v", n, err)
+ }
+ return boom
+ })
+ if !errors.Is(err, boom) || len(r.outbox()) != 0 || r.count("SELECT count(*) FROM chat_events") != events || r.count("SELECT count(*) FROM push_tasks") != 0 {
+ t.Fatal("a rolled back change left its push behind")
+ }
+ k = r.load("tk1")
+ r.s.SetPush(false)
+ r.step(&k, "s1", wire.SpecialistEngineering, wire.StepRunning)
+ if len(r.outbox()) != 0 {
+ t.Fatal("the outbox was written while off")
+ }
+ r.s.SetPush(true)
+ r.stage(&k, wire.StageInProgress)
+ if got := kinds(r.outbox()); got != push.KindActivityStart {
+ t.Fatalf("outbox %q", got)
+ }
+}
+
+// TestPushTaskLifecycle drives a task through the engine: dispatch starts
+// its Live Activity by push-to-start, a stage change updates it, needing
+// the person updates it urgently with the badge (their Needs you count),
+// and its end alerts passively and ends the activity.
+func TestPushTaskLifecycle(t *testing.T) {
+ r := newPushRig(t)
+ k := r.task("tk1", "Fix login", hkOwner)
+ r.stage(&k, wire.StageNoted)
+ if len(r.outbox()) != 0 {
+ t.Fatal("a noted task pushed")
+ }
+ r.step(&k, "s1", wire.SpecialistEngineering, wire.StepRunning)
+ rows := r.outbox()
+ if kinds(rows) != push.KindActivityStart || rows[0].Target != push.TargetStart || rows[0].Priority != 10 || rows[0].PushType != push.TypeLiveActivity {
+ t.Fatalf("start %+v", rows)
+ }
+ var p struct {
+ APS struct {
+ ContentState wire.LiveActivityState `json:"content-state"`
+ } `json:"aps"`
+ }
+ r.must(json.Unmarshal([]byte(rows[0].Payload), &p))
+ 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)
+ }
+ 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:])
+ }
+ 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}}` {
+ t.Fatalf("needs you %+v", last)
+ }
+ r.stage(&k, wire.StageDone)
+ rows = r.outbox()
+ last = rows[len(rows)-2:]
+ // The unsent badge took the new count (it coalesces).
+ if kinds(last) != "activity_end passive" || last[1].CollapseID != "task:tk1" || rows[len(rows)-3].Payload != `{"aps":{"badge":0}}` {
+ t.Fatalf("end %s", kinds(rows))
+ }
+ // Seen again ended: nothing more.
+ n := len(rows)
+ r.stage(&k, wire.StageDone)
+ if len(r.outbox()) != n {
+ t.Fatal("an ended task pushed again")
+ }
+}
+
+// TestPushAtMostThreeActivities: a fourth dispatched task ends the oldest
+// started one's Live Activity.
+func TestPushAtMostThreeActivities(t *testing.T) {
+ r := newPushRig(t)
+ for _, id := range []string{"tk1", "tk2", "tk3", "tk4"} {
+ k := r.task(id, "Task "+id, hkOwner)
+ r.step(&k, "s"+id, wire.SpecialistEngineering, wire.StepRunning)
+ }
+ var ends []push.OutboxRecord
+ for _, row := range r.outbox() {
+ if row.Kind == push.KindActivityEnd {
+ ends = append(ends, row)
+ }
+ }
+ if len(ends) != 1 || ends[0].TaskID != "tk1" || !strings.Contains(ends[0].Payload, `"outcome":"replaced"`) {
+ t.Fatalf("ends %+v", ends)
+ }
+ live, err := push.LiveTasks(r.s.db.G, hkOwner)
+ if err != nil || len(live) != wire.MaxLiveActivities || live[0].TaskID != "tk2" {
+ t.Fatalf("live %+v %v", live, err)
+ }
+}
+
+// TestPushActivityLineOnceAMinute: activity lines update a running
+// activity at most once a minute.
+func TestPushActivityLineOnceAMinute(t *testing.T) {
+ r := newPushRig(t)
+ k := r.task("tk1", "Fix login", hkOwner)
+ r.step(&k, "s1", wire.SpecialistEngineering, wire.StepRunning)
+ s := stepRecord{ID: "s1", TaskID: "tk1", Person: hkOwner}
+ line := func(subject string) {
+ r.must(r.tx(func(t *txn) error {
+ return t.pushLine(s, wire.ActivityLine{Kind: wire.ActivityRead, Subject: subject, At: r.now})
+ }))
+ }
+ 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") {
+ t.Fatalf("lines %s", kinds(rows))
+ }
+}
+
+func (r *pushRig) card(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}
+ r.must(r.tx(func(t *txn) error {
+ if err := t.db.Create(&c).Error; err != nil {
+ return err
+ }
+ return t.cardEvent(c)
+ }))
+ return c
+}
+
+// TestPushCardOpensOnce: an open card alerts its person once, with its
+// question; written again, or set aside, it does not alert again, and
+// set aside it keeps its place in Needs you.
+func TestPushCardOpensOnce(t *testing.T) {
+ r := newPushRig(t)
+ c := r.card("c1", wire.CardOpen)
+ rows := r.outbox()
+ if kinds(rows) != push.KindAlert || rows[0].CollapseID != "c1" || rows[0].Priority != 10 || !strings.Contains(rows[0].Payload, "Which branch should the fix go on?") {
+ t.Fatalf("card alert %+v", rows)
+ }
+ r.must(r.tx(func(t *txn) error { return t.cardEvent(c) }))
+ out, err := r.s.SetCardVisibility(r.ctx, hkOwner, "c1", wire.SetCardVisibility{Aside: true, Revision: 1})
+ if err != nil || !out.Aside || out.State != wire.CardOpen {
+ t.Fatalf("set aside %+v %v", out, err)
+ }
+ if len(r.outbox()) != 1 {
+ t.Fatal("the card alerted again")
+ }
+ r.card("c2", wire.CardAnswered)
+ if len(r.outbox()) != 1 {
+ t.Fatal("an answered card alerted")
+ }
+}
+
+// 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.revoked["cr_mac"] = true
+ r.card("c1", wire.CardOpen)
+ rows := r.outbox()
+ if len(rows) != 1 || rows[0].Credential != "cr_phone" {
+ t.Fatalf("revoked device pushed: %+v", rows)
+ }
+ r.must(r.tx(func(t *txn) error { return t.db.Exec("UPDATE members SET active = 0 WHERE address = ?", hkOwner).Error }))
+ r.card("c2", wire.CardOpen)
+ if len(r.outbox()) != 1 {
+ t.Fatal("a removed person was pushed")
+ }
+}
+
+// TestPushReplyOnlyWhenNotFollowing: a finished reply alerts with its
+// first line, unless the person has the stream open.
+func TestPushReplyOnlyWhenNotFollowing(t *testing.T) {
+ r := newPushRig(t)
+ reply := func(id string) {
+ r.must(r.tx(func(t *txn) error {
+ turn := turnRecord{ID: id, Person: hkOwner, State: wire.TurnRunning, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now}
+ m := messageRecord{ID: "m_" + id, Person: hkOwner, IdempotencyKey: "reply:" + id, Role: wire.RoleCoordinator, Text: "**Done.** The fix is on its branch.\nDetails follow.", TurnID: id, Revision: 1, CreatedAt: r.now}
+ if err := t.db.Create(&turn).Error; err != nil {
+ return err
+ }
+ if err := t.db.Create(&m).Error; err != nil {
+ return err
+ }
+ turn.State, turn.ReplyID = wire.TurnReplied, m.ID
+ return t.saveTurn(&turn)
+ }))
+ }
+ done := r.s.Hub().Follow(hkOwner)
+ reply("t_watched")
+ if len(r.outbox()) != 0 {
+ t.Fatal("pushed a reply the person was watching")
+ }
+ done()
+ reply("t_away")
+ rows := r.outbox()
+ if len(rows) != 1 || rows[0].CollapseID != "reply:t_away" || !strings.Contains(rows[0].Payload, `"body":"Done. The fix is on its branch."`) {
+ t.Fatalf("reply %+v", rows)
+ }
+}
+
+// TestRegisterPushAuthority: only a device credential of a current
+// person registers; the audit names the credential, never a token; an
+// activity token is only for a task of the person's that has not ended.
+func TestRegisterPushAuthority(t *testing.T) {
+ r := newPushRig(t)
+ in := wire.RegisterPush{Token: pushDevice, Environment: wire.APNsProduction, Platform: wire.PlatformIOS}
+ if _, err := r.s.RegisterPush(r.ctx, hkOwner, "", in); !errors.Is(err, ErrForbidden) {
+ t.Fatal("a browser session registered", err)
+ }
+ r.revoked["cr_phone"] = true
+ if _, err := r.s.RegisterPush(r.ctx, hkOwner, "cr_phone", in); !errors.Is(err, ErrForbidden) {
+ t.Fatal("a revoked device registered", err)
+ }
+ r.revoked["cr_phone"] = false
+ if _, err := r.s.RegisterPush(r.ctx, hkOwner, "cr_phone", wire.RegisterPush{Token: "nothex", Environment: wire.APNsProduction, Platform: wire.PlatformIOS}); !errors.Is(err, ErrInvalid) {
+ t.Fatal("a bad token registered", err)
+ }
+ for _, a := range r.audits {
+ if strings.Contains(a, pushDevice) || strings.Contains(a, pushStart) {
+ t.Fatal("token in audit", a)
+ }
+ }
+ if len(r.audits) != 1 || r.audits[0] != hkOwner+" push.register cr_phone" {
+ t.Fatalf("audits %v", r.audits)
+ }
+ r.task("tk_mine", "Mine", hkOwner)
+ r.task("tk_theirs", "Theirs", hkMember)
+ act := func(task string) error {
+ return r.s.RegisterActivity(r.ctx, hkOwner, "cr_phone", wire.RegisterActivity{TaskID: task, Token: pushStart})
+ }
+ if err := act("tk_theirs"); !errors.Is(err, ErrNotFound) {
+ t.Fatal("another's task", err)
+ }
+ if err := act("tk_mine"); err != nil {
+ t.Fatal(err)
+ }
+ k := r.load("tk_mine")
+ r.stage(&k, wire.StageCancelled)
+ if err := act("tk_mine"); !errors.Is(err, ErrTaskEnded) {
+ t.Fatal("an ended task", err)
+ }
+}
+
+// TestPushRegistrationAnswersNoToken: the registration answers its
+// environment and platform, never a token.
+func TestPushRegistrationAnswersNoToken(t *testing.T) {
+ r := newPushRig(t)
+ h := &HTTP{Store: r.s}
+ out, err := h.Store.RegisterPush(personapi.WithVerifiedPrincipal(context.Background(), personapi.PersonPrincipal{Address: hkOwner, CredentialID: "cr_phone"}), hkOwner, "cr_phone", wire.RegisterPush{Token: pushDevice, Environment: wire.APNsDevelopment, Platform: wire.PlatformIOS, StartToken: pushStart})
+ raw, _ := json.Marshal(out)
+ if err != nil || !out.LiveActivities || strings.Contains(string(raw), pushDevice) || strings.Contains(string(raw), pushStart) {
+ t.Fatalf("registration %s %v", raw, err)
+ }
+}
+
+// TestSetAsideKeepsNeedsYou (D5): a card set aside still waits on its
+// person, so its task stays in Needs you and the badge does not move; a
+// stale revision or a card that no longer waits is a conflict carrying
+// the card as it is.
+func TestSetAsideKeepsNeedsYou(t *testing.T) {
+ r := newPushRig(t)
+ k := r.task("tk1", "Fix login", hkOwner)
+ r.stage(&k, wire.StageReadyToMerge)
+ 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())
+ 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)
+ }
+ list, err := r.s.NeedsYou(r.ctx, hkOwner)
+ if err != nil || len(list.Items) != 1 || list.Items[0].ID != "tk1" {
+ t.Fatalf("needs you %+v %v", list.Items, err)
+ }
+ for _, row := range r.outbox()[before:] {
+ if row.Kind == push.KindBadge {
+ t.Fatal("setting aside moved the badge")
+ }
+ }
+ 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)
+ }
+ r.must(r.s.db.G.Model(&cardRecord{}).Where("id = ?", "c1").Update("state", wire.CardAnswered).Error)
+ if out, err := r.s.SetCardVisibility(r.ctx, hkOwner, "c1", wire.SetCardVisibility{Aside: false, Revision: 1}); !errors.Is(err, ErrCardConflict) || out.State != wire.CardAnswered {
+ t.Fatalf("answered %+v %v", out, err)
+ }
+ if _, err := r.s.SetCardVisibility(r.ctx, hkMember, "c1", wire.SetCardVisibility{Aside: true, Revision: 1}); !errors.Is(err, ErrNotFound) {
+ t.Fatal("another person's card", err)
+ }
+}
diff --git a/internal/equipo/chat/roster.go b/internal/equipo/chat/roster.go
index c780f27c..a0230162 100644
--- a/internal/equipo/chat/roster.go
+++ b/internal/equipo/chat/roster.go
@@ -59,15 +59,51 @@ type CardThreadTurn struct {
func (s *Store) SetCardAside(ctx context.Context, person, id string, revision int64, aside bool) error {
return s.tx(ctx, func(t *txn) error {
- if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
+ _, err := t.setCardAside(person, id, revision, aside)
+ return err
+ })
+}
+
+// SetCardVisibility is POST /api/v1/cards/{id}/visibility: SetCardAside
+// for a device, answering the card as the person sees it now, and on a
+// stale revision ErrCardConflict with the card as it is.
+func (s *Store) SetCardVisibility(ctx context.Context, person, id string, in wire.SetCardVisibility) (out wire.Card, err error) {
+ var c cardRecord
+ err = s.tx(ctx, func(t *txn) error {
+ var err error
+ c, err = t.setCardAside(person, id, in.Revision, in.Aside)
+ if err != nil {
return err
}
- var c cardRecord
- if err := t.db.Where("id = ? AND person = ? AND "+coordinatorRole, id, person).First(&c).Error; errors.Is(err, gorm.ErrRecordNotFound) {
- return ErrNotFound
- } else if err != nil {
- return err
+ out, err = t.cardView(c)
+ return err
+ })
+ if errors.Is(err, ErrCardConflict) && c.ID != "" {
+ if rerr := s.read(ctx, func(tx *gorm.DB) error {
+ var e error
+ out, e = (&txn{s: s, ctx: ctx, db: tx}).cardView(c)
+ return e
+ }); rerr != nil {
+ return out, rerr
}
+ }
+ return out, err
+}
+
+// setCardAside sets the card aside (or back) for its person: the card, and
+// ErrCardConflict with it when its revision moved or it no longer waits.
+func (t *txn) setCardAside(person, id string, revision int64, aside bool) (c cardRecord, err error) {
+ s := t.s
+ ctx := t.ctx
+ if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
+ return c, err
+ }
+ if err := t.db.Where("id = ? AND person = ? AND "+coordinatorRole, id, person).First(&c).Error; errors.Is(err, gorm.ErrRecordNotFound) {
+ return c, ErrNotFound
+ } else if err != nil {
+ return c, err
+ }
+ return c, func() error {
if c.Revision != revision {
return ErrCardConflict
}
@@ -98,7 +134,7 @@ func (s *Store) SetCardAside(ctx context.Context, person, id string, revision in
return err
}
return t.cardEvent(c)
- })
+ }()
}
func (s *Store) CardPresentations(ctx context.Context, person string, ids []string) (out map[string]CardPresentation, err error) {
diff --git a/internal/equipo/chat/store.go b/internal/equipo/chat/store.go
index f81fe642..7077527d 100644
--- a/internal/equipo/chat/store.go
+++ b/internal/equipo/chat/store.go
@@ -80,6 +80,10 @@ type Authority struct {
// AssistantHosts are the origins a person may register as their
// Base host (EQUIPO_ASSISTANT_HOSTS), lowercased.
AssistantHosts []string
+ // PushDevice re-checks a device credential of the person's, for a
+ // push to it: nil while it is still valid (not revoked or expired).
+ // Unset, nothing pushes.
+ PushDevice func(tx *gorm.DB, person, credential string) error
// Seal and Open keep a secret sealed with the instance key, bound to
// domain (a host token).
Seal func(domain string, v any) (string, error)
@@ -112,6 +116,9 @@ type Store struct {
logger atomic.Pointer[slog.Logger]
// warm limits how often opening Base warms an Assistant (warm.go).
warm warmGate
+ // pushOn writes the push outbox (SetPush); pushWake wakes its sender.
+ pushOn atomic.Bool
+ pushWake chan struct{}
}
// SetFrameTap sees every frame the instance sends a runner, as sent
@@ -122,7 +129,7 @@ func NewStore(d *db.DB, a Authority, hub *Hub) *Store {
if hub == nil {
hub = NewHub()
}
- return &Store{db: d, authority: a, hub: hub, now: func() time.Time { return time.Now().UTC() }, process: newID("p"), detectors: housekeeping.Default(), remote: make(chan struct{}, 1)}
+ return &Store{db: d, authority: a, hub: hub, now: func() time.Time { return time.Now().UTC() }, process: newID("p"), detectors: housekeeping.Default(), remote: make(chan struct{}, 1), pushWake: make(chan struct{}, 1)}
}
// SetClock replaces the store's clock (tests: the 30-minute offline rule
@@ -164,6 +171,9 @@ func (s *Store) tx(ctx context.Context, fn func(*txn) error) error {
if t.pending {
s.wakeRemote()
}
+ if t.pushed {
+ s.wakePush()
+ }
return nil
}
@@ -190,6 +200,8 @@ type txn struct {
// live are events for the streams following now, never stored,
// published once the transaction commits.
live []liveEvent
+ // pushed: the transaction wrote the push outbox.
+ pushed bool
}
func (t *txn) now() time.Time { return t.s.now() }
@@ -265,6 +277,9 @@ func (t *txn) saveTurn(r *turnRecord) error {
if err := t.turnEvent(*r); err != nil {
return err
}
+ if err := t.pushReply(*r); err != nil {
+ return err
+ }
// Every way a turn ends comes here: a hand-off's Coordinator turn
// that ends may leave its hand-off with nothing more to do, and once
// the Assistant's team_update turn about a job ends, its card may say
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go
index 945d6321..887f700c 100644
--- a/internal/equipo/chat/tasks.go
+++ b/internal/equipo/chat/tasks.go
@@ -702,6 +702,9 @@ func (t *txn) taskEvent(k taskRecord) error {
return err
}
}
+ if slices.Contains(members, k.Creator) {
+ return t.pushTask(v)
+ }
return nil
}
diff --git a/internal/equipo/chat_wiring.go b/internal/equipo/chat_wiring.go
index 278cf891..b0d71238 100644
--- a/internal/equipo/chat_wiring.go
+++ b/internal/equipo/chat_wiring.go
@@ -45,6 +45,14 @@ 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.
+ PushDevice: func(tx *gorm.DB, person, credential string) error {
+ p, err := s.personDevices().VerifyAt(tx, credential, "")
+ if err != nil || p.Address != person {
+ return ErrForbidden
+ }
+ return nil
+ },
ActivityLabel: activityLabel,
Copy: copyText,
Origin: s.chatOrigin,
diff --git a/internal/equipo/config.go b/internal/equipo/config.go
index 7c6cecdf..6d42d7d4 100644
--- a/internal/equipo/config.go
+++ b/internal/equipo/config.go
@@ -2,6 +2,7 @@ package equipo
import (
"amadan.net/oficina/equipo/internal/equipo/oficina"
+ "amadan.net/oficina/equipo/internal/equipo/push"
"amadan.net/oficina/home/connect"
"errors"
"net"
@@ -20,6 +21,12 @@ type Config struct {
InstanceKey string
Owners []string
AllowLoggedMail bool
+ // AllowLoggedPush (EQUIPO_ALLOW_LOGGED_PUSH=1) logs pushes instead of
+ // sending them; like logged mail, only on loopback or staging.
+ AllowLoggedPush bool
+ // Push is the push transport, built by Pusher on the serve path only
+ // (main's run) and set there; nil everywhere else: no outbox, no sender.
+ Push push.Transport
// MailConfigured is true when the platform gave Equipo a way to
// send: CARLOS mail submission (CARLOS_MAIL=submit) or SMTP
// (CARLOS_SMTP_HOST and CARLOS_SMTP_FROM). Mailer builds the sender.
@@ -51,6 +58,7 @@ func LoadConfig(getenv func(string) string) (Config, error) {
Origin: strings.TrimSpace(getenv("EQUIPO_ORIGIN")),
InstanceKey: strings.TrimSpace(getenv("EQUIPO_INSTANCE_KEY")),
AllowLoggedMail: getenv("EQUIPO_ALLOW_LOGGED_MAIL") == "1",
+ AllowLoggedPush: getenv("EQUIPO_ALLOW_LOGGED_PUSH") == "1",
DatabaseName: strings.TrimSpace(getenv("EQUIPO_DATABASE")),
}
raw := connect.Credentials{Issuer: getenv("EQUIPO_HOME_ISSUER"), ConsumerID: getenv("EQUIPO_HOME_CONSUMER_ID"), KeysBase64: getenv("EQUIPO_HOME_KEYS_BASE64"), DEKBase64: getenv("EQUIPO_HOME_DEK_BASE64")}
@@ -138,6 +146,10 @@ func (cfg Config) validate() error {
//lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go.
return errors.New(copyLoggedMailPublic)
}
+ if cfg.AllowLoggedPush && !local && !stagingMailOrigin.MatchString(cfg.Origin) {
+ //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go.
+ return errors.New(copyLoggedPushPublic)
+ }
if cfg.OficinaConnectOrigin != "" {
if _, err := oficina.New(cfg.oficinaConfig(), oficinaStore{}, oficinaSealer{}); err != nil {
//lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go.
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index a02bdada..48d18b23 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -23,6 +23,9 @@ const (
copyMissingStage = "The sign-in layout is missing. Check the Rastrillo installation."
copyInvalidRoot = "The app handler is missing. Configure the Equipo app before serving."
+ 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)
+
copyRunnerPending = "Waiting for you to approve this machine in your browser."
copyRunnerRateLimited = "Too many attempts. Wait before trying again."
copyBrand = "Equipo"
@@ -2011,6 +2014,15 @@ 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)
+
"nav.account": "Account",
"brand": copyBrand,
"nav.conversation": "Conversation",
diff --git a/internal/equipo/invitations.go b/internal/equipo/invitations.go
index 36d998d0..f2ff11f4 100644
--- a/internal/equipo/invitations.go
+++ b/internal/equipo/invitations.go
@@ -3,6 +3,7 @@ package equipo
import (
"context"
+ "amadan.net/oficina/equipo/internal/equipo/push"
"amadan.net/oficina/equipo/internal/equipo/setup"
"amadan.net/oficina/equipo/internal/runnerproto"
"gorm.io/gorm"
@@ -24,7 +25,8 @@ func (s *Store) invitationsAt(tx *gorm.DB) *setup.Store {
RevokeRunners: func(tx *gorm.DB, address string) error {
return revokePersonRunners(tx, address, s.runnerClock.Now().UTC())
},
- Fence: func(tx *gorm.DB) error { return s.fenceAuthority(tx.Statement.Context, tx, 0) },
+ ForgetPush: push.ForgetPerson,
+ Fence: func(tx *gorm.DB) error { return s.fenceAuthority(tx.Statement.Context, tx, 0) },
})
}
diff --git a/internal/equipo/mailer.go b/internal/equipo/mailer.go
index 09bc0748..4793d170 100644
--- a/internal/equipo/mailer.go
+++ b/internal/equipo/mailer.go
@@ -1,8 +1,10 @@
package equipo
import (
+ "errors"
"log/slog"
+ "amadan.net/oficina/equipo/internal/equipo/push"
"amadan.net/rastrillo/rastrillo/mail"
)
@@ -30,3 +32,25 @@ func Mailer(cfg Config, logger *slog.Logger) (mail.Sender, error) {
}
return mail.FromCarlos("CARLOS", logger)
}
+
+// Pusher builds the push transport. Call it only where Equipo serves
+// (main's run), as Mailer: a seed or one-shot has no control socket and
+// 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).
+func Pusher(cfg Config, logger *slog.Logger, getenv func(string) string) (push.Transport, error) {
+ if cfg.AllowLoggedPush {
+ if cfg.validate() != nil {
+ //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go.
+ return nil, errors.New(copyLoggedPushPublic)
+ }
+ return push.Logged{Logger: logger}, nil
+ }
+ t, err := push.FromCarlos(getenv)
+ if err != nil {
+ //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go.
+ return nil, errors.New(copyCarlosPushUnavailable)
+ }
+ return t, nil
+}
diff --git a/internal/equipo/migrations/0095_push.sql b/internal/equipo/migrations/0095_push.sql
new file mode 100644
index 00000000..7d5b3c61
--- /dev/null
+++ b/internal/equipo/migrations/0095_push.sql
@@ -0,0 +1,14 @@
+-- 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.
+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));
+CREATE INDEX push_activity_person ON push_activities(person);
+CREATE TABLE push_outbox (id text PRIMARY KEY, person text, credential text, kind text, target text, task_id text, push_type text, priority integer, collapse_id text, dedupe text, payload text, state text, next_at datetime, attempts integer, lease_until datetime, status integer, reason text, apns_id text, sent_at datetime, created_at datetime, updated_at datetime);
+CREATE INDEX push_outbox_due ON push_outbox(state, next_at);
+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));
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index dd304e75..0719da5f 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -734,3 +734,14 @@ WHERE CASE WHEN json_valid(entries) THEN json_type(entries) = 'array' ELSE 0 END
AND EXISTS (SELECT 1 FROM json_each(chat_notebooks.entries) WHERE json_extract(value, '$.source') = 'person');
ALTER TABLE chat_steps ADD COLUMN base_checks text;
+
+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));
+CREATE INDEX push_activity_person ON push_activities(person);
+CREATE TABLE push_outbox (id text PRIMARY KEY, person text, credential text, kind text, target text, task_id text, push_type text, priority integer, collapse_id text, dedupe text, payload text, state text, next_at datetime, attempts integer, lease_until datetime, status integer, reason text, apns_id text, sent_at datetime, created_at datetime, updated_at datetime);
+CREATE INDEX push_outbox_due ON push_outbox(state, next_at);
+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));
diff --git a/internal/equipo/person_devices.go b/internal/equipo/person_devices.go
index 2d5320dd..4809d95c 100644
--- a/internal/equipo/person_devices.go
+++ b/internal/equipo/person_devices.go
@@ -5,6 +5,7 @@ import (
"net/http"
"amadan.net/oficina/equipo/internal/equipo/personapi"
+ "amadan.net/oficina/equipo/internal/equipo/push"
)
type PersonDeviceChallenge = personapi.PersonDeviceChallenge
@@ -12,7 +13,7 @@ type PersonDeviceProof = personapi.PersonDeviceProof
type PersonCredential = personapi.PersonCredential
func (s *Store) personDevices() *personapi.DeviceStore {
- return &personapi.DeviceStore{Write: s.write, Read: s.invitationRead, Member: memberAt, Instance: runnerInstance, Audit: appendAudit, Key: s.personKey, Origin: s.personOrigin, Now: s.runnerClock.Now, Invalid: ErrInvalid, Forbidden: ErrForbidden, NotFound: ErrNotFound, Conflict: ErrConflict}
+ return &personapi.DeviceStore{Write: s.write, Read: s.invitationRead, Member: memberAt, Instance: runnerInstance, Audit: appendAudit, Key: s.personKey, Origin: s.personOrigin, Now: s.runnerClock.Now, Revoked: push.ForgetCredential, Invalid: ErrInvalid, Forbidden: ErrForbidden, NotFound: ErrNotFound, Conflict: ErrConflict}
}
func (s *Store) BeginPersonDevice(ctx context.Context, key, label, request string) (PersonDeviceChallenge, error) {
return s.personDevices().Begin(ctx, key, label, request)
diff --git a/internal/equipo/personapi/devices.go b/internal/equipo/personapi/devices.go
index ff8f610c..9bc6d8d8 100644
--- a/internal/equipo/personapi/devices.go
+++ b/internal/equipo/personapi/devices.go
@@ -96,6 +96,10 @@ type DeviceStore struct {
Key, Origin string
Now func() time.Time
Invalid, Forbidden, NotFound, Conflict error
+
+ // Revoked runs in the revoking transaction: what else the device
+ // held goes with it (its push registration). Nil is nothing.
+ Revoked func(tx *gorm.DB, id string) error
}
func (s *DeviceStore) mac(domain, value string) string {
@@ -559,6 +563,11 @@ func (s *DeviceStore) RevokeRevision(ctx context.Context, a kernel.Actor, id str
if e := tx.Model(&DeviceRecord{}).Where("id=?", id).Select("revoked_at", "revision", "result_cipher", "begin_cipher").Updates(&r).Error; e != nil {
return e
}
+ if s.Revoked != nil {
+ if e := s.Revoked(tx, id); e != nil {
+ return e
+ }
+ }
if e := s.Audit(tx, a, "person_device.revoke", id); e != nil {
return e
}
diff --git a/internal/equipo/push/budget_test.go b/internal/equipo/push/budget_test.go
new file mode 100644
index 00000000..2dba09c6
--- /dev/null
+++ b/internal/equipo/push/budget_test.go
@@ -0,0 +1,9 @@
+package push
+
+import (
+ "amadan.net/rastrillo/rastrillo/budget"
+ "os"
+ "testing"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
diff --git a/internal/equipo/push/payload.go b/internal/equipo/push/payload.go
new file mode 100644
index 00000000..3901a901
--- /dev/null
+++ b/internal/equipo/push/payload.go
@@ -0,0 +1,113 @@
+package push
+
+import (
+ "encoding/json"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+type alertText struct {
+ Title string `json:"title"`
+ Body string `json:"body"`
+}
+
+type aps struct {
+ Alert *alertText `json:"alert,omitempty"`
+ Badge *int `json:"badge,omitempty"`
+ Sound string `json:"sound,omitempty"`
+ Category string `json:"category,omitempty"`
+ ThreadID string `json:"thread-id,omitempty"`
+ InterruptionLevel string `json:"interruption-level,omitempty"`
+ Timestamp int64 `json:"timestamp,omitempty"`
+ Event string `json:"event,omitempty"`
+ ContentState *wire.LiveActivityState `json:"content-state,omitempty"`
+ AttributesType string `json:"attributes-type,omitempty"`
+ Attributes *wire.LiveActivityAttributes `json:"attributes,omitempty"`
+ DismissalDate int64 `json:"dismissal-date,omitempty"`
+}
+
+type payload struct {
+ APS aps `json:"aps"`
+ Equipo *wire.PushData `json:"equipo,omitempty"`
+}
+
+// EndShown is how long an ended task's Live Activity stays on the Lock
+// Screen; one replaced by a newer task's goes at once.
+const EndShown = time.Hour
+
+// Render is an intent's APNs payload and push type, its words from copy
+// (Intent literals first), badge the person's Needs you count for a badge.
+func Render(in Intent, copy func(string) string, badge int, now time.Time) ([]byte, string, error) {
+ text := func(literal, key string) string {
+ if literal != "" {
+ return literal
+ }
+ if key == "" {
+ return ""
+ }
+ return copy(key)
+ }
+ p := payload{}
+ typ := TypeAlert
+ switch in.Kind {
+ case KindAlert, KindPassive:
+ p.APS.Alert = &alertText{Title: text(in.Title, in.TitleKey), Body: text(in.Body, in.BodyKey)}
+ p.APS.Category = in.Category
+ data := in.Data
+ p.Equipo = &data
+ if in.Kind == KindPassive {
+ p.APS.InterruptionLevel = "passive"
+ } else {
+ p.APS.Sound = "default"
+ }
+ if in.Data.TaskID != "" {
+ p.APS.ThreadID = "task:" + in.Data.TaskID
+ }
+ case KindBadge:
+ n := badge
+ p.APS.Badge = &n
+ case KindActivityStart, KindActivityUpdate, KindActivityEnd:
+ typ = TypeLiveActivity
+ p.APS.Timestamp = now.Unix()
+ p.APS.ContentState = in.State
+ switch in.Kind {
+ case KindActivityStart:
+ p.APS.Event = "start"
+ p.APS.AttributesType = wire.LiveActivityAttributesType
+ p.APS.Attributes = &wire.LiveActivityAttributes{TaskID: in.TaskID}
+ case KindActivityUpdate:
+ p.APS.Event = "update"
+ case KindActivityEnd:
+ p.APS.Event = "end"
+ p.APS.DismissalDate = now.Add(EndShown).Unix()
+ if in.State != nil && in.State.Outcome == wire.PushOutcomeReplaced {
+ p.APS.DismissalDate = now.Unix()
+ }
+ }
+ if title := text(in.Title, in.TitleKey); title != "" {
+ p.APS.Alert = &alertText{Title: title, Body: text(in.Body, in.BodyKey)}
+ p.APS.Sound = "default"
+ }
+ }
+ raw, err := json.Marshal(p)
+ return raw, typ, err
+}
+
+// TopicFor is the apns-topic of a push type.
+func TopicFor(pushType string) string {
+ if pushType == TypeLiveActivity {
+ return Topic + ".push-type.liveactivity"
+ }
+ return Topic
+}
+
+// Expiration is how long Apple keeps trying a push of a kind: an alert or
+// badge a day, a Live Activity change an hour (a newer one follows).
+func Expiration(kind string, created time.Time) time.Time {
+ switch kind {
+ case KindActivityStart, KindActivityUpdate, KindActivityEnd:
+ return created.Add(time.Hour)
+ }
+ return created.Add(24 * time.Hour)
+}
diff --git a/internal/equipo/push/payload_test.go b/internal/equipo/push/payload_test.go
new file mode 100644
index 00000000..85c723ca
--- /dev/null
+++ b/internal/equipo/push/payload_test.go
@@ -0,0 +1,108 @@
+package push
+
+import (
+ "bytes"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// copyStub stands for copy.go: the key in brackets.
+func copyStub(key string) string { return "[" + key + "]" }
+
+// TestPayloadGoldens holds every kind of push's APNs payload to its
+// golden in testdata (EQUIPO_PUSH_GOLDEN=1 rewrites them): the shapes the
+// native apps decode.
+func TestPayloadGoldens(t *testing.T) {
+ working := task(wire.StageInProgress, "", true)
+ working.Activity = "Reading README.md"
+ ready := task(wire.StageReadyToMerge, wire.NeedsMerge, false)
+ ready.Tone = wire.ToneWarning
+ done := task(wire.StageDone, "", false)
+ pick := func(c Change, rule string) Intent {
+ for _, in := range Decide(c) {
+ if in.Rule == rule {
+ return in
+ }
+ }
+ t.Fatalf("no %s", rule)
+ return Intent{}
+ }
+ cases := map[string]struct {
+ in Intent
+ badge int
+ typ string
+ }{
+ "card": {pick(Change{Kind: ChangeCard, Card: Card{ID: "c1", Kind: wire.CardMerge, State: wire.CardOpen, Question: "Merge the login fix?", TaskID: "tk1"}}, "card_opens"), 0, TypeAlert},
+ "reply": {pick(Change{Kind: ChangeReply, Reply: Reply{TurnID: "t1", Kind: wire.TurnPerson, State: wire.TurnReplied, Text: "Done. The fix is on its branch.\nMore."}}, "reply_unseen"), 0, TypeAlert},
+ "task-done": {pick(Change{Kind: ChangeTask, Before: seen(ready, true), After: done}, "task_ends"), 0, TypeAlert},
+ "task-failed": {pick(Change{Kind: ChangeTask, Before: seen(working, true), After: task(wire.StageInProgress, wire.NeedsRetry, false)}, "task_fails"), 0, TypeAlert},
+ "badge": {pick(Change{Kind: ChangeTask, Before: seen(working, true), After: ready}, "badge"), 2, TypeAlert},
+ "activity-start": {pick(Change{Kind: ChangeTask, Before: seen(task(wire.StageNoted, "", false), false), After: working}, "activity_start"), 0, TypeLiveActivity},
+ "activity-update": {pick(Change{Kind: ChangeLine, Now: at, Before: seen(task(wire.StageInProgress, "", true), true), After: working}, "activity_line"), 0, TypeLiveActivity},
+ "activity-needs": {pick(Change{Kind: ChangeTask, Before: seen(working, true), After: ready}, "activity_update"), 0, TypeLiveActivity},
+ "activity-end": {pick(Change{Kind: ChangeTask, Before: seen(ready, true), After: done}, "activity_end"), 0, TypeLiveActivity},
+ "activity-replaced": {Replace(working), 0, TypeLiveActivity},
+ }
+ for name, c := range cases {
+ raw, typ, err := Render(c.in, copyStub, c.badge, at)
+ if err != nil {
+ t.Fatal(name, err)
+ }
+ if typ != c.typ {
+ t.Errorf("%s: push type %s, want %s", name, typ, c.typ)
+ }
+ if len(raw) > 4096 {
+ t.Errorf("%s: %d bytes, over APNs' 4 KB", name, len(raw))
+ }
+ var pretty bytes.Buffer
+ if err := json.Indent(&pretty, raw, "", " "); err != nil {
+ t.Fatal(err)
+ }
+ pretty.WriteByte('\n')
+ path := filepath.Join("testdata", name+".json")
+ if os.Getenv("EQUIPO_PUSH_GOLDEN") == "1" {
+ if err := os.WriteFile(path, pretty.Bytes(), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ continue
+ }
+ want, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(want, pretty.Bytes()) {
+ t.Errorf("%s payload differs from its golden:\n%s", name, pretty.String())
+ }
+ }
+ if TopicFor(TypeLiveActivity) != "works.oficina.equipo.push-type.liveactivity" || TopicFor(TypeAlert) != "works.oficina.equipo" {
+ t.Fatal("topics")
+ }
+}
+
+// TestPayloadContentState: a push-to-start carries the task's content
+// state and attributes as the app's Codable types decode them.
+func TestPayloadContentState(t *testing.T) {
+ k := task(wire.StageInProgress, "", true)
+ raw, _, err := Render(Decide(Change{Kind: ChangeTask, Before: seen(task(wire.StageNoted, "", false), false), After: k})[0], copyStub, 0, at)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var p struct {
+ APS struct {
+ ContentState wire.LiveActivityState `json:"content-state"`
+ Attributes wire.LiveActivityAttributes `json:"attributes"`
+ AttributesType string `json:"attributes-type"`
+ } `json:"aps"`
+ }
+ if err := json.Unmarshal(raw, &p); err != nil {
+ t.Fatal(err)
+ }
+ want := wire.LiveActivityState{TaskID: "tk1", Title: "Fix login", Stage: wire.StageInProgress, Specialist: wire.SpecialistEngineering, NeedsYou: "", Tone: wire.TonePositive}
+ if p.APS.ContentState != want || p.APS.Attributes.TaskID != "tk1" || p.APS.AttributesType != wire.LiveActivityAttributesType {
+ t.Fatalf("content state %+v", p.APS)
+ }
+}
diff --git a/internal/equipo/push/push.go b/internal/equipo/push/push.go
new file mode 100644
index 00000000..4d58782d
--- /dev/null
+++ b/internal/equipo/push/push.go
@@ -0,0 +1,94 @@
+// Package push is Equipo's push notifications for the native apps (plan
+// 2026-11-20-equipo-native-slice-2.md): device registrations, the outbox
+// the conversation engine writes in the transaction of each change, the
+// rule table deciding what pushes whom, the APNs payloads, and the sender
+// that drains the outbox through a Transport.
+//
+// Tokens are secrets: they live only in the registration tables and are
+// handed to the transport. They are never logged, audited or echoed.
+package push
+
+import (
+ "context"
+ "errors"
+ "time"
+)
+
+// Topic is the apps' bundle ID; a Live Activity's topic adds
+// ".push-type.liveactivity".
+const Topic = "works.oficina.equipo"
+
+// Kinds of push, each one outbox row.
+const (
+ KindAlert = "alert"
+ KindPassive = "passive"
+ KindBadge = "badge"
+ KindActivityStart = "activity_start"
+ KindActivityUpdate = "activity_update"
+ KindActivityEnd = "activity_end"
+)
+
+// APNs push types (apns-push-type).
+const (
+ TypeAlert = "alert"
+ TypeLiveActivity = "liveactivity"
+)
+
+// Targets: which of a device's tokens a row goes to.
+const (
+ TargetDevice = "device" // the registration's APNs token
+ TargetStart = "start" // its Live Activity push-to-start token
+ TargetActivity = "activity" // a running activity's own update token
+)
+
+// 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.
+type Message struct {
+ ID string
+ Token string
+ Environment string
+ Topic string
+ PushType string
+ Priority int
+ CollapseID string
+ Expiration time.Time
+ 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.
+type Result struct {
+ Status int
+ Reason string
+ APNsID string
+}
+
+// Apple's reasons that mean the token is gone for good.
+const (
+ ReasonUnregistered = "Unregistered"
+ ReasonBadDeviceToken = "BadDeviceToken"
+)
+
+// 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
+}
+
+// Transport delivers one push. An error is a delivery that did not reach
+// Apple (retried); a Result is Apple's answer, whatever it was.
+type Transport interface {
+ Send(ctx context.Context, m Message) (Result, error)
+}
+
+// ErrNoActivity: an activity update or end with no running activity's
+// token on file yet.
+var ErrNoActivity = errors.New("push: no activity token")
diff --git a/internal/equipo/push/rules.go b/internal/equipo/push/rules.go
new file mode 100644
index 00000000..902c2ef8
--- /dev/null
+++ b/internal/equipo/push/rules.go
@@ -0,0 +1,270 @@
+package push
+
+import (
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Changes the engine reports, each from the transaction that made it.
+const (
+ ChangeCard = "card" // a card was written (cardEvent)
+ ChangeReply = "reply" // a turn was saved (saveTurn)
+ ChangeTask = "task" // a task was written (taskEvent)
+ ChangeLine = "line" // a running step reported an activity line
+)
+
+// Change is one engine change, as the rules read it. Only the fields of
+// its kind are set.
+type Change struct {
+ Kind string
+ Now time.Time
+ Card Card
+ // Reply is a saved turn; Streaming whether the person has an /events
+ // stream open now.
+ Reply Reply
+ Streaming bool
+ // Before is what the person's push memory held for the task; After the
+ // task now. A line change carries the new line in After.Activity.
+ Before Memory
+ After Task
+}
+
+// Card is a card as the rules read it. Alerted: this card already pushed
+// its alert to the person (it opens once).
+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.
+type Reply struct {
+ TurnID, Lane, Kind, State, Text string
+}
+
+// Task is a task the person started, as a Live Activity shows it.
+type Task struct {
+ ID, Title, Stage, NeedsYou, Specialist, StepID, Activity, Tone string
+ // Working: a step of it is running on a runner (it was dispatched).
+ Working bool
+}
+
+// Final reports whether the task ended.
+func (k Task) Final() bool { return wire.FinalStage(k.Stage) }
+
+// Memory is what the person's devices were last told about a task.
+type Memory struct {
+ Seen bool
+ Title, Tone, Stage, NeedsYou, Specialist, StepID, Activity string
+ // Started is when its Live Activity started; Ended once it ended.
+ Started *time.Time
+ Ended bool
+ // LineAt is when an activity line last updated the Live Activity.
+ LineAt *time.Time
+}
+
+// Task is the task as the memory last showed it.
+func (m Memory) Task(id string) Task {
+ return Task{ID: id, Title: m.Title, Tone: m.Tone, Stage: m.Stage, NeedsYou: m.NeedsYou, Specialist: m.Specialist, StepID: m.StepID, Activity: m.Activity}
+}
+
+// Remember is the memory after the devices were told about k.
+func (m Memory) Remember(k Task) Memory {
+ m.Seen, m.Title, m.Tone, m.Stage, m.NeedsYou, m.Specialist, m.StepID, m.Activity = true, k.Title, k.Tone, k.Stage, k.NeedsYou, k.Specialist, k.StepID, k.Activity
+ return m
+}
+
+// Live reports whether the task's Live Activity is running.
+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
+// sent), its words (literal Title and Body, else copy keys), where a tap
+// goes (Data), and a Live Activity's state.
+type Intent struct {
+ Rule string
+ Kind string
+ Priority int
+ CollapseID string
+ Dedupe string
+ Coalesce bool
+ Title string
+ TitleKey string
+ Body string
+ BodyKey string
+ Category string
+ Data wire.PushData
+ State *wire.LiveActivityState
+ // TaskID names the task a Live Activity push follows.
+ TaskID string
+}
+
+// LineEvery is how often an activity line may update a Live Activity, to
+// stay inside Apple's update budget.
+const LineEvery = time.Minute
+
+// CategoryNeedsYou is the alert category whose only action is Open (D4).
+const CategoryNeedsYou = "needs_you"
+
+// Rule is one row of the table: when it applies to a change, and the push.
+type Rule struct {
+ Name string
+ When func(Change) bool
+ Push func(Change) Intent
+}
+
+// Rules is the table: every rule that applies to a change pushes.
+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
+ }, 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 == "" {
+ in.BodyKey = "push.card.body"
+ }
+ return in
+ }},
+ // The coordinator replied to the person while no stream is open: an
+ // alert with the reply's first line (D2).
+ {"reply_unseen", func(c Change) bool {
+ r := c.Reply
+ return c.Kind == ChangeReply && r.Lane == wire.LaneCoordinator && r.Kind == wire.TurnPerson && r.State == wire.TurnReplied && !c.Streaming && FirstLine(r.Text) != ""
+ }, func(c Change) Intent {
+ return Intent{Kind: KindAlert, Priority: 10, CollapseID: "reply:" + c.Reply.TurnID, Dedupe: "reply:" + c.Reply.TurnID, TitleKey: "push.reply.title", Body: FirstLine(c.Reply.Text), Data: wire.PushData{Kind: wire.PushReply, TurnID: c.Reply.TurnID}}
+ }},
+ // A task the person started ends: a passive alert with its outcome.
+ {"task_ends", func(c Change) bool {
+ return c.Kind == ChangeTask && c.Before.Seen && c.After.Final() && !wire.FinalStage(c.Before.Stage)
+ }, func(c Change) Intent {
+ in := taskAlert(c, outcome(c.After))
+ in.Dedupe = "outcome:" + c.After.ID + ":" + outcome(c.After)
+ return in
+ }},
+ // A step of it failed (it waits for Retry): a passive alert too.
+ {"task_fails", func(c Change) bool {
+ return c.Kind == ChangeTask && c.Before.Seen && !c.After.Final() && c.After.NeedsYou == wire.NeedsRetry && c.Before.NeedsYou != wire.NeedsRetry
+ }, func(c Change) Intent {
+ return taskAlert(c, wire.PushOutcomeFailed)
+ }},
+ // Needs you changed: the badge, the newest count replacing any unsent.
+ {"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}}
+ }},
+ // It was dispatched: its Live Activity starts, by push-to-start.
+ {"activity_start", func(c Change) bool {
+ return c.Kind == ChangeTask && c.After.Working && !c.After.Final() && c.Before.Started == nil
+ }, 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.
+ {"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"
+ }
+ return in
+ }},
+ // A new activity line: an update at most once a minute a task.
+ {"activity_line", func(c Change) bool {
+ b := c.Before
+ return c.Kind == ChangeLine && b.Live() && c.After.Activity != b.Activity && (b.LineAt == nil || c.Now.Sub(*b.LineAt) >= LineEvery)
+ }, func(c Change) Intent {
+ return Intent{Kind: KindActivityUpdate, Priority: 5, TaskID: c.After.ID, State: state(c.After, "")}
+ }},
+ // It ended: the Live Activity ends with the outcome.
+ {"activity_end", func(c Change) bool {
+ return c.Kind == ChangeTask && c.Before.Live() && c.After.Final()
+ }, func(c Change) Intent {
+ return Intent{Kind: KindActivityEnd, Priority: 10, TaskID: c.After.ID, State: state(c.After, outcome(c.After))}
+ }},
+}
+
+// Decide is every push the table asks for a change, in table order.
+func Decide(c Change) []Intent {
+ var out []Intent
+ for _, r := range Rules {
+ if r.When(c) {
+ in := r.Push(c)
+ in.Rule = r.Name
+ out = append(out, in)
+ }
+ }
+ return out
+}
+
+// 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)}
+}
+
+// waits reports whether a card waits on its person: open (or asking), not
+// a receipt, and not an access request that already ended.
+func waits(c Card) bool {
+ if c.State != wire.CardOpen && c.State != wire.CardHomeAsk {
+ return false
+ }
+ switch c.Kind {
+ case wire.CardProject, wire.CardTask, wire.CardCombined, wire.CardHousekeeping, wire.CardDigest, wire.CardMergeReceipt:
+ return false
+ case wire.CardHome:
+ return c.State == wire.CardHomeAsk
+ case wire.CardAccess:
+ return !c.AccessFinal
+ }
+ return true
+}
+
+func taskAlert(c Change, outcome string) Intent {
+ return Intent{Kind: KindPassive, Priority: 5, CollapseID: "task:" + c.After.ID, Title: Clip(c.After.Title), BodyKey: "push.task." + outcome, Data: wire.PushData{Kind: wire.PushTask, TaskID: c.After.ID}}
+}
+
+func outcome(k Task) string {
+ if k.Stage == wire.StageDone {
+ return wire.PushOutcomeDone
+ }
+ return wire.PushOutcomeCancelled
+}
+
+func state(k Task, outcome string) *wire.LiveActivityState {
+ return &wire.LiveActivityState{TaskID: k.ID, Title: Clip(k.Title), Stage: k.Stage, Specialist: k.Specialist, Activity: k.Activity, NeedsYou: k.NeedsYou, Tone: k.Tone, Outcome: outcome}
+}
+
+// MaxText bounds an alert's title or body, so a payload stays well under
+// APNs' 4 KB.
+const MaxText = 178
+
+// Clip trims s to MaxText runes, with an ellipsis when it cut.
+func Clip(s string) string {
+ s = strings.TrimSpace(s)
+ if utf8.RuneCountInString(s) <= MaxText {
+ return s
+ }
+ r := []rune(s)
+ return strings.TrimSpace(string(r[:MaxText-1])) + "…"
+}
+
+// FirstLine is a reply's first line with text, as plain words: leading
+// heading and list marks and emphasis stars dropped, clipped.
+func FirstLine(s string) string {
+ for line := range strings.SplitSeq(s, "\n") {
+ line = strings.TrimSpace(line)
+ line = strings.TrimLeft(line, "#>-*+ ")
+ line = strings.ReplaceAll(line, "**", "")
+ line = strings.ReplaceAll(line, "`", "")
+ if line = strings.TrimSpace(line); line != "" {
+ return Clip(line)
+ }
+ }
+ return ""
+}
diff --git a/internal/equipo/push/rules_test.go b/internal/equipo/push/rules_test.go
new file mode 100644
index 00000000..5e4419a9
--- /dev/null
+++ b/internal/equipo/push/rules_test.go
@@ -0,0 +1,200 @@
+package push
+
+import (
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+var at = time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
+
+func rules(c Change) []string {
+ var out []string
+ for _, in := range Decide(c) {
+ out = append(out, in.Rule)
+ }
+ return out
+}
+
+func only(t *testing.T, c Change, want ...string) []Intent {
+ t.Helper()
+ if got := rules(c); !slices.Equal(got, want) {
+ t.Fatalf("rules %v, want %v", got, want)
+ }
+ return Decide(c)
+}
+
+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.
+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]
+ if in.Kind != KindAlert || in.Priority != 10 || in.CollapseID != "c1" || in.Dedupe != "card:c1" || in.Body != "Merge the login fix?" || in.TitleKey != "push.card.title" || in.Category != CategoryNeedsYou {
+ t.Fatalf("card alert %+v", in)
+ }
+ if in.Data != (wire.PushData{Kind: wire.PushCard, CardID: "c1", TaskID: "tk1"}) {
+ t.Fatalf("tap data %+v", in.Data)
+ }
+ noQuestion := open
+ noQuestion.Question = ""
+ if in := only(t, Change{Kind: ChangeCard, Card: noQuestion}, "card_opens")[0]; in.Body != "" || in.BodyKey != "push.card.body" {
+ t.Fatalf("no question %+v", in)
+ }
+ ask := Card{ID: "c2", Kind: wire.CardHome, State: wire.CardHomeAsk}
+ only(t, Change{Kind: ChangeCard, Card: ask}, "card_opens")
+ for name, c := range map[string]Card{
+ "answered": {ID: "c", Kind: wire.CardMerge, State: wire.CardAnswered},
+ "receipt": {ID: "c", Kind: wire.CardTask, State: wire.CardOpen},
+ "project": {ID: "c", Kind: wire.CardProject, State: wire.CardOpen},
+ "home set": {ID: "c", Kind: wire.CardHome, State: wire.CardHomeSet},
+ "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)
+ }
+ }
+}
+
+// TestRuleReplyUnseen: a finished reply to the person's message alerts
+// with its first line only when no stream is open.
+func TestRuleReplyUnseen(t *testing.T) {
+ r := Reply{TurnID: "t1", Kind: wire.TurnPerson, State: wire.TurnReplied, Text: "\n## **Done.** The fix is on its branch.\nMore detail here."}
+ in := only(t, Change{Kind: ChangeReply, Reply: r}, "reply_unseen")[0]
+ if in.Body != "Done. The fix is on its branch." || in.CollapseID != "reply:t1" || in.Dedupe != "reply:t1" || in.Priority != 10 || in.Data.TurnID != "t1" {
+ t.Fatalf("reply alert %+v", in)
+ }
+ if got := rules(Change{Kind: ChangeReply, Reply: r, Streaming: true}); len(got) != 0 {
+ t.Fatalf("an open stream still pushed %v", got)
+ }
+ for name, mod := range map[string]func(*Reply){
+ "move in": func(r *Reply) { r.Kind = wire.TurnMoveIn },
+ "failed": func(r *Reply) { r.State = wire.TurnFailed },
+ "running": func(r *Reply) { r.State = wire.TurnRunning },
+ "assistant": func(r *Reply) { r.Lane = wire.LaneAssistant },
+ "empty": func(r *Reply) { r.Text = " \n " },
+ } {
+ c := r
+ mod(&c)
+ if got := rules(Change{Kind: ChangeReply, Reply: c}); len(got) != 0 {
+ t.Errorf("%s pushed %v", name, got)
+ }
+ }
+ if long := FirstLine(strings.Repeat("word ", 100)); len([]rune(long)) != MaxText || !strings.HasSuffix(long, "…") {
+ t.Fatalf("not clipped: %d", len([]rune(long)))
+ }
+}
+
+func task(stage, needs string, working bool) Task {
+ return Task{ID: "tk1", Title: "Fix login", Stage: stage, NeedsYou: needs, Specialist: wire.SpecialistEngineering, StepID: "s1", Working: working, Tone: wire.TonePositive}
+}
+
+func seen(k Task, live bool) Memory {
+ m := Memory{}.Remember(k)
+ if live {
+ m.Started = started()
+ }
+ return m
+}
+
+// TestRuleTaskLifecycle walks a task the person started: dispatch starts
+// its Live Activity, a stage change updates it at priority 5, needing the
+// person updates it at 10 with an alert and the badge, failing alerts
+// passively, and the end alerts and ends the activity with the outcome.
+func TestRuleTaskLifecycle(t *testing.T) {
+ noted := task(wire.StageNoted, "", false)
+ // Recorded, nothing running: no push yet (no memory: first sighting).
+ only(t, Change{Kind: ChangeTask, After: noted})
+ only(t, Change{Kind: ChangeTask, Before: seen(noted, false), After: noted})
+
+ working := task(wire.StageInProgress, "", true)
+ in := only(t, Change{Kind: ChangeTask, Before: seen(noted, false), After: working}, "activity_start")[0]
+ if in.Kind != KindActivityStart || in.Priority != 10 || in.TaskID != "tk1" || in.State == nil || in.State.Stage != wire.StageInProgress || in.Title != "Fix login" {
+ t.Fatalf("start %+v", in)
+ }
+ // Already started: no second start.
+ only(t, Change{Kind: ChangeTask, Before: seen(working, true), After: working})
+
+ review := task(wire.StageInReview, "", true)
+ review.Specialist, review.StepID = wire.SpecialistReview, "s2"
+ if in := only(t, Change{Kind: ChangeTask, Before: seen(working, true), After: review}, "activity_update")[0]; in.Priority != 5 || in.Title != "" {
+ t.Fatalf("stage update %+v", in)
+ }
+ step := working
+ step.StepID = "s3"
+ only(t, Change{Kind: ChangeTask, Before: seen(working, true), After: step}, "activity_update")
+
+ ready := task(wire.StageReadyToMerge, wire.NeedsMerge, false)
+ ready.Tone = wire.ToneWarning
+ got := only(t, Change{Kind: ChangeTask, Before: seen(review, true), After: ready}, "badge", "activity_update")
+ 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 {
+ t.Fatalf("needs you update %+v", in)
+ }
+
+ failed := task(wire.StageInProgress, wire.NeedsRetry, false)
+ got = only(t, Change{Kind: ChangeTask, Before: seen(working, true), After: failed}, "task_fails", "badge", "activity_update")
+ if got[0].Kind != KindPassive || got[0].BodyKey != "push.task.failed" || got[0].Dedupe != "" {
+ t.Fatalf("failed alert %+v", got[0])
+ }
+
+ done := task(wire.StageDone, "", false)
+ got = only(t, Change{Kind: ChangeTask, Before: seen(ready, true), After: done}, "task_ends", "badge", "activity_end")
+ if got[0].Kind != KindPassive || got[0].BodyKey != "push.task.done" || got[0].Dedupe != "outcome:tk1:done" || got[0].CollapseID != "task:tk1" {
+ t.Fatalf("done alert %+v", got[0])
+ }
+ if end := got[2]; end.Kind != KindActivityEnd || end.State.Outcome != wire.PushOutcomeDone {
+ t.Fatalf("end %+v", end)
+ }
+ cancelled := task(wire.StageCancelled, "", false)
+ if in := only(t, Change{Kind: ChangeTask, Before: seen(working, false), After: cancelled}, "task_ends")[0]; in.BodyKey != "push.task.cancelled" {
+ t.Fatalf("cancelled %+v", in)
+ }
+ // An ended task seen again pushes nothing; one first seen ended neither.
+ only(t, Change{Kind: ChangeTask, Before: seen(done, false), After: done})
+ only(t, Change{Kind: ChangeTask, After: done})
+ // An ended activity is not updated or ended again.
+ m := seen(working, true)
+ m.Ended = true
+ only(t, Change{Kind: ChangeTask, Before: m, After: review})
+}
+
+// TestRuleActivityLine: a new line updates the activity at most once a
+// minute a task, only while it runs.
+func TestRuleActivityLine(t *testing.T) {
+ m := seen(task(wire.StageInProgress, "", true), true)
+ line := m.Task("tk1")
+ line.Activity = "Reading README.md"
+ only(t, Change{Kind: ChangeLine, Now: at, Before: m, After: line}, "activity_line")
+ recent := at.Add(-30 * time.Second)
+ m.LineAt = &recent
+ only(t, Change{Kind: ChangeLine, Now: at, Before: m, After: line})
+ old := at.Add(-LineEvery)
+ m.LineAt = &old
+ if in := only(t, Change{Kind: ChangeLine, Now: at, Before: m, After: line}, "activity_line")[0]; in.Priority != 5 || in.State.Activity != "Reading README.md" {
+ t.Fatalf("line %+v", in)
+ }
+ same := m
+ same.Activity = line.Activity
+ only(t, Change{Kind: ChangeLine, Now: at, Before: same, After: line})
+ notLive := seen(task(wire.StageInProgress, "", true), false)
+ only(t, Change{Kind: ChangeLine, Now: at, Before: notLive, After: line})
+}
+
+// TestReplaceEndsAtOnce: the activity a newer one replaces ends now.
+func TestReplaceEndsAtOnce(t *testing.T) {
+ in := Replace(task(wire.StageInProgress, "", true))
+ if in.Kind != KindActivityEnd || in.State.Outcome != wire.PushOutcomeReplaced {
+ t.Fatalf("replace %+v", in)
+ }
+}
diff --git a/internal/equipo/push/sender.go b/internal/equipo/push/sender.go
new file mode 100644
index 00000000..1a221064
--- /dev/null
+++ b/internal/equipo/push/sender.go
@@ -0,0 +1,221 @@
+package push
+
+import (
+ "context"
+ "errors"
+ "time"
+
+ "gorm.io/gorm"
+)
+
+// 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).
+type Sender struct {
+ Write func(context.Context, func(*gorm.DB) error) error
+ Transport Transport
+ Check func(tx *gorm.DB, person, credential string) error
+ Now func() time.Time
+ // 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).
+const (
+ PassSize = 50
+ Lease = time.Minute
+ FirstRetry = 5 * time.Second
+ MaxRetry = 10 * time.Minute
+ MaxAttempts = 8
+ Keep = 7 * 24 * time.Hour
+)
+
+// Backoff is the wait before attempt n+1 (n sends have failed).
+func Backoff(n int) time.Duration {
+ d := FirstRetry
+ for i := 1; i < n && d < MaxRetry; i++ {
+ d *= 2
+ }
+ return min(d, MaxRetry)
+}
+
+// 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()
+ var due []OutboxRecord
+ err = s.Write(ctx, func(tx *gorm.DB) error {
+ if err := tx.Where("state <> ? AND updated_at < ?", StatePending, now.Add(-Keep)).Delete(&OutboxRecord{}).Error; err != nil {
+ return err
+ }
+ return tx.Where("state = ? AND next_at <= ? AND (lease_until IS NULL OR lease_until < ?)", StatePending, now, now).Order("next_at, created_at, id").Limit(PassSize).Find(&due).Error
+ })
+ if err != nil {
+ return 0, err
+ }
+ for _, r := range due {
+ if ctx.Err() != nil {
+ return sent, ctx.Err()
+ }
+ ok, err := s.one(ctx, r)
+ if err != nil {
+ s.errorf("push not sent", "id", r.ID, "err", err)
+ continue
+ }
+ if ok {
+ sent++
+ }
+ }
+ return sent, nil
+}
+
+// one claims a row, sends it and records the answer.
+func (s *Sender) one(ctx context.Context, r OutboxRecord) (bool, 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})
+ if res.Error != nil || res.RowsAffected != 1 {
+ return res.Error
+ }
+ 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
+ }
+ return finish(tx, r.ID, StateDropped, Result{Reason: "not_current"}, now)
+ }
+ 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 finish(tx, r.ID, StateDropped, Result{Reason: "no_token"}, now)
+ }
+ if err != nil {
+ return err
+ }
+ 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)}
+ return nil
+ })
+ if err != nil || !claimed {
+ return false, err
+ }
+ result, sendErr := s.Transport.Send(ctx, m)
+ ok := false
+ err = s.Write(context.WithoutCancel(ctx), func(tx *gorm.DB) error {
+ now := s.Now()
+ switch {
+ case sendErr != nil || result.Retryable():
+ 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 {
+ return err
+ }
+ return finish(tx, r.ID, StateFailed, result, now)
+ case result.Status >= 200 && result.Status < 300:
+ ok = true
+ 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)
+ }
+ })
+ if sendErr != nil && err == nil {
+ err = sendErr
+ }
+ return ok, err
+}
+
+// token is the row's token as the device registered it now.
+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 {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return "", "", ErrNoActivity
+ }
+ return "", "", err
+ }
+ switch r.Target {
+ case TargetStart:
+ if reg.StartToken == "" {
+ return "", "", ErrNoActivity
+ }
+ return reg.StartToken, reg.Environment, nil
+ 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
+ }
+ return reg.Token, reg.Environment, nil
+}
+
+// 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 {
+ 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
+ }
+ 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
+}
+
+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")}
+ if state == StateSent {
+ fields["sent_at"] = now
+ }
+ if state == StateDropped {
+ fields["attempts"] = gorm.Expr("attempts")
+ }
+ keys := make([]string, 0, len(fields))
+ for k := range fields {
+ keys = append(keys, k)
+ }
+ return tx.Model(&OutboxRecord{}).Where("id = ?", id).Select(keys).Updates(fields).Error
+}
+
+func (s *Sender) errorf(msg string, args ...any) {
+ if s.Errorf != nil {
+ s.Errorf(msg, args...)
+ }
+}
+
+// Serve drains the outbox every interval and at each wake, until ctx ends.
+func (s *Sender) Serve(ctx context.Context, wake <-chan struct{}, every time.Duration) {
+ tick := time.NewTicker(every)
+ defer tick.Stop()
+ for {
+ if _, err := s.Drain(ctx); err != nil && ctx.Err() == nil {
+ s.errorf("push outbox not drained", "err", err)
+ }
+ select {
+ case <-ctx.Done():
+ return
+ case <-tick.C:
+ case <-wake:
+ }
+ }
+}
diff --git a/internal/equipo/push/sender_test.go b/internal/equipo/push/sender_test.go
new file mode 100644
index 00000000..24f1392e
--- /dev/null
+++ b/internal/equipo/push/sender_test.go
@@ -0,0 +1,355 @@
+package push
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "io"
+ "log/slog"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+ "amadan.net/rastrillo/rastrillo/db"
+ "gorm.io/gorm"
+)
+
+const (
+ devToken = "aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11"
+ startToken = "bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22"
+ actToken = "cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33"
+)
+
+type rig struct {
+ t *testing.T
+ d *db.DB
+ now time.Time
+ current map[string]bool // credential -> still valid
+ sent []Message
+ answer func(Message) (Result, error)
+ s *Sender
+}
+
+func newRig(t *testing.T) *rig {
+ t.Helper()
+ d, err := db.Open(filepath.Join(t.TempDir(), "push.db"), slog.New(slog.NewTextHandler(io.Discard, nil)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = d.Close() })
+ if err := d.G.AutoMigrate(Models...); err != nil {
+ t.Fatal(err)
+ }
+ r := &rig{t: t, d: d, now: at, current: map[string]bool{"cr1": true}}
+ r.answer = func(m Message) (Result, error) { return Result{Status: 200, APNsID: "apple-" + m.ID}, nil }
+ r.s = &Sender{
+ Write: func(ctx context.Context, fn func(*gorm.DB) error) error { return d.G.WithContext(ctx).Transaction(fn) },
+ Transport: transportFunc(func(_ context.Context, m Message) (Result, error) {
+ r.sent = append(r.sent, m)
+ return r.answer(m)
+ }),
+ Check: func(_ *gorm.DB, person, credential string) error {
+ if person != "p@example.com" || !r.current[credential] {
+ return errors.New("not current")
+ }
+ return nil
+ },
+ 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)
+ return err
+ }))
+ return r
+}
+
+type transportFunc func(context.Context, Message) (Result, error)
+
+func (f transportFunc) Send(ctx context.Context, m Message) (Result, error) { return f(ctx, m) }
+
+func (r *rig) must(err error) {
+ r.t.Helper()
+ if err != nil {
+ r.t.Fatal(err)
+ }
+}
+
+func (r *rig) enqueue(kind, target, collapse, dedupe 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) }))
+}
+
+func (r *rig) rows() []OutboxRecord {
+ var out []OutboxRecord
+ r.must(r.d.G.Order("created_at, collapse_id, kind").Find(&out).Error)
+ return out
+}
+
+func (r *rig) drain() int {
+ r.t.Helper()
+ n, err := r.s.Drain(context.Background())
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ return n
+}
+
+// TestSenderSendsOnceAndRecordsApple: a row goes once, with its id as
+// apns-id, the token read from the registration, the topic of its push
+// 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)
+ 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 {
+ t.Fatalf("message %+v", m)
+ }
+ if row.State != StateSent || row.Status != 200 || row.APNsID != "apple-"+row.ID || row.SentAt == nil || row.Attempts != 1 {
+ t.Fatalf("row %+v", row)
+ }
+}
+
+// TestSenderRetryIsTheSamePush: a failed delivery is retried after the
+// backoff with the same id and collapse ID, and once accepted never sent
+// 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)
+ calls := 0
+ r.answer = func(m Message) (Result, error) {
+ calls++
+ switch calls {
+ case 1:
+ return Result{}, errors.New("connection reset")
+ case 2:
+ return Result{Status: 429, Reason: "TooManyRequests"}, nil
+ }
+ return Result{Status: 200, APNsID: m.ID}, nil
+ }
+ r.drain()
+ if row := r.rows()[0]; row.State != StatePending || row.Attempts != 1 || !row.NextAt.Equal(at.Add(FirstRetry)) {
+ t.Fatalf("after a failure %+v", row)
+ }
+ if r.drain() != 0 || len(r.sent) != 1 {
+ t.Fatal("retried before the backoff")
+ }
+ r.now = at.Add(FirstRetry)
+ r.drain()
+ if row := r.rows()[0]; row.State != StatePending || row.Attempts != 2 || row.Status != 429 || row.Reason != "TooManyRequests" {
+ t.Fatalf("after throttling %+v", row)
+ }
+ r.now = r.now.Add(Backoff(2))
+ if r.drain() != 1 {
+ t.Fatal("not sent on the third try")
+ }
+ r.now = r.now.Add(time.Hour)
+ r.drain()
+ if len(r.sent) != 3 || r.sent[0].ID != r.sent[2].ID || r.sent[0].CollapseID != r.sent[2].CollapseID {
+ t.Fatalf("sends %d", len(r.sent))
+ }
+ if Backoff(1) != FirstRetry || Backoff(2) != 2*FirstRetry || Backoff(30) != MaxRetry {
+ t.Fatal("backoff")
+ }
+}
+
+// TestSenderGivesUp: after MaxAttempts failed deliveries the row fails.
+func TestSenderGivesUp(t *testing.T) {
+ r := newRig(t)
+ 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()
+ }
+ 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))
+ }
+}
+
+// TestSenderForgetsGoneTokens: Unregistered or BadDeviceToken deletes the
+// registration and drops what waits for it; on a push-to-start token it
+// clears that token only; on an activity's, that activity's.
+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.answer = func(Message) (Result, error) { return Result{Status: 400, Reason: reason}, nil }
+ r.drain()
+ var n int64
+ r.d.G.Model(&Registration{}).Count(&n)
+ states := map[string]int{}
+ rows := r.rows()
+ for _, row := range rows {
+ states[row.State+" "+row.Reason]++
+ }
+ if n != 0 || len(r.sent) != 1 || states[StateFailed+" "+reason] != 1 || states[StateDropped+" forgotten"] != 1 {
+ t.Fatalf("%s: registrations %d, sent %d, rows %+v", reason, n, len(r.sent), rows)
+ }
+ }
+ r := newRig(t)
+ 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" {
+ 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.drain()
+ var acts int64
+ r.d.G.Model(&ActivityToken{}).Count(&acts)
+ if acts != 0 || r.sent[1].Token != actToken {
+ t.Fatal("activity token kept after Unregistered")
+ }
+}
+
+// TestSenderNeverSendsToRevokedOrRemoved: a device no longer current
+// (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.current["cr1"] = false
+ r.drain()
+ var n int64
+ r.d.G.Model(&Registration{}).Count(&n)
+ if len(r.sent) != 0 || n != 0 || r.rows()[0].State != StateDropped {
+ t.Fatalf("sent %d, registrations %d", len(r.sent), n)
+ }
+}
+
+// TestSenderActivityTokens: an update waits for no token (dropped), an end
+// 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.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.now = r.now.Add(FirstRetry)
+ r.drain()
+ var acts int64
+ r.d.G.Model(&ActivityToken{}).Count(&acts)
+ if len(r.sent) != 1 || r.sent[0].Token != actToken || acts != 0 {
+ t.Fatalf("end sent %d, tokens left %d", len(r.sent), acts)
+ }
+}
+
+// TestSenderClaimsOnce: a row another sender holds (an overlapping
+// process) is not sent again until its lease ends.
+func TestSenderClaimsOnce(t *testing.T) {
+ r := newRig(t)
+ 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 {
+ t.Fatal("sent a row another sender holds")
+ }
+ r.now = lease.Add(time.Second)
+ if r.drain() != 1 {
+ t.Fatal("an expired lease was not taken over")
+ }
+}
+
+// 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) {
+ 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 {
+ t.Fatalf("%d rows", n)
+ }
+ r.drain()
+ r.enqueue(KindBadge, TargetDevice, "badge", "", true)
+ if n := len(r.rows()); n != 3 {
+ 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)
+ }
+}
+
+// TestRegisterValidates: hex tokens of a sane length, the two
+// environments and platforms, a start token only on iPhone; a new
+// registration replaces the device's.
+func TestRegisterValidates(t *testing.T) {
+ good := wire.RegisterPush{Token: devToken, Environment: wire.APNsProduction, Platform: wire.PlatformMacOS}
+ if Validate(good) != nil {
+ t.Fatal("good refused")
+ }
+ for name, mod := range map[string]func(*wire.RegisterPush){
+ "short": func(p *wire.RegisterPush) { p.Token = "abcd" },
+ "not hex": func(p *wire.RegisterPush) { p.Token = strings.Repeat("zz", 32) },
+ "long": func(p *wire.RegisterPush) { p.Token = strings.Repeat("a", wire.MaxPushToken+2) },
+ "environment": func(p *wire.RegisterPush) { p.Environment = "sandbox" },
+ "platform": func(p *wire.RegisterPush) { p.Platform = "watchos" },
+ "mac start": func(p *wire.RegisterPush) { p.StartToken = startToken },
+ "bad start": func(p *wire.RegisterPush) { p.Platform, p.StartToken = wire.PlatformIOS, "xyz" },
+ } {
+ p := good
+ mod(&p)
+ if Validate(p) == nil {
+ t.Errorf("%s accepted", name)
+ }
+ }
+ r := newRig(t)
+ r.must(r.d.G.Transaction(func(tx *gorm.DB) error {
+ out, err := Register(tx, "p@example.com", "cr1", good, at)
+ if out.LiveActivities || out.Platform != wire.PlatformMacOS {
+ t.Errorf("registration %+v", out)
+ }
+ return err
+ }))
+ var regs []Registration
+ r.must(r.d.G.Find(&regs).Error)
+ if len(regs) != 1 || regs[0].StartToken != "" || regs[0].Platform != wire.PlatformMacOS {
+ t.Fatalf("not replaced: %+v", regs)
+ }
+}
+
+// TestLoggedTransportKeepsTokensOut: the logged transport logs that a push
+// would go, never its token or payload.
+func TestLoggedTransportKeepsTokensOut(t *testing.T) {
+ var buf bytes.Buffer
+ l := Logged{Logger: slog.New(slog.NewTextHandler(&buf, nil))}
+ res, err := l.Send(context.Background(), Message{ID: "pu1", Token: devToken, Payload: []byte(`{"aps":{"alert":{"body":"Merge the login fix?"}}}`)})
+ 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") {
+ t.Fatalf("log %s", buf.String())
+ }
+}
+
+// TestCarlosSeam: CARLOS_PUSH unset is no transport; submit refuses until
+// the platform verb exists.
+func TestCarlosSeam(t *testing.T) {
+ if tr, err := FromCarlos(func(string) string { return "" }); tr != nil || err != nil {
+ t.Fatal("unset", tr, err)
+ }
+ if _, err := FromCarlos(func(k string) string { return map[string]string{CarlosPushEnv: "submit"}[k] }); !errors.Is(err, ErrCarlosPushUnavailable) {
+ t.Fatal("submit", err)
+ }
+}
diff --git a/internal/equipo/push/store.go b/internal/equipo/push/store.go
new file mode 100644
index 00000000..efd79715
--- /dev/null
+++ b/internal/equipo/push/store.go
@@ -0,0 +1,251 @@
+package push
+
+import (
+ "crypto/rand"
+ "errors"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+)
+
+// Models are the push tables, for the migration check (chat.Models
+// carries them).
+var Models = []any{&Registration{}, &ActivityToken{}, &OutboxRecord{}, &MemoryRecord{}}
+
+// Registration is a paired device's push registration, one per device
+// credential: a new one replaces it.
+type Registration struct {
+ Credential string `gorm:"primaryKey"`
+ Person string `gorm:"index:push_registration_person"`
+ Token string
+ Environment string
+ Platform string
+ StartToken string
+ CreatedAt time.Time
+ UpdatedAt time.Time
+}
+
+func (Registration) TableName() string { return "push_registrations" }
+
+// ActivityToken is a running Live Activity's own update token, on one
+// device, for one task.
+type ActivityToken struct {
+ Credential string `gorm:"primaryKey"`
+ TaskID string `gorm:"primaryKey"`
+ Person string `gorm:"index:push_activity_person"`
+ Token string
+ CreatedAt time.Time
+}
+
+func (ActivityToken) TableName() string { return "push_activities" }
+
+// Outbox row states.
+const (
+ StatePending = "pending"
+ StateSent = "sent"
+ StateFailed = "failed"
+ // StateDropped: never sent, because the device or person is gone or
+ // no token was ever on file.
+ StateDropped = "dropped"
+)
+
+// 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.
+type OutboxRecord struct {
+ ID string `gorm:"primaryKey"`
+ Person string `gorm:"index:push_outbox_person"`
+ Credential string `gorm:"index:push_outbox_credential"`
+ Kind string
+ Target string
+ TaskID string
+ PushType string
+ Priority int
+ CollapseID string
+ Dedupe string `gorm:"index:push_outbox_dedupe"`
+ Payload string
+ State string `gorm:"index:push_outbox_due,priority:1"`
+ NextAt time.Time `gorm:"index:push_outbox_due,priority:2"`
+ Attempts int
+ LeaseUntil *time.Time
+ // Apple's answer to the newest send.
+ Status int
+ Reason string
+ APNsID string `gorm:"column:apns_id"`
+ SentAt *time.Time
+ CreatedAt time.Time
+ UpdatedAt time.Time
+}
+
+func (OutboxRecord) TableName() string { return "push_outbox" }
+
+// MemoryRecord is what a person's devices were last told about a task
+// they started (Memory).
+type MemoryRecord struct {
+ Person string `gorm:"primaryKey"`
+ TaskID string `gorm:"primaryKey"`
+ Title string
+ Tone string
+ Stage string
+ NeedsYou string
+ Specialist string
+ StepID string
+ Activity string
+ StartedAt *time.Time
+ Ended bool
+ LineAt *time.Time
+ UpdatedAt time.Time
+}
+
+func (MemoryRecord) TableName() string { return "push_tasks" }
+
+// ErrInvalid is a registration the server refuses.
+var ErrInvalid = errors.New("push: invalid registration")
+
+func hexToken(s string) bool {
+ if len(s) < 32 || len(s) > wire.MaxPushToken || len(s)%2 != 0 {
+ return false
+ }
+ for _, r := range s {
+ if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'f' || r >= 'A' && r <= 'F') {
+ return false
+ }
+ }
+ return true
+}
+
+// Validate checks a registration: hex tokens, a known environment and
+// platform, and a push-to-start token only on iPhone.
+func Validate(in wire.RegisterPush) error {
+ if !hexToken(in.Token) || in.StartToken != "" && !hexToken(in.StartToken) {
+ return ErrInvalid
+ }
+ if in.Environment != wire.APNsProduction && in.Environment != wire.APNsDevelopment {
+ return ErrInvalid
+ }
+ if in.Platform != wire.PlatformIOS && in.Platform != wire.PlatformMacOS || in.Platform == wire.PlatformMacOS && in.StartToken != "" {
+ return ErrInvalid
+ }
+ 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) {
+ 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
+}
+
+// RegisterActivity keeps a running activity's update token.
+func RegisterActivity(tx *gorm.DB, 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}
+ return tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "credential"}, {Name: "task_id"}}, DoUpdates: clause.AssignmentColumns([]string{"person", "token", "created_at"})}).Create(&a).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.
+func ForgetCredential(tx *gorm.DB, credential string) error {
+ if err := tx.Where("credential = ?", credential).Delete(&Registration{}).Error; err != nil {
+ return err
+ }
+ if err := tx.Where("credential = ?", credential).Delete(&ActivityToken{}).Error; err != nil {
+ return err
+ }
+ return tx.Model(&OutboxRecord{}).Where("credential = ? AND state = ?", credential, StatePending).Select("state", "reason", "lease_until").Updates(map[string]any{"state": StateDropped, "reason": "forgotten", "lease_until": nil}).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{}} {
+ if err := tx.Where("person = ?", person).Delete(m).Error; err != nil {
+ return err
+ }
+ }
+ 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.
+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
+}
+
+// HasActivity reports whether a device has a running activity's token for
+// the task.
+func HasActivity(tx *gorm.DB, credential, task string) (bool, error) {
+ var n int64
+ err := tx.Model(&ActivityToken{}).Where("credential = ? AND task_id = ?", credential, task).Count(&n).Error
+ return n > 0, err
+}
+
+// LoadMemory is the person's memory of a task (Seen false when none).
+func LoadMemory(tx *gorm.DB, person, task string) (Memory, error) {
+ var r MemoryRecord
+ err := tx.Where("person = ? AND task_id = ?", person, task).Take(&r).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return Memory{}, nil
+ }
+ if err != nil {
+ return Memory{}, err
+ }
+ return Memory{Seen: true, Title: r.Title, Tone: r.Tone, Stage: r.Stage, NeedsYou: r.NeedsYou, Specialist: r.Specialist, StepID: r.StepID, Activity: r.Activity, Started: r.StartedAt, Ended: r.Ended, LineAt: r.LineAt}, nil
+}
+
+// SaveMemory records what the devices were told about a task.
+func SaveMemory(tx *gorm.DB, person, task string, m Memory, now time.Time) error {
+ r := MemoryRecord{Person: person, TaskID: task, Title: m.Title, Tone: m.Tone, Stage: m.Stage, NeedsYou: m.NeedsYou, Specialist: m.Specialist, StepID: m.StepID, Activity: m.Activity, StartedAt: m.Started, Ended: m.Ended, LineAt: m.LineAt, UpdatedAt: now}
+ return tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "person"}, {Name: "task_id"}}, DoUpdates: clause.AssignmentColumns([]string{"title", "tone", "stage", "needs_you", "specialist", "step_id", "activity", "started_at", "ended", "line_at", "updated_at"})}).Create(&r).Error
+}
+
+// LiveTasks are the tasks with a running Live Activity for the person,
+// oldest start first.
+func LiveTasks(tx *gorm.DB, person string) ([]MemoryRecord, error) {
+ var out []MemoryRecord
+ err := tx.Where("person = ? AND started_at IS NOT NULL AND ended = ?", person, false).Order("started_at, task_id").Find(&out).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
+ }
+ 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.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
+}
diff --git a/internal/equipo/push/testdata/activity-end.json b/internal/equipo/push/testdata/activity-end.json
new file mode 100644
index 00000000..f31a93d6
--- /dev/null
+++ b/internal/equipo/push/testdata/activity-end.json
@@ -0,0 +1,17 @@
+{
+ "aps": {
+ "timestamp": 1795176000,
+ "event": "end",
+ "content-state": {
+ "task_id": "tk1",
+ "title": "Fix login",
+ "stage": "done",
+ "specialist": "engineering",
+ "activity": "",
+ "needs_you": "",
+ "tone": "positive",
+ "outcome": "done"
+ },
+ "dismissal-date": 1795179600
+ }
+}
diff --git a/internal/equipo/push/testdata/activity-needs.json b/internal/equipo/push/testdata/activity-needs.json
new file mode 100644
index 00000000..51922596
--- /dev/null
+++ b/internal/equipo/push/testdata/activity-needs.json
@@ -0,0 +1,20 @@
+{
+ "aps": {
+ "alert": {
+ "title": "Fix login",
+ "body": "[push.activity.needs_you]"
+ },
+ "sound": "default",
+ "timestamp": 1795176000,
+ "event": "update",
+ "content-state": {
+ "task_id": "tk1",
+ "title": "Fix login",
+ "stage": "ready_to_merge",
+ "specialist": "engineering",
+ "activity": "",
+ "needs_you": "merge",
+ "tone": "warning"
+ }
+ }
+}
diff --git a/internal/equipo/push/testdata/activity-replaced.json b/internal/equipo/push/testdata/activity-replaced.json
new file mode 100644
index 00000000..e317cfde
--- /dev/null
+++ b/internal/equipo/push/testdata/activity-replaced.json
@@ -0,0 +1,17 @@
+{
+ "aps": {
+ "timestamp": 1795176000,
+ "event": "end",
+ "content-state": {
+ "task_id": "tk1",
+ "title": "Fix login",
+ "stage": "in_progress",
+ "specialist": "engineering",
+ "activity": "Reading README.md",
+ "needs_you": "",
+ "tone": "positive",
+ "outcome": "replaced"
+ },
+ "dismissal-date": 1795176000
+ }
+}
diff --git a/internal/equipo/push/testdata/activity-start.json b/internal/equipo/push/testdata/activity-start.json
new file mode 100644
index 00000000..30373829
--- /dev/null
+++ b/internal/equipo/push/testdata/activity-start.json
@@ -0,0 +1,24 @@
+{
+ "aps": {
+ "alert": {
+ "title": "Fix login",
+ "body": "[push.activity.started]"
+ },
+ "sound": "default",
+ "timestamp": 1795176000,
+ "event": "start",
+ "content-state": {
+ "task_id": "tk1",
+ "title": "Fix login",
+ "stage": "in_progress",
+ "specialist": "engineering",
+ "activity": "Reading README.md",
+ "needs_you": "",
+ "tone": "positive"
+ },
+ "attributes-type": "EquipoTaskAttributes",
+ "attributes": {
+ "task_id": "tk1"
+ }
+ }
+}
diff --git a/internal/equipo/push/testdata/activity-update.json b/internal/equipo/push/testdata/activity-update.json
new file mode 100644
index 00000000..2c53c274
--- /dev/null
+++ b/internal/equipo/push/testdata/activity-update.json
@@ -0,0 +1,15 @@
+{
+ "aps": {
+ "timestamp": 1795176000,
+ "event": "update",
+ "content-state": {
+ "task_id": "tk1",
+ "title": "Fix login",
+ "stage": "in_progress",
+ "specialist": "engineering",
+ "activity": "Reading README.md",
+ "needs_you": "",
+ "tone": "positive"
+ }
+ }
+}
diff --git a/internal/equipo/push/testdata/badge.json b/internal/equipo/push/testdata/badge.json
new file mode 100644
index 00000000..a20f01ab
--- /dev/null
+++ b/internal/equipo/push/testdata/badge.json
@@ -0,0 +1,5 @@
+{
+ "aps": {
+ "badge": 2
+ }
+}
diff --git a/internal/equipo/push/testdata/card.json b/internal/equipo/push/testdata/card.json
new file mode 100644
index 00000000..ec33e8df
--- /dev/null
+++ b/internal/equipo/push/testdata/card.json
@@ -0,0 +1,16 @@
+{
+ "aps": {
+ "alert": {
+ "title": "[push.card.title]",
+ "body": "Merge the login fix?"
+ },
+ "sound": "default",
+ "category": "needs_you",
+ "thread-id": "task:tk1"
+ },
+ "equipo": {
+ "kind": "card",
+ "card_id": "c1",
+ "task_id": "tk1"
+ }
+}
diff --git a/internal/equipo/push/testdata/reply.json b/internal/equipo/push/testdata/reply.json
new file mode 100644
index 00000000..6e416f51
--- /dev/null
+++ b/internal/equipo/push/testdata/reply.json
@@ -0,0 +1,13 @@
+{
+ "aps": {
+ "alert": {
+ "title": "[push.reply.title]",
+ "body": "Done. The fix is on its branch."
+ },
+ "sound": "default"
+ },
+ "equipo": {
+ "kind": "reply",
+ "turn_id": "t1"
+ }
+}
diff --git a/internal/equipo/push/testdata/task-done.json b/internal/equipo/push/testdata/task-done.json
new file mode 100644
index 00000000..c7d93c99
--- /dev/null
+++ b/internal/equipo/push/testdata/task-done.json
@@ -0,0 +1,14 @@
+{
+ "aps": {
+ "alert": {
+ "title": "Fix login",
+ "body": "[push.task.done]"
+ },
+ "thread-id": "task:tk1",
+ "interruption-level": "passive"
+ },
+ "equipo": {
+ "kind": "task",
+ "task_id": "tk1"
+ }
+}
diff --git a/internal/equipo/push/testdata/task-failed.json b/internal/equipo/push/testdata/task-failed.json
new file mode 100644
index 00000000..d2131e6b
--- /dev/null
+++ b/internal/equipo/push/testdata/task-failed.json
@@ -0,0 +1,14 @@
+{
+ "aps": {
+ "alert": {
+ "title": "Fix login",
+ "body": "[push.task.failed]"
+ },
+ "thread-id": "task:tk1",
+ "interruption-level": "passive"
+ },
+ "equipo": {
+ "kind": "task",
+ "task_id": "tk1"
+ }
+}
diff --git a/internal/equipo/push/transport.go b/internal/equipo/push/transport.go
new file mode 100644
index 00000000..b05636a7
--- /dev/null
+++ b/internal/equipo/push/transport.go
@@ -0,0 +1,60 @@
+package push
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "log/slog"
+)
+
+// 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.
+type Logged struct {
+ Logger *slog.Logger
+ // Sent sees each message (tests and the local drive); nil is none.
+ Sent func(Message)
+}
+
+// Send logs the push and answers as Apple would to a delivered one.
+func (l Logged) Send(_ context.Context, m Message) (Result, error) {
+ if l.Sent != nil {
+ 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))
+ }
+ return Result{Status: 200, APNsID: m.ID}, nil
+}
+
+// CarlosPushEnv is set to "submit" by the CARLOS agent when the platform
+// sends this instance's pushes (D1: the Apple key stays on the CARLOS box).
+const CarlosPushEnv = "CARLOS_PUSH"
+
+// ErrCarlosPushUnavailable refuses boot when CARLOS_PUSH=submit asks for a
+// 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).
+//
+// 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.
+func FromCarlos(getenv func(string) string) (Transport, error) {
+ if getenv(CarlosPushEnv) != "submit" {
+ return nil, nil
+ }
+ return nil, ErrCarlosPushUnavailable
+}
diff --git a/internal/equipo/push_config_test.go b/internal/equipo/push_config_test.go
new file mode 100644
index 00000000..921d0026
--- /dev/null
+++ b/internal/equipo/push_config_test.go
@@ -0,0 +1,47 @@
+package equipo
+
+import (
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo/push"
+)
+
+// TestLoggedPushBoundary: logged push, like logged mail, only on loopback
+// or a staging origin, refused at LoadConfig and again by Pusher.
+func TestLoggedPushBoundary(t *testing.T) {
+ for origin, allowed := range map[string]bool{
+ "http://127.0.0.1:4321": true,
+ "https://equipo-staging-0123456789abcdef.bds.oncarlos.com": true,
+ "https://equipo.bds.oncarlos.com": false,
+ "https://equipo-staging-0123456789abcdef.bds.oncarlos.com.evil.test": false,
+ } {
+ env := map[string]string{"EQUIPO_ORIGIN": origin, "EQUIPO_INSTANCE_KEY": "k", "CARLOS_MAIL": "submit", "EQUIPO_ALLOW_LOGGED_PUSH": "1"}
+ cfg, err := LoadConfig(func(k string) string { return env[k] })
+ if (err == nil) != allowed {
+ t.Fatalf("%s: allowed=%v error=%v", origin, allowed, err)
+ }
+ if _, err := Pusher(Config{Origin: origin, InstanceKey: "k", AllowLoggedPush: true}, nil, func(string) string { return "" }); (err == nil) != allowed {
+ t.Fatalf("%s: Pusher allowed=%v error=%v", origin, allowed, err)
+ }
+ if allowed {
+ if tr, err := Pusher(cfg, nil, func(string) string { return "" }); err != nil || tr == nil {
+ t.Fatalf("%s: no logged transport %v", origin, err)
+ } else if _, ok := tr.(push.Logged); !ok {
+ t.Fatalf("%s: %T", origin, tr)
+ }
+ }
+ }
+}
+
+// TestPusherChannels: no push setting is no push at all; CARLOS_PUSH=submit
+// refuses until the platform's push submission exists (the seam).
+func TestPusherChannels(t *testing.T) {
+ cfg := Config{Origin: "https://equipo.bds.oncarlos.com", InstanceKey: "k"}
+ if tr, err := Pusher(cfg, nil, func(string) string { return "" }); tr != nil || err != nil {
+ t.Fatalf("unset: %v %v", tr, err)
+ }
+ _, err := Pusher(cfg, nil, func(k string) string { return map[string]string{push.CarlosPushEnv: "submit"}[k] })
+ if err == nil || err.Error() != copyCarlosPushUnavailable {
+ t.Fatalf("submit: %v", err)
+ }
+}
diff --git a/internal/equipo/setup/invites.go b/internal/equipo/setup/invites.go
index 213c4ebc..e6bc8c7d 100644
--- a/internal/equipo/setup/invites.go
+++ b/internal/equipo/setup/invites.go
@@ -59,6 +59,10 @@ type Dependencies struct {
Member func(*gorm.DB, string) (kernel.Member, error)
Audit func(*gorm.DB, kernel.Actor, string, string) error
Invalid, Forbidden, NotFound, Conflict, Unavailable, Expired error
+
+ // ForgetPush deletes a removed person's push registrations; nil is
+ // none to forget.
+ ForgetPush func(*gorm.DB, string) error
}
type Store struct {
tx *gorm.DB
diff --git a/internal/equipo/setup/roster.go b/internal/equipo/setup/roster.go
index 4fa232bf..11373295 100644
--- a/internal/equipo/setup/roster.go
+++ b/internal/equipo/setup/roster.go
@@ -123,6 +123,11 @@ func (s *Store) SetMember(actor Actor, address string, role Role, active bool, r
if err := s.deps.RevokeRunners(tx, address); err != nil {
return err
}
+ if s.deps.ForgetPush != nil {
+ if err := s.deps.ForgetPush(tx, address); err != nil {
+ return err
+ }
+ }
if err := tx.Exec("DELETE FROM sessions WHERE subject = ?", address).Error; err != nil {
return err
}
diff --git a/internal/plan3test/plan3_release_test.go b/internal/plan3test/plan3_release_test.go
index 2b00d9ce..f83b4241 100644
--- a/internal/plan3test/plan3_release_test.go
+++ b/internal/plan3test/plan3_release_test.go
@@ -187,8 +187,11 @@ func plan3CopyInventory(t *testing.T) {
// Luna's delegated pass on the boot refusal for CARLOS mail submission.
acceptedInjection := slices.Contains([]string{"autonomy.title", "autonomy.lede", "autonomy.auto_merge_ci", "autonomy.auto_merge_ci_help", "autonomy.public_previews", "autonomy.public_previews_help", "autonomy.empty", "work.reason.base_checks_failed", "chat.merge.not.base_failed", "chat.merge.not.base_checks", "chat.merge.not.gates", "chat.merge.not.review_truncated", "work.reason.base_gate_unavailable", "work.reason.preview_secrets", "work.reason.preview_scanner", "work.reason.preview_public_disabled", "work.reason.preview_host", "work.reason.preview_headers", "autonomy.auto_merge_sensitive", "autonomy.auto_merge_sensitive_help", "work.reason.preview_header_missing", "preview.unsafe_question", "preview.unsafe_help", "preview.unsafe_open", "preview.wrapper_title"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-19)")
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)")
acceptedCopy := strings.TrimSuffix(cells[3], " |") == "COPY ACCEPTED BY DELEGATION (Copy, record-bound) sha256:"+copydesk.Hash(rows[key])
- if !acceptedInjection && !acceptedMail && !acceptedAccess && !acceptedPlacementEdges && !acceptedPlacement && !acceptedReportActions && !acceptedRoster && !acceptedCopy && !strings.Contains(cells[3], "COPY REVIEW REQUIRED") && !acceptedAll && !acceptedGuide && !acceptedRound2 && !acceptedStarter && !acceptedDelegation && !approvedPublish && !approvedAssistant && !approvedJobs && !approvedOficina {
+ 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
new file mode 100644
index 00000000..a3908b2d
--- /dev/null
+++ b/internal/plan3test/push_device_test.go
@@ -0,0 +1,70 @@
+package plan3test
+
+import (
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/equipo/push"
+ "gorm.io/gorm"
+)
+
+const pushToken = "aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11"
+
+func registerPush(t *testing.T, f *fixture, token string) {
+ t.Helper()
+ w := deviceRequest(t, f, token, "POST", "/api/v1/push-registrations", `{"token":"`+pushToken+`","environment":"production","platform":"ios","start_token":"`+strings.ToUpper(pushToken)+`"}`, "push", "")
+ expectHTTP(t, w, 200)
+ if strings.Contains(strings.ToLower(w.Body.String()), pushToken) || !strings.Contains(w.Body.String(), `"live_activities":true`) {
+ t.Fatal("registration answer", w.Body.String())
+ }
+}
+
+// pushCurrent is the sender's own check of a device: nil while it may be
+// pushed to.
+func pushCurrent(t *testing.T, f *fixture, credential string) error {
+ t.Helper()
+ s := f.Store.Chat().PushSender(push.Logged{})
+ var out error
+ must(t, f.DB.G.Transaction(func(tx *gorm.DB) error { out = s.Check(tx, owner.Address, credential); return nil }))
+ return out
+}
+
+// TestPushRegistrationLifetime: a paired device registers with its own
+// bearer (a browser session cannot); the registration is the
+// credential's, never audited with its tokens, and it goes when the
+// device is revoked or its person is removed, after which the sender's
+// check refuses the device.
+func TestPushRegistrationLifetime(t *testing.T) {
+ f := newFixture(t)
+ cred := approvedDevice(t, f)
+ expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/push-registrations", `{"token":"`+pushToken+`","environment":"production","platform":"ios"}`, "browser", ""), 401)
+ registerPush(t, f, cred.Token)
+ registerPush(t, f, cred.Token)
+ if f.count(t, "SELECT count(*) FROM push_registrations WHERE credential = ? AND person = ?", cred.ID, owner.Address) != 1 {
+ t.Fatal("not one registration for the device")
+ }
+ if f.count(t, "SELECT count(*) FROM audit_events WHERE kind = 'push.register' AND record_id = ?", cred.ID) != 2 || f.count(t, "SELECT count(*) FROM audit_events WHERE lower(record_id) LIKE ? OR lower(kind) LIKE ?", "%"+pushToken+"%", "%"+pushToken+"%") != 0 {
+ t.Fatal("registration audit")
+ }
+ if err := pushCurrent(t, f, cred.ID); err != nil {
+ t.Fatal("a current device refused", err)
+ }
+ 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")
+ }
+
+ second := approvedDevice(t, f)
+ registerPush(t, f, second.Token)
+ must(t, f.Store.SetMember(ctx, peer, owner.Address, equipo.RoleMember, false, 1))
+ 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")
+ }
+}
diff --git a/internal/wire/api.go b/internal/wire/api.go
index 2195f0e0..5d60196f 100644
--- a/internal/wire/api.go
+++ b/internal/wire/api.go
@@ -380,6 +380,9 @@ type Card struct {
Site *CardSite `json:"site,omitempty"`
// Advice is an advice card's advice; absent on every other card.
Advice *Advice `json:"advice,omitempty"`
+ // Aside: the person set the card aside (POST /cards/{id}/visibility).
+ // It still waits on them and stays in Needs you; absent when not.
+ Aside bool `json:"aside,omitempty"`
}
// AnswerCard is the body of POST /api/v1/cards/{id}/answer. Revision must
diff --git a/internal/wire/push.go b/internal/wire/push.go
new file mode 100644
index 00000000..5fb64e64
--- /dev/null
+++ b/internal/wire/push.go
@@ -0,0 +1,128 @@
+package wire
+
+import "time"
+
+// Push (native slice 2, plan 2026-11-20-equipo-native-slice-2.md): a
+// paired device registers its APNs token; the engine writes pushes to an
+// outbox in the transaction of the change; a sender delivers them.
+
+// Push environments: the APNs gateway a token belongs to.
+const (
+ APNsProduction = "production"
+ APNsDevelopment = "development"
+)
+
+// Device platforms. Only iOS starts Live Activities (macOS shows the
+// iPhone's in its menu bar).
+const (
+ PlatformIOS = "ios"
+ PlatformMacOS = "macos"
+)
+
+// MaxPushToken bounds an APNs token in hex: Apple's are 32 bytes today
+// and may grow.
+const MaxPushToken = 400
+
+// RegisterPush is the body of POST /api/v1/push-registrations: the
+// device's APNs token, its environment and platform, and on iPhone the
+// Live Activity push-to-start token. It is bound to the paired device
+// credential that sends it and replaces that credential's earlier one.
+type RegisterPush struct {
+ Token string `json:"token"`
+ Environment string `json:"environment"`
+ Platform string `json:"platform"`
+ StartToken string `json:"start_token,omitempty"`
+}
+
+// PushRegistration is what the server keeps for the device, without its
+// tokens (which are never echoed). LiveActivities is whether a
+// push-to-start token is on file.
+type PushRegistration struct {
+ Environment string `json:"environment"`
+ Platform string `json:"platform"`
+ LiveActivities bool `json:"live_activities"`
+ UpdatedAt time.Time `json:"updated_at"`
+}
+
+// RegisterActivity is the body of POST
+// /api/v1/push-registrations/activities: a running Live Activity's own
+// update token, for the task it follows. The server forgets it when the
+// activity ends.
+type RegisterActivity struct {
+ TaskID string `json:"task_id"`
+ Token string `json:"token"`
+}
+
+// LiveActivityAttributesType is the app's ActivityAttributes type, named in a
+// push-to-start payload ("attributes-type").
+const LiveActivityAttributesType = "EquipoTaskAttributes"
+
+// LiveActivityAttributes are a task Live Activity's fixed attributes.
+type LiveActivityAttributes struct {
+ TaskID string `json:"task_id"`
+}
+
+// Live Activity tones, as Roster's stage track: amber waits on you, red
+// only for a failure.
+const (
+ TonePositive = "positive"
+ ToneWarning = "warning"
+ ToneNegative = "negative"
+)
+
+// Live Activity and task outcomes.
+const (
+ PushOutcomeDone = "done"
+ PushOutcomeCancelled = "cancelled"
+ PushOutcomeFailed = "failed"
+ // PushOutcomeReplaced ends an activity to make room for a newer
+ // task's (at most MaxLiveActivities a person).
+ PushOutcomeReplaced = "replaced"
+)
+
+// MaxLiveActivities is how many task Live Activities a person has at
+// once: the most recently started tasks'.
+const MaxLiveActivities = 3
+
+// LiveActivityState is a task Live Activity's content state, the app's
+// Codable ContentState: the task, its stage (Task.stage), the specialist
+// working on it (Step.specialist), the newest activity line, what it
+// needs from you (Task.needs_you, "" when nothing), the tone, and once it
+// ended, the outcome.
+type LiveActivityState struct {
+ TaskID string `json:"task_id"`
+ Title string `json:"title"`
+ Stage string `json:"stage"`
+ Specialist string `json:"specialist"`
+ Activity string `json:"activity"`
+ NeedsYou string `json:"needs_you"`
+ Tone string `json:"tone"`
+ Outcome string `json:"outcome,omitempty"`
+}
+
+// PushData is what an alert carries beside aps, under "equipo", for the
+// app to open the right place when it is tapped: a card, a task, or the
+// conversation (a reply).
+type PushData struct {
+ Kind string `json:"kind"`
+ CardID string `json:"card_id,omitempty"`
+ TaskID string `json:"task_id,omitempty"`
+ TurnID string `json:"turn_id,omitempty"`
+}
+
+// PushData kinds.
+const (
+ PushCard = "card"
+ PushReply = "reply"
+ PushTask = "task"
+ PushBadge = "badge"
+)
+
+// SetCardVisibility is the body of POST /api/v1/cards/{id}/visibility:
+// set the card aside (or bring it back) for the person, at the card's
+// current revision. It never answers, cancels or starts anything; the
+// card stays in Needs you.
+type SetCardVisibility struct {
+ Aside bool `json:"aside"`
+ Revision int64 `json:"revision"`
+}
diff --git a/internal/wire/wireschema/wireschema.go b/internal/wire/wireschema/wireschema.go
index bbd6712d..920fc4be 100644
--- a/internal/wire/wireschema/wireschema.go
+++ b/internal/wire/wireschema/wireschema.go
@@ -107,7 +107,13 @@ var Ops = map[string]Op{
"GET /advice": {nil, map[string]any{"200": wire.AdviceList{}}},
"POST /advice/{id}/act": {wire.AdviceAction{}, map[string]any{"200": wire.Advice{}}},
"POST /advice/{id}/dismiss": {wire.AdviceAction{}, map[string]any{"200": wire.Advice{}}},
- "GET /events": {nil, map[string]any{"200": wire.Event{}}},
+
+ // Push and set aside (native slice 2).
+ "POST /cards/{id}/visibility": {wire.SetCardVisibility{}, map[string]any{"200": wire.Card{}, "409": wire.CardConflict{}}},
+ "POST /push-registrations": {wire.RegisterPush{}, map[string]any{"200": wire.PushRegistration{}}},
+ "POST /push-registrations/activities": {wire.RegisterActivity{}, map[string]any{"204": nil}},
+
+ "GET /events": {nil, map[string]any{"200": wire.Event{}}},
}
// EventData is what each kind of event on GET /events carries in
@@ -167,8 +173,14 @@ var Enums = map[string][]string{
"UsageTotals.by": wire.UsageGroupings,
"CardConflict.code": {"card_stale", "card_answered"},
"ActionConflict.code": {"not_undoable"},
- "Event.type": eventKeys(0),
- "Event.resource": eventKeys(1),
+
+ "RegisterPush.environment": {wire.APNsProduction, wire.APNsDevelopment},
+ "RegisterPush.platform": {wire.PlatformIOS, wire.PlatformMacOS},
+ "PushRegistration.environment": {wire.APNsProduction, wire.APNsDevelopment},
+ "PushRegistration.platform": {wire.PlatformIOS, wire.PlatformMacOS},
+
+ "Event.type": eventKeys(0),
+ "Event.resource": eventKeys(1),
}
// eventKeys are the event types (part 0) or resources (part 1)
diff --git a/internal/wire/wireschema/wireschema_test.go b/internal/wire/wireschema/wireschema_test.go
index 425731f2..a88f818b 100644
--- a/internal/wire/wireschema/wireschema_test.go
+++ b/internal/wire/wireschema/wireschema_test.go
@@ -159,6 +159,11 @@ var families = map[string]struct{ prefix, other, zero string }{
"UsageTotals.period": {"Usage", "UsageByConnection UsageByRole UsageByProject UsageByTask UsageByModel UsageProbe", ""}, // probe: a usage row's role
"UsageTotals.by": {"UsageBy", "", ""},
"Event.type": {"Event", "EventPing EventGlance", ""}, // a ping is not an Event; a glance is the Assistant's
+
+ "RegisterPush.environment": {"APNs", "", ""},
+ "RegisterPush.platform": {"Platform", "", ""},
+ "PushRegistration.environment": {"APNs", "", ""},
+ "PushRegistration.platform": {"Platform", "", ""},
}
// parseGo parses the Go files in dir, tests apart.