Add revision-guarded local note reading and editing
Use canonical sealed ingestion and durable update receipts, preserving later edits on retries and refusing imported custody. Serialize derived indexing and receipt acknowledgement. Independent GPT-6 Astra spec/source approval; full CI, focused race and seven adverse mutations verified.
Co-Authored-By: Codex <codex~paul@keymail.dev>
14 files changed,
+926
−12
docs/superpowers/specs/2026-11-01-agent-note-editing.md+116 −0internal/memoria/agent_access.go+5 −1internal/memoria/agent_boundary.go+7 −4internal/memoria/agent_edit.go+163 −0internal/memoria/agent_edit_contracts.go+17 −0internal/memoria/agent_edit_limits_test.go+32 −0internal/memoria/agent_edit_receipt_test.go+81 −0internal/memoria/agent_edit_recovery_test.go+158 −0internal/memoria/agent_edit_test.go+215 −0internal/memoria/agent_index_order_test.go+80 −0internal/memoria/agent_migrations/migrations/0003_note_updates.sql+8 −0internal/memoria/agent_response.go+12 −0internal/memoria/models.go+2 −1internal/memoria/store.go+30 −6
CI passed — run details
diff --git a/docs/superpowers/specs/2026-11-01-agent-note-editing.md b/docs/superpowers/specs/2026-11-01-agent-note-editing.md| new file mode 100644 |
| index 0000000..a965f8e |
| --- /dev/null |
| +++ b/docs/superpowers/specs/2026-11-01-agent-note-editing.md |
| @@ -0,0 +1,116 @@ |
| +# Bounded delegated local note editing |
| + |
| +Status: specification and final implementation/evidence approved by independent |
| +GPT-6 Astra review on 2026-11-01. Local CI and race checks passed. Not deployed. |
| +Extends the existing agent-access branch without changing v1 search/create wire |
| +contracts. Existing authority, custody, guarded-response and roster requirements |
| +remain binding. |
| + |
| +## Operations |
| + |
| +`notes_get`, scope `notes:read`, takes `{team,id}` and returns |
| +`{id,title,body,revision,url}`. IDs and revision are positive integers; revision |
| +is the existing `Document.Revision`. It reads only locally authored paste notes |
| +(browser, native or agent), identified by `source='paste'`, empty sibling item |
| +coordinate and zero sibling revision. Other sources and missing/deleted rows |
| +return `not_found`, even when they are searchable. No imported upload, connector |
| +or sibling content becomes editable through this API. Notes remain team-shared; |
| +there is no invented creator-only permission rule. |
| + |
| +`notes_update`, scope `notes:write`, takes |
| +`{team,id,client_id,expected_revision,title,body}` and returns |
| +`{id,revision,indexed,url}`. Title/body replace the complete note, with create's |
| +512-byte title and 1-MiB body bounds and existing trimming/nonblank rules. |
| +`client_id` is a canonical nonzero UUID; `expected_revision` is a positive |
| +integer. Unknown fields are refused. No delete, source move, custody change, |
| +attachment edit, or partial text splice is introduced. |
| + |
| +## Transaction and retries |
| + |
| +Reserve SQLite's writer before reading the target, authority or receipt. Check |
| +the original delegated credential, Home person identity, current admission and |
| +captured roster lease inside that transaction, before and after all work. |
| +Validate the immutable receipt authority marker. Reuse the existing ingestion |
| +implementation for sealing, chunk replacement, provenance and derived indexing, |
| +with a private existing-document target bound to ID and external coordinate; |
| +never derive a new key from the edited title and never recreate a deleted target. |
| + |
| +An additive receipt table stores a keyed coordinate over authority, subject, |
| +client, team, operation and client UUID; a keyed fingerprint binds all supplied |
| +fields including target and precondition. Resource update and completed receipt |
| +(target, resulting revision) commit atomically. Same UUID with changed request |
| +is `conflict`. For an identical completed retry, first recheck current identity, |
| +write authority and exact live local-note coordinate, then return the original |
| +receipt revision without applying old content or requiring the old precondition |
| +to equal the latest revision. Later edits survive; deletion is `not_found`. |
| +New requests with a stale precondition return `conflict` and change nothing. |
| +An unresolved/malformed receipt fails closed instead of repairing by replay. |
| + |
| +For local paste notes, title changes must also advance Document.Revision; the |
| +existing body-only counter cannot protect full-note replacement from concurrent |
| +renames. Make this narrow domain correction for all paste ingestion writers; |
| +sibling/import revision semantics stay unchanged. Byte-identical normalized |
| +saves keep the existing revision. Body changes keep the ordinary chunk lifecycle. |
| + |
| +Indexing is postcommit derived work under WithoutCancel. A Store mutation lock |
| +serializes ingest/delete/rebuild through their derived-state completion, so an |
| +older refresh cannot overwrite a newer revision. A committed update |
| +reports indexed false on index failure; a retry must never reindex request text |
| +over a newer note. `indexed` describes completion of this receipt's indexing, |
| +not proof the current revision is indexed. A reader obtains current state through |
| +notes_get; the update's revision is explicitly the committed receipt revision. |
| + |
| +## Response and evidence |
| + |
| +Capture ID, source, external coordinate, sibling-coordinate absence and revision |
| +for reads. Before headers and each chunk, revalidate the current person/lease and |
| +exact note coordinate/revision; suppress a body selected from an older revision. |
| +Mutation receipts contain no title/body; response emission revalidates live local |
| +custody and identity, while allowing a later revision to coexist with the receipt. |
| + |
| +Tests must prove create/get/update and browser/search effects; browser/native |
| +paste support; imported and sibling refusal; title-only conflicts; simultaneous |
| +updates with one winning precondition; replay after later edit/deletion; changed |
| +payload conflicts; receipt/body/chunk rollback on injected failure; index failure |
| +and recovery; authority/revocation while waiting and at final commit; response |
| +identity/custody/revision loss including a multi-chunk body. Run app CI and race |
| +tests. Independent review selects adversarial mutations; record model and evidence. |
| +No merge, deployment, credentials or infrastructure changes are included. |
| + |
| +## Independent review and mutation evidence — 2026-11-01 |
| + |
| +Independent GPT-6 Astra reviewed the spec and source. Source review required |
| +explicit signed-counter overflow refusal; Calendar additionally rechecks mutation |
| +write permission at emission, standing after database reads, and samples wall |
| +time before the remaining-lease calculation. Those corrections are implemented. |
| +Source approval and deployment status are separate from these test results. |
| + |
| +The independent reviewer selected these mutations; each was applied separately, |
| +failed its behavioral assertion, and was reverted before final checks: |
| + |
| +- `stale-revision`: `TestAgentNoteEditLifecycle` — detected. |
| +- `reapply-receipt`: `TestAgentNoteEditLifecycle` — detected. |
| +- `custody`: `TestAgentNoteEditCustodyAndConcurrency` — detected. |
| +- `final-authority`: `TestAgentNoteUpdateRetryFinalGuardWithoutResponse` — detected. |
| +- `rename-revision`: `TestAgentNoteEditLifecycle` — detected. |
| +- `old-index-publication`: `TestAgentNoteOlderRefreshCannotReplaceNewerIndex` — detected. |
| + |
| +The index ordering test holds an older refresh after it selects its document, |
| +allows a concurrent writer to compete, and verifies the newest title is the only |
| +one indexed. The socket-deadline test observes actual HTTP server deadlines |
| +under a near-expiry roster lease. No mutation result rests on a compiler failure. |
| + |
| +Concurrent identical updates serialize on the existing agent-note mutex through |
| +the final indexed acknowledgement. Lock order is agentNotes then Store.mutationMu; |
| +ordinary ingestion takes only the latter. A replay cannot observe a transient |
| +false acknowledgement while the original request is still completing indexing. |
| +The reviewer requested a controlled pause before the indexed receipt write; the |
| +replay waits, and both calls return the same immutable acknowledgement. |
| + |
| +Final evidence: `make ci` passes; `go test -race ./internal/memoria -run |
| +"Agent|Ingest|Delete|Rebuild" -count=1` passes, followed after the acknowledgement |
| +fix by the focused `AgentNoteConcurrentRetry|AgentNoteEdit|AgentNoteUpdate| |
| +AgentNoteOlderRefresh` race selection and another full CI pass. A seventh mutation |
| +omitting agentNotes serialization fails the controlled concurrent-replay test |
| +with the original transient indexed=false acknowledgement. Final independent |
| +review approved that correction. |
diff --git a/internal/memoria/agent_access.go b/internal/memoria/agent_access.go| index f09f349..f07a1c6 100644 |
| --- a/internal/memoria/agent_access.go |
| +++ b/internal/memoria/agent_access.go |
| @@ -159,7 +159,7 @@ func (a *app) agentOperations(team string) []access.Operation { |
| return out, nil |
| } |
| } |
| - return []access.Operation{ |
| + ops := []access.Operation{ |
| {Name: "notes_search", Description: "Search currently visible Memoria passages for a team. Sibling apps check access on every query.", Scope: "notes:read", ReadOnly: true, Idempotent: true, |
| Input: json.RawMessage(`{"type":"object","required":["team","query"],"additionalProperties":false,"properties":{"team":{"type":"string","minLength":1},"query":{"type":"string","minLength":1,"maxLength":2048}}}`), |
| Output: json.RawMessage(`{"type":"object","required":["results","notices"],"additionalProperties":false,"properties":{"results":{"type":"array","items":{"type":"object","required":["id","document_id","title","text","source"],"properties":{"id":{"type":"integer"},"document_id":{"type":"integer"},"title":{"type":"string"},"text":{"type":"string"},"source":{"type":"string"}}}},"notices":{"type":"array","items":{"type":"string"}}}}`), |
| @@ -169,6 +169,10 @@ func (a *app) agentOperations(team string) []access.Operation { |
| Output: json.RawMessage(`{"type":"object","required":["id","indexed"],"additionalProperties":false,"properties":{"id":{"type":"integer","minimum":1},"indexed":{"type":"boolean"}}}`), |
| Invoke: guard("notes:write", a.agentCreate)}, |
| } |
| + edits := noteEditContracts() |
| + edits[0].Invoke = guard("notes:read", a.agentGetNote) |
| + edits[1].Invoke = guard("notes:write", a.agentUpdateNote) |
| + return append(ops, edits...) |
| } |
| func (a *app) agentSearch(ctx context.Context, p access.Principal, raw json.RawMessage, address string) (any, error) { |
diff --git a/internal/memoria/agent_boundary.go b/internal/memoria/agent_boundary.go| index df3639a..3a3f06a 100644 |
| --- a/internal/memoria/agent_boundary.go |
| +++ b/internal/memoria/agent_boundary.go |
| @@ -24,6 +24,7 @@ type agentRequest struct { |
| selected bool |
| passages []Result |
| noteID int64 |
| + noteRevision int |
| noteKey, noteExternal string |
| } |
| @@ -53,7 +54,7 @@ func (a *app) bindAgent(tx *gorm.DB) error { |
| if e != nil { |
| return e |
| } |
| - if e = tx.Exec("INSERT INTO memoria_agent_state(id,keycheck) SELECT 1,? WHERE NOT EXISTS(SELECT 1 FROM memoria_agent_notes) ON CONFLICT(id) DO NOTHING", want).Error; e != nil { |
| + if e = tx.Exec("INSERT INTO memoria_agent_state(id,keycheck) SELECT 1,? WHERE NOT EXISTS(SELECT 1 FROM memoria_agent_notes) AND NOT EXISTS(SELECT 1 FROM memoria_agent_note_updates) ON CONFLICT(id) DO NOTHING", want).Error; e != nil { |
| return e |
| } |
| var got string |
| @@ -80,7 +81,7 @@ func (a *app) checkAgentWriter(ctx context.Context, tx *gorm.DB, p access.Princi |
| if e != nil { |
| return e |
| } |
| - if person.ID != state.personID || person.Label != address { |
| + if person.ID != state.personID || person.Label != address || !a.teamMode() && !a.Admit(person.Label) { |
| return access.Fail("forbidden", "The linked identity changed.") |
| } |
| @@ -90,8 +91,10 @@ func (a *app) checkAgentWriter(ctx context.Context, tx *gorm.DB, p access.Princi |
| // Hooks are private: only the agent creation path can bind an effect receipt |
| // into canonical ingestion. Public ingestion retains its existing upsert rules. |
| type ingestBoundary struct { |
| - before func(*gormTx, string) (int64, bool, error) |
| - after func(*gormTx, int64) error |
| + external string |
| + refresh bool |
| + before func(*gormTx, string) (int64, bool, error) |
| + after func(*gormTx, int64) error |
| } |
| func (s *Store) ingestAgent(ctx context.Context, spec IngestSpec, guard *ingestBoundary) (int64, error) { |
diff --git a/internal/memoria/agent_edit.go b/internal/memoria/agent_edit.go| new file mode 100644 |
| index 0000000..b7749b2 |
| --- /dev/null |
| +++ b/internal/memoria/agent_edit.go |
| @@ -0,0 +1,163 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "strconv" |
| + "strings" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/memoria/internal/memoria/seal" |
| + "github.com/google/uuid" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// localAgentNote deliberately excludes every imported source, including ones |
| +// whose read custody belongs to Memoria. Read ownership is not edit permission. |
| +func localAgentNote(tx *gorm.DB, id int64) (Document, error) { |
| + var d Document |
| + err := tx.Where("id=? AND source='paste' AND sibling_revision=0 AND (sibling_item_id IS NULL OR length(sibling_item_id)=0)", id).Take(&d).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return d, access.Fail("not_found", "This local note is unavailable.") |
| + } |
| + return d, err |
| +} |
| + |
| +func (a *app) agentGetNote(ctx context.Context, _ access.Principal, raw json.RawMessage, _ string) (any, error) { |
| + var in struct { |
| + ID int64 `json:"id"` |
| + } |
| + if json.Unmarshal(raw, &in) != nil || in.ID <= 0 { |
| + return nil, access.Fail("invalid", "Supply a note ID.") |
| + } |
| + d, err := localAgentNote(a.db.G.WithContext(ctx), in.ID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + title, err := a.store.sealer.Open(seal.PurposeTitle, d.SealedTitle) |
| + if err != nil { |
| + return nil, err |
| + } |
| + body, err := a.store.sealer.Open(seal.PurposeBody, d.SealedBody) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if s, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest); ok { |
| + s.noteID, s.noteExternal, s.noteRevision = d.ID, d.ExternalID, d.Revision |
| + } |
| + return map[string]any{"id": d.ID, "title": string(title), "body": string(body), "revision": d.Revision, "url": a.origin + "/documents/" + strconv.FormatInt(d.ID, 10)}, nil |
| +} |
| + |
| +type agentNoteUpdateInput struct { |
| + Team string `json:"team"` |
| + ID int64 `json:"id"` |
| + ClientID string `json:"client_id"` |
| + ExpectedRevision int `json:"expected_revision"` |
| + Title string `json:"title"` |
| + Body string `json:"body"` |
| +} |
| + |
| +func (a *app) agentUpdateNote(ctx context.Context, p access.Principal, raw json.RawMessage, address string) (any, error) { |
| + var in agentNoteUpdateInput |
| + if json.Unmarshal(raw, &in) != nil { |
| + return nil, access.Fail("invalid", "Invalid note update.") |
| + } |
| + uid, err := uuid.Parse(in.ClientID) |
| + if err != nil || uid == uuid.Nil || uid.String() != in.ClientID || in.ID <= 0 || in.ExpectedRevision < 1 || strings.TrimSpace(in.Title) == "" || strings.TrimSpace(in.Body) == "" || len(in.Title) > 512 || len(in.Body) > 1<<20 { |
| + return nil, access.Fail("invalid", "Supply a local note, revision, nonblank title/body and canonical UUID client_id.") |
| + } |
| + // The receipt's indexing acknowledgement settles before an identical |
| + // request may replay it. Lock order is agentNotes, then Store.mutationMu. |
| + a.agentNotes.Lock() |
| + defer a.agentNotes.Unlock() |
| + coordinate, _ := json.Marshal([]string{a.home.issuer, a.agentIssuer, p.Subject, p.Client, in.Team, "notes_update", in.ClientID}) |
| + key, err := a.store.sealer.Fingerprint("agent.note.update.coordinate.v1", coordinate) |
| + if err != nil { |
| + return nil, err |
| + } |
| + payload, _ := json.Marshal(in) |
| + print, err := a.store.sealer.Fingerprint("agent.note.update.content.v1", payload) |
| + if err != nil { |
| + return nil, err |
| + } |
| + // This preliminary coordinate never authorizes a write: the exact live row |
| + // and its custody are checked again after reserving the writer below. |
| + d, err := localAgentNote(a.db.G.WithContext(ctx), in.ID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + revision, indexed, replayed := 0, false, false |
| + guard := &ingestBoundary{external: d.ExternalID} |
| + guard.before = func(tx *gormTx, external string) (int64, bool, error) { |
| + if err := a.bindAgent(tx); err != nil { |
| + return 0, false, err |
| + } |
| + if err := a.checkAgentWriter(ctx, tx, p, address); err != nil { |
| + return 0, false, err |
| + } |
| + current, err := localAgentNote(tx, in.ID) |
| + if err != nil { |
| + return 0, false, err |
| + } |
| + if current.ExternalID != external { |
| + return 0, false, access.Fail("not_found", "This local note changed identity.") |
| + } |
| + var receipt struct { |
| + Content string |
| + DocumentID int64 |
| + ExternalID string |
| + Revision int |
| + Indexed bool |
| + } |
| + result := tx.Table("memoria_agent_note_updates").Where("coordinate=?", key).Take(&receipt) |
| + if result.Error == nil { |
| + if receipt.Content != print { |
| + return 0, false, access.Fail("conflict", "This client_id was used with different note fields.") |
| + } |
| + if receipt.DocumentID != in.ID || receipt.ExternalID != external || receipt.Revision < 1 { |
| + return 0, false, access.Fail("unavailable", "Note receipt requires repair.") |
| + } |
| + revision, indexed, replayed = receipt.Revision, receipt.Indexed, true |
| + return in.ID, true, nil |
| + } |
| + if !errors.Is(result.Error, gorm.ErrRecordNotFound) { |
| + return 0, false, result.Error |
| + } |
| + if current.Revision != in.ExpectedRevision { |
| + return 0, false, access.Fail("conflict", "This note has changed. Read it before updating.") |
| + } |
| + return 0, false, nil |
| + } |
| + guard.after = func(tx *gormTx, id int64) error { |
| + if id != in.ID { |
| + return access.Fail("unavailable", "Note identity changed.") |
| + } |
| + if !replayed { |
| + guard.refresh = true |
| + current, err := localAgentNote(tx, id) |
| + if err != nil { |
| + return err |
| + } |
| + revision = current.Revision |
| + if err := tx.Exec("INSERT INTO memoria_agent_note_updates(coordinate,content,document_id,external_id,revision) VALUES(?,?,?,?,?)", key, print, id, d.ExternalID, revision).Error; err != nil { |
| + return err |
| + } |
| + } |
| + return a.checkAgentWriter(ctx, tx, p, address) |
| + } |
| + id, err := a.store.ingestAgent(ctx, IngestSpec{Source: "paste", Title: in.Title, Body: in.Body}, guard) |
| + if err != nil && !errors.Is(err, ErrIndexLag) { |
| + return nil, err |
| + } |
| + if !replayed && err == nil { |
| + // A later edit may have committed since ingest released its mutation lock. |
| + // Record success only while this exact committed revision remains current. |
| + r := a.db.G.WithContext(context.WithoutCancel(ctx)).Exec("UPDATE memoria_agent_note_updates SET indexed=1 WHERE coordinate=? AND EXISTS(SELECT 1 FROM documents WHERE id=? AND revision=? AND external_id=?)", key, id, revision, d.ExternalID) |
| + indexed = r.Error == nil && r.RowsAffected == 1 |
| + } |
| + if s, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest); ok { |
| + s.noteID, s.noteExternal = id, d.ExternalID |
| + } |
| + return map[string]any{"id": id, "revision": revision, "indexed": indexed, "url": a.origin + "/documents/" + strconv.FormatInt(id, 10)}, nil |
| +} |
diff --git a/internal/memoria/agent_edit_contracts.go b/internal/memoria/agent_edit_contracts.go| new file mode 100644 |
| index 0000000..c158b53 |
| --- /dev/null |
| +++ b/internal/memoria/agent_edit_contracts.go |
| @@ -0,0 +1,17 @@ |
| +package memoria |
| + |
| +import ( |
| + access "amadan.net/oficina/agent-access.git" |
| + "encoding/json" |
| +) |
| + |
| +func noteEditContracts() []access.Operation { |
| + return []access.Operation{ |
| + {Name: "notes_get", Description: "Read a local user-authored paste note with its current revision. Imported and sibling content is not available through this operation.", Scope: "notes:read", ReadOnly: true, Idempotent: true, |
| + Input: json.RawMessage(`{"type":"object","required":["team","id"],"additionalProperties":false,"properties":{"team":{"type":"string","minLength":1},"id":{"type":"integer","minimum":1}}}`), |
| + Output: json.RawMessage(`{"type":"object","required":["id","title","body","revision","url"],"additionalProperties":false,"properties":{"id":{"type":"integer","minimum":1},"title":{"type":"string"},"body":{"type":"string"},"revision":{"type":"integer","minimum":1},"url":{"type":"string"}}}`)}, |
| + {Name: "notes_update", Description: "Replace a local paste note using its current revision. Reuse client_id only for an identical retry. Returned revision is the originally committed revision; indexed records that update's completed indexing, not the current note's index state.", Scope: "notes:write", Idempotent: true, |
| + Input: json.RawMessage(`{"type":"object","required":["team","id","client_id","expected_revision","title","body"],"additionalProperties":false,"properties":{"team":{"type":"string","minLength":1},"id":{"type":"integer","minimum":1},"client_id":{"type":"string","minLength":36,"maxLength":36},"expected_revision":{"type":"integer","minimum":1},"title":{"type":"string","minLength":1,"maxLength":512},"body":{"type":"string","minLength":1,"maxLength":1048576}}}`), |
| + Output: json.RawMessage(`{"type":"object","required":["id","revision","indexed","url"],"additionalProperties":false,"properties":{"id":{"type":"integer","minimum":1},"revision":{"type":"integer","minimum":1},"indexed":{"type":"boolean"},"url":{"type":"string"}}}`)}, |
| + } |
| +} |
diff --git a/internal/memoria/agent_edit_limits_test.go b/internal/memoria/agent_edit_limits_test.go| new file mode 100644 |
| index 0000000..d79c751 |
| --- /dev/null |
| +++ b/internal/memoria/agent_edit_limits_test.go |
| @@ -0,0 +1,32 @@ |
| +package memoria |
| + |
| +import ( |
| + "math" |
| + "testing" |
| + |
| + "github.com/google/uuid" |
| +) |
| + |
| +func TestAgentNoteUpdateRevisionExhaustion(t *testing.T) { |
| + for _, body := range []string{"original body", "changed body"} { |
| + t.Run(body, func(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + h := mountAgentFixture(t, f, &p, &active) |
| + id, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "limit", Title: "original", Body: "original body"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.app.db.G.Model(&Document{}).Where("id=?", id).Update("revision", math.MaxInt).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if w := agentCall(h, "notes_update", noteUpdateJSON(id, math.MaxInt, uuid.NewString(), "changed", body)); w.Code != 503 { |
| + t.Fatal(w.Code, w.Body.String()) |
| + } |
| + var d Document |
| + if err := f.app.db.G.First(&d, id).Error; err != nil || d.Revision != math.MaxInt { |
| + t.Fatal("revision corrupted", d.Revision, err) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/memoria/agent_edit_receipt_test.go b/internal/memoria/agent_edit_receipt_test.go| new file mode 100644 |
| index 0000000..afd41c7 |
| --- /dev/null |
| +++ b/internal/memoria/agent_edit_receipt_test.go |
| @@ -0,0 +1,81 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "github.com/google/uuid" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func TestAgentNoteConcurrentRetryWaitsForIndexAcknowledgement(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + mountAgentFixture(t, f, &p, &active) |
| + id, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "ack", Title: "before", Body: "before"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + paused := make(chan struct{}) |
| + release := make(chan struct{}) |
| + var once atomic.Bool |
| + if err := f.app.db.G.Callback().Raw().Before("gorm:raw").Register("test:index-ack", func(tx *gorm.DB) { |
| + if strings.HasPrefix(tx.Statement.SQL.String(), "UPDATE memoria_agent_note_updates SET indexed=1") && once.CompareAndSwap(false, true) { |
| + close(paused) |
| + <-release |
| + } |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + defer f.app.db.G.Callback().Raw().Remove("test:index-ack") |
| + replayAdmitted := make(chan struct{}) |
| + var calls atomic.Int32 |
| + h := http.NewServeMux() |
| + if err := f.app.mountAgentAccess(h, f.app.agentIssuer, "acme", access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| + if calls.Add(1) == 4 { |
| + close(replayAdmitted) |
| + } |
| + return p, nil |
| + })); err != nil { |
| + t.Fatal(err) |
| + } |
| + input := noteUpdateJSON(id, 1, uuid.NewString(), "after", "after") |
| + result := make(chan string, 2) |
| + run := func() { |
| + w := agentCall(h, "notes_update", input) |
| + if w.Code != 200 { |
| + t.Errorf("update %d: %s", w.Code, w.Body.String()) |
| + } |
| + result <- w.Body.String() |
| + } |
| + go run() |
| + select { |
| + case <-paused: |
| + case <-time.After(3 * time.Second): |
| + t.Fatal("index acknowledgement not reached") |
| + } |
| + go run() |
| + select { |
| + case <-replayAdmitted: |
| + case <-time.After(3 * time.Second): |
| + close(release) |
| + t.Fatal("replay not admitted") |
| + } |
| + select { |
| + case body := <-result: |
| + close(release) |
| + <-result |
| + t.Fatal("replay observed unfinished acknowledgement", body) |
| + case <-time.After(250 * time.Millisecond): |
| + } |
| + close(release) |
| + first, second := <-result, <-result |
| + if first != second || !strings.Contains(first, `"indexed":true`) { |
| + t.Fatal("acknowledgement changed", first, second) |
| + } |
| +} |
diff --git a/internal/memoria/agent_edit_recovery_test.go b/internal/memoria/agent_edit_recovery_test.go| new file mode 100644 |
| index 0000000..bdb340b |
| --- /dev/null |
| +++ b/internal/memoria/agent_edit_recovery_test.go |
| @@ -0,0 +1,158 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "github.com/google/uuid" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func TestAgentNoteUpdateIndexFailureAndRestart(t *testing.T) { |
| + for _, mode := range []string{"index", "index-receipt", "noop-index"} { |
| + t.Run(mode, func(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + h := mountAgentFixture(t, f, &p, &active) |
| + id, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "recovery", Title: "before", Body: "before body"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if mode == "index-receipt" { |
| + if err := f.app.db.G.Exec("CREATE TRIGGER fail_index BEFORE UPDATE OF indexed ON memoria_agent_note_updates BEGIN SELECT RAISE(ABORT,'injected'); END").Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + } else { |
| + f.app.store.ix.Close() |
| + } |
| + title, body := "after", "after body" |
| + if mode == "noop-index" { |
| + title, body = "before", "before body" |
| + } |
| + update := noteUpdateJSON(id, 1, uuid.NewString(), title, body) |
| + first := agentCall(h, "notes_update", update) |
| + if first.Code != 200 || !strings.Contains(first.Body.String(), `"indexed":false`) { |
| + t.Fatal("false indexing success", first.Code, first.Body.String()) |
| + } |
| + if _, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "recovery", Title: "latest", Body: "latest searchable quasar"}); err != nil && !errors.Is(err, ErrIndexLag) { |
| + t.Fatal(err) |
| + } |
| + reopened := reopenAgentNoteFixture(t, f, true) |
| + h = mountAgentFixture(t, reopened, &p, &active) |
| + if w := agentCall(h, "notes_update", update); w.Code != 200 || w.Body.String() != first.Body.String() { |
| + t.Fatal("replay changed receipt", w.Code, w.Body.String()) |
| + } |
| + if w := agentCall(h, "notes_search", `{"team":"acme","query":"quasar"}`); w.Code != 200 || !strings.Contains(w.Body.String(), "latest searchable quasar") { |
| + t.Fatal("retry restored old index", w.Code, w.Body.String()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestAgentNoteUpdateRetryFinalGuardWithoutResponse(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + h := mountAgentFixture(t, f, &p, &active) |
| + id, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "retry", Title: "before", Body: "before"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + update := noteUpdateJSON(id, 1, uuid.NewString(), "after", "after") |
| + if w := agentCall(h, "notes_update", update); w.Code != 200 { |
| + t.Fatal(w.Code) |
| + } |
| + checks := 0 |
| + state := &agentRequest{verify: func(context.Context, access.Principal, string) error { |
| + checks++ |
| + if checks == 2 { |
| + return access.Fail("unauthenticated", "Revoked.") |
| + } |
| + return nil |
| + }} |
| + ctx := context.WithValue(t.Context(), agentBoundaryKey{}, state) |
| + address, err := f.app.agentAddress(ctx, p, "acme") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := f.app.agentUpdateNote(ctx, p, []byte(update), address); err == nil || access.SafeFailure(err).Code != "unauthenticated" || checks != 2 { |
| + t.Fatal("replay skipped commit guard", err, checks) |
| + } |
| +} |
| + |
| +func TestAgentNoteUpdateRevocationWaitingForWriter(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + mountAgentFixture(t, f, &p, &active) |
| + id, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "waiting", Title: "before", Body: "before"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var revoked atomic.Bool |
| + h := http.NewServeMux() |
| + if err := f.app.mountAgentAccess(h, f.app.agentIssuer, "acme", access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| + if revoked.Load() { |
| + return access.Principal{}, access.Fail("unauthenticated", "Revoked.") |
| + } |
| + return p, nil |
| + })); err != nil { |
| + t.Fatal(err) |
| + } |
| + var path string |
| + if err := f.app.db.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path); err != nil { |
| + t.Fatal(err) |
| + } |
| + other, err := db.Open(path, f.app.logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer other.Close() |
| + held, err := other.Writer().BeginTx(t.Context(), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer held.Rollback() |
| + if _, err := held.Exec("UPDATE memoria_agent_state SET keycheck=keycheck"); err != nil { |
| + t.Fatal(err) |
| + } |
| + attempted := make(chan struct{}) |
| + var once atomic.Bool |
| + if err := f.app.db.G.Callback().Raw().Before("gorm:raw").Register("test:update-wait", func(tx *gorm.DB) { |
| + if strings.HasPrefix(tx.Statement.SQL.String(), "INSERT INTO memoria_agent_state") && once.CompareAndSwap(false, true) { |
| + close(attempted) |
| + } |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + defer f.app.db.G.Callback().Raw().Remove("test:update-wait") |
| + result := make(chan int, 1) |
| + go func() { |
| + result <- agentCall(h, "notes_update", noteUpdateJSON(id, 1, uuid.NewString(), "after", "after")).Code |
| + }() |
| + select { |
| + case <-attempted: |
| + case <-time.After(3 * time.Second): |
| + t.Fatal("no writer attempt") |
| + } |
| + revoked.Store(true) |
| + if err := held.Commit(); err != nil { |
| + t.Fatal(err) |
| + } |
| + select { |
| + case code := <-result: |
| + if code != 401 { |
| + t.Fatal(code) |
| + } |
| + case <-time.After(3 * time.Second): |
| + t.Fatal("writer remained blocked") |
| + } |
| + if title, body, err := f.app.store.Body(t.Context(), id); err != nil || title != "before" || body != "before" { |
| + t.Fatal("revoked edit committed", err) |
| + } |
| +} |
diff --git a/internal/memoria/agent_edit_test.go b/internal/memoria/agent_edit_test.go| new file mode 100644 |
| index 0000000..774d001 |
| --- /dev/null |
| +++ b/internal/memoria/agent_edit_test.go |
| @@ -0,0 +1,215 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "net/http" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "github.com/google/uuid" |
| +) |
| + |
| +func noteUpdateJSON(id int64, revision int, client, title, body string) string { |
| + b, _ := json.Marshal(agentNoteUpdateInput{Team: "acme", ID: id, ExpectedRevision: revision, ClientID: client, Title: title, Body: body}) |
| + return string(b) |
| +} |
| + |
| +func TestAgentNoteEditLifecycle(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + h := mountAgentFixture(t, f, &p, &active) |
| + // A normal browser/native paste is editable; it need not have an agent receipt. |
| + id, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "browser-title", Title: "Browser title", Body: "old nebula content"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + read := fmt.Sprintf(`{"team":"acme","id":%d}`, id) |
| + 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") { |
| + t.Fatal(w.Code, w.Body.String()) |
| + } |
| + update := noteUpdateJSON(id, 1, uuid.NewString(), "Revised title", "new quasar content") |
| + first := agentCall(h, "notes_update", update) |
| + if first.Code != 200 || !strings.Contains(first.Body.String(), `"revision":2`) || !strings.Contains(first.Body.String(), `"indexed":true`) { |
| + t.Fatal(first.Code, first.Body.String()) |
| + } |
| + title, body, err := f.app.store.Body(t.Context(), id) |
| + if err != nil || title != "Revised title" || body != "new quasar content" { |
| + t.Fatal("domain body differs", title, body, err) |
| + } |
| + if w := f.do("GET", fmt.Sprintf("/documents/%d", id), ""); w.Code != 200 || !strings.Contains(w.Body.String(), "new quasar content") { |
| + t.Fatal("page", w.Code) |
| + } |
| + if w := agentCall(h, "notes_search", `{"team":"acme","query":"quasar"}`); w.Code != 200 || !strings.Contains(w.Body.String(), "new quasar content") { |
| + t.Fatal("search", w.Code, w.Body.String()) |
| + } |
| + if w := agentCall(h, "notes_update", noteUpdateJSON(id, 1, uuid.NewString(), "stale", "stale")); w.Code != 409 { |
| + t.Fatal("stale", w.Code) |
| + } |
| + // A title-only edit through the ordinary domain writer advances revision too. |
| + if _, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "browser-title", Title: "Later rename", Body: body}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, rev, _, err := f.app.store.Meta(t.Context(), id); err != nil || rev != 3 { |
| + t.Fatal("rename revision", rev, err) |
| + } |
| + retry := agentCall(h, "notes_update", update) |
| + if retry.Code != 200 || retry.Body.String() != first.Body.String() { |
| + t.Fatal("receipt changed", retry.Code, retry.Body.String()) |
| + } |
| + if title, _, _ := f.app.store.Body(t.Context(), id); title != "Later rename" { |
| + t.Fatal("retry overwrote later title") |
| + } |
| + if w := agentCall(h, "notes_update", strings.Replace(update, "Revised title", "Changed request", 1)); w.Code != 409 { |
| + t.Fatal("changed retry", w.Code) |
| + } |
| + if err := f.app.store.Delete(t.Context(), id); err != nil { |
| + t.Fatal(err) |
| + } |
| + if w := agentCall(h, "notes_update", update); w.Code != 404 { |
| + t.Fatal("recreated deletion", w.Code) |
| + } |
| +} |
| + |
| +func TestAgentNoteEditCustodyAndConcurrency(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + h := mountAgentFixture(t, f, &p, &active) |
| + for _, source := range []string{"upload", "notion", "Docs"} { |
| + spec := IngestSpec{Source: source, Key: source, Title: "Imported", Body: "must remain unchanged"} |
| + if source == "Docs" { |
| + spec.ItemID = "sibling" |
| + spec.SiblingRevision = 1 |
| + } |
| + id, err := f.app.store.Ingest(t.Context(), spec) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, op := range []string{"notes_get", "notes_update"} { |
| + if w := agentCall(h, op, func() string { |
| + if op == "notes_get" { |
| + return fmt.Sprintf(`{"team":"acme","id":%d}`, id) |
| + } |
| + return noteUpdateJSON(id, 1, uuid.NewString(), "overwrite", "overwrite") |
| + }()); w.Code != 404 { |
| + t.Fatal(source, op, w.Code) |
| + } |
| + } |
| + } |
| + id, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "race", Title: "race", Body: "before race"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var ok, conflict atomic.Int32 |
| + var wg sync.WaitGroup |
| + for range 8 { |
| + wg.Go(func() { |
| + w := agentCall(h, "notes_update", noteUpdateJSON(id, 1, uuid.NewString(), "winner", "after race")) |
| + switch w.Code { |
| + case 200: |
| + ok.Add(1) |
| + case 409: |
| + conflict.Add(1) |
| + default: |
| + t.Errorf("race status %d: %s", w.Code, w.Body.String()) |
| + } |
| + }) |
| + } |
| + wg.Wait() |
| + if ok.Load() != 1 || conflict.Load() != 7 { |
| + t.Fatal("lost precondition", ok.Load(), conflict.Load()) |
| + } |
| + var receipts int64 |
| + f.app.db.G.Table("memoria_agent_note_updates").Count(&receipts) |
| + if receipts != 1 { |
| + t.Fatal("failed writes kept receipts", receipts) |
| + } |
| +} |
| + |
| +func TestAgentNoteEditAtomicFailures(t *testing.T) { |
| + for _, mode := range []string{"receipt", "chunk", "unlink", "reserved", "final"} { |
| + t.Run(mode, func(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + mountAgentFixture(t, f, &p, &active) |
| + id, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "atomic", Title: "before", Body: "before content"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var checks atomic.Int32 |
| + h := http.NewServeMux() |
| + err = f.app.mountAgentAccess(h, "https://connect.example.test", "acme", access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| + n := checks.Add(1) |
| + if mode == "reserved" && n >= 2 || mode == "final" && n >= 3 { |
| + return access.Principal{}, access.Fail("unauthenticated", "Revoked.") |
| + } |
| + return p, nil |
| + })) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + trigger := "" |
| + switch mode { |
| + case "receipt": |
| + trigger = "CREATE TRIGGER fail_edit BEFORE INSERT ON memoria_agent_note_updates BEGIN SELECT RAISE(ABORT,'injected'); END" |
| + case "chunk": |
| + trigger = "CREATE TRIGGER fail_edit AFTER INSERT ON chunks BEGIN SELECT RAISE(ABORT,'injected'); END" |
| + case "unlink": |
| + trigger = "CREATE TRIGGER fail_edit AFTER INSERT ON chunks BEGIN DELETE FROM home_identity_links; END" |
| + } |
| + if trigger != "" { |
| + if err := f.app.db.G.Exec(trigger).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + w := agentCall(h, "notes_update", noteUpdateJSON(id, 1, uuid.NewString(), "after", "after content")) |
| + if w.Code != 401 && w.Code != 403 && w.Code != 503 { |
| + t.Fatal(w.Code, w.Body.String()) |
| + } |
| + title, body, err := f.app.store.Body(t.Context(), id) |
| + if err != nil || title != "before" || body != "before content" { |
| + t.Fatal("partial body", err) |
| + } |
| + if _, rev, _, _ := f.app.store.Meta(t.Context(), id); rev != 1 { |
| + t.Fatal("partial revision", rev) |
| + } |
| + var n int64 |
| + f.app.db.G.Table("memoria_agent_note_updates").Count(&n) |
| + if n != 0 { |
| + t.Fatal("partial receipt") |
| + } |
| + passages, err := f.app.store.Passages(t.Context(), id) |
| + if err != nil || len(passages) != 1 || passages[0].Text != "before content" { |
| + t.Fatal("partial chunks", passages, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestAgentNoteGetStopsAfterConcurrentEdit(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + h := mountAgentFixture(t, f, &p, &active) |
| + id, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "large", Title: "large", Body: strings.Repeat("private words ", 16000)}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var changed atomic.Bool |
| + wrapped := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + h.ServeHTTP(agentStreamWriter{ResponseWriter: w, after: func() { |
| + if changed.CompareAndSwap(false, true) { |
| + if _, err := f.app.store.Ingest(context.Background(), IngestSpec{Source: "paste", Key: "large", Title: "new", Body: "new body"}); err != nil { |
| + t.Error(err) |
| + } |
| + } |
| + }}, r) |
| + }) |
| + code, body, err := memoriaLiveCall(t, wrapped, "notes_get", fmt.Sprintf(`{"team":"acme","id":%d}`, id)) |
| + if code != 200 || err == nil || len(body) > 65536 || !changed.Load() { |
| + t.Fatal("stale stream completed", code, len(body), err) |
| + } |
| +} |
diff --git a/internal/memoria/agent_index_order_test.go b/internal/memoria/agent_index_order_test.go| new file mode 100644 |
| index 0000000..e3e53f2 |
| --- /dev/null |
| +++ b/internal/memoria/agent_index_order_test.go |
| @@ -0,0 +1,80 @@ |
| +package memoria |
| + |
| +import ( |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "gorm.io/gorm" |
| +) |
| + |
| +// Reviewer-selected mutation: omit ingest's mutation lock. The old refresh |
| +// captures its title, pauses, and resumes only after a newer refresh completes. |
| +// The real lock forces the newer edit to wait and keeps its title searchable. |
| +func TestAgentNoteOlderRefreshCannotReplaceNewerIndex(t *testing.T) { |
| + f, _ := linkedAgentFixture(t) |
| + id, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "ordered", Title: "original", Body: "constant body"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + captured := make(chan struct{}) |
| + release := make(chan struct{}) |
| + var once atomic.Bool |
| + if err := f.app.db.G.Callback().Query().After("gorm:query").Register("test:index-order", func(tx *gorm.DB) { |
| + d, ok := tx.Statement.Dest.(*Document) |
| + _, inTx := tx.Statement.ConnPool.(gorm.TxCommitter) |
| + if ok && !inTx && d.ID == id && d.Revision == 2 && once.CompareAndSwap(false, true) { |
| + close(captured) |
| + <-release |
| + } |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + defer f.app.db.G.Callback().Query().Remove("test:index-order") |
| + first := make(chan error, 1) |
| + second := make(chan error, 1) |
| + go func() { |
| + _, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "ordered", Title: "oldertitle", Body: "constant body"}) |
| + first <- err |
| + }() |
| + select { |
| + case <-captured: |
| + case <-time.After(3 * time.Second): |
| + t.Fatal("old refresh was not captured") |
| + } |
| + go func() { |
| + _, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "ordered", Title: "newesttitle", Body: "constant body"}) |
| + second <- err |
| + }() |
| + completed := false |
| + select { |
| + case err := <-second: |
| + completed = true |
| + if err != nil { |
| + t.Error(err) |
| + } |
| + case <-time.After(250 * time.Millisecond): |
| + } |
| + close(release) |
| + if err := <-first; err != nil { |
| + t.Fatal(err) |
| + } |
| + if !completed { |
| + if err := <-second; err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + hits, err := f.app.store.ix.Search("newesttitle", 10) |
| + if err != nil || len(hits) != 1 { |
| + t.Fatal("older refresh replaced newer title", len(hits), err) |
| + } |
| + old, err := f.app.store.ix.Search("oldertitle", 10) |
| + if err != nil || len(old) != 0 { |
| + t.Fatal("old title survived", len(old), err) |
| + } |
| + title, _, err := f.app.store.Body(t.Context(), id) |
| + if err != nil || !strings.Contains(title, "newesttitle") { |
| + t.Fatal("wrong durable title", err) |
| + } |
| +} |
diff --git a/internal/memoria/agent_migrations/migrations/0003_note_updates.sql b/internal/memoria/agent_migrations/migrations/0003_note_updates.sql| new file mode 100644 |
| index 0000000..c5a694a |
| --- /dev/null |
| +++ b/internal/memoria/agent_migrations/migrations/0003_note_updates.sql |
| @@ -0,0 +1,8 @@ |
| +CREATE TABLE memoria_agent_note_updates ( |
| + coordinate TEXT PRIMARY KEY, |
| + content TEXT NOT NULL, |
| + document_id INTEGER NOT NULL, |
| + external_id TEXT NOT NULL, |
| + revision INTEGER NOT NULL, |
| + indexed INTEGER NOT NULL DEFAULT 0 |
| +); |
diff --git a/internal/memoria/agent_response.go b/internal/memoria/agent_response.go| index f327174..44d9eb0 100644 |
| --- a/internal/memoria/agent_response.go |
| +++ b/internal/memoria/agent_response.go |
| @@ -35,6 +35,18 @@ func (a *app) agentResponse(ctx context.Context, p access.Principal, name string |
| _, err = a.agentAddress(ctx, p, a.agentTeam) |
| return err |
| } |
| + if name == "notes_get" || name == "notes_update" { |
| + if state.noteID <= 0 || state.noteExternal == "" { |
| + return access.Fail("forbidden", "Note provenance is unavailable.") |
| + } |
| + d, err := localAgentNote(a.db.G.WithContext(ctx), state.noteID) |
| + if err != nil { |
| + return err |
| + } |
| + if d.ExternalID != state.noteExternal || name == "notes_get" && d.Revision != state.noteRevision { |
| + return access.Fail("conflict", "This note changed while reading.") |
| + } |
| + } |
| if name == "notes_create" { |
| if state.noteID <= 0 || state.noteKey == "" || state.noteExternal == "" { |
| return access.Fail("forbidden", "Note provenance is unavailable.") |
diff --git a/internal/memoria/models.go b/internal/memoria/models.go| index 60e8202..060b2b5 100644 |
| --- a/internal/memoria/models.go |
| +++ b/internal/memoria/models.go |
| @@ -46,7 +46,8 @@ type Document struct { |
| // BodyPrint is a keyed fingerprint of the body — the change |
| // detector. Keyed for the same reason ExternalID is. |
| BodyPrint string `gorm:"not null;default:''"` |
| - // Revision increments on every change to the body. **This is |
| + // Revision increments on every change to the body, and on a local paste |
| + // note's title change so full-note optimistic updates cannot lose a rename. **This is |
| // memoria's own counter and it is not what S2 is asked about.** |
| // |
| // The model said the authorization re-check was keyed on it. That is |
diff --git a/internal/memoria/store.go b/internal/memoria/store.go| index 20c1c94..ec273f8 100644 |
| --- a/internal/memoria/store.go |
| +++ b/internal/memoria/store.go |
| @@ -5,8 +5,10 @@ import ( |
| "errors" |
| "fmt" |
| "log/slog" |
| + "math" |
| "sort" |
| "strings" |
| + "sync" |
| "time" |
| "amadan.net/rastrillo/rastrillo/db" |
| @@ -25,9 +27,11 @@ import ( |
| // works in plaintext that never reaches disk; everything below it works |
| // in ciphertext. |
| type Store struct { |
| - db *db.DB |
| - sealer *seal.Sealer |
| - ix *index.Index |
| + // mutationMu orders durable changes and their postcommit index refresh. |
| + mutationMu sync.Mutex |
| + db *db.DB |
| + sealer *seal.Sealer |
| + ix *index.Index |
| // logger is optional. A dropped breaker counter is not allowed to |
| // fail a search, but it is not allowed to be silent either: a |
| // breaker that quietly stops counting reads as "no anomaly" forever, |
| @@ -294,6 +298,8 @@ func (s *Store) Ingest(ctx context.Context, spec IngestSpec) (int64, error) { |
| return s.ingest(ctx, spec, nil) |
| } |
| func (s *Store) ingest(ctx context.Context, spec IngestSpec, guard *ingestBoundary) (int64, error) { |
| + s.mutationMu.Lock() |
| + defer s.mutationMu.Unlock() |
| title := strings.TrimSpace(spec.Title) |
| body := strings.TrimSpace(spec.Body) |
| if body == "" { |
| @@ -338,6 +344,9 @@ func (s *Store) ingest(ctx context.Context, spec IngestSpec, guard *ingestBounda |
| if err != nil { |
| return 0, err |
| } |
| + if guard != nil && guard.external != "" { |
| + external = guard.external |
| + } |
| bodyPrint, err := s.sealer.Fingerprint(seal.PurposeExternal, []byte("body\x00"+body)) |
| if err != nil { |
| return 0, err |
| @@ -437,8 +446,8 @@ func (s *Store) ingest(ctx context.Context, spec IngestSpec, guard *ingestBounda |
| unchanged = true |
| return nil |
| } |
| - // Title or path only. Still no revision bump — the |
| - // passages a citation points at have not moved — and the |
| + // Title or path only. Imported content keeps its revision; |
| + // local paste notes bump it to protect full-note edits. The |
| // chunks are left alone, because the path lives on the |
| // document. The index is refreshed below, since it is |
| // the index that carries the path. |
| @@ -446,13 +455,24 @@ func (s *Store) ingest(ctx context.Context, spec IngestSpec, guard *ingestBounda |
| // with it for the same reason as above: whatever made the |
| // sibling issue a new one, S2 will be asked about the new |
| // one or about nothing. |
| + revision := existing.Revision |
| + if existing.Source == "paste" && len(existing.SiblingItemID) == 0 && existing.SiblingRevision == 0 { |
| + if revision == math.MaxInt { |
| + return errors.New("memoria: document revision exhausted") |
| + } |
| + revision++ |
| + } |
| return tx.Model(&Document{}).Where("id = ?", docID).Updates(map[string]any{ |
| + "revision": revision, |
| "sealed_title": sealedTitle, |
| "sealed_path": sealedPath, |
| "sibling_revision": spec.SiblingRevision, |
| "sibling_item_id": sealedItemID, |
| }).Error |
| } |
| + if existing.Revision == math.MaxInt { |
| + return errors.New("memoria: document revision exhausted") |
| + } |
| rechunk = true |
| if err := tx.Where("document_id = ?", docID).Delete(&Chunk{}).Error; err != nil { |
| return err |
| @@ -530,7 +550,7 @@ func (s *Store) ingest(ctx context.Context, spec IngestSpec, guard *ingestBounda |
| if err != nil { |
| return 0, err |
| } |
| - if unchanged { |
| + if unchanged && (guard == nil || !guard.refresh) { |
| return docID, nil |
| } |
| @@ -664,6 +684,8 @@ func (s *Store) indexDocument(ctx context.Context, docID int64) error { |
| // because the index lives in memory and nowhere else (see the index |
| // package for why). |
| func (s *Store) Rebuild(ctx context.Context) (int, error) { |
| + s.mutationMu.Lock() |
| + defer s.mutationMu.Unlock() |
| var ids []int64 |
| if err := s.db.G.WithContext(ctx).Model(&Document{}).Order("id").Pluck("id", &ids).Error; err != nil { |
| return 0, err |
| @@ -1141,6 +1163,8 @@ func (s *Store) Meta(ctx context.Context, id int64) (source string, revision, by |
| // passages back rather than waiting for the next boot: a delete refused |
| // for standing is not a delete that half happened. |
| func (s *Store) Delete(ctx context.Context, id int64) error { |
| + s.mutationMu.Lock() |
| + defer s.mutationMu.Unlock() |
| if err := s.allowed(ctx, memberWrite); err != nil { |
| return err |
| } |