oficina / equipo Public

feat: persist conversations and automatic task threads

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev be8095ed7616ca7d571295398abb63d79815f06d parent 0e3eccf
21 files changed, +1,260 −4
  • .rastrillo/budgets.txt +2 −0
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +66 −0
  • internal/equipo/conversation/budget_test.go +9 −0
  • internal/equipo/conversation/models.go +97 −0
  • internal/equipo/conversation/store.go +205 −0
  • internal/equipo/conversation/threads.go +126 −0
  • internal/equipo/conversations.go +96 −0
  • internal/equipo/copy.go +5 −0
  • internal/equipo/kernel/budget_test.go +9 −0
  • internal/equipo/kernel/mutation.go +24 −0
  • internal/equipo/kernel/types.go +10 −0
  • internal/equipo/migrations/0019_conversation.sql +12 −0
  • internal/equipo/migrations/schema.sql +13 −0
  • internal/equipo/migrations_test.go +41 −0
  • internal/equipo/models.go +8 −3
  • internal/equipo/store.go +1 −1
  • internal/equipo/tasks.go +4 −0
  • internal/plan3test/budget_test.go +9 −0
  • internal/plan3test/conversation_test.go +353 −0
  • internal/plan3test/harness_test.go +106 −0
  • internal/plan3test/migration_test.go +64 −0

CI failed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 84909d66..ce12eb39 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -24,3 +24,5 @@ perf GET /api/runner/v2/artifacts/{assignment}/{artifact} skip Authenticated run
size internal/runner 7500 - Direct namespaces, capture, journal and tool relay share the mandated runner package. Offline cutover leaves 7437 source lines and 6100 test lines; the test exemption is removed.
time internal/runner/provider/claude 45s Task 5 measured 32.430s for fake CLI sessions and fsynced account, policy, capture and refresh checks; 45s gives 38 percent headroom on the shared runner.
time internal/runner/provider/codex 15s Task 11a full branch gate measured 11.659s (prior attempt 11.464s) for schema, native approval and fsynced capture fixtures; 15s gives 29 percent headroom under shared-runner load.
+
+time internal/plan3test 300s Initial cap for combined browser and runner acceptance; measure at both usable stops.
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
new file mode 100644
index 00000000..bf1d525d
--- /dev/null
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -0,0 +1,66 @@
+# Plan 3 controller report
+
+## Plan 2b interface comparison
+
+Compared the merged baseline at e795e30 with the dependency table before Task 1. Later tasks must retain these completed contracts:
+
+- Permissions: `provider.Answer.Authorize` is a runner-supplied callback over the captured original event. Native approvals and Equipo MCP approvals remain separate; answers cannot replace tool inputs or commands. `ToolProxy.BindTurn` and journal checks bind tool use to the current session, turn, attempt, fence and lease. Add coordinator capabilities separately, not to every specialist socket.
+- Provenance: `provider.Binding` carries a private `AccountLease`; caller-populated identity fields do not prove a dedicated home. `Policy.ValidateSources`, launch attestation and captured frames establish provenance. Keep this private construction path and the sanitized recorded provider fixtures.
+- Sessions: `Launcher` retains Preflight/Open/Events/StartTurn/Respond/Interrupt/Close. Open does not prompt; attach Events first. `Session.ID` is the provider identity, distinct from AttemptKey, Turn.ID and AdmissionID. `Session.Validate` checks resume identity. Durable `BeginTurn`, `BindSession`, answer writes and direct recovery remain authoritative; uncertain prompts must not be resent from provider history.
+- Account refresh: dedicated account leases track runtime credential generation. `ErrRefreshPending` blocks use until `AccountLease.CommitRefresh` verifies the expected identity and commits the refreshed generation. Same-account refresh requires fresh checks; changed identity cannot be adopted mid-step. No interactive-home fallback.
+- Attestation: `provider.AttestLaunch` verifies the effective policy, concrete launch and dedicated-home provenance before containment starts. Trusted check evidence uses the durable `checks.AttestationStore` through `Witness`, keyed to scope, attempt and artifact; model text cannot substitute for executor evidence.
+- Release identity: release schema 2 pins direct launcher, bubblewrap, provider versions, binary digests and policy certificates. Policy version is `direct-v1`, launcher version `direct-v2`, Claude 2.1.312, Codex 0.165.0 and bubblewrap 0.11.0. Effective policy hashes include tools, settings, instructions and launch inputs. New coordinator/tool policies require new certification. The offline manifest does not authorize live execution; the plan's empty-certificate, live-driver and manifest/binary policy-digest blockers remain upstream gates, not work for Task 1.
+- Core/application seams remain usable: Store.write/Execution.Write and team.Store.Atomic share the SQLite transaction; CreateBug retains its compatibility path; new task threads can join that commit. Bug predicates and frozen evidence remain unchanged until the later task kinds. DescriptionTransport still requires exact head/description readback and its four-channel hash. Existing live job invalidation remains post-commit; private topics are later work.
+
+No Plan 2b behavior was changed for this comparison. Retired trial and unconfined paths stay retired.
+
+## Task 1
+
+Implemented private conversations, automatic shared task threads, explicit routing, canonical request replay, sequence allocation, audit/outbox atomicity and snapshot pagination. Feature storage receives transaction-bound roster, task-visibility and audit callbacks through the shared kernel Actor/Mutation boundary. The real-app integration fixture, fixture sessions, per-package budget TestMain files and the single 300s integration exception are in place. Migration 0019 is additive; historical tasks get an idempotent thread backfill.
+
+### TDD commands and results
+
+- RED: `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestConversation' -count=1`, exit 1. The four named tests failed to compile because `equipo.Message`, `equipo.Mutation`, Store.Conversation, SendMessage and RouteMessage did not exist. No implementation preceded this run.
+- Initial implementation runs exposed two fixture setup errors: RouterWithStore lacked its Store argument; historical fixture tasks reused an empty request key. Both were corrected in the harness. The required four tests then passed, exit 0 (1.342s).
+- Additional RED: `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestConversationRouteRevisionAndCardResource$' -count=1`, exit 1, `new stale request reused existing route <nil>`. Moving new-request revision validation after exact replay but before route reuse fixed it. The next run failed with `card did not project authoritative resource revision`; cards now resolve current visible task revisions. The same test passes as part of the final targeted run.
+- Snapshot RED: `CGO_ENABLED=0 go test ./internal/equipo -run '^TestConversationMigrationSnapshot$' -count=1`, exit 1, `schema snapshot differs from ordered migrations`. Added 0019 DDL to the snapshot. The final test compares structural schemas using Rastrillo Snapshot.Equal, preserving the existing snapshot's column order and formatting rather than requiring byte equality with a fresh dump. Final exit 0 (1.053s).
+- Final GREEN after all mutations were restored: `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestConversation' -count=1`, exit 0 (1.738s). Nine tests cover the four required cases, current authorization on replay, cursor scope/expiry, concurrent duplicate sends/routes, resource card revisions, and upgrade/fresh-schema parity with historical records preserved.
+- Regression: `CGO_ENABLED=0 go test ./internal/equipotest -run '^(TestBugSubmissionRetry|TestExecutionSchemaParity|TestFoundationMigratesTwice)$' -count=1`, exit 0 (3.042s).
+- `make migration-check`, exit 0; final TestMigrationModels result 0.085s. No full suite or make ci was run.
+- `CGO_ENABLED=0 go vet ./internal/equipo ./internal/equipo/kernel ./internal/equipo/conversation ./internal/plan3test`, exit 0.
+- `gofmt -l` on all touched Go files/packages and `git diff --check`, exit 0 with no formatting findings.
+
+### Independent guard mutations
+
+Each mutation was applied alone, the named test failed at an assertion (not a compilation error), and the source was restored byte-for-byte in a finally block before the next mutation. The complete conversation selection passed after restoration.
+
+| Guard deliberately broken | Command | Exit | Failed assertion |
+| --- | --- | --- | --- |
+| private-person-scope | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestConversationPrivateAndThreadShared$ -count=1` | 1 | private conversation leaked |
+| private-source-scope | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestConversationPrivateAndThreadShared$ -count=1` | 1 | private source leaked This record changed. Reload the page and try again. |
+| canonical-replay-hash | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestConversationMessageReplay$ -count=1` | 1 | changed replay accepted <nil> |
+| audit-atomicity | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestConversationMessageReplay$ -count=1` | 1 | audit failure ignored |
+| route-once | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestConversationRouteOnce$ -count=1` | 1 | route replay changed reply |
+| route-target-conflict | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestConversationRouteOnce$ -count=1` | 1 | route changed target <nil> |
+| own-task-routing | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestConversationRouteOnce$ -count=1` | 1 | routed into another person's task <nil> |
+| current-roster | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestConversationPrivateAndThreadShared$ -count=1` | 1 | removed member read thread <nil> |
+| body-byte-bound | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestConversationPageBounds$ -count=1` | 1 | invalid body accepted <nil> |
+| cursor-snapshot | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestConversationPageBounds$ -count=1` | 1 | inserts changed snapshot 115 |
+
+### Contracts for later tasks
+
+- `SendMessage` with an empty thread ID queues one private `coordinator` outbox entry. A task ID or its opaque thread ID selects shared discussion and queues `discussion`, never a task execution command. `reference` entries are main-conversation route notices. Later consumers must retain this distinction and recheck their own execution authority.
+- `RouteMessage` accepts only the current person's own private person-authored source and own visible task. It copies only that body, assigns a new public message ID, and stores source/notice linkage privately. Another task requester is a conflict; foreign-team/non-visible resources are not found. A shared projection contains no source conversation or source message ID.
+- Request scope is principal + operation + resource + request ID. Body/target and original revision form the canonical hash. Replay follows current authority checks and precedes stale-revision rejection. A zero Mutation.Revision means an append/action without an optimistic precondition; supplied nonzero revisions are checked. Route revisions refer to the source message; send revisions refer to the selected conversation/thread.
+- Page limit 0 defaults to 50; explicit valid limits are 1 through 100. Opaque database-backed cursors bind principal, stream, initial high-water sequence and revision, with a 24-hour expiry. Page.Revision identifies the message snapshot; Card.Revision is the current visible resource revision. Later card/live/API work must account for resource changes when choosing invalidation/ETag behavior. Expired cursor rows are retained for truthful expiry errors; a retention sweep is not part of Task 1.
+- Body remains a Go string containing valid UTF-8, at most 16 KiB. The test verifies html/template escaping; actual conversation/thread HTTP rendering remains Task 9. No safe-HTML conversion is introduced.
+- `newFixture` supplies Store, DB, real app Handler, two owner fixture sessions and TeamID. Requests can use its cookie-backed get helper. Historical tasks and real CreateBug task setup are separate helpers. Databases use the schema-copy fixture under TMPDIR, close via cleanup, and the template is removed by TestMain.
+
+### Copy pending review
+
+| Key | Draft text |
+| --- | --- |
+| `conversation.routed` | Reply added to the task thread. |
+| `conversation.cursor_expired` | This conversation page has expired. Open the conversation again. |
+
+Both entries are individually marked COPY REVIEW REQUIRED in copy.go. No copy-review server was started. No provider runs, live sign-ins, enrolment, external publication or Plan 2b code changes were needed. README is unchanged. Full report is in `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-1-report.md`.
diff --git a/internal/equipo/conversation/budget_test.go b/internal/equipo/conversation/budget_test.go
new file mode 100644
index 00000000..d796df0c
--- /dev/null
+++ b/internal/equipo/conversation/budget_test.go
@@ -0,0 +1,9 @@
+package conversation
+
+import (
+ "amadan.net/rastrillo/rastrillo/budget"
+ "os"
+ "testing"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
diff --git a/internal/equipo/conversation/models.go b/internal/equipo/conversation/models.go
new file mode 100644
index 00000000..4a9eaf52
--- /dev/null
+++ b/internal/equipo/conversation/models.go
@@ -0,0 +1,97 @@
+// Package conversation stores private conversations and shared task discussion.
+// Its operations use the caller's transaction and authority callbacks.
+package conversation
+
+import "time"
+
+type Message struct {
+ ID, ConversationID, ThreadID, AuthorKind, AuthorID, Body string
+ Sequence, Revision int64
+ CreatedAt time.Time
+}
+type Card struct {
+ ID, Kind, ResourceID string
+ Revision int64
+}
+type ConversationPage struct {
+ Messages []Message
+ Cards []Card
+ NextCursor string
+ Revision int64
+}
+
+type Main struct {
+ ID string `gorm:"primaryKey"`
+ TeamID string `gorm:"uniqueIndex:conversation_person,priority:1"`
+ Person string `gorm:"uniqueIndex:conversation_person,priority:2"`
+ Revision, LastSequence int64
+}
+
+func (Main) TableName() string { return "conversations" }
+
+type Thread struct {
+ ID string `gorm:"primaryKey"`
+ TaskID string `gorm:"uniqueIndex:conversation_task"`
+ TeamID string
+ Revision, LastSequence int64
+}
+
+func (Thread) TableName() string { return "conversation_threads" }
+
+type messageRecord struct {
+ ID string `gorm:"primaryKey"`
+ StreamID string `gorm:"uniqueIndex:conversation_sequence,priority:1"`
+ Sequence int64 `gorm:"uniqueIndex:conversation_sequence,priority:2"`
+ ConversationID, ThreadID, AuthorKind, AuthorID, Body string
+ Revision int64
+ CreatedAt time.Time
+}
+
+func (messageRecord) TableName() string { return "conversation_messages" }
+func (r messageRecord) message() Message {
+ return Message{ID: r.ID, ConversationID: r.ConversationID, ThreadID: r.ThreadID, AuthorKind: r.AuthorKind, AuthorID: r.AuthorID, Body: r.Body, Sequence: r.Sequence, Revision: r.Revision, CreatedAt: r.CreatedAt}
+}
+
+type cardRecord struct {
+ ID string `gorm:"primaryKey"`
+ StreamID string `gorm:"index:conversation_card_stream"`
+ Kind, ResourceID string
+ Sequence, Revision int64
+}
+
+func (cardRecord) TableName() string { return "conversation_cards" }
+
+type requestRecord struct {
+ Principal string `gorm:"primaryKey"`
+ Operation string `gorm:"primaryKey"`
+ Resource string `gorm:"primaryKey"`
+ RequestID string `gorm:"primaryKey"`
+ InputHash, Result string
+}
+
+func (requestRecord) TableName() string { return "conversation_requests" }
+
+type routeRecord struct {
+ SourceID string `gorm:"primaryKey"`
+ TaskID, ReplyID, NoticeID string
+}
+
+func (routeRecord) TableName() string { return "conversation_routes" }
+
+type outboxRecord struct {
+ MessageID string `gorm:"primaryKey"`
+ StreamID, Purpose string
+}
+
+func (outboxRecord) TableName() string { return "conversation_outboxes" }
+
+type cursorRecord struct {
+ ID string `gorm:"primaryKey"`
+ Principal, StreamID string
+ After, Through, Revision int64
+ ExpiresAt time.Time
+}
+
+func (cursorRecord) TableName() string { return "conversation_cursors" }
+
+var Models = []any{&Main{}, &Thread{}, &messageRecord{}, &cardRecord{}, &requestRecord{}, &routeRecord{}, &outboxRecord{}, &cursorRecord{}}
diff --git a/internal/equipo/conversation/store.go b/internal/equipo/conversation/store.go
new file mode 100644
index 00000000..a046f421
--- /dev/null
+++ b/internal/equipo/conversation/store.go
@@ -0,0 +1,205 @@
+package conversation
+
+import (
+ "crypto/rand"
+ "encoding/json"
+ "errors"
+ "time"
+ "unicode/utf8"
+
+ "amadan.net/oficina/equipo/internal/equipo/kernel"
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+)
+
+type TaskAccess struct {
+ ID, TeamID, Requester string
+ Revision int64
+}
+type Dependencies struct {
+ Authorize func(*gorm.DB, kernel.Actor) (string, error)
+ Task func(*gorm.DB, kernel.Actor, string) (TaskAccess, error)
+ Audit func(*gorm.DB, kernel.Actor, string, string) error
+ NotFound, Conflict, Invalid, CursorExpired error
+ RoutedCopy string
+}
+type Store struct {
+ tx *gorm.DB
+ deps Dependencies
+}
+
+func New(tx *gorm.DB, deps Dependencies) *Store { return &Store{tx: tx, deps: deps} }
+func (s *Store) main(actor kernel.Actor) (Main, error) {
+ teamID, err := s.deps.Authorize(s.tx, actor)
+ if err != nil {
+ return Main{}, err
+ }
+ row := Main{ID: rand.Text(), TeamID: teamID, Person: actor.Address, Revision: 1}
+ if err = s.tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "team_id"}, {Name: "person"}}, DoNothing: true}).Create(&row).Error; err != nil {
+ return Main{}, err
+ }
+ row = Main{}
+ err = s.tx.Where("team_id=? AND person=?", teamID, actor.Address).First(&row).Error
+ return row, err
+}
+func (s *Store) Conversation(actor kernel.Actor, cursor string, limit int) (ConversationPage, error) {
+ row, err := s.main(actor)
+ if err != nil {
+ return ConversationPage{}, err
+ }
+ return s.page(actor, row.ID, row.LastSequence, row.Revision, cursor, limit)
+}
+func (s *Store) SendMessage(actor kernel.Actor, threadID, body string, m kernel.Mutation) (Message, error) {
+ if !m.Valid() || !utf8.ValidString(body) || len(body) < 1 || len(body) > 16384 {
+ return Message{}, s.deps.Invalid
+ }
+ var stream, mainID, tid string
+ var revision int64
+ if threadID == "" {
+ row, err := s.main(actor)
+ if err != nil {
+ return Message{}, err
+ }
+ stream, mainID, revision = row.ID, row.ID, row.Revision
+ } else {
+ row, _, err := s.thread(actor, threadID)
+ if err != nil {
+ return Message{}, err
+ }
+ stream, tid, revision = row.ID, row.ID, row.Revision
+ }
+ hash, err := kernel.InputHash(struct {
+ Body string
+ Revision int64
+ }{body, m.Revision})
+ if err != nil {
+ return Message{}, err
+ }
+ req := requestRecord{Principal: actor.Address, Operation: "send", Resource: stream, RequestID: m.RequestID, InputHash: hash}
+ if saved, ok, err := s.replay(req); ok || err != nil {
+ return saved, err
+ }
+ if m.Revision != 0 && m.Revision != revision {
+ return Message{}, s.deps.Conflict
+ }
+ purpose := "discussion"
+ if mainID != "" {
+ purpose = "coordinator"
+ }
+ msg, err := s.appendMessage(stream, mainID, tid, "person", actor.Address, body, purpose)
+ if err != nil {
+ return Message{}, err
+ }
+ if err = s.deps.Audit(s.tx, actor, "conversation.send", msg.ID); err != nil {
+ return Message{}, err
+ }
+ return msg, s.save(req, msg)
+}
+func (s *Store) replay(req requestRecord) (Message, bool, error) {
+ var old requestRecord
+ err := s.tx.Where("principal=? AND operation=? AND resource=? AND request_id=?", req.Principal, req.Operation, req.Resource, req.RequestID).First(&old).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return Message{}, false, nil
+ }
+ if err != nil {
+ return Message{}, false, err
+ }
+ if old.InputHash != req.InputHash {
+ return Message{}, true, s.deps.Conflict
+ }
+ var msg Message
+ err = json.Unmarshal([]byte(old.Result), &msg)
+ return msg, true, err
+}
+func (s *Store) save(req requestRecord, msg Message) error {
+ raw, err := json.Marshal(msg)
+ if err != nil {
+ return err
+ }
+ req.Result = string(raw)
+ return s.tx.Create(&req).Error
+}
+func (s *Store) appendMessage(stream, mainID, tid, kind, author, body, purpose string) (Message, error) {
+ table := "conversations"
+ if tid != "" {
+ table = "conversation_threads"
+ }
+ // The caller owns a write transaction, so sequence allocation and insertion
+ // are serialized with replay, audit and outbox writes.
+ update := s.tx.Table(table).Where("id=?", stream).Select("last_sequence", "revision").Updates(map[string]any{"last_sequence": gorm.Expr("last_sequence+1"), "revision": gorm.Expr("revision+1")})
+ if update.Error != nil {
+ return Message{}, update.Error
+ }
+ if update.RowsAffected != 1 {
+ return Message{}, s.deps.NotFound
+ }
+ var sequence int64
+ if err := s.tx.Table(table).Select("last_sequence").Where("id=?", stream).Scan(&sequence).Error; err != nil {
+ return Message{}, err
+ }
+ row := messageRecord{ID: rand.Text(), StreamID: stream, Sequence: sequence, ConversationID: mainID, ThreadID: tid, AuthorKind: kind, AuthorID: author, Body: body, Revision: 1, CreatedAt: time.Now().UTC()}
+ if err := s.tx.Create(&row).Error; err != nil {
+ return Message{}, err
+ }
+ if err := s.tx.Create(&outboxRecord{MessageID: row.ID, StreamID: stream, Purpose: purpose}).Error; err != nil {
+ return Message{}, err
+ }
+ return row.message(), nil
+}
+func (s *Store) page(actor kernel.Actor, stream string, through, revision int64, cursor string, limit int) (ConversationPage, error) {
+ page := ConversationPage{Messages: []Message{}, Cards: []Card{}, Revision: revision}
+ if limit == 0 {
+ limit = 50
+ }
+ if limit < 1 || limit > 100 {
+ return page, s.deps.Invalid
+ }
+ after := int64(0)
+ if cursor != "" {
+ var c cursorRecord
+ err := s.tx.Where("id=? AND principal=? AND stream_id=?", cursor, actor.Address, stream).First(&c).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return page, s.deps.NotFound
+ }
+ if err != nil {
+ return page, err
+ }
+ if !time.Now().Before(c.ExpiresAt) {
+ return page, s.deps.CursorExpired
+ }
+ after, through, page.Revision = c.After, c.Through, c.Revision
+ }
+ var rows []messageRecord
+ if err := s.tx.Where("stream_id=? AND sequence>? AND sequence<=?", stream, after, through).Order("sequence ASC").Limit(limit + 1).Find(&rows).Error; err != nil {
+ return page, err
+ }
+ more := len(rows) > limit
+ if more {
+ rows = rows[:limit]
+ }
+ for _, row := range rows {
+ page.Messages = append(page.Messages, row.message())
+ }
+ if len(rows) > 0 {
+ end := rows[len(rows)-1].Sequence
+ var cards []cardRecord
+ if err := s.tx.Where("stream_id=? AND sequence>? AND sequence<=?", stream, after, end).Order("sequence ASC, id ASC").Find(&cards).Error; err != nil {
+ return page, err
+ }
+ for _, c := range cards {
+ task, err := s.deps.Task(s.tx, actor, c.ResourceID)
+ if err != nil {
+ return page, err
+ }
+ page.Cards = append(page.Cards, Card{ID: c.ID, Kind: c.Kind, ResourceID: task.ID, Revision: task.Revision})
+ }
+ if more {
+ c := cursorRecord{ID: rand.Text(), Principal: actor.Address, StreamID: stream, After: end, Through: through, Revision: page.Revision, ExpiresAt: time.Now().UTC().Add(24 * time.Hour)}
+ if err := s.tx.Create(&c).Error; err != nil {
+ return page, err
+ }
+ page.NextCursor = c.ID
+ }
+ }
+ return page, nil
+}
diff --git a/internal/equipo/conversation/threads.go b/internal/equipo/conversation/threads.go
new file mode 100644
index 00000000..0a8ce8ac
--- /dev/null
+++ b/internal/equipo/conversation/threads.go
@@ -0,0 +1,126 @@
+package conversation
+
+import (
+ "crypto/rand"
+ "errors"
+
+ "amadan.net/oficina/equipo/internal/equipo/kernel"
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+)
+
+// EnsureThread joins task creation's transaction. Older tasks use the same
+// idempotent insert when first accessed. No separate scheduler is involved.
+func EnsureThread(tx *gorm.DB, taskID, teamID string) (Thread, error) {
+ row := Thread{ID: rand.Text(), TaskID: taskID, TeamID: teamID, Revision: 1}
+ err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "task_id"}}, DoNothing: true}).Create(&row).Error
+ if err != nil {
+ return Thread{}, err
+ }
+ row = Thread{}
+ err = tx.Where("task_id=? AND team_id=?", taskID, teamID).First(&row).Error
+ return row, err
+}
+func (s *Store) thread(actor kernel.Actor, id string) (Thread, TaskAccess, error) {
+ teamID, err := s.deps.Authorize(s.tx, actor)
+ if err != nil {
+ return Thread{}, TaskAccess{}, err
+ }
+ var row Thread
+ err = s.tx.First(&row, "id=?", id).Error
+ if err == nil {
+ id = row.TaskID
+ } else if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return row, TaskAccess{}, err
+ }
+ task, err := s.deps.Task(s.tx, actor, id)
+ if err != nil {
+ return Thread{}, task, err
+ }
+ if task.TeamID != teamID {
+ return Thread{}, task, s.deps.NotFound
+ }
+ row, err = EnsureThread(s.tx, task.ID, teamID)
+ return row, task, err
+}
+func (s *Store) TaskThread(actor kernel.Actor, taskID, cursor string, limit int) (ConversationPage, error) {
+ row, _, err := s.thread(actor, taskID)
+ if err != nil {
+ return ConversationPage{}, err
+ }
+ return s.page(actor, row.ID, row.LastSequence, row.Revision, cursor, limit)
+}
+func (s *Store) RouteMessage(actor kernel.Actor, messageID, taskID string, m kernel.Mutation) (Message, error) {
+ if !m.Valid() {
+ return Message{}, s.deps.Invalid
+ }
+ main, err := s.main(actor)
+ if err != nil {
+ return Message{}, err
+ }
+ var source messageRecord
+ err = s.tx.Where("id=? AND conversation_id=? AND author_kind=? AND author_id=?", messageID, main.ID, "person", actor.Address).First(&source).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return Message{}, s.deps.NotFound
+ }
+ if err != nil {
+ return Message{}, err
+ }
+ thread, task, err := s.thread(actor, taskID)
+ if err != nil {
+ return Message{}, err
+ }
+ // Routing to work is an explicit action by the task's requester. Ordinary
+ // shared discussion uses SendMessage and never queues execution instructions.
+ if task.Requester != actor.Address {
+ return Message{}, s.deps.Conflict
+ }
+ hash, err := kernel.InputHash(struct {
+ TaskID string
+ Revision int64
+ }{task.ID, m.Revision})
+ if err != nil {
+ return Message{}, err
+ }
+ req := requestRecord{Principal: actor.Address, Operation: "route", Resource: source.ID, RequestID: m.RequestID, InputHash: hash}
+ if saved, ok, err := s.replay(req); ok || err != nil {
+ return saved, err
+ }
+ if m.Revision != 0 && m.Revision != source.Revision {
+ return Message{}, s.deps.Conflict
+ }
+ var old routeRecord
+ err = s.tx.First(&old, "source_id=?", source.ID).Error
+ if err == nil {
+ if old.TaskID != task.ID {
+ return Message{}, s.deps.Conflict
+ }
+ var reply messageRecord
+ if err = s.tx.First(&reply, "id=?", old.ReplyID).Error; err != nil {
+ return Message{}, err
+ }
+ return reply.message(), s.save(req, reply.message())
+ }
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return Message{}, err
+ }
+ reply, err := s.appendMessage(thread.ID, "", thread.ID, "person", actor.Address, source.Body, "discussion")
+ if err != nil {
+ return Message{}, err
+ }
+ notice, err := s.appendMessage(main.ID, main.ID, "", "system", "system", s.deps.RoutedCopy, "reference")
+ if err != nil {
+ return Message{}, err
+ }
+ route := routeRecord{SourceID: source.ID, TaskID: task.ID, ReplyID: reply.ID, NoticeID: notice.ID}
+ if err = s.tx.Create(&route).Error; err != nil {
+ return Message{}, err
+ }
+ if err = s.tx.Create(&cardRecord{ID: notice.ID, StreamID: main.ID, Kind: "task", ResourceID: task.ID, Revision: 1, Sequence: notice.Sequence}).Error; err != nil {
+ return Message{}, err
+ }
+ if err = s.deps.Audit(s.tx, actor, "conversation.route", reply.ID); err != nil {
+ return Message{}, err
+ }
+ return reply, s.save(req, reply)
+}
diff --git a/internal/equipo/conversations.go b/internal/equipo/conversations.go
new file mode 100644
index 00000000..a4fb84ec
--- /dev/null
+++ b/internal/equipo/conversations.go
@@ -0,0 +1,96 @@
+package equipo
+
+import (
+ "context"
+ "errors"
+
+ "amadan.net/oficina/equipo/internal/equipo/conversation"
+ "amadan.net/oficina/equipo/internal/equipo/kernel"
+ "gorm.io/gorm"
+)
+
+type Mutation = kernel.Mutation
+type Message = conversation.Message
+type Card = conversation.Card
+type ConversationPage = conversation.ConversationPage
+
+//lint:ignore ST1005 User-facing errors preserve the pending sentence in copy.go.
+var ErrCursorExpired = errors.New(copyConversationCursorExpired)
+
+func conversationAuthority(tx *gorm.DB, actor Actor) (string, error) {
+ if _, err := currentRunnerMember(tx, actor.Address); err != nil {
+ return "", err
+ }
+ var instance Team
+ if err := tx.First(&instance).Error; err != nil {
+ return "", storeError(err)
+ }
+ return instance.ID, nil
+}
+func conversationAt(tx *gorm.DB) *conversation.Store {
+ return conversation.New(tx, conversation.Dependencies{
+ Authorize: conversationAuthority,
+ Task: func(tx *gorm.DB, actor Actor, id string) (conversation.TaskAccess, error) {
+ teamID, err := conversationAuthority(tx, actor)
+ if err != nil {
+ return conversation.TaskAccess{}, err
+ }
+ var task Task
+ err = tx.Where("id=? AND team_id=?", id, teamID).First(&task).Error
+ return conversation.TaskAccess{ID: task.ID, TeamID: task.TeamID, Requester: task.Requester, Revision: task.Revision}, storeError(err)
+ },
+ Audit: appendAudit, NotFound: ErrNotFound, Conflict: ErrConflict, Invalid: ErrInvalid, CursorExpired: ErrCursorExpired, RoutedCopy: pageCopy["conversation.routed"],
+ })
+}
+func (s *Store) Conversation(ctx context.Context, actor Actor, cursor string, limit int) (ConversationPage, error) {
+ actor.Address = normalizeAddress(actor.Address)
+ var page ConversationPage
+ err := s.write(ctx, func(tx *gorm.DB) error {
+ var err error
+ page, err = conversationAt(tx).Conversation(actor, cursor, limit)
+ return err
+ })
+ if err != nil {
+ return ConversationPage{}, err
+ }
+ return page, nil
+}
+func (s *Store) SendMessage(ctx context.Context, actor Actor, threadID, body string, m Mutation) (Message, error) {
+ actor.Address = normalizeAddress(actor.Address)
+ var msg Message
+ err := s.write(ctx, func(tx *gorm.DB) error {
+ var err error
+ msg, err = conversationAt(tx).SendMessage(actor, threadID, body, m)
+ return err
+ })
+ if err != nil {
+ return Message{}, err
+ }
+ return msg, nil
+}
+func (s *Store) TaskThread(ctx context.Context, actor Actor, taskID, cursor string, limit int) (ConversationPage, error) {
+ actor.Address = normalizeAddress(actor.Address)
+ var page ConversationPage
+ err := s.write(ctx, func(tx *gorm.DB) error {
+ var err error
+ page, err = conversationAt(tx).TaskThread(actor, taskID, cursor, limit)
+ return err
+ })
+ if err != nil {
+ return ConversationPage{}, err
+ }
+ return page, nil
+}
+func (s *Store) RouteMessage(ctx context.Context, actor Actor, messageID, taskID string, m Mutation) (Message, error) {
+ actor.Address = normalizeAddress(actor.Address)
+ var msg Message
+ err := s.write(ctx, func(tx *gorm.DB) error {
+ var err error
+ msg, err = conversationAt(tx).RouteMessage(actor, messageID, taskID, m)
+ return err
+ })
+ if err != nil {
+ return Message{}, err
+ }
+ return msg, nil
+}
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index 2f82ab1b..85beb852 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -47,6 +47,8 @@ const BootLog = "Equipo could not start."
// COPY APPROVED BY DELEGATION (Luna pass, 2026-11-01, house rules).
var pageCopy = map[string]string{
+ // COPY REVIEW REQUIRED
+ "conversation.routed": "Reply added to the task thread.",
// COPY REVIEW REQUIRED
"runner.title": "Machines",
// COPY REVIEW REQUIRED
@@ -432,3 +434,6 @@ const CopyExecutionReconcile = "Execution recovery could not finish."
// COPY REVIEW REQUIRED: credential-free runner diagnostic.
const CopyRunnerDiagnostic = "Runner error %s at %s.\n"
+
+// COPY REVIEW REQUIRED: conversation.cursor_expired
+const copyConversationCursorExpired = "This conversation page has expired. Open the conversation again."
diff --git a/internal/equipo/kernel/budget_test.go b/internal/equipo/kernel/budget_test.go
new file mode 100644
index 00000000..158501be
--- /dev/null
+++ b/internal/equipo/kernel/budget_test.go
@@ -0,0 +1,9 @@
+package kernel
+
+import (
+ "amadan.net/rastrillo/rastrillo/budget"
+ "os"
+ "testing"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
diff --git a/internal/equipo/kernel/mutation.go b/internal/equipo/kernel/mutation.go
new file mode 100644
index 00000000..76cbc0c3
--- /dev/null
+++ b/internal/equipo/kernel/mutation.go
@@ -0,0 +1,24 @@
+package kernel
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "strings"
+ "unicode/utf8"
+)
+
+func (m Mutation) Valid() bool {
+ return strings.TrimSpace(m.RequestID) != "" && len(m.RequestID) <= 256 && utf8.ValidString(m.RequestID) && m.Revision >= 0
+}
+
+// InputHash preserves explicit input values, including the original revision.
+// Callers supply a concrete input struct, not an unordered HTTP body.
+func InputHash(input any) (string, error) {
+ raw, err := json.Marshal(input)
+ if err != nil {
+ return "", err
+ }
+ sum := sha256.Sum256(raw)
+ return hex.EncodeToString(sum[:]), nil
+}
diff --git a/internal/equipo/kernel/types.go b/internal/equipo/kernel/types.go
new file mode 100644
index 00000000..ca9f5d3e
--- /dev/null
+++ b/internal/equipo/kernel/types.go
@@ -0,0 +1,10 @@
+// Package kernel holds shared application values without owning storage.
+package kernel
+
+// Actor is supplied by the verified session, never by a submitted payload.
+type Actor struct{ Address string }
+
+type Mutation struct {
+ RequestID string
+ Revision int64
+}
diff --git a/internal/equipo/migrations/0019_conversation.sql b/internal/equipo/migrations/0019_conversation.sql
new file mode 100644
index 00000000..1465003a
--- /dev/null
+++ b/internal/equipo/migrations/0019_conversation.sql
@@ -0,0 +1,12 @@
+CREATE TABLE conversations (id text PRIMARY KEY, team_id text, person text, revision integer, last_sequence integer);
+CREATE UNIQUE INDEX conversation_person ON conversations(team_id,person);
+CREATE TABLE conversation_threads (id text PRIMARY KEY, task_id text, team_id text, revision integer, last_sequence integer);
+CREATE UNIQUE INDEX conversation_task ON conversation_threads(task_id);
+CREATE TABLE conversation_messages (id text PRIMARY KEY, stream_id text, sequence integer, conversation_id text, thread_id text, author_kind text, author_id text, body text, revision integer, created_at datetime);
+CREATE UNIQUE INDEX conversation_sequence ON conversation_messages(stream_id,sequence);
+CREATE TABLE conversation_cards (id text PRIMARY KEY, stream_id text, kind text, resource_id text, sequence integer, revision integer);
+CREATE INDEX conversation_card_stream ON conversation_cards(stream_id);
+CREATE TABLE conversation_requests (principal text, operation text, resource text, request_id text, input_hash text, result text, PRIMARY KEY(principal,operation,resource,request_id));
+CREATE TABLE conversation_routes (source_id text PRIMARY KEY, task_id text, reply_id text, notice_id text);
+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);
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 2340f388..e255d7d6 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -347,3 +347,16 @@ CREATE INDEX question_assignment ON questions(assignment_id);
CREATE TABLE supervised_trials (id text PRIMARY KEY,runner_id text,owner text,owner_revision integer,acknowledged_at datetime,versions text,revoked_at datetime);
CREATE INDEX trial_runner ON supervised_trials(runner_id);
ALTER TABLE runner_assignments ADD COLUMN protocol_version integer NOT NULL DEFAULT 1;
+
+CREATE TABLE conversations (id text PRIMARY KEY, team_id text, person text, revision integer, last_sequence integer);
+CREATE UNIQUE INDEX conversation_person ON conversations(team_id,person);
+CREATE TABLE conversation_threads (id text PRIMARY KEY, task_id text, team_id text, revision integer, last_sequence integer);
+CREATE UNIQUE INDEX conversation_task ON conversation_threads(task_id);
+CREATE TABLE conversation_messages (id text PRIMARY KEY, stream_id text, sequence integer, conversation_id text, thread_id text, author_kind text, author_id text, body text, revision integer, created_at datetime);
+CREATE UNIQUE INDEX conversation_sequence ON conversation_messages(stream_id,sequence);
+CREATE TABLE conversation_cards (id text PRIMARY KEY, stream_id text, kind text, resource_id text, sequence integer, revision integer);
+CREATE INDEX conversation_card_stream ON conversation_cards(stream_id);
+CREATE TABLE conversation_requests (principal text, operation text, resource text, request_id text, input_hash text, result text, PRIMARY KEY(principal,operation,resource,request_id));
+CREATE TABLE conversation_routes (source_id text PRIMARY KEY, task_id text, reply_id text, notice_id text);
+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);
diff --git a/internal/equipo/migrations_test.go b/internal/equipo/migrations_test.go
index 6c155b40..f7a8647a 100644
--- a/internal/equipo/migrations_test.go
+++ b/internal/equipo/migrations_test.go
@@ -1,8 +1,15 @@
package equipo
import (
+ "context"
+ "io"
+ "log/slog"
+ "os"
+ "path/filepath"
"testing"
+ "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/migrate"
"amadan.net/rastrillo/rastrillo/migrate/dump"
)
@@ -15,3 +22,37 @@ func TestMigrationModels(t *testing.T) {
t.Errorf("models and migrations disagree: %s", change.SQL)
}
}
+
+func TestConversationMigrationSnapshot(t *testing.T) {
+ actual, err := migrate.SchemaSQL(context.Background(), Schema.All())
+ if err != nil {
+ t.Fatal(err)
+ }
+ saved, err := os.ReadFile("migrations/schema.sql")
+ if err != nil {
+ t.Fatal(err)
+ }
+ read := func(name, sql string) migrate.Snapshot {
+ d, err := db.Open(filepath.Join(t.TempDir(), name+".db"), slog.New(slog.NewTextHandler(io.Discard, nil)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if err := d.Close(); err != nil {
+ t.Error(err)
+ }
+ })
+ if _, err := d.Writer().Exec(sql); err != nil {
+ t.Fatal(err)
+ }
+ snapshot, err := migrate.Read(context.Background(), d.Writer())
+ if err != nil {
+ t.Fatal(err)
+ }
+ return snapshot
+ }
+ savedSchema, migrationSchema := read("saved", string(saved)), read("migrations", actual)
+ if !savedSchema.Equal(migrationSchema) {
+ t.Fatal("schema snapshot differs from ordered migrations", savedSchema.Diff(migrationSchema))
+ }
+}
diff --git a/internal/equipo/models.go b/internal/equipo/models.go
index 8cbd63ab..3ecdc7b7 100644
--- a/internal/equipo/models.go
+++ b/internal/equipo/models.go
@@ -1,8 +1,13 @@
package equipo
-import "time"
+import (
+ "time"
-var Models = append([]any{&supervisedTrialRecord{}, &questionRecord{}, &runnerEvent{}, &runnerEventID{}, &runnerTimeline{}, &runnerArtifactRequest{}, &artifactBlob{}, &artifactBlobUpload{}, &runnerAssignment{}, &runnerCleanup{}, &runnerObservation{}, &runnerRotation{}, &executionAdmissionTicket{}, &Task{}, &taskOutbox{}, &Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &Specialist{}, &runnerRecord{}, &runnerEnrolment{}, &runnerCredentialRecord{}, &runnerRate{}, &connectionRecord{}, &connectionChoiceRecord{}, &isolationAcknowledgementRecord{}, &ConnectionInvalidation{}}, executionModels...)
+ "amadan.net/oficina/equipo/internal/equipo/conversation"
+ "amadan.net/oficina/equipo/internal/equipo/kernel"
+)
+
+var Models = append(append([]any{&supervisedTrialRecord{}, &questionRecord{}, &runnerEvent{}, &runnerEventID{}, &runnerTimeline{}, &runnerArtifactRequest{}, &artifactBlob{}, &artifactBlobUpload{}, &runnerAssignment{}, &runnerCleanup{}, &runnerObservation{}, &runnerRotation{}, &executionAdmissionTicket{}, &Task{}, &taskOutbox{}, &Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &Specialist{}, &runnerRecord{}, &runnerEnrolment{}, &runnerCredentialRecord{}, &runnerRate{}, &connectionRecord{}, &connectionChoiceRecord{}, &isolationAcknowledgementRecord{}, &ConnectionInvalidation{}}, executionModels...), conversation.Models...)
type Role string
@@ -11,7 +16,7 @@ const (
RoleMember Role = "member"
)
-type Actor struct{ Address string }
+type Actor = kernel.Actor
type Member struct {
Address string `gorm:"primaryKey"`
diff --git a/internal/equipo/store.go b/internal/equipo/store.go
index 98d6b394..4bffe678 100644
--- a/internal/equipo/store.go
+++ b/internal/equipo/store.go
@@ -114,7 +114,7 @@ func (s *Store) write(ctx context.Context, fn func(*gorm.DB) error) error {
notify()
}
}
- if err == nil || errors.Is(err, ErrForbidden) || errors.Is(err, ErrNotFound) || errors.Is(err, ErrConflict) || errors.Is(err, ErrInvalid) || errors.Is(err, ErrUnavailable) {
+ if err == nil || errors.Is(err, ErrForbidden) || errors.Is(err, ErrNotFound) || errors.Is(err, ErrConflict) || errors.Is(err, ErrInvalid) || errors.Is(err, ErrUnavailable) || errors.Is(err, ErrCursorExpired) {
return err
}
return storeError(err)
diff --git a/internal/equipo/tasks.go b/internal/equipo/tasks.go
index d8d8b032..23fd3bfd 100644
--- a/internal/equipo/tasks.go
+++ b/internal/equipo/tasks.go
@@ -8,6 +8,7 @@ import (
"strings"
"unicode/utf8"
+ "amadan.net/oficina/equipo/internal/equipo/conversation"
"amadan.net/oficina/equipo/internal/equipo/team"
"gorm.io/gorm"
)
@@ -131,6 +132,9 @@ func (s *Store) CreateBug(ctx context.Context, actor Actor, projectID int64, des
if err := tx.Create(&task).Error; err != nil {
return storeError(err)
}
+ if _, err := conversation.EnsureThread(tx, task.ID, task.TeamID); err != nil {
+ return storeError(err)
+ }
if err := tx.Create(&outbox).Error; err != nil {
return storeError(err)
}
diff --git a/internal/plan3test/budget_test.go b/internal/plan3test/budget_test.go
new file mode 100644
index 00000000..e0b00bfa
--- /dev/null
+++ b/internal/plan3test/budget_test.go
@@ -0,0 +1,9 @@
+package plan3test
+
+import (
+ "amadan.net/rastrillo/rastrillo/budget"
+ "os"
+ "testing"
+)
+
+func TestMain(m *testing.M) { code := budget.Main(m); schema.Remove(); os.Exit(code) }
diff --git a/internal/plan3test/conversation_test.go b/internal/plan3test/conversation_test.go
new file mode 100644
index 00000000..b29cf316
--- /dev/null
+++ b/internal/plan3test/conversation_test.go
@@ -0,0 +1,353 @@
+package plan3test
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "html/template"
+ "strings"
+ "sync"
+ "testing"
+ "unicode/utf8"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+)
+
+func send(t *testing.T, f *fixture, a equipo.Actor, thread, body, key string) equipo.Message {
+ t.Helper()
+ m, e := f.Store.SendMessage(ctx, a, thread, body, equipo.Mutation{RequestID: key})
+ must(t, e)
+ return m
+}
+func TestConversationPrivateAndThreadShared(t *testing.T) {
+ f := newFixture(t)
+ if w := f.get(t, owner, "/conversation"); w.Code != 200 {
+ t.Fatalf("fixture session: %d", w.Code)
+ }
+ secret := send(t, f, owner, "", "private history", "secret")
+ send(t, f, owner, "", "second secret", "secret2")
+ page, e := f.Store.Conversation(ctx, owner, "", 1)
+ must(t, e)
+ if len(page.Messages) != 1 || page.NextCursor == "" {
+ t.Fatal("missing private page")
+ }
+ other, e := f.Store.Conversation(ctx, peer, "", 50)
+ must(t, e)
+ if len(other.Messages) != 0 {
+ t.Fatal("private conversation leaked")
+ }
+ if _, e = f.Store.Conversation(ctx, peer, page.NextCursor, 1); !errors.Is(e, equipo.ErrNotFound) {
+ t.Fatal("private cursor accepted", e)
+ }
+ if _, e = f.Store.SendMessage(ctx, peer, secret.ConversationID, "intrude", equipo.Mutation{RequestID: "intrude"}); !errors.Is(e, equipo.ErrNotFound) {
+ t.Fatal("private conversation ID accepted as thread", e)
+ }
+ task := f.task(t, owner, "own-task")
+ if _, e = f.Store.RouteMessage(ctx, peer, secret.ID, task.ID, equipo.Mutation{RequestID: "steal"}); !errors.Is(e, equipo.ErrNotFound) {
+ t.Fatal("private source leaked", e)
+ }
+ msg := send(t, f, owner, task.ID, "shared discussion", "discussion")
+ thread, e := f.Store.TaskThread(ctx, peer, task.ID, "", 50)
+ must(t, e)
+ if len(thread.Messages) != 1 || thread.Messages[0].ID != msg.ID || thread.Messages[0].ConversationID != "" {
+ t.Fatal("thread visibility or private provenance", thread)
+ }
+ send(t, f, peer, msg.ThreadID, "ordinary discussion", "peer-discussion")
+ if f.count(t, "SELECT count(*) FROM conversation_outboxes WHERE purpose='coordinator'") != 2 {
+ t.Fatal("thread discussion queued execution instructions")
+ }
+ f.exec(t, "UPDATE members SET active=0 WHERE address=?", peer.Address)
+ if _, e = f.Store.TaskThread(ctx, peer, task.ID, "", 50); !errors.Is(e, equipo.ErrForbidden) {
+ t.Fatal("removed member read thread", e)
+ }
+ if _, e = f.Store.SendMessage(ctx, peer, msg.ThreadID, "ordinary discussion", equipo.Mutation{RequestID: "peer-discussion"}); !errors.Is(e, equipo.ErrForbidden) {
+ t.Fatal("removed member replayed", e)
+ }
+ if w := f.get(t, peer, "/conversation"); w.Code == 200 {
+ t.Fatal("removed member fixture session still works")
+ }
+ f.exec(t, "ALTER TABLE members RENAME TO unavailable_members")
+ if _, e = f.Store.Conversation(ctx, owner, "", 50); e == nil {
+ t.Fatal("roster lookup failed open")
+ }
+}
+func TestConversationMessageReplay(t *testing.T) {
+ f := newFixture(t)
+ m := send(t, f, owner, "", "hello", "once")
+ again := send(t, f, owner, "", "hello", "once")
+ if m != again || m.Sequence != 1 || m.Revision != 1 || m.AuthorKind != "person" || m.AuthorID != owner.Address || m.CreatedAt.Location().String() != "UTC" {
+ t.Fatal("unstable replay or attribution", m, again)
+ }
+ if f.count(t, "SELECT count(*) FROM conversation_messages") != 1 || f.count(t, "SELECT count(*) FROM conversation_outboxes") != 1 {
+ t.Fatal("duplicate send effects")
+ }
+ if _, e := f.Store.SendMessage(ctx, owner, "", "changed", equipo.Mutation{RequestID: "once"}); !errors.Is(e, equipo.ErrConflict) {
+ t.Fatal("changed replay accepted", e)
+ }
+ page, e := f.Store.Conversation(ctx, owner, "", 50)
+ must(t, e)
+ send(t, f, owner, "", "advance", "advance")
+ if _, e = f.Store.SendMessage(ctx, owner, "", "stale", equipo.Mutation{RequestID: "stale", Revision: page.Revision}); !errors.Is(e, equipo.ErrConflict) {
+ t.Fatal("stale revision accepted", e)
+ }
+ f.exec(t, "CREATE TRIGGER fail_conversation_audit BEFORE INSERT ON audit_events WHEN NEW.kind LIKE 'conversation.%' BEGIN SELECT RAISE(ABORT,'audit failed'); END")
+ if _, e = f.Store.SendMessage(ctx, owner, "", "rollback", equipo.Mutation{RequestID: "rollback"}); e == nil {
+ t.Fatal("audit failure ignored")
+ }
+ if f.count(t, "SELECT count(*) FROM conversation_messages") != 2 || f.count(t, "SELECT count(*) FROM conversation_outboxes") != 2 || f.count(t, "SELECT count(*) FROM conversation_requests") != 2 {
+ t.Fatal("audit failure did not roll back")
+ }
+ f.exec(t, "DROP TRIGGER fail_conversation_audit")
+ if m = send(t, f, owner, "", "rollback", "rollback"); m.Sequence != 3 {
+ t.Fatal("rollback consumed sequence")
+ }
+ send(t, f, peer, "", "different principal", "once")
+ if f.count(t, "SELECT count(*) FROM conversation_messages") != 4 {
+ t.Fatal("request keys not principal scoped")
+ }
+}
+func TestConversationRouteOnce(t *testing.T) {
+ f := newFixture(t)
+ task := f.createTask(t)
+ if f.count(t, "SELECT count(*) FROM conversation_threads WHERE task_id=?", task.ID) != 1 {
+ t.Fatal("task creation omitted thread")
+ }
+ secret := send(t, f, owner, "", "selected reply", "source")
+ send(t, f, owner, "", "keep private", "history")
+ m, e := f.Store.RouteMessage(ctx, owner, secret.ID, task.ID, equipo.Mutation{RequestID: "route", Revision: 1})
+ must(t, e)
+ again, e := f.Store.RouteMessage(ctx, owner, secret.ID, task.ID, equipo.Mutation{RequestID: "route", Revision: 1})
+ must(t, e)
+ third, e := f.Store.RouteMessage(ctx, owner, secret.ID, task.ID, equipo.Mutation{RequestID: "route-again"})
+ must(t, e)
+ if m != again || m != third {
+ t.Fatal("route replay changed reply")
+ }
+ if f.count(t, "SELECT count(*) FROM conversation_threads WHERE task_id=?", task.ID) != 1 || f.count(t, "SELECT count(*) FROM conversation_routes") != 1 {
+ t.Fatal("duplicate route or thread")
+ }
+ main, e := f.Store.Conversation(ctx, owner, "", 50)
+ must(t, e)
+ shared, e := f.Store.TaskThread(ctx, peer, task.ID, "", 50)
+ must(t, e)
+ if len(main.Messages) != 3 || main.Messages[2].AuthorKind != "system" || len(main.Cards) != 1 || main.Cards[0].ResourceID != task.ID || len(shared.Messages) != 1 || shared.Messages[0].Body != "selected reply" {
+ t.Fatal("route did not leave exactly one reply and notice", main, shared)
+ }
+ if shared.Messages[0].ConversationID != "" || shared.Messages[0].ID == secret.ID || len(shared.Cards) != 0 {
+ t.Fatal("route exposed private source")
+ }
+ other := f.task(t, owner, "other-task")
+ if _, e = f.Store.RouteMessage(ctx, owner, secret.ID, other.ID, equipo.Mutation{RequestID: "different"}); !errors.Is(e, equipo.ErrConflict) {
+ t.Fatal("route changed target", e)
+ }
+ their := f.task(t, peer, "their-task")
+ fresh := send(t, f, owner, "", "fresh", "fresh")
+ if _, e = f.Store.RouteMessage(ctx, owner, fresh.ID, their.ID, equipo.Mutation{RequestID: "other-person"}); !errors.Is(e, equipo.ErrConflict) {
+ t.Fatal("routed into another person's task", e)
+ }
+ f.exec(t, "UPDATE tasks SET team_id='foreign-team' WHERE id=?", other.ID)
+ if _, e = f.Store.RouteMessage(ctx, owner, fresh.ID, other.ID, equipo.Mutation{RequestID: "foreign"}); !errors.Is(e, equipo.ErrNotFound) {
+ t.Fatal("foreign task accepted", e)
+ }
+ legacy := f.task(t, owner, "legacy")
+ for range 2 {
+ _, e = f.Store.TaskThread(ctx, peer, legacy.ID, "", 50)
+ must(t, e)
+ }
+ if f.count(t, "SELECT count(*) FROM conversation_threads WHERE task_id=?", legacy.ID) != 1 {
+ t.Fatal("backfill duplicated thread")
+ }
+ f.exec(t, "CREATE TRIGGER fail_route_audit BEFORE INSERT ON audit_events WHEN NEW.kind='conversation.route' BEGIN SELECT RAISE(ABORT,'audit failed'); END")
+ before := f.count(t, "SELECT count(*) FROM conversation_messages")
+ if _, e = f.Store.RouteMessage(ctx, owner, fresh.ID, legacy.ID, equipo.Mutation{RequestID: "rollback-route"}); e == nil {
+ t.Fatal("route audit failure ignored")
+ }
+ if f.count(t, "SELECT count(*) FROM conversation_messages") != before || f.count(t, "SELECT count(*) FROM conversation_routes") != 1 {
+ t.Fatal("partial route survived audit failure")
+ }
+}
+func TestConversationPageBounds(t *testing.T) {
+ f := newFixture(t)
+ body := "<script>alert('x')</script> & café"
+ first := send(t, f, owner, "", body, "html")
+ var out bytes.Buffer
+ must(t, template.Must(template.New("message").Parse("{{.Body}}")).Execute(&out, first))
+ if strings.Contains(out.String(), "<script>") || !strings.Contains(out.String(), "&lt;script&gt;") {
+ t.Fatal("message HTML not escaped")
+ }
+ for _, body := range []string{"", strings.Repeat("a", 16385), string([]byte{0xff})} {
+ if _, e := f.Store.SendMessage(ctx, owner, "", body, equipo.Mutation{RequestID: "invalid"}); !errors.Is(e, equipo.ErrInvalid) {
+ t.Fatal("invalid body accepted", e)
+ }
+ }
+ maxBody := strings.Repeat("é", 8192)
+ if m := send(t, f, owner, "", maxBody, "max"); !utf8.ValidString(m.Body) || len(m.Body) != 16384 {
+ t.Fatal("UTF-8 or boundary changed")
+ }
+ for _, n := range []int{-1, 101} {
+ if _, e := f.Store.Conversation(ctx, owner, "", n); !errors.Is(e, equipo.ErrInvalid) {
+ t.Fatal("bad page bound accepted", n, e)
+ }
+ }
+ for i := 2; i < 105; i++ {
+ send(t, f, owner, "", fmt.Sprint(i), fmt.Sprint(i))
+ }
+ for _, n := range []int{0, 1, 50, 100} {
+ p, e := f.Store.Conversation(ctx, owner, "", n)
+ must(t, e)
+ want := n
+ if want == 0 {
+ want = 50
+ }
+ if len(p.Messages) != want {
+ t.Fatal("page size", n, len(p.Messages))
+ }
+ }
+ p, e := f.Store.Conversation(ctx, owner, "", 1)
+ must(t, e)
+ snapshotRevision := p.Revision
+ var wg sync.WaitGroup
+ errs := make(chan error, 10)
+ for i := 0; i < 10; i++ {
+ wg.Go(func() {
+ _, e := f.Store.SendMessage(ctx, owner, "", "concurrent", equipo.Mutation{RequestID: fmt.Sprint("concurrent", i)})
+ errs <- e
+ })
+ }
+ seen := map[string]bool{p.Messages[0].ID: true}
+ seq := int64(1)
+ for p.NextCursor != "" {
+ p, e = f.Store.Conversation(ctx, owner, p.NextCursor, 17)
+ must(t, e)
+ if p.Revision != snapshotRevision {
+ t.Fatal("snapshot revision changed")
+ }
+ for _, m := range p.Messages {
+ seq++
+ if seen[m.ID] || m.Sequence != seq {
+ t.Fatal("unstable cursor order")
+ }
+ seen[m.ID] = true
+ }
+ }
+ wg.Wait()
+ close(errs)
+ for e := range errs {
+ must(t, e)
+ }
+ if len(seen) != 105 {
+ t.Fatal("inserts changed snapshot", len(seen))
+ }
+ if _, e = f.Store.Conversation(ctx, owner, "guessed", 50); !errors.Is(e, equipo.ErrNotFound) {
+ t.Fatal("unknown cursor accepted", e)
+ }
+}
+
+func TestConversationReplayScopeAndPreconditions(t *testing.T) {
+ f := newFixture(t)
+ p, e := f.Store.Conversation(ctx, owner, "", 50)
+ must(t, e)
+ mutation := equipo.Mutation{RequestID: "revision-bound", Revision: p.Revision}
+ m, e := f.Store.SendMessage(ctx, owner, "", "first", mutation)
+ must(t, e)
+ send(t, f, owner, "", "second", "second")
+ replay, e := f.Store.SendMessage(ctx, owner, "", "first", mutation)
+ must(t, e)
+ if replay != m {
+ t.Fatal("replay rejected original revision")
+ }
+ mutation.Revision++
+ if _, e = f.Store.SendMessage(ctx, owner, "", "first", mutation); !errors.Is(e, equipo.ErrConflict) {
+ t.Fatal("changed canonical revision accepted", e)
+ }
+ for _, bad := range []equipo.Mutation{{}, {RequestID: strings.Repeat("a", 257)}, {RequestID: string([]byte{255})}, {RequestID: "negative", Revision: -1}} {
+ if _, e = f.Store.SendMessage(ctx, owner, "", "bad", bad); !errors.Is(e, equipo.ErrInvalid) {
+ t.Fatal("bad mutation accepted", e)
+ }
+ }
+ task := f.task(t, owner, "scope-task")
+ send(t, f, owner, task.ID, "other resource", "revision-bound")
+ if _, e = f.Store.RouteMessage(ctx, owner, m.ID, task.ID, equipo.Mutation{RequestID: "revision-bound", Revision: 7}); !errors.Is(e, equipo.ErrConflict) {
+ t.Fatal("stale source routed", e)
+ }
+ routed, e := f.Store.RouteMessage(ctx, owner, m.ID, task.ID, equipo.Mutation{RequestID: "revision-bound", Revision: 1})
+ must(t, e)
+ if routed.ID == m.ID {
+ t.Fatal("operation scope reused send result")
+ }
+ f.exec(t, "UPDATE tasks SET requester=? WHERE id=?", peer.Address, task.ID)
+ if _, e = f.Store.RouteMessage(ctx, owner, m.ID, task.ID, equipo.Mutation{RequestID: "revision-bound", Revision: 1}); !errors.Is(e, equipo.ErrConflict) {
+ t.Fatal("route replay skipped current requester", e)
+ }
+ f.exec(t, "UPDATE members SET role='unknown' WHERE address=?", owner.Address)
+ if _, e = f.Store.SendMessage(ctx, owner, "", "first", equipo.Mutation{RequestID: "revision-bound", Revision: p.Revision}); !errors.Is(e, equipo.ErrForbidden) {
+ t.Fatal("replay skipped current role", e)
+ }
+}
+
+func TestConversationCursorScopeAndExpiry(t *testing.T) {
+ f := newFixture(t)
+ for i := range 3 {
+ send(t, f, owner, "", fmt.Sprint(i), fmt.Sprint(i))
+ }
+ page, e := f.Store.Conversation(ctx, owner, "", 1)
+ must(t, e)
+ task := f.task(t, owner, "cursor-task")
+ if _, e = f.Store.TaskThread(ctx, owner, task.ID, page.NextCursor, 1); !errors.Is(e, equipo.ErrNotFound) {
+ t.Fatal("cursor crossed resource", e)
+ }
+ f.exec(t, "UPDATE conversation_cursors SET expires_at='2000-01-01 00:00:00' WHERE id=?", page.NextCursor)
+ if _, e = f.Store.Conversation(ctx, owner, page.NextCursor, 1); !errors.Is(e, equipo.ErrCursorExpired) {
+ t.Fatal("expired cursor accepted", e)
+ }
+}
+
+func TestConversationConcurrentReplay(t *testing.T) {
+ f := newFixture(t)
+ task := f.task(t, owner, "concurrent-task")
+ var wg sync.WaitGroup
+ errs := make(chan error, 16)
+ for range 8 {
+ wg.Go(func() {
+ _, e := f.Store.SendMessage(ctx, owner, "", "once", equipo.Mutation{RequestID: "parallel"})
+ errs <- e
+ })
+ }
+ wg.Wait()
+ page, e := f.Store.Conversation(ctx, owner, "", 50)
+ must(t, e)
+ if len(page.Messages) != 1 {
+ t.Fatal("concurrent send duplicated")
+ }
+ for range 8 {
+ wg.Go(func() {
+ _, e := f.Store.RouteMessage(ctx, owner, page.Messages[0].ID, task.ID, equipo.Mutation{RequestID: "parallel-route"})
+ errs <- e
+ })
+ }
+ wg.Wait()
+ close(errs)
+ for e := range errs {
+ must(t, e)
+ }
+ if f.count(t, "SELECT count(*) FROM conversation_messages") != 3 || f.count(t, "SELECT count(*) FROM conversation_outboxes") != 3 || f.count(t, "SELECT count(*) FROM conversation_threads") != 1 || f.count(t, "SELECT count(*) FROM conversation_routes") != 1 {
+ t.Fatal("concurrent retry duplicated effects")
+ }
+}
+
+func TestConversationRouteRevisionAndCardResource(t *testing.T) {
+ f := newFixture(t)
+ task := f.task(t, owner, "card-task")
+ source := send(t, f, owner, "", "route", "source")
+ _, e := f.Store.RouteMessage(ctx, owner, source.ID, task.ID, equipo.Mutation{RequestID: "route", Revision: 1})
+ must(t, e)
+ if _, e = f.Store.RouteMessage(ctx, owner, source.ID, task.ID, equipo.Mutation{RequestID: "new-stale", Revision: 2}); !errors.Is(e, equipo.ErrConflict) {
+ t.Fatal("new stale request reused existing route", e)
+ }
+ f.exec(t, "UPDATE tasks SET revision=7 WHERE id=?", task.ID)
+ page, e := f.Store.Conversation(ctx, owner, "", 50)
+ must(t, e)
+ if len(page.Cards) != 1 || page.Cards[0].Revision != 7 {
+ t.Fatal("card did not project authoritative resource revision", page.Cards)
+ }
+}
diff --git a/internal/plan3test/harness_test.go b/internal/plan3test/harness_test.go
new file mode 100644
index 00000000..c5161910
--- /dev/null
+++ b/internal/plan3test/harness_test.go
@@ -0,0 +1,106 @@
+package plan3test
+
+import (
+ "context"
+ "crypto/rand"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/dbtest"
+ "amadan.net/rastrillo/rastrillo/mail"
+ "amadan.net/rastrillo/rastrillo/sessions"
+)
+
+const origin = "http://127.0.0.1:8080"
+
+var ctx = context.Background()
+var owner = equipo.Actor{Address: "owner@example.com"}
+var peer = equipo.Actor{Address: "peer@example.com"}
+var schema = dbtest.FromSet(equipo.BootSchema)
+
+type fixture struct {
+ DB *db.DB
+ Store *equipo.Store
+ Handler http.Handler
+ Cookies map[string]*http.Cookie
+ TeamID string
+}
+
+func newFixture(t *testing.T) *fixture {
+ t.Helper()
+ if os.Getenv("TMPDIR") == "" {
+ t.Fatal("TMPDIR must name an on-disk scratch directory")
+ }
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ d, err := db.Open(schema.Path(t), logger)
+ must(t, err)
+ t.Cleanup(func() { must(t, d.Close()) })
+ if !filepath.IsAbs(os.TempDir()) {
+ t.Fatal("TMPDIR must be absolute")
+ }
+ s := equipo.NewStore(d)
+ router, err := equipo.RouterWithStore(d, equipo.Config{Origin: origin, InstanceKey: "plan3-fixture", AllowLoggedMail: true, Owners: []string{owner.Address}}, mail.Logged(logger), logger, s)
+ must(t, err)
+ f := &fixture{DB: d, Store: s, Handler: equipo.Mux(router), Cookies: map[string]*http.Cookie{}}
+ must(t, s.SetMember(ctx, owner, peer.Address, equipo.RoleOwner, true, 0))
+ must(t, d.Writer().QueryRow("SELECT id FROM teams").Scan(&f.TeamID))
+ for _, actor := range []equipo.Actor{owner, peer} {
+ token := rand.Text()
+ now := time.Now().UTC()
+ f.exec(t, "INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", sessions.HashToken(token), actor.Address, "fixture", now.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano), now.Add(time.Hour).Format(time.RFC3339Nano))
+ f.Cookies[actor.Address] = &http.Cookie{Name: "rastrillo_session", Value: token, Path: "/"}
+ }
+ return f
+}
+func must(t *testing.T, err error) {
+ t.Helper()
+ if err != nil {
+ t.Fatal(err)
+ }
+}
+func (f *fixture) exec(t *testing.T, q string, args ...any) {
+ t.Helper()
+ _, err := f.DB.Writer().Exec(q, args...)
+ must(t, err)
+}
+func (f *fixture) count(t *testing.T, q string, args ...any) int64 {
+ t.Helper()
+ var n int64
+ must(t, f.DB.Writer().QueryRow(q, args...).Scan(&n))
+ return n
+}
+func (f *fixture) get(t *testing.T, actor equipo.Actor, path string) *httptest.ResponseRecorder {
+ t.Helper()
+ r := httptest.NewRequest("GET", path, nil)
+ r.AddCookie(f.Cookies[actor.Address])
+ w := httptest.NewRecorder()
+ f.Handler.ServeHTTP(w, r)
+ return w
+}
+func (f *fixture) task(t *testing.T, actor equipo.Actor, id string) equipo.Task {
+ t.Helper()
+ // Historical tasks intentionally have no thread; reads backfill them.
+ task := equipo.Task{ID: id, RequestID: id, TeamID: f.TeamID, Requester: actor.Address, Revision: 1, State: "running", Description: "fixture task"}
+ must(t, f.DB.G.Create(&task).Error)
+ return task
+}
+func (f *fixture) createTask(t *testing.T) equipo.Task {
+ t.Helper()
+ p := equipo.Project{Name: "fixture", Repository: "amadan.net/test/fixture", DefaultBranch: "main", Kind: equipo.ProjectRepository, Revision: 1, GrantVersion: 1}
+ must(t, f.DB.G.Create(&p).Error)
+ must(t, f.DB.G.Create(&equipo.DecisionOwner{ProjectID: p.ID, Decision: "merge", Address: owner.Address}).Error)
+ limits := team.PeriodLimits{Calls: 24, InputTokens: 200000, OutputTokens: 40000, Seconds: 10000}
+ must(t, f.Store.SaveBudgets(ctx, owner, equipo.BudgetConfig{Team: limits, Projects: map[team.ProjectID]team.PeriodLimits{team.ProjectID(p.ID): limits}}))
+ task, err := f.Store.CreateBug(ctx, owner, p.ID, "fixture bug", "fixture-bug")
+ must(t, err)
+ return task
+}
diff --git a/internal/plan3test/migration_test.go b/internal/plan3test/migration_test.go
new file mode 100644
index 00000000..f07243fa
--- /dev/null
+++ b/internal/plan3test/migration_test.go
@@ -0,0 +1,64 @@
+package plan3test
+
+import (
+ "io"
+ "log/slog"
+ "path/filepath"
+ "reflect"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/migrate"
+)
+
+func TestConversationMigrationUpgrade(t *testing.T) {
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ d, e := db.Open(filepath.Join(t.TempDir(), "upgrade.db"), logger)
+ must(t, e)
+ t.Cleanup(func() { must(t, d.Close()) })
+ old := &migrate.Set{}
+ for _, m := range equipo.BootSchema.All() {
+ if m.ID != "equipo/0019_conversation" {
+ old.Add(m)
+ }
+ }
+ _, e = migrate.Apply(ctx, d, old)
+ must(t, e)
+ f := &fixture{DB: d, Store: equipo.NewStore(d)}
+ must(t, f.Store.Bootstrap(ctx, []string{owner.Address}))
+ must(t, d.Writer().QueryRow("SELECT id FROM teams").Scan(&f.TeamID))
+ task := f.task(t, owner, "old-task")
+ f.exec(t, "INSERT INTO sessions(token_hash,subject,created_at,expires_at) VALUES('preserved',?,'2026-11-01','2026-12-01')", owner.Address)
+ 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"}) {
+ t.Fatal("wrong upgrade", result.Applied)
+ }
+ var saved equipo.Task
+ must(t, d.G.First(&saved, "id=?", task.ID).Error)
+ if saved != task || f.count(t, "SELECT count(*) FROM sessions WHERE token_hash='preserved'") != 1 || f.count(t, "SELECT count(*) FROM audit_events") != before {
+ t.Fatal("upgrade changed historical records")
+ }
+ for range 2 {
+ _, e = f.Store.TaskThread(ctx, owner, task.ID, "", 50)
+ must(t, e)
+ }
+ if f.count(t, "SELECT count(*) FROM conversation_threads WHERE task_id=?", task.ID) != 1 {
+ t.Fatal("old task thread not unique")
+ }
+ result, e = migrate.Apply(ctx, d, equipo.BootSchema)
+ must(t, e)
+ if len(result.Applied) != 0 {
+ t.Fatal("migration reapplied")
+ }
+ fresh := newFixture(t)
+ upgraded, e := migrate.Read(ctx, d.Writer())
+ must(t, e)
+ baseline, e := migrate.Read(ctx, fresh.DB.Writer())
+ must(t, e)
+ if !reflect.DeepEqual(upgraded, baseline) {
+ t.Fatal("fresh and upgraded schemas differ")
+ }
+}