oficina / equipo Public

Add bounded per-file diffs to native task views

Paul Campbell pushed by claude agent, operated by paul@keymail.dev 58c9c21354f901a0b154692b04a28af2e1e705fb parent edacd40
54 files changed, +2,168 −53
  • .rastrillo/budgets.txt +6 −4
  • docs/api/equipo-v1.openapi.json +154 −13
  • docs/superpowers/plans/2026-11-26-changes-diff.md +20 −2
  • docs/superpowers/plans/CONTROLLER-REPORT-changes-diff.md +172 −0
  • go.mod +2 −2
  • internal/diffscan/scan.go +85 −0
  • internal/diffscan/scan_test.go +32 −0
  • internal/equipo/chat/change_diffs.go +291 −0
  • internal/equipo/chat/change_diffs_test.go +303 −0
  • internal/equipo/chat/http.go +1 −0
  • internal/equipo/chat/models.go +1 −1
  • internal/equipo/chat/runner.go +2 −0
  • internal/equipo/chat/store.go +3 −0
  • internal/equipo/chat/stream.go +1 −1
  • internal/equipo/chat/tasks.go +13 −5
  • internal/equipo/migrations/0111_change_diffs.sql +12 −0
  • internal/equipo/migrations/schema.sql +12 −0
  • internal/runner/thin/change_diffs.go +197 −0
  • internal/runner/thin/change_diffs_test.go +151 −0
  • internal/runner/thin/change_files_test.go +1 −0
  • internal/runner/thin/engineer.go +3 −0
  • internal/runner/thin/run.go +1 −1
  • internal/thintest/change_diffs_contract_test.go +64 −0
  • internal/wire/assistant_test.go +1 −1
  • internal/wire/change_diffs.go +82 −0
  • internal/wire/change_diffs_test.go +80 −0
  • internal/wire/change_files_test.go +1 −1
  • internal/wire/frames.go +3 −1
  • internal/wire/injection_test.go +1 −1
  • internal/wire/mixed_protocol_test.go +1 −1
  • internal/wire/models_test.go +1 −1
  • internal/wire/opencode_test.go +1 −1
  • internal/wire/pinned_release_test.go +1 −1
  • internal/wire/publish_test.go +1 −1
  • internal/wire/runners.go +16 −2
  • internal/wire/runners_test.go +1 −1
  • internal/wire/schedule_test.go +1 −1
  • internal/wire/stuck_test.go +1 −1
  • internal/wire/tasks.go +1 −0
  • internal/wire/usage_test.go +1 −1
  • internal/wire/warm_test.go +1 −1
  • internal/wire/wireschema/wireschema.go +8 −0
  • native/apple/Sources/EquipoActivity/Resources/Localizable.xcstrings +60 −0
  • native/apple/Sources/EquipoKit/API/ChangeDiff.swift +60 −0
  • native/apple/Sources/EquipoKit/Presentation/ChangeDiffModel.swift +34 −0
  • native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings +60 −0
  • native/apple/Sources/EquipoKit/UI/Screens/ChangeDiffSheet.swift +112 −0
  • native/apple/Sources/EquipoKit/UI/Screens/ChangedFilesList.swift +1 −1
  • native/apple/Sources/EquipoKit/UI/Screens/TaskDetailScreen.swift +12 −3
  • native/apple/Sources/EquipoKit/UI/TaskViewFixture.swift +8 −2
  • native/apple/Tests/EquipoKitTests/ChangeDiffTests.swift +72 −0
  • native/ios/UITests/TaskViewUITests.swift +12 −0
  • native/scripts/check-strings.py +1 −1
  • native/scripts/strings.json +6 −1

CI failed — 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/changes__diff: Type  Size Avail | ext4   96G   85G
ci-box: disk /home/ci/.cache/equipo-ci-box: Type  Size Avail | ext4   96G   85G
ci-box: bwrap: fetched and verified in 0.4s
ci-box: claude: fetched and verified in 2.3s
ci-box: codex: fetched and verified in 4.5s
ci-box: codex-code-mode-host: fetched and verified in 1.6s
ci-box: libwrap: fetched and verified in 0.4s
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.5s
ci-box: pi: installed and verified in 7.2s
ci-box: opencode: installed and verified in 2.3s
ci-box: chromium 156.0.8078.79-1~deb13u1: 76 packages fetched, verified and unpacked in 9.3s
ci-box: clone deepened in 4.4s
ci-box: file times set from content: 3130 files, 201 directories
ci-box: ready in 19.1s
=== 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.147s
=== compile ===
go build ./...
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py compile
+ go build -tags testbuild ./...
  4.3s
+ go list -export -test -tags testbuild -f  ./...
  4.8s
+ go list -export -test -tags browser,testbuild -f  ./internal/equipo ./internal/headless ./internal/idtest ./internal/plan3test ./internal/thintest
  3.2s
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-24 15:56:00 +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 1m18.607s 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 1m16.895s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m16.9s amadan.net/oficina/equipo/internal/headless TestHeadless
machine: 32 CPUs, load 75.49, cpu waiting 41.75%, memory waiting 0.00%, io waiting 0.81%
--- 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 1m19.405s 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 1m17.427s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m17.43s amadan.net/oficina/equipo/internal/headless TestHeadless
machine: 32 CPUs, load 75.49, cpu waiting 41.75%, memory waiting 0.00%, io waiting 0.81%
--- 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 1m20.759s 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 1m18.745s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m8.93s amadan.net/oficina/equipo/internal/headless TestHeadlessConnections
receipt: slow test 5.17s amadan.net/oficina/equipo/internal/headless TestHeadlessTokenPasteEndToEnd
receipt: slow test 4.64s amadan.net/oficina/equipo/internal/headless TestHeadlessTokenConnection
machine: 32 CPUs, load 71.77, cpu waiting 41.43%, memory waiting 0.00%, io waiting 0.79%
--- 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 1m17.935s 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 1m15.926s amadan.net/oficina/equipo/internal/headless
receipt: slow test 38.5s amadan.net/oficina/equipo/internal/headless TestMacWorker
receipt: slow test 19.32s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 9.08s amadan.net/oficina/equipo/internal/headless TestHeadlessPrewarm
receipt: slow test 9.02s amadan.net/oficina/equipo/internal/headless TestHeadlessAttachments
machine: 32 CPUs, load 75.49, cpu waiting 41.50%, memory waiting 0.00%, io waiting 0.84%
--- 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_step_refused$|^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 1m35.827s 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 1m33.869s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m4.25s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 9.23s amadan.net/oficina/equipo/internal/headless TestHeadlessRunnerKillLeavesNoCopies
receipt: slow test 8.15s amadan.net/oficina/equipo/internal/headless TestHeadlessCopyRotation
receipt: slow test 7.28s amadan.net/oficina/equipo/internal/headless TestHeadlessPolicyGuards
receipt: slow test 4.96s amadan.net/oficina/equipo/internal/headless TestHeadlessNewHouseRuleStartsFresh
machine: 32 CPUs, load 66.83, cpu waiting 40.67%, memory waiting 0.00%, io waiting 0.62%
--- 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_step_refused$|^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 2m57.532s 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 2m55.715s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m39.18s amadan.net/oficina/equipo/internal/headless TestHeadlessAssistant
receipt: slow test 19.17s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 18.05s amadan.net/oficina/equipo/internal/headless TestHeadlessResearchHandoff
receipt: slow test 6.68s amadan.net/oficina/equipo/internal/headless TestHeadlessTurnBatching
receipt: slow test 6.62s amadan.net/oficina/equipo/internal/headless TestHeadlessBatchAfterRefusedReply
machine: 32 CPUs, load 21.91, cpu waiting 10.97%, memory waiting 0.00%, io waiting 0.14%
--- 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 2m14.523s 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 2m12.238s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 9.75s amadan.net/oficina/equipo/internal/thintest TestContractTeamJobSettledStates
receipt: slow test 6.77s amadan.net/oficina/equipo/internal/thintest TestExplorePreviewsOff
receipt: slow test 3.99s amadan.net/oficina/equipo/internal/thintest TestContractPreviewHeldUntilPublishAnswer
receipt: slow test 3.98s amadan.net/oficina/equipo/internal/thintest TestContractTeamNudgePersonNeeds
receipt: slow test 3.63s amadan.net/oficina/equipo/internal/thintest TestContractTeamUpdatePersonNeeds
machine: 32 CPUs, load 42.08, cpu waiting 23.58%, memory waiting 0.00%, io waiting 0.32%
--- 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
--- FAIL amadan.net/oficina/equipo/internal/thintest TestContractChecksPlacedOnTheWorker
=== RUN   TestContractChecksPlacedOnTheWorker
    placement_contract_test.go:338: failed to get reader: context deadline exceeded
--- FAIL: TestContractChecksPlacedOnTheWorker (45.47s)

--- FAIL amadan.net/oficina/equipo/internal/thintest (package output)
FAIL
rastrillo-budget/v1 ran 2m21.198s
FAIL	amadan.net/oficina/equipo/internal/thintest	141.481s


receipt: test step 2m23.579s 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 2m21.198s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 45.47s amadan.net/oficina/equipo/internal/thintest TestContractChecksPlacedOnTheWorker
receipt: slow test 8.91s amadan.net/oficina/equipo/internal/thintest TestContractPreviewNotScheduled
receipt: slow test 4.83s amadan.net/oficina/equipo/internal/thintest TestContractPublishNotOffered
receipt: slow test 4.52s amadan.net/oficina/equipo/internal/thintest TestContractMacRecheckMergeAuthority
receipt: slow test 2.97s amadan.net/oficina/equipo/internal/thintest TestContractPausedJob
rastrillo: budget test: go test failed
exit status 1
+ go 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)' -v -run '^TestContractChecksPlacedOnTheWorker$' -count=1 ./internal/thintest   (retry, once)
##############################################################################
FLAKE ./internal/thintest:TestContractChecksPlacedOnTheWorker thintest-contract 58c9c21354f901a0b154692b04a28af2e1e705fb 45.47s 36.52
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 33.84, cpu waiting 19.31%, memory waiting 0.00%, io waiting 0.26%
--- 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 4m47.056s, over the 45s its record on line 44 allows; reported only, timing fails on CI

receipt: test step 4m52.54s 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 4m47.056s amadan.net/oficina/equipo/internal/runner/thin
receipt: slow test 37.03s 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.9s amadan.net/oficina/equipo/internal/runner/thin TestOpenCodeStepsRealOpenCode
machine: 32 CPUs, load 4.21, cpu waiting 1.64%, 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 51.208s 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.153s amadan.net/oficina/equipo/internal/runner
receipt: slow test 30.12s amadan.net/oficina/equipo/internal/runner TestDirectBugWorkflow
receipt: slow test 20.03s amadan.net/oficina/equipo/internal/runner TestEnrolKeepsTheRole
machine: 32 CPUs, load 69.09, cpu waiting 34.35%, memory waiting 0.00%, io waiting 1.30%
--- 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 1m3.005s 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 1m1.773s amadan.net/oficina/equipo/internal/runner
receipt: slow test 51.74s amadan.net/oficina/equipo/internal/runner TestPlanWorkflowCandidateOrder
receipt: slow test 47.63s amadan.net/oficina/equipo/internal/runner TestPlanWorkflowFeature
receipt: slow test 8.43s amadan.net/oficina/equipo/internal/runner TestCoordinatorRecoveryCallRefusalKeepsServing
receipt: slow test 1.59s amadan.net/oficina/equipo/internal/runner TestCoordinatorRefusalMatrix
machine: 32 CPUs, load 75.71, cpu waiting 40.53%, memory waiting 0.00%, io waiting 1.06%
--- 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 36.559s 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 35.681s amadan.net/oficina/equipo/internal/runner
receipt: slow test 5.13s amadan.net/oficina/equipo/internal/runner TestDirectFaultIsolation
receipt: slow test 3.38s amadan.net/oficina/equipo/internal/runner TestClaimRefusalsBackOff
receipt: slow test 3.13s amadan.net/oficina/equipo/internal/runner TestCoordinatorRecoveryRefusedKeepsServing
receipt: slow test 3.12s amadan.net/oficina/equipo/internal/runner TestToolVerbUnderFakeHarness
receipt: slow test 1.61s amadan.net/oficina/equipo/internal/runner TestReportPostsRetryExactRequest
machine: 32 CPUs, load 45.40, cpu waiting 22.67%, memory waiting 0.00%, io waiting 1.65%
--- 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 40.5%, load 31.41
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 1m9.361s 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 1m7.271s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 28.67s amadan.net/oficina/equipo/internal/equipotest TestAuthorityCoreIntegration
receipt: slow test 28.64s amadan.net/oficina/equipo/internal/equipotest TestBootstrapNamesOwnersSetting
receipt: slow test 26.34s amadan.net/oficina/equipo/internal/equipotest TestAccountLabelMigration
receipt: slow test 23.68s amadan.net/oficina/equipo/internal/equipotest TestBudgetConfigurationFailuresAreAtomic
receipt: slow test 23.19s amadan.net/oficina/equipo/internal/equipotest TestAuthoritySnapshotChanges
machine: 32 CPUs, load 66.83, cpu waiting 39.46%, memory waiting 0.00%, io waiting 0.58%
--- 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 40.5%, load 31.41
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 1m18.336s 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 1m16.325s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 20.06s amadan.net/oficina/equipo/internal/equipotest TestProjectKindsAndDefaultBranch
receipt: slow test 20.05s amadan.net/oficina/equipo/internal/equipotest TestProjectConcurrentRetry
receipt: slow test 20.03s amadan.net/oficina/equipo/internal/equipotest TestProjectWritesRequireCurrentOwner
receipt: slow test 20.03s amadan.net/oficina/equipo/internal/equipotest TestProjectRequestActorAndUpdate
receipt: slow test 20.01s amadan.net/oficina/equipo/internal/equipotest TestProjectsFailuresRollBack
machine: 32 CPUs, load 59.25, cpu waiting 35.40%, memory waiting 0.00%, io waiting 0.51%
--- 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 40.5%, load 31.41
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 1m15.902s 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 1m10.358s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 15.73s amadan.net/oficina/equipo/internal/equipotest TestReleaseStampContract
receipt: slow test 13.36s amadan.net/oficina/equipo/internal/equipotest TestRosterChangesAffectExistingSession
receipt: slow test 10.45s amadan.net/oficina/equipo/internal/equipotest TestRosterRemovalWhileAssigned
receipt: slow test 10.34s amadan.net/oficina/equipo/internal/equipotest TestRosterRemovalRollsBack
receipt: slow test 7.36s amadan.net/oficina/equipo/internal/equipotest TestRosterBootstrapOnce
machine: 32 CPUs, load 59.25, cpu waiting 36.46%, memory waiting 0.00%, io waiting 0.52%
--- 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 40.5%, load 31.41
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 1m9.231s 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 1m7.415s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 26.17s amadan.net/oficina/equipo/internal/equipotest TestSigninNoProof
receipt: slow test 25.21s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedExistingTeam
receipt: slow test 25.18s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedRollback
receipt: slow test 23.21s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsUpgrade
receipt: slow test 23.19s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedAuditRollback
machine: 32 CPUs, load 66.83, cpu waiting 39.46%, memory waiting 0.00%, io waiting 0.58%
--- 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 41.9%, load 31.41
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 55.219s 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 52.964s amadan.net/oficina/equipo/internal/plan3test
receipt: slow test 3.79s amadan.net/oficina/equipo/internal/plan3test TestPlan3Upgrade
receipt: slow test 3.52s amadan.net/oficina/equipo/internal/plan3test TestCoordinatorAcceptance3B
receipt: slow test 1.7s amadan.net/oficina/equipo/internal/plan3test TestCoordinatorAcceptance3A
receipt: slow test 1.66s amadan.net/oficina/equipo/internal/plan3test TestConversationQuestionRace
receipt: slow test 1.29s amadan.net/oficina/equipo/internal/plan3test TestInviteMigration
machine: 32 CPUs, load 68.74, cpu waiting 40.78%, memory waiting 0.00%, io waiting 0.73%
--- 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 40.5%, load 31.41
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/diffscan ./internal/equipo ./internal/equipo/activity ./internal/equipo/assist ./internal/equipo/chat ./internal/equipo/conversation ./internal/equipo/conversation/chatstate ./internal/equipo/door ./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/pause ./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/claude/realcli ./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/forgekey ./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/diffscan ./internal/equipo ./internal/equipo/activity ./internal/equipo/assist ./internal/equipo/chat ./internal/equipo/conversation ./internal/equipo/conversation/chatstate ./internal/equipo/door ./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/pause ./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/claude/realcli ./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/forgekey ./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/provider/claude/realcli: 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/containment: 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:311 Reason: File:s001.txt}
--- FAIL: TestTimeouts (0.62s)

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

--- FAIL amadan.net/oficina/equipo/internal/testci TestBudgetRecordsAreShort
=== RUN   TestBudgetRecordsAreShort
    budgets_file_test.go:37: .rastrillo/budgets.txt:18: reason is 249 bytes, over 200
    budgets_file_test.go:37: .rastrillo/budgets.txt:41: reason is 240 bytes, over 200
    budgets_file_test.go:37: .rastrillo/budgets.txt:59: reason is 248 bytes, over 200
    budgets_file_test.go:37: .rastrillo/budgets.txt:74: reason is 233 bytes, over 200
--- FAIL: TestBudgetRecordsAreShort (0.00s)

--- FAIL amadan.net/oficina/equipo/internal/testci (package output)
FAIL
rastrillo-budget/v1 ran 2.492s
FAIL	amadan.net/oficina/equipo/internal/testci	2.498s

--- FAIL amadan.net/oficina/equipo/internal/wire TestInjectionProtocolDowngrade
=== RUN   TestInjectionProtocolDowngrade
    injection_test.go:15: negotiated 99 as 32, want 31
--- FAIL: TestInjectionProtocolDowngrade (0.00s)

--- FAIL amadan.net/oficina/equipo/internal/wire (package output)
FAIL
rastrillo-budget/v1 ran 82ms
FAIL	amadan.net/oficina/equipo/internal/wire	0.097s

budget: amadan.net/oficina/equipo/internal/diffscan ran tests but printed no time: add func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
budget note: internal/equipo took 2m23.417s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/equipo/chat took 25.498s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/equipo/setup took 12.553s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/idtest took 2m0.209s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/release took 23.057s, 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 48.525s, over the 15s its record on line 40 allows; reported only, timing fails on CI
budget note: internal/runner/provider/claude/realcli took 13.059s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/runner/provider/pi took 1m16.657s, over the 1m0s its record on line 27 allows; reported only, timing fails on CI
budget note: internal/runner/workspace took 10.757s, over the 10s the default allows; reported only, timing fails on CI

receipt: test step 2m28.789s against a 60s target (the gate's other steps are not in this figure)
receipt: 34 packages ran, 30 cached, 17 without tests, 3 failed
receipt: slow package 2m23.417s amadan.net/oficina/equipo/internal/equipo
receipt: slow package 2m0.209s amadan.net/oficina/equipo/internal/idtest
receipt: slow package 1m16.657s amadan.net/oficina/equipo/internal/runner/provider/pi
receipt: slow package 1m4.42s amadan.net/oficina/equipo/internal/runner/provider/opencode
receipt: slow package 56.685s amadan.net/oficina/equipo/internal/runner/checks
receipt: slow test 56.81s amadan.net/oficina/equipo/internal/idtest TestDoorRemembersOficinaID
receipt: slow test 47.73s amadan.net/oficina/equipo/internal/idtest TestDoorOficinaSettingsUnreadableIsNoLoop
receipt: slow test 47.7s amadan.net/oficina/equipo/internal/idtest TestDoorForgetsOficinaIDForARefusedSession
receipt: slow test 47.22s amadan.net/oficina/equipo/internal/idtest TestDoorStepUpIsLocal
receipt: slow test 46.76s amadan.net/oficina/equipo/internal/idtest TestDoorNeverJudgesANativeSession
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 58c9c21354f901a0b154692b04a28af2e1e705fb 0.62s 21.91
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
+ go test -tags testbuild -timeout 15m -v -run '^TestBudgetRecordsAreShort$' -count=1 ./internal/testci   (retry, once)
FAILED TWICE ./internal/testci:TestBudgetRecordsAreShort rest
=== RUN   TestBudgetRecordsAreShort
    budgets_file_test.go:37: .rastrillo/budgets.txt:18: reason is 249 bytes, over 200
    budgets_file_test.go:37: .rastrillo/budgets.txt:41: reason is 240 bytes, over 200
    budgets_file_test.go:37: .rastrillo/budgets.txt:59: reason is 248 bytes, over 200
    budgets_file_test.go:37: .rastrillo/budgets.txt:74: reason is 233 bytes, over 200
--- FAIL: TestBudgetRecordsAreShort (0.00s)
FAIL
rastrillo-budget/v1 ran 0s
FAIL	amadan.net/oficina/equipo/internal/testci	0.003s
FAIL
+ go test -tags testbuild -timeout 15m -v -run '^TestInjectionProtocolDowngrade$' -count=1 ./internal/wire   (retry, once)
FAILED TWICE ./internal/wire:TestInjectionProtocolDowngrade rest
=== RUN   TestInjectionProtocolDowngrade
    injection_test.go:15: negotiated 99 as 32, want 31
--- FAIL: TestInjectionProtocolDowngrade (0.00s)
FAIL
rastrillo-budget/v1 ran 0s
FAIL	amadan.net/oficina/equipo/internal/wire	0.003s
FAIL
machine: 32 CPUs, load 20.80, cpu waiting 10.61%, memory waiting 0.00%, io waiting 0.14%
make: *** [Makefile:113: ci-shard] Error 1

amadan: step check shard 17 of 29 failed: exit status 2
--- 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

receipt: test step 1m26.121s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m24.421s amadan.net/oficina/equipo/internal/headless
receipt: slow test 38.78s amadan.net/oficina/equipo/internal/headless TestBrowserDraftIsTheMessage
receipt: slow test 14.85s amadan.net/oficina/equipo/internal/headless TestBrowserDraftStreamsFormatted
receipt: slow test 10.94s amadan.net/oficina/equipo/internal/headless TestBrowserChat
receipt: slow test 7.27s amadan.net/oficina/equipo/internal/headless TestBrowserComposer
receipt: slow test 6.66s amadan.net/oficina/equipo/internal/headless TestBrowserChatSendStaysOnPage
machine: 32 CPUs, load 68.74, cpu waiting 40.56%, memory waiting 0.00%, io waiting 0.71%
--- 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

receipt: test step 1m33.612s 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.871s amadan.net/oficina/equipo/internal/headless
receipt: slow test 29.78s amadan.net/oficina/equipo/internal/headless TestBrowserRailFollowsWork
receipt: slow test 21.36s amadan.net/oficina/equipo/internal/headless TestBrowserTaskThread
receipt: slow test 13.1s amadan.net/oficina/equipo/internal/headless TestBrowserReceiptFollowsReview
receipt: slow test 9.47s amadan.net/oficina/equipo/internal/headless TestBrowserAskAfterMerge
receipt: slow test 9.39s amadan.net/oficina/equipo/internal/headless TestBrowserTaskCard
machine: 32 CPUs, load 68.12, cpu waiting 40.67%, memory waiting 0.00%, io waiting 0.62%
--- 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 1m54.019s 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 1m52.098s amadan.net/oficina/equipo/internal/headless
receipt: slow test 14.37s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsConversation
receipt: slow test 13.41s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsAddPage
receipt: slow test 12.49s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsAdd
receipt: slow test 11.32s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsMeteredLimitRequired
receipt: slow test 11.25s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsSignInEmail
machine: 32 CPUs, load 55.30, cpu waiting 31.27%, memory waiting 0.00%, io waiting 0.44%
--- 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|TestBrowserConnectionsSignInEmail|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-26T15:02:29.378Z level=INFO msg="startup phase" phase=state_lock
time=2026-11-26T15:02:29.379Z level=INFO msg="startup phase done" phase=state_lock took=242µs
time=2026-11-26T15:02:29.379Z level=INFO msg="startup phase" phase=claim_roots
time=2026-11-26T15:02:29.379Z level=INFO msg="startup phase done" phase=claim_roots took=196µs
time=2026-11-26T15:02:29.379Z level=INFO msg="startup phase" phase=sweep
time=2026-11-26T15:02:29.455Z level=INFO msg="startup phase done" phase=sweep took=76.453ms
time=2026-11-26T15:02:29.456Z level=INFO msg="startup phase" phase=credentials
time=2026-11-26T15:02:29.456Z level=INFO msg="startup phase done" phase=credentials took=191µs
time=2026-11-26T15:02:29.457Z level=INFO msg="startup phase" phase=open_state
time=2026-11-26T15:02:29.519Z level=INFO msg="startup phase done" phase=open_state took=62.027ms
time=2026-11-26T15:02:29.520Z level=WARN msg="no seal key: token connections cannot be added" err=*fs.PathError
time=2026-11-26T15:02:29.521Z level=INFO msg=connecting host=127.0.0.1:42087 protocol=32
time=2026-11-26T15:02:29.523Z level=INFO msg=connected host=127.0.0.1:42087 took=956µs
time=2026-11-26T15:02:29.523Z level=INFO msg="capabilities gathering"
time=2026-11-26T15:02:29.524Z level=INFO msg="capabilities gathered" took=1.176ms tags=linux,claude,go
time=2026-11-26T15:02:29.527Z level=INFO msg="hello sent" protocol=32
time=2026-11-26T15:02:29.531Z level=INFO msg=welcome protocol=32 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.48s)

--- FAIL amadan.net/oficina/equipo/internal/headless (package output)
FAIL
rastrillo-budget/v1 ran 1m34.643s
FAIL	amadan.net/oficina/equipo/internal/headless	94.863s


receipt: test step 1m36.321s 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 1m34.643s amadan.net/oficina/equipo/internal/headless
receipt: slow test 14.97s amadan.net/oficina/equipo/internal/headless TestBrowserThinkingAndCards
receipt: slow test 11.41s amadan.net/oficina/equipo/internal/headless TestBrowserStalePageReloads
receipt: slow test 11.13s amadan.net/oficina/equipo/internal/headless TestBrowserWaitingTurns
receipt: slow test 9.61s amadan.net/oficina/equipo/internal/headless TestBrowserMoveIn
receipt: slow test 7.78s 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|TestBrowserConnectionsSignInEmail|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$' -count=1 ./internal/headless   (retry, once)
##############################################################################
FLAKE ./internal/headless:TestBrowserCopyContinue browser-headless-rest 58c9c21354f901a0b154692b04a28af2e1e705fb 6.48s 66.83
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 62.84, cpu waiting 38.59%, memory waiting 0.00%, io waiting 0.56%
--- 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|TestBrowserPreviewPassExchange)$' ./internal/equipo

receipt: test step 4.229s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 2.542s amadan.net/oficina/equipo/internal/equipo
receipt: slow test 1.87s amadan.net/oficina/equipo/internal/equipo TestBrowserPreviewPassExchange
receipt: slow test 670ms 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|TestBrowserSmartDoor)$' ./internal/idtest
budget note: internal/idtest took 11.324s, over the 10s the default allows; reported only, timing fails on CI

receipt: test step 12.901s 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 11.324s amadan.net/oficina/equipo/internal/idtest
receipt: slow test 8.99s amadan.net/oficina/equipo/internal/idtest TestBrowserSmartDoor
receipt: slow test 2.34s 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.773s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 2.113s amadan.net/oficina/equipo/internal/plan3test
receipt: slow test 2.11s 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|TestBrowserEmptyConversation|TestBrowserEndedNoteStaysGone|TestBrowserHousekeeping|TestBrowserInnerGallery|TestBrowserInnerScreens|TestBrowserInstantThinking|TestBrowserInstantThinkingQueued|TestBrowserMachines|TestBrowserPausedWork|TestBrowserPhoneIndex|TestBrowserPlacementQuestionAndPending|TestBrowserProjectPlacement|TestBrowserProjectsList|TestBrowserReportActionFeedback|TestBrowserReportNextSteps|TestBrowserReportThread|TestBrowserRhythm|TestBrowserRollup|TestBrowserRosterAlignment|TestBrowserRosterDecisionStates|TestBrowserRosterQuietDay|TestBrowserRosterReports|TestBrowserRosterSetAside|TestBrowserRosterSubchat|TestBrowserRosterThinking|TestBrowserRosterVisual|TestBrowserSettingsHousekeepingGroups|TestBrowserSettingsMenu|TestBrowserSettingsRail|TestBrowserSettingsSaveBar|TestBrowserSettingsShots|TestBrowserSettingsStayOnPage|TestBrowserSettingsTeams|TestBrowserShipsButtons|TestBrowserSpecialistRows|TestBrowserSpendFollowsAnswers|TestBrowserTaskRows|TestBrowserTeamPanel|TestBrowserThinkingCycles|TestBrowserThinkingLinesClear|TestBrowserThinkingSteady|TestBrowserThinkingWords|TestBrowserTokenRowEmail|TestBrowserTrackPulse|TestBrowserTrackStarCentre|TestBrowserTryAgain)$' ./internal/thintest

receipt: test step 3m38.301s 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 3m36.535s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 26.29s amadan.net/oficina/equipo/internal/thintest TestBrowserAccessRequest
receipt: slow test 14.4s amadan.net/oficina/equipo/internal/thintest TestBrowserSettingsTeams
receipt: slow test 12.08s amadan.net/oficina/equipo/internal/thintest TestBrowserThinkingCycles
receipt: slow test 10.68s amadan.net/oficina/equipo/internal/thintest TestBrowserPlacementQuestionAndPending
receipt: slow test 8.96s amadan.net/oficina/equipo/internal/thintest TestBrowserRhythm
machine: 32 CPUs, load 8.42, cpu waiting 3.90%, memory waiting 0.00%, io waiting 0.04%
--- 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   (53s)
ok ./internal/headless TestHeadlessConnections/A5_cancel_and_sign_out 4.58s
ok ./internal/headless TestHeadlessConnections/C4_claude_sign_in 1.31s
ok ./internal/headless TestHeadlessConnections/C5_engineering_failover 9.01s
ok ./internal/headless TestHeadlessConnections/C5_engineering_to_codex 8.62s
ok ./internal/headless TestHeadlessConnections/C5_engineering_waits 26.76s
+ 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   (58s)
ok ./internal/headless TestHeadlessConnections/C5_review_auth 13.91s
ok ./internal/headless TestHeadlessConnections/C5_review_failover 11.85s
ok ./internal/headless TestHeadlessConnections/C5_review_on_codex 10.33s
ok ./internal/headless TestHeadlessConnections/C5_review_other_family_first 19.94s
+ go test -tags testbuild -timeout 15m -v -run '^TestMixedVersions$' ./internal/headless   (21s)
ok ./internal/headless TestMixedVersions 18.81s
+ go test -tags testbuild -timeout 15m -v -run '^TestCheckSandboxDeniedPathsTampering$' ./internal/runner/checks   (2s)
ok ./internal/runner/checks TestCheckSandboxDeniedPathsTampering 0.80s
+ go test -tags testbuild -timeout 15m -v -run '^TestRunnerCancelAndSupersede$' ./internal/runner/thin   (2s)
ok ./internal/runner/thin TestRunnerCancelAndSupersede 0.05s
quarantine: 0 flaked (passed on the retry), 0 failed
machine: 32 CPUs, load 76.21, cpu waiting 39.26%, memory waiting 0.00%, io waiting 1.14%
--- 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 13.628s against a 60s target (the gate's other steps are not in this figure)
receipt: 4 packages ran, 0 cached, 4 without tests, 0 failed
receipt: slow package 8.088s amadan.net/oficina/equipo/internal/runner/checks
receipt: slow package 194ms amadan.net/oficina/equipo/internal/runner/provider/claude
receipt: slow package 90ms 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/gotoolchain
receipt: slow test 5.8s amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPathsGoFixture
receipt: slow test 1.74s amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPaths
receipt: slow test 440ms amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPathsCache
receipt: slow test 190ms amadan.net/oficina/equipo/internal/runner/provider/claude TestDirectJournalAdapterBarrier
receipt: slow test 90ms amadan.net/oficina/equipo/internal/runner/provider/codex TestDirectJournalAdapterBarrier
CGO_ENABLED=0 RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py retried runner-host -run '^TestNamespace' -count=1 ./internal/runner/containment
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -no-time -run '^TestNamespace' -count=1 ./internal/runner/containment

receipt: test step 3.624s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 3.175s amadan.net/oficina/equipo/internal/runner/containment
receipt: slow test 310ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceReadOnlyScratch
receipt: slow test 190ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryUnavailableProof
receipt: slow test 130ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceDirectPolicyAdmission
receipt: slow test 120ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryReusedPID
receipt: slow test 110ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceReapsOrphans
machine: 32 CPUs, load 21.76, cpu waiting 11.72%, memory waiting 0.00%, io waiting 2.23%
--- 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 40.5%, load 31.41
shard 25: make runner-dead-references lanes-check build vet fmt-check spacing budget migration-check
python3 scripts/runner-dead-references.py
reference scan: 2842 text files, 3228 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 tool fiesta spacing -skip tokens.css internal/equipo/static
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size
budget size: 93 directories within budget
CGO_ENABLED=0 go test ./internal/equipo -run '^TestMigrationModels$' -count=1
ok  	amadan.net/oficina/equipo/internal/equipo	2.579s
machine: 32 CPUs, load 75.49, cpu waiting 41.18%, memory waiting 0.00%, io waiting 0.87%
--- 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 40.5%, load 31.41
shard 26: make staticcheck
go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 -tags browser,perf,testbuild ./...
internal/diffscan/scan.go:77:32: detect.Fragment is deprecated: This will be replaced with sources.Fragment in v9  (SA1019)
exit status 1
make[1]: *** [Makefile:195: staticcheck] Error 1
machine: 32 CPUs, load 69.09, cpu waiting 37.19%, memory waiting 0.00%, io waiting 1.22%
make: *** [Makefile:113: ci-shard] Error 2

amadan: step check shard 26 of 29 failed: exit status 2
--- 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 40.5%, load 31.41
shard 27: make govulncheck
go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./...
=== Symbol Results ===

Vulnerability #1: GO-2026-6888
    Excessive memory allocation when decompressing crafted streams in
    github.com/andybalholm/brotli
  More info: https://pkg.go.dev/vuln/GO-2026-6888
  Module: github.com/andybalholm/brotli
    Found in: github.com/andybalholm/brotli@v1.1.2-0.20250424173009-453214e765f3
    Fixed in: github.com/andybalholm/brotli@v1.2.7
    Example traces found:
      #1: internal/thintest/instance.go:345:22: thintest.Instance.Get calls io.ReadAll, which calls brotli.Reader.Read
      #2: internal/runner/workflow.go:391:90: runner.attemptCancellation.Error calls brotli.decodeError.Error

Vulnerability #2: GO-2026-6865
    Panic on two-block frames in github.com/klauspost/compress
  More info: https://pkg.go.dev/vuln/GO-2026-6865
  Module: github.com/klauspost/compress
    Found in: github.com/klauspost/compress@v1.17.11
    Fixed in: github.com/klauspost/compress@v1.20.2
    Example traces found:
      #1: internal/thintest/instance.go:345:22: thintest.Instance.Get calls io.ReadAll, which eventually calls fse.Decompress
      #2: internal/thintest/instance.go:345:22: thintest.Instance.Get calls io.ReadAll, which eventually calls huff0.ReadTable

Vulnerability #3: GO-2025-3922
    Memory leaks when decoding a corrupted multiple LZMA archives in
    github.com/ulikunitz/xz
  More info: https://pkg.go.dev/vuln/GO-2025-3922
  Module: github.com/ulikunitz/xz
    Found in: github.com/ulikunitz/xz@v0.5.12
    Fixed in: github.com/ulikunitz/xz@v0.5.15
    Example traces found:
      #1: internal/runner/enrol.go:170:28: runner.Enrol calls io.WriteString, which eventually calls hash.CyclicPoly.RollByte
      #2: internal/diffscan/scan.go:17:2: diffscan.init calls detect.init, which eventually calls hash.init
      #3: internal/thintest/instance.go:345:22: thintest.Instance.Get calls io.ReadAll, which eventually calls lzma.ByteReader
      #4: internal/thintest/instance.go:345:22: thintest.Instance.Get calls io.ReadAll, which eventually calls lzma.DecodeDictCap
      #5: internal/fakeclaude/fake.go:155:17: fakeclaude.Main calls fmt.Fprintln, which eventually calls lzma.Properties.String
      #6: internal/thintest/instance.go:345:22: thintest.Instance.Get calls io.ReadAll, which eventually calls lzma.Reader.Read
      #7: internal/runner/webread/fetch.go:454:20: webread.countReader.Read calls io.LimitedReader.Read, which calls lzma.Reader2.Read
      #8: internal/thintest/instance.go:345:22: thintest.Instance.Get calls io.ReadAll, which eventually calls lzma.Reader2Config.NewReader2
      #9: internal/thintest/instance.go:345:22: thintest.Instance.Get calls io.ReadAll, which eventually calls lzma.Reader2Config.Verify
      #10: internal/runner/enrol.go:170:28: runner.Enrol calls io.WriteString, which calls lzma.Writer2.Write
      #11: internal/thintest/instance.go:345:22: thintest.Instance.Get calls io.ReadAll, which eventually calls lzma.breader.ReadByte
      #12: internal/fakeclaude/fake.go:155:17: fakeclaude.Main calls fmt.Fprintln, which eventually calls lzma.chunkHeader.String
      #13: internal/fakeclaude/fake.go:155:17: fakeclaude.Main calls fmt.Fprintln, which eventually calls lzma.chunkType.String
      #14: internal/runner/enrol.go:170:28: runner.Enrol calls io.WriteString, which calls lzma.decoderDict.Write
      #15: internal/diffscan/scan.go:17:2: diffscan.init calls detect.init, which eventually calls lzma.init
      #16: internal/thintest/instance.go:345:22: thintest.Instance.Get calls io.ReadAll, which eventually calls xlog.Debugf
      #17: internal/diffscan/scan.go:17:2: diffscan.init calls detect.init, which eventually calls xlog.init
      #18: internal/thintest/instance.go:345:22: thintest.Instance.Get calls io.ReadAll, which calls xz.Reader.Read
      #19: internal/fakeclaude/fake.go:155:17: fakeclaude.Main calls fmt.Fprintln, which eventually calls xz.blockHeader.String
      #20: internal/runner/webread/fetch.go:454:20: webread.countReader.Read calls io.LimitedReader.Read, which calls xz.countingReader.Read
      #21: internal/runner/enrol.go:170:28: runner.Enrol calls io.WriteString, which calls xz.countingWriter.Write
      #22: internal/fakeclaude/fake.go:155:17: fakeclaude.Main calls fmt.Fprintln, which eventually calls xz.footer.String
      #23: internal/fakeclaude/fake.go:155:17: fakeclaude.Main calls fmt.Fprintln, which eventually calls xz.header.String
      #24: internal/diffscan/scan.go:17:2: diffscan.init calls detect.init, which eventually calls xz.init
      #25: internal/fakeclaude/fake.go:155:17: fakeclaude.Main calls fmt.Fprintln, which eventually calls xz.lzmaFilter.String
      #26: internal/runner/enrol.go:170:28: runner.Enrol calls io.WriteString, which eventually calls xz.noneHash.Write

Your code is affected by 3 vulnerabilities from 3 modules.
This scan also found 2 vulnerabilities in packages you import and 10
vulnerabilities in modules you require, but your code doesn't appear to call
these vulnerabilities.
Use '-show verbose' for more details.
exit status 3
make[1]: *** [Makefile:205: govulncheck] Error 1
machine: 32 CPUs, load 69.09, cpu waiting 35.74%, memory waiting 0.00%, io waiting 1.26%
make: *** [Makefile:113: ci-shard] Error 2

amadan: step check shard 27 of 29 failed: exit status 2
--- 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 40.5%, load 31.41
shard 28: make gitleaks
3:02PM INF Unknown SCM platform. Use --platform to include links in findings. host=amadan.net
3:02PM INF 1191 commits scanned.
3:02PM INF scanned ~67048859 bytes (67.05 MB) in 25s
3:02PM INF no leaks found
machine: 32 CPUs, load 69.09, cpu waiting 37.19%, memory waiting 0.00%, io waiting 1.22%

amadan: job failed at step check shards 17, 26, 27 of 29 — its output is above, not at the tail of this log
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 546de20f..f412ce1a 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -15,7 +15,7 @@ time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial re
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 23238 - Native preview pass issuance, bound wrapper grants, Retry/timeline and honest no-access merge copy; measured 23238 source lines (2026-11-26).
-size internal/wire 7199 - Protocol 31 display facts, shared path validation, native task evidence fields and merge credential reasons; measured 7199 source lines (2026-11-26).
+size internal/wire 7298 - Protocol 31 display facts, shared path validation, native task evidence fields and merge credential reasons; measured 7199 source lines (2026-11-26). Protocol 32 bounded display diffs and guard tests; current limits are measured totals (2026-11-26).
size internal/equipotest - 12017 Task 21 repairs historical migration and conversation fixtures after Plan 3, and the Rastrillo upgrade contract comparing served assets with what Assets serves; measured 0/12017 source/test lines.
time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded);
time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s).
@@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full
perf GET /releases/* skip Verified runner release file downloads, not browser GET screens.
perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen.
time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s;
-size internal/runner/thin 28824 23538 Protocol 31 display facts, merge credential fallback, validation and Engineering-only publication guards; measured 28824/23538 (2026-11-26).
+size internal/runner/thin 29024 23690 Protocol 31 display facts, merge credential fallback, validation and Engineering-only publication guards; measured 28824/23538 (2026-11-26). Protocol 32 bounded display diffs and guard tests; current limits are measured totals (2026-11-26).
time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes.
time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing.
time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s).
@@ -56,7 +56,7 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device
perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen.
-size internal/equipo/chat 34984 9873 Detail-only file facts, hosted projection, completion time, no-access merges and transactional preview task reads; measured 34984/9873 (2026-11-26).
+size internal/equipo/chat 35289 10176 Detail-only file facts, hosted projection, completion time, no-access merges and transactional preview task reads; measured 34984/9873 (2026-11-26). Protocol 32 bounded display diffs and guard tests; current limits are measured totals (2026-11-26).
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.
@@ -71,9 +71,11 @@ perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one im
perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section.
time cmd/equipo-runner 60s TestReleaseRunnerHasNoFakeWorker builds the release runner and the thin package under testbuild (about 12s locally).
size internal/headless - 11437 Grant scenarios for a named repository (hub #48); the sign-in's account email at 1280 and 390; measured 11437 test lines.
-size internal/thintest - 35229 Protocol 31 facts and detail-only contracts, stuck tasks, paused-job clock, no-access merges; measured 35229 test lines (2026-11-26).
+size internal/thintest - 35293 Protocol 31 facts and detail-only contracts, stuck tasks, paused-job clock, no-access merges; measured 35229 test lines (2026-11-26). Protocol 32 bounded display diffs and guard tests; current limits are measured totals (2026-11-26).
perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}.
perf GET /api/v1/usage skip Thin v1 person API: bearer-only JSON for devices; the browser reads usage through /usage.
perf GET /api/v1/advice skip Thin v1 person API: bearer-only JSON for devices; the browser reads advice through /usage and /conversation.
perf GET /native/preview/exchange skip Rejects GET with 404; only a same-origin, body-only POST can consume a preview pass.
+
+perf GET /api/v1/tasks/{id}/changes/diff skip Device-only bounded display patch JSON: indexed step/attempt lookup, 64 KiB patch and 128 KiB response, no Git or network work at read time; not an HTML screen.
diff --git a/docs/api/equipo-v1.openapi.json b/docs/api/equipo-v1.openapi.json
index 0e042779..27e59aef 100644
--- a/docs/api/equipo-v1.openapi.json
+++ b/docs/api/equipo-v1.openapi.json
@@ -14329,6 +14329,87 @@
"x-rejectUnknownFields": true
}
}
+ },
+ "/tasks/{id}/changes/diff": {
+ "get": {
+ "summary": "Read one bounded display patch for the current candidate",
+ "description": "Device-only, no-store. Same visibility as GET /tasks/{id}. At most 64 KiB and 2,000 lines of patch text, 128 KiB encoded response. Whole-file withholding on secrets or incomplete scanning. Accepted collections expire after seven days. No patch bytes in task lists or Coordinator tools.",
+ "security": [
+ {
+ "personBearer": []
+ }
+ ],
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "candidate_sha",
+ "in": "query",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "pattern": "^[0-9a-f]{40}$"
+ }
+ },
+ {
+ "name": "path",
+ "in": "query",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "maxLength": 4096
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Bounded patch or withholding reason",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ChangeDiff"
+ }
+ }
+ }
+ },
+ "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"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "The candidate changed",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Error"
+ }
+ }
+ }
+ }
+ }
+ }
}
},
"components": {
@@ -18906,6 +18987,9 @@
"Card": {
"type": "object",
"properties": {
+ "placement_by_name": {
+ "type": "boolean"
+ },
"remember_name": {
"type": "string"
},
@@ -18987,9 +19071,6 @@
},
"aside": {
"type": "boolean"
- },
- "placement_by_name": {
- "type": "boolean"
}
},
"required": [
@@ -21121,6 +21202,10 @@
"ProjectList": {
"type": "object",
"properties": {
+ "cursor": {
+ "type": "integer",
+ "format": "int64"
+ },
"connections": {
"type": "array",
"items": {
@@ -21153,10 +21238,6 @@
},
"home": {
"type": "string"
- },
- "cursor": {
- "type": "integer",
- "format": "int64"
}
},
"required": [
@@ -22226,8 +22307,9 @@
"Step": {
"type": "object",
"properties": {
- "hosted": {
- "$ref": "#/components/schemas/StepHosted"
+ "change_files": {
+ "$ref": "#/components/schemas/ChangeFiles",
+ "description": "Bounded presentation facts, included only on GET /tasks/{id} detail reads. Absent from task lists, snapshots, events and Coordinator tools."
},
"base_checks": {
"type": "string"
@@ -22342,6 +22424,9 @@
],
"format": "int64"
},
+ "hosted": {
+ "$ref": "#/components/schemas/StepHosted"
+ },
"askable": {
"type": "boolean"
},
@@ -22423,10 +22508,6 @@
},
"retried_by": {
"type": "string"
- },
- "change_files": {
- "description": "Bounded presentation facts, included only on GET /tasks/{id} detail reads. Absent from task lists, snapshots, events and Coordinator tools.",
- "$ref": "#/components/schemas/ChangeFiles"
}
},
"required": [
@@ -24397,6 +24478,66 @@
],
"additionalProperties": false,
"x-go-type": "wire.ChangedFile"
+ },
+ "ChangeDiff": {
+ "type": "object",
+ "properties": {
+ "task_id": {
+ "type": "string"
+ },
+ "step_id": {
+ "type": "string"
+ },
+ "attempt": {
+ "type": "integer",
+ "format": "int64"
+ },
+ "base": {
+ "type": "string"
+ },
+ "candidate_sha": {
+ "type": "string"
+ },
+ "status": {
+ "type": "string"
+ },
+ "old_path": {
+ "type": "string"
+ },
+ "path": {
+ "type": "string"
+ },
+ "patch": {
+ "type": "string",
+ "maxLength": 65536,
+ "description": "Plain unified patch, at most 64 KiB UTF-8 and 2,000 complete lines, only after whole-file scanning. Not HTML."
+ },
+ "reason": {
+ "type": "string",
+ "enum": [
+ "binary",
+ "too_large",
+ "withheld",
+ "unavailable",
+ "expired"
+ ]
+ },
+ "truncated": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "task_id",
+ "step_id",
+ "attempt",
+ "base",
+ "candidate_sha",
+ "status",
+ "path",
+ "truncated"
+ ],
+ "additionalProperties": false,
+ "x-go-type": "wire.ChangeDiff"
}
},
"responses": {
diff --git a/docs/superpowers/plans/2026-11-26-changes-diff.md b/docs/superpowers/plans/2026-11-26-changes-diff.md
index 85a0e1c7..147b3c74 100644
--- a/docs/superpowers/plans/2026-11-26-changes-diff.md
+++ b/docs/superpowers/plans/2026-11-26-changes-diff.md
@@ -1,6 +1,6 @@
# Slice 5b: bounded per-file diffs
-Status: proposal for the controller's brief. No implementation yet.
+Status: approved by the controller, 2026-11-26. ProtocolChangeDiffs = 32.
## Source and transport
@@ -55,7 +55,7 @@ Disable hooks, external diff, textconv, filters, config discovery and network
access, following the existing trusted Git environment. Rename identity comes
from the measured entries, not a second heuristic applied to one path.
-Proposed hard limits: 1 MiB per input blob, 8 MiB of input across a collection,
+Approved hard limits: 1 MiB per input blob, 8 MiB of input across a collection,
200 files, 64 KiB and 2,000 lines of patch text per file, 2 MiB retained patch text
per candidate, and 128 KiB encoded JSON per device response. Process files in
stable path order. Apply a 10-second total collection deadline and one collector
@@ -100,3 +100,21 @@ fake-server tests prove the selected file and candidate reach the endpoint.
Controller decisions before implementation: approve precomputed runner patches
and their storage/retention bounds, allocate the protocol capability, and confirm
whole-file withholding for detected secrets. This note proposes no new copy.
+
+
+## Implementation refinements
+
+A complete 64 KiB file patch fits a single base64 durable frame under the
+256 KiB stream bound. There are no partial unscanned chunks in storage. The
+collection hash binds every path, refusal, truncation flag and patch byte; its
+matching accepted report publishes the collection transactionally.
+
+Both ends scan in memory with the pinned Gitleaks 8.30.1 embedded default rules,
+using a fresh detector, a trusted configuration and no path-based exemptions.
+No candidate files configure it. The library logger is disabled. Known-token
+checks run on decoded layers too. Full before/after inputs are scanned on the
+runner; the instance independently scans each complete patch before storage.
+
+Expired bytes are pruned by the existing sweep and during uploads. An internal
+attempt-bound deadline remains on the step to distinguish expiry from an old
+runner that never supplied a patch. It is never projected to the Coordinator.
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-changes-diff.md b/docs/superpowers/plans/CONTROLLER-REPORT-changes-diff.md
new file mode 100644
index 00000000..146d7bc0
--- /dev/null
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-changes-diff.md
@@ -0,0 +1,172 @@
+# Changed files: bounded per-file diffs
+
+Implemented on `changes/diff`, based on main 70e4880 with a normal merge.
+The controller approved the design and protocol 32 on 2026-11-26.
+
+## Decisions
+
+One complete file patch fits one bounded base64 durable frame. This avoids
+persisting partial, unscanned bytes. The collection remains separately bound
+and requires a matching accepted Engineering report before device reads.
+Both ends use the module-pinned Gitleaks 8.30.1 embedded default rules; no
+repository configuration, baseline, path allowlist or inline ignore is read.
+The scanner library logger is permanently disabled to prevent findings from
+reaching diagnostic logs. Known-token checks also run on decoded layers.
+
+## Test-first record
+
+All Go commands use `GOMAXPROCS=2 GOTOOLCHAIN=go1.26.11 CGO_ENABLED=0`, `-p 1`.
+Only focused tests run locally because the shared Mac is loaded.
+
+- `go test -p 1 ./internal/wire -run 'TestProtocol32ChangeDiffs|TestDisplayPatchBounds' -count=1`:
+ failed first (missing types), then passed after implementation. Strict
+ downgrade rejects upload frames and removes the report reference below 32.
+- `go test -p 1 ./internal/diffscan -run TestScanClosed -count=1`:
+ failed first (missing Check), then caught encoded-token and private-key-header
+ gaps. Added decoded-layer token detection and conservative private-key-header
+ withholding. No fixture weakened to accept those cases.
+- `go test -p 1 ./internal/runner/thin -run 'TestCollectChangeDiffs|TestDisplayPatchClip' -count=1`:
+ failed first (missing collector), then passed. Covers Unicode rename, clean
+ text, secret withholding, binary, large blobs, cancellation and patch caps.
+- `go test -p 1 ./internal/equipo/chat -run 'TestChangeDiffUploadBinding|TestChangeDiffPublicationAndRead' -count=1`:
+ failed first (missing upload/read functions).
+
+## Result
+
+Protocol 32 transports complete bounded file patches separately from task views.
+The instance checks runner, person, task, step, attempt, base, candidate, digest,
+path, byte count and collection binding, and scans before storing. Only a
+matching accepted Engineering report publishes the collection. Device reads
+use task-read visibility, exact listed paths, a second roster/candidate check
+and no-store. Patches never enter lists, snapshots or Coordinator prompts.
+
+Limits: 200 files, 1 MiB/blob, 8 MiB input, 64 KiB/2,000 complete lines/file,
+2 MiB/candidate, 128 KiB encoded response, 10 seconds collection time. Unaccepted
+bytes expire after 15 minutes; accepted bytes after seven days. The sweep and
+uploads prune expired bytes. Superseded candidates are deleted even if the next
+runner uploads no replacement. A private attempt-bound deadline preserves the
+expired state after pruning. Collection failure leaves Engineering unchanged;
+the existing Review measurement test proves identical gate results before and
+after display collection.
+
+Native renders selectable plain monospaced text with added/removed styling,
+character wrapping on iPhone and horizontal scrolling on Mac. Open on Amadan
+stays outside the scroll area. Late or mismatched file/candidate responses are
+discarded. All unavailable reasons retain the Amadan action.
+
+## Validation
+
+Restored-code focused Go tests passed with Go 1.26.11, CGO disabled,
+GOMAXPROCS=2 and `-p 1`:
+
+- Wire protocol/downgrade, patch shape and all display bounds.
+- Shared scanner: encoded/known tokens, private key headers, cancellation,
+ oversized input, and hostile repository scanner settings.
+- Runner: clean patches, Unicode rename, initial commit, binary/oversized blobs,
+ input caps, complete before/after scanning, clipping and hostile Git config.
+- Store: upload bindings, replay, publication, expiry, candidate retention,
+ tampering, encoded response cap, revoked membership and stale-candidate race.
+- `TestContractChangeDiffs`: real stream upload/report/device read, no-store,
+ no patches in ordinary task views and unchanged merge authority.
+- `TestConversationMigrationSnapshot`, `TestAPIErrorCopyKeys`,
+ `TestOpsAreWhatTheHandlersWrite|TestSchemaFollowsEncodingJSON`.
+- `swift test --package-path native/apple --jobs 2 --filter ChangeDiffTests`:
+ two table-driven tests passed for transport/bounds/plain line styling and
+ late-response cancellation.
+- Native fixtures/schema, 334 exact web strings, identity and sign-in lifetime
+ checks passed. Mac and unsigned iPhone Simulator builds passed.
+- `make fmt-check`, `make budget` (93 directories) and `make copy-release-check`
+ passed. Size allowances use measured counts, retaining earlier reasons.
+ The new GET has a device-only JSON perf record: indexed lookup, no Git/network.
+
+The loaded-machine instruction overrides the usual full local gate. No full
+native/Go suite or local perf run; Linux CI is the full Go/performance gate.
+Its exact-head verdict is delivered with the SHA. The added UI test was not
+run; direct fixture-app screenshots were inspected instead. The owned simulator
+was stopped/deleted and the fixture Mac app stopped.
+
+## Mutation results
+
+52 mutations killed, then restored. Commands below returned nonzero with a
+relevant failing assertion. Two initially invalid scan mutants were repaired
+and rerun. Initially surviving fixtures were strengthened: isolate newline and
+UTF-8 guards, use a valid index/total pair, test blob caps directly, and use
+distinct before/after files so Git rename detection cannot mask a removed scan.
+
+- `runner` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `person` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `attempt` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `base` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `candidate` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `engineering` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `running` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `retired` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `cancel` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `moving` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `size` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `digest` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `order` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `candidate-byte-cap` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `file-count` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `instance-rescan` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `accepted-only` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `expiry` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `response-cap` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `wire-path` in `internal/wire/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/wire -run TestDisplayPatchBounds -count=1`.
+- `wire-bytes` in `internal/wire/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/wire -run TestDisplayPatchBounds -count=1`.
+- `wire-lines` in `internal/wire/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/wire -run TestDisplayPatchBounds -count=1`.
+- `wire-utf8` in `internal/wire/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/wire -run TestDisplayPatchBounds -count=1`.
+- `wire-nul` in `internal/wire/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/wire -run TestDisplayPatchBounds -count=1`.
+- `wire-withheld` in `internal/wire/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/wire -run TestDisplayPatchBounds -count=1`.
+- `scan-known` in `internal/diffscan/scan.go`: **KILLED**. `go test -p 1 ./internal/diffscan -run TestScanClosed -count=1`.
+- `scan-decoded` in `internal/diffscan/scan.go`: **KILLED**. `go test -p 1 ./internal/diffscan -run TestScanClosed -count=1`.
+- `scan-private-header` in `internal/diffscan/scan.go`: **KILLED**. `go test -p 1 ./internal/diffscan -run TestScanClosed -count=1`.
+- `scan-rules` in `internal/diffscan/scan.go`: **KILLED**. `go test -p 1 ./internal/diffscan -run TestScanClosed -count=1`.
+- `scan-inline-ignore` in `internal/diffscan/scan.go`: **KILLED**. `go test -p 1 ./internal/diffscan -run TestScanClosed -count=1`.
+- `runner-blob-cap` in `internal/runner/thin/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/runner/thin -run TestCollectChangeDiffs|TestDisplayPatchClip|TestDisplayBlobSafetyAndInputBudget|TestCollectionScansBeforeAfterAndBeyondCut -count=1`.
+- `runner-aggregate` in `internal/runner/thin/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/runner/thin -run TestCollectChangeDiffs|TestDisplayPatchClip|TestDisplayBlobSafetyAndInputBudget|TestCollectionScansBeforeAfterAndBeyondCut -count=1`.
+- `runner-mode` in `internal/runner/thin/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/runner/thin -run TestCollectChangeDiffs|TestDisplayPatchClip|TestDisplayBlobSafetyAndInputBudget|TestCollectionScansBeforeAfterAndBeyondCut -count=1`.
+- `runner-before-scan` in `internal/runner/thin/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/runner/thin -run TestCollectChangeDiffs|TestDisplayPatchClip|TestDisplayBlobSafetyAndInputBudget|TestCollectionScansBeforeAfterAndBeyondCut -count=1`.
+- `runner-after-scan` in `internal/runner/thin/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/runner/thin -run TestCollectChangeDiffs|TestDisplayPatchClip|TestDisplayBlobSafetyAndInputBudget|TestCollectionScansBeforeAfterAndBeyondCut -count=1`.
+- `runner-line-cap` in `internal/runner/thin/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/runner/thin -run TestCollectChangeDiffs|TestDisplayPatchClip|TestDisplayBlobSafetyAndInputBudget|TestCollectionScansBeforeAfterAndBeyondCut -count=1`.
+- `native-bearer` in `native/apple/Sources/EquipoKit/API/ChangeDiff.swift`: **KILLED**. `swift test --package-path native/apple --jobs 2 --filter ChangeDiffTests`.
+- `native-response-cap` in `native/apple/Sources/EquipoKit/API/ChangeDiff.swift`: **KILLED**. `swift test --package-path native/apple --jobs 2 --filter ChangeDiffTests`.
+- `native-task` in `native/apple/Sources/EquipoKit/API/ChangeDiff.swift`: **KILLED**. `swift test --package-path native/apple --jobs 2 --filter ChangeDiffTests`.
+- `native-candidate` in `native/apple/Sources/EquipoKit/API/ChangeDiff.swift`: **KILLED**. `swift test --package-path native/apple --jobs 2 --filter ChangeDiffTests`.
+- `native-path` in `native/apple/Sources/EquipoKit/API/ChangeDiff.swift`: **KILLED**. `swift test --package-path native/apple --jobs 2 --filter ChangeDiffTests`.
+- `native-byte-cap` in `native/apple/Sources/EquipoKit/API/ChangeDiff.swift`: **KILLED**. `swift test --package-path native/apple --jobs 2 --filter ChangeDiffTests`.
+- `native-lines` in `native/apple/Sources/EquipoKit/API/ChangeDiff.swift`: **KILLED**. `swift test --package-path native/apple --jobs 2 --filter ChangeDiffTests`.
+- `native-late-response` in `native/apple/Sources/EquipoKit/Presentation/ChangeDiffModel.swift`: **KILLED**. `swift test --package-path native/apple --jobs 2 --filter ChangeDiffTests`.
+- `publication-hash` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `second-candidate` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `second-roster` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `prune-pending` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `discard-superseded` in `internal/equipo/chat/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/equipo/chat -run ^TestChangeDiff -count=1`.
+- `frame-downgrade` in `internal/wire/runners.go`: **KILLED**. `go test -p 1 ./internal/wire -run TestProtocol32ChangeDiffs -count=1`.
+- `report-downgrade` in `internal/wire/runners.go`: **KILLED**. `go test -p 1 ./internal/wire -run TestProtocol32ChangeDiffs -count=1`.
+- `complete-lines` in `internal/wire/change_diffs.go`: **KILLED**. `go test -p 1 ./internal/wire -run TestDisplayPatchBounds -count=1`.
+
+Raw mutation scripts/results and validation logs are archived beside the
+screenshots in `site/build/slice5b/validation/`, outside this repository.
+
+## Screenshots
+
+`~/amadan.net/oficina/polish-audit/equipo-daily-driver/site/build/slice5b/`:
+`iphone-diff.png`, `iphone-diff-large.png`, `mac-diff.png`. Production sheet,
+fake device transport, long lines; the large iPhone capture uses Accessibility
+XL. Wrapping, scrolling and the visible Amadan action were inspected.
+
+## Copy review outstanding
+
+Sent to the controller before marking; still explicitly COPY PENDING:
+
+- `native.diff.withheld`: This file’s changes are hidden because they may contain a secret.
+- `native.diff.too_large`: This file is too large to show here.
+- `native.diff.unavailable`: These changes are unavailable. Open on Amadan to review them.
+- `native.diff.expired`: These changes have expired. Open on Amadan to review them.
+- `native.diff.truncated`: Only part of this file’s changes is shown. Open on Amadan for the rest.
+
+Binary reuses `native.changes.binary`. Stale-candidate errors use the literal
+reviewed `preview_changed` code and `api.preview_changed` words. No server copy
+was added. The server copy gate does not approve these native drafts. Do not
+land or release this branch until native copy review is resolved.
diff --git a/go.mod b/go.mod
index a441c20d..27e28af3 100644
--- a/go.mod
+++ b/go.mod
@@ -21,6 +21,8 @@ require (
amadan.net/oficina/home/connect v0.0.0-20261122114341-150d94e2370f
amadan.net/oficina/home/handoff v0.0.0-20261122114341-150d94e2370f
amadan.net/rastrillo/fiesta v1.6.1
+ github.com/rs/zerolog v1.33.0
+ github.com/spf13/viper v1.19.0
github.com/sqids/sqids-go v0.4.1
golang.org/x/crypto v0.55.0
golang.org/x/net v0.58.0
@@ -71,7 +73,6 @@ require (
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
github.com/pierrec/lz4/v4 v4.1.21 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
- github.com/rs/zerolog v1.33.0 // indirect
github.com/sagikazarmark/locafero v0.7.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect
@@ -84,7 +85,6 @@ require (
github.com/spf13/cast v1.7.1 // indirect
github.com/spf13/cobra v1.9.1 // indirect
github.com/spf13/pflag v1.0.6 // indirect
- github.com/spf13/viper v1.19.0 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/tdewolff/minify/v2 v2.24.19 // indirect
github.com/tdewolff/parse/v2 v2.8.16 // indirect
diff --git a/internal/diffscan/scan.go b/internal/diffscan/scan.go
new file mode 100644
index 00000000..e4eda5d3
--- /dev/null
+++ b/internal/diffscan/scan.go
@@ -0,0 +1,85 @@
+// Package diffscan applies the pinned Preview scanner's embedded default rules
+// to complete bounded text. It never reads repository config, ignore files or
+// baselines, and never returns findings or writes scanner output.
+package diffscan
+
+import (
+ "context"
+ "regexp"
+ "strings"
+ "sync"
+
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "amadan.net/oficina/equipo/internal/wire"
+ "github.com/rs/zerolog"
+ "github.com/spf13/viper"
+ "github.com/zricethezav/gitleaks/v8/config"
+ "github.com/zricethezav/gitleaks/v8/detect"
+ "github.com/zricethezav/gitleaks/v8/detect/codec"
+ "github.com/zricethezav/gitleaks/v8/logging"
+)
+
+// Gitleaks' trace logger can contain matches. Disable this library's logger
+// permanently, not process logging, before any scan. Findings stay in memory.
+func init() { logging.Logger = zerolog.Nop() }
+
+var privateHeader = regexp.MustCompile(`-----BEGIN [A-Z ]*PRIVATE KEY-----`)
+
+var rules = sync.OnceValues(func() (config.Config, error) {
+ v := viper.New()
+ v.SetConfigType("toml")
+ if err := v.ReadConfig(strings.NewReader(config.DefaultConfig)); err != nil {
+ return config.Config{}, err
+ }
+ var raw config.ViperConfig
+ if err := v.Unmarshal(&raw); err != nil {
+ return config.Config{}, err
+ }
+ return raw.Translate()
+})
+
+func Check(ctx context.Context, text string, known []string) (reason string) {
+ // A scanner panic is a failed scan, never a clean result.
+ defer func() {
+ if recover() != nil {
+ reason = wire.DiffUnavailable
+ }
+ }()
+ if ctx.Err() != nil {
+ return wire.DiffUnavailable
+ }
+ if len(text) > wire.MaxDiffBlobBytes {
+ return wire.DiffTooLarge
+ }
+ decoded := text
+ var segments []*codec.EncodedSegment
+ decoder := codec.NewDecoder()
+ for depth := 0; depth <= 5; depth++ {
+ if ctx.Err() != nil {
+ return wire.DiffUnavailable
+ }
+ if privateHeader.MatchString(decoded) || runnerproto.RedactText(decoded, known) != decoded {
+ return wire.DiffWithheld
+ }
+ decoded, segments = decoder.Decode(decoded, segments)
+ if len(segments) == 0 {
+ break
+ }
+ }
+ cfg, err := rules()
+ if err != nil {
+ return wire.DiffUnavailable
+ }
+ d := detect.NewDetectorContext(ctx, cfg)
+ d.IgnoreGitleaksAllow = true
+ d.MaxDecodeDepth = 5
+ d.Redact = 100
+ found := d.DetectContext(ctx, detect.Fragment{Raw: text})
+ if ctx.Err() != nil {
+ return wire.DiffUnavailable
+ }
+ if len(found) > 0 {
+ return wire.DiffWithheld
+ }
+ return ""
+}
diff --git a/internal/diffscan/scan_test.go b/internal/diffscan/scan_test.go
new file mode 100644
index 00000000..55d2ea0c
--- /dev/null
+++ b/internal/diffscan/scan_test.go
@@ -0,0 +1,32 @@
+package diffscan
+
+import (
+ "amadan.net/oficina/equipo/internal/wire"
+ "context"
+ "encoding/base64"
+ "strings"
+ "testing"
+)
+
+func TestScanClosed(t *testing.T) {
+ secret := "ghp_" + "0123456789abcdefghijklmnopqrstuvwxyz"
+ for i, s := range []string{"rk_live_" + "0123456789abcdefghijklmnop", "rk_live_" + "0123456789abcdefghijklmnop # gitleaks:allow", secret, "-token = '" + secret + "' # gitleaks:allow", base64.StdEncoding.EncodeToString([]byte(secret)), "context\n" + secret + "\nend", "-----BEGIN RSA PRIVATE KEY-----\nMIIBOgIBAAJBALlongprivatekey\n-----END RSA PRIVATE KEY-----"} {
+ if got := Check(context.Background(), s, nil); got != wire.DiffWithheld {
+ t.Fatalf("case %d secret not withheld: %q", i, got)
+ }
+ }
+ if Check(context.Background(), "let x = 1\n", nil) != "" {
+ t.Fatal("safe refused")
+ }
+ if Check(context.Background(), "harmless opaque value", []string{"opaque value"}) != wire.DiffWithheld {
+ t.Fatal("known secret")
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if Check(ctx, "let x = 1\n", nil) != wire.DiffUnavailable {
+ t.Fatal("cancelled scan")
+ }
+ if Check(context.Background(), strings.Repeat("x", wire.MaxDiffBlobBytes+1), nil) != wire.DiffTooLarge {
+ t.Fatal("oversize scan")
+ }
+}
diff --git a/internal/equipo/chat/change_diffs.go b/internal/equipo/chat/change_diffs.go
new file mode 100644
index 00000000..1ca28c85
--- /dev/null
+++ b/internal/equipo/chat/change_diffs.go
@@ -0,0 +1,291 @@
+package chat
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/diffscan"
+ "amadan.net/oficina/equipo/internal/equipo/personapi"
+ "amadan.net/oficina/equipo/internal/wire"
+ "github.com/go-chi/chi/v5"
+ "gorm.io/gorm"
+)
+
+type changeDiffRecord struct {
+ StepID string `gorm:"primaryKey"`
+ Attempt int64 `gorm:"primaryKey"`
+ Idx int `gorm:"primaryKey"`
+ TaskID string `gorm:"index:chat_diff_task"`
+ RunnerID string
+ Base string
+ Candidate string
+ Collection string
+ Total int
+ Path string
+ Patch string
+ Reason string
+ Truncated bool
+ Accepted bool
+ ExpiresAt time.Time `gorm:"index:chat_diff_expiry"`
+}
+
+func (changeDiffRecord) TableName() string { return "chat_change_diffs" }
+func (r changeDiffRecord) file() wire.FileDiff {
+ return wire.FileDiff{Path: r.Path, Patch: r.Patch, Reason: r.Reason, Truncated: r.Truncated}
+}
+
+var ErrDiffChanged = errors.New("diff candidate changed")
+
+func (t *txn) pruneChangeDiffs() error {
+ return t.db.Where("expires_at <= ?", t.now()).Delete(&changeDiffRecord{}).Error
+}
+
+func (t *txn) changeDiff(l Lease, v *wire.ChangeDiffUpload) error {
+ refuse := func() error { return ErrRefused }
+ if l.Protocol < wire.ProtocolChangeDiffs || !wire.ValidSHA256(v.Collection) || !wire.ValidSHA256(v.SHA256) || v.Total < 1 || v.Total > wire.MaxChangeEntries || v.Index < 0 || v.Index >= v.Total || v.Size < 0 || v.Size > wire.MaxFileDiffBytes || len(v.Data) > base64.StdEncoding.EncodedLen(wire.MaxFileDiffBytes) {
+ return refuse()
+ }
+ var step stepRecord
+ if err := t.db.Where("id = ? AND task_id = ?", v.StepID, v.TaskID).First(&step).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return refuse()
+ }
+ return err
+ }
+ if step.Specialist != wire.SpecialistEngineering || step.Person != l.Runner.Person || step.RunnerID != l.Runner.RunnerID || step.Attempt != v.Attempt || step.State != wire.StepRunning || step.Retired || step.BaseSHA != v.Base || step.CandidateSHA != v.Candidate || !validSHA(v.Candidate) {
+ return refuse()
+ }
+ k, err := t.loadTask(step.TaskID)
+ if err != nil {
+ return err
+ }
+ if wire.FinalStage(k.Stage) || k.CancelRequested || k.MoveProject != "" {
+ return refuse()
+ }
+ role, err := t.s.authority.RunnerRole(t.db, l.Runner.RunnerID)
+ if err != nil {
+ return err
+ }
+ if role != wire.RolePrimary && role != wire.RoleWorker {
+ return refuse()
+ }
+ data, err := base64.StdEncoding.DecodeString(v.Data)
+ if err != nil || len(data) != v.Size || wire.DiffDigest(data) != v.SHA256 {
+ return refuse()
+ }
+ file := wire.FileDiff{Path: v.Path, Patch: string(data), Reason: v.Reason, Truncated: v.Truncated}
+ if !wire.ValidFileDiff(file) {
+ return refuse()
+ }
+ ctx, cancel := context.WithTimeout(t.db.Statement.Context, 10*time.Second)
+ defer cancel()
+ if diffscan.Check(ctx, file.Patch, nil) != "" {
+ return refuse()
+ }
+ if err := t.pruneChangeDiffs(); err != nil {
+ return err
+ }
+ var rows []changeDiffRecord
+ if err := t.db.Where("step_id = ? AND attempt = ?", step.ID, step.Attempt).Order("idx").Find(&rows).Error; err != nil {
+ return err
+ }
+ bytes := 0
+ for _, r := range rows {
+ if r.Collection != v.Collection || r.Total != v.Total || r.RunnerID != l.Runner.RunnerID || r.Base != v.Base || r.Candidate != v.Candidate {
+ return refuse()
+ }
+ if r.Idx == v.Index {
+ if r.file() == file {
+ return nil
+ }
+ return refuse()
+ }
+ if r.Path == v.Path || r.Accepted {
+ return refuse()
+ }
+ bytes += len(r.Patch)
+ }
+ if len(rows) != v.Index || bytes+len(data) > wire.MaxCandidateDiffBytes {
+ return refuse()
+ }
+ expires := t.now().Add(15 * time.Minute)
+ if len(rows) > 0 {
+ expires = rows[0].ExpiresAt
+ }
+ record := changeDiffRecord{StepID: step.ID, Attempt: step.Attempt, Idx: v.Index, TaskID: k.ID, RunnerID: l.Runner.RunnerID, Base: v.Base, Candidate: v.Candidate, Collection: v.Collection, Total: v.Total, Path: file.Path, Patch: file.Patch, Reason: file.Reason, Truncated: file.Truncated, ExpiresAt: expires}
+ return t.db.Create(&record).Error
+}
+
+// A collection becomes readable only with its matching accepted final report.
+// Missing, conflicting and incomplete collections never affect Engineering.
+func (t *txn) acceptChangeDiffs(l Lease, step stepRecord, collection string) error {
+ if l.Protocol < wire.ProtocolChangeDiffs || step.Specialist != wire.SpecialistEngineering || !wire.ValidSHA256(collection) {
+ return nil
+ }
+ var facts wire.ChangeFiles
+ if json.Unmarshal([]byte(step.ChangeFiles), &facts) != nil || !wire.ValidChangeFiles(&facts) || facts.Base != step.BaseSHA || facts.SHA != step.CandidateSHA {
+ return nil
+ }
+ var rows []changeDiffRecord
+ if err := t.db.Where("step_id = ? AND attempt = ? AND collection = ? AND expires_at > ?", step.ID, step.Attempt, collection, t.now()).Order("idx").Find(&rows).Error; err != nil {
+ return err
+ }
+ if len(rows) == 0 || len(rows) != len(facts.Entries) {
+ return nil
+ }
+ paths := map[string]bool{}
+ for _, e := range facts.Entries {
+ paths[e.Path] = true
+ }
+ files := make([]wire.FileDiff, 0, len(rows))
+ for i, r := range rows {
+ if r.Total != len(rows) || r.Idx != i || r.TaskID != step.TaskID || r.RunnerID != step.RunnerID || r.Base != step.BaseSHA || r.Candidate != step.CandidateSHA || !paths[r.Path] {
+ return nil
+ }
+ delete(paths, r.Path)
+ files = append(files, r.file())
+ }
+ if rows[0].Accepted {
+ return nil
+ }
+ if wire.DiffCollection(files) != collection {
+ return nil
+ }
+ if err := t.db.Model(&changeDiffRecord{}).Where("step_id = ? AND attempt = ? AND accepted = ?", step.ID, step.Attempt, false).Updates(map[string]any{"accepted": true, "expires_at": t.now().Add(7 * 24 * time.Hour)}).Error; err != nil {
+ return err
+ }
+ // Keep only a deadline after pruning bytes, so the device can distinguish
+ // expiry from an old runner that never uploaded display patches.
+ if err := t.db.Model(&stepRecord{}).Where("id = ? AND attempt = ?", step.ID, step.Attempt).Updates(map[string]any{"change_diff_expires_at": t.now().Add(7 * 24 * time.Hour), "change_diff_attempt": step.Attempt}).Error; err != nil {
+ return err
+ }
+ return t.auditPreview(l.Runner.RunnerID, "changes.accepted", &step, collection)
+}
+
+func (s *Store) ChangeDiff(ctx context.Context, person, id, candidate, path string) (out wire.ChangeDiff, err error) {
+ err = s.read(ctx, func(db *gorm.DB) error {
+ if err := s.authority.CurrentPerson(ctx, db); err != nil {
+ return err
+ }
+ tx := &txn{s: s, db: db}
+ task, err := tx.loadTask(id)
+ if err != nil {
+ return err
+ }
+ view, err := tx.taskView(task)
+ if err != nil {
+ return err
+ }
+ if candidate != view.CandidateSHA {
+ return ErrDiffChanged
+ }
+ if !wire.ValidChangePath(path) {
+ return ErrNotFound
+ }
+ var step stepRecord
+ err = db.Where("task_id = ? AND specialist = ? AND candidate_sha = ? AND state = ? AND retired = ?", id, wire.SpecialistEngineering, candidate, wire.StepDone, false).Order("idx DESC").First(&step).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return ErrNotFound
+ }
+ if err != nil {
+ return err
+ }
+ facts := stepChangeFilesView(step)
+ if facts == nil {
+ return ErrNotFound
+ }
+ var entry *wire.ChangedFile
+ for i := range facts.Entries {
+ if facts.Entries[i].Path == path {
+ entry = &facts.Entries[i]
+ break
+ }
+ }
+ if entry == nil {
+ return ErrNotFound
+ }
+ out = wire.ChangeDiff{TaskID: id, StepID: step.ID, Attempt: step.Attempt, Base: facts.Base, Candidate: candidate, Status: entry.Status, OldPath: entry.OldPath, FileDiff: wire.FileDiff{Path: path, Reason: wire.DiffUnavailable}}
+ var row changeDiffRecord
+ err = db.Where("step_id = ? AND attempt = ? AND path = ? AND accepted = ?", step.ID, step.Attempt, path, true).First(&row).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ if step.ChangeDiffAttempt == step.Attempt && step.ChangeDiffExpiresAt != nil && !step.ChangeDiffExpiresAt.After(s.now()) {
+ out.Reason = wire.DiffExpired
+ }
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ if !row.ExpiresAt.After(s.now()) {
+ out.Reason = wire.DiffExpired
+ return nil
+ }
+ if row.Candidate != candidate || row.Base != facts.Base || !wire.ValidFileDiff(row.file()) {
+ return nil
+ }
+ out.FileDiff = row.file()
+ raw, err := json.Marshal(out)
+ if err != nil {
+ return err
+ }
+ if len(raw) > wire.MaxDiffResponseBytes {
+ out.FileDiff = wire.FileDiff{Path: path, Reason: wire.DiffTooLarge}
+ }
+ // Same transaction/snapshot as task read; repeat roster and identity checks
+ // immediately before returning content.
+ if err := s.authority.CurrentPerson(ctx, db); err != nil {
+ return err
+ }
+ fresh, err := tx.loadTask(id)
+ if err != nil {
+ return err
+ }
+ newView, err := tx.taskView(fresh)
+ if err != nil {
+ return err
+ }
+ if newView.CandidateSHA != candidate {
+ return ErrDiffChanged
+ }
+ return nil
+ })
+ if err != nil {
+ out = wire.ChangeDiff{}
+ }
+ return out, err
+}
+
+func (h *HTTP) changeDiff(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ w.Header().Set("Cache-Control", "no-store")
+ out, err := h.Store.ChangeDiff(r.Context(), p.Address, chi.URLParam(r, "id"), r.URL.Query().Get("candidate_sha"), r.URL.Query().Get("path"))
+ if errors.Is(err, ErrDiffChanged) {
+ personapi.WriteError(w, r, 409, "preview_changed", nil)
+ return
+ }
+ if err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ writeJSON(w, 200, out)
+}
+
+// A newer pushed candidate makes the previous display collection obsolete,
+// including candidates from old runners or Copy that upload no replacement.
+func (t *txn) discardOldChangeDiffs(k taskRecord, s stepRecord) error {
+ if !s.Pushed || s.State != wire.StepDone || s.Retired || s.Specialist != wire.SpecialistEngineering && s.Specialist != wire.SpecialistCopy {
+ return nil
+ }
+ var steps []stepRecord
+ if err := t.db.Where("task_id = ? AND coalesce(retired, 0) = 0", k.ID).Order("idx").Find(&steps).Error; err != nil {
+ return err
+ }
+ current := progressFor(k, steps).candidate
+ if current == "" {
+ return nil
+ }
+ return t.db.Where("task_id = ? AND accepted = ? AND candidate <> ?", k.ID, true, current).Delete(&changeDiffRecord{}).Error
+}
diff --git a/internal/equipo/chat/change_diffs_test.go b/internal/equipo/chat/change_diffs_test.go
new file mode 100644
index 00000000..33b2483c
--- /dev/null
+++ b/internal/equipo/chat/change_diffs_test.go
@@ -0,0 +1,303 @@
+package chat
+
+import (
+ "amadan.net/oficina/equipo/internal/wire"
+ "context"
+ "encoding/base64"
+ "fmt"
+ "gorm.io/gorm"
+ "strings"
+ "testing"
+ "time"
+)
+
+func diffRig(t *testing.T) (*meteredRig, Lease, wire.ChangeDiffUpload, wire.ChangeFiles) {
+ r, _ := pausedRigAt(t, wire.ProtocolCurrent, wire.SpecialistEngineering, wire.StepHold{})
+ r.s.authority.RunnerRole = func(*gorm.DB, string) (string, error) { return wire.RolePrimary, nil }
+ f := wire.ChangeFiles{Base: strings.Repeat("a", 40), SHA: strings.Repeat("b", 40), Files: 1, Additions: 1, Entries: []wire.ChangedFile{{Path: "hello 日本語.txt", Status: "added", Additions: 1}}}
+ r.s.db.G.Model(&stepRecord{}).Where("id = ?", "s1").Updates(map[string]any{"base_sha": f.Base, "candidate_sha": f.SHA, "hold": ""})
+ d := wire.FileDiff{Path: f.Entries[0].Path, Patch: "@@ -0,0 +1 @@\n+hello\n"}
+ v := wire.ChangeDiffUpload{TaskID: "tk1", StepID: "s1", Attempt: 1, Base: f.Base, Candidate: f.SHA, Collection: wire.DiffCollection([]wire.FileDiff{d}), Total: 1, Path: d.Path, Size: len(d.Patch), SHA256: wire.DiffDigest([]byte(d.Patch)), Data: base64.StdEncoding.EncodeToString([]byte(d.Patch))}
+ return r, Lease{Protocol: wire.ProtocolCurrent, Runner: RunnerPrincipal{RunnerID: "RUNNER1", Person: "owner@example.com"}}, v, f
+}
+func TestChangeDiffUploadBinding(t *testing.T) {
+ for name, mutate := range map[string]func(*wire.ChangeDiffUpload, *Lease){
+ "valid": func(*wire.ChangeDiffUpload, *Lease) {},
+ "old-protocol": func(_ *wire.ChangeDiffUpload, l *Lease) { l.Protocol = 31 },
+ "runner": func(_ *wire.ChangeDiffUpload, l *Lease) { l.Runner.RunnerID = "other" },
+ "person": func(_ *wire.ChangeDiffUpload, l *Lease) { l.Runner.Person = "other" },
+ "task": func(v *wire.ChangeDiffUpload, _ *Lease) { v.TaskID = "other" },
+ "attempt": func(v *wire.ChangeDiffUpload, _ *Lease) { v.Attempt++ },
+ "base": func(v *wire.ChangeDiffUpload, _ *Lease) { v.Base = v.Candidate },
+ "candidate": func(v *wire.ChangeDiffUpload, _ *Lease) { v.Candidate = v.Base },
+ "digest": func(v *wire.ChangeDiffUpload, _ *Lease) { v.SHA256 = strings.Repeat("0", 64) },
+ "size": func(v *wire.ChangeDiffUpload, _ *Lease) { v.Size++ },
+ "index": func(v *wire.ChangeDiffUpload, _ *Lease) { v.Index = 1; v.Total = 2 },
+ "total": func(v *wire.ChangeDiffUpload, _ *Lease) { v.Total = 201 },
+ "path": func(v *wire.ChangeDiffUpload, _ *Lease) { v.Path = "../secret" },
+ "secret": func(v *wire.ChangeDiffUpload, _ *Lease) {
+ p := "+token = ghp_" + strings.Repeat("aB3cD4", 6) + "\n"
+ v.Data = base64.StdEncoding.EncodeToString([]byte(p))
+ v.Size = len(p)
+ v.SHA256 = wire.DiffDigest([]byte(p))
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ r, l, v, _ := diffRig(t)
+ mutate(&v, &l)
+ err := r.s.tx(context.Background(), func(tx *txn) error { return tx.changeDiff(l, &v) })
+ if (err == nil) != (name == "valid") {
+ t.Fatalf("accept %v", err)
+ }
+ var n int64
+ r.s.db.G.Model(&changeDiffRecord{}).Count(&n)
+ if (n == 1) != (name == "valid") {
+ t.Fatal("stored refused bytes")
+ }
+ })
+ }
+}
+func TestChangeDiffPublicationAndRead(t *testing.T) {
+ r, l, v, f := diffRig(t)
+ ctx := context.Background()
+ upload := func() error { return r.s.tx(ctx, func(tx *txn) error { return tx.changeDiff(l, &v) }) }
+ if err := upload(); err != nil {
+ t.Fatal(err)
+ }
+ if err := upload(); err != nil {
+ t.Fatal("identical replay", err)
+ }
+ r.s.db.G.Model(&stepRecord{}).Where("id = ?", "s1").Updates(map[string]any{"state": wire.StepDone, "pushed": true, "change_files": asJSON(f)})
+ out, err := r.s.ChangeDiff(ctx, "member@example.com", "tk1", f.SHA, v.Path)
+ if err != nil || out.Patch != "" {
+ t.Fatal("unpublished read", err)
+ }
+ err = r.s.tx(ctx, func(tx *txn) error {
+ var st stepRecord
+ tx.db.First(&st, "id = ?", "s1")
+ return tx.acceptChangeDiffs(l, st, v.Collection)
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ out, err = r.s.ChangeDiff(ctx, "member@example.com", "tk1", f.SHA, v.Path)
+ if err != nil || !strings.Contains(out.Patch, "+hello") {
+ t.Fatalf("read %+v %v", out, err)
+ }
+ if _, err = r.s.ChangeDiff(ctx, "member@example.com", "tk1", f.Base, v.Path); err == nil {
+ t.Fatal("stale candidate")
+ }
+ if _, err = r.s.ChangeDiff(ctx, "member@example.com", "tk1", f.SHA, "unlisted"); err == nil {
+ t.Fatal("unlisted path")
+ }
+ now := r.s.now()
+ r.s.now = func() time.Time { return now.Add(7 * 24 * time.Hour) }
+ out, err = r.s.ChangeDiff(ctx, "member@example.com", "tk1", f.SHA, v.Path)
+ if err != nil || out.Reason != wire.DiffExpired || out.Patch != "" {
+ t.Fatal("expired bytes before pruning")
+ }
+ if err := r.s.tx(ctx, func(tx *txn) error { return tx.pruneChangeDiffs() }); err != nil {
+ t.Fatal(err)
+ }
+ out, err = r.s.ChangeDiff(ctx, "member@example.com", "tk1", f.SHA, v.Path)
+ if err != nil || out.Patch != "" || out.Reason != wire.DiffExpired {
+ t.Fatal("expired bytes or missing expiry reason")
+ }
+ r.s.authority.CurrentPerson = func(context.Context, *gorm.DB) error { return ErrForbidden }
+ if _, err = r.s.ChangeDiff(ctx, "member@example.com", "tk1", f.SHA, v.Path); err == nil {
+ t.Fatal("revoked read")
+ }
+}
+
+func TestChangeDiffStateAndPublicationGuards(t *testing.T) {
+ for _, scenario := range []string{"review", "done", "retired", "cancelled-task", "moved-task", "unknown-role", "incomplete", "wrong-final-reference", "wrong-final-facts", "tampered-record", "expired-upload", "conflicting-replay", "task-visibility"} {
+ t.Run(scenario, func(t *testing.T) {
+ r, l, v, f := diffRig(t)
+ ctx := context.Background()
+ db := r.s.db.G
+ upload := func() error { return r.s.tx(ctx, func(tx *txn) error { return tx.changeDiff(l, &v) }) }
+ switch scenario {
+ case "review":
+ db.Model(&stepRecord{}).Where("id = ?", "s1").Update("specialist", wire.SpecialistReview)
+ case "done":
+ db.Model(&stepRecord{}).Where("id = ?", "s1").Update("state", wire.StepDone)
+ case "retired":
+ db.Model(&stepRecord{}).Where("id = ?", "s1").Update("retired", true)
+ case "cancelled-task":
+ db.Model(&taskRecord{}).Where("id = ?", "tk1").Update("cancel_requested", true)
+ case "moved-task":
+ db.Model(&taskRecord{}).Where("id = ?", "tk1").Update("move_project", "other")
+ case "unknown-role":
+ r.s.authority.RunnerRole = func(*gorm.DB, string) (string, error) { return "unknown", nil }
+ }
+ err := upload()
+ if scenario == "review" || scenario == "done" || scenario == "retired" || scenario == "cancelled-task" || scenario == "moved-task" || scenario == "unknown-role" {
+ if err == nil {
+ t.Fatal("bad state accepted")
+ }
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if scenario == "conflicting-replay" {
+ v.Reason = wire.DiffUnavailable
+ v.Data = ""
+ v.Size = 0
+ v.SHA256 = wire.DiffDigest(nil)
+ if upload() == nil {
+ t.Fatal("replacement accepted")
+ }
+ return
+ }
+ switch scenario {
+ case "incomplete":
+ db.Model(&changeDiffRecord{}).Where("step_id = ?", "s1").Update("total", 2)
+ case "wrong-final-reference":
+ v.Collection = strings.Repeat("f", 64)
+ case "wrong-final-facts":
+ f.Entries[0].Path = "other.txt"
+ case "tampered-record":
+ db.Model(&changeDiffRecord{}).Where("step_id = ?", "s1").Update("patch", "+changed\n")
+ case "expired-upload":
+ now := r.s.now()
+ r.s.now = func() time.Time { return now.Add(15 * time.Minute) }
+ }
+ db.Model(&stepRecord{}).Where("id = ?", "s1").Updates(map[string]any{"state": wire.StepDone, "pushed": true, "change_files": asJSON(f)})
+ if err := r.s.tx(ctx, func(tx *txn) error {
+ var st stepRecord
+ tx.db.First(&st, "id = ?", "s1")
+ return tx.acceptChangeDiffs(l, st, v.Collection)
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if scenario == "task-visibility" {
+ db.Where("id = ?", "p_1").Delete(&projectRecord{})
+ if _, err := r.s.ChangeDiff(ctx, "owner@example.com", "tk1", f.SHA, v.Path); err == nil {
+ t.Fatal("orphan read")
+ }
+ return
+ }
+ var accepted int64
+ db.Model(&changeDiffRecord{}).Where("accepted = ?", true).Count(&accepted)
+ if accepted != 0 {
+ t.Fatal("invalid publication")
+ }
+ })
+ }
+}
+
+func TestChangeDiffRetentionAndCandidateByteCap(t *testing.T) {
+ r, l, v, _ := diffRig(t)
+ ctx := context.Background()
+ patch := "+" + strings.Repeat("x", wire.MaxFileDiffBytes-2) + "\n"
+ v.Total = 33
+ v.Data = base64.StdEncoding.EncodeToString([]byte(patch))
+ v.Size = len(patch)
+ v.SHA256 = wire.DiffDigest([]byte(patch))
+ for i := 0; i < 33; i++ {
+ v.Index = i
+ v.Path = fmt.Sprintf("file%02d.txt", i)
+ err := r.s.tx(ctx, func(tx *txn) error { return tx.changeDiff(l, &v) })
+ if (err == nil) != (i < 32) {
+ t.Fatalf("index %d: %v", i, err)
+ }
+ }
+ now := r.s.now()
+ r.s.now = func() time.Time { return now.Add(15 * time.Minute) }
+ if err := r.s.tx(ctx, func(tx *txn) error { return tx.pruneChangeDiffs() }); err != nil {
+ t.Fatal(err)
+ }
+ var n int64
+ r.s.db.G.Model(&changeDiffRecord{}).Count(&n)
+ if n != 0 {
+ t.Fatal("unaccepted bytes retained")
+ }
+}
+
+func TestChangeDiffEncodedResponseCap(t *testing.T) {
+ r, l, v, f := diffRig(t)
+ ctx := context.Background()
+ patch := "+" + strings.Repeat("<", wire.MaxFileDiffBytes-2) + "\n"
+ file := wire.FileDiff{Path: v.Path, Patch: patch}
+ v.Collection = wire.DiffCollection([]wire.FileDiff{file})
+ v.Data = base64.StdEncoding.EncodeToString([]byte(patch))
+ v.Size = len(patch)
+ v.SHA256 = wire.DiffDigest([]byte(patch))
+ if err := r.s.tx(ctx, func(tx *txn) error { return tx.changeDiff(l, &v) }); err != nil {
+ t.Fatal(err)
+ }
+ r.s.db.G.Model(&stepRecord{}).Where("id = ?", "s1").Updates(map[string]any{"state": wire.StepDone, "pushed": true, "change_files": asJSON(f)})
+ if err := r.s.tx(ctx, func(tx *txn) error {
+ var st stepRecord
+ tx.db.First(&st, "id = ?", "s1")
+ return tx.acceptChangeDiffs(l, st, v.Collection)
+ }); err != nil {
+ t.Fatal(err)
+ }
+ out, err := r.s.ChangeDiff(ctx, "member@example.com", "tk1", f.SHA, v.Path)
+ if err != nil || out.Patch != "" || out.Reason != wire.DiffTooLarge {
+ t.Fatal("encoded response cap", err)
+ }
+}
+
+func TestChangeDiffRechecksBeforeReturningBytes(t *testing.T) {
+ for _, change := range []string{"roster", "candidate"} {
+ t.Run(change, func(t *testing.T) {
+ r, l, v, f := diffRig(t)
+ ctx := context.Background()
+ if err := r.s.tx(ctx, func(tx *txn) error { return tx.changeDiff(l, &v) }); err != nil {
+ t.Fatal(err)
+ }
+ r.s.db.G.Model(&stepRecord{}).Where("id = ?", "s1").Updates(map[string]any{"state": wire.StepDone, "pushed": true, "change_files": asJSON(f)})
+ if err := r.s.tx(ctx, func(tx *txn) error {
+ var st stepRecord
+ tx.db.First(&st, "id = ?", "s1")
+ return tx.acceptChangeDiffs(l, st, v.Collection)
+ }); err != nil {
+ t.Fatal(err)
+ }
+ calls := 0
+ r.s.authority.CurrentPerson = func(_ context.Context, db *gorm.DB) error {
+ calls++
+ if calls == 2 {
+ if change == "roster" {
+ return ErrForbidden
+ }
+ return db.Model(&stepRecord{}).Where("id = ?", "s1").Update("candidate_sha", f.Base).Error
+ }
+ return nil
+ }
+ out, err := r.s.ChangeDiff(ctx, "member@example.com", "tk1", f.SHA, v.Path)
+ if err == nil || out.Patch != "" {
+ t.Fatal("stale bytes returned")
+ }
+ })
+ }
+}
+
+func TestChangeDiffSupersededWithoutReplacement(t *testing.T) {
+ r, _, v, _ := diffRig(t)
+ ctx := context.Background()
+ if err := r.s.db.G.Create(&changeDiffRecord{StepID: "old", Attempt: 1, TaskID: "tk1", Candidate: v.Base, Accepted: true, ExpiresAt: r.s.now().Add(time.Hour)}).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := r.s.tx(ctx, func(tx *txn) error {
+ var st stepRecord
+ tx.db.First(&st, "id = ?", "s1")
+ st.State = wire.StepDone
+ st.Pushed = true
+ k, err := tx.loadTask("tk1")
+ if err != nil {
+ return err
+ }
+ return tx.saveStep(&st, &k)
+ }); err != nil {
+ t.Fatal(err)
+ }
+ var n int64
+ r.s.db.G.Model(&changeDiffRecord{}).Count(&n)
+ if n != 0 {
+ t.Fatal("old patch retained without a replacement")
+ }
+}
diff --git a/internal/equipo/chat/http.go b/internal/equipo/chat/http.go
index 17ff1ac3..4454d8d8 100644
--- a/internal/equipo/chat/http.go
+++ b/internal/equipo/chat/http.go
@@ -113,6 +113,7 @@ func (h *HTTP) Mount(r chi.Router) {
r.Post("/tasks/{id}/uncombine", h.bearer(h.uncombineTask))
r.Post("/tasks/{id}/thread", h.bearer(h.postThread))
r.Get("/tasks/{id}/files/{file}", h.bearer(h.taskFile))
+ r.Get("/tasks/{id}/changes/diff", h.bearer(h.changeDiff))
r.Get("/steps/{id}/log", h.bearer(h.stepLog))
r.Post("/tasks/{id}/questions", h.bearer(h.ask))
r.Get("/questions/{id}", h.thinOr("GET /questions/{id}", thinQuestion, h.bearer(h.question)))
diff --git a/internal/equipo/chat/models.go b/internal/equipo/chat/models.go
index 3b0444a9..dc008ac3 100644
--- a/internal/equipo/chat/models.go
+++ b/internal/equipo/chat/models.go
@@ -11,7 +11,7 @@ import (
)
// Models are the tables this package owns, for the migration check.
-var Models = append([]any{&projectNameRecord{}, &cardVisibility{}, &cardThreadRecord{}, &copyAttemptRecord{}, &copyReviewRecord{}, &copyFeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}, &connectTurnRecord{}, &carriedRecord{}, &zoneRecord{}}, push.Models...)
+var Models = append([]any{&changeDiffRecord{}, &projectNameRecord{}, &cardVisibility{}, &cardThreadRecord{}, &copyAttemptRecord{}, &copyReviewRecord{}, &copyFeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}, &connectTurnRecord{}, &carriedRecord{}, &zoneRecord{}}, push.Models...)
type turnRecord struct {
CreateRepo string
diff --git a/internal/equipo/chat/runner.go b/internal/equipo/chat/runner.go
index 28efbe83..518cdfb3 100644
--- a/internal/equipo/chat/runner.go
+++ b/internal/equipo/chat/runner.go
@@ -361,6 +361,8 @@ func (s *Store) Apply(ctx context.Context, l Lease, f wire.Frame, body any) erro
return t.usageReport(l, v)
case *wire.StepActivityReport:
return t.stepActivity(l, v)
+ case *wire.ChangeDiffUpload:
+ return t.changeDiff(l, v)
case *wire.ResearchFile:
return t.researchFile(l, v)
}
diff --git a/internal/equipo/chat/store.go b/internal/equipo/chat/store.go
index 7baa640e..bf0c12c1 100644
--- a/internal/equipo/chat/store.go
+++ b/internal/equipo/chat/store.go
@@ -1138,6 +1138,9 @@ func (s *Store) Sweep(ctx context.Context) error {
return err
}
t := &txn{s: s, ctx: ctx, db: tx, touched: map[string]bool{}}
+ if err := t.pruneChangeDiffs(); err != nil {
+ return err
+ }
// Transfers past their TTL, and their chunks.
var old []transferRecord
if err := tx.Where("expires_at < ? AND state <> ?", s.now(), transferClosed).Find(&old).Error; err != nil {
diff --git a/internal/equipo/chat/stream.go b/internal/equipo/chat/stream.go
index 9765e472..e9be4872 100644
--- a/internal/equipo/chat/stream.go
+++ b/internal/equipo/chat/stream.go
@@ -179,7 +179,7 @@ func (rc *runnerConn) read(ctx context.Context) websocket.StatusCode {
switch v := body.(type) {
case *wire.Hello:
err = store.Heartbeat(ctx, rc.lease, *v)
- case *wire.AccessReport, *wire.Sync, *wire.Ack, *wire.DeltaReport, *wire.Reply, *wire.TurnReport, *wire.ToolCall, *wire.ActivityReport, *wire.MoveIn, *wire.NotebookReport, *wire.StepReport, *wire.MergedReport, *wire.AnswerReport, *wire.BranchReport, *wire.ConnectionReport, *wire.UsageReport, *wire.StepActivityReport, *wire.Blob, *wire.PublishedReport, *wire.ResearchFile, *wire.GlanceReport:
+ case *wire.ChangeDiffUpload, *wire.AccessReport, *wire.Sync, *wire.Ack, *wire.DeltaReport, *wire.Reply, *wire.TurnReport, *wire.ToolCall, *wire.ActivityReport, *wire.MoveIn, *wire.NotebookReport, *wire.StepReport, *wire.MergedReport, *wire.AnswerReport, *wire.BranchReport, *wire.ConnectionReport, *wire.UsageReport, *wire.StepActivityReport, *wire.Blob, *wire.PublishedReport, *wire.ResearchFile, *wire.GlanceReport:
err = store.Apply(ctx, rc.lease, f, body)
case *wire.LeaseCheck:
// Answered only while this connection holds the lease; at
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go
index 07865566..f53111f0 100644
--- a/internal/equipo/chat/tasks.go
+++ b/internal/equipo/chat/tasks.go
@@ -224,11 +224,13 @@ type stepRecord struct {
// kept only when it passed acceptance. DecidedBy is who decided a
// merge step ("policy", or "person:<address>"); MergeSource and
// MergeParents (JSON) where its SHA came from.
- ChangeFiles string // Presentation only: bounded Engineering file list.
- ChangeFacts string
- DecidedBy string
- MergeSource string
- MergeParents string
+ ChangeFiles string // Presentation only: bounded Engineering file list.
+ ChangeDiffExpiresAt *time.Time // Private retention marker, never projected into task tools.
+ ChangeDiffAttempt int64
+ ChangeFacts string
+ DecidedBy string
+ MergeSource string
+ MergeParents string
// RecheckBy is the runner whose arrival ran these checks again, after
// they waited for a Mac (macrecheck.go). Set only at creation.
RecheckBy string
@@ -772,6 +774,9 @@ func (t *txn) saveStep(s *stepRecord, k *taskRecord) error {
if err := t.writeStep(s); err != nil {
return err
}
+ if err := t.discardOldChangeDiffs(*k, *s); err != nil {
+ return err
+ }
if err := t.saveTask(k); err != nil {
return err
}
@@ -1578,6 +1583,9 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error {
s.Pushed = true
}
s.ChangeFiles = acceptChangeFiles(l, role, s, v.ChangeFiles)
+ if err := t.acceptChangeDiffs(l, s, v.ChangeDiffs); err != nil {
+ return err
+ }
s.Apple = v.Apple
s.Askable = v.Askable
if s.Rebase && s.BaseSHA != "" {
diff --git a/internal/equipo/migrations/0111_change_diffs.sql b/internal/equipo/migrations/0111_change_diffs.sql
new file mode 100644
index 00000000..1861ae62
--- /dev/null
+++ b/internal/equipo/migrations/0111_change_diffs.sql
@@ -0,0 +1,12 @@
+-- Display patches are separate from task views and merge evidence.
+CREATE TABLE chat_change_diffs (
+ step_id text, attempt integer, idx integer, task_id text, runner_id text,
+ base text, candidate text, collection text, total integer, path text,
+ patch text, reason text, truncated numeric, accepted numeric, expires_at datetime,
+ PRIMARY KEY (step_id, attempt, idx)
+);
+CREATE INDEX chat_diff_task ON chat_change_diffs(task_id);
+CREATE INDEX chat_diff_expiry ON chat_change_diffs(expires_at);
+
+ALTER TABLE chat_steps ADD COLUMN change_diff_expires_at datetime;
+ALTER TABLE chat_steps ADD COLUMN change_diff_attempt integer;
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index fdf32512..0b5e6a0d 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -799,3 +799,15 @@ CREATE INDEX preview_grant_expiry ON preview_grants(expires_at);
-- Replace pending passes and active grants by indexed device/task identity.
CREATE INDEX idx_preview_passes_device_task ON preview_passes(credential, task_id);
CREATE INDEX idx_preview_grants_device_task ON preview_grants(credential, task_id);
+-- Display patches are separate from task views and merge evidence.
+CREATE TABLE chat_change_diffs (
+ step_id text, attempt integer, idx integer, task_id text, runner_id text,
+ base text, candidate text, collection text, total integer, path text,
+ patch text, reason text, truncated numeric, accepted numeric, expires_at datetime,
+ PRIMARY KEY (step_id, attempt, idx)
+);
+CREATE INDEX chat_diff_task ON chat_change_diffs(task_id);
+CREATE INDEX chat_diff_expiry ON chat_change_diffs(expires_at);
+
+ALTER TABLE chat_steps ADD COLUMN change_diff_expires_at datetime;
+ALTER TABLE chat_steps ADD COLUMN change_diff_attempt integer;
diff --git a/internal/runner/thin/change_diffs.go b/internal/runner/thin/change_diffs.go
new file mode 100644
index 00000000..6ea69fa0
--- /dev/null
+++ b/internal/runner/thin/change_diffs.go
@@ -0,0 +1,197 @@
+package thin
+
+import (
+ "context"
+ "database/sql"
+ "encoding/base64"
+ "encoding/json"
+ "os/exec"
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "amadan.net/oficina/equipo/internal/diffscan"
+ "amadan.net/oficina/equipo/internal/runner/forge"
+ "amadan.net/oficina/equipo/internal/runner/workspace"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+func displayGit(ctx context.Context, git, dir string, limit int, args ...string) (string, bool, error) {
+ cmd := exec.CommandContext(ctx, git, append([]string{"--git-dir=" + dir, "-c", "core.quotePath=false", "-c", "core.hooksPath=/nonexistent"}, args...)...)
+ env := workspace.GitEnvironment()
+ env["HOME"] = "/nonexistent"
+ env["GIT_LITERAL_PATHSPECS"] = "1"
+ env["GIT_NO_LAZY_FETCH"] = "1"
+ env["GIT_ALLOW_PROTOCOL"] = ""
+ for k, v := range env {
+ cmd.Env = append(cmd.Env, k+"="+v)
+ }
+ raw, cut, err := boundedOutput(cmd, limit)
+ return string(raw), cut, err
+}
+
+// Read only a regular Git blob. Tree modes, object size and aggregate input
+// are checked before cat-file; a checkout symlink is never dereferenced.
+func displayBlob(ctx context.Context, git, dir, sha, path string, budget *int) (string, string) {
+ if sha == "" {
+ return "", ""
+ }
+ raw, cut, err := displayGit(ctx, git, dir, 8192, "ls-tree", "-z", sha, "--", path)
+ if err != nil || cut {
+ return "", wire.DiffUnavailable
+ }
+ if raw == "" {
+ return "", ""
+ }
+ if strings.Count(raw, "\x00") != 1 {
+ return "", wire.DiffUnavailable
+ }
+ header, name, ok := strings.Cut(strings.TrimSuffix(raw, "\x00"), "\t")
+ fields := strings.Fields(header)
+ if !ok || name != path || len(fields) != 3 || fields[0] != "100644" && fields[0] != "100755" || fields[1] != "blob" || !shaPattern.MatchString(fields[2]) {
+ return "", wire.DiffUnavailable
+ }
+ size, cut, err := displayGit(ctx, git, dir, 64, "cat-file", "-s", fields[2])
+ n, e := strconv.Atoi(strings.TrimSpace(size))
+ if err != nil || cut || e != nil || n < 0 {
+ return "", wire.DiffUnavailable
+ }
+ if n > wire.MaxDiffBlobBytes || n > *budget {
+ return "", wire.DiffTooLarge
+ }
+ *budget -= n
+ data, cut, err := displayGit(ctx, git, dir, n, "cat-file", "blob", fields[2])
+ if err != nil || cut || len(data) != n {
+ return "", wire.DiffUnavailable
+ }
+ if !utf8.ValidString(data) || strings.ContainsRune(data, 0) {
+ return "", wire.DiffBinary
+ }
+ return data, ""
+}
+
+func collectChangeDiffs(ctx context.Context, git, dir string, facts *wire.ChangeFiles, known []string) []wire.FileDiff {
+ if !wire.ValidChangeFiles(facts) {
+ return nil
+ }
+ ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ defer cancel()
+ entries := slices.Clone(facts.Entries)
+ slices.SortFunc(entries, func(a, b wire.ChangedFile) int { return strings.Compare(a.Path, b.Path) })
+ files := make([]wire.FileDiff, 0, len(entries))
+ input, left := wire.MaxDiffInputBytes, wire.MaxCandidateDiffBytes
+ for _, file := range entries {
+ d := wire.FileDiff{Path: file.Path, Reason: wire.DiffUnavailable}
+ if ctx.Err() != nil {
+ files = append(files, d)
+ continue
+ }
+ if file.Binary {
+ d.Reason = wire.DiffBinary
+ files = append(files, d)
+ continue
+ }
+ old := file.Path
+ if file.OldPath != "" {
+ old = file.OldPath
+ }
+ before, why := displayBlob(ctx, git, dir, facts.Base, old, &input)
+ if why == "" {
+ why = diffscan.Check(ctx, before, known)
+ }
+ if why == "" {
+ var after string
+ after, why = displayBlob(ctx, git, dir, facts.SHA, file.Path, &input)
+ if why == "" {
+ why = diffscan.Check(ctx, after, known)
+ }
+ }
+ if why != "" {
+ d.Reason = why
+ files = append(files, d)
+ continue
+ }
+ pair := []string{facts.Base, facts.SHA}
+ if facts.Base == "" {
+ pair = []string{"--root", "--no-commit-id", facts.SHA}
+ }
+ args := append([]string{"diff-tree", "-p", "-r", "-M", "--no-ext-diff", "--no-textconv", "--no-color"}, pair...)
+ args = append(args, "--", file.Path)
+ if old != file.Path {
+ args = append(args, old)
+ }
+ patch, cut, err := displayGit(ctx, git, dir, wire.MaxFileDiffBytes, args...)
+ // Overflow kills Git intentionally. The complete input blobs were scanned.
+ if ctx.Err() != nil || err != nil && !cut {
+ files = append(files, d)
+ continue
+ }
+ patch, clipped := clipDisplayPatch(patch)
+ d = wire.FileDiff{Path: file.Path, Patch: patch, Truncated: cut || clipped}
+ if len(patch) > left {
+ d = wire.FileDiff{Path: file.Path, Reason: wire.DiffTooLarge}
+ } else if why := diffscan.Check(ctx, patch, known); why != "" {
+ d = wire.FileDiff{Path: file.Path, Reason: why}
+ }
+ if !wire.ValidFileDiff(d) {
+ d = wire.FileDiff{Path: file.Path, Reason: wire.DiffUnavailable}
+ }
+ left -= len(d.Patch)
+ files = append(files, d)
+ }
+ return files
+}
+
+func clipDisplayPatch(s string) (string, bool) {
+ end, lines := 0, 0
+ for end < len(s) && lines < wire.MaxFileDiffLines {
+ n := strings.IndexByte(s[end:], '\n')
+ if n < 0 || end+n+1 > wire.MaxFileDiffBytes {
+ break
+ }
+ end += n + 1
+ lines++
+ }
+ return s[:end], end < len(s)
+}
+
+func (e *Engineer) queueChangeDiffs(ctx context.Context, r stepRow, git, dir string, f *wire.ChangeFiles) string {
+ if e.O.State == nil || e.O.Protocol == nil || e.O.Protocol() < wire.ProtocolChangeDiffs || !e.diffCollect.TryLock() {
+ return ""
+ }
+ defer e.diffCollect.Unlock()
+ known := slices.Clone(e.DiffSecrets)
+ // Read only the credential file already used for this runner's forge work;
+ // never resolve a remote credential or access the network for display.
+ if e.O.Runner.AmadanCredentialPath != "" {
+ credential, err := (forge.FileCredentials{Path: e.O.Runner.AmadanCredentialPath}).Credential(ctx, r.Repo)
+ if err != nil {
+ return ""
+ }
+ known = append(known, credential.Bearer, credential.GitPassword)
+ }
+ files := collectChangeDiffs(ctx, git, dir, f, known)
+ if len(files) == 0 {
+ return ""
+ }
+ collection := wire.DiffCollection(files)
+ err := e.O.State.tx(ctx, func(tx *sql.Tx) error {
+ for i, file := range files {
+ v := wire.ChangeDiffUpload{TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, Base: f.Base, Candidate: f.SHA, Collection: collection, Index: i, Total: len(files), Path: file.Path, Size: len(file.Patch), SHA256: wire.DiffDigest([]byte(file.Patch)), Data: base64.StdEncoding.EncodeToString([]byte(file.Patch)), Reason: file.Reason, Truncated: file.Truncated}
+ raw, _ := json.Marshal(v)
+ if len(raw) > wire.MaxFrameBytes-1024 {
+ return wire.ErrProtocol
+ }
+ if err := e.O.State.enqueue(tx, wire.FrameChangeDiff, "", v); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return ""
+ }
+ return collection
+}
diff --git a/internal/runner/thin/change_diffs_test.go b/internal/runner/thin/change_diffs_test.go
new file mode 100644
index 00000000..56055447
--- /dev/null
+++ b/internal/runner/thin/change_diffs_test.go
@@ -0,0 +1,151 @@
+package thin
+
+import (
+ "amadan.net/oficina/equipo/internal/wire"
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestCollectChangeDiffs(t *testing.T) {
+ dir, git := factsRepo(t)
+ base := git("rev-parse", "HEAD")
+ git("mv", "README.md", "read me 日本語.md")
+ writeFile(t, dir, "clean.txt", "one\ntwo\n")
+ writeFile(t, dir, "secret.txt", "token = ghp_"+strings.Repeat("aB3cD4", 6)+"\n")
+ writeFile(t, dir, "large.txt", strings.Repeat("x", wire.MaxDiffBlobBytes+1))
+ writeFile(t, dir, "binary.dat", "\x00\xff")
+ git("add", "-A")
+ git("commit", "-qm", "candidate")
+ sha := git("rev-parse", "HEAD")
+ facts := changeFiles(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), base, sha)
+ files := collectChangeDiffs(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), facts, nil)
+ got := map[string]wire.FileDiff{}
+ for _, f := range files {
+ got[f.Path] = f
+ }
+ if !strings.Contains(got["clean.txt"].Patch, "+two\n") {
+ t.Fatal("clean patch missing")
+ }
+ if got["secret.txt"].Reason != wire.DiffWithheld || got["secret.txt"].Patch != "" {
+ t.Fatal("secret leaked")
+ }
+ if got["large.txt"].Reason != wire.DiffTooLarge {
+ t.Fatal("large blob read")
+ }
+ if got["binary.dat"].Reason != wire.DiffBinary {
+ t.Fatal("binary patch")
+ }
+ if !strings.Contains(got["read me 日本語.md"].Patch, "rename from README.md") {
+ t.Fatal("rename missing")
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ for _, f := range collectChangeDiffs(ctx, "/usr/bin/git", filepath.Join(dir, ".git"), facts, nil) {
+ if f.Patch != "" {
+ t.Fatal("cancelled output")
+ }
+ }
+}
+func TestDisplayPatchClip(t *testing.T) {
+ for _, input := range []string{strings.Repeat("+x\n", wire.MaxFileDiffLines+1), strings.Repeat("+"+strings.Repeat("é", 200)+"\n", 400)} {
+ p, cut := clipDisplayPatch(input)
+ if !cut || !wire.ValidFileDiff(wire.FileDiff{Path: "x", Patch: p, Truncated: cut}) {
+ t.Fatal("bounds")
+ }
+ }
+}
+
+func TestDisplayBlobSafetyAndInputBudget(t *testing.T) {
+ dir, git := factsRepo(t)
+ writeFile(t, dir, "safe.txt", "hello\n")
+ writeFile(t, dir, "large.txt", strings.Repeat("x", wire.MaxDiffBlobBytes+1))
+ if err := os.Symlink("safe.txt", filepath.Join(dir, "link")); err != nil {
+ t.Fatal(err)
+ }
+ git("add", "-A")
+ git("commit", "-qm", "modes")
+ sha := git("rev-parse", "HEAD")
+ gitDir := filepath.Join(dir, ".git")
+ for _, tc := range []struct {
+ path string
+ budget int
+ want string
+ }{{"large.txt", 2 * wire.MaxDiffBlobBytes, wire.DiffTooLarge}, {"safe.txt", 5, wire.DiffTooLarge}, {"safe.txt", 6, ""}, {"link", 100, wire.DiffUnavailable}} {
+ budget := tc.budget
+ data, reason := displayBlob(context.Background(), "/usr/bin/git", gitDir, sha, tc.path, &budget)
+ if reason != tc.want {
+ t.Fatalf("%s: %s", tc.path, reason)
+ }
+ if reason != "" && data != "" {
+ t.Fatal("refused bytes")
+ }
+ if reason == "" && budget != 0 {
+ t.Fatal("aggregate budget not charged")
+ }
+ }
+ // Initial commit is compared with the empty tree; long lines never leak a
+ // clipped prefix, even when the scanner would find a secret at the end.
+ root := strings.Fields(git("rev-list", "--max-parents=0", "HEAD"))[0]
+ facts := changeFiles(context.Background(), "/usr/bin/git", gitDir, "", root)
+ if got := collectChangeDiffs(context.Background(), "/usr/bin/git", gitDir, facts, nil); len(got) == 0 || got[0].Reason != "" {
+ t.Fatal("initial commit unavailable")
+ }
+}
+
+func TestCollectionScansBeforeAfterAndBeyondCut(t *testing.T) {
+ dir, git := factsRepo(t)
+ secret := "rk_live_" + "0123456789abcdefghijklmnop"
+ writeFile(t, dir, "removed.txt", strings.Repeat("before-safe\n", 3000)+secret+"\n")
+ writeFile(t, dir, "context.txt", secret+"\none\n")
+ git("add", "-A")
+ git("commit", "-qm", "base")
+ base := git("rev-parse", "HEAD")
+ git("rm", "removed.txt")
+ writeFile(t, dir, "context.txt", secret+"\ntwo\n")
+ writeFile(t, dir, "beyond-cut.txt", strings.Repeat("after-safe\n", 3000)+secret+"\n")
+ git("add", "-A")
+ git("commit", "-qm", "candidate")
+ f := changeFiles(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), base, git("rev-parse", "HEAD"))
+ for _, d := range collectChangeDiffs(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), f, nil) {
+ if d.Reason != wire.DiffWithheld || d.Patch != "" {
+ t.Fatalf("%s was not wholly withheld", d.Path)
+ }
+ }
+}
+
+func TestDisplayIgnoresRepositoryScannerAndDiffCommands(t *testing.T) {
+ dir, git := factsRepo(t)
+ base := git("rev-parse", "HEAD")
+ marker := filepath.Join(t.TempDir(), "executed")
+ driver := filepath.Join(t.TempDir(), "driver")
+ if err := os.WriteFile(driver, []byte("#!/bin/sh\ntouch '"+marker+"'\n"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ git("config", "diff.evil.command", driver)
+ git("config", "diff.evil.textconv", driver)
+ writeFile(t, dir, ".gitattributes", "*.txt diff=evil\n")
+ writeFile(t, dir, ".gitleaks.toml", "[allowlist]\nregexes = ['.*']\n")
+ writeFile(t, dir, "secret.txt", "rk_live_"+"0123456789abcdefghijklmnop # gitleaks:allow\n")
+ writeFile(t, dir, "safe.txt", "plain text\n")
+ git("add", "-A")
+ git("commit", "-qm", "hostile configuration")
+ f := changeFiles(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), base, git("rev-parse", "HEAD"))
+ found := false
+ for _, d := range collectChangeDiffs(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), f, nil) {
+ if d.Path == "secret.txt" {
+ found = true
+ if d.Reason != wire.DiffWithheld {
+ t.Fatal("candidate weakened scanner")
+ }
+ }
+ }
+ if !found {
+ t.Fatal("missing secret fixture")
+ }
+ if _, err := os.Stat(marker); !os.IsNotExist(err) {
+ t.Fatal("candidate diff command ran")
+ }
+}
diff --git a/internal/runner/thin/change_files_test.go b/internal/runner/thin/change_files_test.go
index 8e6fc656..d1ce14af 100644
--- a/internal/runner/thin/change_files_test.go
+++ b/internal/runner/thin/change_files_test.go
@@ -52,6 +52,7 @@ func TestEngineeringChangeFiles(t *testing.T) {
if e := entries["new space.txt"]; e.Status != "added" || e.Additions != 2 {
t.Fatalf("added: %+v", e)
}
+ _ = collectChangeDiffs(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), f, nil)
after := measure(t, dir, base, sha, "")
a, _ := json.Marshal(before)
b, _ := json.Marshal(after)
diff --git a/internal/runner/thin/engineer.go b/internal/runner/thin/engineer.go
index d04cfe45..bc8d70d0 100644
--- a/internal/runner/thin/engineer.go
+++ b/internal/runner/thin/engineer.go
@@ -55,6 +55,8 @@ const (
// (workspace read-write, nothing else), the runner's own commit, and the
// push through forge.
type Engineer struct {
+ diffCollect sync.Mutex
+ DiffSecrets []string
// keptLog holds the last kept-sessions figures logged and when.
keptLog sync.Mutex
keptLast [2]int64
@@ -422,6 +424,7 @@ func (e *Engineer) publish(ctx context.Context, r stepRow, rep wire.StepReport)
}
if r.Specialist == wire.SpecialistEngineering {
rep.ChangeFiles = changeFiles(ctx, tree.Git, tree.GitDir, r.Base, r.Candidate)
+ rep.ChangeDiffs = e.queueChangeDiffs(ctx, r, tree.Git, tree.GitDir, rep.ChangeFiles)
}
expectedHead := ""
if r.Specialist == wire.SpecialistCopy {
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go
index 9a431dba..50d7fb55 100644
--- a/internal/runner/thin/run.go
+++ b/internal/runner/thin/run.go
@@ -345,7 +345,7 @@ func Run(ctx context.Context, c runner.Config, o Options) error {
if err = engine.Start(ctx); err != nil {
return err
}
- engineer := &Engineer{O: o.Claude, Codex: o.Codex, Pi: piOptions(c, o.Pi), OpenCode: opencodeOptions(c, o.OpenCode), Clones: clones, Forge: fg, CI: hostedCIOf(fg), Authorize: link.Confirm, AuthorizeStep: link.ConfirmStep, ConfirmMerge: link.ConfirmMerge, ConfirmPreview: link.ConfirmPreview, Preview: preview, Devbox: devbox, Site: site, ConfirmPublish: link.ConfirmPublish, ConfirmPublication: link.ConfirmPublication, Owners: withPerson(coordinatorPersons(c)(), creds.Bearer.Person), MaxStep: o.MaxStep, Note: o.StepNote, Healthy: conns.Usable, Conns: conns, Delta: link.Delta, Activity: link.Activity, StepActivity: link.StepActivity, Retention: o.KeptRetention, Host: c.MachineLabel, Merged: func(string) { index.Kick() }}
+ engineer := &Engineer{DiffSecrets: []string{creds.Bearer.Token}, O: o.Claude, Codex: o.Codex, Pi: piOptions(c, o.Pi), OpenCode: opencodeOptions(c, o.OpenCode), Clones: clones, Forge: fg, CI: hostedCIOf(fg), Authorize: link.Confirm, AuthorizeStep: link.ConfirmStep, ConfirmMerge: link.ConfirmMerge, ConfirmPreview: link.ConfirmPreview, Preview: preview, Devbox: devbox, Site: site, ConfirmPublish: link.ConfirmPublish, ConfirmPublication: link.ConfirmPublication, Owners: withPerson(coordinatorPersons(c)(), creds.Bearer.Person), MaxStep: o.MaxStep, Note: o.StepNote, Healthy: conns.Usable, Conns: conns, Delta: link.Delta, Activity: link.Activity, StepActivity: link.StepActivity, Retention: o.KeptRetention, Host: c.MachineLabel, Merged: func(string) { index.Kick() }}
link.Forget = engineer.RemoveKept
link.TaskEnded = engineer.PreviewTaskEnded
// A Research step that met an address outside the confirmed inventory
diff --git a/internal/thintest/change_diffs_contract_test.go b/internal/thintest/change_diffs_contract_test.go
new file mode 100644
index 00000000..895b0df8
--- /dev/null
+++ b/internal/thintest/change_diffs_contract_test.go
@@ -0,0 +1,64 @@
+package thintest
+
+import (
+ "amadan.net/oficina/equipo/internal/wire"
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+)
+
+func TestContractChangeDiffs(t *testing.T) {
+ r := newToolRigAt(t, wire.ProtocolChangeDiffs)
+ base, sha := strings.Repeat("1", 40), strings.Repeat("2", 40)
+ id := taskID(t, r.call("diff-record", wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": "Bounded diff", "brief": "Change a line", "separate": true}))
+ if result := r.call("diff-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Change it"}); result.IsError {
+ t.Fatal(result)
+ }
+ _, body := r.expect(wire.FrameDispatch)
+ step := body.(*wire.DispatchCommand)
+ r.step("diff-progress", wire.StepReport{TaskID: id, StepID: step.StepID, Attempt: step.Attempt, State: wire.StepRunning, BaseSHA: base, CandidateSHA: sha})
+ file := wire.FileDiff{Path: "space 日本語.txt", Patch: "@@ -1 +1 @@\n-before\n+after\n"}
+ collection := wire.DiffCollection([]wire.FileDiff{file})
+ r.step2("diff-file", wire.FrameChangeDiff, wire.ChangeDiffUpload{TaskID: id, StepID: step.StepID, Attempt: step.Attempt, Base: base, Candidate: sha, Collection: collection, Total: 1, Path: file.Path, Size: len(file.Patch), SHA256: wire.DiffDigest([]byte(file.Patch)), Data: base64.StdEncoding.EncodeToString([]byte(file.Patch))})
+ facts := &wire.ChangeFiles{Base: base, SHA: sha, Files: 1, Additions: 1, Deletions: 1, Entries: []wire.ChangedFile{{Path: file.Path, Status: "modified", Additions: 1, Deletions: 1}}}
+ r.step("diff-done", wire.StepReport{TaskID: id, StepID: step.StepID, Attempt: step.Attempt, State: wire.StepDone, BaseSHA: base, CandidateSHA: sha, Pushed: true, Termination: true, ChangeFiles: facts, ChangeDiffs: collection})
+ var out wire.ChangeDiff
+ path := "/api/v1/tasks/" + id + "/changes/diff?candidate_sha=" + sha + "&path=" + url.QueryEscape(file.Path)
+ if err := r.client.do(r.ctx, "GET", path, nil, &out); err != nil {
+ t.Fatal(err)
+ }
+ if out.Patch != file.Patch || out.TaskID != id || out.StepID != step.StepID || out.Candidate != sha {
+ t.Fatalf("patch %+v", out)
+ }
+ request, err := http.NewRequestWithContext(r.ctx, http.MethodGet, r.client.Origin+path, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ request.Header.Set("Authorization", "Bearer "+r.client.Token)
+ response, err := r.client.HTTP.Do(request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ response.Body.Close()
+ if response.StatusCode != 200 || response.Header.Get("Cache-Control") != "no-store" {
+ t.Fatal("cacheable patch response")
+ }
+
+ task, err := r.client.Task(r.ctx, id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, _ := json.Marshal(task)
+ if strings.Contains(string(raw), "before") || strings.Contains(string(raw), "change_diffs") {
+ t.Fatal("patch leaked into task")
+ }
+ if task.MergeDecision != nil {
+ t.Fatal("display became merge evidence")
+ }
+ if err := r.client.do(r.ctx, "GET", strings.Replace(path, sha, base, 1), nil, &out); err == nil {
+ t.Fatal("stale candidate")
+ }
+}
diff --git a/internal/wire/assistant_test.go b/internal/wire/assistant_test.go
index 4e8a748b..336dc866 100644
--- a/internal/wire/assistant_test.go
+++ b/internal/wire/assistant_test.go
@@ -81,7 +81,7 @@ func TestAssistantCardJSON(t *testing.T) {
// A runner that speaks 24 or more is spoken to at 24, the warm
// protocol; glances came at 23 and jobs at 22.
func TestSpokenIs24(t *testing.T) {
- if wire.Spoken(99) != 31 || wire.ProtocolCurrent != wire.ProtocolChangeFiles || wire.ProtocolWarm != wire.Protocol24 || wire.ProtocolGlance != wire.Protocol23 || wire.ProtocolJobs != wire.Protocol22 || wire.ProtocolCopy != wire.Protocol21 || wire.ProtocolUsageRefresh != wire.Protocol20 || wire.ProtocolAssistant != wire.Protocol19 {
+ if wire.Spoken(99) != 32 || wire.ProtocolCurrent != wire.ProtocolChangeDiffs || wire.ProtocolWarm != wire.Protocol24 || wire.ProtocolGlance != wire.Protocol23 || wire.ProtocolJobs != wire.Protocol22 || wire.ProtocolCopy != wire.Protocol21 || wire.ProtocolUsageRefresh != wire.Protocol20 || wire.ProtocolAssistant != wire.Protocol19 {
t.Fatalf("spoken %d, current %d", wire.Spoken(99), wire.ProtocolCurrent)
}
}
diff --git a/internal/wire/change_diffs.go b/internal/wire/change_diffs.go
new file mode 100644
index 00000000..e96b4bc4
--- /dev/null
+++ b/internal/wire/change_diffs.go
@@ -0,0 +1,82 @@
+package wire
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "strings"
+ "unicode/utf8"
+)
+
+const (
+ MaxDiffBlobBytes = 1 << 20
+ MaxDiffInputBytes = 8 << 20
+ MaxFileDiffBytes = 64 << 10
+ MaxFileDiffLines = 2000
+ MaxCandidateDiffBytes = 2 << 20
+ MaxDiffResponseBytes = 128 << 10
+ FrameChangeDiff = "change_diff"
+ DiffBinary = "binary"
+ DiffTooLarge = "too_large"
+ DiffWithheld = "withheld"
+ DiffUnavailable = "unavailable"
+ DiffExpired = "expired"
+)
+
+// FileDiff is display evidence only, never a merge or Review input.
+type FileDiff struct {
+ Path string `json:"path"`
+ Patch string `json:"patch,omitempty"`
+ Reason string `json:"reason,omitempty"`
+ Truncated bool `json:"truncated"`
+}
+
+// ChangeDiffUpload sends one complete bounded file, base64 encoded so even
+// maximally escaped text fits a durable frame. The receiver scans the whole
+// decoded patch before storing it; no partial unscanned chunks are persisted.
+type ChangeDiffUpload struct {
+ TaskID string `json:"task_id"`
+ StepID string `json:"step_id"`
+ Attempt int64 `json:"attempt"`
+ Base string `json:"base"`
+ Candidate string `json:"candidate_sha"`
+ Collection string `json:"collection"`
+ Index int `json:"index"`
+ Total int `json:"total"`
+ Path string `json:"path"`
+ Size int `json:"size"`
+ SHA256 string `json:"sha256"`
+ Data string `json:"data"`
+ Reason string `json:"reason,omitempty"`
+ Truncated bool `json:"truncated"`
+}
+
+type ChangeDiff struct {
+ TaskID string `json:"task_id"`
+ StepID string `json:"step_id"`
+ Attempt int64 `json:"attempt"`
+ Base string `json:"base"`
+ Candidate string `json:"candidate_sha"`
+ Status string `json:"status"`
+ OldPath string `json:"old_path,omitempty"`
+ FileDiff
+}
+
+func ValidFileDiff(d FileDiff) bool {
+ if !ValidChangePath(d.Path) || len(d.Patch) > MaxFileDiffBytes || !utf8.ValidString(d.Patch) || strings.ContainsRune(d.Patch, 0) || strings.Count(d.Patch, "\n") > MaxFileDiffLines {
+ return false
+ }
+ switch d.Reason {
+ case "":
+ return d.Patch == "" || strings.HasSuffix(d.Patch, "\n")
+ case DiffBinary, DiffTooLarge, DiffWithheld, DiffUnavailable, DiffExpired:
+ return d.Patch == "" && !d.Truncated
+ default:
+ return false
+ }
+}
+
+func DiffDigest(data []byte) string { sum := sha256.Sum256(data); return hex.EncodeToString(sum[:]) }
+
+// The collection hash binds ordering, paths, refusals and every patch byte.
+func DiffCollection(files []FileDiff) string { raw, _ := json.Marshal(files); return DiffDigest(raw) }
diff --git a/internal/wire/change_diffs_test.go b/internal/wire/change_diffs_test.go
new file mode 100644
index 00000000..d0b29303
--- /dev/null
+++ b/internal/wire/change_diffs_test.go
@@ -0,0 +1,80 @@
+package wire_test
+
+import (
+ "amadan.net/oficina/equipo/internal/wire"
+ "encoding/json"
+ "errors"
+ "strings"
+ "testing"
+)
+
+func TestProtocol32ChangeDiffs(t *testing.T) {
+ if wire.ProtocolChangeDiffs != 32 || wire.ProtocolCurrent != 32 {
+ t.Fatal("protocol")
+ }
+ f, err := wire.NewFrame("diff", wire.FrameChangeDiff, wire.ChangeDiffUpload{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for p := 1; p < 32; p++ {
+ if _, err := wire.Encode(f, p); !errors.Is(err, wire.ErrProtocol) {
+ t.Fatalf("upload at %d", p)
+ }
+ }
+ if _, err := wire.Encode(f, 32); err != nil {
+ t.Fatal(err)
+ }
+ report := wire.StepReport{ChangeDiffs: "collection"}
+ f, _ = wire.NewFrame("done", wire.FrameStep, report)
+ for p := 1; p <= 32; p++ {
+ got, err := wire.Encode(f, p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var fields map[string]json.RawMessage
+ _ = json.Unmarshal(got.Data, &fields)
+ if (fields["change_diffs"] != nil) != (p == 32) {
+ t.Fatalf("report at %d", p)
+ }
+ }
+ if report.ChangeDiffs != "collection" {
+ t.Fatal("mutated caller")
+ }
+}
+
+func TestDisplayPatchBounds(t *testing.T) {
+ good := wire.FileDiff{Path: "space 日本語.txt", Patch: "@@ -1 +1 @@\n-old\n+new\n"}
+ if !wire.ValidFileDiff(good) {
+ t.Fatal("valid")
+ }
+ for name, mutate := range map[string]func(*wire.FileDiff){
+ "partial-line": func(d *wire.FileDiff) { d.Patch = "+partial" },
+ "path": func(d *wire.FileDiff) { d.Path = "../x" },
+ "bytes": func(d *wire.FileDiff) { d.Patch = strings.Repeat("x", wire.MaxFileDiffBytes) + "\n" },
+ "lines": func(d *wire.FileDiff) { d.Patch = strings.Repeat("+\n", wire.MaxFileDiffLines+1) },
+ "utf8": func(d *wire.FileDiff) { d.Patch = string([]byte{255}) + "\n" },
+ "nul": func(d *wire.FileDiff) { d.Patch = "+\x00\n" },
+ "reason": func(d *wire.FileDiff) { d.Reason = "unknown" },
+ "withheld-bytes": func(d *wire.FileDiff) { d.Reason = wire.DiffWithheld },
+ "withheld-truncated": func(d *wire.FileDiff) { d.Patch = ""; d.Reason = wire.DiffWithheld; d.Truncated = true },
+ } {
+ t.Run(name, func(t *testing.T) {
+ d := good
+ mutate(&d)
+ if wire.ValidFileDiff(d) {
+ t.Fatal("accepted")
+ }
+ })
+ }
+ for _, reason := range []string{wire.DiffBinary, wire.DiffTooLarge, wire.DiffWithheld, wire.DiffUnavailable, wire.DiffExpired} {
+ if !wire.ValidFileDiff(wire.FileDiff{Path: "x", Reason: reason}) {
+ t.Fatal(reason)
+ }
+ }
+}
+
+func TestDisplayBoundsContract(t *testing.T) {
+ if wire.MaxChangeEntries != 200 || wire.MaxDiffBlobBytes != 1<<20 || wire.MaxDiffInputBytes != 8<<20 || wire.MaxFileDiffBytes != 64<<10 || wire.MaxFileDiffLines != 2000 || wire.MaxCandidateDiffBytes != 2<<20 || wire.MaxDiffResponseBytes != 128<<10 {
+ t.Fatal("approved display limits changed")
+ }
+}
diff --git a/internal/wire/change_files_test.go b/internal/wire/change_files_test.go
index cd74f040..530afe17 100644
--- a/internal/wire/change_files_test.go
+++ b/internal/wire/change_files_test.go
@@ -11,7 +11,7 @@ import (
)
func TestProtocol31ChangeFiles(t *testing.T) {
- if wire.ProtocolChangeFiles != 31 || wire.ProtocolCurrent != 31 {
+ if wire.ProtocolChangeFiles != 31 || wire.ProtocolCurrent != 32 {
t.Fatal("protocol not 31")
}
facts := &wire.ChangeFiles{Base: strings.Repeat("a", 40), SHA: strings.Repeat("b", 40), Files: 1, Additions: 1, Entries: []wire.ChangedFile{{Path: "a.txt", Status: "added", Additions: 1}}}
diff --git a/internal/wire/frames.go b/internal/wire/frames.go
index 0f09798a..14e6d2f4 100644
--- a/internal/wire/frames.go
+++ b/internal/wire/frames.go
@@ -67,7 +67,7 @@ type Frame struct {
// Durable reports whether a frame must be acked and resent until acked.
func (f Frame) Durable() bool {
switch f.Type {
- case FrameRequestAccess, FrameAccess, FrameMessage, FrameAttachment, FrameCancel, FrameReply, FrameTurn, FrameToolCall, FrameToolResult, FrameMoveIn, FrameNotebook, FrameReset, FrameDispatch, FrameCancelStep, FrameStep, FrameRecheck, FrameWatchMerge, FrameMerged, FrameAsk, FrameCancelAsk, FrameAnswer, FrameForgetTask, FrameBranch, FrameBlob, FrameSendPack, FramePublish, FramePublished, FrameConnect, FrameCancelConnect, FrameConnection, FrameUsage, FrameDisconnect, FramePreference, FrameSecret, FrameCheck, FrameModel, FrameModels, FrameBudget, FrameResumeSpend, FrameResearchFile, FrameRelease, FramePriority, FrameWarm:
+ case FrameChangeDiff, FrameRequestAccess, FrameAccess, FrameMessage, FrameAttachment, FrameCancel, FrameReply, FrameTurn, FrameToolCall, FrameToolResult, FrameMoveIn, FrameNotebook, FrameReset, FrameDispatch, FrameCancelStep, FrameStep, FrameRecheck, FrameWatchMerge, FrameMerged, FrameAsk, FrameCancelAsk, FrameAnswer, FrameForgetTask, FrameBranch, FrameBlob, FrameSendPack, FramePublish, FramePublished, FrameConnect, FrameCancelConnect, FrameConnection, FrameUsage, FrameDisconnect, FramePreference, FrameSecret, FrameCheck, FrameModel, FrameModels, FrameBudget, FrameResumeSpend, FrameResearchFile, FrameRelease, FramePriority, FrameWarm:
return true
}
return false
@@ -184,6 +184,8 @@ func (f Frame) Decode() (any, error) {
v = &PublishedReport{}
case FrameRefused:
v = &Refused{}
+ case FrameChangeDiff:
+ v = &ChangeDiffUpload{}
case FrameResearchFile:
v = &ResearchFile{}
case FrameRelease:
diff --git a/internal/wire/injection_test.go b/internal/wire/injection_test.go
index 49ac9e94..bc777819 100644
--- a/internal/wire/injection_test.go
+++ b/internal/wire/injection_test.go
@@ -7,7 +7,7 @@ import (
)
func TestInjectionProtocolDowngrade(t *testing.T) {
- if wire.ProtocolInjectionDefences != 28 || wire.ProtocolCurrent != 31 {
+ if wire.ProtocolInjectionDefences != 28 || wire.ProtocolCurrent != 32 {
t.Fatal("injection guarantees require protocol 28")
}
for version, want := range map[int]int{26: 26, 27: 27, 28: 28, 29: 29, 30: 30, 31: 31, 99: 31} {
diff --git a/internal/wire/mixed_protocol_test.go b/internal/wire/mixed_protocol_test.go
index 73a547f3..9b1745b4 100644
--- a/internal/wire/mixed_protocol_test.go
+++ b/internal/wire/mixed_protocol_test.go
@@ -15,7 +15,7 @@ import (
// both go out whole; at 11 both are downgraded. The numbers are written
// out so that pointing ProtocolResearch back at 12 fails here.
func TestEncodeMixedMeteredAndResearch(t *testing.T) {
- if wire.ProtocolMetered != wire.Protocol12 || wire.ProtocolResearch != wire.Protocol13 || wire.ProtocolCurrent != wire.Protocol31 {
+ if wire.ProtocolMetered != wire.Protocol12 || wire.ProtocolResearch != wire.Protocol13 || wire.ProtocolCurrent != wire.ProtocolChangeDiffs {
t.Fatalf("metered %d, research %d, current %d", wire.ProtocolMetered, wire.ProtocolResearch, wire.ProtocolCurrent)
}
metered := wire.HeldConnection{LocalID: "tensorx-1", Person: "p", Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, State: wire.ConnHealthy, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Budget: &wire.Budget{Day: 1, Month: 2, Currency: "USD"}, Spend: &wire.Spend{Currency: "USD"}}
diff --git a/internal/wire/models_test.go b/internal/wire/models_test.go
index 892faa67..797653a0 100644
--- a/internal/wire/models_test.go
+++ b/internal/wire/models_test.go
@@ -94,7 +94,7 @@ func modelsFrames(t *testing.T) map[string]wire.Frame {
// protocol is checked because an older step in Encode's chain could
// undo a newer one (S5's bug).
func TestEncodeBelowProtocol18AgainstFrozenSchemas(t *testing.T) {
- if wire.ProtocolModels != wire.Protocol18 || wire.ProtocolCurrent != wire.Protocol31 {
+ if wire.ProtocolModels != wire.Protocol18 || wire.ProtocolCurrent != wire.ProtocolChangeDiffs {
t.Fatalf("models %d, current %d", wire.ProtocolModels, wire.ProtocolCurrent)
}
fs := modelsFrames(t)
diff --git a/internal/wire/opencode_test.go b/internal/wire/opencode_test.go
index 6458a7ef..61b7cf64 100644
--- a/internal/wire/opencode_test.go
+++ b/internal/wire/opencode_test.go
@@ -57,7 +57,7 @@ func providersIn(t *testing.T, raw []byte) (providers, harnesses []string) {
// leave hello and sync, its usage rows leave every report, and a connect
// or a report about one is refused. At 17 nothing changes.
func TestEncodeBelowProtocol17DropsOpenCode(t *testing.T) {
- if wire.ProtocolOpenCode != wire.Protocol17 || wire.ProtocolCurrent != wire.Protocol31 {
+ if wire.ProtocolOpenCode != wire.Protocol17 || wire.ProtocolCurrent != wire.ProtocolChangeDiffs {
t.Fatalf("opencode %d, current %d", wire.ProtocolOpenCode, wire.ProtocolCurrent)
}
budget := &wire.Budget{Day: 1_000_000, Month: 10_000_000, Currency: "USD", Revision: 1}
diff --git a/internal/wire/pinned_release_test.go b/internal/wire/pinned_release_test.go
index aeb0eb6c..994f5625 100644
--- a/internal/wire/pinned_release_test.go
+++ b/internal/wire/pinned_release_test.go
@@ -13,7 +13,7 @@ import (
// carrying a pinned release loses the release and its pin; an unpinned
// release is unchanged from protocol 14.
func TestEncodePinnedReleaseBelow29(t *testing.T) {
- if wire.ProtocolPinnedRelease != wire.Protocol29 || wire.ProtocolCurrent != wire.Protocol31 {
+ if wire.ProtocolPinnedRelease != wire.Protocol29 || wire.ProtocolCurrent != wire.ProtocolChangeDiffs {
t.Fatalf("pinned %d, current %d", wire.ProtocolPinnedRelease, wire.ProtocolCurrent)
}
pinned, err := wire.NewFrame("f1", wire.FrameRelease, wire.ReleaseCommand{ID: "rl_1", Person: "p", TaskID: "tk1", StepID: "s1", StepRevision: 1, Connection: "claude-1"})
diff --git a/internal/wire/publish_test.go b/internal/wire/publish_test.go
index d47cb0c2..41d78c2b 100644
--- a/internal/wire/publish_test.go
+++ b/internal/wire/publish_test.go
@@ -17,7 +17,7 @@ import (
// and a hello's sites capability are dropped, so nothing a protocol 15
// peer decodes strictly carries them.
func TestEncodeBelowProtocol16DropsPublish(t *testing.T) {
- if wire.ProtocolPublish != wire.Protocol16 || wire.ProtocolCurrent != wire.Protocol31 {
+ if wire.ProtocolPublish != wire.Protocol16 || wire.ProtocolCurrent != wire.ProtocolChangeDiffs {
t.Fatalf("publish %d, current %d", wire.ProtocolPublish, wire.ProtocolCurrent)
}
publish := wire.DispatchCommand{Person: "p", TaskID: "tk", StepID: "s", Attempt: 1, Specialist: wire.SpecialistPublish, Findings: []wire.Finding{}, CandidateSHA: strings.Repeat("e", 40), Publish: &wire.PublishDispatch{App: "site-sample", Into: "main"}}
diff --git a/internal/wire/runners.go b/internal/wire/runners.go
index 56d363f6..88fcda94 100644
--- a/internal/wire/runners.go
+++ b/internal/wire/runners.go
@@ -57,6 +57,7 @@ const (
Protocol29 = 29
Protocol30 = 30
Protocol31 = 31
+ Protocol32 = 32
// ProtocolSpend is the first protocol with a fix round's Feedback and
// a usage row's Turns; Encode drops both below it.
ProtocolSpend = Protocol3
@@ -197,7 +198,9 @@ const (
ProtocolStuckTasks = Protocol30
// ProtocolChangeFiles adds bounded Engineering file-list facts.
ProtocolChangeFiles = Protocol31
- ProtocolCurrent = ProtocolChangeFiles
+ // ProtocolChangeDiffs adds separate bounded display patches.
+ ProtocolChangeDiffs = Protocol32
+ ProtocolCurrent = ProtocolChangeDiffs
)
// Runner roles. A person's first runner is the primary: the coordinator,
@@ -633,12 +636,23 @@ func Encode(f Frame, protocol int) (Frame, error) {
return Frame{}, ErrProtocol
}
changed := false
+ if protocol < ProtocolChangeDiffs {
+ switch v := body.(type) {
+ case *ChangeDiffUpload:
+ return Frame{}, ErrProtocol
+ case *StepReport:
+ if v.ChangeDiffs != "" {
+ v.ChangeDiffs = ""
+ changed = true
+ }
+ }
+ }
if protocol < ProtocolStuckTasks {
dropped, err := downgradeStuck(body, protocol)
if err != nil {
return Frame{}, err
}
- changed = dropped
+ changed = changed || dropped
}
if protocol < ProtocolChangeFiles {
if v, ok := body.(*StepReport); ok && v.ChangeFiles != nil {
diff --git a/internal/wire/runners_test.go b/internal/wire/runners_test.go
index d54328bd..f98350a3 100644
--- a/internal/wire/runners_test.go
+++ b/internal/wire/runners_test.go
@@ -413,7 +413,7 @@ func TestEncodeBelowProtocol9DropsPreviews(t *testing.T) {
if _, err := wire.Encode(d, wire.ProtocolPreview); err != nil {
t.Fatal(err)
}
- if wire.ProtocolCurrent != wire.ProtocolChangeFiles || wire.ProtocolStuckTasks != 30 || wire.ProtocolPinnedRelease != 29 || wire.ProtocolInjectionDefences != 28 || wire.ProtocolWarm != 24 || wire.ProtocolGlance != 23 || wire.ProtocolJobs != 22 || wire.ProtocolCopy != 21 || wire.ProtocolUsageRefresh != 20 || wire.ProtocolAssistant != 19 || wire.ProtocolModels != 18 || wire.ProtocolOpenCode != 17 || wire.ProtocolPublish != 16 || wire.ProtocolReadings != 15 || wire.ProtocolScheduler != 14 || wire.ProtocolResearch != 13 || wire.ProtocolMetered != 12 || wire.ProtocolPreviewHost != 11 || wire.ProtocolExplore != 10 || wire.ProtocolPreview != 9 {
+ if wire.ProtocolCurrent != wire.ProtocolChangeDiffs || wire.ProtocolStuckTasks != 30 || wire.ProtocolPinnedRelease != 29 || wire.ProtocolInjectionDefences != 28 || wire.ProtocolWarm != 24 || wire.ProtocolGlance != 23 || wire.ProtocolJobs != 22 || wire.ProtocolCopy != 21 || wire.ProtocolUsageRefresh != 20 || wire.ProtocolAssistant != 19 || wire.ProtocolModels != 18 || wire.ProtocolOpenCode != 17 || wire.ProtocolPublish != 16 || wire.ProtocolReadings != 15 || wire.ProtocolScheduler != 14 || wire.ProtocolResearch != 13 || wire.ProtocolMetered != 12 || wire.ProtocolPreviewHost != 11 || wire.ProtocolExplore != 10 || wire.ProtocolPreview != 9 {
t.Fatalf("current %d", wire.ProtocolCurrent)
}
}
diff --git a/internal/wire/schedule_test.go b/internal/wire/schedule_test.go
index 5eab12b5..1c3832e2 100644
--- a/internal/wire/schedule_test.go
+++ b/internal/wire/schedule_test.go
@@ -17,7 +17,7 @@ import (
// refused anything that spends, never handed it), and a dispatch loses
// its priority, deadline and release; what 13 already had is unchanged.
func TestEncodeBelowProtocol14DropsScheduler(t *testing.T) {
- if wire.ProtocolScheduler != wire.Protocol14 || wire.ProtocolCurrent != wire.Protocol31 {
+ if wire.ProtocolScheduler != wire.Protocol14 || wire.ProtocolCurrent != wire.ProtocolChangeDiffs {
t.Fatalf("scheduler %d, current %d", wire.ProtocolScheduler, wire.ProtocolCurrent)
}
by := time.Date(2026, 11, 20, 17, 0, 0, 0, time.UTC)
diff --git a/internal/wire/stuck_test.go b/internal/wire/stuck_test.go
index ea32482a..b733c733 100644
--- a/internal/wire/stuck_test.go
+++ b/internal/wire/stuck_test.go
@@ -14,7 +14,7 @@ import (
// Stuck tasks (protocol 30): a hello's tool health is a fixed state per
// pinned tool, never a path, and an older instance never hears it.
func TestProtocol30ToolHealth(t *testing.T) {
- if wire.ProtocolStuckTasks != wire.Protocol30 || wire.ProtocolCurrent != wire.Protocol31 || wire.Spoken(99) != 31 {
+ if wire.ProtocolStuckTasks != wire.Protocol30 || wire.ProtocolCurrent != wire.ProtocolChangeDiffs || wire.Spoken(99) != 32 {
t.Fatalf("stuck %d, current %d", wire.ProtocolStuckTasks, wire.ProtocolCurrent)
}
caps := func(h *wire.ToolHealth) wire.Capabilities {
diff --git a/internal/wire/tasks.go b/internal/wire/tasks.go
index 32963498..da0c8fa3 100644
--- a/internal/wire/tasks.go
+++ b/internal/wire/tasks.go
@@ -797,6 +797,7 @@ type CancelStepCommand struct {
// once the attempt's namespace exit was observed. Reason is a fixed code.
type StepReport struct {
// Protocol 31: Engineering file-list facts, presentation only.
+ ChangeDiffs string `json:"change_diffs,omitempty"`
ChangeFiles *ChangeFiles `json:"change_files,omitempty"`
BaseChecks string `json:"base_checks,omitempty"`
BaseChecksSHA string `json:"base_checks_sha,omitempty"`
diff --git a/internal/wire/usage_test.go b/internal/wire/usage_test.go
index 5b254189..2ef4ad2e 100644
--- a/internal/wire/usage_test.go
+++ b/internal/wire/usage_test.go
@@ -44,7 +44,7 @@ func headrooms(t *testing.T, raw []byte) []map[string]json.RawMessage {
// decodes strictly against the frozen protocol 14 headroom, and the
// caller's own values are untouched; at 15 nothing changes.
func TestEncodeBelowProtocol15DropsReadingTimes(t *testing.T) {
- if wire.ProtocolReadings != wire.Protocol15 || wire.ProtocolCurrent != wire.Protocol31 {
+ if wire.ProtocolReadings != wire.Protocol15 || wire.ProtocolCurrent != wire.ProtocolChangeDiffs {
t.Fatalf("readings %d, current %d", wire.ProtocolReadings, wire.ProtocolCurrent)
}
at := time.Date(2026, 11, 12, 9, 58, 0, 0, time.UTC)
diff --git a/internal/wire/warm_test.go b/internal/wire/warm_test.go
index 66bd188d..490fdc1c 100644
--- a/internal/wire/warm_test.go
+++ b/internal/wire/warm_test.go
@@ -13,7 +13,7 @@ import (
// other (durable, acked), and Encode refuses it below 24: an older
// runner's strict decoder would close the stream on it.
func TestEncodeWarmBelow24(t *testing.T) {
- if wire.ProtocolWarm != 24 || wire.ProtocolCurrent != wire.ProtocolChangeFiles || wire.Spoken(99) != 31 {
+ if wire.ProtocolWarm != 24 || wire.ProtocolCurrent != wire.ProtocolChangeDiffs || wire.Spoken(99) != 32 {
t.Fatalf("protocols %d %d", wire.ProtocolWarm, wire.ProtocolCurrent)
}
f, err := wire.NewFrame("c1", wire.FrameWarm, wire.WarmCommand{Person: "ana@example.com"})
diff --git a/internal/wire/wireschema/wireschema.go b/internal/wire/wireschema/wireschema.go
index f3644000..568827f2 100644
--- a/internal/wire/wireschema/wireschema.go
+++ b/internal/wire/wireschema/wireschema.go
@@ -43,6 +43,7 @@ var accepted = struct {
// "METHOD /path", the Assistant lane's apart: the Assistant keeps its
// own schemas.
var Ops = map[string]Op{
+ "GET /tasks/{id}/changes/diff": {nil, map[string]any{"200": wire.ChangeDiff{}}},
"GET /messages": {nil, map[string]any{"200": wire.MessagePage{}}},
"POST /messages": {wire.SendMessage{}, map[string]any{"200": wire.Sent{}, "201": wire.Sent{}}},
"POST /attachments": {Bytes{}, map[string]any{"201": wire.MessageAttachment{}}},
@@ -461,6 +462,13 @@ func (g *gen) fields(t reflect.Type, name string, props *ordered, required *[]st
s.set("enum", values)
g.enums[name+"."+key] = true
}
+ if name == "ChangeDiff" && key == "patch" {
+ s.set("maxLength", wire.MaxFileDiffBytes)
+ s.set("description", "Plain unified patch, at most 64 KiB UTF-8 and 2,000 complete lines, only after whole-file scanning. Not HTML.")
+ }
+ if name == "ChangeDiff" && key == "reason" {
+ s.set("enum", []string{wire.DiffBinary, wire.DiffTooLarge, wire.DiffWithheld, wire.DiffUnavailable, wire.DiffExpired})
+ }
if name == "Step" && key == "change_files" {
s.set("description", "Bounded presentation facts, included only on GET /tasks/{id} detail reads. Absent from task lists, snapshots, events and Coordinator tools.")
}
diff --git a/native/apple/Sources/EquipoActivity/Resources/Localizable.xcstrings b/native/apple/Sources/EquipoActivity/Resources/Localizable.xcstrings
index 47e4b98f..52282a22 100644
--- a/native/apple/Sources/EquipoActivity/Resources/Localizable.xcstrings
+++ b/native/apple/Sources/EquipoActivity/Resources/Localizable.xcstrings
@@ -1506,6 +1506,66 @@
}
}
},
+ "native.diff.expired": {
+ "comment": "COPY PENDING: sent to controller, 2026-11-26.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "These changes have expired. Open on Amadan to review them."
+ }
+ }
+ }
+ },
+ "native.diff.too_large": {
+ "comment": "COPY PENDING: sent to controller, 2026-11-26.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "This file is too large to show here."
+ }
+ }
+ }
+ },
+ "native.diff.truncated": {
+ "comment": "COPY PENDING: sent to controller, 2026-11-26.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Only part of this file’s changes is shown. Open on Amadan for the rest."
+ }
+ }
+ }
+ },
+ "native.diff.unavailable": {
+ "comment": "COPY PENDING: sent to controller, 2026-11-26.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "These changes are unavailable. Open on Amadan to review them."
+ }
+ }
+ }
+ },
+ "native.diff.withheld": {
+ "comment": "COPY PENDING: sent to controller, 2026-11-26.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "This file’s changes are hidden because they may contain a secret."
+ }
+ }
+ }
+ },
"native.needs.done_at": {
"extractionState": "manual",
"localizations": {
diff --git a/native/apple/Sources/EquipoKit/API/ChangeDiff.swift b/native/apple/Sources/EquipoKit/API/ChangeDiff.swift
new file mode 100644
index 00000000..5f49e06a
--- /dev/null
+++ b/native/apple/Sources/EquipoKit/API/ChangeDiff.swift
@@ -0,0 +1,60 @@
+import Foundation
+
+struct ChangeDiff: Codable, Sendable, Equatable {
+ var taskId: String
+ var stepId: String
+ var attempt: Int64
+ var base: String
+ var candidateSha: String
+ var status: String
+ var oldPath: String? = nil
+ var path: String
+ var patch: String? = nil
+ var reason: String? = nil
+ var truncated: Bool
+
+ var isValid: Bool {
+ guard !taskId.isEmpty, !stepId.isEmpty, attempt > 0,
+ (base.isEmpty || ThinChangeFiles.commit(base)), ThinChangeFiles.commit(candidateSha),
+ ThinChangeFiles.path(path), ["added", "modified", "deleted", "renamed"].contains(status),
+ (patch ?? "").utf8.count <= 64 * 1024, !(patch ?? "").contains("\0"),
+ (patch ?? "").filter({ $0 == "\n" }).count <= 2000 else { return false }
+ if status == "renamed" {
+ guard let oldPath, ThinChangeFiles.path(oldPath), oldPath != path else { return false }
+ } else if oldPath != nil { return false }
+ if let reason {
+ return ["binary", "too_large", "withheld", "unavailable", "expired"].contains(reason)
+ && (patch ?? "").isEmpty && !truncated
+ }
+ return (patch ?? "").isEmpty || patch?.hasSuffix("\n") == true
+ }
+ struct Line: Identifiable, Equatable {
+ enum Kind { case added, removed, context }
+ let id: Int
+ let text: String
+ var kind: Kind {
+ if text.hasPrefix("+") && !text.hasPrefix("+++") { return .added }
+ if text.hasPrefix("-") && !text.hasPrefix("---") { return .removed }
+ return .context
+ }
+ }
+ var lines: [Line] {
+ var lines = (patch ?? "").components(separatedBy: "\n")
+ if lines.last == "" { lines.removeLast() }
+ return lines.enumerated().map { Line(id: $0.offset, text: $0.element) }
+ }
+}
+extension EquipoClient {
+ func changeDiff(task: String, candidate: String, path: String) async throws -> ChangeDiff {
+ guard ThinChangeFiles.commit(candidate), ThinChangeFiles.path(path) else { throw EquipoAPIError.undecodable }
+ var request = APIRequest("GET", "/tasks/\(escape(task))/changes/diff",
+ query: [URLQueryItem(name: "candidate_sha", value: candidate), URLQueryItem(name: "path", value: path)], bearer: token)
+ request.maximumResponseBytes = 128 * 1024
+ let response = try await transport.send(request)
+ guard (200..<300).contains(response.status) else { throw Self.error(response) }
+ guard response.data.count <= request.maximumResponseBytes else { throw EquipoAPIError.tooLarge }
+ guard let diff = try? EquipoJSON.decoder.decode(ChangeDiff.self, from: response.data), diff.isValid,
+ diff.taskId == task, diff.candidateSha == candidate, diff.path == path else { throw EquipoAPIError.undecodable }
+ return diff
+ }
+}
diff --git a/native/apple/Sources/EquipoKit/Presentation/ChangeDiffModel.swift b/native/apple/Sources/EquipoKit/Presentation/ChangeDiffModel.swift
new file mode 100644
index 00000000..96a4e2ef
--- /dev/null
+++ b/native/apple/Sources/EquipoKit/Presentation/ChangeDiffModel.swift
@@ -0,0 +1,34 @@
+import Foundation
+import Observation
+
+@MainActor @Observable final class ChangeDiffModel {
+ private(set) var diff: ChangeDiff?
+ private(set) var failure: String?
+ private(set) var loading = false
+ private var generation = UUID()
+
+ func clear() { generation = UUID(); diff = nil; failure = nil; loading = false }
+ func load(client: EquipoClient, task: String, candidate: String, path: String) async {
+ clear()
+ let generation = generation
+ loading = true
+ do {
+ let result = try await client.changeDiff(task: task, candidate: candidate, path: path)
+ guard generation == self.generation, !Task.isCancelled else { return }
+ diff = result
+ } catch {
+ guard generation == self.generation, !Task.isCancelled else { return }
+ if let api = error as? EquipoAPIError, api.status == 409, api.code == "preview_changed" {
+ failure = EquipoStrings.text("api.preview_changed")
+ } else { failure = StoppedWorkActions.logFailure(error) }
+ }
+ loading = false
+ }
+}
+
+struct ChangeDiffSelection: Identifiable {
+ let task: ThinTask
+ let facts: ThinChangeFiles
+ let file: ThinChangedFile
+ var id: String { task.id + ":" + facts.sha + ":" + file.path }
+}
diff --git a/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings b/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings
index 47e4b98f..52282a22 100644
--- a/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings
+++ b/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings
@@ -1506,6 +1506,66 @@
}
}
},
+ "native.diff.expired": {
+ "comment": "COPY PENDING: sent to controller, 2026-11-26.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "These changes have expired. Open on Amadan to review them."
+ }
+ }
+ }
+ },
+ "native.diff.too_large": {
+ "comment": "COPY PENDING: sent to controller, 2026-11-26.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "This file is too large to show here."
+ }
+ }
+ }
+ },
+ "native.diff.truncated": {
+ "comment": "COPY PENDING: sent to controller, 2026-11-26.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Only part of this file’s changes is shown. Open on Amadan for the rest."
+ }
+ }
+ }
+ },
+ "native.diff.unavailable": {
+ "comment": "COPY PENDING: sent to controller, 2026-11-26.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "These changes are unavailable. Open on Amadan to review them."
+ }
+ }
+ }
+ },
+ "native.diff.withheld": {
+ "comment": "COPY PENDING: sent to controller, 2026-11-26.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "This file’s changes are hidden because they may contain a secret."
+ }
+ }
+ }
+ },
"native.needs.done_at": {
"extractionState": "manual",
"localizations": {
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/ChangeDiffSheet.swift b/native/apple/Sources/EquipoKit/UI/Screens/ChangeDiffSheet.swift
new file mode 100644
index 00000000..79bccee8
--- /dev/null
+++ b/native/apple/Sources/EquipoKit/UI/Screens/ChangeDiffSheet.swift
@@ -0,0 +1,112 @@
+import SwiftUI
+
+struct ChangeDiffSheet: View {
+ let selection: ChangeDiffSelection
+ let session: EquipoSession
+ @Environment(\.dismiss) private var dismiss
+ @State private var model = ChangeDiffModel()
+
+ var body: some View {
+ NavigationStack {
+ VStack(alignment: .leading, spacing: 12) {
+ ScrollView(axes) {
+ VStack(alignment: .leading, spacing: 12) {
+ Text(verbatim: selection.file.path).font(.system(.subheadline, design: .monospaced))
+ .textSelection(.enabled).fixedSize(horizontal: false, vertical: true)
+ Text(ChangedFilesPresentation.status(selection.file)).font(Typo.caption).foregroundStyle(Palette.secondary)
+ if model.loading { ProgressView().accessibilityLabel(EquipoStrings.text("native.task.changes")) }
+ if let failure = model.failure {
+ Text(failure).foregroundStyle(Palette.negative)
+ Button(EquipoStrings.text("read.retry")) { Task { await load() } }
+ }
+ if let diff = model.diff {
+ if let reason = diff.reason { Text(EquipoStrings.text(reasonKey(reason))).fixedSize(horizontal: false, vertical: true) }
+ else {
+ if diff.truncated { Text(EquipoStrings.text("native.diff.truncated")).font(Typo.secondary) }
+ DiffText(diff: diff).padding(12)
+ .background(Palette.surface2, in: .rect(cornerRadius: 8))
+ }
+ }
+ }.frame(maxWidth: .infinity, alignment: .leading)
+ }.defaultScrollAnchor(.topLeading)
+ Button(EquipoStrings.text("work.open")) {
+ if let url = ChangedFilesPresentation.fileURL(task: selection.task, facts: selection.facts, file: selection.file) {
+ session.settings.openChanges(origin: session.origin, url: url)
+ } else { session.settings.open(origin: session.origin, path: "/tasks/\(selection.task.id)") }
+ }.buttonStyle(.bordered).frame(minHeight: 44)
+ }.padding(16).background(Palette.background)
+ .navigationTitle(EquipoStrings.text("native.task.changes"))
+ .toolbar { ToolbarItem(placement: .cancellationAction) { Button(EquipoStrings.text("team.close")) { dismiss() } } }
+ }
+ #if os(macOS)
+ .frame(minWidth: 560, idealWidth: 800, minHeight: 420, idealHeight: 640)
+ #endif
+ .task(id: selection.id) { await load() }
+ .onDisappear { model.clear() }
+ }
+ private var axes: Axis.Set {
+ #if os(iOS)
+ .vertical
+ #else
+ [.vertical, .horizontal]
+ #endif
+ }
+ private func load() async { await model.load(client: session.client, task: selection.task.id, candidate: selection.facts.sha, path: selection.file.path) }
+ private func reasonKey(_ reason: String) -> String.LocalizationValue {
+ switch reason {
+ case "binary": "native.changes.binary"
+ case "withheld": "native.diff.withheld"
+ case "too_large": "native.diff.too_large"
+ case "expired": "native.diff.expired"
+ default: "native.diff.unavailable"
+ }
+ }
+}
+
+private struct DiffText: View {
+ let diff: ChangeDiff
+ var body: some View {
+ #if os(iOS)
+ WrappingDiffText(diff: diff)
+ #else
+ Text(attributed).font(.system(.caption, design: .monospaced)).textSelection(.enabled).fixedSize()
+ #endif
+ }
+ private var attributed: AttributedString {
+ var result = AttributedString()
+ for line in diff.lines {
+ var text = AttributedString(line.text + "\n")
+ text.foregroundColor = line.kind == .added ? Palette.positive : line.kind == .removed ? Palette.negative : Palette.text
+ result.append(text)
+ }
+ return result
+ }
+}
+
+#if os(iOS)
+import UIKit
+private struct WrappingDiffText: UIViewRepresentable {
+ let diff: ChangeDiff
+ func makeUIView(context: Context) -> UITextView {
+ let view = UITextView()
+ view.isEditable = false; view.isSelectable = true; view.isScrollEnabled = false
+ view.backgroundColor = .clear; view.textContainerInset = .zero
+ view.textContainer.lineFragmentPadding = 0; view.textContainer.lineBreakMode = .byCharWrapping
+ view.adjustsFontForContentSizeCategory = true
+ return view
+ }
+ func updateUIView(_ view: UITextView, context: Context) {
+ let text = NSMutableAttributedString(string: "")
+ let font = UIFontMetrics(forTextStyle: .caption1).scaledFont(for: .monospacedSystemFont(ofSize: 12, weight: .regular))
+ for line in diff.lines {
+ let color = line.kind == .added ? Palette.positive : line.kind == .removed ? Palette.negative : Palette.text
+ text.append(NSAttributedString(string: line.text + "\n", attributes: [.font: font, .foregroundColor: UIColor(color)]))
+ }
+ view.attributedText = text
+ }
+ func sizeThatFits(_ proposal: ProposedViewSize, uiView: UITextView, context: Context) -> CGSize? {
+ guard let width = proposal.width else { return nil }
+ return uiView.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude))
+ }
+}
+#endif
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/ChangedFilesList.swift b/native/apple/Sources/EquipoKit/UI/Screens/ChangedFilesList.swift
index ac703386..06f4a7be 100644
--- a/native/apple/Sources/EquipoKit/UI/Screens/ChangedFilesList.swift
+++ b/native/apple/Sources/EquipoKit/UI/Screens/ChangedFilesList.swift
@@ -59,7 +59,7 @@ private struct ChangedFileLabel: View {
}
}.font(.system(.caption, design: .monospaced))
}.frame(maxWidth: .infinity, alignment: .leading)
- Image(systemName: "arrow.up.right").font(.caption).foregroundStyle(Palette.secondary)
+ Image(systemName: "chevron.right").font(.caption).foregroundStyle(Palette.secondary)
}.padding(.vertical, 12).frame(minHeight: 44).contentShape(Rectangle())
}
}
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/TaskDetailScreen.swift b/native/apple/Sources/EquipoKit/UI/Screens/TaskDetailScreen.swift
index bea29989..3a805779 100644
--- a/native/apple/Sources/EquipoKit/UI/Screens/TaskDetailScreen.swift
+++ b/native/apple/Sources/EquipoKit/UI/Screens/TaskDetailScreen.swift
@@ -20,6 +20,7 @@ public struct TaskScreen: View {
@State private var model: TaskDetailModel
@State private var tab: TaskDetailTab = .overview
@State private var talking = false
+ @State private var diffSelection: ChangeDiffSelection?
public init(session: EquipoSession, taskID: String) {
_model = State(initialValue: TaskDetailModel(session: session, taskID: taskID))
}
@@ -49,9 +50,7 @@ public struct TaskScreen: View {
case .changes:
if let facts = model.changeFiles {
ChangedFilesList(facts: facts) { file in
- if let url = ChangedFilesPresentation.fileURL(task: task, facts: facts, file: file) {
- model.session.settings.openChanges(origin: model.session.origin, url: url)
- } else { openWeb(task) }
+ diffSelection = ChangeDiffSelection(task: task, facts: facts, file: file)
}
}
webEvidence(task, preview: false)
@@ -73,6 +72,12 @@ public struct TaskScreen: View {
.scrollDismissesKeyboard(.interactively)
.background(Palette.background)
#if DEBUG
+ .task(id: model.changeFiles?.sha) {
+ if ProcessInfo.processInfo.environment["EQUIPO_TASK_FIXTURE"] == "changes-diff",
+ let facts = model.changeFiles, let file = facts.entries.first, let task = model.task {
+ diffSelection = ChangeDiffSelection(task: task, facts: facts, file: file)
+ }
+ }
.onAppear {
if (ProcessInfo.processInfo.environment["EQUIPO_TASK_FIXTURE"] ?? "").hasPrefix("changes") { tab = .changes }
}
@@ -80,6 +85,10 @@ public struct TaskScreen: View {
.task(id: model.session.task(model.taskID)?.revision) { await model.load() }
.refreshable { await model.session.refresh(); await model.load() }
.sheet(item: $model.confirmation) { confirm in TaskConfirmationSheet(model: model, confirmation: confirm) }
+ .sheet(item: $diffSelection) { selection in ChangeDiffSheet(selection: selection, session: model.session) }
+ .onChange(of: model.task?.candidateSha) { _, candidate in
+ if diffSelection?.facts.sha != candidate { diffSelection = nil }
+ }
.sheet(isPresented: $model.moving) { TaskMoveSheet(model: model) }
.modifier(PreviewSheetPresenter(session: model.session))
.onDisappear { model.session.previews.dismiss() }
diff --git a/native/apple/Sources/EquipoKit/UI/TaskViewFixture.swift b/native/apple/Sources/EquipoKit/UI/TaskViewFixture.swift
index f8c2ce5e..7238449b 100644
--- a/native/apple/Sources/EquipoKit/UI/TaskViewFixture.swift
+++ b/native/apple/Sources/EquipoKit/UI/TaskViewFixture.swift
@@ -30,8 +30,8 @@ public struct TaskViewFixture: View {
#if os(macOS)
if let path = ProcessInfo.processInfo.environment["EQUIPO_FIXTURE_CAPTURE"] {
try? await Task.sleep(for: .seconds(2))
- if let window = NSApp.windows.first(where: { $0.isVisible && !$0.isSheet }), let view = window.contentView {
- window.setContentSize(NSSize(width: 800, height: 1000))
+ if let window = NSApp.windows.first(where: { $0.isVisible && $0.isSheet }) ?? NSApp.windows.first(where: { $0.isVisible && !$0.isSheet }), let view = window.contentView {
+ window.setContentSize(NSSize(width: 800, height: window.isSheet ? 600 : 1000))
view.layoutSubtreeIfNeeded(); window.displayIfNeeded()
if let bitmap = view.bitmapImageRepForCachingDisplay(in: view.bounds) {
view.cacheDisplay(in: view.bounds, to: bitmap)
@@ -57,6 +57,12 @@ private struct TaskViewFixtureTransport: EquipoTransport {
value = ["me": ["id": "fixture", "address": "paul@example.com", "role": "owner", "team_id": "fixture", "team_name": "Oficina", "revision": 1], "cursor": 1, "tasks": [task], "messages": [], "turns": [], "cards": failed ? [] : [card], "projects": []]
case "/tasks", "/needs-you": value = ["items": [task]]
case "/tasks/tk_fixture": value = task
+ case "/tasks/tk_fixture/changes/diff":
+ let path = request.query.first(where: { $0.name == "path" })?.value ?? "Sources/Session/EquipoSession.swift"
+ value = ["task_id": "tk_fixture", "step_id": "engineering", "attempt": 1,
+ "base": String(repeating: "a", count: 40), "candidate_sha": candidate,
+ "path": path, "status": "modified", "truncated": false,
+ "patch": "diff --git a/Sources/Session/EquipoSession.swift b/Sources/Session/EquipoSession.swift\n--- a/Sources/Session/EquipoSession.swift\n+++ b/Sources/Session/EquipoSession.swift\n@@ -42,6 +42,8 @@\n func signOut() {\n+ needsYouCount = 0\n+ accountGeneration += 1\n credential = nil\n- refreshBadge()\n+ notifications.updateBadge(count: 0, account: signedOutAccount, reason: .signedOut)\n }\n"]
case "/steps/checks/log": value = ["step_id": "checks", "attempt": 1, "tail": hosted ? "Hosted CI on oficina/equipo at 3f9c2a1: failed.\nFailed: format; check shard 5 of 23\n=== format\nThe changed Swift file needs formatting.\n=== check shard 5 of 23\nTest needsBadgeClearsAfterSignOut failed\nExpected: 0\nReceived: 1\n" : "=== formatting\nFormatting passed.\n=== native-tests\nRunning EquipoKitTests\nTest needsBadgeClearsAfterSignOut failed\nExpected: 0\nReceived: 1\nThe signed-out account still contributes to the Needs you badge.\nexit status 1"]
case "/projects": value = ["items": [], "allowed": ["oficina/equipo", "oficina/notes"]]
default: value = [:]
diff --git a/native/apple/Tests/EquipoKitTests/ChangeDiffTests.swift b/native/apple/Tests/EquipoKitTests/ChangeDiffTests.swift
new file mode 100644
index 00000000..14015eb6
--- /dev/null
+++ b/native/apple/Tests/EquipoKitTests/ChangeDiffTests.swift
@@ -0,0 +1,72 @@
+import Foundation
+import Testing
+@testable import EquipoKit
+
+@MainActor @Suite struct ChangeDiffTests {
+ static let sha = String(repeating: "b", count: 40)
+ static let base = String(repeating: "a", count: 40)
+ static func value() -> ChangeDiff {
+ .init(taskId: "tk1", stepId: "s1", attempt: 1, base: base, candidateSha: sha,
+ status: "modified", path: "dir/space 日本語.txt", patch: "@@ -1 +1 @@\n-old\n+new\n", truncated: false)
+ }
+ @Test func responseBindingsBoundsAndPlainLineStyles() async throws {
+ let server = ScriptedTransport(), good = Self.value()
+ let key = "GET /tasks/tk1/changes/diff"
+ server.on(key, .success(APIResponse(status: 200, data: try EquipoJSON.encoder.encode(good))))
+ let client = EquipoClient(transport: server, token: "device-bearer")
+ let read = try await client.changeDiff(task: "tk1", candidate: Self.sha, path: good.path)
+ #expect(read == good)
+ let request = try #require(server.sent(key).first)
+ #expect(request.bearer == "device-bearer")
+ #expect(request.maximumResponseBytes == 128 * 1024)
+ #expect(request.query == [URLQueryItem(name: "candidate_sha", value: Self.sha), URLQueryItem(name: "path", value: good.path)])
+ #expect(read.lines.map(\.kind) == [.context, .removed, .added])
+ var oversized = Data(repeating: 32, count: 128 * 1024)
+ oversized.append(try EquipoJSON.encoder.encode(good))
+ server.replace(key, with: .success(APIResponse(status: 200, data: oversized)))
+ await #expect(throws: (any Error).self) { try await client.changeDiff(task: "tk1", candidate: Self.sha, path: good.path) }
+
+ for mutation in ["task", "candidate", "path", "bytes", "lines", "reason", "withheld", "old"] {
+ var bad = good
+ switch mutation {
+ case "task": bad.taskId = "other"
+ case "candidate": bad.candidateSha = Self.base
+ case "path": bad.path = "other"
+ case "bytes": bad.patch = String(repeating: "x", count: 65536) + "\n"
+ case "lines": bad.patch = String(repeating: "+\n", count: 2001)
+ case "reason": bad.reason = "unknown"
+ case "withheld": bad.reason = "withheld"
+ default: bad.oldPath = "../bad"
+ }
+ server.replace(key, with: .success(APIResponse(status: 200, data: try EquipoJSON.encoder.encode(bad))))
+ await #expect(throws: (any Error).self) { try await client.changeDiff(task: "tk1", candidate: Self.sha, path: good.path) }
+ }
+ }
+ @Test func selectionChangeDropsLateResponse() async throws {
+ let server = ScriptedTransport()
+ let gate = DiffReadGate(base: server)
+ server.on("GET /tasks/tk1/changes/diff", .success(APIResponse(status: 200, data: try EquipoJSON.encoder.encode(Self.value()))))
+ let model = ChangeDiffModel()
+ let job = Task { await model.load(client: EquipoClient(transport: gate, token: "device"), task: "tk1", candidate: Self.sha, path: Self.value().path) }
+ await gate.waitUntilHeld()
+ model.clear()
+ await gate.release()
+ await job.value
+ #expect(model.diff == nil)
+ }
+}
+
+private actor DiffReadGate: EquipoTransport {
+ nonisolated let origin = URL(string: "https://oficina.example.test")!
+ nonisolated let base: ScriptedTransport
+ init(base: ScriptedTransport) {self.base=base}
+ var held=false
+ var continuation: CheckedContinuation<Void,Never>?
+ func waitUntilHeld() async {while !held {await Task.yield()}}
+ func release(){continuation?.resume();continuation=nil}
+ func send(_ request: APIRequest) async throws -> APIResponse {
+ held=true;await withCheckedContinuation {continuation=$0}
+ return try await base.send(request)
+ }
+ func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String,Error> {try await base.lines(request)}
+}
diff --git a/native/ios/UITests/TaskViewUITests.swift b/native/ios/UITests/TaskViewUITests.swift
index d9c43172..1851b938 100644
--- a/native/ios/UITests/TaskViewUITests.swift
+++ b/native/ios/UITests/TaskViewUITests.swift
@@ -1,6 +1,18 @@
import XCTest
final class TaskViewUITests: XCTestCase {
+ @MainActor func testChangedFileDiffWrapsAndKeepsAmadan() {
+ for large in [false, true] {
+ let app = launch("changes-diff", large: large)
+ XCTAssertTrue(app.buttons["Open on Amadan"].waitForExistence(timeout: 15))
+ XCTAssertTrue(app.textViews.firstMatch.waitForExistence(timeout: 10))
+ XCTAssertTrue((app.textViews.firstMatch.value as? String ?? "").contains("reason: .signedOut)"))
+ XCTAssertLessThanOrEqual(app.textViews.firstMatch.frame.width, app.frame.width)
+ capture(large ? "iphone-diff-large" : "iphone-diff")
+ app.terminate()
+ }
+ }
+
@MainActor func testChangedFilesAndOldRunnerFallback() {
let app = launch("changes")
XCTAssertTrue(app.buttons["changed-file-Sources/Session/EquipoSession.swift"].waitForExistence(timeout: 15))
diff --git a/native/scripts/check-strings.py b/native/scripts/check-strings.py
index b8a05da1..c3b4dc8f 100755
--- a/native/scripts/check-strings.py
+++ b/native/scripts/check-strings.py
@@ -18,7 +18,7 @@ plurals = json.loads((native / 'scripts/plurals.json').read_text())
def catalog():
return {'sourceLanguage': 'en', 'version': '1.0', 'strings': {
- k: {**({'comment': 'COPY APPROVED: Luna, 2026-11-26.'} if k.startswith('native.changes.') or k in ('api.preview_changed', 'api.preview_expired') else {}), 'extractionState': 'manual', 'localizations': {'en': plurals.get(k, {'stringUnit': {'state': 'translated', 'value': v}})}}
+ k: {**({'comment': 'COPY PENDING: sent to controller, 2026-11-26.'} if k.startswith('native.diff.') else {'comment': 'COPY APPROVED: Luna, 2026-11-26.'} if k.startswith('native.changes.') or k in ('api.preview_changed', 'api.preview_expired') else {}), 'extractionState': 'manual', 'localizations': {'en': plurals.get(k, {'stringUnit': {'state': 'translated', 'value': v}})}}
for k, v in sorted(source.items())}}
def used_keys():
diff --git a/native/scripts/strings.json b/native/scripts/strings.json
index 80aa2cf9..7104c5f1 100644
--- a/native/scripts/strings.json
+++ b/native/scripts/strings.json
@@ -502,5 +502,10 @@
"work.merged": "Merged into %@ at %@",
"native.needs.merged_at": "Merged into %1$@ at %2$@",
"api.preview_changed": "The change has been updated. Review it again.",
- "api.preview_expired": "This preview expired. Open it again."
+ "api.preview_expired": "This preview expired. Open it again.",
+ "native.diff.withheld": "This file’s changes are hidden because they may contain a secret.",
+ "native.diff.too_large": "This file is too large to show here.",
+ "native.diff.unavailable": "These changes are unavailable. Open on Amadan to review them.",
+ "native.diff.expired": "These changes have expired. Open on Amadan to review them.",
+ "native.diff.truncated": "Only part of this file’s changes is shown. Open on Amadan for the rest."
}