| 1 | package memoria |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "strconv" |
| 8 | "strings" |
| 9 | |
| 10 | access "amadan.net/oficina/agent-access.git" |
| 11 | "amadan.net/oficina/memoria/internal/memoria/seal" |
| 12 | "github.com/google/uuid" |
| 13 | "gorm.io/gorm" |
| 14 | ) |
| 15 | |
| 16 | // localAgentNote deliberately excludes every imported source, including ones |
| 17 | // whose read custody belongs to Memoria. Read ownership is not edit permission. |
| 18 | func localAgentNote(tx *gorm.DB, id int64) (Document, error) { |
| 19 | var d Document |
| 20 | 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 |
| 21 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 22 | return d, access.Fail("not_found", "This local note is unavailable.") |
| 23 | } |
| 24 | return d, err |
| 25 | } |
| 26 | |
| 27 | func (a *app) agentGetNote(ctx context.Context, _ access.Principal, raw json.RawMessage, _ string) (any, error) { |
| 28 | var in struct { |
| 29 | ID int64 `json:"id"` |
| 30 | } |
| 31 | if json.Unmarshal(raw, &in) != nil || in.ID <= 0 { |
| 32 | return nil, access.Fail("invalid", "Supply a note ID.") |
| 33 | } |
| 34 | d, err := localAgentNote(a.db.G.WithContext(ctx), in.ID) |
| 35 | if err != nil { |
| 36 | return nil, err |
| 37 | } |
| 38 | title, err := a.store.sealer.Open(seal.PurposeTitle, d.SealedTitle) |
| 39 | if err != nil { |
| 40 | return nil, err |
| 41 | } |
| 42 | body, err := a.store.sealer.Open(seal.PurposeBody, d.SealedBody) |
| 43 | if err != nil { |
| 44 | return nil, err |
| 45 | } |
| 46 | if s, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest); ok { |
| 47 | s.noteID, s.noteExternal, s.noteRevision = d.ID, d.ExternalID, d.Revision |
| 48 | } |
| 49 | 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 |
| 50 | } |
| 51 | |
| 52 | type agentNoteUpdateInput struct { |
| 53 | Team string `json:"team"` |
| 54 | ID int64 `json:"id"` |
| 55 | ClientID string `json:"client_id"` |
| 56 | ExpectedRevision int `json:"expected_revision"` |
| 57 | Title string `json:"title"` |
| 58 | Body string `json:"body"` |
| 59 | } |
| 60 | |
| 61 | func (a *app) agentUpdateNote(ctx context.Context, p access.Principal, raw json.RawMessage, address string) (any, error) { |
| 62 | var in agentNoteUpdateInput |
| 63 | if json.Unmarshal(raw, &in) != nil { |
| 64 | return nil, access.Fail("invalid", "Invalid note update.") |
| 65 | } |
| 66 | uid, err := uuid.Parse(in.ClientID) |
| 67 | 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 { |
| 68 | return nil, access.Fail("invalid", "Supply a local note, revision, nonblank title/body and canonical UUID client_id.") |
| 69 | } |
| 70 | // The receipt's indexing acknowledgement settles before an identical |
| 71 | // request may replay it. Lock order is agentNotes, then Store.mutationMu. |
| 72 | a.agentNotes.Lock() |
| 73 | defer a.agentNotes.Unlock() |
| 74 | coordinate, _ := json.Marshal([]string{a.home.issuer, a.agentIssuer, p.Subject, p.Client, in.Team, "notes_update", in.ClientID}) |
| 75 | key, err := a.store.sealer.Fingerprint("agent.note.update.coordinate.v1", coordinate) |
| 76 | if err != nil { |
| 77 | return nil, err |
| 78 | } |
| 79 | payload, _ := json.Marshal(in) |
| 80 | print, err := a.store.sealer.Fingerprint("agent.note.update.content.v1", payload) |
| 81 | if err != nil { |
| 82 | return nil, err |
| 83 | } |
| 84 | // This preliminary coordinate never authorizes a write: the exact live row |
| 85 | // and its custody are checked again after reserving the writer below. |
| 86 | d, err := localAgentNote(a.db.G.WithContext(ctx), in.ID) |
| 87 | if err != nil { |
| 88 | return nil, err |
| 89 | } |
| 90 | revision, indexed, replayed := 0, false, false |
| 91 | guard := &ingestBoundary{external: d.ExternalID} |
| 92 | guard.before = func(tx *gormTx, external string) (int64, bool, error) { |
| 93 | if err := a.bindAgent(tx); err != nil { |
| 94 | return 0, false, err |
| 95 | } |
| 96 | if err := a.checkAgentWriter(ctx, tx, p, address); err != nil { |
| 97 | return 0, false, err |
| 98 | } |
| 99 | current, err := localAgentNote(tx, in.ID) |
| 100 | if err != nil { |
| 101 | return 0, false, err |
| 102 | } |
| 103 | if current.ExternalID != external { |
| 104 | return 0, false, access.Fail("not_found", "This local note changed identity.") |
| 105 | } |
| 106 | var receipt struct { |
| 107 | Content string |
| 108 | DocumentID int64 |
| 109 | ExternalID string |
| 110 | Revision int |
| 111 | Indexed bool |
| 112 | } |
| 113 | result := tx.Table("memoria_agent_note_updates").Where("coordinate=?", key).Take(&receipt) |
| 114 | if result.Error == nil { |
| 115 | if receipt.Content != print { |
| 116 | return 0, false, access.Fail("conflict", "This client_id was used with different note fields.") |
| 117 | } |
| 118 | if receipt.DocumentID != in.ID || receipt.ExternalID != external || receipt.Revision < 1 { |
| 119 | return 0, false, access.Fail("unavailable", "Note receipt requires repair.") |
| 120 | } |
| 121 | revision, indexed, replayed = receipt.Revision, receipt.Indexed, true |
| 122 | return in.ID, true, nil |
| 123 | } |
| 124 | if !errors.Is(result.Error, gorm.ErrRecordNotFound) { |
| 125 | return 0, false, result.Error |
| 126 | } |
| 127 | if current.Revision != in.ExpectedRevision { |
| 128 | return 0, false, access.Fail("conflict", "This note has changed. Read it before updating.") |
| 129 | } |
| 130 | return 0, false, nil |
| 131 | } |
| 132 | guard.after = func(tx *gormTx, id int64) error { |
| 133 | if id != in.ID { |
| 134 | return access.Fail("unavailable", "Note identity changed.") |
| 135 | } |
| 136 | if !replayed { |
| 137 | guard.refresh = true |
| 138 | current, err := localAgentNote(tx, id) |
| 139 | if err != nil { |
| 140 | return err |
| 141 | } |
| 142 | revision = current.Revision |
| 143 | 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 { |
| 144 | return err |
| 145 | } |
| 146 | } |
| 147 | return a.checkAgentWriter(ctx, tx, p, address) |
| 148 | } |
| 149 | id, err := a.store.ingestAgent(ctx, IngestSpec{Source: "paste", Title: in.Title, Body: in.Body}, guard) |
| 150 | if err != nil && !errors.Is(err, ErrIndexLag) { |
| 151 | return nil, err |
| 152 | } |
| 153 | if !replayed && err == nil { |
| 154 | // A later edit may have committed since ingest released its mutation lock. |
| 155 | // Record success only while this exact committed revision remains current. |
| 156 | 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) |
| 157 | indexed = r.Error == nil && r.RowsAffected == 1 |
| 158 | } |
| 159 | if s, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest); ok { |
| 160 | s.noteID, s.noteExternal = id, d.ExternalID |
| 161 | } |
| 162 | return map[string]any{"id": id, "revision": revision, "indexed": indexed, "url": a.origin + "/documents/" + strconv.FormatInt(id, 10)}, nil |
| 163 | } |
| 164 | |