oficina / mapa Public

Clone
git clone https://amadan.net/oficina/mapa

Plain git — no account needed to clone.

Download

Download this file

1package mapa
2
3import (
4 "errors"
5 "slices"
6 "strings"
7 "testing"
8 "time"
9
10 "gorm.io/gorm"
11
12 "amadan.net/oficina/notion.git/notiontest"
13)
14
15// Gates from Fable's first review (M3 to M6), each red without its fix.
16
17// atPoint runs act at the nth arrival at point, and goes on: what a
18// teammate does in Mapa between the run's decision and its write.
19func atPoint(t *testing.T, point string, nth int, act func()) {
20 t.Helper()
21 seen := 0
22 importCrash = func(at string) error {
23 if at == point {
24 if seen++; seen == nth {
25 act()
26 }
27 }
28 return nil
29 }
30 t.Cleanup(func() { importCrash = nil })
31}
32
33// rerunChanged imports the small workspace, then changes Handbook in
34// Notion, ready for a second run.
35func rerunChanged(t *testing.T) (*importWorld, Page) {
36 ws := newSmall()
37 world := newImportWorld(t, ws.Workspace)
38 world.connect(ana)
39 world.importAs(ana)
40 ws.set(ws.handbook, 1, notiontest.Para(notiontest.Text("Changed.")))
41 handbook, _, _ := world.pageTitled("Handbook")
42 return world, handbook
43}
44
45// M3: a teammate's save landing after the run decided Handbook was
46// untouched is kept, whole: only ImportUpdate's own re-read of the
47// revision, inside its write, can catch it.
48//
49// Mutation (make mutate, first red 2026-11-17): ImportUpdate's revision
50// check alone removed.
51func TestM3ASaveMidRunIsKept(t *testing.T) {
52 world, handbook := rerunChanged(t)
53 atPoint(t, "write:rendered", 1, func() {
54 if _, err := world.store.Commit(ctx(), bo, handbook.ID,
55 handbook.Revision, "Bo's words."); err != nil {
56 t.Error(err)
57 }
58 })
59 run := world.importAs(ana)
60 _, record, _ := world.pageTitled("Handbook")
61 if record.Body != "Bo's words." || run.Kept != 1 || run.Updated != 0 {
62 t.Errorf("a save mid-run: body %q, run %+v", record.Body, run)
63 }
64}
65
66// M3: a page deleted after the run decided is not written to.
67//
68// Mutation (make mutate, first red 2026-11-17): ImportUpdate's gone
69// check alone removed.
70func TestM3ADeleteMidRunIsNotWritten(t *testing.T) {
71 world, handbook := rerunChanged(t)
72 atPoint(t, "write:rendered", 1, func() {
73 if err := world.store.Delete(ctx(), bo, handbook.ID); err != nil {
74 t.Error(err)
75 }
76 })
77 world.importAs(ana)
78 var last Event
79 world.store.database.Where("object_kind = ? AND object_id = ?",
80 ObjectPage, handbook.ID).Order("id DESC").First(&last)
81 if last.Verb != VerbDeleted {
82 t.Errorf("a page deleted mid-run was written: last verb %s",
83 last.Verb)
84 }
85}
86
87// M3, §13.2: a page deleted in Mapa is not created again.
88//
89// Mutation (make mutate, first red 2026-11-17): a deleted page sent to
90// create.
91func TestM3ADeletedPageIsNotRecreated(t *testing.T) {
92 world, handbook := rerunChanged(t)
93 if err := world.store.Delete(ctx(), bo, handbook.ID); err != nil {
94 t.Fatal(err)
95 }
96 run := world.importAs(ana)
97 report, _ := world.store.report(ctx(), run)
98 if live := world.count("pages", "gone = ?", false); live != 2 ||
99 run.Created != 0 || report.Gone != 1 {
100 t.Errorf("after a delete in Mapa: %d live, run %+v, gone %d", live,
101 run, report.Gone)
102 }
103}
104
105// M4: every write a run makes holds its lease: ImportUpdate, staging, a
106// page's outcome and the run's end, each refused once Stop moved it.
107//
108// Mutations (make mutate, first red 2026-11-17): each of those writes
109// made without the run's lease.
110func TestM4EveryRunWriteHoldsTheLease(t *testing.T) {
111 world, handbook := rerunChanged(t)
112 lease, err := world.store.StartRun(ctx(), ana, false)
113 if err != nil {
114 t.Fatal(err)
115 }
116 job := world.job(lease, ana)
117 if err := job.survey(ctx()); err != nil {
118 t.Fatal(err)
119 }
120 set, err := job.loadSet(ctx())
121 if err != nil || len(set.pages) == 0 {
122 t.Fatalf("set: %v", err)
123 }
124 if _, err := world.store.StopRun(ctx(), ana); err != nil {
125 t.Fatal(err)
126 }
127 entry := set.pages[0]
128 for name, write := range map[string]func() error{
129 "update": func() error {
130 _, err := world.store.ImportUpdate(ctx(), importWrite{
131 lease: lease, who: ana, row: entry.row, title: "Late",
132 body: "Late.", pageID: handbook.ID,
133 expect: handbook.Revision})
134 return err
135 },
136 "stage": func() error {
137 return job.stage(ctx(), entry.row, entry.staged, false)
138 },
139 "outcome": func() error {
140 return job.outcome(ctx(), entry, mapUnchanged, "",
141 &pageImages{})
142 },
143 "done": func() error { return job.done(ctx()) },
144 } {
145 if err := write(); !errors.Is(err, errLeaseLost) {
146 t.Errorf("%s after Stop: %v", name, err)
147 }
148 }
149 if world.run(lease.run).State != runStopped {
150 t.Error("a write after Stop changed the run")
151 }
152}
153
154// M4: replacing the token ends a resumable run, so a Resume never runs
155// on a token other than the one its survey used (§8.3).
156//
157// Mutation (make mutate, first red 2026-11-17): Connect's replacement
158// leaves resumable runs alone.
159func TestM4ANewTokenEndsAResumableRun(t *testing.T) {
160 world := newImportWorld(t, newSmall().Workspace)
161 world.connect(ana)
162 lease, err := world.store.StartRun(ctx(), ana, false)
163 if err != nil {
164 t.Fatal(err)
165 }
166 world.store.InterruptRuns(ctx())
167 world.connect(ana)
168 run := world.run(lease.run)
169 if run.State != runFailed || run.ErrorCode != runDisconnected {
170 t.Errorf("after a new token: %+v", run)
171 }
172 if _, err := world.store.ResumeRun(ctx(), ana); !errors.Is(err,
173 ErrNoRun) {
174 t.Errorf("Resume after a new token: %v", err)
175 }
176}
177
178// M4: the heartbeat stops a goroutine whose lease moved, even when
179// nothing cancelled its context and it is waiting on Notion.
180//
181// Mutation (make mutate, first red 2026-11-17): the heartbeat notes the
182// lost lease and carries on.
183func TestM4TheHeartbeatStopsALeaselessRun(t *testing.T) {
184 saved := heartbeatEvery
185 heartbeatEvery = 20 * time.Millisecond
186 t.Cleanup(func() { heartbeatEvery = saved })
187 world := newImportWorld(t, newSmall().Workspace)
188 world.connect(ana)
189 lease, err := world.store.StartRun(ctx(), ana, false)
190 if err != nil {
191 t.Fatal(err)
192 }
193 world.server.Lock()
194 defer world.server.Unlock()
195 if err := world.app.launch(lease, ana); err != nil {
196 t.Fatal(err)
197 }
198 world.store.bookkeep(ctx(), runLease{}, func(db *gorm.DB) error {
199 return db.Model(&NotionRun{}).Where("id = ?", lease.run).
200 Update("lease", 1).Error
201 })
202 ended := make(chan struct{})
203 go func() { world.app.running.wait.Wait(); close(ended) }()
204 select {
205 case <-ended:
206 case <-time.After(3 * time.Second):
207 t.Error("a run whose lease moved kept waiting on Notion")
208 }
209}
210
211// M5: retention deletes a token unused for 90 days, with the staged
212// trees of runs nobody resumed, and keeps one checked or run since.
213//
214// Mutation (make mutate, first red 2026-11-17): the idle test never
215// finds a connection idle.
216func TestM5AnIdleTokenIsDeletedAt90Days(t *testing.T) {
217 world := newImportWorld(t, newSmall().Workspace)
218 world.connect(ana)
219 lease, err := world.store.StartRun(ctx(), ana, false)
220 if err != nil {
221 t.Fatal(err)
222 }
223 world.job(lease, ana).survey(ctx())
224 world.store.InterruptRuns(ctx())
225 start := time.Now()
226 for _, check := range []struct {
227 days int
228 kept bool
229 }{{89, true}, {91, false}} {
230 world.store.SetClock(func() time.Time {
231 return start.Add(time.Duration(check.days) * 24 * time.Hour)
232 })
233 if err := world.store.Sweep(ctx()); err != nil {
234 t.Fatal(err)
235 }
236 kept := world.count("notion_connections") == 1
237 staged := world.count("notion_pages", "sealed_staged IS NOT NULL")
238 if kept != check.kept || (staged > 0) != check.kept {
239 t.Errorf("after %d days: token %v, %d staged", check.days,
240 kept, staged)
241 }
242 }
243 if world.run(lease.run).ErrorCode != "idle" {
244 t.Error("the run the idle token ended does not say so")
245 }
246}
247
248// M6: Forget deletes the token too, so "Run again" cannot make second
249// copies of every page, and the next Connect claims its workspace
250// afresh (Paul's ruling: Forget is one of the token-deleting acts).
251//
252// Mutations (make mutate, first red 2026-11-17): Forget leaves the
253// connection; Forget leaves notion_images (round 3, M3).
254func TestM6ForgetDeletesTheToken(t *testing.T) {
255 ws, _ := imagePage(t)
256 world := newImportWorld(t, ws.Workspace)
257 world.useImages()
258 world.connect(ana)
259 world.importAs(ana)
260 if world.count("notion_images") == 0 {
261 t.Fatal("the import kept no image places to forget")
262 }
263 if err := world.store.Forget(ctx(), ana); err != nil {
264 t.Fatal(err)
265 }
266 if _, err := world.store.StartRun(ctx(), ana, false); !errors.Is(err,
267 ErrNotConnected) {
268 t.Errorf("Run again after Forget: %v", err)
269 }
270 if world.count("notion_images") != 0 {
271 t.Error("Forget left where the images went")
272 }
273 world.server.Workspace.Me["bot"].(map[string]any)["workspace_name"] =
274 "Another workspace"
275 workspace, _ := world.app.notion.Verify(ctx(), "secret_other")
276 if err := world.store.Connect(ctx(), ana, "secret_other",
277 workspace); err != nil {
278 t.Fatalf("a new workspace after Forget: %v", err)
279 }
280 row, _, _ := world.store.mapRowOf(world.store.database, workspaceKey)
281 place, _ := world.store.openCoordinate(row)
282 if place.Workspace != workspace.Identity() {
283 t.Errorf("the map's workspace is %q", place.Workspace)
284 }
285}
286
287// Fable L5: a mention of a page mapped but deleted in Mapa is its text,
288// plain, never a link that would bind to whatever page takes the free
289// title next (§11.2).
290//
291// Mutation (make mutate, first red 2026-11-17): the resolver answers a
292// page this run planned no title for as live.
293func TestL5ALinkToADeletedPageIsText(t *testing.T) {
294 ws := newSmall()
295 world := newImportWorld(t, ws.Workspace)
296 world.connect(ana)
297 world.importAs(ana)
298 handbook, _, _ := world.pageTitled("Handbook")
299 if err := world.store.Delete(ctx(), bo, handbook.ID); err != nil {
300 t.Fatal(err)
301 }
302 ws.set(ws.equipment, 0, notiontest.Para(notiontest.Text("Now "),
303 notiontest.PageMention(ws.handbook, "Handbook")))
304 world.importAs(ana)
305 _, record, _ := world.pageTitled("Equipment")
306 if links := world.linksOf("Equipment"); len(links) != 1 ||
307 !strings.Contains(record.Body, "Now Handbook") {
308 t.Errorf("Equipment links %v, body %q", links, record.Body)
309 }
310}
311
312// Fable round 2, Low 4 and Low 6: a page deleted mid-run is reported
313// deleted, not kept, and the page after it stops linking it.
314//
315// Mutations (make mutate, first red 2026-11-17): a page refused for
316// being gone is reported kept; a page found gone stays live.
317func TestLowADeleteMidRunIsGoneForLaterPages(t *testing.T) {
318 world, handbook := rerunChanged(t)
319 atPoint(t, "write:rendered", 1, func() {
320 world.store.Delete(ctx(), bo, handbook.ID)
321 })
322 run := world.importAs(ana)
323 report, _ := world.store.report(ctx(), run)
324 if report.Gone != 1 || report.KeptEdited != 0 {
325 t.Errorf("deleted mid-run: gone %d, kept %d", report.Gone,
326 report.KeptEdited)
327 }
328 if slices.Contains(world.linksOf("Onboarding"), "Handbook") {
329 t.Error("Onboarding still links the deleted Handbook")
330 }
331}
332
333// Fable round 2, Low 6: Forget ends a resumable run.
334//
335// Mutation (make mutate, first red 2026-11-17): Forget leaves resumable
336// runs.
337func TestLowForgetEndsAResumableRun(t *testing.T) {
338 world := newImportWorld(t, newSmall().Workspace)
339 world.connect(ana)
340 lease, err := world.store.StartRun(ctx(), ana, false)
341 if err != nil {
342 t.Fatal(err)
343 }
344 world.store.InterruptRuns(ctx())
345 if err := world.store.Forget(ctx(), ana); err != nil {
346 t.Fatal(err)
347 }
348 if run := world.run(lease.run); run.State != runFailed ||
349 run.ErrorCode != runForgotten {
350 t.Errorf("after Forget: %+v", run)
351 }
352}
353
354// Fable round 2, Low 6: a run since keeps a token checked long ago;
355// idle counts from the run's last activity, not its start.
356//
357// Mutation (make mutate, first red 2026-11-17): idle ignores runs.
358func TestLowARecentRunKeepsTheToken(t *testing.T) {
359 world := newImportWorld(t, newSmall().Workspace)
360 world.connect(ana)
361 lease, err := world.store.StartRun(ctx(), ana, false)
362 if err != nil {
363 t.Fatal(err)
364 }
365 start := time.Now()
366 world.store.database.Model(&NotionRun{}).Where("id = ?", lease.run).
367 Updates(map[string]any{"started_at": start,
368 "progress_at": start.Add(80 * 24 * time.Hour)})
369 world.store.SetClock(func() time.Time {
370 return start.Add(100 * 24 * time.Hour)
371 })
372 if err := world.store.Sweep(ctx()); err != nil {
373 t.Fatal(err)
374 }
375 if world.count("notion_connections") != 1 {
376 t.Error("a token with a run active 20 days ago was swept")
377 }
378}
379