oficina / mapa Public

Phase 1 step 8: Pinned and Recently edited in the sidebar

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Human

Prompt

Phase 1 step 8 of the Mapa level-up: Recently edited, and pins, built with the proposed answers as defaults (pins per person and sealed; Recently edited).

From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.

Summary

Pins are the person's own: a sealed list of page ids in their member row (new sealed column members.sealed_pins, migration 0003), at most 12, changed by POST /p/{id}/pin from the Page menu, logging one 'pins' event on the member, never naming the page. Recently edited is the six pages the viewer last committed a revision to (created, edited, reverted), from the event log, leaving out any transaction with more than one 'edited' (bulk link updates). Both lists go through the scoped accessor, so a page the viewer may no longer open drops out.
Agent notes
The plaintext gate's sealed-column list gains members.sealed_pins; no plaintext column was added. Gate 8 drives the pin route.
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 21ec6fd75c07316a7496d0dff78cb3cf08ec90e8 parent 15d9fbe
14 files changed, +338 −9
  • internal/mapa/frame.go +1 −1
  • internal/mapa/handlers_pages.go +2 −0
  • internal/mapa/menus.go +14 −3
  • internal/mapa/migrations/0003_alter_members.sql +2 −0
  • internal/mapa/migrations/schema.sql +1 −1
  • internal/mapa/models.go +7 −0
  • internal/mapa/pins.go +134 −0
  • internal/mapa/recent.go +111 −0
  • internal/mapa/seal/seal.go +2 −0
  • internal/mapa/side.go +8 −4
  • internal/mapa/today.go +1 −0
  • internal/mapatest/gate8_test.go +1 −0
  • internal/mapatest/plaintext_test.go +1 −0
  • internal/mapatest/sidebar_test.go +53 −0

CI passed — run details

CI log
=== vet ===
go vet ./...
go vet -tags browser ./internal/mapatest/
=== fmt ===
=== code ===
go tool rastrillo budget code
The base has no .rastrillo/code.txt: skipping the check that records only go down.
budget code: within the limits.
=== test ===
CGO_ENABLED=0 go test ./...
?   	amadan.net/oficina/mapa/cmd/mapa	[no test files]
ok  	amadan.net/oficina/mapa/internal/mapa	0.344s
?   	amadan.net/oficina/mapa/internal/mapa/icons	[no test files]
ok  	amadan.net/oficina/mapa/internal/mapa/markup	(cached)
ok  	amadan.net/oficina/mapa/internal/mapa/seal	0.002s
ok  	amadan.net/oficina/mapa/internal/mapatest	8.152s
?   	amadan.net/oficina/mapa/scripts/mutate	[no test files]
?   	amadan.net/oficina/mapa/scripts/preview	[no test files]
=== migration-check ===
go tool rastrillo migration check
rastrillo migration check: models and migrations agree
diff --git a/internal/mapa/frame.go b/internal/mapa/frame.go
index 355fabf..a67f74f 100644
--- a/internal/mapa/frame.go
+++ b/internal/mapa/frame.go
@@ -54,6 +54,7 @@ type leadView struct {
// are this app's templates, rendered into the bar's trusted slots.
func (app *app) buildFrame(request *http.Request, page *view) error {
tmpl := pages[page.name]
+ page.Frame.Side = app.side(request, page)
menus, err := fragment(tmpl, "mapa-menubar", menusFor(page))
if err != nil {
return err
@@ -73,7 +74,6 @@ func (app *app) buildFrame(request *http.Request, page *view) error {
Menu: "Menu"},
Menubar: menus, Lead: lead,
}
- page.Frame.Side = app.side(request, page)
if page.Chrome != nil && page.Chrome.Links {
page.Frame.Panel = linksState(request)
}
diff --git a/internal/mapa/handlers_pages.go b/internal/mapa/handlers_pages.go
index 224c8d4..18facc2 100644
--- a/internal/mapa/handlers_pages.go
+++ b/internal/mapa/handlers_pages.go
@@ -186,6 +186,8 @@ func notice(request *http.Request) string {
return "Updated links in " + pagesCount(query.Get("n")) + "."
case "linked":
return "Linked."
+ case "pinsfull":
+ return ErrTooManyPins.Error()
case "freed":
return "That old title is free for another page now."
case "deleted":
diff --git a/internal/mapa/menus.go b/internal/mapa/menus.go
index 163590f..1f04217 100644
--- a/internal/mapa/menus.go
+++ b/internal/mapa/menus.go
@@ -44,7 +44,7 @@ var divider = menuEntry{Kind: "divider"}
// menusFor is the bar's menus for one screen.
func menusFor(page *view) menuBar {
groups := []menuGroup{{ID: "page", Title: "Page",
- Items: pageMenu(page.Chrome)}}
+ Items: pageMenu(page.Chrome, page.Frame.Side.pinned())}}
if page.Chrome != nil && page.Chrome.Editor {
groups = append(groups, menuGroup{ID: "edit", Title: "Edit",
Items: editMenu()}, menuGroup{ID: "insert", Title: "Insert",
@@ -57,11 +57,11 @@ func menusFor(page *view) menuBar {
}
// pageMenu is New, then what this page allows, then the lists.
-func pageMenu(page *pageChrome) []menuEntry {
+func pageMenu(page *pageChrome, pinned bool) []menuEntry {
items := []menuEntry{link("New team page", "/new"),
link("New scratch page", "/scratch/new")}
if page != nil && page.Page != nil && page.Page.ID != 0 {
- items = append(items, divider)
+ items = append(items, divider, pinEntry(page.Page, pinned))
items = append(items, pageVerbs(*page.Page)...)
}
return append(items, divider, link("Deleted pages", "/deleted"))
@@ -150,3 +150,14 @@ func helpMenu() []menuEntry {
// iconHTML is one of Mapa's icons for a bar action (estilo draws it
// before the label, decoratively).
func iconHTML(slug string) template.HTML { return icons.Icon(slug) }
+
+// pinEntry is Pin or Unpin, a POST (the busy rule holds it 650ms).
+func pinEntry(page *PageView, pinned bool) menuEntry {
+ entry := menuEntry{Kind: "form", Label: "Pin to sidebar",
+ Action: "/p/" + page.Public + "/pin",
+ Fields: map[string]string{"pin": "1"}}
+ if pinned {
+ entry.Label, entry.Fields["pin"] = "Unpin from sidebar", "0"
+ }
+ return entry
+}
diff --git a/internal/mapa/migrations/0003_alter_members.sql b/internal/mapa/migrations/0003_alter_members.sql
new file mode 100644
index 0000000..cc1dcbb
--- /dev/null
+++ b/internal/mapa/migrations/0003_alter_members.sql
@@ -0,0 +1,2 @@
+ALTER TABLE `members` ADD `sealed_pins` blob;
+
diff --git a/internal/mapa/migrations/schema.sql b/internal/mapa/migrations/schema.sql
index 9edc26f..9f54774 100644
--- a/internal/mapa/migrations/schema.sql
+++ b/internal/mapa/migrations/schema.sql
@@ -9,7 +9,7 @@ CREATE TABLE `drafts` (`id` integer PRIMARY KEY AUTOINCREMENT,`page_id` integer,
CREATE TABLE `events` (`id` integer PRIMARY KEY AUTOINCREMENT,`nonce` integer NOT NULL,`at` datetime NOT NULL,`actor_id` integer NOT NULL,`object_kind` text NOT NULL,`object_id` integer NOT NULL,`verb` text NOT NULL,`revision` integer NOT NULL);
-CREATE TABLE `members` (`id` integer PRIMARY KEY AUTOINCREMENT,`address_print` text NOT NULL,`sealed_address` blob,`sealed_time_zone` blob);
+CREATE TABLE `members` (`id` integer PRIMARY KEY AUTOINCREMENT,`address_print` text NOT NULL,`sealed_address` blob,`sealed_time_zone` blob, `sealed_pins` blob);
CREATE TABLE `pages` (`id` integer PRIMARY KEY AUTOINCREMENT,`nonce` integer NOT NULL,`kind` text NOT NULL,`rung` text NOT NULL,`owner_id` integer NOT NULL,`revision` integer NOT NULL,`gone` numeric NOT NULL DEFAULT false,`sealed_record` blob,`created_at` datetime,`updated_at` datetime,CONSTRAINT `fk_pages_owner` FOREIGN KEY (`owner_id`) REFERENCES `members`(`id`) ON DELETE RESTRICT);
diff --git a/internal/mapa/models.go b/internal/mapa/models.go
index 259e2b2..891fd6c 100644
--- a/internal/mapa/models.go
+++ b/internal/mapa/models.go
@@ -36,6 +36,10 @@ type Member struct {
AddressPrint string `gorm:"uniqueIndex;size:64;not null"`
SealedAddress []byte
SealedTimeZone []byte
+ // SealedPins is the page ids the person pinned to their sidebar
+ // (level-up §3.2, §8; §11 Q1 proposed per person): sealed, so the
+ // file does not say which pages anyone pinned.
+ SealedPins []byte
}
// Page is a team page, a daily note or a scratch page. Its title, date and
@@ -158,4 +162,7 @@ const (
VerbAliasFreed = "alias_freed"
VerbJoined = "joined"
VerbTimeZoneSet = "timezone_set"
+ // VerbPinsSet is a change to a person's pins. Its object is the
+ // member, never the page (level-up §8).
+ VerbPinsSet = "pins"
)
diff --git a/internal/mapa/pins.go b/internal/mapa/pins.go
new file mode 100644
index 0000000..3c82cd8
--- /dev/null
+++ b/internal/mapa/pins.go
@@ -0,0 +1,134 @@
+package mapa
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "slices"
+
+ "github.com/go-chi/chi/v5"
+
+ "amadan.net/oficina/mapa/internal/mapa/seal"
+)
+
+// Pins (level-up spec §3.2, §8; §11 Q1, proposed per person, awaiting
+// Paul): the pages a person keeps at the top of their sidebar. They are
+// theirs alone, sealed in their member row, and the event a change logs
+// names the member, never the page.
+
+// maxPins is how many pages a sidebar holds pinned.
+const maxPins = 12
+
+// ErrTooManyPins is a pin past maxPins.
+var ErrTooManyPins = errors.New("You can pin up to 12 pages. " +
+ "Unpin one first.")
+
+// Pins is the viewer's pinned page ids, newest first. A page since
+// deleted or out of scope is dropped where the list is read.
+func (store *Store) Pins(ctx context.Context,
+ viewer Viewer) ([]int64, error) {
+ if viewer.MemberID == 0 {
+ return nil, nil
+ }
+ var member Member
+ err := store.database.WithContext(ctx).
+ First(&member, viewer.MemberID).Error
+ if err != nil {
+ return nil, err
+ }
+ return store.openPins(member.SealedPins)
+}
+
+func (store *Store) openPins(sealed []byte) ([]int64, error) {
+ if len(sealed) == 0 {
+ return nil, nil
+ }
+ plain, err := store.sealer.Open(seal.PurposePins, sealed)
+ if err != nil {
+ return nil, err
+ }
+ var ids []int64
+ return ids, json.Unmarshal(plain, &ids)
+}
+
+// SetPin pins or unpins a page the person may open.
+func (store *Store) SetPin(ctx context.Context, viewer Viewer,
+ pageID int64, pinned bool) error {
+ if _, err := store.readable(ctx, viewer, pageID); err != nil {
+ return err
+ }
+ return store.write(ctx, func(tx *Tx) error {
+ memberID, err := tx.member(viewer.Address)
+ if err != nil {
+ return err
+ }
+ var member Member
+ if err := tx.db.First(&member, memberID).Error; err != nil {
+ return err
+ }
+ ids, err := store.openPins(member.SealedPins)
+ if err != nil {
+ return err
+ }
+ if ids, err = repin(ids, pageID, pinned); err != nil {
+ return err
+ }
+ return tx.savePins(memberID, ids)
+ })
+}
+
+func repin(ids []int64, pageID int64, pinned bool) ([]int64, error) {
+ ids = slices.DeleteFunc(ids, func(id int64) bool { return id == pageID })
+ if !pinned {
+ return ids, nil
+ }
+ if len(ids) >= maxPins {
+ return nil, ErrTooManyPins
+ }
+ return append([]int64{pageID}, ids...), nil
+}
+
+func (tx *Tx) savePins(memberID int64, ids []int64) error {
+ plain, err := json.Marshal(ids)
+ if err != nil {
+ return err
+ }
+ sealed, err := tx.store.sealer.Seal(seal.PurposePins, plain)
+ if err != nil {
+ return err
+ }
+ err = tx.db.Model(&Member{}).Where("id = ?", memberID).
+ Update("sealed_pins", sealed).Error
+ if err != nil {
+ return err
+ }
+ return tx.log(memberID, ObjectMember, memberID, VerbPinsSet, 0)
+}
+
+func (app *app) pinRoutes(router chi.Router) {
+ router.Post("/p/{id}/pin", app.pin)
+}
+
+// pin is Page → Pin or Unpin: pin=1 or pin=0, then back to the page.
+func (app *app) pin(writer http.ResponseWriter, request *http.Request) {
+ page, ok := app.visible(writer, request)
+ if !ok {
+ return
+ }
+ viewer, err := app.viewer(request)
+ if err != nil {
+ app.fail(writer, request, err)
+ return
+ }
+ pinned := request.PostFormValue("pin") == "1"
+ err = app.store.SetPin(request.Context(), viewer, page.ID, pinned)
+ switch {
+ case errors.Is(err, ErrTooManyPins):
+ seeOther(writer, request, page.Href+"?done=pinsfull")
+ case err != nil:
+ app.refuse(writer, request, err)
+ default:
+ seeOther(writer, request, page.Href)
+ }
+}
diff --git a/internal/mapa/recent.go b/internal/mapa/recent.go
new file mode 100644
index 0000000..e78cf7e
--- /dev/null
+++ b/internal/mapa/recent.go
@@ -0,0 +1,111 @@
+package mapa
+
+import (
+ "context"
+ "net/http"
+)
+
+// The sidebar's two lists (level-up spec §3.2): Pinned (pins.go) and
+// Recently edited. Both are the viewer's own and both are read through
+// the scoped accessor, so a page they may no longer open drops out.
+
+// recentCount is how many pages Recently edited shows.
+const recentCount = 6
+
+// recentVerbs are the writes that count as editing a page. Bulk link
+// edits on team pages log their own verbs and do not count (§8).
+var recentVerbs = []string{VerbCreated, VerbEdited, VerbReverted}
+
+// recentEdits is the page ids the person last wrote in, newest first,
+// leaving out bulk edits: a transaction that logged more than one
+// "edited" (Update links on private pages, which keep "edited" so the
+// plaintext log says nothing of a private link graph; §3.2, N1).
+func (store *Store) recentEdits(ctx context.Context,
+ memberID int64) ([]int64, error) {
+ var rows []Event
+ err := store.database.WithContext(ctx).
+ Where("actor_id = ? AND object_kind = ? AND verb IN ?", memberID,
+ ObjectPage, recentVerbs).
+ Order("id DESC").Limit(200).Find(&rows).Error
+ if err != nil {
+ return nil, err
+ }
+ edited := map[int64]int{}
+ for _, row := range rows {
+ if row.Verb == VerbEdited {
+ edited[row.At.UnixNano()]++
+ }
+ }
+ var ids []int64
+ seen := map[int64]bool{}
+ for _, row := range rows {
+ if (row.Verb == VerbEdited && edited[row.At.UnixNano()] > 1) ||
+ seen[row.ObjectID] {
+ continue
+ }
+ seen[row.ObjectID] = true
+ ids = append(ids, row.ObjectID)
+ }
+ return ids, nil
+}
+
+// sideLists are Pinned and Recently edited for the viewer. A failure to
+// read them leaves them out; the page itself still draws.
+func (app *app) sideLists(request *http.Request,
+ page *view) ([]sideLink, []sideLink) {
+ viewer := page.Viewer
+ if viewer.MemberID == 0 {
+ return nil, nil
+ }
+ ctx := request.Context()
+ pins, pinErr := app.store.Pins(ctx, viewer)
+ recent, recentErr := app.store.recentEdits(ctx, viewer.MemberID)
+ if pinErr != nil || recentErr != nil {
+ app.logger.Error("sidebar lists", "pins", pinErr,
+ "recent", recentErr)
+ return nil, nil
+ }
+ current := ""
+ if page.Chrome != nil && page.Chrome.Page != nil {
+ current = page.Chrome.Page.Href
+ }
+ return app.index.SideLinks(ctx, ScopeOf(viewer), pins, 0, current),
+ app.index.SideLinks(ctx, ScopeOf(viewer), recent, recentCount,
+ current)
+}
+
+// SideLinks is pages by id as sidebar rows, those the scope may open
+// only, at most limit of them (0 for no limit).
+func (index *Index) SideLinks(ctx context.Context, scope Scope,
+ ids []int64, limit int, current string) []sideLink {
+ if err := index.Sync(ctx); err != nil {
+ return nil
+ }
+ index.mutex.RLock()
+ defer index.mutex.RUnlock()
+ view := index.in(scope)
+ var out []sideLink
+ for _, pageID := range ids {
+ found := view.page(pageID)
+ if found == nil {
+ continue
+ }
+ out = append(out, sideLink{Label: found.label(),
+ Href: found.href(), Icon: sideIcon(found.kind),
+ Current: found.href() == current})
+ if limit > 0 && len(out) == limit {
+ break
+ }
+ }
+ return out
+}
+
+func sideIcon(kind string) string {
+ switch kind {
+ case KindDaily:
+ return "calendar"
+ case KindScratch:
+ return "file"
+ }
+ return "file-text"
+}
diff --git a/internal/mapa/seal/seal.go b/internal/mapa/seal/seal.go
index 6ef2606..1b22a9f 100644
--- a/internal/mapa/seal/seal.go
+++ b/internal/mapa/seal/seal.go
@@ -41,6 +41,8 @@ const (
PurposeAddress = "member.address"
// PurposeTimeZone seals a member's time zone setting.
PurposeTimeZone = "member.timezone"
+ // PurposePins seals the pages a member pinned to their sidebar.
+ PurposePins = "member.pins"
)
// Print purposes. Each answers one equality question and no other, so a
diff --git a/internal/mapa/side.go b/internal/mapa/side.go
index 82b0f45..78539de 100644
--- a/internal/mapa/side.go
+++ b/internal/mapa/side.go
@@ -119,8 +119,12 @@ func localReturn(target string) string {
return target
}
-// sideLists are Pinned and Recently edited. Filled in by recent.go.
-func (app *app) sideLists(request *http.Request,
- page *view) ([]sideLink, []sideLink) {
- return nil, nil
+// pinned reports whether the page on screen is one of the viewer's pins.
+func (side sideView) pinned() bool {
+ for _, link := range side.Pinned {
+ if link.Current {
+ return true
+ }
+ }
+ return false
}
diff --git a/internal/mapa/today.go b/internal/mapa/today.go
index 5e9d0c0..bc825ee 100644
--- a/internal/mapa/today.go
+++ b/internal/mapa/today.go
@@ -23,6 +23,7 @@ func (app *app) pageRoutes(router chi.Router) {
app.privateRoutes(router)
app.searchRoutes(router)
app.viewRoutes(router)
+ app.pinRoutes(router)
}
// viewer resolves the signed-in person without writing anything.
diff --git a/internal/mapatest/gate8_test.go b/internal/mapatest/gate8_test.go
index 7a36e1e..2a95fa7 100644
--- a/internal/mapatest/gate8_test.go
+++ b/internal/mapatest/gate8_test.go
@@ -130,6 +130,7 @@ func gate8Steps(t *testing.T, world *rig) []step {
url.Values{"state": {"rail"}, "return": {"/"}}),
posting("/view/links", Ana, "/view/links",
url.Values{"state": {"closed"}, "return": {"/"}}),
+ posting("/p/{id}/pin", Bo, acme+"/pin", url.Values{"pin": {"1"}}),
}
return append(steps, gate8Later(t, acme, notes)...)
}
diff --git a/internal/mapatest/plaintext_test.go b/internal/mapatest/plaintext_test.go
index e206efc..3365106 100644
--- a/internal/mapatest/plaintext_test.go
+++ b/internal/mapatest/plaintext_test.go
@@ -67,6 +67,7 @@ var plaintextColumns = map[string]string{
var sealedColumns = map[string]bool{
"members.sealed_address": true,
"members.sealed_time_zone": true,
+ "members.sealed_pins": true,
"pages.sealed_record": true,
"aliases.sealed_title": true,
"revisions.sealed_record": true,
diff --git a/internal/mapatest/sidebar_test.go b/internal/mapatest/sidebar_test.go
new file mode 100644
index 0000000..5a2ea5a
--- /dev/null
+++ b/internal/mapatest/sidebar_test.go
@@ -0,0 +1,53 @@
+package mapatest
+
+import (
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+)
+
+// Pins are the viewer's own (level-up §3.2, §11 Q1 proposed): Bo's pin
+// is in Bo's sidebar and nobody else's, and a page cannot be pinned by
+// someone who may not open it.
+func TestPinsAreYoursAlone(t *testing.T) {
+ rig := newRig(t)
+ acme := rig.createPage(t, Ana, "Acme", "One.")
+ rig.post(t, Bo, acme+"/pin", url.Values{"pin": {"1"}})
+ bo, ana := rig.page(t, Bo, "/pages"), rig.page(t, Ana, "/pages")
+ if !strings.Contains(between(bo, "Pinned", "</nav>"), "Acme") {
+ t.Fatal("Bo's pin is not in his sidebar")
+ }
+ if strings.Contains(ana, ">Pinned<") {
+ t.Fatal("Bo's pin showed in Ana's sidebar")
+ }
+ if !strings.Contains(rig.page(t, Bo, acme), "Unpin from sidebar") {
+ t.Fatal("a pinned page does not offer Unpin")
+ }
+ rig.post(t, Bo, acme+"/pin", url.Values{"pin": {"0"}})
+ if strings.Contains(rig.page(t, Bo, "/pages"), ">Pinned<") {
+ t.Fatal("Unpin left the page pinned")
+ }
+ scratch := rig.post(t, Ana, "/scratch", url.Values{"body": {"Mine."}})
+ private := scratch.Header().Get("Location")
+ if got := rig.post(t, Bo, private+"/pin",
+ url.Values{"pin": {"1"}}); got.Code != http.StatusNotFound {
+ t.Fatalf("Bo pinned Ana's scratch page: %d", got.Code)
+ }
+}
+
+// Recently edited is the pages you last wrote in, newest first, and
+// "Update links" is not writing (level-up §3.2).
+func TestRecentlyEditedIsWhatYouWroteIn(t *testing.T) {
+ rig := newRig(t)
+ acme := rig.createPage(t, Bo, "Acme", "One.")
+ rig.createPage(t, Bo, "Beta", "Two.")
+ recent := between(rig.page(t, Bo, acme), "Recently edited", "</nav>")
+ if strings.Index(recent, "Beta") > strings.Index(recent, "Acme") ||
+ !strings.Contains(recent, "Acme") {
+ t.Fatalf("Recently edited is not newest first:\n%s", recent)
+ }
+ if strings.Contains(rig.page(t, Ana, acme), "Recently edited") {
+ t.Fatal("Ana, who wrote nothing, has Recently edited")
+ }
+}