| 1 | package memoria |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "net/http" |
| 8 | "strings" |
| 9 | "sync" |
| 10 | "sync/atomic" |
| 11 | "testing" |
| 12 | |
| 13 | access "amadan.net/oficina/agent-access.git" |
| 14 | "github.com/google/uuid" |
| 15 | ) |
| 16 | |
| 17 | func noteUpdateJSON(id int64, revision int, client, title, body string) string { |
| 18 | b, _ := json.Marshal(agentNoteUpdateInput{Team: "acme", ID: id, ExpectedRevision: revision, ClientID: client, Title: title, Body: body}) |
| 19 | return string(b) |
| 20 | } |
| 21 | |
| 22 | func TestAgentNoteEditLifecycle(t *testing.T) { |
| 23 | f, p := linkedAgentFixture(t) |
| 24 | active := true |
| 25 | h := mountAgentFixture(t, f, &p, &active) |
| 26 | // A normal browser/native paste is editable; it need not have an agent receipt. |
| 27 | id, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "browser-title", Title: "Browser title", Body: "old nebula content"}) |
| 28 | if err != nil { |
| 29 | t.Fatal(err) |
| 30 | } |
| 31 | read := fmt.Sprintf(`{"team":"acme","id":%d}`, id) |
| 32 | if w := agentCall(h, "notes_get", read); w.Code != 200 || !strings.Contains(w.Body.String(), `"revision":1`) || !strings.Contains(w.Body.String(), "old nebula content") { |
| 33 | t.Fatal(w.Code, w.Body.String()) |
| 34 | } |
| 35 | update := noteUpdateJSON(id, 1, uuid.NewString(), "Revised title", "new quasar content") |
| 36 | first := agentCall(h, "notes_update", update) |
| 37 | if first.Code != 200 || !strings.Contains(first.Body.String(), `"revision":2`) || !strings.Contains(first.Body.String(), `"indexed":true`) { |
| 38 | t.Fatal(first.Code, first.Body.String()) |
| 39 | } |
| 40 | title, body, err := f.app.store.Body(t.Context(), id) |
| 41 | if err != nil || title != "Revised title" || body != "new quasar content" { |
| 42 | t.Fatal("domain body differs", title, body, err) |
| 43 | } |
| 44 | if w := f.do("GET", fmt.Sprintf("/documents/%d", id), ""); w.Code != 200 || !strings.Contains(w.Body.String(), "new quasar content") { |
| 45 | t.Fatal("page", w.Code) |
| 46 | } |
| 47 | if w := agentCall(h, "notes_search", `{"team":"acme","query":"quasar"}`); w.Code != 200 || !strings.Contains(w.Body.String(), "new quasar content") { |
| 48 | t.Fatal("search", w.Code, w.Body.String()) |
| 49 | } |
| 50 | if w := agentCall(h, "notes_update", noteUpdateJSON(id, 1, uuid.NewString(), "stale", "stale")); w.Code != 409 { |
| 51 | t.Fatal("stale", w.Code) |
| 52 | } |
| 53 | // A title-only edit through the ordinary domain writer advances revision too. |
| 54 | if _, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "browser-title", Title: "Later rename", Body: body}); err != nil { |
| 55 | t.Fatal(err) |
| 56 | } |
| 57 | if _, rev, _, err := f.app.store.Meta(t.Context(), id); err != nil || rev != 3 { |
| 58 | t.Fatal("rename revision", rev, err) |
| 59 | } |
| 60 | retry := agentCall(h, "notes_update", update) |
| 61 | if retry.Code != 200 || retry.Body.String() != first.Body.String() { |
| 62 | t.Fatal("receipt changed", retry.Code, retry.Body.String()) |
| 63 | } |
| 64 | if title, _, _ := f.app.store.Body(t.Context(), id); title != "Later rename" { |
| 65 | t.Fatal("retry overwrote later title") |
| 66 | } |
| 67 | if w := agentCall(h, "notes_update", strings.Replace(update, "Revised title", "Changed request", 1)); w.Code != 409 { |
| 68 | t.Fatal("changed retry", w.Code) |
| 69 | } |
| 70 | if err := f.app.store.Delete(t.Context(), id); err != nil { |
| 71 | t.Fatal(err) |
| 72 | } |
| 73 | if w := agentCall(h, "notes_update", update); w.Code != 404 { |
| 74 | t.Fatal("recreated deletion", w.Code) |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | func TestAgentNoteEditCustodyAndConcurrency(t *testing.T) { |
| 79 | f, p := linkedAgentFixture(t) |
| 80 | active := true |
| 81 | h := mountAgentFixture(t, f, &p, &active) |
| 82 | for _, source := range []string{"upload", "notion", "Docs"} { |
| 83 | spec := IngestSpec{Source: source, Key: source, Title: "Imported", Body: "must remain unchanged"} |
| 84 | if source == "Docs" { |
| 85 | spec.ItemID = "sibling" |
| 86 | spec.SiblingRevision = 1 |
| 87 | } |
| 88 | id, err := f.app.store.Ingest(t.Context(), spec) |
| 89 | if err != nil { |
| 90 | t.Fatal(err) |
| 91 | } |
| 92 | for _, op := range []string{"notes_get", "notes_update"} { |
| 93 | if w := agentCall(h, op, func() string { |
| 94 | if op == "notes_get" { |
| 95 | return fmt.Sprintf(`{"team":"acme","id":%d}`, id) |
| 96 | } |
| 97 | return noteUpdateJSON(id, 1, uuid.NewString(), "overwrite", "overwrite") |
| 98 | }()); w.Code != 404 { |
| 99 | t.Fatal(source, op, w.Code) |
| 100 | } |
| 101 | } |
| 102 | } |
| 103 | id, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "race", Title: "race", Body: "before race"}) |
| 104 | if err != nil { |
| 105 | t.Fatal(err) |
| 106 | } |
| 107 | var ok, conflict atomic.Int32 |
| 108 | var wg sync.WaitGroup |
| 109 | for range 8 { |
| 110 | wg.Go(func() { |
| 111 | w := agentCall(h, "notes_update", noteUpdateJSON(id, 1, uuid.NewString(), "winner", "after race")) |
| 112 | switch w.Code { |
| 113 | case 200: |
| 114 | ok.Add(1) |
| 115 | case 409: |
| 116 | conflict.Add(1) |
| 117 | default: |
| 118 | t.Errorf("race status %d: %s", w.Code, w.Body.String()) |
| 119 | } |
| 120 | }) |
| 121 | } |
| 122 | wg.Wait() |
| 123 | if ok.Load() != 1 || conflict.Load() != 7 { |
| 124 | t.Fatal("lost precondition", ok.Load(), conflict.Load()) |
| 125 | } |
| 126 | var receipts int64 |
| 127 | f.app.db.G.Table("memoria_agent_note_updates").Count(&receipts) |
| 128 | if receipts != 1 { |
| 129 | t.Fatal("failed writes kept receipts", receipts) |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | func TestAgentNoteEditAtomicFailures(t *testing.T) { |
| 134 | for _, mode := range []string{"receipt", "chunk", "unlink", "reserved", "final"} { |
| 135 | t.Run(mode, func(t *testing.T) { |
| 136 | f, p := linkedAgentFixture(t) |
| 137 | active := true |
| 138 | mountAgentFixture(t, f, &p, &active) |
| 139 | id, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "atomic", Title: "before", Body: "before content"}) |
| 140 | if err != nil { |
| 141 | t.Fatal(err) |
| 142 | } |
| 143 | var checks atomic.Int32 |
| 144 | h := http.NewServeMux() |
| 145 | err = f.app.mountAgentAccess(h, "https://connect.example.test", "acme", access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| 146 | n := checks.Add(1) |
| 147 | if mode == "reserved" && n >= 2 || mode == "final" && n >= 3 { |
| 148 | return access.Principal{}, access.Fail("unauthenticated", "Revoked.") |
| 149 | } |
| 150 | return p, nil |
| 151 | })) |
| 152 | if err != nil { |
| 153 | t.Fatal(err) |
| 154 | } |
| 155 | trigger := "" |
| 156 | switch mode { |
| 157 | case "receipt": |
| 158 | trigger = "CREATE TRIGGER fail_edit BEFORE INSERT ON memoria_agent_note_updates BEGIN SELECT RAISE(ABORT,'injected'); END" |
| 159 | case "chunk": |
| 160 | trigger = "CREATE TRIGGER fail_edit AFTER INSERT ON chunks BEGIN SELECT RAISE(ABORT,'injected'); END" |
| 161 | case "unlink": |
| 162 | trigger = "CREATE TRIGGER fail_edit AFTER INSERT ON chunks BEGIN DELETE FROM home_identity_links; END" |
| 163 | } |
| 164 | if trigger != "" { |
| 165 | if err := f.app.db.G.Exec(trigger).Error; err != nil { |
| 166 | t.Fatal(err) |
| 167 | } |
| 168 | } |
| 169 | w := agentCall(h, "notes_update", noteUpdateJSON(id, 1, uuid.NewString(), "after", "after content")) |
| 170 | if w.Code != 401 && w.Code != 403 && w.Code != 503 { |
| 171 | t.Fatal(w.Code, w.Body.String()) |
| 172 | } |
| 173 | title, body, err := f.app.store.Body(t.Context(), id) |
| 174 | if err != nil || title != "before" || body != "before content" { |
| 175 | t.Fatal("partial body", err) |
| 176 | } |
| 177 | if _, rev, _, _ := f.app.store.Meta(t.Context(), id); rev != 1 { |
| 178 | t.Fatal("partial revision", rev) |
| 179 | } |
| 180 | var n int64 |
| 181 | f.app.db.G.Table("memoria_agent_note_updates").Count(&n) |
| 182 | if n != 0 { |
| 183 | t.Fatal("partial receipt") |
| 184 | } |
| 185 | passages, err := f.app.store.Passages(t.Context(), id) |
| 186 | if err != nil || len(passages) != 1 || passages[0].Text != "before content" { |
| 187 | t.Fatal("partial chunks", passages, err) |
| 188 | } |
| 189 | }) |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | func TestAgentNoteGetStopsAfterConcurrentEdit(t *testing.T) { |
| 194 | f, p := linkedAgentFixture(t) |
| 195 | active := true |
| 196 | h := mountAgentFixture(t, f, &p, &active) |
| 197 | id, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "large", Title: "large", Body: strings.Repeat("private words ", 16000)}) |
| 198 | if err != nil { |
| 199 | t.Fatal(err) |
| 200 | } |
| 201 | var changed atomic.Bool |
| 202 | wrapped := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 203 | h.ServeHTTP(agentStreamWriter{ResponseWriter: w, after: func() { |
| 204 | if changed.CompareAndSwap(false, true) { |
| 205 | if _, err := f.app.store.Ingest(context.Background(), IngestSpec{Source: "paste", Key: "large", Title: "new", Body: "new body"}); err != nil { |
| 206 | t.Error(err) |
| 207 | } |
| 208 | } |
| 209 | }}, r) |
| 210 | }) |
| 211 | code, body, err := memoriaLiveCall(t, wrapped, "notes_get", fmt.Sprintf(`{"team":"acme","id":%d}`, id)) |
| 212 | if code != 200 || err == nil || len(body) > 65536 || !changed.Load() { |
| 213 | t.Fatal("stale stream completed", code, len(body), err) |
| 214 | } |
| 215 | } |
| 216 | |