Commit delegated note receipts with content and recheck live authority
16 files changed,
+925
−201
docs/superpowers/specs/2026-10-25-agent-retry-hardening.md+48 −0go.mod+1 −1go.sum+0 −2internal/memoria/agent_access.go+32 −61internal/memoria/agent_access_test.go+4 −4internal/memoria/agent_boundary.go+104 −0internal/memoria/agent_continuity_test.go+63 −0internal/memoria/agent_create.go+105 −0internal/memoria/agent_hardening_test.go+139 −0internal/memoria/agent_integration_test.go+1 −1internal/memoria/agent_migrations/migrations/0002_authority.sql+4 −0internal/memoria/agent_recovery_test.go+157 −0internal/memoria/agent_wait_test.go+110 −0internal/memoria/handlers.go+8 −7internal/memoria/home.go+2 −1internal/memoria/store.go+147 −124
CI passed — run details
diff --git a/docs/superpowers/specs/2026-10-25-agent-retry-hardening.md b/docs/superpowers/specs/2026-10-25-agent-retry-hardening.md| new file mode 100644 |
| index 0000000..3829793 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/2026-10-25-agent-retry-hardening.md |
| @@ -0,0 +1,48 @@ |
| +# Delegated note retry and authority hardening |
| + |
| +Status: implementation design approved by GPT-6 Astra on 2026-10-25 after |
| +reviewing the existing Memoria, Calendar and Calls adapters. Source review, |
| +CI and deployed canary verification remain separate requirements. |
| + |
| +Persist a keyed receipt-authority marker binding the content fingerprint key, |
| +exact Home issuer, delegation issuer and selected team. Initialize under the |
| +SQLite writer reservation only if receipt and attribution state is empty. Check |
| +on enablement and every mutation before receipt lookup. Existing receipt state |
| +without the marker requires explicit migration; do not bless, erase or reset it. |
| +Include both issuers in new receipt coordinates. |
| + |
| +The HTTP adapter supplies a private context callback using only the original |
| +credential's underlying verifier. Compare subject, client, grant and required |
| +team/scope. Never invoke local-DB/rate-limit middleware from inside the writer |
| +transaction. Check delegation and the existing local Home link/admission using |
| +the reserved transaction, then repeat before every successful commit, including |
| +retry exits. An absent callback fails closed on agent mutations. Reject malformed |
| +Unicode before lossy decoding. |
| + |
| +Memoria's current Ingest is an upsert. A guard alone cannot make pending receipt |
| +recovery safe: after body commit but before receipt completion, retrying that |
| +upsert can overwrite intervening edits or recreate a deleted note. The delegated |
| +creation path must commit the document/chunks and receipt document ID together. |
| +Keep public Ingest behavior; factor its transaction body into an inner function |
| +surrounded by private required agent hooks. All early successes pass the final |
| +hook. The before hook reserves the writer, validates marker and authority, claims |
| +and rereads the receipt. Completed receipts skip ingestion entirely, check the |
| +referenced document still exists, and preserve current edits/revision. Deletion |
| +returns not_found. For an incomplete receipt, refuse if source/key already exists; |
| +agent creation must never upsert even matching content. |
| + |
| +Indexing remains derived postcommit work. Preserve committed IDs on index failure. |
| +A skipped ingestion does not prove indexing succeeded. Any repair uses current |
| +stored content, never the old request body. Keep indexed false until indexing |
| +actually succeeds; no success-looking result for a deleted document. |
| + |
| +Test crash/reopen at receipt/body/index boundaries, independent concurrent |
| +requests, deletion and edits before retry, orphan source/key refusal, changed |
| +key/authority refusal, and revocation while waiting for the writer and just before |
| +commit. Adverse mutations must fail meaningful behavior tests. Source approval |
| +and checks do not claim a deployed canary. |
| + |
| +The same immutable-marker and writer-boundary pattern applies to Calendar and |
| +Calls in their own adapters. Existing direct Registry.HTTP read emission remains |
| +a separate response-revalidation gap; this write-hardening slice does not claim |
| +Docs-equivalent response guards or full suite completion. |
diff --git a/go.mod b/go.mod| index 588b7a1..5556564 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -26,7 +26,7 @@ require ( |
| require ( |
| amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060 |
| - github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 // indirect |
| + github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 |
| ) |
| require ( |
diff --git a/go.sum b/go.sum| index 3178998..2428be8 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -1,5 +1,3 @@ |
| -amadan.net/oficina/agent-access.git v0.0.0-20261024224328-3966c68144d1 h1:GknXgICfFlRNJTwXrZRdeTRS6DtQ37b3e7COQX/IxAs= |
| -amadan.net/oficina/agent-access.git v0.0.0-20261024224328-3966c68144d1/go.mod h1:Ph9PIa3VE1IEaUzZiQH6D+IQ6HThWWGfVr0ecMMgrFA= |
| amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000 h1:L07nc+dmLI7c1PBkSkbnrjOK5f8p6OBbA/yTxznxCAw= |
| amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000/go.mod h1:Ph9PIa3VE1IEaUzZiQH6D+IQ6HThWWGfVr0ecMMgrFA= |
| amadan.net/oficina/estilo.git v0.0.0-20261001093750-530cb932e768 h1:bVscoa9fH5LdLDjlyecZhrX7JzWPT0blb57MH0FIm2U= |
diff --git a/internal/memoria/agent_access.go b/internal/memoria/agent_access.go| index 8b3b01d..56c77f2 100644 |
| --- a/internal/memoria/agent_access.go |
| +++ b/internal/memoria/agent_access.go |
| @@ -2,7 +2,7 @@ package memoria |
| import ( |
| "context" |
| - "database/sql" |
| + |
| "encoding/json" |
| "errors" |
| "net/http" |
| @@ -12,7 +12,8 @@ import ( |
| "amadan.net/oficina/home/connect/linkstore" |
| "amadan.net/oficina/suite" |
| "amadan.net/rastrillo/rastrillo/migrate" |
| - "github.com/google/uuid" |
| + strictjson "github.com/go-json-experiment/json" |
| + "gorm.io/gorm" |
| ) |
| // WireAgentAccess mounts a bearer-only API outside browser sessions and CSRF. |
| @@ -28,13 +29,20 @@ func (a *app) WireAgentAccess(mux *http.ServeMux, cfg Config) error { |
| if err != nil { |
| return errors.New("memoria: invalid agent access configuration") |
| } |
| - return a.mountAgentAccess(mux, cfg.AgentTeam, v) |
| + return a.mountAgentAccess(mux, cfg.AgentIssuer, cfg.AgentTeam, v) |
| } |
| -func (a *app) mountAgentAccess(mux *http.ServeMux, team string, verifier access.Verifier) error { |
| +func (a *app) mountAgentAccess(mux *http.ServeMux, issuer, team string, verifier access.Verifier) error { |
| if _, err := migrate.Apply(context.Background(), a.db, agentSchema); err != nil { |
| return err |
| } |
| + a.agentIssuer, a.agentTeam = issuer, team |
| + if a.home == nil || issuer == "" { |
| + return errors.New("memoria: agent authority unavailable") |
| + } |
| + if err := a.db.G.Transaction(func(tx *gorm.DB) error { return a.bindAgent(tx) }); err != nil { |
| + return err |
| + } |
| registry, err := access.NewRegistry(a.agentOperations(team)...) |
| if err != nil { |
| return err |
| @@ -49,7 +57,7 @@ func (a *app) mountAgentAccess(mux *http.ServeMux, team string, verifier access. |
| } |
| return p, nil |
| }) |
| - h := registry.HTTP(checked) |
| + h := a.agentBoundary(verifier, registry.HTTP(checked)) |
| mux.Handle("/api/v1/operations", h) |
| mux.Handle("/api/v1/operations/", h) |
| return nil |
| @@ -70,6 +78,12 @@ func (a *app) agentAddress(ctx context.Context, p access.Principal, team string) |
| if err != nil || person.Label == "" || !a.Admit(person.Label) { |
| return "", access.Fail("forbidden", "Link an admitted Memoria account to Home first.") |
| } |
| + if state, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest); ok { |
| + if state.personID != 0 && state.personID != person.ID { |
| + return "", access.Fail("forbidden", "The linked identity changed.") |
| + } |
| + state.personID = person.ID |
| + } |
| return person.Label, nil |
| } |
| @@ -79,14 +93,25 @@ func (a *app) agentOperations(team string) []access.Operation { |
| var in struct { |
| Team string `json:"team"` |
| } |
| - if json.Unmarshal(raw, &in) != nil || in.Team != team || !p.Allows(team, scope) { |
| + if strictjson.Unmarshal(raw, &in) != nil { |
| + return nil, access.Fail("invalid", "Send valid Unicode JSON.") |
| + } |
| + if in.Team != team || !p.Allows(team, scope) { |
| return nil, access.Fail("forbidden", "This connection cannot access this team.") |
| } |
| address, err := a.agentAddress(ctx, p, team) |
| if err != nil { |
| return nil, err |
| } |
| - return fn(ctx, p, raw, address) |
| + out, err := fn(ctx, p, raw, address) |
| + if err != nil { |
| + var failure access.Failure |
| + if errors.As(err, &failure) { |
| + return nil, failure |
| + } |
| + return nil, access.Fail("unavailable", "Note storage or authority is unavailable.") |
| + } |
| + return out, nil |
| } |
| } |
| return []access.Operation{ |
| @@ -135,60 +160,6 @@ type agentNoteResult struct { |
| Indexed bool `json:"indexed"` |
| } |
| -func (a *app) agentCreate(ctx context.Context, p access.Principal, raw json.RawMessage, _ string) (any, error) { |
| - var in struct { |
| - Team, Title, Body string |
| - ClientID string `json:"client_id"` |
| - } |
| - if json.Unmarshal(raw, &in) != nil { |
| - return nil, access.Fail("invalid", "Invalid note.") |
| - } |
| - uid, err := uuid.Parse(in.ClientID) |
| - if err != nil || len(in.ClientID) != 36 || uid == uuid.Nil || strings.TrimSpace(in.Title) == "" || strings.TrimSpace(in.Body) == "" || len(in.Title) > 512 || len(in.Body) > 1<<20 { |
| - return nil, access.Fail("invalid", "Supply a title, a note up to 1 MiB, and a nonzero UUID client_id.") |
| - } |
| - // Fingerprint both the request and its coordinate. Neither a readable |
| - // passage nor a dictionary-testable content hash belongs in the bucket. |
| - coordinate, _ := json.Marshal([]string{p.Subject, p.Client, in.Team, uid.String()}) |
| - key, err := a.store.sealer.Fingerprint("agent.note.coordinate.v1", coordinate) |
| - if err != nil { |
| - return nil, err |
| - } |
| - content, _ := json.Marshal([]string{in.Title, in.Body}) |
| - fingerprint, err := a.store.sealer.Fingerprint("agent.note.content.v1", content) |
| - if err != nil { |
| - return nil, err |
| - } |
| - // Serialize pending retries through Ingest and receipt completion. The DB |
| - // reservation also survives a restart between these two commits. |
| - a.agentNotes.Lock() |
| - defer a.agentNotes.Unlock() |
| - if _, err = a.db.Writer().ExecContext(ctx, "INSERT INTO memoria_agent_notes(coordinate,content) VALUES(?,?) ON CONFLICT(coordinate) DO NOTHING", key, fingerprint); err != nil { |
| - return nil, err |
| - } |
| - var saved string |
| - var id sql.NullInt64 |
| - var indexed bool |
| - if err = a.db.Writer().QueryRowContext(ctx, "SELECT content,document_id,indexed FROM memoria_agent_notes WHERE coordinate=?", key).Scan(&saved, &id, &indexed); err != nil { |
| - return nil, err |
| - } |
| - if saved != fingerprint { |
| - return nil, access.Fail("conflict", "This client_id was already used with different note content.") |
| - } |
| - if id.Valid { |
| - return agentNoteResult{id.Int64, indexed}, nil |
| - } |
| - noteID, err := a.store.Ingest(ctx, IngestSpec{Source: "paste", Key: "agent-" + key, Title: in.Title, Body: in.Body}) |
| - if err != nil && !errors.Is(err, ErrIndexLag) { |
| - return nil, err |
| - } |
| - indexed = err == nil |
| - if _, err = a.db.Writer().ExecContext(context.WithoutCancel(ctx), "UPDATE memoria_agent_notes SET document_id=?,indexed=? WHERE coordinate=?", noteID, indexed, key); err != nil { |
| - return nil, err |
| - } |
| - return agentNoteResult{noteID, indexed}, nil |
| -} |
| - |
| // AgentContracts exports the same descriptors used by the live app, without |
| // opening a database or reading deployment credentials. The connection service |
| // consumes these descriptors as operator-reviewed routing configuration. |
diff --git a/internal/memoria/agent_access_test.go b/internal/memoria/agent_access_test.go| index 82a84f7..0d91bbc 100644 |
| --- a/internal/memoria/agent_access_test.go |
| +++ b/internal/memoria/agent_access_test.go |
| @@ -37,7 +37,7 @@ func linkedAgentFixture(t *testing.T) (*homeRouterFixture, access.Principal) { |
| func mountAgentFixture(t *testing.T, f *homeRouterFixture, p *access.Principal, active *bool) http.Handler { |
| t.Helper() |
| mux := http.NewServeMux() |
| - err := f.app.mountAgentAccess(mux, "acme", access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| + err := f.app.mountAgentAccess(mux, "https://connect.example.test", "acme", access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| if !*active { |
| return access.Principal{}, access.Fail("unauthenticated", "Revoked.") |
| } |
| @@ -173,8 +173,8 @@ func TestAgentNoteAdmissionScopeAndRetries(t *testing.T) { |
| t.Fatal(err) |
| } |
| w = agentCall(h, "notes_create", agentNoteInput) |
| - if w.Code != 200 || w.Body.String() != first.Body.String() { |
| - t.Fatal("completed receipt changed after deletion", w.Code) |
| + if w.Code != 404 { |
| + t.Fatal("deleted receipt succeeded", w.Code) |
| } |
| if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&count); err != nil || count != 0 { |
| t.Fatal("replay recreated deleted note", count, err) |
| @@ -302,7 +302,7 @@ func TestAgentReceiptCoordinateAndSchema(t *testing.T) { |
| if w.Code != 200 { |
| t.Fatal(w.Code, w.Body.String()) |
| } |
| - coordinate, _ := json.Marshal([]string{p.Subject, client, "acme", "a8d99147-249b-40df-a8a6-c311d425e03b"}) |
| + coordinate, _ := json.Marshal([]string{f.app.home.issuer, f.app.agentIssuer, p.Subject, client, "acme", "a8d99147-249b-40df-a8a6-c311d425e03b"}) |
| expected, err := f.app.store.sealer.Fingerprint("agent.note.coordinate.v1", coordinate) |
| if err != nil { |
| t.Fatal(err) |
diff --git a/internal/memoria/agent_boundary.go b/internal/memoria/agent_boundary.go| new file mode 100644 |
| index 0000000..e12dee9 |
| --- /dev/null |
| +++ b/internal/memoria/agent_boundary.go |
| @@ -0,0 +1,104 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "crypto/hmac" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "strings" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "gorm.io/gorm" |
| +) |
| + |
| +type agentBoundaryKey struct{} |
| +type agentRequest struct { |
| + verify func(context.Context, access.Principal, string) error |
| + personID int64 |
| +} |
| + |
| +func (a *app) agentBoundary(verifier access.Verifier, next http.Handler) http.Handler { |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + parts := strings.Fields(r.Header.Get("Authorization")) |
| + token := "" |
| + if len(parts) == 2 { |
| + token = parts[1] |
| + } |
| + state := &agentRequest{verify: func(ctx context.Context, p access.Principal, scope string) error { |
| + current, e := verifier.Verify(ctx, token) |
| + if e != nil { |
| + return e |
| + } |
| + if current.Subject != p.Subject || current.Client != p.Client || current.Grant != p.Grant || !current.Allows(a.agentTeam, scope) { |
| + return access.Fail("forbidden", "This connection is no longer authorized.") |
| + } |
| + return nil |
| + }} |
| + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), agentBoundaryKey{}, state))) |
| + }) |
| +} |
| +func (a *app) bindAgent(tx *gorm.DB) error { |
| + raw, _ := json.Marshal([]string{a.home.issuer, a.agentIssuer, a.agentTeam}) |
| + want, e := a.store.sealer.Fingerprint("agent.authority.v1", raw) |
| + 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 { |
| + return e |
| + } |
| + var got string |
| + if e = tx.Raw("SELECT keycheck FROM memoria_agent_state WHERE id=1").Scan(&got).Error; e != nil { |
| + return e |
| + } |
| + if !hmac.Equal([]byte(want), []byte(got)) { |
| + return access.Fail("unavailable", "Agent receipt authority requires an explicit migration.") |
| + } |
| + return nil |
| +} |
| +func (a *app) checkAgentWriter(ctx context.Context, tx *gorm.DB, p access.Principal, address string) error { |
| + state, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest) |
| + if !ok || state == nil || state.verify == nil || state.personID <= 0 { |
| + return access.Fail("forbidden", "Agent authority is unavailable.") |
| + } |
| + if e := state.verify(ctx, p, "notes:write"); e != nil { |
| + return e |
| + } |
| + var id int64 |
| + if e := tx.Raw("SELECT person_id FROM home_identity_links WHERE issuer=? AND subject=?", a.home.issuer, p.Subject).Row().Scan(&id); e != nil { |
| + if errors.Is(e, sql.ErrNoRows) { |
| + return access.Fail("forbidden", "The linked identity is unavailable.") |
| + } |
| + return e |
| + } |
| + if id != state.personID { |
| + return access.Fail("forbidden", "The linked identity changed.") |
| + } |
| + q, ok := tx.Statement.ConnPool.(homeIdentityQueryer) |
| + if !ok { |
| + return errors.New("memoria: transaction identity unavailable") |
| + } |
| + current, e := a.lookupHomeLocalIdentity(ctx, q, id) |
| + if e != nil && !errors.Is(e, sql.ErrNoRows) { |
| + return e |
| + } |
| + if e != nil || current != address { |
| + return access.Fail("forbidden", "This account is no longer admitted.") |
| + } |
| + return nil |
| +} |
| + |
| +// 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 |
| +} |
| + |
| +func (s *Store) ingestAgent(ctx context.Context, spec IngestSpec, guard *ingestBoundary) (int64, error) { |
| + if guard == nil || guard.before == nil || guard.after == nil { |
| + return 0, errors.New("memoria: missing ingest authority") |
| + } |
| + return s.ingest(ctx, spec, guard) |
| +} |
diff --git a/internal/memoria/agent_continuity_test.go b/internal/memoria/agent_continuity_test.go| new file mode 100644 |
| index 0000000..2ef0e7e |
| --- /dev/null |
| +++ b/internal/memoria/agent_continuity_test.go |
| @@ -0,0 +1,63 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| +) |
| + |
| +func TestAgentNoteLiveMarkerAndVerifierContinuity(t *testing.T) { |
| + for _, field := range []string{"subject", "client", "grant", "team", "scope"} { |
| + t.Run(field, func(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + var checks atomic.Int64 |
| + h := http.NewServeMux() |
| + if e := f.app.mountAgentAccess(h, "https://connect.example.test", "acme", access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| + current := p |
| + if checks.Add(1) > 1 { |
| + switch field { |
| + case "subject": |
| + current.Subject = "different" |
| + case "client": |
| + current.Client = "different" |
| + case "grant": |
| + current.Grant = "different" |
| + case "team": |
| + current.Teams = []string{"green"} |
| + case "scope": |
| + current.Scopes = []string{"notes:read"} |
| + } |
| + } |
| + return current, nil |
| + })); e != nil { |
| + t.Fatal(e) |
| + } |
| + if rec := agentCall(h, "notes_create", agentNoteInput); rec.Code != 403 { |
| + t.Fatal("changed principal accepted", field, rec.Code) |
| + } |
| + assertAgentNoteEmpty(t, f.app) |
| + }) |
| + } |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + h := mountAgentFixture(t, f, &p, &active) |
| + if rec := agentCall(h, "notes_create", agentNoteInput); rec.Code != 200 { |
| + t.Fatal(rec.Code) |
| + } |
| + if _, e := f.app.db.Writer().Exec("UPDATE memoria_agent_state SET keycheck='damaged'"); e != nil { |
| + t.Fatal(e) |
| + } |
| + for _, input := range []string{agentNoteInput, strings.Replace(agentNoteInput, "a8d99147-249b-40df-a8a6-c311d425e03b", "15bb7913-1316-4b96-bc3a-4b4cded1ded4", 1)} { |
| + if rec := agentCall(h, "notes_create", input); rec.Code != 503 { |
| + t.Fatal("live marker ignored", rec.Code) |
| + } |
| + } |
| + var n int |
| + if e := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&n); e != nil || n != 1 { |
| + t.Fatal("bad marker wrote extra note", n, e) |
| + } |
| +} |
diff --git a/internal/memoria/agent_create.go b/internal/memoria/agent_create.go| new file mode 100644 |
| index 0000000..1a11c67 |
| --- /dev/null |
| +++ b/internal/memoria/agent_create.go |
| @@ -0,0 +1,105 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "strings" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "github.com/google/uuid" |
| +) |
| + |
| +func (a *app) agentCreate(ctx context.Context, p access.Principal, raw json.RawMessage, address string) (any, error) { |
| + var in struct { |
| + Team, Title, Body string |
| + ClientID string `json:"client_id"` |
| + } |
| + if json.Unmarshal(raw, &in) != nil { |
| + return nil, access.Fail("invalid", "Invalid note.") |
| + } |
| + uid, e := uuid.Parse(in.ClientID) |
| + if e != nil || uid == uuid.Nil || uid.String() != in.ClientID || strings.TrimSpace(in.Title) == "" || strings.TrimSpace(in.Body) == "" || len(in.Title) > 512 || len(in.Body) > 1<<20 { |
| + return nil, access.Fail("invalid", "Supply a title, a note up to 1 MiB, and a canonical nonzero UUID client_id.") |
| + } |
| + coordinate, _ := json.Marshal([]string{a.home.issuer, a.agentIssuer, p.Subject, p.Client, in.Team, uid.String()}) |
| + key, e := a.store.sealer.Fingerprint("agent.note.coordinate.v1", coordinate) |
| + if e != nil { |
| + return nil, e |
| + } |
| + content, _ := json.Marshal([]string{in.Title, in.Body}) |
| + fingerprint, e := a.store.sealer.Fingerprint("agent.note.content.v1", content) |
| + if e != nil { |
| + return nil, e |
| + } |
| + a.agentNotes.Lock() |
| + defer a.agentNotes.Unlock() |
| + replayed, indexed := false, false |
| + guard := &ingestBoundary{ |
| + before: func(tx *gormTx, external string) (int64, bool, error) { |
| + if e := a.bindAgent(tx); e != nil { |
| + return 0, false, e |
| + } |
| + if e := a.checkAgentWriter(ctx, tx, p, address); e != nil { |
| + return 0, false, e |
| + } |
| + if e := tx.Exec("INSERT INTO memoria_agent_notes(coordinate,content) VALUES(?,?) ON CONFLICT(coordinate) DO NOTHING", key, fingerprint).Error; e != nil { |
| + return 0, false, e |
| + } |
| + var saved string |
| + var id sql.NullInt64 |
| + if e := tx.Raw("SELECT content,document_id,indexed FROM memoria_agent_notes WHERE coordinate=?", key).Row().Scan(&saved, &id, &indexed); e != nil { |
| + return 0, false, e |
| + } |
| + if saved != fingerprint { |
| + return 0, false, access.Fail("conflict", "This client_id was already used with different note content.") |
| + } |
| + if id.Valid { |
| + var count int64 |
| + if e := tx.Model(&Document{}).Where("id=? AND source='paste' AND external_id=?", id.Int64, external).Count(&count).Error; e != nil { |
| + return 0, false, e |
| + } |
| + if count != 1 { |
| + return 0, false, access.Fail("not_found", "This note is unavailable.") |
| + } |
| + replayed = true |
| + return id.Int64, true, nil |
| + } |
| + var count int64 |
| + if e := tx.Model(&Document{}).Where("source='paste' AND external_id=?", external).Count(&count).Error; e != nil { |
| + return 0, false, e |
| + } |
| + if count != 0 { |
| + return 0, false, access.Fail("unavailable", "The note receipt requires explicit repair.") |
| + } |
| + return 0, false, nil |
| + }, |
| + after: func(tx *gormTx, id int64) error { |
| + if !replayed { |
| + result := tx.Exec("UPDATE memoria_agent_notes SET document_id=?,indexed=0 WHERE coordinate=? AND document_id IS NULL", id, key) |
| + if result.Error != nil { |
| + return result.Error |
| + } |
| + if result.RowsAffected != 1 { |
| + return errors.New("memoria: note receipt changed") |
| + } |
| + } |
| + return a.checkAgentWriter(ctx, tx, p, address) |
| + }, |
| + } |
| + noteID, e := a.store.ingestAgent(ctx, IngestSpec{Source: "paste", Key: "agent-" + key, Title: in.Title, Body: in.Body}, guard) |
| + if e != nil && !errors.Is(e, ErrIndexLag) { |
| + return nil, e |
| + } |
| + if replayed { |
| + return agentNoteResult{noteID, indexed}, nil |
| + } |
| + indexed = e == nil |
| + if _, e = a.db.Writer().ExecContext(context.WithoutCancel(ctx), "UPDATE memoria_agent_notes SET indexed=? WHERE coordinate=? AND document_id=?", indexed, key, noteID); e != nil { |
| + // Content and durable retry identity already committed. Conservatively report |
| + // index state unknown rather than turn this into a duplicate-producing error. |
| + return agentNoteResult{noteID, false}, nil |
| + } |
| + return agentNoteResult{noteID, indexed}, nil |
| +} |
diff --git a/internal/memoria/agent_hardening_test.go b/internal/memoria/agent_hardening_test.go| new file mode 100644 |
| index 0000000..7525458 |
| --- /dev/null |
| +++ b/internal/memoria/agent_hardening_test.go |
| @@ -0,0 +1,139 @@ |
| +package memoria |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "net/http" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/memoria/internal/memoria/seal" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func agentNoteCoordinate(t *testing.T, a *app, p access.Principal) string { |
| + t.Helper() |
| + raw, _ := json.Marshal([]string{a.home.issuer, a.agentIssuer, p.Subject, p.Client, a.agentTeam, "a8d99147-249b-40df-a8a6-c311d425e03b"}) |
| + key, e := a.store.sealer.Fingerprint("agent.note.coordinate.v1", raw) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + return key |
| +} |
| +func assertAgentNoteEmpty(t *testing.T, a *app) { |
| + t.Helper() |
| + for _, table := range []string{"documents", "chunks", "memoria_agent_notes"} { |
| + var n int |
| + if e := a.db.Writer().QueryRow("SELECT COUNT(*) FROM " + table).Scan(&n); e != nil || n != 0 { |
| + t.Fatal("partial note", table, n, e) |
| + } |
| + } |
| +} |
| +func TestAgentNoteAtomicReceiptAndAuthority(t *testing.T) { |
| + for _, mode := range []string{"receipt-failure", "chunk-failure", "unlink", "revoke-reserved", "revoke-final"} { |
| + t.Run(mode, func(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + var checks atomic.Int64 |
| + mux := http.NewServeMux() |
| + if e := f.app.mountAgentAccess(mux, "https://connect.example.test", "acme", access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| + n := checks.Add(1) |
| + if mode == "revoke-reserved" && n >= 2 || mode == "revoke-final" && n >= 3 { |
| + return access.Principal{}, access.Fail("unauthenticated", "Revoked.") |
| + } |
| + return p, nil |
| + })); e != nil { |
| + t.Fatal(e) |
| + } |
| + trigger := "" |
| + switch mode { |
| + case "receipt-failure": |
| + trigger = "CREATE TRIGGER fail_receipt BEFORE UPDATE OF document_id ON memoria_agent_notes BEGIN SELECT RAISE(ABORT,'injected'); END" |
| + case "chunk-failure": |
| + trigger = "CREATE TRIGGER fail_chunk AFTER INSERT ON chunks BEGIN SELECT RAISE(ABORT,'injected'); END" |
| + case "unlink": |
| + trigger = "CREATE TRIGGER unlink_after_body AFTER INSERT ON chunks BEGIN DELETE FROM home_identity_links; END" |
| + } |
| + if trigger != "" { |
| + if _, e := f.app.db.Writer().Exec(trigger); e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + rec := agentCall(mux, "notes_create", agentNoteInput) |
| + if rec.Code != 401 && rec.Code != 403 && rec.Code != 503 { |
| + t.Fatal("authority/fault succeeded", mode, rec.Code, rec.Body.String()) |
| + } |
| + assertAgentNoteEmpty(t, f.app) |
| + }) |
| + } |
| +} |
| +func TestAgentNoteOrphanNeverUpsertsAndMarkerRefuses(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + h := mountAgentFixture(t, f, &p, &active) |
| + key := agentNoteCoordinate(t, f.app, p) |
| + id, e := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "agent-" + key, Title: "Later title", Body: "Later body must survive"}) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + rec := agentCall(h, "notes_create", agentNoteInput) |
| + if rec.Code != 503 { |
| + t.Fatal("orphan overwritten", rec.Code) |
| + } |
| + var d Document |
| + if e = f.app.db.G.First(&d, id).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + plain, e := f.app.store.sealer.Open(seal.PurposeBody, d.SealedBody) |
| + if e != nil || string(plain) != "Later body must survive" || d.Revision != 1 { |
| + t.Fatal("orphan content changed", e) |
| + } |
| + for _, kind := range []string{"issuer", "home", "team", "key"} { |
| + t.Run(kind, func(t *testing.T) { |
| + oldIssuer, oldHome, oldTeam, oldSeal := f.app.agentIssuer, f.app.home.issuer, f.app.agentTeam, f.app.store.sealer |
| + defer func() { |
| + f.app.agentIssuer = oldIssuer |
| + f.app.home.issuer = oldHome |
| + f.app.agentTeam = oldTeam |
| + f.app.store.sealer = oldSeal |
| + }() |
| + switch kind { |
| + case "issuer": |
| + f.app.agentIssuer = "https://other-connect.test" |
| + case "home": |
| + f.app.home.issuer = "https://other-home.test" |
| + case "team": |
| + f.app.agentTeam = "green" |
| + case "key": |
| + f.app.store.sealer, _ = seal.New(bytes.Repeat([]byte{9}, 32)) |
| + } |
| + if e := f.app.db.G.Transaction(func(tx *gorm.DB) error { return f.app.bindAgent(tx) }); e == nil { |
| + t.Fatal("changed authority accepted") |
| + } |
| + }) |
| + } |
| + // Even existing pending receipts cannot bootstrap a fresh marker. |
| + if _, e = f.app.db.Writer().Exec("INSERT INTO memoria_agent_notes(coordinate,content) VALUES('old','old')"); e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, e = f.app.db.Writer().Exec("DELETE FROM memoria_agent_state"); e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = f.app.db.G.Transaction(func(tx *gorm.DB) error { return f.app.bindAgent(tx) }); e == nil { |
| + t.Fatal("unbound receipts blessed") |
| + } |
| +} |
| +func TestAgentNoteRejectsLossyUnicode(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + h := mountAgentFixture(t, f, &p, &active) |
| + for _, invalid := range []string{`\ud800`, string([]byte{255})} { |
| + raw := strings.Replace(agentNoteInput, "Nebula", invalid, 1) |
| + if rec := agentCall(h, "notes_create", raw); rec.Code != 422 { |
| + t.Fatal("malformed Unicode accepted", rec.Code) |
| + } |
| + } |
| + assertAgentNoteEmpty(t, f.app) |
| +} |
diff --git a/internal/memoria/agent_integration_test.go b/internal/memoria/agent_integration_test.go| index 685f1cf..e4d8553 100644 |
| --- a/internal/memoria/agent_integration_test.go |
| +++ b/internal/memoria/agent_integration_test.go |
| @@ -75,7 +75,7 @@ func TestAgentGatewayToRealMemoria(t *testing.T) { |
| } |
| remote.Client.Transport = issuer.Client().Transport |
| mux := http.NewServeMux() |
| - if err = f.app.mountAgentAccess(mux, "acme", remote); err != nil { |
| + if err = f.app.mountAgentAccess(mux, issuer.URL, "acme", remote); err != nil { |
| t.Fatal(err) |
| } |
| appHandler = mux |
diff --git a/internal/memoria/agent_migrations/migrations/0002_authority.sql b/internal/memoria/agent_migrations/migrations/0002_authority.sql| new file mode 100644 |
| index 0000000..df62306 |
| --- /dev/null |
| +++ b/internal/memoria/agent_migrations/migrations/0002_authority.sql |
| @@ -0,0 +1,4 @@ |
| +CREATE TABLE memoria_agent_state ( |
| + id INTEGER PRIMARY KEY CHECK(id=1), |
| + keycheck TEXT NOT NULL |
| +); |
diff --git a/internal/memoria/agent_recovery_test.go b/internal/memoria/agent_recovery_test.go| new file mode 100644 |
| index 0000000..7df052c |
| --- /dev/null |
| +++ b/internal/memoria/agent_recovery_test.go |
| @@ -0,0 +1,157 @@ |
| +package memoria |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "sync" |
| + "testing" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/memoria/internal/memoria/seal" |
| + "amadan.net/rastrillo/rastrillo/db" |
| +) |
| + |
| +func reopenAgentNoteFixture(t *testing.T, f *homeRouterFixture, closeOld bool) *homeRouterFixture { |
| + t.Helper() |
| + var path string |
| + if e := f.app.db.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path); e != nil { |
| + t.Fatal(e) |
| + } |
| + if closeOld { |
| + f.app.store.ix.Close() |
| + f.app.db.Close() |
| + } |
| + d, e := db.Open(path, f.app.logger) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + cipher, e := seal.New(bytes.Repeat([]byte{6}, 32)) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + mux, a, e := App(d, homeTestOrigin, cipher, f.app.logger) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + t.Cleanup(func() { a.store.ix.Close() }) |
| + a.SetOwners([]string{"alice@example.test"}) |
| + auth, e := NewAuth(d.Writer(), AuthEnv{Origin: homeTestOrigin, InstanceKey: "isolated-test-instance-key", Mailer: f.mail, HomeEnabled: true}, f.app.logger, a) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + a.UseAuth(auth) |
| + cfg := Config{Origin: homeTestOrigin, Home: &connect.DecodedCredentials{Issuer: homeTestIssuer, ConsumerID: "memoria-test", Keys: map[string][]byte{"key": f.key.SignPub()}, DEK: bytes.Repeat([]byte{7}, 32)}} |
| + if e = a.WireHome(mux, cfg); e != nil { |
| + t.Fatal(e) |
| + } |
| + a.MountAuth(mux, homeTestOrigin) |
| + return &homeRouterFixture{a, mux, f.key, f.mail, map[string]*http.Cookie{}} |
| +} |
| +func agentNoteResultFrom(t *testing.T, code int, raw []byte) agentNoteResult { |
| + t.Helper() |
| + var out agentNoteResult |
| + if code != 200 || json.Unmarshal(raw, &out) != nil || out.ID <= 0 { |
| + t.Fatalf("note create: %d %s", code, raw) |
| + } |
| + return out |
| +} |
| +func TestAgentNotePostcommitRecoveryPreservesEditsAndDeletion(t *testing.T) { |
| + for _, stage := range []string{"index", "index-receipt"} { |
| + t.Run(stage, func(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + h := mountAgentFixture(t, f, &p, &active) |
| + if stage == "index" { |
| + f.app.store.ix.Close() |
| + } else { |
| + if _, e := f.app.db.Writer().Exec("CREATE TRIGGER fail_index_receipt BEFORE UPDATE OF indexed ON memoria_agent_notes WHEN OLD.document_id IS NOT NULL BEGIN SELECT RAISE(ABORT,'injected'); END"); e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + rec := agentCall(h, "notes_create", agentNoteInput) |
| + made := agentNoteResultFrom(t, rec.Code, rec.Body.Bytes()) |
| + if made.Indexed { |
| + t.Fatal("uncertain index reported complete") |
| + } |
| + var receiptID int64 |
| + if e := f.app.db.Writer().QueryRow("SELECT document_id FROM memoria_agent_notes").Scan(&receiptID); e != nil || receiptID != made.ID { |
| + t.Fatal("body committed without receipt", e) |
| + } |
| + key := agentNoteCoordinate(t, f.app, p) |
| + id, e := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "agent-" + key, Title: "Edited note", Body: "Later edits survive all initial retries"}) |
| + if id != made.ID || e != nil && !errors.Is(e, ErrIndexLag) { |
| + t.Fatal("browser edit", id, e) |
| + } |
| + restarted := reopenAgentNoteFixture(t, f, true) |
| + h = mountAgentFixture(t, restarted, &p, &active) |
| + rec = agentCall(h, "notes_create", agentNoteInput) |
| + got := agentNoteResultFrom(t, rec.Code, rec.Body.Bytes()) |
| + if got.ID != made.ID || got.Indexed { |
| + t.Fatal("retry changed historical index result", got) |
| + } |
| + var d Document |
| + if e = restarted.app.db.G.First(&d, made.ID).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + body, e := restarted.app.store.sealer.Open(seal.PurposeBody, d.SealedBody) |
| + if e != nil || string(body) != "Later edits survive all initial retries" || d.Revision != 2 { |
| + t.Fatal("retry overwrote later edit", d.Revision, e) |
| + } |
| + if e = restarted.app.store.Delete(t.Context(), made.ID); e != nil { |
| + t.Fatal(e) |
| + } |
| + if rec = agentCall(h, "notes_create", agentNoteInput); rec.Code != 404 { |
| + t.Fatal("deleted note retry", rec.Code) |
| + } |
| + var n int |
| + if e = restarted.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&n); e != nil || n != 0 { |
| + t.Fatal("deleted note recreated", n, e) |
| + } |
| + }) |
| + } |
| +} |
| +func TestAgentNoteIndependentInstancesFirstCreate(t *testing.T) { |
| + first, p := linkedAgentFixture(t) |
| + active := true |
| + h1 := mountAgentFixture(t, first, &p, &active) |
| + second := reopenAgentNoteFixture(t, first, false) |
| + h2 := mountAgentFixture(t, second, &p, &active) |
| + start := make(chan struct{}) |
| + results := make(chan agentNoteResult, 2) |
| + var wg sync.WaitGroup |
| + for _, h := range []http.Handler{h1, h2} { |
| + wg.Add(1) |
| + go func(h http.Handler) { |
| + defer wg.Done() |
| + <-start |
| + rec := agentCall(h, "notes_create", agentNoteInput) |
| + results <- agentNoteResultFrom(t, rec.Code, rec.Body.Bytes()) |
| + }(h) |
| + } |
| + close(start) |
| + wg.Wait() |
| + close(results) |
| + var id int64 |
| + count := 0 |
| + for result := range results { |
| + count++ |
| + if id == 0 { |
| + id = result.ID |
| + } |
| + if id != result.ID { |
| + t.Fatal("independent writers duplicated", id, result.ID) |
| + } |
| + } |
| + if count != 2 { |
| + t.Fatal("missing concurrent result") |
| + } |
| + for _, table := range []string{"documents", "memoria_agent_notes"} { |
| + var n int |
| + if e := first.app.db.Writer().QueryRow("SELECT COUNT(*) FROM " + table).Scan(&n); e != nil || n != 1 { |
| + t.Fatal("duplicate durable effect", table, n, e) |
| + } |
| + } |
| +} |
diff --git a/internal/memoria/agent_wait_test.go b/internal/memoria/agent_wait_test.go| new file mode 100644 |
| index 0000000..3fe1723 |
| --- /dev/null |
| +++ b/internal/memoria/agent_wait_test.go |
| @@ -0,0 +1,110 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func TestAgentNoteRevocationWhileWaitingForWriter(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + var revoked atomic.Bool |
| + mux := http.NewServeMux() |
| + if e := f.app.mountAgentAccess(mux, "https://connect.example.test", "acme", access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| + if revoked.Load() { |
| + return access.Principal{}, access.Fail("unauthenticated", "Revoked.") |
| + } |
| + return p, nil |
| + })); e != nil { |
| + t.Fatal(e) |
| + } |
| + // If authorization is moved after body work, this fault wins and produces503. |
| + if _, e := f.app.db.Writer().Exec("CREATE TRIGGER body_must_not_run BEFORE INSERT ON documents BEGIN SELECT RAISE(ABORT,'body attempted'); END"); e != nil { |
| + t.Fatal(e) |
| + } |
| + var path string |
| + if e := f.app.db.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path); e != nil { |
| + t.Fatal(e) |
| + } |
| + other, e := db.Open(path, f.app.logger) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer other.Close() |
| + held, e := other.Writer().BeginTx(t.Context(), nil) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer held.Rollback() |
| + if _, e = held.Exec("UPDATE memoria_agent_state SET keycheck=keycheck"); e != nil { |
| + t.Fatal(e) |
| + } |
| + // The separate SQLite connection holds the writer; WAL identity reads finish. |
| + // Observe entry into the real reservation statement after BOTH Home lookups. |
| + attempted := make(chan struct{}) |
| + var once atomic.Bool |
| + if e = f.app.db.G.Callback().Raw().Before("gorm:raw").Register("test:agent_writer", func(tx *gorm.DB) { |
| + if strings.HasPrefix(tx.Statement.SQL.String(), "INSERT INTO memoria_agent_state") && once.CompareAndSwap(false, true) { |
| + close(attempted) |
| + } |
| + }); e != nil { |
| + t.Fatal(e) |
| + } |
| + defer f.app.db.G.Callback().Raw().Remove("test:agent_writer") |
| + result := make(chan int, 1) |
| + go func() { result <- agentCall(mux, "notes_create", agentNoteInput).Code }() |
| + select { |
| + case <-attempted: |
| + case <-time.After(3 * time.Second): |
| + t.Fatal("request never reached reserved-writer statement") |
| + } |
| + select { |
| + case code := <-result: |
| + t.Fatal("writer did not block", code) |
| + case <-time.After(20 * time.Millisecond): |
| + } |
| + revoked.Store(true) |
| + if e = held.Commit(); e != nil { |
| + t.Fatal(e) |
| + } |
| + select { |
| + case code := <-result: |
| + if code != 401 { |
| + t.Fatal("body attempted before fresh delegation check", code) |
| + } |
| + case <-time.After(3 * time.Second): |
| + t.Fatal("writer did not resume") |
| + } |
| + assertAgentNoteEmpty(t, f.app) |
| +} |
| +func TestAgentNoteCompletedRetryRechecksBeforeCommit(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + h := mountAgentFixture(t, f, &p, &active) |
| + rec := agentCall(h, "notes_create", agentNoteInput) |
| + made := agentNoteResultFrom(t, rec.Code, rec.Body.Bytes()) |
| + var checks atomic.Int64 |
| + mux := http.NewServeMux() |
| + if e := f.app.mountAgentAccess(mux, f.app.agentIssuer, "acme", access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| + if checks.Add(1) >= 3 { |
| + return access.Principal{}, access.Fail("unauthenticated", "Revoked.") |
| + } |
| + return p, nil |
| + })); e != nil { |
| + t.Fatal(e) |
| + } |
| + if rec = agentCall(mux, "notes_create", agentNoteInput); rec.Code != 401 { |
| + t.Fatal("completed retry skipped final check", rec.Code) |
| + } |
| + var d Document |
| + if e := f.app.db.G.First(&d, made.ID).Error; e != nil || d.Revision != 1 { |
| + t.Fatal("retry changed content", d.Revision, e) |
| + } |
| +} |
diff --git a/internal/memoria/handlers.go b/internal/memoria/handlers.go| index 95b4634..b9f56c4 100644 |
| --- a/internal/memoria/handlers.go |
| +++ b/internal/memoria/handlers.go |
| @@ -85,13 +85,14 @@ func dropLimit() string { return strconv.Itoa(maxDropBytes>>20) + " MiB" } |
| func fileLimit() string { return strconv.Itoa(maxDropFiles) } |
| type app struct { |
| - agentNotes sync.Mutex |
| - native *nativeauth.Auth |
| - db *db.DB |
| - logger *slog.Logger |
| - store *Store |
| - auth *auth.Auth |
| - home *homeIntegration |
| + agentNotes sync.Mutex |
| + agentIssuer, agentTeam string |
| + native *nativeauth.Auth |
| + db *db.DB |
| + logger *slog.Logger |
| + store *Store |
| + auth *auth.Auth |
| + home *homeIntegration |
| // sess reads the session cookie auth mints (the same table, the same |
| // cookie name), for the pages that want to know who is signed in |
| // without requiring anybody: the error pages, the sign-in page's |
diff --git a/internal/memoria/home.go b/internal/memoria/home.go| index b7d5afc..c34c680 100644 |
| --- a/internal/memoria/home.go |
| +++ b/internal/memoria/home.go |
| @@ -14,6 +14,7 @@ import ( |
| ) |
| type homeIntegration struct { |
| + issuer string |
| bridge *connect.Bridge |
| routes *connect.Routes |
| sessions *sessions.Sessions |
| @@ -63,7 +64,7 @@ func (a *app) WireHome(mux *http.ServeMux, cfg Config) error { |
| if err != nil { |
| return errHomeIdentity |
| } |
| - a.home = &homeIntegration{bridge: b, routes: routes, sessions: sess} |
| + a.home = &homeIntegration{issuer: h.Issuer, bridge: b, routes: routes, sessions: sess} |
| a.directory = h.Directory |
| return nil |
| } |
diff --git a/internal/memoria/store.go b/internal/memoria/store.go| index 9dd7016..95ef802 100644 |
| --- a/internal/memoria/store.go |
| +++ b/internal/memoria/store.go |
| @@ -232,6 +232,9 @@ type IngestSpec struct { |
| // after it means the document IS stored and only the index is behind: the |
| // id comes back real and the error wraps ErrIndexLag. |
| 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) { |
| title := strings.TrimSpace(spec.Title) |
| body := strings.TrimSpace(spec.Body) |
| if body == "" { |
| @@ -304,141 +307,161 @@ func (s *Store) Ingest(ctx context.Context, spec IngestSpec) (int64, error) { |
| var docID int64 |
| var unchanged, rechunk bool |
| err = s.db.G.WithContext(ctx).Transaction(func(tx *gormTx) error { |
| - var existing Document |
| - res := tx.Where("source = ? AND external_id = ?", spec.Source, external).First(&existing) |
| - switch { |
| - case res.Error == nil: |
| - docID = existing.ID |
| - if existing.BodyPrint == bodyPrint { |
| - // Same key, same body — but the page may have been |
| - // RENAMED or MOVED, and neither touches the body. |
| - // |
| - // An earlier version returned here unconditionally, so a |
| - // renamed page kept its old title forever and a moved one |
| - // kept its old ancestry. Worse for a connector: an |
| - // ancestor rename does not change a descendant's own edit |
| - // time at all, so nothing upstream ever signalled it. |
| - // Found by a design review. |
| - moved, err := s.titleOrPathMoved(existing, title, pathStr) |
| - if err != nil { |
| - return err |
| - } |
| - if !moved { |
| - // Genuinely unchanged. Do NOT bump memoria's own |
| - // revision: a revision that moves without the content |
| - // moving would make every cached authorization stale |
| - // for no reason. |
| - // |
| - // **But the SIBLING's revision must still be |
| - // recorded, and this returned without it.** The two |
| - // numbers answer different questions. memoria's |
| - // counts its own edits; the sibling's is the token S2 |
| - // is asked about, and the sibling issues it for |
| - // reasons memoria cannot see — a permissions change, |
| - // a metadata edit, a re-save that touched no bytes. |
| - // |
| - // Left stale, the failure is permanent and invisible: |
| - // the sibling announces revision 8 of a body |
| - // identical to 7, memoria keeps 7, and every |
| - // subsequent query asks S2 about `(item, 7)`. The |
| - // sibling answers STALE — correctly, it has moved on |
| - // — so the passage is withheld loudly on every page, |
| - // forever, and re-polling cannot fix it because the |
| - // body never changes. "Docs has moved on from 1 |
| - // result; refetching" on every single query, for a |
| - // document the reader is entitled to. |
| + if guard != nil { |
| + id, done, e := guard.before(tx, external) |
| + if e != nil { |
| + return e |
| + } |
| + if done { |
| + docID = id |
| + unchanged = true |
| + return guard.after(tx, docID) |
| + } |
| + } |
| + apply := func() error { |
| + var existing Document |
| + res := tx.Where("source = ? AND external_id = ?", spec.Source, external).First(&existing) |
| + switch { |
| + case res.Error == nil: |
| + docID = existing.ID |
| + if existing.BodyPrint == bodyPrint { |
| + // Same key, same body — but the page may have been |
| + // RENAMED or MOVED, and neither touches the body. |
| // |
| - // Found by a review, 2026-09-07. |
| - if spec.ItemID != "" && existing.SiblingRevision != spec.SiblingRevision { |
| + // An earlier version returned here unconditionally, so a |
| + // renamed page kept its old title forever and a moved one |
| + // kept its old ancestry. Worse for a connector: an |
| + // ancestor rename does not change a descendant's own edit |
| + // time at all, so nothing upstream ever signalled it. |
| + // Found by a design review. |
| + moved, err := s.titleOrPathMoved(existing, title, pathStr) |
| + if err != nil { |
| + return err |
| + } |
| + if !moved { |
| + // Genuinely unchanged. Do NOT bump memoria's own |
| + // revision: a revision that moves without the content |
| + // moving would make every cached authorization stale |
| + // for no reason. |
| + // |
| + // **But the SIBLING's revision must still be |
| + // recorded, and this returned without it.** The two |
| + // numbers answer different questions. memoria's |
| + // counts its own edits; the sibling's is the token S2 |
| + // is asked about, and the sibling issues it for |
| + // reasons memoria cannot see — a permissions change, |
| + // a metadata edit, a re-save that touched no bytes. |
| + // |
| + // Left stale, the failure is permanent and invisible: |
| + // the sibling announces revision 8 of a body |
| + // identical to 7, memoria keeps 7, and every |
| + // subsequent query asks S2 about `(item, 7)`. The |
| + // sibling answers STALE — correctly, it has moved on |
| + // — so the passage is withheld loudly on every page, |
| + // forever, and re-polling cannot fix it because the |
| + // body never changes. "Docs has moved on from 1 |
| + // result; refetching" on every single query, for a |
| + // document the reader is entitled to. |
| + // |
| + // Found by a review, 2026-09-07. |
| + if spec.ItemID != "" && existing.SiblingRevision != spec.SiblingRevision { |
| + unchanged = true |
| + return tx.Model(&Document{}).Where("id = ?", docID).Updates(map[string]any{ |
| + "sibling_revision": spec.SiblingRevision, |
| + "sibling_item_id": sealedItemID, |
| + }).Error |
| + } |
| unchanged = true |
| - return tx.Model(&Document{}).Where("id = ?", docID).Updates(map[string]any{ |
| - "sibling_revision": spec.SiblingRevision, |
| - "sibling_item_id": sealedItemID, |
| - }).Error |
| + return nil |
| } |
| - unchanged = true |
| - return nil |
| + // Title or path only. Still no revision bump — the |
| + // passages a citation points at have not moved — and 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. |
| + // Title or path moved. The sibling's revision travels |
| + // 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. |
| + return tx.Model(&Document{}).Where("id = ?", docID).Updates(map[string]any{ |
| + "sealed_title": sealedTitle, |
| + "sealed_path": sealedPath, |
| + "sibling_revision": spec.SiblingRevision, |
| + "sibling_item_id": sealedItemID, |
| + }).Error |
| } |
| - // Title or path only. Still no revision bump — the |
| - // passages a citation points at have not moved — and 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. |
| - // Title or path moved. The sibling's revision travels |
| - // 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. |
| - return tx.Model(&Document{}).Where("id = ?", docID).Updates(map[string]any{ |
| - "sealed_title": sealedTitle, |
| - "sealed_path": sealedPath, |
| - "sibling_revision": spec.SiblingRevision, |
| + rechunk = true |
| + if err := tx.Where("document_id = ?", docID).Delete(&Chunk{}).Error; err != nil { |
| + return err |
| + } |
| + if err := tx.Model(&Document{}).Where("id = ?", docID).Updates(map[string]any{ |
| + "revision": existing.Revision + 1, |
| + "sealed_title": sealedTitle, |
| + "sealed_body": sealedBody, |
| + "sealed_path": sealedPath, |
| + "body_print": bodyPrint, |
| + "bytes": len(body), |
| + // The sibling's own revision moves with the body, and it |
| + // is the sibling's number rather than an increment of |
| + // ours: §4.1 forbids memoria inventing or ordering one. |
| "sibling_item_id": sealedItemID, |
| - }).Error |
| - } |
| - rechunk = true |
| - if err := tx.Where("document_id = ?", docID).Delete(&Chunk{}).Error; err != nil { |
| - return err |
| - } |
| - if err := tx.Model(&Document{}).Where("id = ?", docID).Updates(map[string]any{ |
| - "revision": existing.Revision + 1, |
| - "sealed_title": sealedTitle, |
| - "sealed_body": sealedBody, |
| - "sealed_path": sealedPath, |
| - "body_print": bodyPrint, |
| - "bytes": len(body), |
| - // The sibling's own revision moves with the body, and it |
| - // is the sibling's number rather than an increment of |
| - // ours: §4.1 forbids memoria inventing or ordering one. |
| - "sibling_item_id": sealedItemID, |
| - "sibling_revision": spec.SiblingRevision, |
| - }).Error; err != nil { |
| - return err |
| + "sibling_revision": spec.SiblingRevision, |
| + }).Error; err != nil { |
| + return err |
| + } |
| + default: |
| + rechunk = true |
| + d := Document{ |
| + Source: spec.Source, |
| + ExternalID: external, |
| + BodyPrint: bodyPrint, |
| + Revision: 1, |
| + SealedTitle: sealedTitle, |
| + SealedBody: sealedBody, |
| + SealedPath: sealedPath, |
| + SiblingItemID: sealedItemID, |
| + SiblingRevision: spec.SiblingRevision, |
| + Bytes: len(body), |
| + } |
| + if err := tx.Create(&d).Error; err != nil { |
| + return err |
| + } |
| + docID = d.ID |
| } |
| - default: |
| - rechunk = true |
| - d := Document{ |
| - Source: spec.Source, |
| - ExternalID: external, |
| - BodyPrint: bodyPrint, |
| - Revision: 1, |
| - SealedTitle: sealedTitle, |
| - SealedBody: sealedBody, |
| - SealedPath: sealedPath, |
| - SiblingItemID: sealedItemID, |
| - SiblingRevision: spec.SiblingRevision, |
| - Bytes: len(body), |
| + |
| + if !rechunk { |
| + return nil |
| } |
| - if err := tx.Create(&d).Error; err != nil { |
| - return err |
| + rows := make([]Chunk, 0, len(chunks)) |
| + for _, c := range chunks { |
| + // Seal the body ALONE, not Indexable(): the heading has its |
| + // own indexed column, and sealing heading+body made the |
| + // heading count twice in BM25 and appear at the front of |
| + // every snippet. Found by reading a rendered page. |
| + st, err := s.sealer.Seal(seal.PurposeChunk, []byte(c.Text)) |
| + if err != nil { |
| + return err |
| + } |
| + sh, err := s.sealer.Seal(seal.PurposeTitle, []byte(c.Heading())) |
| + if err != nil { |
| + return err |
| + } |
| + rows = append(rows, Chunk{ |
| + DocumentID: docID, |
| + Ordinal: c.Ordinal, |
| + SealedHeading: sh, |
| + SealedText: st, |
| + }) |
| } |
| - docID = d.ID |
| + return tx.Create(&rows).Error |
| } |
| - |
| - if !rechunk { |
| - return nil |
| + if e := apply(); e != nil { |
| + return e |
| } |
| - rows := make([]Chunk, 0, len(chunks)) |
| - for _, c := range chunks { |
| - // Seal the body ALONE, not Indexable(): the heading has its |
| - // own indexed column, and sealing heading+body made the |
| - // heading count twice in BM25 and appear at the front of |
| - // every snippet. Found by reading a rendered page. |
| - st, err := s.sealer.Seal(seal.PurposeChunk, []byte(c.Text)) |
| - if err != nil { |
| - return err |
| - } |
| - sh, err := s.sealer.Seal(seal.PurposeTitle, []byte(c.Heading())) |
| - if err != nil { |
| - return err |
| - } |
| - rows = append(rows, Chunk{ |
| - DocumentID: docID, |
| - Ordinal: c.Ordinal, |
| - SealedHeading: sh, |
| - SealedText: st, |
| - }) |
| + if guard != nil { |
| + return guard.after(tx, docID) |
| } |
| - return tx.Create(&rows).Error |
| + return nil |
| }) |
| if err != nil { |
| return 0, err |