oficina / equipo Public

fix: apply the Plan 3 final review fix wave

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev b7a90575b5b5b44f912ba16892fe21571b760a2b parent 1e2c5d4
53 files changed, +1,088 −181
  • docs/live-gate.md +1 −1
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +92 −0
  • internal/equipo/conversation/coordinator_application.go +1 −0
  • internal/equipo/conversation/live.go +22 −16
  • internal/equipo/conversation/tools.go +1 −1
  • internal/equipo/conversation_handlers.go +2 −2
  • internal/equipo/conversation_read_test.go +31 −0
  • internal/equipo/coordinator.go +4 −1
  • internal/equipo/copy.go +2 −0
  • internal/equipo/library/counts.go +7 −56
  • internal/equipo/migrations/0032_plan_defaults.sql +12 −0
  • internal/equipo/migrations/0033_plan_notifications.sql +21 −0
  • internal/equipo/migrations/schema.sql +7 −9
  • internal/equipo/migrations_test.go +11 −1
  • internal/equipo/person_api_mutations.go +1 −1
  • internal/equipo/personapi/conversation.go +10 −2
  • internal/equipo/personapi/devices.go +21 −6
  • internal/equipo/personapi/extended_mutations.go +42 −17
  • internal/equipo/personapi/native.go +1 −0
  • internal/equipo/plan_selection.go +5 −0
  • internal/equipo/planning/approval_settings.go +5 −2
  • internal/equipo/planning/dispatch.go +1 −1
  • internal/equipo/planning/plans.go +42 −4
  • internal/equipo/planning/selection.go +5 −5
  • internal/equipo/planning/selection_policy.go +3 −3
  • internal/equipo/planning/selection_validation.go +50 −0
  • internal/equipo/planning/views.go +7 −5
  • internal/equipo/plans.go +21 −4
  • internal/equipo/runner_execution.go +5 −2
  • internal/equipo/templates/plan.html +3 −3
  • internal/plan3test/coordinator_migration_test.go +2 −2
  • internal/plan3test/finalfix_authority_test.go +109 −0
  • internal/plan3test/finalfix_counts_test.go +56 −0
  • internal/plan3test/finalfix_install_test.go +20 −0
  • internal/plan3test/finalfix_live_test.go +47 −0
  • internal/plan3test/finalfix_migration_test.go +14 −0
  • internal/plan3test/finalfix_notifications_test.go +63 −0
  • internal/plan3test/finalfix_revisions_test.go +53 −0
  • internal/plan3test/migration_test.go +2 −2
  • internal/plan3test/notifications_fixture.go +5 −0
  • internal/plan3test/notifications_lifecycle_test.go +6 −3
  • internal/plan3test/notifications_migration_test.go +3 −3
  • internal/plan3test/notifications_test.go +7 −4
  • internal/plan3test/onboarding_acceptance_test.go +2 −2
  • internal/plan3test/person_api_migration_test.go +2 −2
  • internal/plan3test/plan3_upgrade_test.go +15 −3
  • internal/plan3test/plan_model_choice_test.go +1 −1
  • internal/plan3test/plan_workflow_test.go +33 −1
  • internal/plan3test/plans_migration_test.go +2 −2
  • internal/runner/setup/account_command.go +15 −3
  • internal/runner/setup/account_login.go +35 −10
  • internal/runner/setup/account_login_test.go +159 −0
  • scripts/runner-reference-allowlist.json +1 −1
diff --git a/docs/live-gate.md b/docs/live-gate.md
index e5b939e1..12985074 100644
--- a/docs/live-gate.md
+++ b/docs/live-gate.md
@@ -94,7 +94,7 @@ launch evidence.
credential contents, hashes, sign-in links or bearer tokens into evidence.
5. Configure the runner environment file at
- `$HOME/.config/equipo-runner/runner.env`, mode 0600. Set every value to the
+ `$HOME/.local/share/equipo-runner/runner.env`, mode 0600. Set every value to the
intended instance and an absolute path on docs-t1:
```text
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index 49db5cf6..3a40a691 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -5097,6 +5097,7 @@ records to satisfy a gate. Release remains blocked while any row is pending.
| `docs/mockups/onboarding.html / Safe first task` | Start with a recommendation in your conversation. Ask what to work on next. | 16 | Proposal only; COPY REVIEW REQUIRED |
| `docs/mockups/onboarding.html / actual time` | 4 Nov 2026, 10:00 UTC | 16 | Proposal only; COPY REVIEW REQUIRED |
| `docs/mockups/onboarding.html / paired without account` | Waiting for a model account. | 16 | Proposal only; COPY REVIEW REQUIRED |
+| `plan.awaiting_approval` | Waiting for your plan approval | Final review fix wave | COPY REVIEW REQUIRED |
## Task 21
@@ -5407,3 +5408,94 @@ The load run recorded at least 20 in 30 of 35 five-second samples. All load work
`CGO_ENABLED=0 go vet` and `CGO_ENABLED=0 go run honnef.co/go/tools/cmd/staticcheck@v0.7.0` passed on the absolute package path. `gofmt -l` on that directory and `git diff --check` were clean. No production Go code changed and no app-owned runtime strings were added. Full CI remains the controller's work.
Full report and retained evidence: `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/dlfix-report.md` and its adjacent `dlfix-*.log` / `dlfix-load.json` files. No push, live provider run, agents, HANDOFF.md or review server.
+
+
+## Final review fix wave
+
+Scope: I1–I4, M1–M8, the installer environment path and transient account-login polling. Controller rulings limit plan edits, selections, project correction and approval to the requester. Coordinator proposals carry a delegated principal and their own request namespace. I5 and the full CI/live gates remain the controller's work; this wave does not run `make ci` or live providers.
+
+TDD commands use `CGO_ENABLED=0 go test` with absolute package paths and `-count=1`. Unless stated otherwise the package is `/home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test`.
+
+| Test selection | Red evidence (exit 1) | Green evidence |
+| --- | --- | --- |
+| `TestFinalFixRequesterAuthority` | Another owner approved/edited; foreign execution controls visible; requester mode missing | Exit 0 after shared requester checks and requester mode rendering |
+| `TestFinalFixPlanSelections` | Propose/edit persisted foreign connection and unknown model | Exit 0 after transaction-bound eligibility checks |
+| `TestFinalFixSpecialistCounts` | Product/copy/design work counted under Engineering and Review | Exit 0 after counting persisted specialist steps |
+| `TestPlanWorkflowInvestigationCheckpoint` | Replacement stayed proposed with task.wait.setup on second runner | Exit 0 through prepare, new job and claim of reused research key |
+| `TestFinalFixApprovalWait` | Proposed wait was task.wait.setup; started wait was empty | Exit 0 with plan.awaiting_approval |
+| `TestPlan3Upgrade/main` | Baseline lacked system.migration.direct_reconcile audit event | Exit 0 with 0001–0018 plus 0019_direct_reconcile, retained data and repeated reopen |
+| `TestFinalFixSQLDefaults` | Defaults were double-quoted bug/empty strings | Exit 0 with follow-up 0032; 0020 unchanged |
+| `TestFinalFixOwnPlanNotifications` and `TestFinalFixCoordinatorNotification` | Own propose/edit/approve notified; approval left unread entry | Exit 0 with follow-up 0033 |
+| `TestFinalFixConversationReadLookup` | Subscription acquired the writer once | Exit 0 with read handle and thread-ID lookup |
+| `TestFinalFixDeviceExchangeRevision` | ETag was 3 with persisted revision 18 | Exit 0 reading persisted revision |
+| `TestFinalFixAckRevision` | ETag/body were 4 with persisted revision 9 after a fixture trigger | Exit 0 reading resource revision |
+| `TestFinalFixAccountTransientPoll` in `/home/paulca/amadan.net/oficina/equipo-plan-3/internal/runner/setup` | Network error cancelled in-progress login | Exit 0, home retained and polling resumed |
+| `TestFinalFixAccountPollBackoff` in the same setup package | Only two instance calls; transient poll not retried | Exit 0, first poll at least 1s and first retry at least 2s |
+| `TestFinalFixLiveGateRunnerEnvironment` | Checklist path differed from installer | Exit 0 after restoring installer-default path |
+
+New copy: `plan.awaiting_approval` = “Waiting for your plan approval”. COPY REVIEW REQUIRED. No copy-review server or live provider session was used.
+
+
+### Guard mutations
+
+Each mutation was applied alone, its test failed with exit 1, and the original file was restored in a `finally` block. No mutation remains. The final package runs verify the restored source.
+
+| Guard disabled | Command | Failed assertion |
+| --- | --- | --- |
+| I1-approve | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixRequesterAuthority/owner/approve$ -count=1` | non-requester approved <nil> |
+| I2-edit | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixRequesterAuthority/owner/edit$ -count=1` | non-requester edited <nil> |
+| I2-correct | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixRequesterAuthority/owner/correct$ -count=1` | non-requester corrected project <nil> |
+| I2-connection | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixPlanSelections/edit/foreign$ -count=1` | invalid requester selection persisted <nil> |
+| I2-model | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixPlanSelections/edit/unknown-model$ -count=1` | invalid requester selection persisted <nil> |
+| I3-counts | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixSpecialistCounts$ -count=1` | non-participating engineering counted: {Tasks:[] Working:0 Queued:1 Finished:0 Waiting:0 CountsKnown:true UsageKnown:true InputTokens:0 OutputToken... |
+| I4-actual | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestPlanWorkflowInvestigationCheckpoint$ -count=1` | replacement did not prepare on new runner proposed task.wait.setup |
+| I4-runner | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestPlanWorkflowInvestigationCheckpoint$ -count=1` | sql: no rows in result set |
+| I4-dedup | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestPlanWorkflowInvestigationCheckpoint$ -count=1` | sql: no rows in result set |
+| M1-code | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixApprovalWait$ -count=1` | approval wait mislabelled task.wait.setup |
+| M1-running | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixApprovalWait/started$ -count=1` | approval wait mislabelled |
+| M2-baseline | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestPlan3Upgrade/main$ -count=1` | main baseline missing 0019_direct_reconcile |
+| M3-defaults | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixSQLDefaults$ -count=1` | kind default "bug", want 'bug' |
+| M4-notifications | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixOwnPlanNotifications$ -count=1` | own proposal notified |
+| M5-principal | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixCoordinatorNotification$ -count=1` | coordinator used person's request namespace |
+| M6-read | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixConversationReadLookup$ -count=1` | live subscription acquired writer 1 |
+| M6-lookup | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixConversationReadLookup$ -count=1` | thread lookup scanned team |
+| M7-mode | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixRequesterAuthority/owner/read$ -count=1` | requester and project approval modes missing |
+| M8-exchange | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixDeviceExchangeRevision$ -count=1` | synthetic exchange revision "3" |
+| M8-ack | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixAckRevision$ -count=1` | synthetic ack revision map[Cache-Control:[no-store] Content-Type:[application/json] Etag:["4"]] {"revision":4} |
+| login-preserve | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/runner/setup -run ^TestFinalFixAccountTransientPoll$ -count=1` | network error cancelled in-progress login |
+| login-cadence | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/runner/setup -run ^TestFinalFixAccountPollBackoff$ -count=1` | poll interval or backoff too short [2026-11-04 16:10:18.392904171 +0000 GMT m=+0.000588004 2026-11-04 16:10:18.498834122 +0000 GMT m=+0.106517965 2... |
+| live-doc | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixLiveGateRunnerEnvironment$ -count=1` | live-gate environment path differs from installer |
+| M4-clear-wait | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixOwnPlanNotifications$ -count=1` | own edit notified |
+| M4-immediate | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixImmediateCoordinatorNotification$ -count=1` | automatic plan notified for approval |
+| M8-generic-ack | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixAckReadback$ -count=1` | ack did not read the stored revision {"revision":2} |
+| M8-self-demotion | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test -run ^TestFinalFixAckSelfDemotion$ -count=1` | HTTP 403, want 200: {"code":"forbidden","copy_key":"roster.forbidden","request_id":"demote"} |
+| login-expiry | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/runner/setup -run ^TestFinalFixAccountTransientExpiry$ -count=1` | expired offline login left provider running runner_transient false |
+| login-cap | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/runner/setup -run ^TestFinalFixAccountBackoffBound$ -count=1` | unbounded backoff 32s |
+| login-final-authority | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/runner/setup -run ^TestFinalFixAccountAuthorityAfterProbe$ -count=1` | saved without current instance authority <nil> 1 |
+| M6-reader-pool | `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipo -run ^TestConversationSubscriptionUsesReaderPool$ -count=1` | conversation subscription waited for writer pool context deadline exceeded |
+
+The first M4 immediate-policy mutation changed only the supersession predicate and survived. The refined mutation changed the eligibility predicate for notification insertion too; `TestFinalFixImmediateCoordinatorNotification` then failed. Both attempts were restored.
+
+Additional red/green cases: `TestFinalFixAccountTransientExpiry` initially left the provider running (exit 1); it now cancels before removing an expired setup. `TestFinalFixAccountAuthorityAfterProbe` initially saved after authority changed (exit 1); it now repeats the instance check after identity verification and retains the verified binding only for transient retries. `TestFinalFixAckSelfDemotion` initially returned 403 after a successful write (exit 1); it now returns the actual member revision. `TestConversationSubscriptionUsesReaderPool` initially timed out while the writer pool was held (exit 1); it now completes on the explicit read pool. All named targeted runs passed after restoration.
+
+### Verification and implementation notes
+
+- SQL migrations 0032 and 0033 are follow-ups. Migration 0020 is unchanged. The upgrade fixture retains non-default task kinds and replacement links as well as historical jobs, evidence, charges, approvals, sessions and conversations.
+- The pinned Rastrillo v0.30.1 gormlite parser retains single quotes when reading defaults. `TestMigrationModels` normalizes only 0032 defaults in its in-memory model comparison; the executable migration, snapshot comparison and `TestFinalFixSQLDefaults` still require single quotes. No dependency or module cache changed. The upstream migration generator still uses the affected parser; this narrowly scoped check workaround does not patch that generator.
+- The source budget remains unchanged. Selection validation belongs in planning with injected transaction-bound eligibility checks. A redundant planning accessor was removed; both HTML handlers use the same existing application directly.
+- Notification fixtures now create approval waits instead of expecting notifications from personal proposals. The existing same-person edit/revision races remain.
+- Live topics now include an opaque resource ID plus a scoped digest, within Rastrillo’s key grammar. Subscription checks read one main/thread row and recheck the current roster.
+- Readback revisions use persisted resources; device self-revocation reads its revision inside the write transaction, so revoking the caller does not turn the successful response into 401.
+- The live-gate path correction also updates its exact-line reference inventory hash.
+
+Final restored-source verification: all commands below exited 0.
+
+- `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipo/planning /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipo/library /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipo/notifications /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipo/conversation /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipo/personapi /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipotest /home/paulca/amadan.net/oficina/equipo-plan-3/internal/runner/setup -count=1`: Plan 3 95.388s; equipotest 216.616s; runner/setup 4.837s; all six requested feature packages passed. Library, notifications and conversation have no package-local test cases; their covering tests ran in plan3test.
+- `make -C /home/paulca/amadan.net/oficina/equipo-plan-3 migration-check budget`: model/migration check passed; all 35 package directories stayed within unchanged budgets.
+- `CGO_ENABLED=0 go test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipo -run 'TestConversationMigrationSnapshot|TestConversationSubscriptionUsesReaderPool' -count=1`: passed in 1.072s.
+- `CGO_ENABLED=0 go vet /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipo /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipo/planning /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipo/library /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipo/notifications /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipo/conversation /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipo/personapi /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipotest /home/paulca/amadan.net/oficina/equipo-plan-3/internal/runner/setup`: passed with no output.
+- `CGO_ENABLED=0 go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipo /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipo/planning /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipo/library /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipo/notifications /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipo/conversation /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipo/personapi /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipotest /home/paulca/amadan.net/oficina/equipo-plan-3/internal/runner/setup`: passed with no output.
+- `gofmt -l /home/paulca/amadan.net/oficina/equipo-plan-3/internal/equipo /home/paulca/amadan.net/oficina/equipo-plan-3/internal/plan3test /home/paulca/amadan.net/oficina/equipo-plan-3/internal/runner/setup`: no output.
+- `git -C /home/paulca/amadan.net/oficina/equipo-plan-3 diff --check` and staged diff check: clean.
+
+Thirty-one distinct guard mutations failed their tests and were restored. No source or test budget was raised. `make ci`, live provider tests, sign-ins and enrolment were not run. The full I5 gate remains the controller’s responsibility.
diff --git a/internal/equipo/conversation/coordinator_application.go b/internal/equipo/conversation/coordinator_application.go
index 86fe36e7..31dce799 100644
--- a/internal/equipo/conversation/coordinator_application.go
+++ b/internal/equipo/conversation/coordinator_application.go
@@ -14,6 +14,7 @@ import (
type Actor = kernel.Actor
type Mutation = kernel.Mutation
type Application struct {
+ Read func(context.Context, func(*gorm.DB) error) error
Now func() time.Time
Core *team.Store
Write func(context.Context, func(*gorm.DB) error) error
diff --git a/internal/equipo/conversation/live.go b/internal/equipo/conversation/live.go
index 2820486f..625ab3ac 100644
--- a/internal/equipo/conversation/live.go
+++ b/internal/equipo/conversation/live.go
@@ -6,8 +6,10 @@ import (
"crypto/sha256"
"database/sql"
"encoding/json"
+ "errors"
"fmt"
"net/http"
+ "strings"
"time"
"amadan.net/rastrillo/rastrillo/auth"
@@ -66,42 +68,46 @@ func PersonalChanges(ctx context.Context, tx *sql.Tx) ([]string, error) {
func ConversationTopic(team, person, resource string) string {
raw, _ := json.Marshal([]string{team, person, resource})
- return fmt.Sprintf("conversation/%x", sha256.Sum256(raw))
+ sum := sha256.Sum256(raw)
+ return fmt.Sprintf("conversation/%s_%x", resource, sum[:16])
}
func (s *Application) AllowConversation(r *http.Request, key string) bool {
id, ok := auth.From(r)
if !ok {
return false
}
+
+ resource, _, ok := strings.Cut(key, "_")
+ if !ok || resource == "" || s.Read == nil {
+ return false
+ }
allowed := false
- err := s.Write(r.Context(), func(tx *gorm.DB) error {
+ err := s.Read(r.Context(), func(tx *gorm.DB) error {
a := Actor{Address: s.Normalize(id.Address)}
team, err := s.Conversation(tx).deps.Authorize(tx, a)
if err != nil {
return err
}
- var mains []Main
- if err = tx.Where("team_id=? AND person=?", team, a.Address).Find(&mains).Error; err != nil {
- return err
- }
- for _, main := range mains {
- if ConversationTopic(team, a.Address, main.ID) == "conversation/"+key {
- allowed = true
- }
+ var main Main
+ err = tx.Where("id=? AND team_id=? AND person=?", resource, team, a.Address).Take(&main).Error
+ if err == nil {
+ allowed = ConversationTopic(team, a.Address, main.ID) == "conversation/"+key
+ return nil
}
- var threads []Thread
- if err = tx.Table("conversation_threads").Select("conversation_threads.*").Joins("JOIN tasks ON tasks.id=conversation_threads.task_id AND tasks.team_id=conversation_threads.team_id").Where("conversation_threads.team_id=?", team).Find(&threads).Error; err != nil {
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
return err
}
- for _, thread := range threads {
- if ConversationTopic(team, "", thread.ID) == "conversation/"+key {
- allowed = true
- }
+ var thread Thread
+ err = tx.Table("conversation_threads").Select("conversation_threads.*").Joins("JOIN tasks ON tasks.id=conversation_threads.task_id AND tasks.team_id=conversation_threads.team_id").Where("conversation_threads.id=? AND conversation_threads.team_id=?", resource, team).Take(&thread).Error
+ if err != nil {
+ return err
}
+ allowed = ConversationTopic(team, "", thread.ID) == "conversation/"+key
return nil
})
return err == nil && allowed
}
+
func InstallConversationChanges(ctx context.Context, tx *sql.Tx) error {
stmts := []string{
`CREATE TEMP TABLE IF NOT EXISTS equipo_conversation_changes(team TEXT,person TEXT,resource TEXT,PRIMARY KEY(team,person,resource))`,
diff --git a/internal/equipo/conversation/tools.go b/internal/equipo/conversation/tools.go
index c7af54db..591528f0 100644
--- a/internal/equipo/conversation/tools.go
+++ b/internal/equipo/conversation/tools.go
@@ -115,7 +115,7 @@ func (e *Engine) CallCoordinatorTool(ctx context.Context, p RunnerPrincipal, c C
return err
}
} else {
- plan, err := e.Tools.Planning(tx).ProposeCoordinator(actor, b.ID, a.Plan.TaskPlan(), Mutation{RequestID: resource + ":" + call.RequestID}, func(tx *gorm.DB, _ Actor, kind, id string) error { return e.Audit(tx, b, kind, id) })
+ plan, err := e.Tools.Planning(tx).ProposeCoordinator(planning.DelegatedPrincipal{BindingID: b.ID, Person: b.Person}, a.Plan.TaskPlan(), Mutation{RequestID: resource + ":" + call.RequestID}, func(tx *gorm.DB, _ Actor, kind, id string) error { return e.Audit(tx, b, kind, id) })
if err != nil {
return err
}
diff --git a/internal/equipo/conversation_handlers.go b/internal/equipo/conversation_handlers.go
index b98ebb0b..9302e94e 100644
--- a/internal/equipo/conversation_handlers.go
+++ b/internal/equipo/conversation_handlers.go
@@ -14,7 +14,7 @@ func (a *application) allowConversation(r *http.Request, key string) bool {
return a.store.coordinatorApplication().AllowConversation(r, key)
}
func (a *application) conversationHandler() *conversation.Handler {
- return &conversation.Handler{Live: a.live, App: a.store.coordinatorApplication(), Plans: a.store.planningApplication(), Failure: a.failure,
+ return &conversation.Handler{Live: a.live, App: a.store.coordinatorApplication(), Plans: a.store.PlanApplication, Failure: a.failure,
Render: func(w http.ResponseWriter, r *http.Request, v conversation.Page) {
data, err := a.page(r, "conversation")
if err != nil {
@@ -39,7 +39,7 @@ func (a *application) conversationHandler() *conversation.Handler {
}}
}
func (a *application) planHandler() *planning.Handler {
- return &planning.Handler{App: a.store.planningApplication(), Invalid: ErrInvalid, Forbidden: ErrForbidden, Failure: a.failure, Render: func(w http.ResponseWriter, r *http.Request, v planning.Page) {
+ return &planning.Handler{App: a.store.PlanApplication, Invalid: ErrInvalid, Forbidden: ErrForbidden, Failure: a.failure, Render: func(w http.ResponseWriter, r *http.Request, v planning.Page) {
data, err := a.page(r, "conversation")
if err != nil {
a.failure(w, r, err)
diff --git a/internal/equipo/conversation_read_test.go b/internal/equipo/conversation_read_test.go
new file mode 100644
index 00000000..227b309d
--- /dev/null
+++ b/internal/equipo/conversation_read_test.go
@@ -0,0 +1,31 @@
+package equipo
+
+import (
+ "amadan.net/rastrillo/rastrillo/db"
+ "context"
+ "gorm.io/gorm"
+ "io"
+ "log/slog"
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+func TestConversationSubscriptionUsesReaderPool(t *testing.T) {
+ d, err := db.Open(filepath.Join(t.TempDir(), "read.db"), slog.New(slog.NewTextHandler(io.Discard, nil)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer d.Close()
+ held, err := d.Writer().BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer held.Rollback()
+ ctx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond)
+ defer cancel()
+ err = NewStore(d).coordinatorApplication().Read(ctx, func(tx *gorm.DB) error { var one int; return tx.Raw("SELECT 1").Scan(&one).Error })
+ if err != nil {
+ t.Fatal("conversation subscription waited for writer pool", err)
+ }
+}
diff --git a/internal/equipo/coordinator.go b/internal/equipo/coordinator.go
index 7f44cca7..a64d8ad4 100644
--- a/internal/equipo/coordinator.go
+++ b/internal/equipo/coordinator.go
@@ -7,6 +7,7 @@ import (
"context"
"errors"
"gorm.io/gorm"
+ "gorm.io/plugin/dbresolver"
"slices"
"time"
)
@@ -68,7 +69,9 @@ func (s *Store) coordinatorApplication() *conversation.Application {
if s.execution != nil {
core = s.execution.Core
}
- return &conversation.Application{Now: s.runnerClock.Now, Core: core, Write: s.write, Conversation: conversationAt, Normalize: normalizeAddress, Audit: appendAudit, Invalid: ErrInvalid, Conflict: ErrConflict, Forbidden: ErrForbidden, Unavailable: ErrUnavailable, NotFound: ErrNotFound,
+ return &conversation.Application{Now: s.runnerClock.Now, Core: core, Write: s.write, Read: func(ctx context.Context, fn func(*gorm.DB) error) error {
+ return s.db.G.WithContext(ctx).Clauses(dbresolver.Read).Transaction(fn)
+ }, Conversation: conversationAt, Normalize: normalizeAddress, Audit: appendAudit, Invalid: ErrInvalid, Conflict: ErrConflict, Forbidden: ErrForbidden, Unavailable: ErrUnavailable, NotFound: ErrNotFound,
BindingIdentity: func(tx *gorm.DB, actor Actor, runner, connection string) (int64, int64, error) {
member, err := currentRunnerMember(tx, actor.Address)
if err != nil {
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index 76515d4a..a510833e 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -826,6 +826,8 @@ var runnerDraftCopy = map[string]string{
// COPY REVIEW REQUIRED: evidence.approved
"evidence.approved": "Approved",
+ // COPY REVIEW REQUIRED: plan.awaiting_approval
+ "plan.awaiting_approval": "Waiting for your plan approval",
// COPY REVIEW REQUIRED: plan.proposed
"plan.proposed": "Proposed plan",
// COPY REVIEW REQUIRED: plan.edit
diff --git a/internal/equipo/library/counts.go b/internal/equipo/library/counts.go
index ba128b61..82aef9e5 100644
--- a/internal/equipo/library/counts.go
+++ b/internal/equipo/library/counts.go
@@ -16,62 +16,13 @@ func VisibleTasks(tx *gorm.DB, teamID string, since time.Time) *gorm.DB {
func Counts(tx *gorm.DB, teamID string, now time.Time) (map[string]planning.SpecialistWorkView, error) {
out := map[string]planning.SpecialistWorkView{}
- err := func() error {
- for _, key := range DefaultKeys {
- v := planning.SpecialistWorkView{CountsKnown: true, UsageKnown: true}
- if key != "engineering" && key != "review" {
- out[key] = v
- continue
- }
- caps := []string{"reproduce", "implement"}
- if key == "review" {
- caps = []string{"review", "verify"}
- }
- var counts struct {
- Working, Queued, Finished, Waiting int
- Unknown int64
- Calls, Input, Output int64
- }
- // One row per task before aggregation avoids multiplying usage by attempts.
- err := tx.Raw(`WITH visible AS (?), classified AS (
- SELECT t.id,t.job_id,
- CASE WHEN t.state IN ('failed','cancelled','merged') OR j.state IN ('failed','cancelled') THEN 'finished'
- WHEN (SELECT count(*) FROM steps WHERE job_id=t.job_id AND capability IN ? AND state='succeeded')=2 THEN CASE WHEN (SELECT MAX(julianday(att.updated_at)) FROM attempts att JOIN steps st ON st.id=att.step_id JOIN runner_assignments a ON a.attempt_id=att.id WHERE a.task_id=t.id AND st.capability IN ?)<julianday(?) THEN 'hidden' ELSE 'finished' END
- WHEN EXISTS(SELECT 1 FROM questions q JOIN runner_assignments a ON a.id=q.assignment_id JOIN attempts att ON att.id=a.attempt_id WHERE q.task_id=t.id AND q.state='pending' AND a.state='claimed' AND att.state='active' AND a.fence=att.fence AND a.step_key IN ? AND julianday(a.lease_deadline)>julianday(?) AND julianday(att.lease_deadline)>julianday(?)) THEN 'waiting'
- WHEN EXISTS(SELECT 1 FROM steps WHERE job_id=t.job_id AND capability IN ? AND state='running') THEN 'working'
- ELSE 'queued' END bucket
- FROM visible t LEFT JOIN jobs j ON j.id=t.job_id
- ) SELECT COALESCE(SUM(bucket='working'),0) working,COALESCE(SUM(bucket='queued'),0) queued,
- COALESCE(SUM(bucket='finished'),0) finished,COALESCE(SUM(bucket='waiting'),0) waiting,COALESCE(SUM(job_id=0),0) unknown
- FROM classified`, VisibleTasks(tx, teamID, weekStart(now)), caps, caps, weekStart(now), caps, now, now, caps).Scan(&counts).Error
- if err != nil {
- return err
- }
- v.Working, v.Queued, v.Finished, v.Waiting = counts.Working, counts.Queued, counts.Finished, counts.Waiting
- unprepared := counts.Unknown > 0
- err = tx.Raw(`SELECT COALESCE(SUM(CASE WHEN r.state='open' THEN r.r_calls ELSE r.s_calls END),0) calls,
- COALESCE(SUM(r.s_input),0) input, COALESCE(SUM(r.s_output),0) output,
- COALESCE(SUM(r.state='open' OR r.settled_by='unknown'),0) unknown
- FROM reservations r JOIN steps st ON st.id=r.step_id JOIN (?) t ON t.job_id=r.job_id
- WHERE st.capability IN ? AND julianday(r.created_at)>=julianday(?)`, VisibleTasks(tx, teamID, weekStart(now)), caps, weekStart(now)).Scan(&counts).Error
- if err != nil {
- return err
- }
- v.CountedTurns, v.InputTokens, v.OutputTokens = counts.Calls, counts.Input, counts.Output
- v.UsageKnown = counts.Unknown == 0 && !unprepared
- out[key] = v
- }
- return nil
- }()
- if err == nil {
- err = additionalCounts(tx, teamID, now, out)
- }
+ err := additionalCounts(tx, teamID, now, out)
return out, err
}
func additionalCounts(tx *gorm.DB, teamID string, now time.Time, out map[string]planning.SpecialistWorkView) error {
var keys []string
- if err := tx.Model(&Specialist{}).Where("team_id=? AND key NOT IN ?", teamID, []string{"engineering", "review"}).Pluck("key", &keys).Error; err != nil {
+ if err := tx.Model(&Specialist{}).Where("team_id=?", teamID).Pluck("key", &keys).Error; err != nil {
return err
}
for _, key := range keys {
@@ -81,19 +32,19 @@ func additionalCounts(tx *gorm.DB, teamID string, now time.Time, out map[string]
}
// Classify once per task; plan step identities, not display labels, join work.
err := tx.Raw(`WITH selected AS (
- SELECT t.id,t.job_id,t.state,st.key,st.state step_state,
+ SELECT t.id,t.job_id,t.state,j.state job_state,st.key,st.state step_state,
(SELECT MAX(julianday(a.updated_at)) FROM attempts a WHERE a.step_id=st.id) ended,
EXISTS(SELECT 1 FROM questions q JOIN runner_assignments a ON a.id=q.assignment_id JOIN attempts att ON att.id=a.attempt_id
- WHERE q.task_id=t.id AND a.step_key=st.key AND q.state='pending' AND a.state='claimed' AND att.state='active' AND a.fence=att.fence
+ WHERE q.task_id=t.id AND a.job_id=t.job_id AND a.step_key=st.key AND q.state='pending' AND a.state='claimed' AND att.state='active' AND a.fence=att.fence
AND julianday(a.lease_deadline)>julianday(?) AND julianday(att.lease_deadline)>julianday(?)) waiting
- FROM (?) t JOIN plan_revisions p ON p.task_id=t.id AND p.revision=t.plan_revision,
+ FROM (?) t LEFT JOIN jobs j ON j.id=t.job_id JOIN plan_revisions p ON p.task_id=t.id AND p.revision=t.plan_revision,
json_each(p.plan,'$.Steps') ps
LEFT JOIN steps st ON st.job_id=t.job_id AND st.key=json_extract(ps.value,'$.Key')
WHERE json_extract(ps.value,'$.Specialist')=?
), grouped AS (
- SELECT id,job_id,CASE WHEN state IN ('failed','cancelled','merged') THEN 'finished'
+ SELECT id,job_id,CASE WHEN state IN ('failed','cancelled','merged') OR job_state IN ('failed','cancelled') THEN 'finished'
WHEN SUM(step_state='succeeded')=count(*) THEN CASE WHEN MAX(ended)<julianday(?) THEN 'hidden' ELSE 'finished' END
- WHEN SUM(waiting)>0 THEN 'waiting' WHEN SUM(step_state='running')>0 THEN 'working' ELSE 'queued' END bucket FROM selected GROUP BY id,job_id,state
+ WHEN SUM(waiting)>0 THEN 'waiting' WHEN SUM(step_state='running')>0 THEN 'working' ELSE 'queued' END bucket FROM selected GROUP BY id,job_id,state,job_state
) SELECT COALESCE(SUM(bucket='working'),0) working,COALESCE(SUM(bucket='queued'),0) queued,
COALESCE(SUM(bucket='finished'),0) finished,COALESCE(SUM(bucket='waiting'),0) waiting,COALESCE(SUM(job_id=0),0) unknown FROM grouped`, now, now, VisibleTasks(tx, teamID, weekStart(now)), key, weekStart(now)).Scan(&result).Error
if err != nil {
diff --git a/internal/equipo/migrations/0032_plan_defaults.sql b/internal/equipo/migrations/0032_plan_defaults.sql
new file mode 100644
index 00000000..1e071cfa
--- /dev/null
+++ b/internal/equipo/migrations/0032_plan_defaults.sql
@@ -0,0 +1,12 @@
+ALTER TABLE tasks ADD COLUMN kind_quoted text NOT NULL DEFAULT 'bug';
+UPDATE tasks SET kind_quoted=kind;
+ALTER TABLE tasks DROP COLUMN kind;
+ALTER TABLE tasks RENAME COLUMN kind_quoted TO kind;
+ALTER TABLE tasks ADD COLUMN replacement_id_quoted text NOT NULL DEFAULT '';
+UPDATE tasks SET replacement_id_quoted=replacement_id;
+ALTER TABLE tasks DROP COLUMN replacement_id;
+ALTER TABLE tasks RENAME COLUMN replacement_id_quoted TO replacement_id;
+ALTER TABLE tasks ADD COLUMN replaces_id_quoted text NOT NULL DEFAULT '';
+UPDATE tasks SET replaces_id_quoted=replaces_id;
+ALTER TABLE tasks DROP COLUMN replaces_id;
+ALTER TABLE tasks RENAME COLUMN replaces_id_quoted TO replaces_id;
diff --git a/internal/equipo/migrations/0033_plan_notifications.sql b/internal/equipo/migrations/0033_plan_notifications.sql
new file mode 100644
index 00000000..d673420c
--- /dev/null
+++ b/internal/equipo/migrations/0033_plan_notifications.sql
@@ -0,0 +1,21 @@
+DROP TRIGGER notification_task_insert;
+CREATE TRIGGER notification_task_insert AFTER INSERT ON tasks BEGIN
+UPDATE notification_outbox SET state='superseded' WHERE resource_type='task' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state IN ('cancelled','cancel_requested','merged','failed') OR (event='task_ready.plan' AND NOT (NEW.approval_revision<>NEW.plan_revision AND NEW.state NOT IN ('cancelled','cancel_requested','merged','failed','succeeded') AND (NEW.wait_code='plan.awaiting_approval' OR (NEW.state='proposed' AND EXISTS(SELECT 1 FROM plan_revisions p WHERE p.task_id=NEW.id AND p.revision=NEW.plan_revision AND p.actor_kind='coordinator') AND COALESCE(NULLIF((SELECT mode FROM plan_approval_settings WHERE project_id=NEW.project_id AND person=NEW.requester),''),(SELECT mode FROM plan_approval_settings WHERE project_id=NEW.project_id AND person=''),'immediate')='required')))));
+INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),NEW.team_id,NEW.requester,'task_ready.plan',NEW.id,NEW.revision,'task_ready','task','/tasks/'||NEW.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') WHERE NEW.approval_revision<>NEW.plan_revision AND NEW.state NOT IN ('cancelled','cancel_requested','merged','failed','succeeded') AND (NEW.wait_code='plan.awaiting_approval' OR (NEW.state='proposed' AND EXISTS(SELECT 1 FROM plan_revisions p WHERE p.task_id=NEW.id AND p.revision=NEW.plan_revision AND p.actor_kind='coordinator') AND COALESCE(NULLIF((SELECT mode FROM plan_approval_settings WHERE project_id=NEW.project_id AND person=NEW.requester),''),(SELECT mode FROM plan_approval_settings WHERE project_id=NEW.project_id AND person=''),'immediate')='required')) AND EXISTS(SELECT 1 FROM members m WHERE m.address=NEW.requester AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING;
+END;
+DROP TRIGGER notification_task_update;
+CREATE TRIGGER notification_task_update AFTER UPDATE ON tasks BEGIN
+UPDATE notification_outbox SET state='superseded' WHERE resource_type='task' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state IN ('cancelled','cancel_requested','merged','failed') OR (event='task_ready.plan' AND NOT (NEW.approval_revision<>NEW.plan_revision AND NEW.state NOT IN ('cancelled','cancel_requested','merged','failed','succeeded') AND (NEW.wait_code='plan.awaiting_approval' OR (NEW.state='proposed' AND EXISTS(SELECT 1 FROM plan_revisions p WHERE p.task_id=NEW.id AND p.revision=NEW.plan_revision AND p.actor_kind='coordinator') AND COALESCE(NULLIF((SELECT mode FROM plan_approval_settings WHERE project_id=NEW.project_id AND person=NEW.requester),''),(SELECT mode FROM plan_approval_settings WHERE project_id=NEW.project_id AND person=''),'immediate')='required')))));
+INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),NEW.team_id,NEW.requester,'task_ready.plan',NEW.id,NEW.revision,'task_ready','task','/tasks/'||NEW.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') WHERE NEW.approval_revision<>NEW.plan_revision AND NEW.state NOT IN ('cancelled','cancel_requested','merged','failed','succeeded') AND (NEW.wait_code='plan.awaiting_approval' OR (NEW.state='proposed' AND EXISTS(SELECT 1 FROM plan_revisions p WHERE p.task_id=NEW.id AND p.revision=NEW.plan_revision AND p.actor_kind='coordinator') AND COALESCE(NULLIF((SELECT mode FROM plan_approval_settings WHERE project_id=NEW.project_id AND person=NEW.requester),''),(SELECT mode FROM plan_approval_settings WHERE project_id=NEW.project_id AND person=''),'immediate')='required')) AND EXISTS(SELECT 1 FROM members m WHERE m.address=NEW.requester AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING;
+END;
+DROP TRIGGER notification_card_insert;
+CREATE TRIGGER notification_card_insert AFTER INSERT ON conversation_cards BEGIN
+UPDATE notification_outbox SET state='superseded' WHERE resource_type='card' AND resource_id=NEW.id AND state<>'superseded' AND resource_revision<>NEW.revision;
+INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),c.team_id,c.person,'card',NEW.id,NEW.revision,'card','card','/conversation','unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM conversations c WHERE c.id=NEW.stream_id AND NEW.kind LIKE 'suggest_%' AND EXISTS(SELECT 1 FROM members m WHERE m.address=c.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING;
+END;
+DROP TRIGGER notification_card_update;
+CREATE TRIGGER notification_card_update AFTER UPDATE ON conversation_cards BEGIN
+UPDATE notification_outbox SET state='superseded' WHERE resource_type='card' AND resource_id=NEW.id AND state<>'superseded' AND resource_revision<>NEW.revision;
+INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),c.team_id,c.person,'card',NEW.id,NEW.revision,'card','card','/conversation','unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM conversations c WHERE c.id=NEW.stream_id AND NEW.kind LIKE 'suggest_%' AND EXISTS(SELECT 1 FROM members m WHERE m.address=c.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING;
+END;
+UPDATE notification_outbox SET state='superseded' WHERE event='task_ready.plan' AND NOT EXISTS(SELECT 1 FROM tasks t WHERE t.id=notification_outbox.resource_id AND t.revision=notification_outbox.resource_revision AND t.approval_revision<>t.plan_revision AND t.state NOT IN ('cancelled','cancel_requested','merged','failed','succeeded') AND (t.wait_code='plan.awaiting_approval' OR (t.state='proposed' AND EXISTS(SELECT 1 FROM plan_revisions p WHERE p.task_id=t.id AND p.revision=t.plan_revision AND p.actor_kind='coordinator') AND COALESCE(NULLIF((SELECT mode FROM plan_approval_settings WHERE project_id=t.project_id AND person=t.requester),''),(SELECT mode FROM plan_approval_settings WHERE project_id=t.project_id AND person=''),'immediate')='required')));
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 9de1b892..b3c9388a 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -363,11 +363,11 @@ CREATE TABLE conversation_routes (source_id text PRIMARY KEY, task_id text, repl
CREATE TABLE conversation_outboxes (message_id text PRIMARY KEY, stream_id text, purpose text);
CREATE TABLE conversation_cursors (id text PRIMARY KEY, principal text, stream_id text, after integer, through integer, revision integer, expires_at datetime);
-ALTER TABLE tasks ADD COLUMN kind text NOT NULL DEFAULT "bug";
+ALTER TABLE tasks ADD COLUMN kind text NOT NULL DEFAULT 'bug';
ALTER TABLE tasks ADD COLUMN plan_revision integer NOT NULL DEFAULT 0;
ALTER TABLE tasks ADD COLUMN approval_revision integer NOT NULL DEFAULT 0;
-ALTER TABLE tasks ADD COLUMN replacement_id text NOT NULL DEFAULT "";
-ALTER TABLE tasks ADD COLUMN replaces_id text NOT NULL DEFAULT "";
+ALTER TABLE tasks ADD COLUMN replacement_id text NOT NULL DEFAULT '';
+ALTER TABLE tasks ADD COLUMN replaces_id text NOT NULL DEFAULT '';
CREATE TABLE plan_revisions (task_id text, revision integer, plan text, actor_kind text, actor text, changed_keys text, created_at datetime, PRIMARY KEY(task_id,revision));
CREATE TABLE plan_requests (principal text, operation text, resource text, request_id text, input_hash text, result text, PRIMARY KEY(principal,operation,resource,request_id));
CREATE TABLE plan_approval_settings (project_id integer, person text, mode text, revision integer, PRIMARY KEY(project_id,person));
@@ -505,12 +505,11 @@ UPDATE notification_outbox SET state='superseded' WHERE resource_type='question'
INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),t.team_id,t.requester,'question',NEW.id,NEW.revision,'question','question','/tasks/'||t.id||'/questions/'||NEW.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM tasks t WHERE t.id=NEW.task_id AND NEW.state='pending' AND EXISTS(SELECT 1 FROM members m WHERE m.address=t.requester AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING;
END;
CREATE TRIGGER notification_task_insert AFTER INSERT ON tasks BEGIN
-UPDATE notification_outbox SET state='superseded' WHERE resource_type='task' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state IN ('cancelled','cancel_requested','merged','failed'));
-INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),NEW.team_id,NEW.requester,'task_ready.plan',NEW.id,NEW.revision,'task_ready','task','/tasks/'||NEW.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') WHERE NEW.state='proposed' AND EXISTS(SELECT 1 FROM members m WHERE m.address=NEW.requester AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING;
+UPDATE notification_outbox SET state='superseded' WHERE resource_type='task' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state IN ('cancelled','cancel_requested','merged','failed') OR (event='task_ready.plan' AND NOT (NEW.approval_revision<>NEW.plan_revision AND NEW.state NOT IN ('cancelled','cancel_requested','merged','failed','succeeded') AND (NEW.wait_code='plan.awaiting_approval' OR (NEW.state='proposed' AND EXISTS(SELECT 1 FROM plan_revisions p WHERE p.task_id=NEW.id AND p.revision=NEW.plan_revision AND p.actor_kind='coordinator') AND COALESCE(NULLIF((SELECT mode FROM plan_approval_settings WHERE project_id=NEW.project_id AND person=NEW.requester),''),(SELECT mode FROM plan_approval_settings WHERE project_id=NEW.project_id AND person=''),'immediate')='required')))));
+INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),NEW.team_id,NEW.requester,'task_ready.plan',NEW.id,NEW.revision,'task_ready','task','/tasks/'||NEW.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') WHERE NEW.approval_revision<>NEW.plan_revision AND NEW.state NOT IN ('cancelled','cancel_requested','merged','failed','succeeded') AND (NEW.wait_code='plan.awaiting_approval' OR (NEW.state='proposed' AND EXISTS(SELECT 1 FROM plan_revisions p WHERE p.task_id=NEW.id AND p.revision=NEW.plan_revision AND p.actor_kind='coordinator') AND COALESCE(NULLIF((SELECT mode FROM plan_approval_settings WHERE project_id=NEW.project_id AND person=NEW.requester),''),(SELECT mode FROM plan_approval_settings WHERE project_id=NEW.project_id AND person=''),'immediate')='required')) AND EXISTS(SELECT 1 FROM members m WHERE m.address=NEW.requester AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING;
END;
CREATE TRIGGER notification_card_insert AFTER INSERT ON conversation_cards BEGIN
UPDATE notification_outbox SET state='superseded' WHERE resource_type='card' AND resource_id=NEW.id AND state<>'superseded' AND resource_revision<>NEW.revision;
-INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),c.team_id,c.person,'task_ready.plan',NEW.resource_id,NEW.revision,'task_ready','task','/tasks/'||NEW.resource_id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM conversations c WHERE c.id=NEW.stream_id AND NEW.kind='task' AND EXISTS(SELECT 1 FROM members m WHERE m.address=c.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING;
INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),c.team_id,c.person,'card',NEW.id,NEW.revision,'card','card','/conversation','unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM conversations c WHERE c.id=NEW.stream_id AND NEW.kind LIKE 'suggest_%' AND EXISTS(SELECT 1 FROM members m WHERE m.address=c.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING;
END;
CREATE TRIGGER notification_turn_insert AFTER INSERT ON coordinator_turns BEGIN
@@ -526,12 +525,11 @@ UPDATE notification_outbox SET state='superseded' WHERE resource_type='question'
INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),t.team_id,t.requester,'question',NEW.id,NEW.revision,'question','question','/tasks/'||t.id||'/questions/'||NEW.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM tasks t WHERE t.id=NEW.task_id AND NEW.state='pending' AND EXISTS(SELECT 1 FROM members m WHERE m.address=t.requester AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING;
END;
CREATE TRIGGER notification_task_update AFTER UPDATE ON tasks BEGIN
-UPDATE notification_outbox SET state='superseded' WHERE resource_type='task' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state IN ('cancelled','cancel_requested','merged','failed'));
-INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),NEW.team_id,NEW.requester,'task_ready.plan',NEW.id,NEW.revision,'task_ready','task','/tasks/'||NEW.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') WHERE NEW.state='proposed' AND EXISTS(SELECT 1 FROM members m WHERE m.address=NEW.requester AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING;
+UPDATE notification_outbox SET state='superseded' WHERE resource_type='task' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state IN ('cancelled','cancel_requested','merged','failed') OR (event='task_ready.plan' AND NOT (NEW.approval_revision<>NEW.plan_revision AND NEW.state NOT IN ('cancelled','cancel_requested','merged','failed','succeeded') AND (NEW.wait_code='plan.awaiting_approval' OR (NEW.state='proposed' AND EXISTS(SELECT 1 FROM plan_revisions p WHERE p.task_id=NEW.id AND p.revision=NEW.plan_revision AND p.actor_kind='coordinator') AND COALESCE(NULLIF((SELECT mode FROM plan_approval_settings WHERE project_id=NEW.project_id AND person=NEW.requester),''),(SELECT mode FROM plan_approval_settings WHERE project_id=NEW.project_id AND person=''),'immediate')='required')))));
+INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),NEW.team_id,NEW.requester,'task_ready.plan',NEW.id,NEW.revision,'task_ready','task','/tasks/'||NEW.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') WHERE NEW.approval_revision<>NEW.plan_revision AND NEW.state NOT IN ('cancelled','cancel_requested','merged','failed','succeeded') AND (NEW.wait_code='plan.awaiting_approval' OR (NEW.state='proposed' AND EXISTS(SELECT 1 FROM plan_revisions p WHERE p.task_id=NEW.id AND p.revision=NEW.plan_revision AND p.actor_kind='coordinator') AND COALESCE(NULLIF((SELECT mode FROM plan_approval_settings WHERE project_id=NEW.project_id AND person=NEW.requester),''),(SELECT mode FROM plan_approval_settings WHERE project_id=NEW.project_id AND person=''),'immediate')='required')) AND EXISTS(SELECT 1 FROM members m WHERE m.address=NEW.requester AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING;
END;
CREATE TRIGGER notification_card_update AFTER UPDATE ON conversation_cards BEGIN
UPDATE notification_outbox SET state='superseded' WHERE resource_type='card' AND resource_id=NEW.id AND state<>'superseded' AND resource_revision<>NEW.revision;
-INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),c.team_id,c.person,'task_ready.plan',NEW.resource_id,NEW.revision,'task_ready','task','/tasks/'||NEW.resource_id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM conversations c WHERE c.id=NEW.stream_id AND NEW.kind='task' AND EXISTS(SELECT 1 FROM members m WHERE m.address=c.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING;
INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),c.team_id,c.person,'card',NEW.id,NEW.revision,'card','card','/conversation','unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM conversations c WHERE c.id=NEW.stream_id AND NEW.kind LIKE 'suggest_%' AND EXISTS(SELECT 1 FROM members m WHERE m.address=c.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING;
END;
CREATE TRIGGER notification_turn_update AFTER UPDATE ON coordinator_turns BEGIN
diff --git a/internal/equipo/migrations_test.go b/internal/equipo/migrations_test.go
index 2770f441..80bfdf47 100644
--- a/internal/equipo/migrations_test.go
+++ b/internal/equipo/migrations_test.go
@@ -16,7 +16,17 @@ import (
)
func TestMigrationModels(t *testing.T) {
- payload, err := dump.Compute(Schema.All(), BootSchema.All(), Models)
+ // Rastrillo v0.30.1's gormlite parser strips double quotes but retains
+ // single quotes on defaults. Normalize only this check's in-memory SQL;
+ // the snapshot and default tests verify the executable migration unchanged.
+ migrations := append([]migrate.Migration(nil), Schema.All()...)
+ for i := range migrations {
+ if migrations[i].ID == "equipo/0032_plan_defaults" {
+ migrations[i].SQL = strings.ReplaceAll(migrations[i].SQL, "DEFAULT 'bug'", `DEFAULT "bug"`)
+ migrations[i].SQL = strings.ReplaceAll(migrations[i].SQL, "DEFAULT ''", `DEFAULT ""`)
+ }
+ }
+ payload, err := dump.Compute(migrations, BootSchema.All(), Models)
if err != nil {
t.Fatal(err)
}
diff --git a/internal/equipo/person_api_mutations.go b/internal/equipo/person_api_mutations.go
index 333ca322..f4f3723d 100644
--- a/internal/equipo/person_api_mutations.go
+++ b/internal/equipo/person_api_mutations.go
@@ -6,7 +6,7 @@ import (
)
func (s *Store) nativeAPI() *personapi.Native {
- return &personapi.Native{NativeOperations: s, SettingsUpdate: s.saveAPIProjectSettings, Devices: s.personDevices, ReadTeam: s.readTeam, Owner: requireOwner, Copy: copyText, Invalid: ErrInvalid, Forbidden: ErrForbidden, NotFound: ErrNotFound, Conflict: ErrConflict, Unavailable: ErrUnavailable}
+ return &personapi.Native{NativeOperations: s, LookupMember: s.Member, SettingsUpdate: s.saveAPIProjectSettings, Devices: s.personDevices, ReadTeam: s.readTeam, Owner: requireOwner, Copy: copyText, Invalid: ErrInvalid, Forbidden: ErrForbidden, NotFound: ErrNotFound, Conflict: ErrConflict, Unavailable: ErrUnavailable}
}
func (s *Store) PersonAPIExtendedMutation(ctx context.Context, a Actor, op, id string, in any, m Mutation) (personapi.Result, error) {
return s.nativeAPI().Mutate(ctx, a, op, id, in, m)
diff --git a/internal/equipo/personapi/conversation.go b/internal/equipo/personapi/conversation.go
index 358d7dbf..4dda8cf8 100644
--- a/internal/equipo/personapi/conversation.go
+++ b/internal/equipo/personapi/conversation.go
@@ -88,9 +88,9 @@ func (h *Handler) mutate(ctx context.Context, a kernel.Actor, op, id string, inp
v, err := h.App.SubscribeNotifications(ctx, a, input.(*SubscribeNotificationsInput).DeviceID, m)
return Result{v, v.Revision}, err
case "unsubscribe_notifications":
- return apiAck(m, h.App.UnsubscribeNotifications(ctx, a, id, m))
+ return h.notificationAck(ctx, a, id, h.App.UnsubscribeNotifications(ctx, a, id, m))
case "ack_notification":
- return apiAck(m, h.App.AcknowledgeNotification(ctx, a, id, input.(*AcknowledgeNotificationInput).NotificationID, m))
+ return h.notificationAck(ctx, a, id, h.App.AcknowledgeNotification(ctx, a, id, input.(*AcknowledgeNotificationInput).NotificationID, m))
case "send", "send_thread":
v := input.(*MessageInput)
thread := ""
@@ -175,3 +175,11 @@ func (h *Handler) mutate(ctx context.Context, a kernel.Actor, op, id string, inp
}
return h.App.PersonAPIExtendedMutation(ctx, a, op, id, input, m)
}
+
+func (h *Handler) notificationAck(ctx context.Context, a kernel.Actor, id string, err error) (Result, error) {
+ if err != nil {
+ return Result{}, err
+ }
+ out, err := h.App.NotificationSubscription(ctx, a, id)
+ return apiAck(out.Revision, err)
+}
diff --git a/internal/equipo/personapi/devices.go b/internal/equipo/personapi/devices.go
index 9e08c39f..8d1096ef 100644
--- a/internal/equipo/personapi/devices.go
+++ b/internal/equipo/personapi/devices.go
@@ -44,6 +44,7 @@ type PersonDeviceProof struct {
Signature string `json:"signature"`
}
type PersonCredential struct {
+ Revision int64 `json:"-"`
ID string `json:"id"`
Token string `json:"token"`
Audience string `json:"audience"`
@@ -381,7 +382,9 @@ func (s *DeviceStore) Exchange(ctx context.Context, p PersonDeviceProof) (out Pe
denied = ErrDeviceExpired
return nil
}
- return s.open("exchange/"+row.ID, row.ResultCipher, &out)
+ err := s.open("exchange/"+row.ID, row.ResultCipher, &out)
+ out.Revision = row.Revision
+ return err
}
if !now.Before(row.ExpiresAt) {
denied = ErrDeviceExpired
@@ -403,7 +406,7 @@ func (s *DeviceStore) Exchange(ctx context.Context, p PersonDeviceProof) (out Pe
return nil
}
token := PersonAudience + "." + rand.Text()
- out = PersonCredential{row.ID, token, PersonAudience, row.InstanceID, now.Add(30 * 24 * time.Hour)}
+ out = PersonCredential{ID: row.ID, Token: token, Audience: PersonAudience, InstanceID: row.InstanceID, ExpiresAt: now.Add(30 * 24 * time.Hour)}
sealed, e := s.seal("exchange/"+row.ID, out)
if e != nil {
return e
@@ -422,6 +425,9 @@ func (s *DeviceStore) Exchange(ctx context.Context, p PersonDeviceProof) (out Pe
if result.RowsAffected != 1 {
return s.Conflict
}
+ if err := tx.Model(&DeviceRecord{}).Select("revision").Where("id=?", row.ID).Scan(&out.Revision).Error; err != nil {
+ return err
+ }
return s.Audit(tx, kernel.Actor{Address: row.Person}, "person_device.exchange", row.ID)
})
if err == nil {
@@ -509,16 +515,20 @@ func (s *DeviceStore) Approval(ctx context.Context, id string) (out Device, err
return
}
func (s *DeviceStore) Revoke(ctx context.Context, a kernel.Actor, id string, m kernel.Mutation) error {
+ _, err := s.RevokeRevision(ctx, a, id, m)
+ return err
+}
+func (s *DeviceStore) RevokeRevision(ctx context.Context, a kernel.Actor, id string, m kernel.Mutation) (revision int64, err error) {
if !m.Valid() {
- return s.Invalid
+ return 0, s.Invalid
}
var requestErr error
ctx, requestErr = ApplicationRequest(ctx, a, "person_device.revoke", id, m, m)
if requestErr != nil {
- return requestErr
+ return 0, requestErr
}
- return s.Write(WithoutRequest(ctx), func(tx *gorm.DB) error {
+ err = s.Write(WithoutRequest(ctx), func(tx *gorm.DB) error {
if e := s.member(tx, a.Address, s.Now().Unix()); e != nil {
return e
}
@@ -528,6 +538,7 @@ func (s *DeviceStore) Revoke(ctx context.Context, a kernel.Actor, id string, m k
}
var ack Ack
if replay, e := Replay(tx, ctx, &ack, s.Conflict); e != nil || replay {
+ revision = ack.Revision
return e
}
if r.Revision != m.Revision {
@@ -544,8 +555,12 @@ func (s *DeviceStore) Revoke(ctx context.Context, a kernel.Actor, id string, m k
if e := s.Audit(tx, a, "person_device.revoke", id); e != nil {
return e
}
- return SaveResult(tx, ctx, Ack{r.Revision}, s.Conflict)
+ if err := tx.Model(&DeviceRecord{}).Select("revision").Where("id=?", id).Scan(&revision).Error; err != nil {
+ return err
+ }
+ return SaveResult(tx, ctx, Ack{revision}, s.Conflict)
})
+ return
}
func (s *DeviceStore) Sweep(ctx context.Context) error {
diff --git a/internal/equipo/personapi/extended_mutations.go b/internal/equipo/personapi/extended_mutations.go
index 23293fcd..22aa0381 100644
--- a/internal/equipo/personapi/extended_mutations.go
+++ b/internal/equipo/personapi/extended_mutations.go
@@ -14,8 +14,32 @@ import (
"amadan.net/oficina/equipo/internal/runnerproto"
)
-func apiAck(m kernel.Mutation, err error) (Result, error) {
- return Result{Value: Ack{Revision: m.Revision + 1}, Revision: m.Revision + 1}, err
+func apiAck(revision int64, err error) (Result, error) {
+ return Result{Value: Ack{Revision: revision}, Revision: revision}, err
+}
+func (s *Native) ack(ctx context.Context, a kernel.Actor, op, id string, err error) (Result, error) {
+ if err != nil {
+ return Result{}, err
+ }
+ // A successful self-demotion still needs its acknowledgement. The write
+ // already checked owner authority; this reads only the resulting revision.
+ if op == "set_roster" {
+ member, err := s.LookupMember(ctx, id)
+ return apiAck(member.Revision, err)
+ }
+ reads := map[string]string{"approve_device": "devices", "revoke_device": "devices", "set_roster": "roster_member", "save_budgets": "budgets", "forget_link": "teams", "delete_specialist": "specialist", "delete_playbook": "playbook", "rename_connection": "connection", "revoke_connection": "connection", "save_choices": "project_settings", "approve_runner": "runners", "revoke_runner": "runner", "cancel_account_setup": "account_setup", "revoke_invite": "invite"}
+ read, ok := reads[op]
+ if !ok {
+ return Result{}, s.Unavailable
+ }
+ out, err := s.Read(ctx, a, read, id)
+ if err != nil {
+ return Result{}, err
+ }
+ if op == "save_choices" {
+ out.Revision = out.Value.(ProjectSettings).ConnectionsRevision
+ }
+ return apiAck(out.Revision, nil)
}
func apiSpecialist(v library.Specialist, err error) (Result, error) {
return Result{Value: ProjectSpecialist(v), Revision: v.Revision}, err
@@ -43,14 +67,15 @@ func (s *Native) Mutate(ctx context.Context, a kernel.Actor, op, id string, inpu
return Result{Value: out, Revision: 1}, err
case "exchange_device":
out, err := s.ExchangePersonDevice(ctx, *input.(*PersonDeviceProof))
- return Result{Value: out, Revision: 3}, err
+ return Result{Value: out, Revision: out.Revision}, err
case "approve_device":
- return apiAck(m, s.ApprovePersonDevice(ctx, a, id, input.(*ApproveDeviceInput).TypedCode, m))
+ return s.ack(ctx, a, op, id, s.ApprovePersonDevice(ctx, a, id, input.(*ApproveDeviceInput).TypedCode, m))
case "revoke_device":
- return apiAck(m, s.RevokePersonDevice(ctx, a, id, m))
+ revision, err := s.Devices().RevokeRevision(ctx, a, id, m)
+ return apiAck(revision, err)
case "set_roster":
v := input.(*RosterInput)
- return apiAck(m, s.SetMember(ctx, a, id, kernel.Role(v.Role), v.Active, m.Revision))
+ return s.ack(ctx, a, op, id, s.SetMember(ctx, a, id, kernel.Role(v.Role), v.Active, m.Revision))
case "save_budgets":
v := input.(*BudgetsInput)
b := kernel.BudgetConfig{Revision: m.Revision, Team: apiLimits(v.Team), Projects: map[team.ProjectID]team.PeriodLimits{}}
@@ -61,13 +86,13 @@ func (s *Native) Mutate(ctx context.Context, a kernel.Actor, op, id string, inpu
}
b.Projects[team.ProjectID(n)] = apiLimits(limits)
}
- return apiAck(m, s.SaveBudgets(ctx, a, b))
+ return s.ack(ctx, a, op, id, s.SaveBudgets(ctx, a, b))
case "save_link":
v := input.(*TeamLinkInput)
out, err := s.RememberTeam(ctx, a, setup.TeamLink{ID: id, Origin: v.Origin, Name: v.Name}, m)
return Result{Value: apiLink(out), Revision: out.Revision}, err
case "forget_link":
- return apiAck(m, s.ForgetTeam(ctx, a, id, m))
+ return s.ack(ctx, a, op, id, s.ForgetTeam(ctx, a, id, m))
case "create_account":
out, err := s.SaveAccount(ctx, a, kernel.Account{Label: input.(*LabelInput).Label})
return Result{Value: Account{ID: strconv.FormatInt(out.ID, 10), Label: out.Label, Revision: out.Revision}, Revision: out.Revision}, err
@@ -94,11 +119,11 @@ func (s *Native) Mutate(ctx context.Context, a kernel.Actor, op, id string, inpu
case "update_specialist":
return apiSpecialist(s.UpdateSpecialist(ctx, a, input.(*SpecialistInput).Value(id), m))
case "delete_specialist":
- return apiAck(m, s.DeleteSpecialist(ctx, a, id, m))
+ return s.ack(ctx, a, op, id, s.DeleteSpecialist(ctx, a, id, m))
case "save_playbook":
return apiPlaybook(s.SavePlaybook(ctx, a, input.(*PlaybookInput).Value(id), m))
case "delete_playbook":
- return apiAck(m, s.DeletePlaybook(ctx, a, id, m))
+ return s.ack(ctx, a, op, id, s.DeletePlaybook(ctx, a, id, m))
case "install_template":
ref := library.TemplateRef{ID: id, Version: input.(*TemplateInstallInput).Version}
if strings.HasPrefix(id, "playbook_") {
@@ -112,16 +137,16 @@ func (s *Native) Mutate(ctx context.Context, a kernel.Actor, op, id string, inpu
v := input.(*TemplateUpdateInput)
return apiPlaybook(s.ApplyPlaybookTemplate(ctx, a, id, v.Diff.Value(), v.Fields, m))
case "rename_connection":
- return apiAck(m, s.RenameConnection(ctx, a, id, input.(*LabelInput).Label, m))
+ return s.ack(ctx, a, op, id, s.RenameConnection(ctx, a, id, input.(*LabelInput).Label, m))
case "revoke_connection":
- return apiAck(m, s.RevokeConnection(ctx, a, id, m))
+ return s.ack(ctx, a, op, id, s.RevokeConnection(ctx, a, id, m))
case "save_choices":
v := input.(*ConnectionChoiceInput)
n, err := s.apiNumericID(id, false)
if err != nil {
return Result{}, err
}
- return apiAck(m, s.SaveConnectionChoice(ctx, a, planning.ConnectionChoice{ProjectID: n, Revision: m.Revision, ConnectionIDs: v.ConnectionIDs, PinnedID: v.PinnedID, Mode: v.Mode}))
+ return s.ack(ctx, a, op, id, s.SaveConnectionChoice(ctx, a, planning.ConnectionChoice{ProjectID: n, Revision: m.Revision, ConnectionIDs: v.ConnectionIDs, PinnedID: v.PinnedID, Mode: v.Mode}))
case "select_step":
v := input.(*SelectionInput)
parts := strings.SplitN(id, "/", 2)
@@ -131,9 +156,9 @@ func (s *Native) Mutate(ctx context.Context, a kernel.Actor, op, id string, inpu
out, err := s.ConfirmPlanSelection(ctx, a, parts[0], parts[1], v.ConnectionID, v.Model, m)
return Result{Value: Selected{ConnectionID: out.ConnectionID, Model: out.Model, Reason: out.Reason, Revision: m.Revision}, Revision: m.Revision}, err
case "approve_runner":
- return apiAck(m, s.ApproveEnrolment(ctx, a, input.(*RunnerApproveInput).TypedCode))
+ return s.ack(ctx, a, op, id, s.ApproveEnrolment(ctx, a, input.(*RunnerApproveInput).TypedCode))
case "revoke_runner":
- return apiAck(m, s.RevokeRunner(ctx, a, id, m.Revision))
+ return s.ack(ctx, a, op, id, s.RevokeRunner(ctx, a, id, m.Revision))
case "advance_onboarding":
v := input.(*OnboardingInput)
if v.Step == "first_task" && v.ProjectID > 0 {
@@ -156,7 +181,7 @@ func (s *Native) Mutate(ctx context.Context, a kernel.Actor, op, id string, inpu
out, err := s.RequestAccountSetup(ctx, a, v.RunnerID, v.Provider, v.Label, m)
return Result{Value: s.apiAccountSetup(out), Revision: out.Revision}, err
case "cancel_account_setup":
- return apiAck(m, s.CancelAccountSetup(ctx, a, id, m))
+ return s.ack(ctx, a, op, id, s.CancelAccountSetup(ctx, a, id, m))
case "create_invite":
v := input.(*InviteInput)
out, err := s.CreateInvitation(ctx, a, v.Address, kernel.Role(v.Role), m)
@@ -165,7 +190,7 @@ func (s *Native) Mutate(ctx context.Context, a kernel.Actor, op, id string, inpu
out, err := s.AcceptInvitation(ctx, a, id, input.(*AcceptInviteInput).Secret, m)
return Result{Value: RosterMember{Person: Person{Address: out.Address, DisplayIdentity: out.Address, Role: string(out.Role), Active: out.Active}, Revision: out.Revision}, Revision: out.Revision}, err
case "revoke_invite":
- return apiAck(m, s.RevokeInvitation(ctx, a, id, m))
+ return s.ack(ctx, a, op, id, s.RevokeInvitation(ctx, a, id, m))
}
return Result{}, s.NotFound
}
diff --git a/internal/equipo/personapi/native.go b/internal/equipo/personapi/native.go
index 65f40aef..abd2d065 100644
--- a/internal/equipo/personapi/native.go
+++ b/internal/equipo/personapi/native.go
@@ -12,6 +12,7 @@ import (
)
type Native struct {
+ LookupMember func(context.Context, string) (kernel.Member, error)
SettingsUpdate func(context.Context, kernel.Actor, int64, ProjectSettingsInput, kernel.Mutation, bool) (Result, error)
NativeOperations
Devices func() *DeviceStore
diff --git a/internal/equipo/plan_selection.go b/internal/equipo/plan_selection.go
index effbb5e9..4cdf1474 100644
--- a/internal/equipo/plan_selection.go
+++ b/internal/equipo/plan_selection.go
@@ -9,10 +9,15 @@ import (
"gorm.io/gorm"
)
+var errPlanApproval = &refusal{copyText("plan.awaiting_approval"), ErrConflict}
+
var errPlanSelectionAsk = &refusal{copyText("connections.ask"), ErrUnavailable}
var errPlanSecondFamily = &refusal{copyText("connections.second_family"), ErrUnavailable}
func selectionWaitCode(err error) string {
+ if errors.Is(err, errPlanApproval) {
+ return "plan.awaiting_approval"
+ }
if errors.Is(err, errPlanSelectionAsk) {
return "connections.ask"
}
diff --git a/internal/equipo/planning/approval_settings.go b/internal/equipo/planning/approval_settings.go
index 24bdd3a3..15b23994 100644
--- a/internal/equipo/planning/approval_settings.go
+++ b/internal/equipo/planning/approval_settings.go
@@ -95,7 +95,7 @@ func (s *Store) SetApproval(actor kernel.Actor, projectID int64, mode *ApprovalM
return s.save(q, true)
}
func (s *Store) Approve(actor kernel.Actor, id string, m kernel.Mutation) (Task, error) {
- t, err := s.task(actor, id)
+ t, err := s.requesterTask(actor, id)
if err != nil {
return t, err
}
@@ -125,6 +125,9 @@ func (s *Store) Approve(actor kernel.Actor, id string, m kernel.Mutation) (Task,
}
}
t.ApprovalRevision = t.PlanRevision
+ if t.WaitCode == "plan.awaiting_approval" {
+ t.WaitCode = ""
+ }
t.Revision++
if err = s.persist(t, actor, "plan.approve"); err != nil {
return result, err
@@ -152,7 +155,7 @@ func (s *Store) CheckDispatch(actor kernel.Actor, id string) error {
return err
}
if (mode == ApprovalRequired || t.ReplacesID != "") && t.ApprovalRevision != p.Revision {
- return s.deps.Conflict
+ return s.deps.AwaitingApproval
}
return s.deps.Ready(s.tx, t, p)
}
diff --git a/internal/equipo/planning/dispatch.go b/internal/equipo/planning/dispatch.go
index 3efe6d6a..ad678ba4 100644
--- a/internal/equipo/planning/dispatch.go
+++ b/internal/equipo/planning/dispatch.go
@@ -84,7 +84,7 @@ func GraphChange(p taskplan.Plan, old []team.Step) (team.PlanChange, error) {
return c, nil
}
func (s *Store) Correct(actor kernel.Actor, id string, projectID int64, m kernel.Mutation) (Task, error) {
- t, err := s.task(actor, id)
+ t, err := s.requesterTask(actor, id)
if err != nil {
return t, err
}
diff --git a/internal/equipo/planning/plans.go b/internal/equipo/planning/plans.go
index e1c16c9d..72be2de5 100644
--- a/internal/equipo/planning/plans.go
+++ b/internal/equipo/planning/plans.go
@@ -59,7 +59,15 @@ type Access struct {
TeamID, MergeOwner string
ProjectRevision int64
}
+type DelegatedPrincipal struct {
+ BindingID, Person string
+}
+
type Dependencies struct {
+ AwaitingApproval error
+ DelegatedAccess func(*gorm.DB, DelegatedPrincipal, int64) (Access, error)
+ DelegatedPlaybook func(*gorm.DB, DelegatedPrincipal, taskplan.Plan) (taskplan.Plan, error)
+ EligibleSelection func(*gorm.DB, int64, taskplan.Step, ConnectionRecord, runnerproto.ConnectionReport) (bool, error)
ApprovalReady func(*gorm.DB, Task, taskplan.Plan) error
Choose func(*gorm.DB, Task, taskplan.Plan, taskplan.Step, bool) (runnerproto.Selection, error)
PlaybookDetails func(*gorm.DB, string, taskplan.Plan) (string, []string, error)
@@ -214,6 +222,9 @@ func (s *Store) propose(actor kernel.Actor, requester string, p taskplan.Plan, m
if err = s.deps.Specialists(s.tx, a.TeamID, p, nil); err != nil {
return result, err
}
+ if err = s.validateSelections(requester, p, nil); err != nil {
+ return result, err
+ }
t := Task{ID: rand.Text(), Requester: requester, RequestID: rand.Text(), Description: p.Steps[0].Instructions, ProjectID: p.ProjectID, Revision: 1, PlanRevision: 1, Kind: p.Kind, TeamID: a.TeamID, MergeOwner: a.MergeOwner, State: "proposed"}
t.ReviewRef = "equipo/" + t.ID
if err = s.tx.Create(&t).Error; err != nil {
@@ -234,7 +245,7 @@ func (s *Store) propose(actor kernel.Actor, requester string, p taskplan.Plan, m
return p, s.save(q, p)
}
func (s *Store) Edit(actor kernel.Actor, p taskplan.Plan, m kernel.Mutation) (taskplan.Plan, error) {
- t, err := s.task(actor, p.TaskID)
+ t, err := s.requesterTask(actor, p.TaskID)
if err != nil {
return taskplan.Plan{}, err
}
@@ -287,6 +298,9 @@ func (s *Store) Edit(actor kernel.Actor, p taskplan.Plan, m kernel.Mutation) (ta
if err = s.deps.Specialists(s.tx, t.TeamID, p, started); err != nil {
return result, err
}
+ if err = s.validateSelections(t.Requester, p, started); err != nil {
+ return result, err
+ }
if t.JobID != 0 && !checkpoint {
change, err := GraphChange(p, steps)
if err != nil {
@@ -318,6 +332,9 @@ func (s *Store) Edit(actor kernel.Actor, p taskplan.Plan, m kernel.Mutation) (ta
t.Revision++
t.PlanRevision++
t.ApprovalRevision = 0
+ if t.WaitCode == "plan.awaiting_approval" {
+ t.WaitCode = ""
+ }
t.Kind = p.Kind
p.Revision = t.PlanRevision
if err = s.history(&t, p, actor, &before); err != nil {
@@ -364,10 +381,31 @@ func (s *Store) actorID(a kernel.Actor) string {
}
return a.Address
}
-func (s *Store) ProposeCoordinator(actor kernel.Actor, binding string, p taskplan.Plan, m kernel.Mutation, audit func(*gorm.DB, kernel.Actor, string, string) error) (taskplan.Plan, error) {
+func (s *Store) ProposeCoordinator(principal DelegatedPrincipal, p taskplan.Plan, m kernel.Mutation, audit func(*gorm.DB, kernel.Actor, string, string) error) (taskplan.Plan, error) {
+ if principal.BindingID == "" || principal.Person == "" || s.deps.DelegatedAccess == nil {
+ return taskplan.Plan{}, s.deps.Forbidden
+ }
copy := *s
- copy.coordinator = "coordinator:" + binding
+ copy.coordinator = "coordinator:" + principal.BindingID
copy.deps = s.deps
copy.deps.Audit = audit
- return copy.Propose(actor, p, m)
+ copy.deps.Access = func(tx *gorm.DB, _ kernel.Actor, project int64) (Access, error) {
+ return s.deps.DelegatedAccess(tx, principal, project)
+ }
+ copy.deps.ResolvePlaybook = func(tx *gorm.DB, _ kernel.Actor, p taskplan.Plan) (taskplan.Plan, error) {
+ return s.deps.DelegatedPlaybook(tx, principal, p)
+ }
+ return copy.propose(kernel.Actor{Address: copy.coordinator}, principal.Person, p, m)
+}
+
+func (s *Store) requesterTask(actor kernel.Actor, id string) (Task, error) {
+ t, err := s.visibleTask(actor, id)
+ if err != nil {
+ return t, err
+ }
+ if actor.Address != t.Requester || s.coordinator != "" {
+ return t, s.deps.Forbidden
+ }
+ _, err = s.deps.Access(s.tx, actor, t.ProjectID)
+ return t, err
}
diff --git a/internal/equipo/planning/selection.go b/internal/equipo/planning/selection.go
index ed1f904d..e5115ccd 100644
--- a/internal/equipo/planning/selection.go
+++ b/internal/equipo/planning/selection.go
@@ -22,9 +22,9 @@ type SelectionRecord struct {
func (SelectionRecord) TableName() string { return "plan_selections" }
-func ActualSelection(tx *gorm.DB, taskID, key string) (runnerproto.Selection, bool, error) {
+func ActualSelection(tx *gorm.DB, t Task, key string) (runnerproto.Selection, bool, error) {
var row struct{ Selection string }
- err := tx.Table("runner_assignments").Select("selection").Where("task_id=? AND step_key=? AND claim_request<>''", taskID, key).Order("id").Take(&row).Error
+ err := tx.Table("runner_assignments").Select("selection").Where("task_id=? AND job_id=? AND step_key=? AND claim_request<>''", t.ID, t.JobID, key).Order("id").Take(&row).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return runnerproto.Selection{}, false, nil
}
@@ -38,7 +38,7 @@ func ActualSelection(tx *gorm.DB, taskID, key string) (runnerproto.Selection, bo
func (s *Store) Select(actor kernel.Actor, id, key, connection, model string, confirm bool, m kernel.Mutation) (runnerproto.Selection, error) {
var result runnerproto.Selection
- t, err := s.task(actor, id)
+ t, err := s.requesterTask(actor, id)
if err != nil {
return result, err
}
@@ -69,7 +69,7 @@ func (s *Store) Select(actor kernel.Actor, id, key, connection, model string, co
if err != nil {
return result, err
}
- actual, started, err := ActualSelection(s.tx, id, key)
+ actual, started, err := ActualSelection(s.tx, t, key)
if err != nil {
return result, err
}
@@ -143,7 +143,7 @@ type SelectionView struct {
}
func SavedSelection(tx *gorm.DB, t Task, key string) (runnerproto.Selection, bool, bool, error) {
- sel, actual, err := ActualSelection(tx, t.ID, key)
+ sel, actual, err := ActualSelection(tx, t, key)
if err != nil || actual {
return sel, actual, true, err
}
diff --git a/internal/equipo/planning/selection_policy.go b/internal/equipo/planning/selection_policy.go
index d28b723f..3df8d2b4 100644
--- a/internal/equipo/planning/selection_policy.go
+++ b/internal/equipo/planning/selection_policy.go
@@ -39,7 +39,7 @@ func (s SelectionPolicy) Choose(tx *gorm.DB, t Task, p taskplan.Plan, step taskp
if !taskplan.Candidate(st) {
continue
}
- sel, started, err := ActualSelection(tx, t.ID, st.Key)
+ sel, started, err := ActualSelection(tx, t, st.Key)
if err != nil {
return Selection{}, err
}
@@ -70,7 +70,7 @@ func (s SelectionPolicy) Choose(tx *gorm.DB, t Task, p taskplan.Plan, step taskp
}
func (s SelectionPolicy) ForStep(tx *gorm.DB, t Task, st taskplan.Step, excluded, runner string, availabilityOnly bool) (Selection, error) {
- actual, started, err := ActualSelection(tx, t.ID, st.Key)
+ actual, started, err := ActualSelection(tx, t, st.Key)
if err != nil {
return Selection{}, err
}
@@ -156,7 +156,7 @@ func (s SelectionPolicy) Pair(tx *gorm.DB, t Task, p taskplan.Plan, approval boo
func (s SelectionPolicy) Dispatch(tx *gorm.DB, t Task, st taskplan.Step, first Selection) (Selection, error) {
runnerID := first.RunnerID
var assignments []struct{ Brief, RunnerID string }
- if err := tx.Table("runner_assignments").Where("task_id=? AND claim_request<>''", t.ID).Order("id").Find(&assignments).Error; err != nil {
+ if err := tx.Table("runner_assignments").Where("task_id=? AND job_id=? AND claim_request<>''", t.ID, t.JobID).Order("id").Find(&assignments).Error; err != nil {
return Selection{}, err
}
families := map[string]bool{}
diff --git a/internal/equipo/planning/selection_validation.go b/internal/equipo/planning/selection_validation.go
new file mode 100644
index 00000000..b311c8a1
--- /dev/null
+++ b/internal/equipo/planning/selection_validation.go
@@ -0,0 +1,50 @@
+package planning
+
+import (
+ "amadan.net/oficina/equipo/internal/taskplan"
+ "encoding/json"
+)
+
+// Explicit plan picks must be eligible for the requester in this transaction.
+func (s *Store) validateSelections(person string, p taskplan.Plan, started map[string]bool) error {
+ for _, step := range p.Steps {
+ if started[step.Key] || step.ConnectionID == "" && step.Model == "" {
+ continue
+ }
+ if step.Specialist == "" {
+ return s.deps.Invalid
+ }
+ _, ids, err := ConnectionChoiceAt(s.tx, person, p.ProjectID)
+ if err != nil {
+ return s.deps.Invalid
+ }
+ var rows []ConnectionRecord
+ q := s.tx.Where("person=? AND id IN ?", person, ids)
+ if step.ConnectionID != "" {
+ q = q.Where("id=?", step.ConnectionID)
+ }
+ if err = q.Find(&rows).Error; err != nil {
+ return err
+ }
+ found := false
+ for _, c := range rows {
+ if err = json.Unmarshal([]byte(c.ReportsJSON), &c.Reports); err != nil {
+ return err
+ }
+ for _, report := range c.Reports {
+ if step.Model != "" && step.Model != report.Model {
+ continue
+ }
+ ok, err := s.deps.EligibleSelection(s.tx, p.ProjectID, step, c, report)
+ if err != nil {
+ return err
+ }
+ found = found || ok
+ }
+ }
+ if !found {
+ return s.deps.Invalid
+ }
+ }
+ return nil
+}
diff --git a/internal/equipo/planning/views.go b/internal/equipo/planning/views.go
index cf90c90b..f880b9be 100644
--- a/internal/equipo/planning/views.go
+++ b/internal/equipo/planning/views.go
@@ -55,7 +55,7 @@ func (s *Store) Page(a kernel.Actor, id string) (out Page, err error) {
}
}
_, accessErr := s.deps.Access(s.tx, a, out.Task.ProjectID)
- out.CanEdit = accessErr == nil
+ out.CanEdit = accessErr == nil && a.Address == out.Task.Requester
out.CanSelect = out.CanEdit && a.Address == out.Task.Requester
out.Owner = s.deps.Member(s.tx, a, true) == nil
out.RequestID, out.ApproveID, out.CorrectID = rand.Text(), rand.Text(), rand.Text()
@@ -71,7 +71,7 @@ func (s *Store) Page(a kernel.Actor, id string) (out Page, err error) {
for _, setting := range []struct {
person string
out *ApprovalSetting
- }{{"", &out.ProjectSetting}, {a.Address, &out.PersonalSetting}} {
+ }{{"", &out.ProjectSetting}, {out.Task.Requester, &out.PersonalSetting}} {
err = s.tx.Where("project_id=? AND person=?", out.Plan.ProjectID, setting.person).Take(setting.out).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
err = nil
@@ -80,11 +80,13 @@ func (s *Store) Page(a kernel.Actor, id string) (out Page, err error) {
return
}
}
- out.Connections, err = s.connectionOptions(a, out.Plan.ProjectID)
+ if out.CanSelect {
+ out.Connections, err = s.connectionOptions(a, out.Plan.ProjectID)
+ }
if err != nil {
return
}
- out.Effective, err = s.Approval(a.Address, out.Plan.ProjectID)
+ out.Effective, err = s.Approval(out.Task.Requester, out.Plan.ProjectID)
if err != nil {
return
}
@@ -120,7 +122,7 @@ func (s *Store) Page(a kernel.Actor, id string) (out Page, err error) {
}
}
var n int64
- if err = s.tx.Table("runner_assignments").Where("task_id=? AND step_key=? AND claim_request<>''", id, st.Key).Count(&n).Error; err != nil {
+ if err = s.tx.Table("runner_assignments").Where("task_id=? AND job_id=? AND step_key=? AND claim_request<>''", id, out.Task.JobID, st.Key).Count(&n).Error; err != nil {
return
}
v.Locked = v.Locked || n > 0
diff --git a/internal/equipo/plans.go b/internal/equipo/plans.go
index 9246c4cb..cbb905f4 100644
--- a/internal/equipo/plans.go
+++ b/internal/equipo/plans.go
@@ -2,8 +2,10 @@ package equipo
import (
"amadan.net/oficina/equipo/internal/equipo/conversation"
+ "amadan.net/oficina/equipo/internal/equipo/library"
"amadan.net/oficina/equipo/internal/equipo/planning"
"amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runnerproto"
"amadan.net/oficina/equipo/internal/taskplan"
"encoding/json"
"gorm.io/gorm"
@@ -18,7 +20,19 @@ const (
func (s *Store) planningAt(tx *gorm.DB) *planning.Store {
deps := planning.Dependencies{
- Choose: s.choosePlanSelection,
+ AwaitingApproval: errPlanApproval,
+ Choose: s.choosePlanSelection,
+ EligibleSelection: func(tx *gorm.DB, project int64, step taskplan.Step, c planning.ConnectionRecord, report runnerproto.ConnectionReport) (bool, error) {
+ sp, err := specialistAt(tx, step.Specialist)
+ if err != nil {
+ return false, err
+ }
+ if c.RevokedAt != nil || !knownFamily(report.Family) || !library.ProjectAllowed(sp, project) || !specialistAllows(sp, report) {
+ return false, nil
+ }
+ ok, _, err := s.eligible(tx, c, report, s.runnerClock.Now())
+ return ok, err
+ },
ApprovalReady: func(tx *gorm.DB, t Task, p taskplan.Plan) error { return s.planReadyFor(tx, t, p, true) },
PlaybookDetails: func(tx *gorm.DB, teamID string, p taskplan.Plan) (string, []string, error) {
return s.libraryAt(tx).PlanDetails(teamID, p)
@@ -77,6 +91,12 @@ func (s *Store) planningAt(tx *gorm.DB) *planning.Store {
Ready: s.planReady,
Invalid: ErrInvalid, Conflict: ErrConflict, Forbidden: ErrForbidden, Unavailable: ErrUnavailable,
}
+ deps.DelegatedAccess = func(tx *gorm.DB, principal planning.DelegatedPrincipal, project int64) (planning.Access, error) {
+ return deps.Access(tx, Actor{Address: principal.Person}, project)
+ }
+ deps.DelegatedPlaybook = func(tx *gorm.DB, principal planning.DelegatedPrincipal, p taskplan.Plan) (taskplan.Plan, error) {
+ return deps.ResolvePlaybook(tx, Actor{Address: principal.Person}, p)
+ }
if s.execution != nil {
deps.Core = s.execution.Core
}
@@ -110,9 +130,6 @@ func (s *Store) planReadyFor(tx *gorm.DB, t Task, p taskplan.Plan, approval bool
_, _, err = s.selectionPolicy().Pair(tx, t, p, approval)
return err
}
-func (s *Store) planningApplication() *planning.Application {
- return s.PlanApplication
-}
func (s *Store) preparePlanOutbox(tx *gorm.DB, t Task) error {
if err := s.planningAt(tx).CheckDispatch(Actor{Address: t.Requester}, t.ID); err != nil {
return err
diff --git a/internal/equipo/runner_execution.go b/internal/equipo/runner_execution.go
index 18ce35b4..310e2301 100644
--- a/internal/equipo/runner_execution.go
+++ b/internal/equipo/runner_execution.go
@@ -258,7 +258,7 @@ func (e *Execution) Sync(ctx context.Context) error {
if !taskRefusal(err) {
return err
}
- if err := taskWait(tx, task.ID, "task.wait.setup"); err != nil {
+ if err := taskWait(tx, task.ID, selectionWaitCode(err)); err != nil {
return err
}
continue
@@ -277,6 +277,9 @@ func (e *Execution) Sync(ctx context.Context) error {
}
if err := e.store.planningAt(tx).CheckDispatch(Actor{Address: task.Requester}, task.ID); err != nil {
if taskRefusal(err) {
+ if waitErr := taskWait(tx, task.ID, selectionWaitCode(err)); waitErr != nil {
+ return waitErr
+ }
continue
}
return err
@@ -353,7 +356,7 @@ func (e *Execution) Sync(ctx context.Context) error {
}
for _, key := range keys {
var count int64
- if err := tx.Model(&runnerAssignment{}).Where("task_id=? AND step_key=? AND state!='contained' AND NOT(state='fenced' AND claim_request='')", task.ID, key).Count(&count).Error; err != nil {
+ if err := tx.Model(&runnerAssignment{}).Where("task_id=? AND job_id=? AND step_key=? AND state!='contained' AND NOT(state='fenced' AND claim_request='')", task.ID, task.JobID, key).Count(&count).Error; err != nil {
return storeError(err)
}
if count > 0 {
diff --git a/internal/equipo/templates/plan.html b/internal/equipo/templates/plan.html
index 0b4c8f5d..d73be0d0 100644
--- a/internal/equipo/templates/plan.html
+++ b/internal/equipo/templates/plan.html
@@ -42,9 +42,9 @@
<form method="post" action="/tasks/{{.Task.ID}}/plan/approve" equipo-form><input type="hidden" name="request_id" value="{{.ApproveID}}"><input type="hidden" name="revision" value="{{.Plan.Revision}}"><button rst-btn type="submit">{{copy "plan.approve"}}</button></form>
<section id="project" equipo-card><h2>{{copy "plan.project"}}</h2><form method="post" action="/tasks/{{.Task.ID}}/project" equipo-form><input type="hidden" name="request_id" value="{{.CorrectID}}"><input type="hidden" name="revision" value="{{.Task.Revision}}"><label>{{copy "plan.correct_project"}}<select rst-input name="project_id">{{$project := .Plan.ProjectID}}{{range .Projects}}<option value="{{.ID}}" {{if eq .ID $project}}selected{{end}}>{{.Name}}</option>{{end}}</select></label><button rst-btn type="submit">{{copy "plan.correct_project"}}</button></form></section>
{{else}}<ol equipo-plan-steps>{{range .Steps}}<li equipo-plan-step data-plan-step="{{.Key}}"><strong>{{copy (printf "plan.action.%s" .Action)}}</strong><span equipo-badge>{{copy (printf "step.%s" .State)}}</span><p>{{.Instructions}}</p><span equipo-value>{{.Model}} {{.Account}}</span><span equipo-secondary title="{{.SelectionReason}}">{{.SelectionReason}}</span></li>{{end}}</ol>{{end}}
-<section equipo-card><h2>{{copy "plan.approval_settings"}}</h2><p>{{copy (printf "plan.%s" .Effective)}}</p>
+<section equipo-card><h2>{{copy "plan.approval_settings"}}</h2><p data-requester-mode="{{.Effective}}">{{.Task.Requester}}: {{copy (printf "plan.%s" .Effective)}}</p><p data-project-mode="{{if .ProjectSetting.Mode}}{{.ProjectSetting.Mode}}{{else}}immediate{{end}}">{{copy "plan.project"}}: {{if .ProjectSetting.Mode}}{{copy (printf "plan.%s" .ProjectSetting.Mode)}}{{else}}{{copy "plan.immediate"}}{{end}}</p>
{{if .Owner}}<form method="post" action="/tasks/{{.Task.ID}}/plan/settings" equipo-form><input type="hidden" name="request_id" value="{{.ProjectSettingID}}"><input type="hidden" name="revision" value="{{.ProjectSetting.Revision}}"><input type="hidden" name="scope" value="project"><label>{{copy "plan.project"}}<select rst-input name="mode"><option value="immediate" {{if ne .ProjectSetting.Mode "required"}}selected{{end}}>{{copy "plan.immediate"}}</option><option value="required" {{if eq .ProjectSetting.Mode "required"}}selected{{end}}>{{copy "plan.required"}}</option></select></label><button rst-btn type="submit">{{copy "form.save"}}</button></form>{{end}}
-<form method="post" action="/tasks/{{.Task.ID}}/plan/settings" equipo-form><input type="hidden" name="request_id" value="{{.PersonalSettingID}}"><input type="hidden" name="revision" value="{{.PersonalSetting.Revision}}"><input type="hidden" name="scope" value="personal"><label>{{copy "plan.personal_override"}}<select rst-input name="mode"><option value="" {{if eq .PersonalSetting.Mode ""}}selected{{end}}>{{copy "plan.inherit"}}</option><option value="immediate" {{if eq .PersonalSetting.Mode "immediate"}}selected{{end}}>{{copy "plan.immediate"}}</option><option value="required" {{if eq .PersonalSetting.Mode "required"}}selected{{end}}>{{copy "plan.required"}}</option></select></label><button rst-btn type="submit">{{copy "form.save"}}</button></form>
-</section>
+{{if .CanEdit}}<form method="post" action="/tasks/{{.Task.ID}}/plan/settings" equipo-form><input type="hidden" name="request_id" value="{{.PersonalSettingID}}"><input type="hidden" name="revision" value="{{.PersonalSetting.Revision}}"><input type="hidden" name="scope" value="personal"><label>{{copy "plan.personal_override"}}<select rst-input name="mode"><option value="" {{if eq .PersonalSetting.Mode ""}}selected{{end}}>{{copy "plan.inherit"}}</option><option value="immediate" {{if eq .PersonalSetting.Mode "immediate"}}selected{{end}}>{{copy "plan.immediate"}}</option><option value="required" {{if eq .PersonalSetting.Mode "required"}}selected{{end}}>{{copy "plan.required"}}</option></select></label><button rst-btn type="submit">{{copy "form.save"}}</button></form>
+{{end}}</section>
{{end}}</div>
{{end}}
diff --git a/internal/plan3test/coordinator_migration_test.go b/internal/plan3test/coordinator_migration_test.go
index 503a9fe6..5426a6ed 100644
--- a/internal/plan3test/coordinator_migration_test.go
+++ b/internal/plan3test/coordinator_migration_test.go
@@ -18,7 +18,7 @@ func TestCoordinatorMigrationUpgrade(t *testing.T) {
t.Cleanup(func() { must(t, d.Close()) })
old := &migrate.Set{}
for _, m := range equipo.BootSchema.All() {
- if m.ID != "equipo/0021_coordinator" && m.ID != "equipo/0031_notifications" {
+ if m.ID != "equipo/0021_coordinator" && m.ID != "equipo/0031_notifications" && m.ID != "equipo/0033_plan_notifications" {
old.Add(m)
}
}
@@ -30,7 +30,7 @@ func TestCoordinatorMigrationUpgrade(t *testing.T) {
must(t, err)
result, err := migrate.Apply(ctx, d, equipo.BootSchema)
must(t, err)
- if len(result.Applied) != 2 || result.Applied[0] != "equipo/0021_coordinator" || result.Applied[1] != "equipo/0031_notifications" {
+ if len(result.Applied) != 3 || result.Applied[0] != "equipo/0021_coordinator" || result.Applied[1] != "equipo/0031_notifications" || result.Applied[2] != "equipo/0033_plan_notifications" {
t.Fatal("wrong upgrade", result.Applied)
}
f := &fixture{DB: d, Store: equipo.NewStore(d)}
diff --git a/internal/plan3test/finalfix_authority_test.go b/internal/plan3test/finalfix_authority_test.go
new file mode 100644
index 00000000..d28882d0
--- /dev/null
+++ b/internal/plan3test/finalfix_authority_test.go
@@ -0,0 +1,109 @@
+package plan3test
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo"
+ "errors"
+ "strings"
+ "testing"
+)
+
+func TestFinalFixRequesterAuthority(t *testing.T) {
+ for _, role := range []string{"owner", "member"} {
+ t.Run(role, func(t *testing.T) {
+ f := newFixture(t)
+ p := proposed(t, f)
+ f.planConnections(t, p.ProjectID)
+ f.exec(t, "UPDATE members SET role=? WHERE address=?", role, peer.Address)
+ mode := equipo.ApprovalRequired
+ must(t, f.Store.SetApprovalOverride(ctx, owner, p.ProjectID, &mode, equipo.Mutation{RequestID: "required"}))
+ t.Run("approve", func(t *testing.T) {
+ _, err := f.Store.ApprovePlan(ctx, peer, p.TaskID, equipo.Mutation{RequestID: "foreign-approve", Revision: 1})
+ if !errors.Is(err, equipo.ErrForbidden) {
+ t.Fatal("non-requester approved", err)
+ }
+ })
+ t.Run("edit", func(t *testing.T) {
+ q := p
+ q.Steps[0].Instructions = "foreign instructions"
+ _, err := f.Store.EditPlan(ctx, peer, q, equipo.Mutation{RequestID: "foreign-edit", Revision: 1})
+ if !errors.Is(err, equipo.ErrForbidden) {
+ t.Fatal("non-requester edited", err)
+ }
+ })
+ t.Run("correct", func(t *testing.T) {
+ _, err := f.Store.CorrectTaskProject(ctx, peer, p.TaskID, p.ProjectID, equipo.Mutation{RequestID: "foreign-correct", Revision: 1})
+ if !errors.Is(err, equipo.ErrForbidden) {
+ t.Fatal("non-requester corrected project", err)
+ }
+ })
+ t.Run("read", func(t *testing.T) {
+ var thread string
+ must(t, f.DB.Writer().QueryRow("SELECT id FROM conversation_threads WHERE task_id=?", p.TaskID).Scan(&thread))
+ _, err := f.Store.SendMessage(ctx, peer, thread, "Shared discussion", equipo.Mutation{RequestID: "discussion"})
+ must(t, err)
+ w := f.get(t, peer, "/tasks/"+p.TaskID+"/plan")
+ expectHTTP(t, w, 200)
+ if strings.Contains(w.Body.String(), `id="plan-editor"`) || strings.Contains(w.Body.String(), `action="/tasks/`+p.TaskID+`/plan/approve"`) {
+ t.Fatal("foreign execution controls visible")
+ }
+ if !strings.Contains(w.Body.String(), `data-requester-mode="required"`) || !strings.Contains(w.Body.String(), `data-project-mode="immediate"`) {
+ t.Fatal("requester and project approval modes missing")
+ }
+ })
+ t.Run("http", func(t *testing.T) {
+ expectHTTP(t, apiRequest(t, f, peer, "POST", "/api/v1/tasks/"+p.TaskID+"/plan/approve", "{}", "api-foreign", `"1"`), 403)
+ expectHTTP(t, formPost(t, f, peer, "/tasks/"+p.TaskID+"/plan/approve", actionForm("html-foreign", 1)), 403)
+ })
+ })
+ }
+}
+
+func TestFinalFixPlanSelections(t *testing.T) {
+ for _, operation := range []string{"propose", "edit"} {
+ for _, value := range []string{"foreign", "unknown-model"} {
+ t.Run(operation+"/"+value, func(t *testing.T) {
+ f := newFixture(t)
+ p := proposed(t, f)
+ f.planConnections(t, p.ProjectID)
+ if value == "foreign" {
+ f.exec(t, "UPDATE connections SET person=? WHERE id='claude'", peer.Address)
+ p.Steps[0].ConnectionID = "claude"
+ } else {
+ p.Steps[0].Model = "not-reported"
+ }
+ var err error
+ if operation == "propose" {
+ p.TaskID = ""
+ p.Revision = 0
+ _, err = f.Store.ProposePlan(ctx, owner, p, equipo.Mutation{RequestID: "bad-pick"})
+ } else {
+ _, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "bad-pick", Revision: 1})
+ }
+ if !errors.Is(err, equipo.ErrInvalid) {
+ t.Fatal("invalid requester selection persisted", err)
+ }
+ })
+ }
+ }
+}
+
+func TestFinalFixApprovalWait(t *testing.T) {
+ for _, started := range []bool{false, true} {
+ t.Run(map[bool]string{false: "proposed", true: "started"}[started], func(t *testing.T) {
+ f := newFixture(t)
+ p := proposed(t, f)
+ f.planConnections(t, p.ProjectID)
+ x, _, _ := f.planCore(t, p)
+ if !started {
+ f.exec(t, "UPDATE tasks SET state='proposed',job_id=0 WHERE id=?", p.TaskID)
+ }
+ must(t, f.Store.SetProjectApproval(ctx, owner, p.ProjectID, equipo.ApprovalRequired, equipo.Mutation{RequestID: "wait"}))
+ must(t, x.Sync(ctx))
+ task, err := f.Store.Task(ctx, owner, p.TaskID)
+ must(t, err)
+ if task.WaitCode != "plan.awaiting_approval" {
+ t.Fatal("approval wait mislabelled", task.WaitCode)
+ }
+ })
+ }
+}
diff --git a/internal/plan3test/finalfix_counts_test.go b/internal/plan3test/finalfix_counts_test.go
new file mode 100644
index 00000000..5bf333f3
--- /dev/null
+++ b/internal/plan3test/finalfix_counts_test.go
@@ -0,0 +1,56 @@
+package plan3test
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/library"
+ "amadan.net/oficina/equipo/internal/taskplan"
+ "encoding/json"
+ "testing"
+ "time"
+)
+
+func TestFinalFixSpecialistCounts(t *testing.T) {
+ for _, kind := range []string{"recommendation", "investigation", "feature", "copy", "design"} {
+ t.Run(kind, func(t *testing.T) {
+ f := newFixture(t)
+ p := proposed(t, f)
+ f.exec(t, "DELETE FROM tasks WHERE id<>?", p.TaskID)
+ specialist, action := "product", "recommend"
+ if kind == "feature" {
+ specialist, action = "engineering", "implement"
+ }
+ if kind == "copy" || kind == "design" {
+ specialist, action = kind, kind
+ }
+ p.Steps = []taskplan.Step{{Key: "one", Specialist: specialist, Action: action}, {Key: "two", Specialist: specialist, Action: action}, {Key: "person", Action: "person"}}
+ if kind == "feature" {
+ p.Steps = append(p.Steps[:1], p.Steps[2:]...)
+ }
+ raw, err := json.Marshal(p)
+ must(t, err)
+ f.exec(t, "UPDATE plan_revisions SET plan=? WHERE task_id=?", string(raw), p.TaskID)
+ upgradeRow(t, f, "jobs", map[string]any{"id": 1, "account": f.TeamID, "state": "running"})
+ f.exec(t, "UPDATE tasks SET job_id=1,state='queued' WHERE id=?", p.TaskID)
+ keys := []string{"one", "two"}
+ if kind == "feature" {
+ keys = keys[:1]
+ }
+ for i, key := range keys {
+ upgradeRow(t, f, "steps", map[string]any{"id": i + 1, "job_id": 1, "key": key, "state": "pending", "capability": "implement"})
+ }
+ for _, state := range []string{"pending", "running", "succeeded"} {
+ f.exec(t, "UPDATE steps SET state=?", state)
+ counts, err := library.Counts(f.DB.G, f.TeamID, time.Now())
+ must(t, err)
+ for key, v := range counts {
+ total := v.Working + v.Queued + v.Finished + v.Waiting
+ if key != specialist && total != 0 {
+ t.Errorf("non-participating %s counted: %+v", key, v)
+ }
+ if key == specialist && (total != 1 || state == "succeeded" && v.Finished != 1 || state == "running" && v.Working != 1 || state == "pending" && v.Queued != 1) {
+ t.Errorf("%s %s count: %+v", key, state, v)
+ }
+ }
+ }
+ })
+ }
+}
diff --git a/internal/plan3test/finalfix_install_test.go b/internal/plan3test/finalfix_install_test.go
new file mode 100644
index 00000000..d5aa3997
--- /dev/null
+++ b/internal/plan3test/finalfix_install_test.go
@@ -0,0 +1,20 @@
+package plan3test
+
+import (
+ "os"
+ "strings"
+ "testing"
+)
+
+func TestFinalFixLiveGateRunnerEnvironment(t *testing.T) {
+ install, err := os.ReadFile("../../cmd/equipo-runner/install.go")
+ must(t, err)
+ doc, err := os.ReadFile("../../docs/live-gate.md")
+ must(t, err)
+ if !strings.Contains(string(install), `filepath.Join(home, ".local/share/equipo-runner")`) {
+ t.Fatal("installer default changed; update the live-gate check")
+ }
+ if !strings.Contains(string(doc), "$HOME/.local/share/equipo-runner/runner.env") || strings.Contains(string(doc), "$HOME/.config/equipo-runner/runner.env") {
+ t.Fatal("live-gate environment path differs from installer")
+ }
+}
diff --git a/internal/plan3test/finalfix_live_test.go b/internal/plan3test/finalfix_live_test.go
new file mode 100644
index 00000000..ac010f00
--- /dev/null
+++ b/internal/plan3test/finalfix_live_test.go
@@ -0,0 +1,47 @@
+package plan3test
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/equipo/conversation"
+ "amadan.net/rastrillo/rastrillo/mail"
+ "context"
+ "crypto/rand"
+ "gorm.io/gorm"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestFinalFixConversationReadLookup(t *testing.T) {
+ f := newFixture(t)
+ p := proposed(t, f)
+ var thread string
+ must(t, f.DB.Writer().QueryRow("SELECT id FROM conversation_threads WHERE task_id=?", p.TaskID).Scan(&thread))
+ writes := 0
+ app := conversation.Application{Normalize: strings.ToLower, Read: func(_ context.Context, fn func(*gorm.DB) error) error { return fn(f.DB.G) }, Write: func(_ context.Context, fn func(*gorm.DB) error) error { writes++; return fn(f.DB.G) }, Conversation: func(tx *gorm.DB) *conversation.Store {
+ return conversation.New(tx, conversation.Dependencies{Authorize: func(*gorm.DB, equipo.Actor) (string, error) { return f.TeamID, nil }})
+ }}
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ auth, err := equipo.NewAuth(f.DB, equipo.Config{Origin: origin, InstanceKey: rand.Text(), AllowLoggedMail: true}, mail.Logged(logger), f.Store, logger)
+ must(t, err)
+ must(t, f.DB.G.Callback().Query().After("gorm:query").Register("finalfix_thread_lookup", func(tx *gorm.DB) {
+ if tx.Statement.Table == "conversation_threads" && !strings.Contains(tx.Statement.SQL.String(), "conversation_threads.id=") {
+ t.Error("thread lookup scanned team")
+ }
+ }))
+ key := strings.TrimPrefix(conversation.ConversationTopic(f.TeamID, "", thread), "conversation/")
+ h := auth.RequireSession(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !app.AllowConversation(r, key) {
+ t.Error("shared thread denied")
+ }
+ }))
+ r := httptest.NewRequest("GET", "/", nil)
+ r.AddCookie(f.Cookies[peer.Address])
+ h.ServeHTTP(httptest.NewRecorder(), r)
+ if writes != 0 {
+ t.Fatal("live subscription acquired writer", writes)
+ }
+}
diff --git a/internal/plan3test/finalfix_migration_test.go b/internal/plan3test/finalfix_migration_test.go
new file mode 100644
index 00000000..74081ab6
--- /dev/null
+++ b/internal/plan3test/finalfix_migration_test.go
@@ -0,0 +1,14 @@
+package plan3test
+
+import "testing"
+
+func TestFinalFixSQLDefaults(t *testing.T) {
+ f := newFixture(t)
+ for name, want := range map[string]string{"kind": "'bug'", "replacement_id": "''", "replaces_id": "''"} {
+ var got string
+ must(t, f.DB.Writer().QueryRow("SELECT dflt_value FROM pragma_table_info('tasks') WHERE name=?", name).Scan(&got))
+ if got != want {
+ t.Errorf("%s default %s, want %s", name, got, want)
+ }
+ }
+}
diff --git a/internal/plan3test/finalfix_notifications_test.go b/internal/plan3test/finalfix_notifications_test.go
new file mode 100644
index 00000000..a8751348
--- /dev/null
+++ b/internal/plan3test/finalfix_notifications_test.go
@@ -0,0 +1,63 @@
+package plan3test
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo"
+ "testing"
+)
+
+func TestFinalFixOwnPlanNotifications(t *testing.T) {
+ f := newFixture(t)
+ p := proposed(t, f)
+ f.planConnections(t, p.ProjectID)
+ count := func() int64 {
+ return f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=? AND event='task_ready.plan' AND state='unread'", p.TaskID)
+ }
+ if count() != 0 {
+ t.Error("own proposal notified")
+ }
+ notificationPlanWait(t, f, p.TaskID)
+ if count() != 1 {
+ t.Fatal("approval wait did not notify")
+ }
+ p.Steps[0].Instructions = "personal edit"
+ var err error
+ p, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "edit", Revision: p.Revision})
+ must(t, err)
+ if count() != 0 {
+ t.Error("own edit notified")
+ }
+ _, err = f.Store.ApprovePlan(ctx, owner, p.TaskID, equipo.Mutation{RequestID: "approve", Revision: p.Revision})
+ must(t, err)
+ if count() != 0 {
+ t.Error("own approval notified")
+ }
+}
+func TestFinalFixCoordinatorNotification(t *testing.T) {
+ f, x, principal, c := claimTools(t)
+ project := f.count(t, "SELECT id FROM projects LIMIT 1")
+ must(t, f.Store.SetProjectApproval(ctx, owner, project, equipo.ApprovalRequired, equipo.Mutation{RequestID: "required"}))
+ result := toolCall(t, x, principal, c, "proposal", "propose_plan", proposalArgs(c.Turn.MessageID, project))
+ count := func() int64 {
+ return f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=? AND event='task_ready.plan' AND state='unread'", result.ResourceID)
+ }
+ if count() != 1 {
+ t.Fatal("coordinator approval proposal did not notify")
+ }
+ if f.count(t, "SELECT count(*) FROM plan_requests WHERE resource='' AND operation='plan.propose' AND principal=?", "coordinator:"+c.Binding.ID) != 1 {
+ t.Error("coordinator used person's request namespace")
+ }
+ _, err := f.Store.ApprovePlan(ctx, owner, result.ResourceID, equipo.Mutation{RequestID: "approve", Revision: result.Revision})
+ must(t, err)
+ if count() != 0 {
+ t.Fatal("approval left ready notification")
+ }
+}
+
+func TestFinalFixImmediateCoordinatorNotification(t *testing.T) {
+ f, x, principal, c := claimTools(t)
+ project := f.count(t, "SELECT id FROM projects LIMIT 1")
+ result := toolCall(t, x, principal, c, "immediate-proposal", "propose_plan", proposalArgs(c.Turn.MessageID, project))
+ if f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=? AND event='task_ready.plan'", result.ResourceID) != 0 {
+ t.Fatal("automatic plan notified for approval")
+ }
+}
diff --git a/internal/plan3test/finalfix_revisions_test.go b/internal/plan3test/finalfix_revisions_test.go
new file mode 100644
index 00000000..2df8701b
--- /dev/null
+++ b/internal/plan3test/finalfix_revisions_test.go
@@ -0,0 +1,53 @@
+package plan3test
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/personapi"
+ "fmt"
+ "testing"
+)
+
+func TestFinalFixDeviceExchangeRevision(t *testing.T) {
+ f := newFixture(t)
+ c, key := deviceChallenge(t, f)
+ expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/auth/devices/"+c.ID+"/approve", fmt.Sprintf(`{"typed_code":%q}`, c.UserCode), "approve", `"1"`), 200)
+ f.exec(t, "UPDATE person_devices SET revision=17 WHERE id=?", c.ID)
+ w := deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", signedDevice(t, f, c, key), "exchange", "")
+ expectHTTP(t, w, 200)
+ if w.Header().Get("ETag") != `"18"` {
+ t.Fatal("synthetic exchange revision", w.Header().Get("ETag"))
+ }
+}
+func TestFinalFixAckRevision(t *testing.T) {
+ f := newFixture(t)
+ c := approvedDevice(t, f)
+ path := "/api/v1/auth/devices/" + c.ID
+ f.exec(t, "CREATE TRIGGER advance_device_revision AFTER UPDATE ON person_devices WHEN NEW.revoked_at IS NOT NULL AND OLD.revoked_at IS NULL BEGIN UPDATE person_devices SET revision=revision+5 WHERE id=NEW.id; END")
+ w := apiRequest(t, f, owner, "DELETE", path, `{}`, "revoke", `"3"`)
+ expectHTTP(t, w, 200)
+ actual := f.count(t, "SELECT revision FROM person_devices WHERE id=?", c.ID)
+ if w.Header().Get("ETag") != fmt.Sprintf(`"%d"`, actual) || apiValue[personapi.Ack](t, w).Revision != actual {
+ t.Fatal("synthetic ack revision", w.Header(), w.Body.String(), actual)
+ }
+}
+
+func TestFinalFixAckSelfDemotion(t *testing.T) {
+ f := newFixture(t)
+ revision := f.count(t, "SELECT revision FROM members WHERE address=?", owner.Address)
+ w := apiRequest(t, f, owner, "PUT", "/api/v1/roster/"+owner.Address, `{"role":"member","active":true}`, "demote", fmt.Sprintf(`"%d"`, revision))
+ expectHTTP(t, w, 200)
+ actual := f.count(t, "SELECT revision FROM members WHERE address=?", owner.Address)
+ if apiValue[personapi.Ack](t, w).Revision != actual {
+ t.Fatal("wrong self-demotion revision")
+ }
+}
+
+func TestFinalFixAckReadback(t *testing.T) {
+ f, _ := modelChoiceFixture(t)
+ f.exec(t, "CREATE TRIGGER connection_revision_jump AFTER UPDATE ON connections WHEN NEW.label IS NOT OLD.label BEGIN UPDATE connections SET revision=revision+5 WHERE id=NEW.id; END")
+ w := apiRequest(t, f, owner, "PATCH", "/api/v1/connections/claude", `{"label":"Renamed account"}`, "rename", `"1"`)
+ expectHTTP(t, w, 200)
+ actual := f.count(t, "SELECT revision FROM connections WHERE id='claude'")
+ if apiValue[personapi.Ack](t, w).Revision != actual || w.Header().Get("ETag") != fmt.Sprintf(`"%d"`, actual) {
+ t.Fatal("ack did not read the stored revision", w.Body.String(), actual)
+ }
+}
diff --git a/internal/plan3test/migration_test.go b/internal/plan3test/migration_test.go
index da627499..09539191 100644
--- a/internal/plan3test/migration_test.go
+++ b/internal/plan3test/migration_test.go
@@ -19,7 +19,7 @@ func TestConversationMigrationUpgrade(t *testing.T) {
t.Cleanup(func() { must(t, d.Close()) })
old := &migrate.Set{}
for _, m := range equipo.BootSchema.All() {
- if m.ID != "equipo/0019_conversation" && m.ID != "equipo/0021_coordinator_sources" && m.ID != "equipo/0031_notifications" {
+ if m.ID != "equipo/0019_conversation" && m.ID != "equipo/0021_coordinator_sources" && m.ID != "equipo/0031_notifications" && m.ID != "equipo/0033_plan_notifications" {
old.Add(m)
}
}
@@ -33,7 +33,7 @@ func TestConversationMigrationUpgrade(t *testing.T) {
before := f.count(t, "SELECT count(*) FROM audit_events")
result, e := migrate.Apply(ctx, d, equipo.BootSchema)
must(t, e)
- if !reflect.DeepEqual(result.Applied, []string{"equipo/0019_conversation", "equipo/0021_coordinator_sources", "equipo/0031_notifications"}) {
+ if !reflect.DeepEqual(result.Applied, []string{"equipo/0019_conversation", "equipo/0021_coordinator_sources", "equipo/0031_notifications", "equipo/0033_plan_notifications"}) {
t.Fatal("wrong upgrade", result.Applied)
}
var saved equipo.Task
diff --git a/internal/plan3test/notifications_fixture.go b/internal/plan3test/notifications_fixture.go
index e233535c..df5fc2e1 100644
--- a/internal/plan3test/notifications_fixture.go
+++ b/internal/plan3test/notifications_fixture.go
@@ -21,3 +21,8 @@ func notificationRouter(t *testing.T, f *fixture, s *equipo.Store) {
f.Store = s
f.Handler = equipo.Mux(h)
}
+
+func notificationPlanWait(t *testing.T, f *fixture, id string) {
+ t.Helper()
+ f.exec(t, "UPDATE tasks SET wait_code='plan.awaiting_approval' WHERE id=?", id)
+}
diff --git a/internal/plan3test/notifications_lifecycle_test.go b/internal/plan3test/notifications_lifecycle_test.go
index b11f3f80..c83bda38 100644
--- a/internal/plan3test/notifications_lifecycle_test.go
+++ b/internal/plan3test/notifications_lifecycle_test.go
@@ -24,7 +24,7 @@ func TestNotificationExplicitRenewal(t *testing.T) {
t.Fatal("subscription lacks independent 30 day cap")
}
f.task(t, owner, "renew")
- f.exec(t, "UPDATE tasks SET state='proposed',revision=2 WHERE id='renew'")
+ f.exec(t, "UPDATE tasks SET state='proposed',revision=2,plan_revision=1,wait_code='plan.awaiting_approval' WHERE id='renew'")
page := notificationFeed(t, f, d, sub.Cursor)
clock.at = clock.at.Add(time.Hour)
page = notificationFeed(t, f, d, page.NextCursor)
@@ -107,7 +107,7 @@ func TestNotificationAuditAndRevocationRollback(t *testing.T) {
d := approvedDevice(t, f)
sub := notificationSubscription(t, f, d)
f.task(t, owner, "audit")
- f.exec(t, "UPDATE tasks SET state='proposed',revision=2 WHERE id='audit'")
+ f.exec(t, "UPDATE tasks SET state='proposed',revision=2,plan_revision=1,wait_code='plan.awaiting_approval' WHERE id='audit'")
page := notificationFeed(t, f, d, sub.Cursor)
f.exec(t, "CREATE TRIGGER notification_audit_refusal BEFORE INSERT ON audit_events WHEN NEW.kind IN ('notifications.ack','person_device.revoke') BEGIN SELECT RAISE(ABORT,'fixture'); END")
if err := f.Store.AcknowledgeNotification(ctx, owner, sub.ID, page.Items[0].ID, equipo.Mutation{RequestID: "fail", Revision: 1}); err == nil {
@@ -142,6 +142,9 @@ func TestNotificationPrivateInvalidation(t *testing.T) {
spy := &preferenceNotifications{}
f.Store.SetJobNotifier(spy)
p := proposed(t, f)
+ x, _, _ := f.planCore(t, p)
+ must(t, f.Store.SetProjectApproval(ctx, owner, p.ProjectID, equipo.ApprovalRequired, equipo.Mutation{RequestID: "required"}))
+ must(t, x.Sync(ctx))
topic := notifications.Topic(f.TeamID, owner.Address, sub.ID)
found := false
for _, got := range spy.topics {
@@ -224,7 +227,7 @@ func TestNotificationAckLostWrite(t *testing.T) {
d := approvedDevice(t, f)
sub := notificationSubscription(t, f, d)
f.task(t, owner, "lost-write")
- f.exec(t, "UPDATE tasks SET state='proposed',revision=2 WHERE id='lost-write'")
+ f.exec(t, "UPDATE tasks SET state='proposed',revision=2,plan_revision=1,wait_code='plan.awaiting_approval' WHERE id='lost-write'")
page := notificationFeed(t, f, d, sub.Cursor)
f.exec(t, "CREATE TRIGGER skip_notification_update BEFORE UPDATE ON notification_subscriptions BEGIN SELECT RAISE(IGNORE); END")
expectHTTP(t, deviceRequest(t, f, d.Token, "POST", "/api/v1/notification-subscriptions/"+sub.ID+"/ack", fmt.Sprintf(`{"notification_id":%q}`, page.Items[0].ID), "lost-write", `"1"`), 409)
diff --git a/internal/plan3test/notifications_migration_test.go b/internal/plan3test/notifications_migration_test.go
index ac59124f..0dbef606 100644
--- a/internal/plan3test/notifications_migration_test.go
+++ b/internal/plan3test/notifications_migration_test.go
@@ -17,7 +17,7 @@ func TestNotificationMigrationUpgrade(t *testing.T) {
must(t, err)
old := &migrate.Set{}
for _, m := range equipo.BootSchema.All() {
- if m.ID != "equipo/0031_notifications" {
+ if m.ID != "equipo/0031_notifications" && m.ID != "equipo/0033_plan_notifications" {
old.Add(m)
}
}
@@ -29,11 +29,11 @@ func TestNotificationMigrationUpgrade(t *testing.T) {
must(t, err)
var team string
must(t, d.Writer().QueryRow("SELECT id FROM teams").Scan(&team))
- _, err = d.Writer().Exec("INSERT INTO tasks(id,requester,request_id,team_id,revision,state) VALUES('old-task',?,'old-task',?,1,'proposed')", owner.Address, team)
+ _, err = d.Writer().Exec("INSERT INTO tasks(id,requester,request_id,team_id,revision,state,plan_revision,wait_code) VALUES('old-task',?,'old-task',?,1,'proposed',1,'plan.awaiting_approval')", owner.Address, team)
must(t, err)
applied, err := migrate.Apply(ctx, d, equipo.BootSchema)
must(t, err)
- if len(applied.Applied) != 1 || applied.Applied[0] != "equipo/0031_notifications" {
+ if len(applied.Applied) != 2 || applied.Applied[0] != "equipo/0031_notifications" {
t.Fatal(applied)
}
var n int
diff --git a/internal/plan3test/notifications_test.go b/internal/plan3test/notifications_test.go
index f2073539..3365728a 100644
--- a/internal/plan3test/notifications_test.go
+++ b/internal/plan3test/notifications_test.go
@@ -84,12 +84,14 @@ func TestNotificationOutboxAtomic(t *testing.T) {
f.exec(t, "DROP TRIGGER fail_notification_audit")
f = newFixture(t)
plan := proposed(t, f)
+ notificationPlanWait(t, f, plan.TaskID)
if f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=? AND kind='task_ready'", plan.TaskID) != 1 {
t.Fatal("plan card notification missing")
}
plan.Steps[0].Instructions = "changed"
_, err := f.Store.EditPlan(ctx, owner, plan, equipo.Mutation{RequestID: "edit", Revision: 1})
must(t, err)
+ notificationPlanWait(t, f, plan.TaskID)
if f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=? AND resource_revision=2", plan.TaskID) != 1 {
t.Fatal("plan revision notification missing")
}
@@ -102,6 +104,7 @@ func TestNotificationRecipientIsolation(t *testing.T) {
d := approvedDevice(t, f)
s := notificationSubscription(t, f, d)
p := proposed(t, f)
+ notificationPlanWait(t, f, p.TaskID)
own := notificationFeed(t, f, d, s.Cursor)
if len(own.Items) != 1 || own.Items[0].ResourceID != p.TaskID {
t.Fatal("missing own notification", own)
@@ -144,9 +147,9 @@ func TestNotificationReconnect(t *testing.T) {
sa := notificationSubscription(t, f, a)
sb := notificationSubscription(t, f, b)
f.task(t, owner, "first")
- f.exec(t, "UPDATE tasks SET state='proposed',revision=2 WHERE id='first'")
+ f.exec(t, "UPDATE tasks SET state='proposed',revision=2,plan_revision=1,wait_code='plan.awaiting_approval' WHERE id='first'")
f.task(t, owner, "second")
- f.exec(t, "UPDATE tasks SET state='proposed',revision=2 WHERE id='second'")
+ f.exec(t, "UPDATE tasks SET state='proposed',revision=2,plan_revision=1,wait_code='plan.awaiting_approval' WHERE id='second'")
// No delivery on B means no acknowledgement authority, even for the same person.
pa := notificationFeed(t, f, a, sa.Cursor)
if len(pa.Items) != 2 {
@@ -222,7 +225,7 @@ func TestNotificationSubscriptionExpiry(t *testing.T) {
t.Fatal("subscription exceeds credential expiry", sub.ExpiresAt, d.ExpiresAt)
}
f.task(t, owner, "pending")
- f.exec(t, "UPDATE tasks SET state='proposed',revision=2 WHERE id='pending'")
+ f.exec(t, "UPDATE tasks SET state='proposed',revision=2,plan_revision=1,wait_code='plan.awaiting_approval' WHERE id='pending'")
page := notificationFeed(t, f, d, sub.Cursor)
if len(page.Items) != 1 {
t.Fatal("pending work absent")
@@ -328,7 +331,7 @@ func TestNotificationRetentionAndCursor(t *testing.T) {
s := equipo.NewStore(f.DB, equipo.WithRunnerClock(clock))
notificationRouter(t, f, s)
f.task(t, owner, "retained")
- f.exec(t, "UPDATE tasks SET state='proposed',revision=2 WHERE id='retained'")
+ f.exec(t, "UPDATE tasks SET state='proposed',revision=2,plan_revision=1,wait_code='plan.awaiting_approval' WHERE id='retained'")
page := notificationFeed(t, f, d, sub.Cursor)
notificationAck(t, f, d, sub, page.Items[0].ID, "ack", `"1"`)
// Cursor remains cryptographically fresh; the retained-history boundary changed.
diff --git a/internal/plan3test/onboarding_acceptance_test.go b/internal/plan3test/onboarding_acceptance_test.go
index 8d068ed6..b28b7371 100644
--- a/internal/plan3test/onboarding_acceptance_test.go
+++ b/internal/plan3test/onboarding_acceptance_test.go
@@ -202,8 +202,8 @@ func acceptanceOnboarding(t *testing.T) {
}
}
request("POST", "/tasks/"+plan.TaskID+"/plan/approve", `{}`, "approve", `"1"`)
- if f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=? AND resource_revision=1 AND recipient=?", plan.TaskID, invitee.Address) != 1 {
- t.Fatal("proposal did not create one durable notification")
+ if f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=? AND resource_revision=1 AND recipient=?", plan.TaskID, invitee.Address) != 0 {
+ t.Fatal("own proposal or approval created a notification")
}
request("POST", "/tasks/"+plan.TaskID+"/plan/approve", `{}`, "approve", `"1"`)
if f.count(t, "SELECT count(*) FROM audit_events WHERE kind='plan.approve' AND actor=?", invitee.Address) != 1 {
diff --git a/internal/plan3test/person_api_migration_test.go b/internal/plan3test/person_api_migration_test.go
index 9f02a792..39ddd842 100644
--- a/internal/plan3test/person_api_migration_test.go
+++ b/internal/plan3test/person_api_migration_test.go
@@ -80,7 +80,7 @@ func TestPersonAPIDeviceMigrationUpgrade(t *testing.T) {
must(t, err)
old := &migrate.Set{}
for _, m := range equipo.BootSchema.All() {
- if m.ID != "equipo/0030_person_devices" && m.ID != "equipo/0030_person_devices_usage" && m.ID != "equipo/0031_notifications" {
+ if m.ID != "equipo/0030_person_devices" && m.ID != "equipo/0030_person_devices_usage" && m.ID != "equipo/0031_notifications" && m.ID != "equipo/0033_plan_notifications" {
old.Add(m)
}
}
@@ -92,7 +92,7 @@ func TestPersonAPIDeviceMigrationUpgrade(t *testing.T) {
must(t, err)
result, err := migrate.Apply(ctx, d, equipo.BootSchema)
must(t, err)
- if len(result.Applied) != 3 || result.Applied[0] != "equipo/0030_person_devices" || result.Applied[1] != "equipo/0030_person_devices_usage" || result.Applied[2] != "equipo/0031_notifications" {
+ if len(result.Applied) != 4 || result.Applied[0] != "equipo/0030_person_devices" || result.Applied[1] != "equipo/0030_person_devices_usage" || result.Applied[2] != "equipo/0031_notifications" {
t.Fatal(result.Applied)
}
f := newFixture(t)
diff --git a/internal/plan3test/plan3_upgrade_test.go b/internal/plan3test/plan3_upgrade_test.go
index f19f66c9..d8ed59d1 100644
--- a/internal/plan3test/plan3_upgrade_test.go
+++ b/internal/plan3test/plan3_upgrade_test.go
@@ -18,7 +18,7 @@ import (
)
func TestPlan3Upgrade(t *testing.T) {
- for _, version := range []string{"0018", "0023"} {
+ for _, version := range []string{"0018", "0023", "main"} {
t.Run(version, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "upgrade.db")
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
@@ -27,13 +27,20 @@ func TestPlan3Upgrade(t *testing.T) {
defer func() { must(t, d.Close()) }()
before := &migrate.Set{}
for _, m := range equipo.BootSchema.All() {
- if !strings.HasPrefix(m.ID, "equipo/") || strings.Split(strings.TrimPrefix(m.ID, "equipo/"), "_")[0] <= version {
+ if !strings.HasPrefix(m.ID, "equipo/") || version == "main" && m.ID == "equipo/0019_direct_reconcile" || strings.Split(strings.TrimPrefix(m.ID, "equipo/"), "_")[0] <= map[string]string{"0018": "0018", "0023": "0023", "main": "0018"}[version] {
before.Add(m)
}
}
_, err = migrate.Apply(ctx, d, before)
must(t, err)
f := &fixture{DB: d}
+ if version == "main" {
+ var n int
+ must(t, d.Writer().QueryRow("SELECT count(*) FROM audit_events WHERE kind='system.migration.direct_reconcile'").Scan(&n))
+ if n == 0 {
+ t.Fatal("main baseline missing 0019_direct_reconcile")
+ }
+ }
upgradeRow(t, f, "teams", map[string]any{"id": "saved-team", "name": "Existing team", "roster_epoch": 7})
upgradeRow(t, f, "members", map[string]any{"address": owner.Address, "role": "owner", "active": 1, "revision": 4, "session_epoch": 123})
upgradeRow(t, f, "projects", map[string]any{"id": 1, "name": "Existing project", "repository": "amadan.net/test/upgrade", "default_branch": "main", "revision": 3, "grant_version": 3})
@@ -53,6 +60,11 @@ func TestPlan3Upgrade(t *testing.T) {
if version == "0023" {
for _, id := range []string{"saved-1", "saved-2"} {
plan := taskplan.BugPlan(id, 1)
+ if id == "saved-2" {
+ plan.Kind = taskplan.Feature
+ plan.Steps[0] = taskplan.Step{Key: "scope", Specialist: "product", Action: "scope"}
+ f.exec(t, "UPDATE tasks SET kind='feature',replacement_id='retained-replacement',replaces_id='retained-source' WHERE id=?", id)
+ }
raw, e := json.Marshal(plan)
must(t, e)
upgradeRow(t, f, "plan_revisions", map[string]any{"task_id": id, "revision": 1, "plan": string(raw), "actor": owner.Address, "actor_kind": "person", "changed_keys": "[]"})
@@ -83,7 +95,7 @@ func TestPlan3Upgrade(t *testing.T) {
t.Fatalf("upgrade changed %s: %s -> %s", table, saved[table], got)
}
}
- if version == "0018" && f.count(t, "SELECT count(*) FROM plan_revisions WHERE revision=1") != 2 {
+ if version != "0023" && f.count(t, "SELECT count(*) FROM plan_revisions WHERE revision=1") != 2 {
t.Fatal("historical task plans not backfilled")
}
fresh := newFixture(t)
diff --git a/internal/plan3test/plan_model_choice_test.go b/internal/plan3test/plan_model_choice_test.go
index 879c2f6f..395d1e36 100644
--- a/internal/plan3test/plan_model_choice_test.go
+++ b/internal/plan3test/plan_model_choice_test.go
@@ -120,7 +120,7 @@ func TestPlanModelChoiceImmutableStep(t *testing.T) {
s := pick(t, f, p, "reproduce")
raw, e := json.Marshal(s)
must(t, e)
- f.exec(t, `INSERT INTO runner_assignments(id,task_id,step_key,claim_request,selection,state) VALUES('actual',?,'reproduce','claimed',?,'claimed')`, p.TaskID, string(raw))
+ f.exec(t, `INSERT INTO runner_assignments(id,task_id,job_id,step_key,claim_request,selection,state) VALUES('actual',?,0,'reproduce','claimed',?,'claimed')`, p.TaskID, string(raw))
must(t, f.Store.SaveConnectionChoice(ctx, owner, equipo.ConnectionChoice{ProjectID: p.ProjectID, Revision: 1, ConnectionIDs: []string{"claude-two", "codex"}, Mode: "pinned", PinnedID: "claude-two"}))
actual, e := f.Store.SelectPlanStep(ctx, owner, p.TaskID, "reproduce", equipo.Mutation{RequestID: "after-change", Revision: p.Revision})
must(t, e)
diff --git a/internal/plan3test/plan_workflow_test.go b/internal/plan3test/plan_workflow_test.go
index 0ddd7b82..83ef523e 100644
--- a/internal/plan3test/plan_workflow_test.go
+++ b/internal/plan3test/plan_workflow_test.go
@@ -132,7 +132,7 @@ func planReadDelivery(t *testing.T, investigation bool) {
next := taskplan.BugPlan(p.TaskID, p.ProjectID)
next.Revision = p.Revision
next.Kind = taskplan.Feature
- next.Steps[0] = taskplan.Step{Key: "scope", Specialist: "product", Action: "scope"}
+ next.Steps[0] = taskplan.Step{Key: "research", Specialist: "product", Action: "scope"}
next, err = f.Store.EditPlan(ctx, owner, next, equipo.Mutation{RequestID: "explicit-build-revision", Revision: p.Revision})
must(t, err)
task, err = f.Store.Task(ctx, owner, p.TaskID)
@@ -145,6 +145,38 @@ func planReadDelivery(t *testing.T, investigation bool) {
if old.State != team.JobSucceeded {
t.Fatal("historical research changed")
}
+
+ // A retained runner reconciliation record belongs to the old job too.
+ f.exec(t, "UPDATE runner_assignments SET state='reconcile' WHERE id=?", id)
+ // A completed investigation must not bind the replacement to its runner.
+ f.exec(t, "INSERT INTO runners(id,person,instance_id,revision) VALUES('second-runner',?,?,1)", owner.Address, f.TeamID)
+ f.exec(t, "UPDATE connections SET runner_id='second-runner',revision=revision+1")
+ f.exec(t, "INSERT INTO runner_credentials(id,runner_id,instance_id,audience,person,machine_key_hash,token_hash,expires_at) VALUES('second-credential','second-runner',?,?,?,'','second-token',?)", f.TeamID, runnerproto.RunnerAudience, owner.Address, time.Now().Add(time.Hour).UTC())
+ must(t, x.Sync(ctx))
+ task, err = f.Store.Task(ctx, owner, p.TaskID)
+ must(t, err)
+ if task.State != "preparing" {
+ t.Fatal("replacement did not prepare on new runner", task.State, task.WaitCode)
+ }
+ var project equipo.Project
+ must(t, f.DB.G.First(&project, p.ProjectID).Error)
+ second := equipo.RunnerPrincipal{RunnerID: "second-runner", Person: owner.Address, CredentialID: "second-credential"}
+ definition := []byte("checkpoint check")
+ task, err = f.Store.PrepareBug(ctx, second, p.TaskID, task.Revision, equipo.PreparedBug{Repository: project.Repository, DefaultBranch: project.DefaultBranch, BaseCommit: strings.Repeat("a", 40), CheckDefinition: definition, CheckDefinitionHash: team.ContentDigest(definition), BaselineTestSetHash: strings.Repeat("b", 64)})
+ must(t, err)
+ task, err = f.Store.StartBug(ctx, second, p.TaskID, task.Revision)
+ must(t, err)
+ if task.JobID == beforeJob {
+ t.Fatal("replacement reused historical job")
+ }
+ must(t, x.Sync(ctx))
+ var nextID string
+ must(t, f.DB.Writer().QueryRow("SELECT id,revision FROM runner_assignments WHERE task_id=? AND job_id=? AND step_key='research' AND state='pending'", p.TaskID, task.JobID).Scan(&nextID, &rev))
+ nextClaim, err := x.Claim(ctx, second, equipo.ClaimRequest{Version: 2, AssignmentID: nextID, Revision: rev, RequestID: "replacement-claim"})
+ must(t, err)
+ if nextClaim.Brief.Step.PlanRevision != next.Revision || nextClaim.Brief.Selection.RunnerID != "second-runner" {
+ t.Fatal("stale replacement dispatch", nextClaim.Brief.Step)
+ }
return
}
for _, column := range []string{"project", "budget", "plan", "choice"} {
diff --git a/internal/plan3test/plans_migration_test.go b/internal/plan3test/plans_migration_test.go
index 6cb1f733..8b449d25 100644
--- a/internal/plan3test/plans_migration_test.go
+++ b/internal/plan3test/plans_migration_test.go
@@ -23,7 +23,7 @@ func TestPlanMigrationUpgrade(t *testing.T) {
t.Cleanup(func() { must(t, d.Close()) })
old := &migrate.Set{}
for _, m := range equipo.BootSchema.All() {
- if m.ID != "equipo/0020_plans" {
+ if m.ID != "equipo/0020_plans" && m.ID != "equipo/0032_plan_defaults" && m.ID != "equipo/0033_plan_notifications" {
old.Add(m)
}
}
@@ -36,7 +36,7 @@ func TestPlanMigrationUpgrade(t *testing.T) {
audits := f.count(t, "SELECT count(*) FROM audit_events")
result, err := migrate.Apply(ctx, d, equipo.BootSchema)
must(t, err)
- if !reflect.DeepEqual(result.Applied, []string{"equipo/0020_plans"}) {
+ if !reflect.DeepEqual(result.Applied, []string{"equipo/0020_plans", "equipo/0032_plan_defaults", "equipo/0033_plan_notifications"}) {
t.Fatal("wrong migration", result.Applied)
}
var task equipo.Task
diff --git a/internal/runner/setup/account_command.go b/internal/runner/setup/account_command.go
index 54dbae3a..093304e4 100644
--- a/internal/runner/setup/account_command.go
+++ b/internal/runner/setup/account_command.go
@@ -1,7 +1,9 @@
package runnersetup
import (
+ "amadan.net/oficina/equipo/internal/runnerproto"
"context"
+ "errors"
"time"
"amadan.net/oficina/equipo/internal/runner/provider"
@@ -19,24 +21,34 @@ func RunAccountLogin(ctx context.Context, l *AccountLogin, id string) error {
_ = l.Cancel(cleanup)
}
}()
- ticker := time.NewTicker(100 * time.Millisecond)
- defer ticker.Stop()
+ delay := time.Second
+ timer := time.NewTimer(delay)
+ defer timer.Stop()
retries := 0
for {
select {
case <-ctx.Done():
return context.Canceled
- case <-ticker.C:
+ case <-timer.C:
out, err := l.Poll(ctx)
if err != nil {
+ if errors.Is(err, runnerproto.ErrTransient) && l.active != nil && time.Now().Before(l.active.challenge.ExpiresAt) {
+ delay = min(delay*2, 30*time.Second)
+ timer.Reset(delay)
+ continue
+ }
if l.Saved() && retries < 3 {
retries++
+ timer.Reset(min(time.Duration(1<<retries)*time.Second, 30*time.Second))
continue
}
return err
}
switch out.State {
case "pending":
+ delay = time.Second
+ retries = 0
+ timer.Reset(delay)
case "connected":
return nil
case "expired":
diff --git a/internal/runner/setup/account_login.go b/internal/runner/setup/account_login.go
index 6b2add32..d6b4e04a 100644
--- a/internal/runner/setup/account_login.go
+++ b/internal/runner/setup/account_login.go
@@ -5,6 +5,7 @@ import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
+ "errors"
"os"
"path/filepath"
"time"
@@ -23,6 +24,8 @@ type accountLogin struct {
home string
marker string
saved *runnerproto.AccountSetupResult
+ result *provider.LoginResult
+ binding *provider.Binding
}
type AccountLogin struct {
Root, RunnerID string
@@ -124,6 +127,9 @@ func (l *AccountLogin) current(ctx context.Context) error {
}
s, e := l.Instance.AccountSetup(ctx, l.active.setup.ID)
if e != nil {
+ if errors.Is(e, runnerproto.ErrTransient) {
+ return e
+ }
_ = l.Driver.Cancel(ctx, l.active.challenge.ID)
return e
}
@@ -138,9 +144,15 @@ func (l *AccountLogin) Poll(ctx context.Context) (runnerproto.AccountSetup, erro
return l.reportSaved(ctx)
}
if err := l.current(ctx); err != nil {
+ if errors.Is(err, runnerproto.ErrTransient) && ctx.Err() == nil && time.Now().Before(l.active.challenge.ExpiresAt) {
+ return runnerproto.AccountSetup{}, err
+ }
if l.interrupted(ctx) {
return runnerproto.AccountSetup{}, ctx.Err()
}
+ if errors.Is(err, runnerproto.ErrTransient) {
+ _ = l.Driver.Cancel(ctx, l.active.challenge.ID)
+ }
l.cleanup()
return runnerproto.AccountSetup{}, err
}
@@ -148,7 +160,11 @@ func (l *AccountLogin) Poll(ctx context.Context) (runnerproto.AccountSetup, erro
r := provider.LoginResult{State: "expired"}
var err error
if time.Now().Before(a.challenge.ExpiresAt) {
- r, err = l.Driver.Poll(ctx, a.challenge.ID)
+ if a.result != nil {
+ r = *a.result
+ } else {
+ r, err = l.Driver.Poll(ctx, a.challenge.ID)
+ }
} else {
_ = l.Driver.Cancel(ctx, a.challenge.ID)
}
@@ -170,28 +186,37 @@ func (l *AccountLogin) Poll(ctx context.Context) (runnerproto.AccountSetup, erro
return runnerproto.AccountSetup{}, provider.ErrContract
}
q := runnerproto.AccountSetupResult{ID: a.setup.ID, Revision: a.setup.Revision, State: r.State}
+
if r.State == "connected" {
- b, err := l.verify(ctx, r.Identity)
- if err != nil {
- if l.interrupted(ctx) {
- return runnerproto.AccountSetup{}, ctx.Err()
+ a.result = &r
+ if a.binding == nil {
+ b, err := l.verify(ctx, r.Identity)
+ if err != nil {
+ if l.interrupted(ctx) {
+ return runnerproto.AccountSetup{}, ctx.Err()
+ }
+ _ = l.Driver.Cancel(ctx, a.challenge.ID)
+ _, _ = l.Instance.ReportAccountSetup(ctx, runnerproto.AccountSetupResult{ID: a.setup.ID, Revision: a.setup.Revision, State: "unavailable"})
+ l.cleanup()
+ return runnerproto.AccountSetup{}, err
}
- _ = l.Driver.Cancel(ctx, a.challenge.ID)
- _, _ = l.Instance.ReportAccountSetup(ctx, runnerproto.AccountSetupResult{ID: a.setup.ID, Revision: a.setup.Revision, State: "unavailable"})
- l.cleanup()
- return runnerproto.AccountSetup{}, err
+ a.binding = &b
}
if err = l.current(ctx); err != nil {
+ if errors.Is(err, runnerproto.ErrTransient) && ctx.Err() == nil {
+ return runnerproto.AccountSetup{}, err
+ }
if l.interrupted(ctx) {
return runnerproto.AccountSetup{}, ctx.Err()
}
l.cleanup()
return runnerproto.AccountSetup{}, err
}
+
if l.Save == nil {
return runnerproto.AccountSetup{}, provider.ErrContract
}
- if err = l.Save(ctx, a.setup, b); err != nil {
+ if err = l.Save(ctx, a.setup, *a.binding); err != nil {
if l.interrupted(ctx) {
return runnerproto.AccountSetup{}, ctx.Err()
}
diff --git a/internal/runner/setup/account_login_test.go b/internal/runner/setup/account_login_test.go
index b78d9423..e2c3181c 100644
--- a/internal/runner/setup/account_login_test.go
+++ b/internal/runner/setup/account_login_test.go
@@ -9,6 +9,7 @@ import (
"path/filepath"
"strings"
"testing"
+ "testing/synctest"
"time"
"amadan.net/oficina/equipo/internal/runner/provider"
@@ -396,3 +397,161 @@ func TestOnboardingAccountInterruptDuringProbe(t *testing.T) {
t.Fatal("interrupted probe retained home")
}
}
+
+type transientInstance struct {
+ *loginInstance
+ fail bool
+}
+
+func (i *transientInstance) AccountSetup(ctx context.Context, id string) (runnerproto.AccountSetup, error) {
+ if i.fail {
+ return runnerproto.AccountSetup{}, runnerproto.ErrTransient
+ }
+ return i.loginInstance.AccountSetup(ctx, id)
+}
+func TestFinalFixAccountTransientPoll(t *testing.T) {
+ l, d, base := loginHarness(t, "codex")
+ i := &transientInstance{loginInstance: base}
+ l.Instance = i
+ if _, err := l.Begin(context.Background(), base.setup.ID); err != nil {
+ t.Fatal(err)
+ }
+ i.fail = true
+ if _, err := l.Poll(context.Background()); !errors.Is(err, runnerproto.ErrTransient) {
+ t.Fatal("transient error lost", err)
+ }
+ if d.cancelled || l.active == nil {
+ t.Fatal("network error cancelled in-progress login")
+ }
+ if _, err := os.Stat(d.home); err != nil {
+ t.Fatal("network error deleted login home", err)
+ }
+ i.fail = false
+ out, err := l.Poll(context.Background())
+ if err != nil || out.State != "pending" {
+ t.Fatal("login could not continue", out, err)
+ }
+ if err = l.Cancel(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+}
+
+type commandRetryInstance struct {
+ *loginInstance
+ calls []time.Time
+ stop context.CancelFunc
+ driver *loginFixture
+}
+
+func (i *commandRetryInstance) AccountSetup(ctx context.Context, id string) (runnerproto.AccountSetup, error) {
+ i.calls = append(i.calls, time.Now())
+ if len(i.calls) == 2 {
+ return runnerproto.AccountSetup{}, runnerproto.ErrTransient
+ }
+ if len(i.calls) == 3 {
+ i.stop()
+ }
+ return i.loginInstance.AccountSetup(ctx, id)
+}
+func TestFinalFixAccountPollBackoff(t *testing.T) {
+ l, d, base := loginHarness(t, "claude")
+ ctx, stop := context.WithTimeout(context.Background(), 6*time.Second)
+ defer stop()
+ i := &commandRetryInstance{loginInstance: base, stop: stop, driver: d}
+ l.Instance = i
+ _ = RunAccountLogin(ctx, l, base.setup.ID)
+ if len(i.calls) < 3 {
+ t.Fatal("transient poll was not retried", len(i.calls))
+ }
+ if i.calls[1].Sub(i.calls[0]) < time.Second || i.calls[2].Sub(i.calls[1]) < 2*time.Second {
+ t.Fatal("poll interval or backoff too short", i.calls)
+ }
+}
+
+func TestFinalFixAccountTransientExpiry(t *testing.T) {
+ l, d, base := loginHarness(t, "codex")
+ i := &transientInstance{loginInstance: base}
+ l.Instance = i
+ if _, err := l.Begin(context.Background(), base.setup.ID); err != nil {
+ t.Fatal(err)
+ }
+ l.active.challenge.ExpiresAt = time.Now().Add(-time.Second)
+ i.fail = true
+ _, err := l.Poll(context.Background())
+ if err == nil || !d.cancelled || l.active != nil {
+ t.Fatal("expired offline login left provider running", err, d.cancelled)
+ }
+}
+
+func TestFinalFixAccountBackoffBound(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ l, d, base := loginHarness(t, "codex")
+ i := &commandRetryInstance{loginInstance: base, driver: d}
+ l.Instance = &offlineAfterBegin{instance: i}
+ err := RunAccountLogin(context.Background(), l, base.setup.ID)
+ if !errors.Is(err, runnerproto.ErrTransient) || !d.cancelled {
+ t.Fatal("expired offline login not stopped", err)
+ }
+ if len(i.calls) < 7 {
+ t.Fatal("retry schedule not exercised", len(i.calls))
+ }
+ for n := 1; n < len(i.calls); n++ {
+ delta := i.calls[n].Sub(i.calls[n-1])
+ if delta < time.Second || delta > 30*time.Second {
+ t.Fatal("unbounded backoff", delta)
+ }
+ }
+ })
+}
+
+type offlineAfterBegin struct{ instance *commandRetryInstance }
+
+func (i *offlineAfterBegin) AccountSetup(ctx context.Context, id string) (runnerproto.AccountSetup, error) {
+ i.instance.calls = append(i.instance.calls, time.Now())
+ if len(i.instance.calls) > 1 {
+ return runnerproto.AccountSetup{}, runnerproto.ErrTransient
+ }
+ return i.instance.loginInstance.AccountSetup(ctx, id)
+}
+func (i *offlineAfterBegin) ReportAccountSetup(ctx context.Context, q runnerproto.AccountSetupResult) (runnerproto.AccountSetup, error) {
+ return i.instance.ReportAccountSetup(ctx, q)
+}
+
+func TestFinalFixAccountAuthorityAfterProbe(t *testing.T) {
+ for _, mode := range []string{"revoked", "transient"} {
+ t.Run(mode, func(t *testing.T) {
+ l, d, base := loginHarness(t, "codex")
+ i := &transientInstance{loginInstance: base}
+ l.Instance = i
+ if _, err := l.Begin(context.Background(), base.setup.ID); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(d.home, "auth.json"), []byte(`{"token":"fixture"}`), 0600); err != nil {
+ t.Fatal(err)
+ }
+ d.state = "connected"
+ probes, saves := 0, 0
+ l.Probe = func(context.Context, provider.Binding) (provider.Identity, error) {
+ probes++
+ if mode == "revoked" {
+ base.setup.State = "cancelled"
+ } else {
+ i.fail = true
+ }
+ return d.identity, nil
+ }
+ l.Save = func(context.Context, runnerproto.AccountSetup, provider.Binding) error { saves++; return nil }
+ _, err := l.Poll(context.Background())
+ if err == nil || saves != 0 {
+ t.Fatal("saved without current instance authority", err, saves)
+ }
+ if mode == "transient" {
+ i.fail = false
+ out, err := l.Poll(context.Background())
+ if err != nil || out.State != "connected" || probes != 1 || saves != 1 {
+ t.Fatal("verified login could not resume", out, err, probes, saves)
+ }
+ }
+ })
+ }
+}
diff --git a/scripts/runner-reference-allowlist.json b/scripts/runner-reference-allowlist.json
index ce2e66a3..31129ce8 100644
--- a/scripts/runner-reference-allowlist.json
+++ b/scripts/runner-reference-allowlist.json
@@ -22,7 +22,7 @@
},
{
"path": "docs/live-gate.md",
- "line_sha256": "488776b6907a5f5ef4c025485dd84cf4d0a29f412893e0f6187650a071a934cd",
+ "line_sha256": "51dbcdc706898958f485863d2460b2a4eb4e2ce383aa6a19533bf8b59cfc4bfc",
"match": "equipo-runner",
"count": 1,
"reason": "Retained runner executable, versioned package or user-service path in Task 11b release tooling, tests or draft operator steps."