Add delegated local note creation, search and revision-checked editing
Prompts: Maybe crack on with own-rolled and coalesce on a later Rastrillo update? Squashed from feat/agent-access into main.
43 files changed,
+3,557
−143
Makefile+2 −2cmd/memoria-contract/main.go+23 −0cmd/memoria/main.go+4 −0docs/superpowers/specs/2026-09-03-memoria-design.md+44 −0docs/superpowers/specs/2026-10-25-agent-response-authorization.md+13 −0docs/superpowers/specs/2026-10-25-agent-retry-hardening.md+48 −0docs/superpowers/specs/2026-11-01-agent-note-editing.md+116 −0go.mod+16 −2go.sum+44 −2internal/memoria/agent_access.go+237 −0internal/memoria/agent_access_test.go+362 −0internal/memoria/agent_boundary.go+131 −0internal/memoria/agent_continuity_test.go+63 −0internal/memoria/agent_create.go+112 −0internal/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_hardening_test.go+141 −0internal/memoria/agent_index_order_test.go+80 −0internal/memoria/agent_integration_test.go+151 −0internal/memoria/agent_migrations.go+19 −0internal/memoria/agent_migrations/migrations/0001_note_receipts.sql+6 −0internal/memoria/agent_migrations/migrations/0002_authority.sql+4 −0internal/memoria/agent_migrations/migrations/0003_note_updates.sql+8 −0internal/memoria/agent_recorder_test.go+12 −0internal/memoria/agent_recovery_test.go+157 −0internal/memoria/agent_response.go+124 −0internal/memoria/agent_response_test.go+261 −0internal/memoria/agent_team_compat_test.go+198 −0internal/memoria/agent_team_lease_test.go+105 −0internal/memoria/agent_wait_test.go+110 −0internal/memoria/config.go+6 −0internal/memoria/credits/notices.json+99 −0internal/memoria/credits_inventory_test.go+1 −1internal/memoria/custody_test.go+2 −0internal/memoria/handlers.go+9 −6internal/memoria/home.go+2 −1internal/memoria/models.go+2 −1internal/memoria/store.go+175 −128internal/memoriatest/routes_test.go+4 −0
CI passed — run details
diff --git a/Makefile b/Makefile| index 8a1ec4e..40357dc 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -1,5 +1,5 @@ |
| export GOTOOLCHAIN := go1.26.5 |
| -export GOPRIVATE := $(GOPRIVATE),amadan.net/oficina/estilo.git |
| +export GOPRIVATE := $(GOPRIVATE),amadan.net/oficina/estilo.git,amadan.net/oficina/agent-access.git |
| APP := memoria |
| @@ -129,6 +129,6 @@ credits: |
| go build -o "$$notices_tmp/notices" amadan.net/oficina/estilo.git/cmd/oficina-notices; \ |
| GOOS=linux GOARCH=arm64 CGO_ENABLED=0 "$$notices_tmp/notices" \ |
| -package ./cmd/memoria -lucide -onest \ |
| - -exclude amadan.net/oficina/estilo.git,amadan.net/oficina/home/connect,amadan.net/oficina/home/handoff,amadan.net/oficina/home/roster,amadan.net/oficina/home/teammode,amadan.net/oficina/suite,amadan.net/rastrillo/native/server \ |
| + -exclude amadan.net/oficina/agent-access.git,amadan.net/oficina/estilo.git,amadan.net/oficina/home/connect,amadan.net/oficina/home/handoff,amadan.net/oficina/home/roster,amadan.net/oficina/home/teammode,amadan.net/oficina/suite,amadan.net/rastrillo/native/server \ |
| > "$$notices_tmp/notices.json"; \ |
| mv "$$notices_tmp/notices.json" internal/memoria/credits/notices.json |
diff --git a/cmd/memoria-contract/main.go b/cmd/memoria-contract/main.go| new file mode 100644 |
| index 0000000..cb7e797 |
| --- /dev/null |
| +++ b/cmd/memoria-contract/main.go |
| @@ -0,0 +1,23 @@ |
| +// Command memoria-contract exports the live agent operation schemas as JSON. |
| +package main |
| + |
| +import ( |
| + "encoding/json" |
| + "fmt" |
| + "os" |
| + |
| + "amadan.net/oficina/memoria/internal/memoria" |
| +) |
| + |
| +func main() { |
| + ops, err := memoria.AgentContracts() |
| + if err != nil { |
| + fmt.Fprintln(os.Stderr, "Could not export operation contracts.") |
| + os.Exit(1) |
| + } |
| + encoder := json.NewEncoder(os.Stdout) |
| + encoder.SetIndent("", " ") |
| + if encoder.Encode(ops) != nil { |
| + os.Exit(1) |
| + } |
| +} |
diff --git a/cmd/memoria/main.go b/cmd/memoria/main.go| index d07033d..dcbaaed 100644 |
| --- a/cmd/memoria/main.go |
| +++ b/cmd/memoria/main.go |
| @@ -94,6 +94,10 @@ func main() { |
| logger.Error("Home sign-in unavailable", "err", err) |
| os.Exit(1) |
| } |
| + if err := app.WireAgentAccess(mux, cfg); err != nil { |
| + logger.Error("Agent access unavailable") |
| + os.Exit(1) |
| + } |
| app.MountAuth(mux, cfg.Origin) |
| // The apps of record memoria may ask about passages (§4.1). |
diff --git a/docs/superpowers/specs/2026-09-03-memoria-design.md b/docs/superpowers/specs/2026-09-03-memoria-design.md| index cfbd109..c9dd426 100644 |
| --- a/docs/superpowers/specs/2026-09-03-memoria-design.md |
| +++ b/docs/superpowers/specs/2026-09-03-memoria-design.md |
| @@ -6153,3 +6153,47 @@ returned passages, and presents the result as an AI draft with source links. |
| Unsupported devices retain search and notes. Queries, results and answers stay |
| out of logs and persisted app state; the session alone is stored in Keychain. |
| The app requires online retrieval even though answer generation is local. |
| + |
| +## Agent access (Paul's scope, 2026-10-24) |
| + |
| +The optional delegated API adds GET `/api/v1/operations` and POST |
| +`/api/v1/operations/{name}`. Both mounts use bearer authentication independently |
| +of browser sessions. Enable with `MEMORIA_AGENT_ISSUER` (trusted HTTPS connection |
| +service) and `MEMORIA_AGENT_TEAM` (this instance's team), with Home configured. |
| +Partial configuration refuses startup. No cookie or caller-supplied address can |
| +authorize an operation. Every request verifies the audience-bound credential |
| +online and resolves its opaque Home subject to an existing linked local account; |
| +outside team mode, current local admission still applies. In team mode, one |
| +request-scoped Home roster decision must remain Member through admission, the |
| +writer transaction (including completed retries), and response emission. Local |
| +allowlists do not grant team standing. Agent team configuration must match the |
| +provisioned roster binding before agent migrations or receipts are installed. |
| +Home-only browser identities remain supported, but this first delegated API |
| +requires an existing account link and never allocates an identity. Input team must equal this instance's |
| +configured team and be covered by the grant. |
| + |
| +`notes_search` requires `notes:read` and uses `SearchWithoutFacts`, with the linked |
| +local address as the sibling asker outside team mode, or the verified Home |
| +person reference in team mode. Sibling visibility is checked on every query; |
| +the operation cannot read unfiltered bodies or summaries. No model is called. |
| +`notes_create` requires `notes:write` and creates a team-shared paste note, with |
| +a nonzero UUID `client_id`. Retrying the same request returns its receipt; |
| +reusing the key with different content returns a conflict. Receipts bind the |
| +Home subject, client and team using purpose-separated keyed fingerprints; |
| +they contain no readable title, body or address. A completed receipt survives |
| +note deletion and never recreates the note on replay. Notes use the existing |
| +sealed Ingest store. The shared HTTP adapter caps requests and masks internal |
| +errors; queries, arguments, credentials and returned content stay out of logs. |
| + |
| + |
| +Independent review: GPT-5.6 Sol approved the scoped implementation and final |
| +contract-export/integration delta on 2026-10-24; the findings, fixes and mutation |
| +evidence are recorded in Memoria discussion 30 and agent-access discussion 1. |
| +`make ci` and focused agent race tests pass. This is branch implementation, not |
| +production deployment or suite-wide completion. |
| + |
| +`go run ./cmd/memoria-contract` exports the live operation descriptors without |
| +opening storage or reading deployment secrets. The connection service pins that |
| +array into its configured team/app route. Its API, CLI and MCP all reach these |
| +same checked operations. The integration fixture proves real HTTPS forwarding, |
| +local account resolution, note storage/search, retries and parent revocation. |
diff --git a/docs/superpowers/specs/2026-10-25-agent-response-authorization.md b/docs/superpowers/specs/2026-10-25-agent-response-authorization.md| new file mode 100644 |
| index 0000000..2b0364f |
| --- /dev/null |
| +++ b/docs/superpowers/specs/2026-10-25-agent-response-authorization.md |
| @@ -0,0 +1,13 @@ |
| +# Guarded app HTTP responses |
| + |
| +Status: bounded design approved by GPT-6 Astra with the explicit continuity and fail-closed requirements below; implementation/evidence review pending. Follow-up to close the legacy adapters' response-emission gap. Docs, Sheets and Slides already have app-owned guarded emission; Calendar, Calls and Memoria still use direct Registry.HTTP output. |
| + |
| +Add a separate Registry.HTTPGuarded(initial Verifier, recheck Verifier, guard ResponseGuard) entry point. Existing HTTP behavior stays for the connection gateway and compatibility. A nonnil app guard is mandatory. Initial verification may include local admission and one rate-limit charge. Rechecks use the original underlying credential verifier, never the rate-limiting wrapper. Preserve the exact bearer and Subject/Client/Grant; require the original operation's scope and input team on each check. Discovery must retain the originally disclosed team/scope set (revoked facts cannot be emitted). Registry.Call and schemas remain the single invocation path, executed exactly once. |
| + |
| +Before serializing success, bound it to MaxPayload. The app callback receives the request context, original principal, operation name, input and result, and revalidates current local identity plus permissions for every returned resource. It must not execute a write, refresh a token or replay the operation. Call original-verifier plus app guard immediately before headers and each at-most-64-KiB write with a five-second context/write deadline (shortened to caller deadline). Fail safely before headers; abort partial HTTP bodies with ErrAbortHandler and exact Content-Length. Do not silently tolerate a transport without write-deadline support. Failure bodies contain no app result. Check the elapsed context deadline after every verifier and guard callback, including callbacks that return nil. |
| + |
| +Adapter state is per request, captured before domain execution, and retains stable local person ID/address plus the returned resource set. Calendar rechecks current calendar readability and archive state; event reads/creation capture the event and calendar IDs, then re-read the live event and reject deletion or any change to its captured calendar coordinate, and free/busy must carry calendar provenance from the same range expansion that produced its spans. Calls rechecks local membership and meeting existence; invitation responses additionally require the exact originally returned invitation to remain live and its meeting unended. Memoria checks current Home/local admission, exact live chunk/document pairs, and current sibling custody for the returned revisions. Sibling checks use the existing custody interface without replaying search or recording duplicate breaker statistics. Locally owned created notes require the same current document/receipt identity. Missing or incomplete resource provenance fails closed. Memoria freezes the original sibling item/revision coordinates; current coordinates must still match, and every original candidate must receive an explicit VISIBLE/renderable custody disposition. Missing, short, or non-renderable dispositions fail closed. Never filter a selected response midway through emission. No second model call and no repeated mutation. |
| + |
| +Tests use actual HTTP transport to prove revocation/permission loss after the first chunk truncates the body, plus preheader rejection, successful-principal continuity, metadata revocation, deadline failure/timeout, single domain invocation, and one Calls rate charge. App tests distinguish loss of local identity, item permission, invitation revocation, missing/stale chunks and changed sibling visibility. Writer-boundary regression tests must remain discriminating now that a later response guard could mask a missing transaction guard. Effective mutants omit preheader versus chunk checks independently and each app's resource guard. Run full shared and affected app CI/race checks, independent source/evidence review, then exact module pins. |
| + |
| +Consumer pins shared module 4b94ff9. Design approval: GPT-6 Astra. App implementation/evidence review is recorded in the existing agent-access branch discussion. Source and tests are additive to the already reviewed create/retry authority boundary; direct completed-retry tests prevent later HTTP checks masking missing transaction checks. |
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/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/go.mod b/go.mod| index 47f334e..885ebba 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -5,8 +5,9 @@ go 1.26 |
| toolchain go1.26.5 |
| require ( |
| + amadan.net/oficina/agent-access.git v0.0.0-20261025011012-4b94ff9e8a8d |
| amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d |
| - amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2 |
| + amadan.net/oficina/home/connect v0.0.0-20261030223040-6d99b0ccc542 |
| amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d |
| amadan.net/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2 |
| amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2 |
| @@ -17,34 +18,47 @@ require ( |
| github.com/chromedp/chromedp v0.14.2 |
| github.com/go-chi/chi/v5 v5.3.2 |
| github.com/google/uuid v1.6.0 |
| + github.com/modelcontextprotocol/go-sdk v1.7.0 |
| golang.org/x/crypto v0.55.0 |
| golang.org/x/net v0.57.0 |
| + golang.org/x/oauth2 v0.35.0 |
| gorm.io/gorm v1.31.2 |
| modernc.org/sqlite v1.55.0 |
| ) |
| 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 ( |
| amadan.net/rastrillo/rastrillo/money v0.1.0 // indirect |
| github.com/BurntSushi/toml v1.6.0 // indirect |
| github.com/chromedp/sysutil v1.1.0 // indirect |
| + github.com/danieljoos/wincred v1.2.3 // indirect |
| github.com/dustin/go-humanize v1.0.1 // indirect |
| github.com/gobwas/httphead v0.1.0 // indirect |
| github.com/gobwas/pool v0.2.1 // indirect |
| github.com/gobwas/ws v1.4.0 // indirect |
| + github.com/godbus/dbus/v5 v5.2.2 // indirect |
| + github.com/gofrs/flock v0.12.1 // indirect |
| + github.com/google/jsonschema-go v0.4.3 // indirect |
| github.com/jinzhu/inflection v1.0.0 // indirect |
| github.com/jinzhu/now v1.1.5 // indirect |
| github.com/keymaildev/signin v0.1.1 // indirect |
| github.com/mattn/go-isatty v0.0.20 // indirect |
| github.com/ncruces/go-strftime v1.0.0 // indirect |
| github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect |
| + github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect |
| + github.com/segmentio/asm v1.1.3 // indirect |
| + github.com/segmentio/encoding v0.5.4 // indirect |
| + github.com/yosida95/uritemplate/v3 v3.0.2 // indirect |
| + github.com/zalando/go-keyring v0.2.8 // indirect |
| golang.org/x/mod v0.38.0 // indirect |
| + golang.org/x/sync v0.22.0 // indirect |
| golang.org/x/sys v0.47.0 // indirect |
| golang.org/x/text v0.41.0 // indirect |
| + golang.org/x/time v0.15.0 // indirect |
| gorm.io/plugin/dbresolver v1.6.2 // indirect |
| modernc.org/libc v1.74.1 // indirect |
| modernc.org/mathutil v1.7.1 // indirect |
diff --git a/go.sum b/go.sum| index dfdf288..7e14299 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -1,7 +1,9 @@ |
| +amadan.net/oficina/agent-access.git v0.0.0-20261025011012-4b94ff9e8a8d h1:bSsf1NXVhXTfLLB9J7a5v9CqzdKj8CALHZ6W3H7A/4M= |
| +amadan.net/oficina/agent-access.git v0.0.0-20261025011012-4b94ff9e8a8d/go.mod h1:Ph9PIa3VE1IEaUzZiQH6D+IQ6HThWWGfVr0ecMMgrFA= |
| amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d h1:p9+01xRdBD7s1viTINgQ6XoDD5ghOxYubD7FNcjhBTw= |
| amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw= |
| -amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2 h1:MPO8MRkk+tT2k+95fZPJ0JStnmAKUCKiVoPbfBVTk6E= |
| -amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk= |
| +amadan.net/oficina/home/connect v0.0.0-20261030223040-6d99b0ccc542 h1:b2JT0B0Y+5sTsCmVhX6cywCRdGd9s3lRP8wpqOytlbM= |
| +amadan.net/oficina/home/connect v0.0.0-20261030223040-6d99b0ccc542/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk= |
| amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d h1:8RTZkLQnyxvH2g0RMovhN/m2LN9D8qb+kBfqdBeqq+s= |
| amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k= |
| amadan.net/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2 h1:yKUTS0nOiVw7ktHpTin0bCcUDLFjmMjpW6CsHIZzZKk= |
| @@ -26,6 +28,12 @@ github.com/chromedp/chromedp v0.14.2 h1:r3b/WtwM50RsBZHMUm9fsNhhzRStTHrKdr2zmwbZ |
| github.com/chromedp/chromedp v0.14.2/go.mod h1:rHzAv60xDE7VNy/MYtTUrYreSc0ujt2O1/C3bzctYBo= |
| github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM= |
| github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8= |
| +github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ= |
| +github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs= |
| +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= |
| +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= |
| +github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= |
| +github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= |
| github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= |
| github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= |
| github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY= |
| @@ -40,6 +48,16 @@ github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og= |
| github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= |
| github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs= |
| github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc= |
| +github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ= |
| +github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c= |
| +github.com/gofrs/flock v0.12.1 h1:MTLVXXHf8ekldpJk3AKicLij9MdwOWkZ+a/jHHZby9E= |
| +github.com/gofrs/flock v0.12.1/go.mod h1:9zxTsyu5xtJ9DK+1tFZyibEV7y3uwDxPPfbxeeHCoD0= |
| +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= |
| +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= |
| +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= |
| +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= |
| +github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0= |
| +github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE= |
| github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs= |
| github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= |
| github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= |
| @@ -58,20 +76,40 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE |
| github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= |
| github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= |
| github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= |
| +github.com/modelcontextprotocol/go-sdk v1.7.0 h1:yqjY2dsbKAC0LSuWZVBMrHgiG8ukXv6NRo0JiALay44= |
| +github.com/modelcontextprotocol/go-sdk v1.7.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts= |
| github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= |
| github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= |
| github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw= |
| github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0= |
| +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= |
| +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= |
| github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= |
| github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= |
| +github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 h1:1EYB5IzjZawrrnELUi78f9fPu57HuXjmddZPjrls/28= |
| +github.com/santhosh-tekuri/jsonschema/v6 v6.0.3/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU= |
| +github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc= |
| +github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg= |
| +github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0= |
| +github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0= |
| github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0= |
| github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M= |
| +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= |
| +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= |
| +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= |
| +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= |
| +github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4= |
| +github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4= |
| +github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs= |
| +github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0= |
| golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= |
| golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= |
| golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk= |
| golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= |
| golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= |
| golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= |
| +golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ= |
| +golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= |
| golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= |
| golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= |
| golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= |
| @@ -79,8 +117,12 @@ golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= |
| golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= |
| golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= |
| golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= |
| +golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= |
| +golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= |
| golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE= |
| golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk= |
| +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= |
| +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= |
| gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo= |
| gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM= |
| gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ= |
diff --git a/internal/memoria/agent_access.go b/internal/memoria/agent_access.go| new file mode 100644 |
| index 0000000..f07a1c6 |
| --- /dev/null |
| +++ b/internal/memoria/agent_access.go |
| @@ -0,0 +1,237 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "strings" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/home/connect/linkstore" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/oficina/suite" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + strictjson "github.com/go-json-experiment/json" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// WireAgentAccess mounts a bearer-only API outside browser sessions and CSRF. |
| +// Home linking and the instance's admission policy remain mandatory. |
| +func (a *app) WireAgentAccess(mux *http.ServeMux, cfg Config) error { |
| + if cfg.AgentIssuer == "" && cfg.AgentTeam == "" { |
| + return nil |
| + } |
| + if a.home == nil || cfg.Home == nil || cfg.AgentTeam == "" || mux == nil { |
| + return errors.New("memoria: agent access requires Home and a team") |
| + } |
| + v, err := access.NewRemoteVerifier(cfg.AgentIssuer, cfg.Origin+"/api/v1", cfg.Home.Issuer) |
| + if err != nil { |
| + return errors.New("memoria: invalid agent access configuration") |
| + } |
| + return a.mountAgentAccess(mux, cfg.AgentIssuer, cfg.AgentTeam, v) |
| +} |
| + |
| +func (a *app) mountAgentAccess(mux *http.ServeMux, issuer, team string, verifier access.Verifier) error { |
| + if a.teamMode() && (a.team == nil || a.team.Bindings().Team != team) { |
| + return errors.New("memoria: agent team must match provisioned roster authority") |
| + } |
| + 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 |
| + } |
| + checked := access.VerifyFunc(func(ctx context.Context, token string) (access.Principal, error) { |
| + p, err := verifier.Verify(ctx, token) |
| + if err != nil { |
| + return access.Principal{}, err |
| + } |
| + if _, err = a.agentAddress(ctx, p, team); err != nil { |
| + return access.Principal{}, err |
| + } |
| + return p, nil |
| + }) |
| + h := a.agentBoundary(verifier, registry.HTTPGuarded(checked, verifier, a.agentResponse)) |
| + mux.Handle("/api/v1/operations", h) |
| + mux.Handle("/api/v1/operations/", h) |
| + return nil |
| +} |
| + |
| +func (a *app) agentAddress(ctx context.Context, p access.Principal, team string) (string, error) { |
| + allowed := false |
| + for _, t := range p.Teams { |
| + allowed = allowed || t == team |
| + } |
| + if !allowed || p.Client == "" || p.Grant == "" || p.Subject == "" || a.home == nil { |
| + return "", access.Fail("forbidden", "This connection cannot access this app.") |
| + } |
| + person, err := a.home.bridge.ResolveOn(ctx, a.db.G.Statement.ConnPool, p.Subject) |
| + if errors.Is(err, linkstore.ErrStorage) { |
| + return "", access.Fail("unavailable", "Account verification is temporarily unavailable.") |
| + } |
| + if err != nil || person.ID <= 0 || person.Label == "" || !a.teamMode() && !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 || state.address != person.Label) { |
| + return "", access.Fail("forbidden", "The linked identity changed.") |
| + } |
| + state.personID = person.ID |
| + state.address = person.Label |
| + } |
| + if a.teamMode() { |
| + state, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest) |
| + if !ok || state == nil || a.team == nil || a.team.Bindings().Team != team { |
| + return "", access.Fail("unavailable", "Team authority is unavailable.") |
| + } |
| + if state.standing == nil { |
| + state.standing = a.team.Access(ctx, p.Subject) |
| + } |
| + if err := a.agentStanding(ctx, p.Subject); err != nil { |
| + return "", err |
| + } |
| + } |
| + return person.Label, nil |
| +} |
| + |
| +// agentStanding reads only the request's original leased decision. In particular |
| +// the SQLite writer never refreshes membership or opens another connection. |
| +func (a *app) agentStanding(ctx context.Context, subject string) error { |
| + if !a.teamMode() { |
| + return nil |
| + } |
| + state, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest) |
| + if !ok || state == nil || state.standing == nil || state.standing.Subject() != subject { |
| + return access.Fail("unavailable", "Team authority is unavailable.") |
| + } |
| + switch state.standing.State() { |
| + case roster.Member: |
| + return nil |
| + case roster.NotMember: |
| + return access.Fail("forbidden", "This account is not a team member.") |
| + default: |
| + return access.Fail("unavailable", "Team membership cannot be verified now.") |
| + } |
| +} |
| + |
| +func (a *app) agentOperations(team string) []access.Operation { |
| + guard := func(scope string, fn func(context.Context, access.Principal, json.RawMessage, string) (any, error)) func(context.Context, access.Principal, json.RawMessage) (any, error) { |
| + return func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) { |
| + var in struct { |
| + Team string `json:"team"` |
| + } |
| + 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 |
| + } |
| + if a.teamMode() { |
| + state := ctx.Value(agentBoundaryKey{}).(*agentRequest) |
| + ctx = teammode.WithAccess(ctx, state.standing) |
| + } |
| + 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.") |
| + } |
| + if state, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest); ok { |
| + state.selected = true |
| + } |
| + return out, nil |
| + } |
| + } |
| + 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"}}}}`), |
| + Invoke: guard("notes:read", a.agentSearch)}, |
| + {Name: "notes_create", Description: "Create a team-shared note. Reuse client_id only to retry the same title and body.", Scope: "notes:write", Idempotent: true, |
| + Input: json.RawMessage(`{"type":"object","required":["team","title","body","client_id"],"additionalProperties":false,"properties":{"team":{"type":"string","minLength":1},"title":{"type":"string","minLength":1,"maxLength":512},"body":{"type":"string","minLength":1,"maxLength":1048576},"client_id":{"type":"string","minLength":36,"maxLength":36}}}`), |
| + 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) { |
| + var in struct { |
| + Query string `json:"query"` |
| + } |
| + if json.Unmarshal(raw, &in) != nil || strings.TrimSpace(in.Query) == "" || len(in.Query) > 2048 { |
| + return nil, access.Fail("invalid", "Enter a query of at most 2048 bytes.") |
| + } |
| + found, err := a.store.SearchWithoutFacts(ctx, a.agentSubject(p, address), strings.TrimSpace(in.Query), 25) |
| + if err != nil { |
| + return nil, access.Fail("unavailable", "Search is unavailable. Try again.") |
| + } |
| + if state, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest); ok { |
| + state.passages = append([]Result{}, found.Results...) |
| + } |
| + type result struct { |
| + ID int64 `json:"id"` |
| + DocumentID int64 `json:"document_id"` |
| + Title string `json:"title"` |
| + Text string `json:"text"` |
| + Source string `json:"source"` |
| + } |
| + out := make([]result, 0, len(found.Results)) |
| + for _, v := range found.Results { |
| + out = append(out, result{v.ChunkID, v.DocumentID, v.Title, strings.NewReplacer("<mark>", "", "</mark>", "").Replace(v.Snippet), v.Source}) |
| + } |
| + notices := found.Notices |
| + if notices == nil { |
| + notices = []string{} |
| + } |
| + return map[string]any{"results": out, "notices": notices}, nil |
| +} |
| + |
| +type agentNoteResult struct { |
| + ID int64 `json:"id"` |
| + Indexed bool `json:"indexed"` |
| +} |
| + |
| +// 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. |
| +func AgentContracts() ([]access.Operation, error) { |
| + a := &app{} |
| + operations := a.agentOperations("contract") |
| + scopes := make([]string, 0, len(operations)) |
| + for _, op := range operations { |
| + scopes = append(scopes, op.Scope) |
| + } |
| + registry, err := access.NewRegistry(operations...) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return registry.List(access.Principal{Subject: "contract", Teams: []string{"contract"}, Scopes: scopes}), nil |
| +} |
| + |
| +func (a *app) agentSubject(p access.Principal, address string) suite.Subject { |
| + if a.teamMode() { |
| + return suite.Subject{Kind: suite.SubjectPersonRef, Value: p.Subject} |
| + } |
| + return suite.Subject{Kind: suite.SubjectAddress, Value: address} |
| +} |
diff --git a/internal/memoria/agent_access_test.go b/internal/memoria/agent_access_test.go| new file mode 100644 |
| index 0000000..6759bd9 |
| --- /dev/null |
| +++ b/internal/memoria/agent_access_test.go |
| @@ -0,0 +1,362 @@ |
| +package memoria |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "testing" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/suite" |
| +) |
| + |
| +// The account link goes through both real browser proofs and confirmation; |
| +// a verifier alone must never provision a Memoria identity. |
| +func linkedAgentFixture(t *testing.T) (*homeRouterFixture, access.Principal) { |
| + t.Helper() |
| + f := newHomeRouterFixture(t) |
| + f.local(t) |
| + if w := f.do("GET", "/account/home", ""); w.Code != 200 { |
| + t.Fatal("link page", w.Code) |
| + } |
| + start := homeRedirect(t, f.do("POST", "/account/home", "")) |
| + if homeRedirect(t, f.exchange(t, start, "opaque-home-alice")) != "/account/home/confirm" { |
| + t.Fatal("wrong link landing") |
| + } |
| + homeRedirect(t, f.do("POST", "/account/home/confirm", "")) |
| + return f, access.Principal{Subject: "opaque-home-alice", Client: "test-agent", Grant: "grant-1", Teams: []string{"acme"}, Scopes: []string{"notes:read", "notes:write"}} |
| +} |
| + |
| +func mountAgentFixture(t *testing.T, f *homeRouterFixture, p *access.Principal, active *bool) http.Handler { |
| + t.Helper() |
| + mux := http.NewServeMux() |
| + 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.") |
| + } |
| + return *p, nil |
| + })) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return mux |
| +} |
| + |
| +func agentCall(h http.Handler, name, body string) *httptest.ResponseRecorder { |
| + r := httptest.NewRequest("POST", homeTestOrigin+"/api/v1/operations/"+name, strings.NewReader(body)) |
| + r.Header.Set("Content-Type", "application/json") |
| + r.Header.Set("Authorization", "Bearer test-token") |
| + w := httptest.NewRecorder() |
| + h.ServeHTTP(responseRecorder{w}, r) |
| + return w |
| +} |
| + |
| +const agentTitleCanary = "title_canary_7f360f42e2ab4a52b47a" |
| +const agentBodyCanary = "body_canary_358efd1ec48c4db9b01e" |
| +const agentNoteInput = `{"team":"acme","title":"Nebula agent note ` + agentTitleCanary + `","body":"nebula private note passage ` + agentBodyCanary + `","client_id":"a8d99147-249b-40df-a8a6-c311d425e03b"}` |
| + |
| +func TestAgentNoteAdmissionScopeAndRetries(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + h := mountAgentFixture(t, f, &p, &active) |
| + first := agentCall(h, "notes_create", agentNoteInput) |
| + if first.Code != 200 { |
| + t.Fatal(first.Code, first.Body.String()) |
| + } |
| + var result agentNoteResult |
| + if json.Unmarshal(first.Body.Bytes(), &result) != nil || result.ID <= 0 || !result.Indexed { |
| + t.Fatal("invalid receipt") |
| + } |
| + var wg sync.WaitGroup |
| + for range 5 { |
| + wg.Go(func() { |
| + w := agentCall(h, "notes_create", agentNoteInput) |
| + if w.Code != 200 || w.Body.String() != first.Body.String() { |
| + t.Errorf("retry: %d", w.Code) |
| + } |
| + }) |
| + } |
| + wg.Wait() |
| + if w := agentCall(h, "notes_create", strings.Replace(agentNoteInput, "private note passage", "different passage", 1)); w.Code != 409 { |
| + t.Fatal("mismatched retry", w.Code) |
| + } |
| + if w := agentCall(h, "notes_create", strings.Replace(agentNoteInput, "Nebula agent note", "Different title", 1)); w.Code != 409 { |
| + t.Fatal("title mismatch retry", w.Code) |
| + } |
| + var count int |
| + if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&count); err != nil || count != 1 { |
| + t.Fatal("duplicate created", count, err) |
| + } |
| + var sealedBody []byte |
| + if err := f.app.db.Writer().QueryRow("SELECT sealed_body FROM documents WHERE id=?", result.ID).Scan(&sealedBody); err != nil { |
| + t.Fatal(err) |
| + } |
| + if strings.Contains(string(sealedBody), "private note") { |
| + t.Fatal("body stored unsealed") |
| + } |
| + var coordinate, content string |
| + if err := f.app.db.Writer().QueryRow("SELECT coordinate,content FROM memoria_agent_notes").Scan(&coordinate, &content); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(coordinate) != 64 || len(content) != 64 || strings.Contains(coordinate+content, p.Subject) { |
| + t.Fatal("receipt is not fingerprinted") |
| + } |
| + |
| + checks := []struct { |
| + name string |
| + change func() |
| + restore func() |
| + }{ |
| + {"read-only grant", func() { p.Scopes = []string{"notes:read"} }, func() { p.Scopes = []string{"notes:read", "notes:write"} }}, |
| + {"wrong instance team", func() { p.Teams = []string{"other"} }, func() { p.Teams = []string{"acme"} }}, |
| + {"unlinked subject", func() { p.Subject = "unlinked-home-bob" }, func() { p.Subject = "opaque-home-alice" }}, |
| + {"local removal", func() { f.app.SetOwners([]string{"bob@example.test"}) }, func() { f.app.SetOwners([]string{"alice@example.test"}) }}, |
| + {"revoked grant", func() { active = false }, func() { active = true }}, |
| + } |
| + for _, tc := range checks { |
| + t.Run(tc.name, func(t *testing.T) { |
| + tc.change() |
| + defer tc.restore() |
| + var identitiesBefore, linksBefore, identitiesAfter, linksAfter int |
| + if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM memoria_home_local_identities").Scan(&identitiesBefore); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM home_identity_links").Scan(&linksBefore); err != nil { |
| + t.Fatal(err) |
| + } |
| + w := agentCall(h, "notes_create", strings.Replace(agentNoteInput, "a8d99147", "b8d99147", 1)) |
| + if w.Code != 401 && w.Code != 403 { |
| + t.Fatal(w.Code, w.Body.String()) |
| + } |
| + if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&count); err != nil || count != 1 { |
| + t.Fatal("denial changed documents", count, err) |
| + } |
| + if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM memoria_home_local_identities").Scan(&identitiesAfter); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM home_identity_links").Scan(&linksAfter); err != nil { |
| + t.Fatal(err) |
| + } |
| + if identitiesBefore != identitiesAfter || linksBefore != linksAfter { |
| + t.Fatal("denial provisioned identity or link") |
| + } |
| + }) |
| + } |
| + // A cookie may authorize the browser UI, but cannot replace a bearer. |
| + r := httptest.NewRequest("POST", homeTestOrigin+"/api/v1/operations/notes_create", strings.NewReader(agentNoteInput)) |
| + for _, cookie := range f.cookies { |
| + r.AddCookie(cookie) |
| + } |
| + w := httptest.NewRecorder() |
| + h.ServeHTTP(responseRecorder{w}, r) |
| + if w.Code != 401 { |
| + t.Fatal("cookie authorized delegated API", w.Code) |
| + } |
| + p.Teams = []string{"other"} |
| + r = httptest.NewRequest("GET", homeTestOrigin+"/api/v1/operations", nil) |
| + r.Header.Set("Authorization", "Bearer test-token") |
| + w = httptest.NewRecorder() |
| + h.ServeHTTP(responseRecorder{w}, r) |
| + if w.Code != 403 { |
| + t.Fatal("wrong instance team discovered operations", w.Code) |
| + } |
| + p.Teams = []string{"acme"} |
| + assertAgentContentSealed(t, f) |
| + if err := f.app.store.Delete(t.Context(), result.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + w = agentCall(h, "notes_create", agentNoteInput) |
| + 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) |
| + } |
| +} |
| + |
| +func TestAgentSearchRechecksSiblingPermission(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + h := mountAgentFixture(t, f, &p, &active) |
| + custody := &fixedCustody{apps: docsRoster(), give: suite.VISIBLE} |
| + f.app.store.custody = custody |
| + if w := agentCall(h, "notes_create", agentNoteInput); w.Code != 200 { |
| + t.Fatal(w.Code) |
| + } |
| + if _, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "Docs", Key: "agent-sibling", Title: "Sibling nebula", Body: "nebula sibling secret", ItemID: "docs-one", SiblingRevision: 1}); err != nil { |
| + t.Fatal(err) |
| + } |
| + input := `{"team":"acme","query":"nebula"}` |
| + w := agentCall(h, "notes_search", input) |
| + if w.Code != 200 || !strings.Contains(w.Body.String(), "sibling secret") || !strings.Contains(w.Body.String(), "private note passage") { |
| + t.Fatal("positive search", w.Code, w.Body.String()) |
| + } |
| + if custody.asker.Kind != suite.SubjectAddress || custody.asker.Value != "alice@example.test" { |
| + t.Fatal("wrong sibling asker", custody.asker) |
| + } |
| + custody.give = suite.NOT_VISIBLE |
| + w = agentCall(h, "notes_search", input) |
| + if w.Code != 200 || strings.Contains(w.Body.String(), "sibling secret") || strings.Contains(w.Body.String(), "Sibling nebula") || !strings.Contains(w.Body.String(), "private note passage") { |
| + t.Fatal("sibling refusal not enforced", w.Code, w.Body.String()) |
| + } |
| + // First query: search plus preheader and first-chunk checks. The second |
| + // query withholds the sibling before selection and needs no custody replay. |
| + if custody.calls != 4 { |
| + t.Fatal("did not ask sibling on each query", custody.calls) |
| + } |
| + // A grant for two teams still cannot select the other instance's team. |
| + p.Teams = []string{"acme", "other"} |
| + if w = agentCall(h, "notes_search", `{"team":"other","query":"nebula"}`); w.Code != 403 { |
| + t.Fatal("cross-instance team", w.Code) |
| + } |
| +} |
| + |
| +// Review-selected gate: scanning complete database files catches a newly added |
| +// plaintext column that selected-column assertions would miss. Existing local |
| +// auth sessions predate this API and contain addresses; the new content canaries |
| +// must be absent from every file, including WAL and temporary files. |
| +func assertAgentContentSealed(t *testing.T, f *homeRouterFixture) { |
| + t.Helper() |
| + var dbPath string |
| + if err := f.app.db.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&dbPath); err != nil { |
| + t.Fatal(err) |
| + } |
| + scan := func() { |
| + err := filepath.WalkDir(filepath.Dir(dbPath), func(path string, entry os.DirEntry, err error) error { |
| + if err != nil { |
| + return err |
| + } |
| + if entry.IsDir() { |
| + return nil |
| + } |
| + data, err := os.ReadFile(path) |
| + if err != nil { |
| + return err |
| + } |
| + for _, canary := range []string{agentTitleCanary, agentBodyCanary} { |
| + if bytes.Contains(data, []byte(canary)) { |
| + t.Error("readable content persisted in database files") |
| + } |
| + } |
| + return nil |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + scan() |
| + if _, err := f.app.db.Writer().Exec("PRAGMA wal_checkpoint(TRUNCATE)"); err != nil { |
| + t.Fatal(err) |
| + } |
| + scan() |
| +} |
| + |
| +func TestAgentIdentityStorageFailureIsUnavailable(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + h := mountAgentFixture(t, f, &p, &active) |
| + f.app.db.Close() |
| + if w := agentCall(h, "notes_create", agentNoteInput); w.Code != 503 { |
| + t.Fatal("storage failure misreported", w.Code) |
| + } |
| +} |
| + |
| +func TestAgentAccessConfigurationFailsClosed(t *testing.T) { |
| + f := newHomeRouterFixture(t) |
| + for _, cfg := range []Config{ |
| + {Origin: homeTestOrigin, AgentTeam: "acme"}, |
| + {Origin: homeTestOrigin, AgentIssuer: "https://connect.example.test"}, |
| + {Origin: homeTestOrigin, AgentTeam: "acme", AgentIssuer: "http://insecure.example.test"}, |
| + } { |
| + if f.app.WireAgentAccess(http.NewServeMux(), cfg) == nil { |
| + t.Fatal("accepted invalid configuration") |
| + } |
| + } |
| + mux := http.NewServeMux() |
| + if err := f.app.WireAgentAccess(mux, Config{}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if w := agentCall(mux, "notes_create", agentNoteInput); w.Code != 404 { |
| + t.Fatal("disabled endpoint mounted", w.Code) |
| + } |
| + f.app.home = nil |
| + if f.app.WireAgentAccess(mux, Config{Origin: homeTestOrigin, AgentTeam: "acme", AgentIssuer: "https://connect.example.test"}) == nil { |
| + t.Fatal("enabled without Home") |
| + } |
| +} |
| + |
| +// Review-selected 2026-10-24: bind every coordinate field and distinguish |
| +// independent clients reusing the same UUID. Deleting any field must go red. |
| +func TestAgentReceiptCoordinateAndSchema(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + h := mountAgentFixture(t, f, &p, &active) |
| + for _, client := range []string{"first-agent", "second-agent"} { |
| + p.Client = client |
| + w := agentCall(h, "notes_create", agentNoteInput) |
| + if w.Code != 200 { |
| + t.Fatal(w.Code, w.Body.String()) |
| + } |
| + 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) |
| + } |
| + var count int |
| + if err = f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM memoria_agent_notes WHERE coordinate=?", expected).Scan(&count); err != nil || count != 1 { |
| + t.Fatal("coordinate binding", count, err) |
| + } |
| + } |
| + var count int |
| + if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&count); err != nil || count != 2 { |
| + t.Fatal("independent client receipts collided", count, err) |
| + } |
| + rows, err := f.app.db.Writer().Query("SELECT name FROM pragma_table_info('memoria_agent_notes') ORDER BY cid") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer rows.Close() |
| + var columns []string |
| + for rows.Next() { |
| + var name string |
| + if err = rows.Scan(&name); err != nil { |
| + t.Fatal(err) |
| + } |
| + columns = append(columns, name) |
| + } |
| + if err = rows.Err(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !slices.Equal(columns, []string{"coordinate", "content", "document_id", "indexed"}) { |
| + t.Fatal("receipt schema retains extra data", columns) |
| + } |
| +} |
| + |
| +func TestAgentRechecksDeletedLocalIdentity(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + h := mountAgentFixture(t, f, &p, &active) |
| + if w := agentCall(h, "notes_create", agentNoteInput); w.Code != 200 { |
| + t.Fatal(w.Code) |
| + } |
| + if _, err := f.app.db.Writer().Exec("DELETE FROM memoria_home_local_identities"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if w := agentCall(h, "notes_create", strings.Replace(agentNoteInput, "a8d99147", "b8d99147", 1)); w.Code != 403 { |
| + t.Fatal("removed identity authorized", w.Code) |
| + } |
| + var count int |
| + if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM memoria_home_local_identities").Scan(&count); err != nil || count != 0 { |
| + t.Fatal("identity recreated", count, err) |
| + } |
| + if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&count); err != nil || count != 1 { |
| + t.Fatal("denial changed documents", count, err) |
| + } |
| +} |
diff --git a/internal/memoria/agent_boundary.go b/internal/memoria/agent_boundary.go| new file mode 100644 |
| index 0000000..3a3f06a |
| --- /dev/null |
| +++ b/internal/memoria/agent_boundary.go |
| @@ -0,0 +1,131 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "crypto/hmac" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "strings" |
| + "time" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/home/connect/linkstore" |
| + "amadan.net/oficina/home/teammode" |
| + "gorm.io/gorm" |
| +) |
| + |
| +type agentBoundaryKey struct{} |
| +type agentRequest struct { |
| + standing *teammode.Access |
| + verify func(context.Context, access.Principal, string) error |
| + personID int64 |
| + address string |
| + selected bool |
| + passages []Result |
| + noteID int64 |
| + noteRevision int |
| + noteKey, noteExternal string |
| +} |
| + |
| +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(&agentLeaseWriter{ResponseWriter: w, state: state, team: a.teamMode()}, 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) AND NOT EXISTS(SELECT 1 FROM memoria_agent_note_updates) 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 |
| + } |
| + person, e := a.home.bridge.ResolveOn(ctx, tx.Statement.ConnPool, p.Subject) |
| + if errors.Is(e, linkstore.ErrRefused) { |
| + return access.Fail("forbidden", "The linked identity is unavailable.") |
| + } |
| + if e != nil { |
| + return e |
| + } |
| + if person.ID != state.personID || person.Label != address || !a.teamMode() && !a.Admit(person.Label) { |
| + return access.Fail("forbidden", "The linked identity changed.") |
| + } |
| + |
| + return a.agentStanding(ctx, p.Subject) |
| +} |
| + |
| +// 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 { |
| + 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) { |
| + if guard == nil || guard.before == nil || guard.after == nil { |
| + return 0, errors.New("memoria: missing ingest authority") |
| + } |
| + return s.ingest(ctx, spec, guard) |
| +} |
| + |
| +// The shared transport's five-second I/O budget cannot outlive the roster lease. |
| +// Read only this request's captured decision; never refresh standing here. |
| +type agentLeaseWriter struct { |
| + http.ResponseWriter |
| + state *agentRequest |
| + team bool |
| +} |
| + |
| +func (w *agentLeaseWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } |
| +func (w *agentLeaseWriter) SetWriteDeadline(deadline time.Time) error { |
| + if w.team && !deadline.IsZero() { |
| + now := time.Now() |
| + if w.state == nil || w.state.standing == nil { |
| + return access.Fail("unavailable", "Team authority is unavailable.") |
| + } |
| + remaining := w.state.standing.Remaining() |
| + if remaining <= 0 { |
| + return access.Fail("unavailable", "Team membership cannot be verified now.") |
| + } |
| + if lease := now.Add(remaining); lease.Before(deadline) { |
| + deadline = lease |
| + } |
| + } |
| + return http.NewResponseController(w.ResponseWriter).SetWriteDeadline(deadline) |
| +} |
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..90a0916 |
| --- /dev/null |
| +++ b/internal/memoria/agent_create.go |
| @@ -0,0 +1,112 @@ |
| +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 |
| + var noteExternal string |
| + guard := &ingestBoundary{ |
| + before: func(tx *gormTx, external string) (int64, bool, error) { |
| + noteExternal = external |
| + 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 state, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest); ok { |
| + state.noteID = noteID |
| + state.noteKey = key |
| + state.noteExternal = noteExternal |
| + } |
| + 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_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_hardening_test.go b/internal/memoria/agent_hardening_test.go| new file mode 100644 |
| index 0000000..3464754 |
| --- /dev/null |
| +++ b/internal/memoria/agent_hardening_test.go |
| @@ -0,0 +1,141 @@ |
| +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", "binding", "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 "binding": |
| + trigger = "CREATE TRIGGER lose_binding AFTER INSERT ON chunks BEGIN UPDATE home_identity_links SET person_binding='broken'; 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_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_integration_test.go b/internal/memoria/agent_integration_test.go| new file mode 100644 |
| index 0000000..e4d8553 |
| --- /dev/null |
| +++ b/internal/memoria/agent_integration_test.go |
| @@ -0,0 +1,151 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "database/sql" |
| + "encoding/base64" |
| + "encoding/json" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/agent-access.git/client" |
| + "amadan.net/oficina/agent-access.git/grant" |
| + "github.com/modelcontextprotocol/go-sdk/mcp" |
| + "golang.org/x/oauth2" |
| +) |
| + |
| +type agentCredentials struct{ value client.Credentials } |
| + |
| +func (m *agentCredentials) Load() (client.Credentials, error) { return m.value, nil } |
| +func (m *agentCredentials) Save(v client.Credentials) error { m.value = v; return nil } |
| +func (m *agentCredentials) Delete() error { m.value = client.Credentials{}; return nil } |
| + |
| +type agentBearer struct { |
| + base http.RoundTripper |
| + token string |
| +} |
| + |
| +func (b agentBearer) RoundTrip(r *http.Request) (*http.Response, error) { |
| + copy := r.Clone(r.Context()) |
| + copy.Header.Set("Authorization", "Bearer "+b.token) |
| + return b.base.RoundTrip(copy) |
| +} |
| + |
| +// This fixture crosses real HTTPS boundaries from the shared CLI/MCP gateway |
| +// into Memoria's own operation handlers, linked identity, sealer and index. |
| +// The signed Home/browser/PKCE flow is exercised in the connection module. |
| +func TestAgentGatewayToRealMemoria(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + ctx := t.Context() |
| + var appHandler, httpHandler http.Handler |
| + appServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { appHandler.ServeHTTP(w, r) })) |
| + defer appServer.Close() |
| + issuer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { httpHandler.ServeHTTP(w, r) })) |
| + defer issuer.Close() |
| + database, err := sql.Open("sqlite", filepath.Join(t.TempDir(), "grants.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer database.Close() |
| + database.SetMaxOpenConns(1) |
| + store, err := grant.NewStore(ctx, database) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + teams := func(context.Context, string) ([]grant.Team, error) { |
| + return []grant.Team{{ID: "acme", Name: "Acme"}}, nil |
| + } |
| + grants, err := grant.NewServer(grant.Config{IdentityIssuer: homeTestIssuer, Origin: issuer.URL, Resource: issuer.URL + "/mcp", Store: store, ConsentKey: []byte(strings.Repeat("k", 32)), Clients: []grant.Client{{ID: client.ClientID, Name: "Oficina CLI", Loopback: true}}, Scopes: map[string]string{"notes:read": "Read notes", "notes:write": "Create notes"}, Subject: func(*http.Request) string { return "" }, Teams: teams, ResourceTeams: func(ctx context.Context, subject, resource string) ([]grant.Team, error) { |
| + if resource != appServer.URL+"/api/v1" { |
| + return nil, nil |
| + } |
| + return teams(ctx, subject) |
| + }, SignInPath: "/signin"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + remote, err := access.NewRemoteVerifier(issuer.URL, appServer.URL+"/api/v1", homeTestIssuer) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + remote.Client.Transport = issuer.Client().Transport |
| + mux := http.NewServeMux() |
| + if err = f.app.mountAgentAccess(mux, issuer.URL, "acme", remote); err != nil { |
| + t.Fatal(err) |
| + } |
| + appHandler = mux |
| + contracts, err := AgentContracts() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + gateway, err := access.Gateway([]access.Route{{Team: "acme", Resource: appServer.URL + "/api/v1", Operations: contracts}}, store, appServer.Client().Transport) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + serviceMux := http.NewServeMux() |
| + serviceMux.Handle("/mcp", gateway.MCP(grants)) |
| + serviceMux.Handle("/api/v1/operations", gateway.HTTP(grants)) |
| + serviceMux.Handle("/api/v1/operations/", gateway.HTTP(grants)) |
| + serviceMux.Handle("/", grants.Handler()) |
| + httpHandler = serviceMux |
| + verifier := oauth2.GenerateVerifier() |
| + challenge := sha256.Sum256([]byte(verifier)) |
| + redirect := "http://127.0.0.1:43210/callback" |
| + code, err := store.CreateCode(ctx, grant.Grant{Subject: p.Subject, ClientID: client.ClientID, Teams: p.Teams, Scopes: p.Scopes}, grant.Code{Redirect: redirect, Challenge: base64.RawURLEncoding.EncodeToString(challenge[:]), Resource: issuer.URL + "/mcp"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + token, err := store.Exchange(ctx, code, client.ClientID, redirect, issuer.URL+"/mcp", verifier) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + credentials := &agentCredentials{client.Credentials{Server: issuer.URL, Resource: issuer.URL + "/mcp", TokenEndpoint: issuer.URL + "/oauth/token", Token: &oauth2.Token{AccessToken: token.AccessToken, TokenType: "Bearer"}}} |
| + cli := client.New(credentials) |
| + cli.HTTP = issuer.Client() |
| + result, err := cli.Call(ctx, "notes_create", json.RawMessage(agentNoteInput)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + encoded, _ := json.Marshal(result) |
| + var note agentNoteResult |
| + if json.Unmarshal(encoded, ¬e) != nil || note.ID <= 0 { |
| + t.Fatal("invalid note receipt") |
| + } |
| + mcpClient := mcp.NewClient(&mcp.Implementation{Name: "Memoria integration", Version: "1"}, nil) |
| + session, err := mcpClient.Connect(ctx, &mcp.StreamableClientTransport{Endpoint: issuer.URL + "/mcp", HTTPClient: &http.Client{Transport: agentBearer{issuer.Client().Transport, token.AccessToken}}}, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer session.Close() |
| + retry, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "notes_create", Arguments: json.RawMessage(agentNoteInput)}) |
| + if err != nil || retry.IsError { |
| + t.Fatal("MCP retry", retry, err) |
| + } |
| + search, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "notes_search", Arguments: map[string]any{"team": "acme", "query": "nebula"}}) |
| + if err != nil || search.IsError { |
| + t.Fatal("MCP search", search, err) |
| + } |
| + text, _ := json.Marshal(search.Content) |
| + if !strings.Contains(string(text), agentTitleCanary) { |
| + t.Fatal("MCP could not see created note") |
| + } |
| + var count int |
| + if err = f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&count); err != nil || count != 1 { |
| + t.Fatal("transport retry duplicated note", count, err) |
| + } |
| + assertAgentContentSealed(t, f) |
| + if err = cli.Logout(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = session.CallTool(ctx, &mcp.CallToolParams{Name: "notes_create", Arguments: json.RawMessage(strings.Replace(agentNoteInput, "a8d99147", "b8d99147", 1))}); err == nil { |
| + t.Fatal("MCP survived CLI revocation") |
| + } |
| + if err = f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&count); err != nil || count != 1 { |
| + t.Fatal("revoked call wrote note", count, err) |
| + } |
| +} |
diff --git a/internal/memoria/agent_migrations.go b/internal/memoria/agent_migrations.go| new file mode 100644 |
| index 0000000..da702d6 |
| --- /dev/null |
| +++ b/internal/memoria/agent_migrations.go |
| @@ -0,0 +1,19 @@ |
| +package memoria |
| + |
| +import ( |
| + "embed" |
| + "io/fs" |
| + |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| +) |
| + |
| +//go:embed agent_migrations/migrations/*.sql |
| +var agentMigrationFS embed.FS |
| + |
| +var agentSchema = func() *migrate.Set { |
| + sub, err := fs.Sub(agentMigrationFS, "agent_migrations") |
| + if err != nil { |
| + panic(err) |
| + } |
| + return migrate.MustFromFS(sub, "memoria_agent_access") |
| +}() |
diff --git a/internal/memoria/agent_migrations/migrations/0001_note_receipts.sql b/internal/memoria/agent_migrations/migrations/0001_note_receipts.sql| new file mode 100644 |
| index 0000000..35b7441 |
| --- /dev/null |
| +++ b/internal/memoria/agent_migrations/migrations/0001_note_receipts.sql |
| @@ -0,0 +1,6 @@ |
| +CREATE TABLE memoria_agent_notes ( |
| + coordinate TEXT PRIMARY KEY, |
| + content TEXT NOT NULL, |
| + document_id INTEGER, |
| + indexed INTEGER NOT NULL DEFAULT 0 |
| +); |
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_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_recorder_test.go b/internal/memoria/agent_recorder_test.go| new file mode 100644 |
| index 0000000..f88e6c4 |
| --- /dev/null |
| +++ b/internal/memoria/agent_recorder_test.go |
| @@ -0,0 +1,12 @@ |
| +package memoria |
| + |
| +import ( |
| + "net/http/httptest" |
| + "time" |
| +) |
| + |
| +// Unit request fixtures use an in-memory transport. Real HTTP deadline and |
| +// truncation behavior is exercised separately. |
| +type responseRecorder struct{ *httptest.ResponseRecorder } |
| + |
| +func (responseRecorder) SetWriteDeadline(time.Time) error { return nil } |
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_response.go b/internal/memoria/agent_response.go| new file mode 100644 |
| index 0000000..44d9eb0 |
| --- /dev/null |
| +++ b/internal/memoria/agent_response.go |
| @@ -0,0 +1,124 @@ |
| +package memoria |
| + |
| +import ( |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/memoria/internal/memoria/seal" |
| + "amadan.net/oficina/memoria/internal/memoria/sibling" |
| + "amadan.net/oficina/suite" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func (a *app) agentResponse(ctx context.Context, p access.Principal, name string, _ json.RawMessage, result any) error { |
| + state, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest) |
| + if !ok || state.personID == 0 || name != "" && !state.selected { |
| + return access.Fail("forbidden", "Response authority is unavailable.") |
| + } |
| + address, err := a.agentAddress(ctx, p, a.agentTeam) |
| + if err != nil { |
| + return err |
| + } |
| + if name == "notes_search" { |
| + value, ok := result.(map[string]any) |
| + if !ok { |
| + return access.Fail("forbidden", "Passage provenance is unavailable.") |
| + } |
| + rows, ok := value["results"].([]any) |
| + if !ok || len(rows) != len(state.passages) { |
| + return access.Fail("forbidden", "Passage provenance is unavailable.") |
| + } |
| + if err := a.store.guardAgentPassages(ctx, a.agentSubject(p, address), state.passages); err != nil { |
| + return err |
| + } |
| + _, 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.") |
| + } |
| + var count int64 |
| + err := a.db.G.WithContext(ctx).Table("documents").Joins("JOIN memoria_agent_notes ON memoria_agent_notes.document_id=documents.id").Where("documents.id=? AND documents.source='paste' AND documents.external_id=? AND memoria_agent_notes.coordinate=?", state.noteID, state.noteExternal, state.noteKey).Count(&count).Error |
| + if err != nil { |
| + return access.Fail("unavailable", "Note storage is unavailable.") |
| + } |
| + if count != 1 { |
| + return access.Fail("not_found", "This note is unavailable.") |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// guardAgentPassages asks only about the already selected passage coordinates; |
| +// it neither searches again nor changes the original search's breaker counters. |
| +func (s *Store) guardAgentPassages(ctx context.Context, subject suite.Subject, passages []Result) error { |
| + var candidates []sibling.Candidate |
| + for _, r := range passages { |
| + if r.ChunkID <= 0 || r.DocumentID <= 0 { |
| + return access.Fail("forbidden", "Passage provenance is unavailable.") |
| + } |
| + if r.item.Item.ItemID == "" { |
| + continue |
| + } |
| + if s.custody == nil { |
| + return access.Fail("unavailable", "Passage custody is unavailable.") |
| + } |
| + sib, ok := s.custody.Sibling(r.Source) |
| + if !ok { |
| + return access.Fail("forbidden", "Passage custody is unavailable.") |
| + } |
| + candidate := r.item |
| + candidate.Sibling = sib |
| + candidates = append(candidates, candidate) |
| + } |
| + if len(candidates) > 0 { |
| + dispositions := s.custody.Rule(ctx, subject, candidates) |
| + if len(dispositions) != len(candidates) { |
| + return access.Fail("forbidden", "Passage custody is incomplete.") |
| + } |
| + for _, d := range dispositions { |
| + if !d.Renders() { |
| + return access.Fail("forbidden", "Passage access changed.") |
| + } |
| + } |
| + } |
| + // Custody may take network time; verify local provenance after it returns. |
| + for _, r := range passages { |
| + var d Document |
| + err := s.db.G.WithContext(ctx).Table("documents").Select("documents.*").Joins("JOIN chunks ON chunks.document_id=documents.id").Where("documents.id=? AND chunks.id=?", r.DocumentID, r.ChunkID).Take(&d).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return access.Fail("not_found", "This passage is unavailable.") |
| + } |
| + if err != nil { |
| + return access.Fail("unavailable", "Passage storage is unavailable.") |
| + } |
| + if d.Source != r.Source { |
| + return access.Fail("not_found", "This passage is unavailable.") |
| + } |
| + if r.item.Item.ItemID == "" { |
| + if len(d.SiblingItemID) != 0 || d.SiblingRevision != 0 { |
| + return access.Fail("forbidden", "Passage custody changed.") |
| + } |
| + continue |
| + } |
| + id, err := s.sealer.Open(seal.PurposeItemID, d.SiblingItemID) |
| + if err != nil || string(id) != r.item.Item.ItemID || d.SiblingRevision != r.item.Item.Revision { |
| + return access.Fail("forbidden", "Passage custody changed.") |
| + } |
| + } |
| + return nil |
| +} |
diff --git a/internal/memoria/agent_response_test.go b/internal/memoria/agent_response_test.go| new file mode 100644 |
| index 0000000..efdcfbe |
| --- /dev/null |
| +++ b/internal/memoria/agent_response_test.go |
| @@ -0,0 +1,261 @@ |
| +package memoria |
| + |
| +import ( |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/memoria/internal/memoria/seal" |
| + "amadan.net/oficina/memoria/internal/memoria/sibling" |
| + "amadan.net/oficina/suite" |
| + "context" |
| + "errors" |
| + "gorm.io/gorm" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| +) |
| + |
| +type responseCustody struct { |
| + *fixedCustody |
| + rule func([]sibling.Candidate) []sibling.Disposition |
| +} |
| + |
| +func (c *responseCustody) Rule(_ context.Context, _ suite.Subject, items []sibling.Candidate) []sibling.Disposition { |
| + return c.rule(items) |
| +} |
| + |
| +type agentStreamWriter struct { |
| + http.ResponseWriter |
| + after func() |
| +} |
| + |
| +func (w agentStreamWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } |
| +func (w agentStreamWriter) Write(b []byte) (int, error) { |
| + n, e := w.ResponseWriter.Write(b) |
| + w.after() |
| + return n, e |
| +} |
| +func memoriaLiveCall(t *testing.T, h http.Handler, name, raw string) (int, []byte, error) { |
| + t.Helper() |
| + server := httptest.NewServer(h) |
| + defer server.Close() |
| + req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/"+name, strings.NewReader(raw)) |
| + req.Header.Set("Authorization", "Bearer test-token") |
| + req.Header.Set("Content-Type", "application/json") |
| + resp, e := server.Client().Do(req) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer resp.Body.Close() |
| + body, e := io.ReadAll(resp.Body) |
| + return resp.StatusCode, body, e |
| +} |
| +func TestAgentResponseFrozenPassageCustody(t *testing.T) { |
| + for _, kind := range []string{"unlink", "chunk", "revision", "item-id", "new-revision-only", "missing-disposition", "withheld", "removed-source", "during-custody-chunk", "during-custody-revision", "during-custody-unlink", "storage"} { |
| + t.Run(kind, func(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + mountAgentFixture(t, f, &p, &active) |
| + var changed atomic.Bool |
| + var documentID int64 |
| + custody := &responseCustody{fixedCustody: &fixedCustody{apps: docsRoster(), give: suite.VISIBLE}} |
| + custody.rule = func(items []sibling.Candidate) []sibling.Disposition { |
| + if changed.Load() { |
| + var err error |
| + switch kind { |
| + case "during-custody-chunk": |
| + err = f.app.db.G.Exec("DELETE FROM chunks WHERE document_id=?", documentID).Error |
| + case "during-custody-revision": |
| + err = f.app.db.G.Exec("UPDATE documents SET sibling_revision=2 WHERE id=?", documentID).Error |
| + case "during-custody-unlink": |
| + err = f.app.db.G.Exec("DELETE FROM home_identity_links").Error |
| + } |
| + if err != nil { |
| + t.Error(err) |
| + } |
| + } |
| + if changed.Load() && kind == "missing-disposition" { |
| + return nil |
| + } |
| + out := make([]sibling.Disposition, len(items)) |
| + for i, item := range items { |
| + out[i] = sibling.Render |
| + if changed.Load() && (kind == "withheld" || kind == "new-revision-only" && item.Item.Revision == 1) { |
| + out[i] = sibling.Withhold |
| + } |
| + } |
| + return out |
| + } |
| + f.app.store.custody = custody |
| + id, e := f.app.store.Ingest(t.Context(), IngestSpec{Source: "Docs", Key: "response-sibling", Title: "Nebula private title", Body: "nebula private sibling text", ItemID: "frozen-item", SiblingRevision: 1}) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if kind == "storage" { |
| + if e := f.app.db.G.Callback().Query().Before("gorm:query").Register("response-storage-fault", func(tx *gorm.DB) { |
| + if changed.Load() && tx.Statement.Table == "documents" { |
| + tx.AddError(errors.New("private storage diagnostic")) |
| + } |
| + }); e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + documentID = id |
| + var checks atomic.Int32 |
| + v := access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| + if checks.Add(1) == 2 { |
| + changed.Store(true) |
| + var e error |
| + switch kind { |
| + case "unlink": |
| + e = f.app.db.G.Exec("DELETE FROM home_identity_links").Error |
| + case "chunk": |
| + e = f.app.db.G.Exec("DELETE FROM chunks WHERE document_id=?", id).Error |
| + case "revision", "new-revision-only": |
| + e = f.app.db.G.Exec("UPDATE documents SET sibling_revision=2 WHERE id=?", id).Error |
| + case "item-id": |
| + sealed, err := f.app.store.sealer.Seal(seal.PurposeItemID, []byte("different-item")) |
| + if err != nil { |
| + return access.Principal{}, err |
| + } |
| + e = f.app.db.G.Exec("UPDATE documents SET sibling_item_id=? WHERE id=?", sealed, id).Error |
| + case "removed-source": |
| + delete(custody.apps, "Docs") |
| + } |
| + if e != nil { |
| + return access.Principal{}, e |
| + } |
| + } |
| + return p, nil |
| + }) |
| + mux := http.NewServeMux() |
| + if e := f.app.mountAgentAccess(mux, f.app.agentIssuer, "acme", v); e != nil { |
| + t.Fatal(e) |
| + } |
| + if strings.HasPrefix(kind, "during-custody-") { |
| + // Exercise one complete app callback directly: the first chunk's |
| + // second check must not mask ordering within the preheader check. |
| + state := &agentRequest{} |
| + ctx := context.WithValue(t.Context(), agentBoundaryKey{}, state) |
| + registry, err := access.NewRegistry(f.app.agentOperations("acme")...) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + raw := []byte(`{"team":"acme","query":"nebula"}`) |
| + result, err := registry.Call(ctx, p, "notes_search", raw) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + changed.Store(true) |
| + if err = f.app.agentResponse(ctx, p, "notes_search", raw, result); err == nil { |
| + t.Fatal("custody-time change escaped the same response check") |
| + } |
| + return |
| + } |
| + status, body, e := memoriaLiveCall(t, mux, "notes_search", `{"team":"acme","query":"nebula"}`) |
| + if kind == "storage" && status != 503 { |
| + t.Fatalf("storage failure masked: %d %s", status, body) |
| + } |
| + if e != nil || status == 200 || strings.Contains(string(body), "private") { |
| + t.Fatalf("%d %s %v", status, body, e) |
| + } |
| + }) |
| + } |
| +} |
| +func TestAgentResponseStreamRechecksLivePassage(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + h := mountAgentFixture(t, f, &p, &active) |
| + id, e := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "large-title", Title: strings.Repeat("private title ", 10000), Body: "nebula passage"}) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + var writes atomic.Int32 |
| + wrapped := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + h.ServeHTTP(agentStreamWriter{w, func() { |
| + if writes.Add(1) == 1 { |
| + if e := f.app.db.G.Exec("DELETE FROM chunks WHERE document_id=?", id).Error; e != nil { |
| + t.Error(e) |
| + } |
| + } |
| + }}, r) |
| + }) |
| + status, body, e := memoriaLiveCall(t, wrapped, "notes_search", `{"team":"acme","query":"nebula"}`) |
| + if status != 200 || e == nil || len(body) != 64<<10 { |
| + t.Fatalf("%d %d %v", status, len(body), e) |
| + } |
| +} |
| + |
| +func TestAgentRetryFinalGuardWithoutResponseMask(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + active := true |
| + h := mountAgentFixture(t, f, &p, &active) |
| + if w := agentCall(h, "notes_create", agentNoteInput); w.Code != 200 { |
| + t.Fatal(w.Code) |
| + } |
| + var checks int |
| + 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) |
| + } |
| + _, err = f.app.agentCreate(ctx, p, []byte(agentNoteInput), address) |
| + if err == nil || access.SafeFailure(err).Code != "unauthenticated" || checks != 2 { |
| + t.Fatalf("retry final guard: %v checks=%d", err, checks) |
| + } |
| +} |
| + |
| +func TestAgentCreateResponseReceiptAndStorage(t *testing.T) { |
| + for _, kind := range []string{"storage", "receipt", "external"} { |
| + t.Run(kind, func(t *testing.T) { |
| + f, p := linkedAgentFixture(t) |
| + var checks atomic.Int32 |
| + v := access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| + if checks.Add(1) == 4 { |
| + if kind == "storage" { |
| + if err := f.app.db.G.Callback().Query().Before("gorm:query").Register("response-receipt-fault", func(tx *gorm.DB) { |
| + if tx.Statement.Table == "documents" { |
| + tx.AddError(errors.New("private storage diagnostic")) |
| + } |
| + }); err != nil { |
| + return access.Principal{}, err |
| + } |
| + } else { |
| + query := "UPDATE memoria_agent_notes SET coordinate='changed'" |
| + if kind == "external" { |
| + query = "UPDATE documents SET external_id='changed'" |
| + } |
| + if err := f.app.db.G.Exec(query).Error; err != nil { |
| + return access.Principal{}, err |
| + } |
| + } |
| + } |
| + return p, nil |
| + }) |
| + mux := http.NewServeMux() |
| + if err := f.app.mountAgentAccess(mux, "https://connect.example.test", "acme", v); err != nil { |
| + t.Fatal(err) |
| + } |
| + status, body, err := memoriaLiveCall(t, mux, "notes_create", agentNoteInput) |
| + want := 404 |
| + if kind == "storage" { |
| + want = 503 |
| + } |
| + if err != nil || status != want || strings.Contains(string(body), "private") { |
| + t.Fatalf("%d %s %v", status, body, err) |
| + } |
| + var count int64 |
| + if err := f.app.db.G.Raw("SELECT count(*) FROM memoria_agent_notes WHERE document_id IS NOT NULL").Scan(&count).Error; err != nil || count != 1 { |
| + t.Fatalf("response failure replayed or rolled back committed create: %d %v", count, err) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/memoria/agent_team_compat_test.go b/internal/memoria/agent_team_compat_test.go| new file mode 100644 |
| index 0000000..aad136a |
| --- /dev/null |
| +++ b/internal/memoria/agent_team_compat_test.go |
| @@ -0,0 +1,198 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net/http" |
| + "strings" |
| + "testing" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/oficina/memoria/internal/memoria/sibling" |
| + "amadan.net/oficina/suite" |
| +) |
| + |
| +func linkedTeamAgentFixture(t *testing.T) (*teamFixture, access.Principal, http.Handler, string) { |
| + t.Helper() |
| + f := newTeamFixture(t, "alice@example.test") |
| + subject := teamSubject('a') |
| + f.dir.Set(subject, "member") |
| + f.refreshed() |
| + f.local(t) |
| + if w := f.linkFromMenu(t, subject); w.Code != http.StatusSeeOther { |
| + t.Fatal("link", w.Code, w.Body.String()) |
| + } |
| + team := f.app.team.Bindings().Team |
| + p := access.Principal{Subject: subject, Client: "test-agent", Grant: "grant-1", Teams: []string{team}, Scopes: []string{"notes:read", "notes:write"}} |
| + mux := http.NewServeMux() |
| + if err := f.app.mountAgentAccess(mux, "https://connect.example.test", team, access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return p, nil })); err != nil { |
| + t.Fatal(err) |
| + } |
| + input := strings.Replace(agentNoteInput, `"acme"`, `"`+team+`"`, 1) |
| + return f, p, mux, input |
| +} |
| + |
| +func TestAgentTeamMembershipSupersedesLocalAllowlist(t *testing.T) { |
| + for _, mode := range []string{"member-without-local-admission", "removed-but-still-locally-admitted", "unknown"} { |
| + t.Run(mode, func(t *testing.T) { |
| + f, p, h, input := linkedTeamAgentFixture(t) |
| + if w := agentCall(h, "notes_create", input); w.Code != 200 { |
| + t.Fatal("positive create", w.Code, w.Body.String()) |
| + } |
| + want := 200 |
| + switch mode { |
| + case "member-without-local-admission": |
| + f.app.SetOwners(nil) |
| + case "removed-but-still-locally-admitted": |
| + f.dir.Set(p.Subject, "") |
| + f.refreshed() |
| + want = 403 |
| + case "unknown": |
| + f.expired() |
| + want = 503 |
| + } |
| + for op, raw := range map[string]string{"notes_create": input, "notes_search": `{"team":"` + p.Teams[0] + `","query":"nebula"}`} { |
| + if w := agentCall(h, op, raw); w.Code != want { |
| + t.Fatal(op, w.Code, w.Body.String(), "want", want) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestAgentTeamConfigRejectsForeignBindingAndMissingRuntime(t *testing.T) { |
| + for _, mode := range []string{"foreign", "missing-runtime"} { |
| + t.Run(mode, func(t *testing.T) { |
| + f := newTeamFixture(t, "alice@example.test") |
| + team := f.app.team.Bindings().Team |
| + if mode == "foreign" { |
| + team = "different" |
| + } else { |
| + f.app.team = nil |
| + } |
| + if err := f.app.mountAgentAccess(http.NewServeMux(), "https://connect.example.test", team, access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return access.Principal{}, nil })); err == nil { |
| + t.Fatal("invalid team binding accepted") |
| + } |
| + var tables int |
| + if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE name IN ('memoria_agent_state','memoria_agent_notes')").Scan(&tables); err != nil || tables != 0 { |
| + t.Fatal("invalid binding reached agent migrations", tables, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type teamAgentCustody struct { |
| + *fixedCustody |
| + subjects []suite.Subject |
| + after func(int) |
| +} |
| + |
| +func (c *teamAgentCustody) Rule(ctx context.Context, subject suite.Subject, items []sibling.Candidate) []sibling.Disposition { |
| + c.subjects = append(c.subjects, subject) |
| + result := c.fixedCustody.Rule(ctx, subject, items) |
| + if c.after != nil { |
| + c.after(len(c.subjects)) |
| + } |
| + return result |
| +} |
| + |
| +func TestAgentTeamCustodyUsesPersonRefAndRechecksStanding(t *testing.T) { |
| + for _, phase := range []string{"valid", "after-search", "during-emission"} { |
| + t.Run(phase, func(t *testing.T) { |
| + f, p, h, _ := linkedTeamAgentFixture(t) |
| + custody := &teamAgentCustody{fixedCustody: &fixedCustody{apps: docsRoster(), give: suite.VISIBLE}} |
| + f.app.store.custody = custody |
| + if _, err := f.app.store.Ingest(systemWrite(t.Context()), IngestSpec{Source: "Docs", Key: "team-sibling", Title: "Sibling nebula", Body: "nebula sibling secret", ItemID: "docs-one", SiblingRevision: 1}); err != nil { |
| + t.Fatal(err) |
| + } |
| + custody.after = func(n int) { |
| + if phase == "after-search" && n == 1 || phase == "during-emission" && n == 2 { |
| + f.expired() |
| + } |
| + } |
| + w := agentCall(h, "notes_search", `{"team":"`+p.Teams[0]+`","query":"nebula"}`) |
| + if phase == "valid" { |
| + if w.Code != 200 || !strings.Contains(w.Body.String(), "sibling secret") || len(custody.subjects) < 2 { |
| + t.Fatal("positive search", w.Code, w.Body.String(), custody.subjects) |
| + } |
| + } else if w.Code != 503 || strings.Contains(w.Body.String(), "sibling secret") { |
| + t.Fatal("expired standing disclosed passage", w.Code, w.Body.String()) |
| + } |
| + for _, subject := range custody.subjects { |
| + if subject != (suite.Subject{Kind: suite.SubjectPersonRef, Value: p.Subject}) { |
| + t.Fatal("wrong sibling identity", subject) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestAgentTeamWriterExpiryRollsBackAndRefusesRetry(t *testing.T) { |
| + for _, retry := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "new", true: "completed-retry"}[retry], func(t *testing.T) { |
| + f, p, h, input := linkedTeamAgentFixture(t) |
| + if retry { |
| + if w := agentCall(h, "notes_create", input); w.Code != 200 { |
| + t.Fatal(w.Code, w.Body.String()) |
| + } |
| + } |
| + beforeDocs, beforeChunks, beforeReceipts := f.count("documents"), f.count("chunks"), f.count("memoria_agent_notes") |
| + checks := 0 |
| + state := &agentRequest{verify: func(context.Context, access.Principal, string) error { |
| + checks++ |
| + if checks == 2 { |
| + f.expired() |
| + } |
| + return nil |
| + }} |
| + ctx := context.WithValue(t.Context(), agentBoundaryKey{}, state) |
| + address, err := f.app.agentAddress(ctx, p, p.Teams[0]) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx = teammode.WithAccess(ctx, state.standing) |
| + // Domain call has no HTTP response guard to conceal a missed commit check. |
| + result, err := f.app.agentCreate(ctx, p, json.RawMessage(input), address) |
| + if err == nil || result != nil || checks != 2 { |
| + t.Fatal("expired write/retry succeeded", result, err, checks) |
| + } |
| + if f.count("documents") != beforeDocs || f.count("chunks") != beforeChunks || f.count("memoria_agent_notes") != beforeReceipts { |
| + t.Fatal("expired write retained effects") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestAgentTeamHomeOnlyReadRefused(t *testing.T) { |
| + f := newTeamFixture(t) |
| + subject := teamSubject('a') |
| + f.member(subject, "member") |
| + team := f.app.team.Bindings().Team |
| + p := access.Principal{Subject: subject, Client: "test", Grant: "grant", Teams: []string{team}, Scopes: []string{"notes:read", "notes:write"}} |
| + mux := http.NewServeMux() |
| + if err := f.app.mountAgentAccess(mux, "https://connect.example.test", team, access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return p, nil })); err != nil { |
| + t.Fatal(err) |
| + } |
| + if w := agentCall(mux, "notes_search", `{"team":"`+team+`","query":"nebula"}`); w.Code != 403 { |
| + t.Fatal("Home-only agent read accepted", w.Code, w.Body.String()) |
| + } |
| +} |
| + |
| +func TestAgentTeamWriterStandingIsIndependent(t *testing.T) { |
| + f, p, _, _ := linkedTeamAgentFixture(t) |
| + state := &agentRequest{verify: func(context.Context, access.Principal, string) error { f.expired(); return nil }} |
| + ctx := context.WithValue(t.Context(), agentBoundaryKey{}, state) |
| + address, err := f.app.agentAddress(ctx, p, p.Teams[0]) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + tx := f.app.db.G.WithContext(ctx).Begin() |
| + if tx.Error != nil { |
| + t.Fatal(tx.Error) |
| + } |
| + defer tx.Rollback() |
| + if err := f.app.checkAgentWriter(ctx, tx, p, address); err == nil { |
| + t.Fatal("writer ignored expired standing") |
| + } |
| +} |
diff --git a/internal/memoria/agent_team_lease_test.go b/internal/memoria/agent_team_lease_test.go| new file mode 100644 |
| index 0000000..ccbc93a |
| --- /dev/null |
| +++ b/internal/memoria/agent_team_lease_test.go |
| @@ -0,0 +1,105 @@ |
| +package memoria |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/suite" |
| +) |
| + |
| +type agentLeaseObserver struct { |
| + http.ResponseWriter |
| + budgets chan time.Duration |
| +} |
| + |
| +func (w *agentLeaseObserver) Unwrap() http.ResponseWriter { return w.ResponseWriter } |
| +func (w *agentLeaseObserver) SetWriteDeadline(d time.Time) error { |
| + if !d.IsZero() { |
| + w.budgets <- time.Until(d) |
| + } |
| + return http.NewResponseController(w.ResponseWriter).SetWriteDeadline(d) |
| +} |
| + |
| +// Reviewer-selected mutant: forward the requested deadline unchanged. The |
| +// actual shared HTTPGuarded transport must fail this near-expiry assertion. |
| +func TestAgentTeamLeaseBoundsSocketDeadlineAfterCustody(t *testing.T) { |
| + f, p, h, _ := linkedTeamAgentFixture(t) |
| + custody := &teamAgentCustody{fixedCustody: &fixedCustody{apps: docsRoster(), give: suite.VISIBLE}} |
| + f.app.store.custody = custody |
| + if _, err := f.app.store.Ingest(systemWrite(t.Context()), IngestSpec{Source: "Docs", Key: "lease-sibling", Title: "Nebula", Body: "nebula sibling secret", ItemID: "docs-one", SiblingRevision: 1}); err != nil { |
| + t.Fatal(err) |
| + } |
| + standing := f.app.team.Access(t.Context(), p.Subject) |
| + custody.after = func(n int) { |
| + if n == 1 { |
| + f.dir.SetDown(true) |
| + f.clock.Step(standing.Remaining() - 250*time.Millisecond) |
| + } |
| + } |
| + budgets := make(chan time.Duration, 16) |
| + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h.ServeHTTP(&agentLeaseObserver{w, budgets}, r) })) |
| + defer server.Close() |
| + raw, _ := json.Marshal(map[string]any{"team": p.Teams[0], "query": "nebula"}) |
| + req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/notes_search", bytes.NewReader(raw)) |
| + req.Header.Set("Authorization", "Bearer test-token") |
| + req.Header.Set("Content-Type", "application/json") |
| + res, err := server.Client().Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer res.Body.Close() |
| + _, err = io.ReadAll(res.Body) |
| + if err != nil || res.StatusCode != 200 { |
| + t.Fatal(res.StatusCode, err) |
| + } |
| + close(budgets) |
| + n := 0 |
| + for d := range budgets { |
| + n++ |
| + if d <= 0 || d > 300*time.Millisecond { |
| + t.Fatalf("write deadline outlives custody lease: %s", d) |
| + } |
| + } |
| + if n == 0 { |
| + t.Fatal("no transport deadline") |
| + } |
| +} |
| + |
| +type leaseRecorder struct { |
| + *httptest.ResponseRecorder |
| + deadline time.Time |
| +} |
| + |
| +func (w *leaseRecorder) SetWriteDeadline(d time.Time) error { w.deadline = d; return nil } |
| +func TestAgentTeamLeaseWriterEdges(t *testing.T) { |
| + f, p, _, _ := linkedTeamAgentFixture(t) |
| + state := &agentRequest{standing: f.app.team.Access(context.Background(), p.Subject)} |
| + underlying := &leaseRecorder{ResponseRecorder: httptest.NewRecorder()} |
| + w := &agentLeaseWriter{ResponseWriter: underlying, state: state, team: true} |
| + shorter := time.Now().Add(time.Millisecond) |
| + if e := w.SetWriteDeadline(shorter); e != nil || !underlying.deadline.Equal(shorter) { |
| + t.Fatal("short deadline widened", e) |
| + } |
| + f.expired() |
| + if e := w.SetWriteDeadline(time.Now().Add(time.Second)); e == nil { |
| + t.Fatal("expired lease accepted") |
| + } |
| + w.state = nil |
| + if e := w.SetWriteDeadline(time.Now().Add(time.Second)); e == nil { |
| + t.Fatal("missing standing accepted") |
| + } |
| + if e := w.SetWriteDeadline(time.Time{}); e != nil || !underlying.deadline.IsZero() { |
| + t.Fatal("clear failed", e) |
| + } |
| + w.team = false |
| + d := time.Now().Add(time.Second) |
| + if e := w.SetWriteDeadline(d); e != nil || !underlying.deadline.Equal(d) { |
| + t.Fatal("nonteam changed", 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/config.go b/internal/memoria/config.go| index 6d5d1b6..9e7b0a0 100644 |
| --- a/internal/memoria/config.go |
| +++ b/internal/memoria/config.go |
| @@ -28,6 +28,8 @@ type Config struct { |
| Owners []string |
| Sealer *seal.Sealer |
| Home *connect.DecodedCredentials |
| + AgentIssuer string |
| + AgentTeam string |
| // AllowLoggedMail permits booting with no SMTP, which makes |
| // rastrillo substitute mail.Logged — and mail.Logged writes the |
| // magic link, a live credential, into the process log at Warn. |
| @@ -167,6 +169,10 @@ func LoadConfig(getenv func(string) string) (Config, error) { |
| return c, err |
| } |
| } |
| + c.AgentIssuer, c.AgentTeam = getenv("MEMORIA_AGENT_ISSUER"), getenv("MEMORIA_AGENT_TEAM") |
| + if (c.AgentIssuer != "" || c.AgentTeam != "") && (c.AgentIssuer == "" || c.AgentTeam == "" || c.Home == nil) { |
| + return c, errors.New("memoria: agent access requires MEMORIA_AGENT_ISSUER, MEMORIA_AGENT_TEAM and Home") |
| + } |
| // Team mode exists only beside Home: the roster names Home subjects, |
| // and nobody could sign in to be asked about. |
| if c.Team != nil && c.Home == nil { |
diff --git a/internal/memoria/credits/notices.json b/internal/memoria/credits/notices.json| index 683e00f..b237262 100644 |
| --- a/internal/memoria/credits/notices.json |
| +++ b/internal/memoria/credits/notices.json |
| @@ -107,6 +107,17 @@ |
| } |
| ] |
| }, |
| + { |
| + "Name": "github.com/google/jsonschema-go", |
| + "Version": "v0.4.3", |
| + "SourceURL": "https://pkg.go.dev/github.com/google/jsonschema-go@v0.4.3", |
| + "Notices": [ |
| + { |
| + "Name": "LICENSE", |
| + "Text": "MIT License\n\nCopyright (c) 2025 JSON Schema Go Project Authors\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n" |
| + } |
| + ] |
| + }, |
| { |
| "Name": "github.com/google/uuid", |
| "Version": "v1.6.0", |
| @@ -146,6 +157,17 @@ |
| "SourceURL": "https://pkg.go.dev/github.com/keymaildev/signin@v0.1.1", |
| "Notices": [] |
| }, |
| + { |
| + "Name": "github.com/modelcontextprotocol/go-sdk", |
| + "Version": "v1.7.0", |
| + "SourceURL": "https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk@v1.7.0", |
| + "Notices": [ |
| + { |
| + "Name": "LICENSE", |
| + "Text": "The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 (\"Apache-2.0\"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0.\n\nContributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License.\n\nNo rights beyond those granted by the applicable original license are conveyed for such contributions.\n\n---\n\n Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n\n TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n 1. Definitions.\n\n \"License\" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n \"Licensor\" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n \"Legal Entity\" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n \"control\" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n \"You\" (or \"Your\") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n \"Source\" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n \"Object\" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n \"Work\" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n \"Derivative Works\" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n \"Contribution\" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright\n owner or by an individual or Legal Entity authorized to submit on behalf\n of the copyright owner. For the purposes of this definition, \"submitted\"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as \"Not a Contribution.\"\n\n \"Contributor\" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n 2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n 3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable\n by such Contributor that are necessarily infringed by their\n Contribution(s) alone or by combination of their Contribution(s)\n with the Work to which such Contribution(s) was submitted. If You\n institute patent litigation against any entity (including a\n cross-claim or counterclaim in a lawsuit) alleging that the Work\n or a Contribution incorporated within the Work constitutes direct\n or contributory patent infringement, then any patent licenses\n granted to You under this License for that Work shall terminate\n as of the date such litigation is filed.\n\n 4. Redistribution. You may reproduce and distribute copies of the\n Work or Derivative Works thereof in any medium, with or without\n modifications, and in Source or Object form, provided that You\n meet the following conditions:\n\n (a) You must give any other recipients of the Work or\n Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices\n stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works\n that You distribute, all copyright, patent, trademark, and\n attribution notices from the Source form of the Work,\n excluding those notices that do not pertain to any part of\n the Derivative Works; and\n\n (d) If the Work includes a \"NOTICE\" text file as part of its\n distribution, then any Derivative Works that You distribute must\n include a readable copy of the attribution notices contained\n within such NOTICE file, excluding those notices that do not\n pertain to any part of the Derivative Works, in at least one\n of the following places: within a NOTICE text file distributed\n as part of the Derivative Works; within the Source form or\n documentation, if provided along with the Derivative Works; or,\n within a display generated by the Derivative Works, if and\n wherever such third-party notices normally appear. The contents\n of the NOTICE file are for informational purposes only and\n do not modify the License. You may add Your own attribution\n notices within Derivative Works that You distribute, alongside\n or as an addendum to the NOTICE text from the Work, provided\n that such additional attribution notices cannot be construed\n as modifying the License.\n\n You may add Your own copyright statement to Your modifications and\n may provide additional or different license terms and conditions\n for use, reproduction, or distribution of Your modifications, or\n for any such Derivative Works as a whole, provided Your use,\n reproduction, and distribution of the Work otherwise complies with\n the conditions stated in this License.\n\n 5. Submission of Contributions. Unless You explicitly state otherwise,\n any Contribution intentionally submitted for inclusion in the Work\n by You to the Licensor shall be under the terms and conditions of\n this License, without any additional terms or conditions.\n Notwithstanding the above, nothing herein shall supersede or modify\n the terms of any separate license agreement you may have executed\n with Licensor regarding such Contributions.\n\n 6. Trademarks. This License does not grant permission to use the trade\n names, trademarks, service marks, or product names of the Licensor,\n except as required for reasonable and customary use in describing the\n origin of the Work and reproducing the content of the NOTICE file.\n\n 7. Disclaimer of Warranty. Unless required by applicable law or\n agreed to in writing, Licensor provides the Work (and each\n Contributor provides its Contributions) on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied, including, without limitation, any warranties or conditions\n of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n PARTICULAR PURPOSE. You are solely responsible for determining the\n appropriateness of using or redistributing the Work and assume any\n risks associated with Your exercise of permissions under this License.\n\n 8. Limitation of Liability. In no event and under no legal theory,\n whether in tort (including negligence), contract, or otherwise,\n unless required by applicable law (such as deliberate and grossly\n negligent acts) or agreed to in writing, shall any Contributor be\n liable to You for damages, including any direct, indirect, special,\n incidental, or consequential damages of any character arising as a\n result of this License or out of the use or inability to use the\n Work (including but not limited to damages for loss of goodwill,\n work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses), even if such Contributor\n has been advised of the possibility of such damages.\n\n 9. Accepting Warranty or Additional Liability. While redistributing\n the Work or Derivative Works thereof, You may choose to offer,\n and charge a fee for, acceptance of support, warranty, indemnity,\n or other liability obligations and/or rights consistent with this\n License. However, in accepting such obligations, You may act only\n on Your own behalf and on Your sole responsibility, not on behalf\n of any other Contributor, and only if You agree to indemnify,\n defend, and hold each Contributor harmless for any liability\n incurred by, or claims asserted against, such Contributor by reason\n of your accepting any such warranty or additional liability.\n\n END OF TERMS AND CONDITIONS\n\n---\n\nMIT License\n\nCopyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n---\n\nCreative Commons Attribution 4.0 International (CC-BY-4.0)\n\nDocumentation in this project (excluding specifications) is licensed under\nCC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for\nthe full license text.\n" |
| + } |
| + ] |
| + }, |
| { |
| "Name": "github.com/remyoudompheng/bigfft", |
| "Version": "v0.0.0-20230129092748-24d4a6f8daec", |
| @@ -157,6 +179,50 @@ |
| } |
| ] |
| }, |
| + { |
| + "Name": "github.com/santhosh-tekuri/jsonschema/v6", |
| + "Version": "v6.0.3", |
| + "SourceURL": "https://pkg.go.dev/github.com/santhosh-tekuri/jsonschema/v6@v6.0.3", |
| + "Notices": [ |
| + { |
| + "Name": "LICENSE", |
| + "Text": "\n Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n\n TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n 1. Definitions.\n\n \"License\" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n \"Licensor\" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n \"Legal Entity\" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n \"control\" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n \"You\" (or \"Your\") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n \"Source\" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n \"Object\" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n \"Work\" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n \"Derivative Works\" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n \"Contribution\" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright owner\n or by an individual or Legal Entity authorized to submit on behalf of\n the copyright owner. For the purposes of this definition, \"submitted\"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as \"Not a Contribution.\"\n\n \"Contributor\" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n 2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n 3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable\n by such Contributor that are necessarily infringed by their\n Contribution(s) alone or by combination of their Contribution(s)\n with the Work to which such Contribution(s) was submitted. If You\n institute patent litigation against any entity (including a\n cross-claim or counterclaim in a lawsuit) alleging that the Work\n or a Contribution incorporated within the Work constitutes direct\n or contributory patent infringement, then any patent licenses\n granted to You under this License for that Work shall terminate\n as of the date such litigation is filed.\n\n 4. Redistribution. You may reproduce and distribute copies of the\n Work or Derivative Works thereof in any medium, with or without\n modifications, and in Source or Object form, provided that You\n meet the following conditions:\n\n (a) You must give any other recipients of the Work or\n Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices\n stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works\n that You distribute, all copyright, patent, trademark, and\n attribution notices from the Source form of the Work,\n excluding those notices that do not pertain to any part of\n the Derivative Works; and\n\n (d) If the Work includes a \"NOTICE\" text file as part of its\n distribution, then any Derivative Works that You distribute must\n include a readable copy of the attribution notices contained\n within such NOTICE file, excluding those notices that do not\n pertain to any part of the Derivative Works, in at least one\n of the following places: within a NOTICE text file distributed\n as part of the Derivative Works; within the Source form or\n documentation, if provided along with the Derivative Works; or,\n within a display generated by the Derivative Works, if and\n wherever such third-party notices normally appear. The contents\n of the NOTICE file are for informational purposes only and\n do not modify the License. You may add Your own attribution\n notices within Derivative Works that You distribute, alongside\n or as an addendum to the NOTICE text from the Work, provided\n that such additional attribution notices cannot be construed\n as modifying the License.\n\n You may add Your own copyright statement to Your modifications and\n may provide additional or different license terms and conditions\n for use, reproduction, or distribution of Your modifications, or\n for any such Derivative Works as a whole, provided Your use,\n reproduction, and distribution of the Work otherwise complies with\n the conditions stated in this License.\n\n 5. Submission of Contributions. Unless You explicitly state otherwise,\n any Contribution intentionally submitted for inclusion in the Work\n by You to the Licensor shall be under the terms and conditions of\n this License, without any additional terms or conditions.\n Notwithstanding the above, nothing herein shall supersede or modify\n the terms of any separate license agreement you may have executed\n with Licensor regarding such Contributions.\n\n 6. Trademarks. This License does not grant permission to use the trade\n names, trademarks, service marks, or product names of the Licensor,\n except as required for reasonable and customary use in describing the\n origin of the Work and reproducing the content of the NOTICE file.\n\n 7. Disclaimer of Warranty. Unless required by applicable law or\n agreed to in writing, Licensor provides the Work (and each\n Contributor provides its Contributions) on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied, including, without limitation, any warranties or conditions\n of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n PARTICULAR PURPOSE. You are solely responsible for determining the\n appropriateness of using or redistributing the Work and assume any\n risks associated with Your exercise of permissions under this License.\n\n 8. Limitation of Liability. In no event and under no legal theory,\n whether in tort (including negligence), contract, or otherwise,\n unless required by applicable law (such as deliberate and grossly\n negligent acts) or agreed to in writing, shall any Contributor be\n liable to You for damages, including any direct, indirect, special,\n incidental, or consequential damages of any character arising as a\n result of this License or out of the use or inability to use the\n Work (including but not limited to damages for loss of goodwill,\n work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses), even if such Contributor\n has been advised of the possibility of such damages.\n\n 9. Accepting Warranty or Additional Liability. While redistributing\n the Work or Derivative Works thereof, You may choose to offer,\n and charge a fee for, acceptance of support, warranty, indemnity,\n or other liability obligations and/or rights consistent with this\n License. However, in accepting such obligations, You may act only\n on Your own behalf and on Your sole responsibility, not on behalf\n of any other Contributor, and only if You agree to indemnify,\n defend, and hold each Contributor harmless for any liability\n incurred by, or claims asserted against, such Contributor by reason\n of your accepting any such warranty or additional liability." |
| + } |
| + ] |
| + }, |
| + { |
| + "Name": "github.com/segmentio/asm", |
| + "Version": "v1.1.3", |
| + "SourceURL": "https://pkg.go.dev/github.com/segmentio/asm@v1.1.3", |
| + "Notices": [ |
| + { |
| + "Name": "LICENSE", |
| + "Text": "MIT License\n\nCopyright (c) 2021 Segment\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n" |
| + } |
| + ] |
| + }, |
| + { |
| + "Name": "github.com/segmentio/encoding", |
| + "Version": "v0.5.4", |
| + "SourceURL": "https://pkg.go.dev/github.com/segmentio/encoding@v0.5.4", |
| + "Notices": [ |
| + { |
| + "Name": "LICENSE", |
| + "Text": "MIT License\n\nCopyright (c) 2019 Segment.io, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n" |
| + } |
| + ] |
| + }, |
| + { |
| + "Name": "github.com/yosida95/uritemplate/v3", |
| + "Version": "v3.0.2", |
| + "SourceURL": "https://pkg.go.dev/github.com/yosida95/uritemplate/v3@v3.0.2", |
| + "Notices": [ |
| + { |
| + "Name": "LICENSE", |
| + "Text": "Copyright (C) 2016, Kohei YOSHIDA \u003chttps://yosida95.com/\u003e. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n * Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" |
| + } |
| + ] |
| + }, |
| { |
| "Name": "golang.org/x/crypto", |
| "Version": "v0.55.0", |
| @@ -168,6 +234,28 @@ |
| } |
| ] |
| }, |
| + { |
| + "Name": "golang.org/x/oauth2", |
| + "Version": "v0.35.0", |
| + "SourceURL": "https://pkg.go.dev/golang.org/x/oauth2@v0.35.0", |
| + "Notices": [ |
| + { |
| + "Name": "LICENSE", |
| + "Text": "Copyright 2009 The Go Authors.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n * Neither the name of Google LLC nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" |
| + } |
| + ] |
| + }, |
| + { |
| + "Name": "golang.org/x/sync", |
| + "Version": "v0.22.0", |
| + "SourceURL": "https://pkg.go.dev/golang.org/x/sync@v0.22.0", |
| + "Notices": [ |
| + { |
| + "Name": "LICENSE", |
| + "Text": "Copyright 2009 The Go Authors.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n * Neither the name of Google LLC nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" |
| + } |
| + ] |
| + }, |
| { |
| "Name": "golang.org/x/sys", |
| "Version": "v0.47.0", |
| @@ -190,6 +278,17 @@ |
| } |
| ] |
| }, |
| + { |
| + "Name": "golang.org/x/time", |
| + "Version": "v0.15.0", |
| + "SourceURL": "https://pkg.go.dev/golang.org/x/time@v0.15.0", |
| + "Notices": [ |
| + { |
| + "Name": "LICENSE", |
| + "Text": "Copyright 2009 The Go Authors.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n * Neither the name of Google LLC nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" |
| + } |
| + ] |
| + }, |
| { |
| "Name": "gorm.io/gorm", |
| "Version": "v1.31.2", |
diff --git a/internal/memoria/credits_inventory_test.go b/internal/memoria/credits_inventory_test.go| index 6f09885..6d0d9e9 100644 |
| --- a/internal/memoria/credits_inventory_test.go |
| +++ b/internal/memoria/credits_inventory_test.go |
| @@ -35,7 +35,7 @@ func TestCreditsMatchProductionDependencies(t *testing.T) { |
| if err != nil { |
| t.Fatal("production dependency graph unavailable", err) |
| } |
| - inventory, err := catalog.Collect(bytes.NewReader(raw), map[string]bool{"amadan.net/oficina/estilo.git": true, "amadan.net/oficina/home/handoff": true, "amadan.net/oficina/home/connect": true, "amadan.net/oficina/home/roster": true, "amadan.net/oficina/home/teammode": true, "amadan.net/oficina/suite": true, "amadan.net/rastrillo/native/server": true}) |
| + inventory, err := catalog.Collect(bytes.NewReader(raw), map[string]bool{"amadan.net/oficina/agent-access.git": true, "amadan.net/oficina/estilo.git": true, "amadan.net/oficina/home/handoff": true, "amadan.net/oficina/home/connect": true, "amadan.net/oficina/home/roster": true, "amadan.net/oficina/home/teammode": true, "amadan.net/oficina/suite": true, "amadan.net/rastrillo/native/server": true}) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/memoria/custody_test.go b/internal/memoria/custody_test.go| index 591aad9..37e2181 100644 |
| --- a/internal/memoria/custody_test.go |
| +++ b/internal/memoria/custody_test.go |
| @@ -24,6 +24,7 @@ import ( |
| // asked. It is the seam that lets §4.1's table be exercised end to end |
| // without a live sibling. |
| type fixedCustody struct { |
| + calls int |
| // apps is the configured roster. A source not in it does not resolve. |
| apps map[string]sibling.Sibling |
| give suite.Authorization |
| @@ -38,6 +39,7 @@ func (f *fixedCustody) Sibling(source string) (sibling.Sibling, bool) { |
| } |
| func (f *fixedCustody) Rule(ctx context.Context, asker suite.Subject, cands []sibling.Candidate) []sibling.Disposition { |
| + f.calls++ |
| f.asker = asker |
| out := make([]sibling.Disposition, len(cands)) |
| for i, c := range cands { |
diff --git a/internal/memoria/handlers.go b/internal/memoria/handlers.go| index e82da4f..040fa2f 100644 |
| --- a/internal/memoria/handlers.go |
| +++ b/internal/memoria/handlers.go |
| @@ -12,6 +12,7 @@ import ( |
| "net/url" |
| "strconv" |
| "strings" |
| + "sync" |
| "time" |
| "amadan.net/oficina/estilo.git/chrome" |
| @@ -83,12 +84,14 @@ func dropLimit() string { return strconv.Itoa(maxDropBytes>>20) + " MiB" } |
| func fileLimit() string { return strconv.Itoa(maxDropFiles) } |
| type app struct { |
| - 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 23d405d..2571eb4 100644 |
| --- a/internal/memoria/home.go |
| +++ b/internal/memoria/home.go |
| @@ -13,6 +13,7 @@ import ( |
| ) |
| type homeIntegration struct { |
| + issuer string |
| bridge *connect.Bridge |
| routes *connect.Routes |
| sessions *sessions.Sessions |
| @@ -71,7 +72,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 |
| // The roster runtime, last: it needs the bridge, and nothing serves |
| // until it is open or boot has been refused (team_config.go). |
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 9f7907f..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, |
| @@ -291,6 +295,11 @@ 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) { |
| + s.mutationMu.Lock() |
| + defer s.mutationMu.Unlock() |
| title := strings.TrimSpace(spec.Title) |
| body := strings.TrimSpace(spec.Body) |
| if body == "" { |
| @@ -335,6 +344,9 @@ func (s *Store) Ingest(ctx context.Context, spec IngestSpec) (int64, error) { |
| 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 |
| @@ -367,147 +379,178 @@ func (s *Store) Ingest(ctx context.Context, spec IngestSpec) (int64, error) { |
| // a sibling poll's ingest is a systemWrite and is not. |
| err = s.db.G.WithContext(ctx).Transaction(func(tx *gormTx) error { |
| return s.guard(ctx, memberWrite, 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. |
| - // |
| - // 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 |
| + } |
| + // 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. |
| + // 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. |
| + 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++ |
| } |
| - unchanged = true |
| - return nil |
| + 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 |
| } |
| - // 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, |
| + 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 |
| + } |
| + 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 |
| } |
| - if unchanged { |
| + if unchanged && (guard == nil || !guard.refresh) { |
| return docID, nil |
| } |
| @@ -641,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 |
| @@ -1118,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 |
| } |
diff --git a/internal/memoriatest/routes_test.go b/internal/memoriatest/routes_test.go| index eba3b69..4103e5e 100644 |
| --- a/internal/memoriatest/routes_test.go |
| +++ b/internal/memoriatest/routes_test.go |
| @@ -60,6 +60,10 @@ func TestNoUndeclaredRoutes(t *testing.T) { |
| // http.ServeMux patterns, verbatim — these are mounts, and the method |
| // (where there is one) lives inside the string. |
| declaredMux := map[string]bool{ |
| + // Delegated API: independent bearer verifier and current Home/local |
| + // admission. Spec's Agent access addendum declares both mounts. |
| + "/api/v1/operations": true, |
| + "/api/v1/operations/": true, |
| "GET /static/credits.css": true, |
| "GET /static/": true, |
| "GET /static/estilo/fonts/v1/": true, |