feat(gateway): chat memory read path (unification slice 3) (#887)

Wires the durable-memory engine into the chat turn: prepareTurn resolves a
per-channel Subject (BotUser as AgentID, TurnRunnerConfig.UserIdentity for
the user), runs a scope-only Query over Subject.Scopes(), and renders the
result into a new <memory purpose="durable_context" trust="data"> block
between <tools> and <env>, following the same untrusted-data framing as
those two blocks. The read is synchronous, total, and never surfaces an
error: a nil engine, a failing Query, or a panicking provider all degrade to
no memory block (recovered in gateway.renderMemory).

UserIdentity is supplied per channel by the composition
(userIdentityResolver in internal/app/archied): telegram and email resolve
their native SenderID, the dashboard ("web") and webhook resolve nothing, so
a webhook's route-path SenderID can never become a user identity and the
dashboard's shared bearer token can never impersonate a person.

Fixes the composition-ordering bug that left every turn runner holding a nil
memory engine: setupMemoryAll now runs before setupGateways in main.go, and
before setupGatewayChat in gateway.go's startGatewayRuntime, so
boot.memoryStore() has a live engine at every turn-runner construction site.

Named constants bound the read: memoryRecordsPerScope per scope, and
memoryBlockByteCap on the rendered block, which drops (and logs) trailing
records rather than truncating one mid-line.
This commit is contained in:
sam authored and GitHub committed 2026-09-19 11:40:45 +10:00
1 parent d5026f1a49
commit c8f88c84b2
14 files changed
+699 -6

No files matched your search

+32
View File
@@ -2,16 +2,21 @@ cel.dev/cel-go v0.32.0 h1:irvpFKr5EuGPyxeME03ERh0rii1TX+BDAnB9eL3IvNk=
cel.dev/cel-go v0.32.0/go.mod h1:DnVip7tpJSsgZymwfT+m1tnEVy3ivAjSMXPx12YrMkU=
cel.dev/expr v0.25.3 h1:A2jO8jwOugrrovveCWfj0KEZOfqiLgAcwjpHPhzIGw0=
cel.dev/expr v0.25.3/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
cloud.google.com/go/auth v0.20.0/go.mod h1:942/yi/itH1SsmpyrbnTMDgGfdy2BUqIKyd0cyYLc5Q=
cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
code.gitea.io/sdk/gitea v0.25.1 h1:yywxWwoV+SdjHtbC6unBiXojWdZOtoHuGhEazEXeWuE=
code.gitea.io/sdk/gitea v0.25.1/go.mod h1:uDFWYBU8dgZsgOHwe6C/6olxvf8FHguNB3wW1i83fgg=
github.com/42wim/httpsig v1.2.4 h1:mI5bH0nm4xn7K18fo1K3okNDRq8CCJ0KbBYWyA6r8lU=
github.com/42wim/httpsig v1.2.4/go.mod h1:yKsYfSyTBEohkPik224QPFylmzEBtda/kjyIAJjh3ps=
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.34.0/go.mod h1:pJTkW8hEUIIi3Pf65lPZOnn4Y81yCllX6IWk2jNXdkM=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/ProtonMail/go-crypto v1.4.1 h1:9RfcZHqEQUvP8RzecWEUafnZVtEvrBVL9BiF67IQOfM=
github.com/ProtonMail/go-crypto v1.4.1/go.mod h1:e1OaTyu5SYVrO9gKOEhTc+5UcXtTUa+P3uLudwcgPqo=
github.com/a-h/templ v0.3.1020/go.mod h1:A2DlK61v+K+NRoGnhmYbNYVmtYHcFO5/AisMvBdDxTM=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
github.com/antithesishq/antithesis-sdk-go v0.8.0 h1:bVV5ZAuwaREn4klRSJusYaA+A7NXq8Qi9C/knCaQ2N4=
@@ -20,14 +25,18 @@ github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYW
github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
github.com/bwesterb/go-ristretto v1.2.4/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cloudflare/circl v1.6.5 h1:O64F26HEqNhznd/hrC5KZXVKYuKM2rx4deZDTc4ihQA=
github.com/cloudflare/circl v1.6.5/go.mod h1:h5LNyxAc5nTue9DS5jT+48en2PSDYt3zdGnz5OstK6c=
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4=
github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=
github.com/containerd/typeurl/v2 v2.2.0/go.mod h1:8XOOxnyatxSWuG8OfsZXVnAF4iZfedjS/8UHSPJnX4g=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davidmz/go-pageant v1.0.2 h1:bPblRCh5jGU+Uptpz6LgMZGD5hJoOt7otgT454WvHn0=
@@ -42,6 +51,10 @@ github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU=
github.com/envoyproxy/go-control-plane/envoy v1.37.0/go.mod h1:DReE9MMrmecPy+YvQOAOHNYMALuowAnbjjEMkkWOi6A=
github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4=
github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0=
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c=
@@ -56,13 +69,17 @@ github.com/go-git/go-git-fixtures/v6 v6.0.0-alpha.1 h1:gmqi2jvsreu0s8JMLylYDFq4s
github.com/go-git/go-git-fixtures/v6 v6.0.0-alpha.1/go.mod h1:ECf1MqJlBdYpKggBrOXjo/0EnvRZx6D++I86UYjPgAQ=
github.com/go-git/go-git/v6 v6.0.0-alpha.5 h1:sE+OlkHgYWNMVmN1s9sR7uyFgsWLtxcNWse/vBYKxRE=
github.com/go-git/go-git/v6 v6.0.0-alpha.5/go.mod h1:3IjhiZnM+uBmUrOGSeqrJpsmi4Vd0H2NZO/uK2a7d0s=
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow=
github.com/go-telegram/bot v1.27.0 h1:PG9yBDzM8O26oUerE9SZwWlHon4RpH8WcNslZ7CEZmE=
github.com/go-telegram/bot v1.27.0/go.mod h1:i2TRs7fXWIeaceF3z7KzsMt/he0TwkVC680mvdTFYeM=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang/glog v1.2.5/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/codesearch v1.3.0-rc.1 h1:vSFGuF5wS3sjimuLzqPG+PGjWQ9VvEtPFbxdZD7YuuQ=
@@ -76,10 +93,14 @@ github.com/google/go-querystring v1.2.0 h1:yhqkPbu2/OH+V9BfpCVPZkNmUXhb2gBxJArfh
github.com/google/go-querystring v1.2.0/go.mod h1:8IFJqpSRITyJ8QhQ13bmbeMBDfmeEJZD5A0egEOmkqU=
github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba/go.mod h1:EFYHy8/1y2KfgTAsx7Luu7NGhoxtuVHnNo8jE7FikKc=
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/enterprise-certificate-proxy v0.3.15/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg=
github.com/googleapis/gax-go/v2 v2.22.0/go.mod h1:irWBbALSr0Sk3qlqb9SyJ1h68WjgeFuiOzI4Rqw5+aY=
github.com/hashicorp/go-version v1.9.0 h1:CeOIz6k+LoN3qX9Z0tyQrPtiB1DFYRPfCIBtaXPSCnA=
github.com/hashicorp/go-version v1.9.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
@@ -107,6 +128,7 @@ github.com/moby/moby/api v1.56.0 h1:GQzua3NA599ASSIICx0iFgiJeO9YkdDARvQsm23ZZuQ=
github.com/moby/moby/api v1.56.0/go.mod h1:sZ+THbVWkjOmBPPfbnzdD/G1LuIexWhqlSHHPTDQ1Uk=
github.com/moby/moby/client v0.6.0 h1:AJjEB21QPbXSXjDsZorFBoDZPhMrfbpaPLgSMAW9Bgs=
github.com/moby/moby/client v0.6.0/go.mod h1:OCo00wNRyA3m4lmJ228W3JbyCN4ZNNYjpOXiJydBdcQ=
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc=
github.com/nats-io/jwt/v2 v2.8.2/go.mod h1:Ag/56sq9OblL4JgdYufDd16Egb17Kr/8WwwuO/forVc=
github.com/nats-io/nats-server/v2 v2.15.0 h1:M99yf0y05rTr46/qc/Is6ZAowI58Ryp2SjufLCUeVJc=
@@ -127,15 +149,20 @@ github.com/pjbgf/sha1cd v0.6.0 h1:3WJ8Wz8gvDz29quX1OcEmkAlUg9diU4GxJHqs0/XiwU=
github.com/pjbgf/sha1cd v0.6.0/go.mod h1:lhpGlyHLpQZoxMv8HcgXvZEhcGs0PG/vsZnEJ7H0iCM=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8=
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/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/russross/blackfriday v1.6.0/go.mod h1:ti0ldHuxg49ri4ksnFxlkCfN+hvslNlmVHqNRXXJNAY=
github.com/samcharles93/ai-sdk v0.1.39 h1:gbNPYeA27MifReCruBiqMgb4fFSjCDi1Zv57a9bo0Vo=
github.com/samcharles93/ai-sdk v0.1.39/go.mod h1:u4zrQ9/Q58L5mNEut4bNQ1ks+RCKq71LN5EDz2N/0Zk=
github.com/santhosh-tekuri/jsonschema/v5 v5.3.1/go.mod h1:uToXkOrWAZ6/Oc07xWQrPOhJotwFIyu2bBVN41fcDUY=
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/spiffe/go-spiffe/v2 v2.8.1/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
@@ -144,6 +171,7 @@ github.com/traefik/yaegi v0.16.1 h1:f1De3DVJqIDKmnasUF6MwmWv1dSEEat0wcpXhD2On3E=
github.com/traefik/yaegi v0.16.1/go.mod h1:4eVhbPb3LnD2VigQjhYbEJ69vDRFdT2HQNrXx8eEwUY=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/detectors/gcp v1.44.0/go.mod h1:tNAsgd8avTGke1+MndXlU5Cru4PQ9Ai/cCNWQv/ZJ/s=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU=
go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc=
@@ -171,6 +199,7 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -192,8 +221,11 @@ golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU=
golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0=
golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY=
golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/api v0.278.0/go.mod h1:B9TqLBwJqVjp1mtt7WeoQwWRwvu/400y5lETOql+giQ=
google.golang.org/genproto/googleapis/api v0.0.0-20260918162117-cecb64721679 h1:FEp7JNE32DTAwbnI/ixagnmj7Xm1eTONofGEUXFjZ4w=
google.golang.org/genproto/googleapis/api v0.0.0-20260918162117-cecb64721679/go.mod h1:52bV8FLAQ9Qmcqaq9ECLmuEHZthk+6OPV45aKBBrsNw=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260918162117-cecb64721679 h1:KmqdJU4vrNcxy/6qdg3JduZtalEXrJLspVltnR1cE+8=
+23 -1
View File
@@ -688,7 +688,8 @@ func (b *boot) setupGateways(ctx context.Context, cfgPath, overlayPath string) b
Bus: b.bus,
Log: log,
ChannelManager: b.channelManager, AgentStatus: b.agentStatus,
RateLimiter: b.rateLimiter,
RateLimiter: b.rateLimiter,
MemoryEngine: b.memoryStore(),
})
if !ok {
return false
@@ -1156,6 +1157,27 @@ func (b *boot) setupMemoryAll() error {
return b.setupMemoryEngine()
}
// memoryStore resolves the active memory engine (the same one
// setupMemoryEngine registered under cfg.Memory.Engine) as the narrow read
// surface a chat turn runner needs. Nil when the registry was never set up
// or the configured engine is not registered -- both cases the turn runner
// already treats as "no memory block" (gateway.renderMemory), so a chat
// turn degrades instead of failing.
func (b *boot) memoryStore() gateway.MemoryStore {
if b.memEngines == nil {
return nil
}
name := b.cfg.Memory.Engine
if name == "" {
name = infraMemory.EngineName
}
engine, ok := b.memEngines.Get(name)
if !ok {
return nil
}
return engine
}
// setupCurators wires the curator engine family. The registry owns
// curator registration, lifecycle and shutdown ordering. The runtime
// loop (archie-core-89x) and the reference curators (archie-core-i7i,
+44
View File
@@ -0,0 +1,44 @@
package archied
import (
"github.com/samcharles93/archie-core/internal/domain/memory"
"github.com/samcharles93/archie-core/internal/domain/messaging"
)
// userIdentityResolver returns the gateway.TurnRunnerConfig.UserIdentity
// function for one channel, per docs/prds/memory-engine-unification.md §3:
// resolution is supplied per channel by the composition, never inferred by
// the engine or guessed from a channel-neutral "channel:SenderID"
// concatenation.
//
// Telegram and email carry a native per-person sender id (a Telegram numeric
// user id, an SMTP from address). The dashboard ("web") has one bearer
// token, not users, and a webhook's SenderID is the configured route path
// (internal/channels/webhook/webhook.go), not a person -- treating either as
// an identity would give a URL or a shared token the same standing as a
// real user, which the read path's isolation guarantee depends on never
// happening. Both resolve nothing, so a turn on either channel gets global
// and agent scopes only (Subject.WritableScopes' fail-closed behaviour).
func userIdentityResolver(channel string) func(messaging.Message) (memory.IdentityID, bool) {
switch channel {
case "telegram", "email":
return senderIDIdentity
default:
return noUserIdentity
}
}
// senderIDIdentity resolves a channel's own SenderID as the user's identity.
// Empty means the channel carries no per-person identity for this message.
func senderIDIdentity(msg messaging.Message) (memory.IdentityID, bool) {
if msg.SenderID == "" {
return "", false
}
return memory.IdentityID(msg.SenderID), true
}
// noUserIdentity resolves nothing: the channel it is wired to (the
// dashboard, a webhook) carries no per-person identity at all.
func noUserIdentity(messaging.Message) (memory.IdentityID, bool) {
return "", false
}
@@ -0,0 +1,60 @@
package archied
import (
"testing"
"github.com/samcharles93/archie-core/internal/domain/messaging"
)
// TestWebhookUserIdentityNeverReturnsTheRoutePath guards
// docs/prds/memory-engine-unification.md §3 and §4's specific webhook
// requirement: internal/channels/webhook/webhook.go sets SenderID to the
// configured route path (RouteConfig.Path), and that must never surface as
// a user identity, however plausible it looks as one.
func TestWebhookUserIdentityNeverReturnsTheRoutePath(t *testing.T) {
resolver := userIdentityResolver("webhook")
id, ok := resolver(messaging.Message{SenderID: "/github", Sender: "webhook"})
if ok || id != "" {
t.Fatalf("webhook resolver = (%q, %v), want (\"\", false)", id, ok)
}
}
// TestUserIdentityResolverPerChannel documents the composition's per-channel
// choice: telegram and email carry a native sender id, the dashboard ("web")
// and webhook do not.
func TestUserIdentityResolverPerChannel(t *testing.T) {
tests := []struct {
channel string
senderID string
wantOK bool
}{
{"telegram", "12345", true},
{"email", "person@example.com", true},
{"web", "anything", false},
{"webhook", "/github", false},
{"unknown-future-channel", "anything", false},
}
for _, tt := range tests {
t.Run(tt.channel, func(t *testing.T) {
resolver := userIdentityResolver(tt.channel)
id, ok := resolver(messaging.Message{SenderID: tt.senderID})
if ok != tt.wantOK {
t.Fatalf("%s resolver ok = %v, want %v", tt.channel, ok, tt.wantOK)
}
if ok && string(id) != tt.senderID {
t.Fatalf("%s resolver id = %q, want %q", tt.channel, id, tt.senderID)
}
})
}
}
// TestSenderIDIdentityFailsClosedOnEmptySenderID guards §3's "fail closed":
// an empty SenderID (a channel that carries no per-caller id for this
// particular message) must resolve to no identity, never an empty-string
// identity that Subject would treat as present.
func TestSenderIDIdentityFailsClosedOnEmptySenderID(t *testing.T) {
id, ok := senderIDIdentity(messaging.Message{SenderID: ""})
if ok || id != "" {
t.Fatalf("senderIDIdentity(empty) = (%q, %v), want (\"\", false)", id, ok)
}
}
@@ -33,3 +33,51 @@ func TestRunBuildsWorktreeManagerBeforeGateways(t *testing.T) {
t.Fatal("Run wires the gateways before buildTreesAndIdentities; prReviewer captures b.trees, so review_pr would be dropped instead of advertised")
}
}
// TestRunSetsUpMemoryBeforeGateways pins the ordering
// docs/prds/memory-engine-unification.md §4's "Prerequisite" note requires:
// setupGateways constructs every chat turn runner (setupGatewayChat,
// setupTelegramGateway), and a turn runner captures b.memEngines at
// construction time via boot.memoryStore(). Built the other way round, every
// turn runner captures a nil engine and the chat <memory> block never
// appears, silently, because renderMemory treats a nil engine the same as a
// failed read. Nothing at runtime observes the order, so it is asserted by
// source position, the same way TestRunBuildsWorktreeManagerBeforeGateways
// pins the worktree-manager ordering above.
func TestRunSetsUpMemoryBeforeGateways(t *testing.T) {
fileset := token.NewFileSet()
file, err := parser.ParseFile(fileset, "main.go", nil, 0)
if err != nil {
t.Fatal(err)
}
run := methodBody(t, file, "Run")
memoryAll := methodCallPosition(run, "setupMemoryAll")
gateways := methodCallPosition(run, "setupGateways")
if memoryAll == token.NoPos || gateways == token.NoPos {
t.Fatalf("Run call positions: setupMemoryAll=%v setupGateways=%v, want both present", memoryAll, gateways)
}
if gateways < memoryAll {
t.Fatal("Run wires the gateways before setupMemoryAll; every turn runner would capture a nil memory engine")
}
}
// TestStartGatewayRuntimeSetsUpMemoryBeforeGatewayChat is the standalone
// Gateway process's half of the same prerequisite: startGatewayRuntime
// (gateway.go) constructs the turn runner via setupGatewayChat, which must
// see a non-nil b.memEngines already.
func TestStartGatewayRuntimeSetsUpMemoryBeforeGatewayChat(t *testing.T) {
fileset := token.NewFileSet()
file, err := parser.ParseFile(fileset, "gateway.go", nil, 0)
if err != nil {
t.Fatal(err)
}
run := methodBody(t, file, "startGatewayRuntime")
memoryAll := methodCallPosition(run, "setupMemoryAll")
chat := methodCallPosition(run, "setupGatewayChat")
if memoryAll == token.NoPos || chat == token.NoPos {
t.Fatalf("startGatewayRuntime call positions: setupMemoryAll=%v setupGatewayChat=%v, want both present", memoryAll, chat)
}
if chat < memoryAll {
t.Fatal("startGatewayRuntime wires setupGatewayChat before setupMemoryAll; the turn runner would capture a nil memory engine")
}
}
+5 -2
View File
@@ -125,14 +125,17 @@ func (b *boot) startGatewayRuntime(ctx context.Context, actor gateway.ChatTaskAc
b.bus = events.NewBus()
b.addCleanup(b.bus.Close)
b.capabilityHost = plugin.NewHost()
contract := b.setupGatewayChat(ctx, actor)
// setupMemoryAll must run before setupGatewayChat: setupGatewayChat
// constructs the turn runner, which captures b.memEngines at
// construction time (see the identical ordering note in main.go's Run).
// Memory is opened with its own long-lived context inside (matching the
// daemon path via setupMemoryAll): shutdown of the file-backed provider
// outlives the boot context by design, so the legacy manager wires itself
// with a background context rather than the gateway's boot ctx.
if err := b.setupMemory(); err != nil { //nolint:contextcheck // setupMemory owns its lifecycle contexts, matching the daemon's setupMemoryAll
if err := b.setupMemoryAll(); err != nil { //nolint:contextcheck // setupMemory owns its lifecycle contexts, matching the daemon's setupMemoryAll
return nil, err
}
contract := b.setupGatewayChat(ctx, actor)
if err := b.registerTools(ctx); err != nil {
return nil, err
}
+1
View File
@@ -67,6 +67,7 @@ func (b *boot) setupGatewayChat(ctx context.Context, actor gateway.ChatTaskActor
ChatTaskActor: actor, ChatPRReviewer: b.prReviewer(),
DefaultChatIdentity: b.defaultChatIdentity, SessionStore: b.chatSessionStore,
Bus: b.bus, Log: b.log, Secrets: b.secrets,
MemoryEngine: b.memoryStore(),
}
router.LLM, router.LLMStream = makeChatLLMResponder(ctx, "web", setup, b.chatSessionStore, router)
router.Titles = newChatTitleGenerator(setup)
+9 -3
View File
@@ -411,6 +411,15 @@ func Run() int { //nolint:cyclop // the composition root's setup sequence is del
if err := b.buildTreesAndIdentities(ctx); err != nil {
return 1
}
// setupMemoryAll must run before setupGateways: setupGateways constructs
// every chat turn runner (setupGatewayChat / setupTelegramGateway), and a
// turn runner captures b.memEngines at construction time. Built the other
// way round, every turn runner would capture a nil engine and the chat
// read path (docs/prds/memory-engine-unification.md §4) would silently
// never see a record.
if err := b.setupMemoryAll(); err != nil {
return 1
}
if !b.setupGateways(ctx, args.cfgPath, args.overlayPath) {
return 1
}
@@ -425,9 +434,6 @@ func Run() int { //nolint:cyclop // the composition root's setup sequence is del
if err := b.registerNATSRPC(); err != nil {
return 1
}
if err := b.setupMemoryAll(); err != nil {
return 1
}
b.setupCurators(ctx)
if err := b.setupScheduling(); err != nil {
+6
View File
@@ -68,6 +68,10 @@ type telegramSetup struct {
// RateLimiter budgets inbound messages per sender when set. Nil
// leaves rate limiting off.
RateLimiter *ratelimit.Limiter
// MemoryEngine is the durable-memory read surface (b.memEngines' active
// engine, resolved by cfg.Memory.Engine). Nil disables the chat <memory>
// block for every turn runner built from this setup.
MemoryEngine gateway.MemoryStore
}
// telegramValidateConfigMap builds the map Gateway.ValidateConfig expects
@@ -355,6 +359,8 @@ func newChatTurnRunner(
Operator: cfg.Chat.Operator,
Workspace: cfg.Chat.Workspace,
Repos: chatRepoEnv(cfg, s.DefaultChatIdentity),
MemoryEngine: s.MemoryEngine,
UserIdentity: userIdentityResolver(channel),
Log: s.Log,
})
if err := runner.Recover(ctx); err != nil && s.Log != nil {
+8
View File
@@ -64,6 +64,13 @@ type SystemPromptConfig struct {
// (chat.operator). Rendered so the agent knows the identity context it
// serves under; empty means unconfigured and must be said explicitly.
Operator string
// Memory is the pre-rendered <memory> block body: the durable records the
// read path recalled for this turn's resolved subject, already bounded by
// the per-scope record limit and the render byte cap. Empty when there is
// nothing to recall, or when the read degraded (engine failure, panic,
// unresolved identity beyond global/agent scope) -- the template omits
// the block entirely in that case, exactly like Tools.
Memory string
}
// promptData is the template execution context. It exists so the template
@@ -105,6 +112,7 @@ func BuildSystemPrompt(cfg SystemPromptConfig) string {
Workspace: cfg.Workspace,
Repos: cfg.Repos,
Operator: cfg.Operator,
Memory: cfg.Memory,
}
var buf strings.Builder
if err := archiePromptTemplate.Execute(&buf, data); err != nil {
+5
View File
@@ -46,6 +46,11 @@ The `<soul>` block above, when present, supplies identity and communication styl
{{- else}}
Right now no tools are available to you, so you can only answer from the conversation and your own knowledge. Say that directly when asked to act on files, systems or the network.
{{- end}}
{{if .Memory}}
<memory purpose="durable_context" trust="data">
{{xml .Memory}}
</memory>
{{- end}}
<env purpose="runtime_metadata" trust="data">
Today's date: {{xml .Date}}
+14
View File
@@ -8,6 +8,7 @@ import (
"sync"
"time"
"github.com/samcharles93/archie-core/internal/domain/memory"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/tools"
@@ -99,6 +100,17 @@ type TurnRunnerConfig struct {
// default branch, rendered into the prompt's <env> block.
Repos []RepoEnv
Log *slog.Logger
// MemoryEngine is the durable-memory read surface consulted once per turn
// in prepareTurn. Nil disables the <memory> block entirely (renderMemory
// treats a nil store the same as a failed read).
MemoryEngine MemoryStore
// UserIdentity resolves the initiating user's identity for one inbound
// message, per channel. False (or a nil UserIdentity) means the channel
// carries no per-person identity -- the dashboard's one bearer token, or a
// webhook's route path, which must never be treated as a person -- and
// the turn's memory Subject gets no UserID, so its read is agent and
// global scope only (docs/prds/memory-engine-unification.md §3, §4).
UserIdentity func(msg messaging.Message) (memory.IdentityID, bool)
}
// TurnRunner owns one chat turn from session resolution through model
@@ -314,6 +326,7 @@ func (r *TurnRunner) prepareTurn(ctx context.Context, sessionID string, in Inbou
if r.Personas != nil {
persona = r.Personas.GetActive(sessionID)
}
memoryBlock := renderMemory(ctx, r.MemoryEngine, r.resolveSubject(in.Message), r.Log)
systemPrompt := BuildSystemPrompt(SystemPromptConfig{
Persona: persona,
Tools: prepared.ToolSummaries(),
@@ -325,6 +338,7 @@ func (r *TurnRunner) prepareTurn(ctx context.Context, sessionID string, in Inbou
Workspace: r.Workspace,
Repos: r.Repos,
Operator: r.Operator,
Memory: memoryBlock,
})
compression, err := CompressionConfigForModel(
modelDetails,
+109
View File
@@ -0,0 +1,109 @@
package gateway
import (
"context"
"fmt"
"log/slog"
"strings"
domainmemory "github.com/samcharles93/archie-core/internal/domain/memory"
"github.com/samcharles93/archie-core/internal/domain/messaging"
)
// memoryRecordsPerScope bounds how many records of each scope the read path
// asks the engine for. It is a per-scope limit, not a total: Subject.Scopes()
// returns at most four scopes, so the worst case is four times this many
// records before the byte cap below trims further.
const memoryRecordsPerScope = 20
// memoryBlockByteCap bounds the rendered <memory> block's size. This is a
// size guard, not a timeout: the read is local and synchronous, and nothing
// here waits on the network. A record that would push the block over the cap
// is dropped (not truncated mid-record) and the drop is logged, so the block
// stays valid content rather than silently corrupted output.
const memoryBlockByteCap = 8192
// MemoryStore is the read surface prepareTurn needs from a memory engine: a
// scope-only Query, nothing else. Narrowed from domainmemory.Store (which
// also carries the write operations slice 4 uses) so this package's read
// path cannot accidentally reach for Create/Update/Forget.
type MemoryStore interface {
Query(ctx context.Context, q domainmemory.Query) ([]domainmemory.Record, error)
}
// renderMemory builds the turn's <memory> block body: a scope-only Query over
// subject.Scopes() (most specific first, per Subject.Scopes' own doc), bounded
// by memoryRecordsPerScope per scope and memoryBlockByteCap overall.
//
// This is synchronous, total, and never returns an error: docs/prds/
// memory-engine-unification.md §4 requires the chat read path to degrade to
// an empty block on any engine failure, including a panic, rather than fail
// the turn -- a memory read is an enhancement to the prompt, never a
// precondition for answering. The recover here is that contract's only
// enforcement point; every caller below runs inside it.
func renderMemory(ctx context.Context, store MemoryStore, subject domainmemory.Subject, log *slog.Logger) (block string) {
if store == nil {
return ""
}
defer func() {
if p := recover(); p != nil {
if log != nil {
log.Warn("chat memory read panicked; continuing without a memory block", "panic", p)
}
block = ""
}
}()
records, err := store.Query(ctx, domainmemory.Query{
Scopes: subject.Scopes(),
Limit: memoryRecordsPerScope * len(subject.Scopes()),
})
if err != nil {
if log != nil {
log.Warn("chat memory read failed; continuing without a memory block", "err", err)
}
return ""
}
return renderMemoryRecords(records, log)
}
// renderMemoryRecords formats records as one line each, addressed by the
// record's own id -- the same id the write path (slice 4) will take a
// memory_edit call by, so the read and write directions share one source of
// truth for addressing. A record whose line would push the block past
// memoryBlockByteCap is dropped and logged rather than truncated mid-line,
// so a partial block is never mistaken for a complete or a corrupted one.
func renderMemoryRecords(records []domainmemory.Record, log *slog.Logger) string {
var b strings.Builder
dropped := 0
for _, record := range records {
line := fmt.Sprintf("- [%s] (%s, %s) %s\n", record.ID, record.Scope.Kind, record.Kind, record.Content)
if b.Len()+len(line) > memoryBlockByteCap {
dropped++
continue
}
b.WriteString(line)
}
if dropped > 0 && log != nil {
log.Warn("chat memory block exceeded its render cap; some records were dropped",
"cap_bytes", memoryBlockByteCap, "dropped", dropped, "rendered", len(records)-dropped)
}
return strings.TrimRight(b.String(), "\n")
}
// resolveSubject builds a turn's memory Subject from the runner's agent
// identity (BotUser, the closest thing to an Agent id the tree records today
// -- see sessioncurator.Adapter) and the channel's UserIdentity resolver. A
// nil resolver, or one that returns false, yields UserID "" -- Subject.Scopes
// then names only agent and global, never a wider fallback
// (docs/prds/memory-engine-unification.md §3, "fail closed").
func (r *TurnRunner) resolveSubject(msg messaging.Message) domainmemory.Subject {
subject := domainmemory.Subject{AgentID: domainmemory.AgentID(r.BotUser)}
if r.UserIdentity == nil {
return subject
}
if id, ok := r.UserIdentity(msg); ok {
subject.UserID = id
}
return subject
}
+335
View File
@@ -0,0 +1,335 @@
package gateway
import (
"context"
"errors"
"fmt"
"log/slog"
"strings"
"testing"
domainmemory "github.com/samcharles93/archie-core/internal/domain/memory"
"github.com/samcharles93/archie-core/internal/domain/messaging"
infraMemory "github.com/samcharles93/archie-core/internal/infrastructure/memory"
)
// newMemoryTestEngine builds a real builtin engine so these tests exercise
// the actual scope-key isolation, not a fake that might not mirror it.
func newMemoryTestEngine(t *testing.T) *infraMemory.BuiltinEngine {
t.Helper()
return infraMemory.NewBuiltinEngine(t.TempDir(), 0)
}
func telegramIdentity(msg messaging.Message) (domainmemory.IdentityID, bool) {
if msg.SenderID == "" {
return "", false
}
return domainmemory.IdentityID(msg.SenderID), true
}
func chatMsg(sourceID, channelID, senderID, text string) Inbound {
return Inbound{Message: messaging.Message{
SourceID: sourceID,
ConversationID: messaging.ConversationID{ChannelID: channelID},
Sender: "user",
SenderID: senderID,
Role: messaging.RoleUser,
Text: text,
}}
}
func newMemoryTestRunner(t *testing.T, engine MemoryStore, userIdentity func(messaging.Message) (domainmemory.IdentityID, bool), botUser string) (*TurnRunner, *turnTestPreparedModel) {
t.Helper()
store := NewSessionStoreMemory()
router := NewRouter(nil, nil, "telegram")
router.Identity = botUser
router.InitSessions(store)
prepared := &turnTestPreparedModel{reply: "ok"}
runner := NewTurnRunner(TurnRunnerConfig{
Router: router,
Sessions: store,
Models: &fakeModelManager{models: []string{"test/model"}, activeModel: "test/model"},
Personas: NewPersonaRegistry(DefaultPersonas()),
Model: &turnTestModel{prepared: prepared},
BotUser: botUser,
Channel: "telegram",
Log: slog.New(slog.DiscardHandler),
MemoryEngine: engine,
UserIdentity: userIdentity,
})
return runner, prepared
}
// lastSystemPrompt returns the system-prompt message content the model saw
// on its most recent Generate call.
func lastSystemPrompt(prepared *turnTestPreparedModel) string {
for _, m := range prepared.lastRequest.Messages {
if m.Role == "system" {
return m.Content
}
}
return ""
}
// TestTurnMemoryReadPathAppearsNextTurn is acceptance criterion 1: a record
// created directly through the engine's Store appears in a later turn's
// prompt, with its id.
func TestTurnMemoryReadPathAppearsNextTurn(t *testing.T) {
engine := newMemoryTestEngine(t)
runner, prepared := newMemoryTestRunner(t, engine, telegramIdentity, "archie")
rec, err := engine.Create(context.Background(), domainmemory.NewRecord{
Scope: domainmemory.Scope{Kind: domainmemory.ScopeAgentUser, Agent: "archie", User: "alice"},
Kind: "note",
Content: "alice prefers dark roast coffee",
Author: "test",
})
if err != nil {
t.Fatalf("Create() error = %v", err)
}
if _, err := runner.Run(context.Background(), chatMsg("s1", "chat-1", "alice", "hi"), nil); err != nil {
t.Fatalf("Run() error = %v", err)
}
prompt := lastSystemPrompt(prepared)
if !strings.Contains(prompt, "alice prefers dark roast coffee") {
t.Fatalf("prompt missing planted record content, prompt = %q", prompt)
}
if !strings.Contains(prompt, string(rec.ID)) {
t.Fatalf("prompt missing record id %q, prompt = %q", rec.ID, prompt)
}
if !strings.Contains(prompt, `<memory purpose="durable_context" trust="data">`) {
t.Fatalf("prompt missing memory block wrapper, prompt = %q", prompt)
}
}
// TestTurnMemoryIsolatesByUser is acceptance criterion 2: an agent-user
// record for one user is absent from a different user's prompt on the same
// channel and agent, asserted end to end through the turn path.
func TestTurnMemoryIsolatesByUser(t *testing.T) {
engine := newMemoryTestEngine(t)
runner, prepared := newMemoryTestRunner(t, engine, telegramIdentity, "archie")
if _, err := engine.Create(context.Background(), domainmemory.NewRecord{
Scope: domainmemory.Scope{Kind: domainmemory.ScopeAgentUser, Agent: "archie", User: "alice"},
Kind: "note",
Content: "alice's secret project is codename phoenix",
Author: "test",
}); err != nil {
t.Fatalf("Create() error = %v", err)
}
if _, err := runner.Run(context.Background(), chatMsg("s1", "chat-bob", "bob", "hi"), nil); err != nil {
t.Fatalf("Run() error = %v", err)
}
prompt := lastSystemPrompt(prepared)
if strings.Contains(prompt, "codename phoenix") {
t.Fatalf("bob's prompt leaked alice's agent-user record, prompt = %q", prompt)
}
}
// TestTurnMemoryScopeSharing is acceptance criterion 3: agent-scope records
// are visible to both of that agent's users, a global record is visible to a
// second agent, and an agent-user record is not shared.
func TestTurnMemoryScopeSharing(t *testing.T) {
engine := newMemoryTestEngine(t)
ctx := context.Background()
if _, err := engine.Create(ctx, domainmemory.NewRecord{
Scope: domainmemory.Scope{Kind: domainmemory.ScopeAgent, Agent: "archie"}, Kind: "note",
Content: "agent-wide fact about archie", Author: "test",
}); err != nil {
t.Fatalf("Create(agent) error = %v", err)
}
if _, err := engine.Create(ctx, domainmemory.NewRecord{
Scope: domainmemory.Scope{Kind: domainmemory.ScopeGlobal}, Kind: "note",
Content: "global fact for every agent", Author: "test",
}); err != nil {
t.Fatalf("Create(global) error = %v", err)
}
if _, err := engine.Create(ctx, domainmemory.NewRecord{
Scope: domainmemory.Scope{Kind: domainmemory.ScopeAgentUser, Agent: "archie", User: "alice"}, Kind: "note",
Content: "relationship-only fact about alice and archie", Author: "test",
}); err != nil {
t.Fatalf("Create(agent-user) error = %v", err)
}
// alice and bob both talk to archie: both see the agent-wide fact, only
// alice sees the agent-user fact.
archieRunner, archiePrepared := newMemoryTestRunner(t, engine, telegramIdentity, "archie")
if _, err := archieRunner.Run(ctx, chatMsg("s-alice", "chat-alice", "alice", "hi"), nil); err != nil {
t.Fatalf("Run(alice) error = %v", err)
}
alicePrompt := lastSystemPrompt(archiePrepared)
if !strings.Contains(alicePrompt, "agent-wide fact about archie") {
t.Fatalf("alice's prompt missing agent-wide fact, prompt = %q", alicePrompt)
}
if !strings.Contains(alicePrompt, "relationship-only fact about alice and archie") {
t.Fatalf("alice's prompt missing her own agent-user fact, prompt = %q", alicePrompt)
}
if _, err := archieRunner.Run(ctx, chatMsg("s-bob", "chat-bob", "bob", "hi"), nil); err != nil {
t.Fatalf("Run(bob) error = %v", err)
}
bobPrompt := lastSystemPrompt(archiePrepared)
if !strings.Contains(bobPrompt, "agent-wide fact about archie") {
t.Fatalf("bob's prompt missing agent-wide fact, prompt = %q", bobPrompt)
}
if strings.Contains(bobPrompt, "relationship-only fact about alice and archie") {
t.Fatalf("bob's prompt leaked alice's agent-user fact, prompt = %q", bobPrompt)
}
// A second agent sees the global fact but not the first agent's
// agent-scope fact.
otherRunner, otherPrepared := newMemoryTestRunner(t, engine, telegramIdentity, "other-agent")
if _, err := otherRunner.Run(ctx, chatMsg("s-carol", "chat-carol", "carol", "hi"), nil); err != nil {
t.Fatalf("Run(other agent) error = %v", err)
}
otherPrompt := lastSystemPrompt(otherPrepared)
if !strings.Contains(otherPrompt, "global fact for every agent") {
t.Fatalf("second agent's prompt missing global fact, prompt = %q", otherPrompt)
}
if strings.Contains(otherPrompt, "agent-wide fact about archie") {
t.Fatalf("second agent's prompt leaked the first agent's agent-scope fact, prompt = %q", otherPrompt)
}
}
// failingMemoryStore always errors.
type failingMemoryStore struct{}
func (failingMemoryStore) Query(context.Context, domainmemory.Query) ([]domainmemory.Record, error) {
return nil, errors.New("engine unavailable")
}
// panickingMemoryStore always panics.
type panickingMemoryStore struct{}
func (panickingMemoryStore) Query(context.Context, domainmemory.Query) ([]domainmemory.Record, error) {
panic("boom")
}
// TestTurnMemoryFailingEngineDegradesSilently is acceptance criterion 6 (the
// failing half): a failing engine completes the turn with no memory block
// and no surfaced error.
func TestTurnMemoryFailingEngineDegradesSilently(t *testing.T) {
runner, prepared := newMemoryTestRunner(t, failingMemoryStore{}, telegramIdentity, "archie")
reply, err := runner.Run(context.Background(), chatMsg("s1", "chat-1", "alice", "hi"), nil)
if err != nil {
t.Fatalf("Run() error = %v, want turn to complete despite the engine failure", err)
}
if reply != "ok" {
t.Fatalf("reply = %q, want ok", reply)
}
if strings.Contains(lastSystemPrompt(prepared), "<memory ") {
t.Fatalf("prompt has a memory block despite a failing engine, prompt = %q", lastSystemPrompt(prepared))
}
}
// TestTurnMemoryPanickingEngineDegradesSilently is acceptance criterion 6
// (the panic half): a panicking engine/provider completes the turn with no
// memory block and no surfaced error or crash.
func TestTurnMemoryPanickingEngineDegradesSilently(t *testing.T) {
runner, prepared := newMemoryTestRunner(t, panickingMemoryStore{}, telegramIdentity, "archie")
reply, err := runner.Run(context.Background(), chatMsg("s1", "chat-1", "alice", "hi"), nil)
if err != nil {
t.Fatalf("Run() error = %v, want turn to complete despite the engine panic", err)
}
if reply != "ok" {
t.Fatalf("reply = %q, want ok", reply)
}
if strings.Contains(lastSystemPrompt(prepared), "<memory ") {
t.Fatalf("prompt has a memory block despite a panicking engine, prompt = %q", lastSystemPrompt(prepared))
}
}
// TestTurnMemoryNoResolvableUserGetsGlobalAndAgentOnly is acceptance
// criterion 7 (the fail-closed half): a channel whose UserIdentity resolver
// is nil (the dashboard/"web" channel) renders only global and agent scopes,
// never a user-scoped or agent-user record.
func TestTurnMemoryNoResolvableUserGetsGlobalAndAgentOnly(t *testing.T) {
engine := newMemoryTestEngine(t)
ctx := context.Background()
if _, err := engine.Create(ctx, domainmemory.NewRecord{
Scope: domainmemory.Scope{Kind: domainmemory.ScopeAgent, Agent: "archie"}, Kind: "note",
Content: "agent-scope fact", Author: "test",
}); err != nil {
t.Fatalf("Create(agent) error = %v", err)
}
if _, err := engine.Create(ctx, domainmemory.NewRecord{
Scope: domainmemory.Scope{Kind: domainmemory.ScopeGlobal}, Kind: "note",
Content: "global-scope fact", Author: "test",
}); err != nil {
t.Fatalf("Create(global) error = %v", err)
}
if _, err := engine.Create(ctx, domainmemory.NewRecord{
Scope: domainmemory.Scope{Kind: domainmemory.ScopeUser, User: "webhook-user"}, Kind: "note",
Content: "user-scope fact that must never leak to a resolverless channel", Author: "test",
}); err != nil {
t.Fatalf("Create(user) error = %v", err)
}
// nil UserIdentity: exactly what the dashboard/"web" channel wires.
runner, prepared := newMemoryTestRunner(t, engine, nil, "archie")
msg := chatMsg("s1", "chat-1", "webhook-user", "hi")
if _, err := runner.Run(ctx, msg, nil); err != nil {
t.Fatalf("Run() error = %v", err)
}
prompt := lastSystemPrompt(prepared)
if !strings.Contains(prompt, "agent-scope fact") || !strings.Contains(prompt, "global-scope fact") {
t.Fatalf("prompt missing agent/global scope facts, prompt = %q", prompt)
}
if strings.Contains(prompt, "user-scope fact that must never leak") {
t.Fatalf("prompt leaked a user-scope record despite no resolvable user identity, prompt = %q", prompt)
}
}
// TestRenderMemoryRecordsCapsLoudly is acceptance criterion 8's read-side
// analogue: a set of records whose rendering would exceed the byte cap is
// bounded, not silently corrupted -- some records are dropped and a warning
// is logged, rather than the block being cut off mid-line.
func TestRenderMemoryRecordsCapsLoudly(t *testing.T) {
var records []domainmemory.Record
for i := range 500 {
records = append(records, domainmemory.Record{
ID: domainmemory.RecordID(fmt.Sprintf("rec-%d", i)),
Scope: domainmemory.Scope{Kind: domainmemory.ScopeGlobal},
Kind: "note",
Content: strings.Repeat("x", 100),
})
}
var logged strings.Builder
log := slog.New(slog.NewTextHandler(&logged, nil))
got := renderMemoryRecords(records, log)
if len(got) > memoryBlockByteCap {
t.Fatalf("rendered block = %d bytes, want <= %d", len(got), memoryBlockByteCap)
}
if !strings.Contains(logged.String(), "exceeded its render cap") {
t.Fatalf("expected a loud log line on cap overflow, got %q", logged.String())
}
// Every rendered line must be complete: no record content cut off
// mid-line, which would be silent corruption rather than a bounded drop.
for line := range strings.SplitSeq(got, "\n") {
if line == "" {
continue
}
if !strings.HasSuffix(line, strings.Repeat("x", 100)) {
t.Fatalf("rendered line looks truncated mid-record: %q", line)
}
}
}
// TestRenderMemoryNilStoreIsANoOp guards the nil-engine composition case
// (setupMemoryEngine failed or was never reached): a nil MemoryEngine must
// not panic prepareTurn.
func TestRenderMemoryNilStoreIsANoOp(t *testing.T) {
got := renderMemory(context.Background(), nil, domainmemory.Subject{AgentID: "archie"}, slog.New(slog.DiscardHandler))
if got != "" {
t.Fatalf("renderMemory(nil store) = %q, want empty", got)
}
}