diff --git a/.planning/phases/31-chat-polish-against-wavepath-clients/31-RESEARCH.md b/.planning/phases/31-chat-polish-against-wavepath-clients/31-RESEARCH.md new file mode 100644 index 00000000..e29d68da --- /dev/null +++ b/.planning/phases/31-chat-polish-against-wavepath-clients/31-RESEARCH.md @@ -0,0 +1,1070 @@ +# Phase 31: Chat polish against WavePath clients - Research + +**Researched:** 2026-11-13 +**Domain:** PHP-to-Go API parity (tide record and replay), WinterCMS community plugins, Centrifugo, LiveKit, web push +**Confidence:** MEDIUM (code facts are HIGH; everything that needs a running PHP stack is not observed, because this research started no server) + +Provenance tags used below: `[VERIFIED: path:lines]` means the file was opened with Read in this session and the value is quoted. `[SHELL: path]` means the lines were printed with a shell command in this session (seen, but not through Read; treat as strong evidence, re-open before copying a value into code). `[ASSUMED]` means not checked. + + +## User Constraints (from CONTEXT.md) + +### Locked Decisions + +#### Replay target and paths +- **D-01:** **Recorded `/_wave` requests replay unchanged against `/_wave` routes served by Go.** A Go app mounts the seven plugins and an in-repo `wavepath` app plugin registers the recorded paths as aliases over the plugin services. `tide` gets no path-rewrite feature, and the plugin test hosts get no `/_wave` aliases. This is the "thin aliases" route that P19 D-07 and P19.1 D-05 left open for the WavePath port. +- **D-02:** **The app is a new sibling repo, `sm-wavepath-app`,** laid out like `fonoteka.go`: `summer.yaml`, shared plugins as git submodules at `plugins/golem15/`, the app plugin in-repo, `parity/` with the manifest, fixtures, capture rules and broadcast goldens, a `replace` of the framework to `../summercms.go` during development. WavePath's own agent later grows the same repo for the rest of the app port. — **Reversibility:** costly — the repo name, module path and `parity/` layout are what WavePath's agent and every later WavePath phase build on. +- **D-03:** **The app plugin ports whatever the recorded routes need, not only aliases.** That includes the controller logic of WavePath's community controllers and the host seams: the channel and forum access resolvers, the bot auth resolver, the herald profile and presence gate, the notification dispatch, the group context adapter and the group lifecycle wiring (a created group spawns its chat and channels, a deleted group ends video and removes the forum context). Routes outside the corpus stay unported. +- **D-04:** **One named scenario, seeded on both sides.** The scenario (users in each role, groups, channels, conversations, an existing thread, pins, a call link, forum content, friendships, a bot, a guest) is defined once. A PHP reset script seeds it into the local WavePath database, and a Go fixture plugin in `sm-wavepath-app` seeds the same rows into Postgres, as `fonoteka.go/parity` does with `fonoteka_reset.php` and `fixtureplugin`. `summer import:winter` is not used here. + +#### Recording source and timing +- **D-05:** **Phase 31 does not depend on Phase 30.** The user: "phase 30 was meant for plytarium cutover, wavepath is totally separate project". The roadmap dependency was sequencing only. +- **D-06:** **Record now, re-record before the WavePath freeze.** The corpus is recorded from today's PHP and Go is fixed against it. Shortly before the WavePath cutover the whole corpus is re-recorded with a drift report and each drift is resolved (the Phase 30 D-12 pattern). That re-record belongs to the WavePath cutover phase. Phase 31 must leave it runnable unattended. +- **D-07:** **Proxy once, then scripted specs.** The three real clients run through `summer parity:proxy` once to learn the exact requests, headers and bodies they send. Those sessions become committed spec flows that `summer parity:record` re-runs without a person. +- **D-08:** **The PHP backend is the local checkout at `/media/nvme/dev/jz/wavepath.org`,** brought up by a script this phase delivers: the PHP server, its database with the D-04 scenario, Centrifugo pointed at the `tide` recorder, and LiveKit and the push service answered by the `tide` upstream proxy. Nothing is committed in `wavepath.org`. The reset script and the env overlay live in `sm-wavepath-app/parity` and are applied from outside. The phase may check the PHP submodules out at the commits the repo pins and may write to the local dev database. + +#### Corpus boundary +- **D-09:** **The corpus is WavePath's community surface, about 190 routes:** + - everything under `/_wave/api/v1/community`: `groups` (108 routes, group administration included), `dm`, `threads`, `prefs`, `forums`, `friends`, `notes`, `status`, `join`, `presence`, `call-links`, `call-guest`; + - `/_wave/api/v1/guest/*` (call-link knock, guest session, guest thread and reactions); + - `/_wave/api/v1/push/*`; + - the bot and token routes under `/api/v1` (`conversations`, `conversations/{id}/messages`, `realtime/token`) and the `/hooks/{token}` webhook. + + The researcher re-counts from `routes.php` at the recording commit and lists any route under these prefixes that no client calls. +- **D-10:** **Every publication of every writing step is asserted.** Each corpus step that writes gets a broadcast golden with all publications PHP sent for it, on any namespace (`chat`, `video`, `presence:`, `user`, `wave`). Channel authorization (the Centrifugo subscribe proxy and `realtime/token`) is replayed as ordinary routes. +- **D-11:** **Case depth is client paths plus denials.** Per route: + - the cases the clients produced in the proxy sessions; + - one denial per access rule (unauthenticated 401, non-member 403 or 404); + - the validation errors the UI can trigger (422); + - one 429 case per named rate bucket. + + Outbound LiveKit and web-push calls are recorded as `tide` upstream sidecars and asserted on replay. + +#### Drift and fix policy +- **D-12:** **The port contract is re-frozen at the recording commit.** It replaces the commits in P19 D-01 and P19.1 D-01. The WavePath commit and its pinned submodule commits are written into the manifest. Every delta since the old freeze that the corpus exercises is ported in this phase: into the shared Go plugin when the PHP change is in a shared plugin (chat `943b712..fbfbcf9`, attachment streaming with Range support), into the app plugin when it is in `wavepath` (guest threads and guest identity). — **Reversibility:** costly — names and shapes from the new freeze are copied into every app that mounts the shared plugins. +- **D-13:** **Go reproduces PHP's observable behaviour, quirks included.** The one exception is a security defect (data reaching a non-member, a missing access check): Go keeps the safe behaviour, and the case goes into an accepted-differences file with its reason. The user signs off each entry. Precedent: the Phase 19.5 email-proof divergence. +- **D-14:** **The PHP shape wins in the shared plugins; consumers follow.** A parity fix corrects the shared serializer or behaviour itself, so the generic `/_x/api/v1` APIs and the `/_wave` aliases keep one serializer set. Each changed plugin gets a patch tag and a changelog post on `/changelog/plugins`, and `sm-demo-app` and the vue layers are updated in this phase. A renamed or removed field is called out in the release notes. The user's condition: "1 is fine as long as sm-bm-app keeps working". Before any plugin tag, `sm-bm-app` (mounts chat, chatchannels and chatbots, with its own frontend) must build with the new plugin commits, pass its tests (`chat_test.go`, `realtime_test.go`), and have its frontend checked against any renamed or removed field. — **Reversibility:** costly — a changed field in a published plugin API reaches every mounting app and vue layer. +- **D-15:** **The phase closes at zero pending.** Every corpus route is `ported` with passing cases, every broadcast golden is asserted, and the only non-matching cases are signed entries in the accepted-differences file. A fail-closed gate script checks this, and checks that `sm-bm-app` and `sm-demo-app` build and pass. The gate lives in `sm-wavepath-app`, because a script in `summercms.go` would name an application. + +#### Folded Todos +- **Record PHP OIDC parity against WavePath before the OIDC cutover** (`2026-10-19-record-php-oidc-parity-against-wavepath.md`, `sm-oauthserver-plugin`). Phase 19.4 shipped the harness but never recorded PHP. The local WavePath stack from D-08 is exactly what the todo's runbook needs, so the recording is done here: follow `../sm-oauthserver-plugin/testdata/parity/README.md` until `PHASE194_REQUIRE_PARITY=1 go test -run '^(TestPHPParityReplay|TestIDTokenShapeParity)$' ./...` passes. It is separate from the community corpus and lives in the plugin repo. +- **Chat messages that start with "/" but name no command are posted as text** (`chat-slash-text-escape.md`, `../vue-chat-layer/app/composables/useChat.ts`). Every text starting with "/" is dispatched as a command and refused. Fix in the layer: dispatch only when the first token is a known trigger from the command catalog, or support a "//" escape. The researcher first checks what `vue-wavepath-app` and the PHP command controller do with such text and matches that. +- **Moderate profile names, friend-group names and chat attachment filenames** (`moderation-profile-group-and-filenames.md`, `../sm-demo-app/plugins/demo/moderation.go`). The demo's filter covers only message content and forum text. Add the checks through additive seams (a user-plugin saving event, a group saving seam in userfriends, filenames on chat's message-saving event). The seams are additive and must leave PHP parity untouched: with no listener, behaviour is unchanged. + +### Claude's Discretion +- Go package, type and route-handler names in the app plugin, and the layout inside `parity/`. +- The scenario's exact rows, as long as every access rule in D-11 has a user on each side of it. +- How the PHP reset script is run against the checkout without committing there (artisan tinker, a script path, a mounted file). +- The name of the gate script and of the accepted-differences file. +- Whether `tide` needs additions (for example more broadcast normalisation rules for chat payloads). Any such change is generic, documented in `modules/tide/README.md` and names no application. +- The module path and git remote of `sm-wavepath-app`. Creating a remote and pushing need the user's go-ahead. +- Plan count and split, subject to the plan-count checkpoint and "unit tests are the last plan". This is a large phase; say so at the checkpoint and propose a split into decimal phases if the count gets unwieldy. +- Run the security-review agent: the app plugin adds guest access, bot and token authentication, a webhook and access resolvers. + +### Deferred Ideas (OUT OF SCOPE) +- The pre-freeze re-record with a drift report: a task of the WavePath cutover phase (D-06). +- The rest of WavePath's backend and the MariaDB to Postgres import: later WavePath phases, owned with WavePath's agent. +- `electron-wavepath` and `tauri-wavepath-desktop` as recording clients: with the full-surface corpus at the cutover. +- A manual session of the real clients against the Go app: not required to close this phase (D-15); belongs to the cutover. +- Reviewed todos, not folded: the WinterCMS vs SummerCMS benchmark, gate scripts that name applications, changelog previous/next links, the forum and friends 401 refresh, MailBlocker, the menu plugin port, the first password for social accounts, README `src=` fences, the fonoteka README and the translate messages editor. + + + +## Phase Requirements + +No requirement IDs are mapped to this phase (the roadmap says TBD). The four success criteria are used as the requirement set in the Validation Architecture below. + +| ID | Description | Research Support | +|----|-------------|------------------| +| SC-1 | The community corpus (D-09), recorded from PHP through the clients, replays green against Go | Sections "Corpus", "Gap map", "tide readiness", "PHP stack" | +| SC-2 | Every publication of every writing step matches the PHP broadcasts (D-10) | "tide readiness" items T-2, T-3, T-9; "Realtime surface" | +| SC-3 | Neutral to other consumers; `sm-bm-app` and `sm-demo-app` build and pass with the released plugins (D-14, D-15) | "Consumer gate" | +| SC-4 | New code has unit tests, in the last plan | "Validation Architecture" | + + +## Summary + +The corpus is **194 routes** in `routes.php` plus 2 realtime routes of the websockets plugin (196 tracked). 177 are called by the clients, 17 are not. `wavepath-mcp` calls none of them: its ten calls all go to `/api/v1/diary`, `practices`, `trainings`, `stats`, `me` and `state`, which D-09 leaves out. The corpus is recorded from two clients (the SPA with its service worker, and `hubot-wavepath`), not three. + +"Thin aliases" understates the work. The `/_wave` handlers in PHP are host controllers that call the shared plugins and then merge a large host layer on top: 10.8k lines of community controllers, about 4.4k lines of host services, 1.5k lines of guest code, 1.1k of notification code and 0.7k of video service. The seven Go plugins cover the plugin half (models, services, access seams) well. The app plugin has to port the host half, about 19k lines of PHP including comments, with around 15 host tables. Fonoteka's 154 routes took three phases (12, 13, 14). This phase is the same order of size and should be split into decimal phases. + +`tide` covers the mechanics, but ten gaps block a green replay of this corpus. Three are hard blockers: relative-time strings (`created_at_human`) are compared exactly, broadcast goldens are recorded one step per CLI run, and upstream sidecars cannot hold LiveKit or web-push calls (per-request signed `Authorization`, encrypted or binary bodies). All ten can be closed with generic additions that name no application. + +Of the old freeze, only chat moved (`943b712..fbfbcf9`, two commits). The other six shared plugins are pinned at exactly the P19 and P19.1 commits. The `wavepath` plugin was never frozen before, so its whole community surface is new port work. + +**Primary recommendation:** split into three decimal phases (corpus and harness, messaging, satellites and close-out), close the tide gaps first, record the whole corpus from an isolated MariaDB-backed PHP instance in one unattended run, then port by controller family until the manifest has zero pending. + +## Architectural Responsibility Map + +| Capability | Primary Tier | Secondary Tier | Rationale | +|------------|-------------|----------------|-----------| +| `/_wave` community routes, envelope, gates | API (app plugin `golem15.wavepath` in `sm-wavepath-app`) | Shared plugin services | PHP keeps this logic in host controllers; plugins stay host-blind (D-01, D-03) | +| Messages, channels, threads, pins, mentions | API (sm-chat-plugin, sm-chatchannels-plugin) | App plugin row decoration | Shared serializer is the base row; host extras are merged by the app | +| Reactions, unfurl cards, emoji, webhooks, user status, guest identity | API (app plugin) | Database (host tables) | PHP stores these in `golem15_wavepath_*` tables, outside the shared plugins | +| Realtime publish and channel authorization | API (lighthouse + plugin authorizers) | App plugin (`wave`, `presence:` namespaces) | Namespaces `chat`, `video`, `user` come from plugins; `wave` and presence are host | +| Video rooms, guest admission | API (sm-chatvideo-plugin + app plugin) | External (LiveKit) | The plugin owns LiveKit and sessions; call cards, channel calls and guests are host logic | +| Web push | API (sm-herald-plugin sender) | App plugin (profile, presence gate, dispatch) | Vocabulary and recipient selection are host seams | +| Recording and replay | Tooling (`tide`, `summer parity:*`) | App repo `parity/` | Framework tooling stays generic; corpus and gate live in the app | +| Scenario data | Database (MariaDB for PHP, Postgres for Go) | — | One scenario, two seeders (D-04) | + +## Corpus (task 1) + +### Recording commit and pins + +| Repo | Commit | Notes | +|------|--------|-------| +| `wavepath.org` (superproject) | `7c517191879cada7bb50ac05f474f3ac02ad4b98` | "Bump chat, journal, pgstripe", 2026-11-13. Working tree has uncommitted `.planning/config.json` and two submodule checkouts behind their pins (`chat`, `journal`) | +| `plugins/golem15/wavepath` | `a08ed0a34d1af72314a3453bb25593c6a1660056` | Working tree clean and at the pin. `routes.php` is 1087 lines | +| `plugins/golem15/chat` | pin `fbfbcf98e3392269c6e98801270669dc5d845b3b` | **Working tree is at `943b712a64e9`** (two commits behind). Must be checked out at the pin before recording (D-08 allows it) | +| `plugins/golem15/chatchannels` | `b92fb42a1492` | Same as P19 D-01 | +| `plugins/golem15/chatbots` | `1ecf8c8bb6b8` | Same as P19.1 D-01 | +| `plugins/golem15/chatvideo` | `25135b46c157` | Same as P19.1 D-01 | +| `plugins/golem15/forum` | `ad10b54eb7be` | Same as P19.1 D-01 | +| `plugins/golem15/herald` | `a749f83912a7` | Same as P19.1 D-01 | +| `plugins/golem15/userfriends` | `182b5145561f` | Same as P19.1 D-01 | +| `plugins/golem15/user` | `d4f779b4633f` | | +| `plugins/golem15/websockets` | `00b95affb503` | Owns `/api/realtime/token` and `/api/realtime/subscribe` | +| `plugins/golem15/oauthserver` | `9beac91fae3a` | For the folded OIDC todo | +| `plugins/golem15/journal` | pin `92c237a5670c` | Working tree at `3fa3bf75baa9`; not in the corpus, but the app boots it | +| `vue-wavepath-app` | `5d4541b` | Clean, at the pin | +| `wavepath-mcp` | `28c6539` | Clean, at the pin | +| `hubot-wavepath` | `b545869` | Clean, at the pin | + +Source: `git -C /media/nvme/dev/jz/wavepath.org rev-parse HEAD`, `git ls-tree HEAD plugins/golem15/`, `git submodule status` (this session). The wavepath commit in the manifest must be the submodule commit `a08ed0a`, together with the superproject commit. + +### Count + +194 routes under the D-09 prefixes, out of 273 `Route::` verbs in the file. `[VERIFIED: /media/nvme/dev/jz/wavepath.org/plugins/golem15/wavepath/routes.php:221-249, 515-937, 1021-1055, 1072-1078]` (read in full; counted with a parser over `git show a08ed0a:routes.php`). + +| Prefix | Routes | Auth group (manifest name suggested) | +|--------|-------:|--------------------------------------| +| `/_wave/api/v1/community/groups` | 108 | `jwt` (cookie JWT, `jwt.auth`) | +| `/_wave/api/v1/community/dm` | 16 | `jwt` | +| `/_wave/api/v1/community/forums` | 16 | `jwt` | +| `/_wave/api/v1/community/notes` | 16 | `jwt` | +| `/_wave/api/v1/community/friends` | 8 | `jwt` | +| `/_wave/api/v1/community/status` | 3 | `jwt` | +| `/_wave/api/v1/community/join` | 2 | `jwt` | +| `/_wave/api/v1/community/presence` | 2 | `jwt` | +| `/_wave/api/v1/community/threads` | 1 | `jwt` | +| `/_wave/api/v1/community/prefs` | 1 | `jwt` | +| `/_wave/api/v1/community/call-links` | 1 | `jwt` | +| `/_wave/api/v1/community/call-guest` | 1 | `jwt` | +| `/_wave/api/v1/push` | 4 | `jwt` | +| `/_wave/api/v1/guest` | 10 | `guest` (2 public with a code, 8 behind the `wave_guest` cookie) | +| `/api/v1` (bot) | 4 | `bot` (`wave_` bearer token, scope `chat:bot`) | +| `/hooks` | 1 | `webhook` (URL token is the only credential) | +| **Total** | **194** | | + +Two extra tracked routes for D-10, outside `routes.php` (the fonoteka corpus tracks the same pair as "realtime" extras): `GET /api/realtime/token` and `POST /api/realtime/subscribe` (websockets plugin; lighthouse serves the same default paths `[SHELL: modules/lighthouse/README.md:231-232]`). **196 tracked routes.** + +Group middleware, quoted from the file: +- guest: `['prefix' => '/_wave/api/v1/guest', 'middleware' => ['bindings']]` (line 222). No `throttle:wave-api` on this group. +- jwt: `['prefix' => '/_wave/api/v1', 'middleware' => ['jwt.auth', 'bindings', 'throttle:wave-api']]` (line 252). +- bot: `['prefix' => '/api/v1', 'middleware' => ['bindings', 'throttle:wave-api-bot']]` (line 1022), each route `->middleware('wave.scope.public:chat:bot')`. +- webhook: `['prefix' => '/hooks', 'middleware' => ['bindings', 'throttle:wave-webhook']]` (line 1073). + +### Rate buckets in the corpus + +`[VERIFIED: routes.php:60-186]` + +| Bucket | Limit | Key | Requests for the 429 case | +|--------|-------|-----|---------------------------| +| `wave-api` | 240/min | user id, else IP | 241 | +| `community-join` | 10/min | user id, else IP | 11 | +| `call-link` | 10/min | user id, else IP | 11 | +| `call-guest-resolve` | 10/min per IP (`cgr-ip:`) and 30/min per link hash (`cgr-link:`) | two limits | 11 | +| `call-guest-entry` | 5/min per IP (`cg-ip:`) and 10/min per link hash (`cg-link:`) | two limits | 6 | +| `call-guest-session` | 120/min | `cg-sess:` + guest session id, else IP | 121 | +| `call-guest-send` | 20/min | `cg-send:` + guest session id, else IP | 21 | +| `presence-state` | 30/min | user id, else IP | 31 | +| `wave-api-bot` | 300/min | `bot:` + token id, else IP | 301 | +| `wave-webhook` | 60/min | `wh:` + webhook id, else `wh-ip:` + IP | 61 | + +Ten buckets, so ten 429 cases (D-11). `wave-api-token` (60/min) belongs to the human token routes, which are outside the corpus. Stacked buckets on top of `wave-api`: `community-join` on 4 routes, `presence-state` on 2, `call-link` on 1, `call-guest-entry` on 1. + +Name collision to resolve at plan time: the Go plugins already define buckets named `community-join` (sm-userfriends-plugin, 10/min) and `call-link` (sm-chatvideo-plugin, 10/min) `[SHELL: sm-userfriends-plugin/routes.go:22,85; sm-chatvideo-plugin/routes.go:24,63]`. The app plugin either reuses them or registers its own names; if surf bucket names are global, two definitions of one name will conflict `[ASSUMED]`. + +### Route table + +One line per route: method, path below `/_wave/api/v1/` (bot and webhook paths are absolute), PHP action, extra throttle, line in `routes.php`. Every `community/*` and `push/*` route also carries `jwt.auth` and `throttle:wave-api`. + +**GuestCallController** (10; all but the first two also carry `wave.guest`) +- `GET guest/call-links/{code}` → resolve +call-guest-resolve (L224) +- `POST guest/call-links/{code}/knock` → knock +call-guest-entry (L227) +- `GET guest/session` → session +call-guest-session (L230) +- `POST guest/session/knock-again` → knockAgain +call-guest-session (L232) +- `POST guest/session/join` → join +call-guest-session (L234) +- `POST guest/session/leave` → leave +call-guest-session (L236) +- `GET guest/thread` → thread +call-guest-session (L238) +- `POST guest/thread` → send +call-guest-send (L240) +- `POST guest/thread/{messageId}/reactions` → react +call-guest-session (L242) +- `DELETE guest/thread/{messageId}/reactions` → unreact +call-guest-session (L245) + +**CommunityGroupController** (9) +- `GET community/groups` → index (L519) +- `POST community/groups` → store (L520) +- `GET community/groups/{id}` → show (L521) +- `PUT community/groups/{id}` → update (L522) +- `DELETE community/groups/{id}` → destroy (L523) +- `POST community/groups/{id}/image` → uploadImage (L524) +- `POST community/groups/{id}/join` → joinOpen +community-join (L525) +- `GET community/join/{code}` → preview +community-join (L561) +- `POST community/join/{code}` → join +community-join (L562) + +**CommunityMemberController** (12) +- `GET community/groups/{id}/members` → index (L527) +- `POST community/groups/{id}/members` → add (L530) +- `GET community/groups/{id}/banned` → banned (L531) +- `POST community/groups/{id}/leave` → leave (L532) +- `DELETE community/groups/{id}/members/{userId}` → kick (L533) +- `POST community/groups/{id}/members/{userId}/ban` → ban (L534) +- `POST community/groups/{id}/members/{userId}/unban` → unban (L535) +- `POST community/groups/{id}/members/{userId}/promote` → promote (L536) +- `POST community/groups/{id}/members/{userId}/demote` → demote (L537) +- `POST community/groups/{id}/members/{userId}/transfer` → transfer (L538) +- `POST community/groups/{id}/members/{userId}/bot` → flagBot (L541) +- `DELETE community/groups/{id}/members/{userId}/bot` → unflagBot (L542) + +**CommunityInviteController** (5) +- `GET community/groups/{id}/invite` → show (L544) +- `POST community/groups/{id}/invite` → mint (L545) +- `POST community/groups/{id}/invite/rotate` → rotate (L546) +- `POST community/groups/{id}/invite/custom` → setCustom (L547) +- `DELETE community/groups/{id}/invite` → revoke (L548) + +**CommunityWebhookController** (5) +- `GET community/groups/{id}/webhooks` → index (L555) +- `POST community/groups/{id}/webhooks` → store (L556) +- `PUT community/groups/{id}/webhooks/{webhookId}` → update (L557) +- `POST community/groups/{id}/webhooks/{webhookId}/regenerate` → regenerate (L558) +- `DELETE community/groups/{id}/webhooks/{webhookId}` → destroy (L559) + +**CommunityChatController** (15) +- `GET community/groups/{id}/messages` → messages (L569) +- `POST community/groups/{id}/messages` → send (L570) +- `DELETE community/groups/{id}/messages/{messageId}` → deleteMessage (L571) +- `PATCH community/groups/{id}/messages/{messageId}` → editMessage (L572) +- `POST community/groups/{id}/read` → read (L573) +- `POST community/groups/{id}/typing` → typing (L574) +- `POST community/groups/{id}/mute` → mute (L575) +- `DELETE community/groups/{id}/mute` → unmute (L576) +- `POST community/groups/{id}/attachments` → uploadAttachment (L577) +- `GET community/groups/{id}/attachments/{messageId}/{fileId}` → downloadAttachment (L578) +- `GET community/groups/{id}/attachments/{messageId}/unfurl/{kind}` → unfurlImage (L586) +- `GET community/groups/{id}/attachments/{messageId}/webhook-icon` → webhookIcon (L594) +- `POST community/groups/{id}/messages/{messageId}/reactions` → addReaction (L599) +- `DELETE community/groups/{id}/messages/{messageId}/reactions` → removeReaction (L600) +- `GET community/groups/{id}/messages/{messageId}/replies` → threadReplies (L607) + +**CommunityFriendsController** (8) +- `GET community/friends` → index (L616) +- `GET community/friends/requests` → requests (L617) +- `GET community/friends/sent` → sent (L620) +- `POST community/friends/request` → sendRequest +community-join (L621) +- `POST community/friends/requests/{id}/accept` → accept (L622) +- `DELETE community/friends/requests/{id}` → reject (L623) +- `DELETE community/friends/sent/{id}` → cancel (L626) +- `DELETE community/friends/{userId}` → unfriend (L630) + +**CommunityDmController** (14) +- `POST community/dm` → start (L639) +- `GET community/dm` → inbox (L640) +- `GET community/dm/{convId}/messages` → messages (L641) +- `POST community/dm/{convId}/messages` → send (L642) +- `PATCH community/dm/{convId}/messages/{messageId}` → editMessage (L643) +- `POST community/dm/{convId}/read` → read (L644) +- `POST community/dm/{convId}/typing` → typing (L645) +- `PUT community/dm/{convId}/mute` → setMute (L649) +- `POST community/dm/{convId}/messages/{messageId}/reactions` → addReaction (L663) +- `DELETE community/dm/{convId}/messages/{messageId}/reactions` → removeReaction (L664) +- `GET community/dm/{convId}/messages/{messageId}/replies` → threadReplies (L668) +- `POST community/dm/{convId}/attachments` → uploadAttachment (L669) +- `GET community/dm/{convId}/attachments/{messageId}/{fileId}` → downloadAttachment (L670) +- `GET community/dm/{convId}/messages/{messageId}/unfurl-image/{kind}` → unfurlImage (L671) + +**CommunityThreadController** (1), **CommunityPresenceController** (2), **CommunityStatusController** (3), **CommunityPrefsController** (1), **CommunityEmojiController** (3) +- `PUT community/threads/{rootId}/mute` → setMute (L655) +- `GET community/presence` → snapshot (L679) +- `POST community/presence/state` → setState +presence-state (L680) +- `GET community/status` → show (L687) +- `PUT community/status` → update +presence-state (L688) +- `DELETE community/status` → clear (L689) +- `PATCH community/prefs` → update (L696) +- `GET community/groups/{id}/emojis` → list (L700) +- `POST community/groups/{id}/emojis` → upload (L701) +- `DELETE community/groups/{id}/emojis/{emojiId}` → delete (L702) + +**CommunityVideoController** (11) +- `POST community/groups/{id}/video` → start (L706) +- `POST community/groups/{id}/video/join` → join (L707) +- `DELETE community/groups/{id}/video/leave` → leave (L708) +- `POST community/groups/{id}/video/end` → end (L709) +- `GET community/groups/{id}/video` → status (L710) +- `POST community/groups/{id}/channels/{channelId}/video` → startChannel (L815) +- `POST community/groups/{id}/channels/{channelId}/video/join` → joinChannel (L816) +- `DELETE community/groups/{id}/channels/{channelId}/video/leave` → leaveChannel (L817) +- `POST community/groups/{id}/channels/{channelId}/video/end` → endChannel (L818) +- `GET community/groups/{id}/channels/{channelId}/video` → statusChannel (L819) +- `GET community/call-links/{code}` → resolveCallLink +call-link (L841) + +**CommunityForumController** (16) +- `GET community/forums/{groupId}/categories` → categories (L718) +- `POST community/forums/{groupId}/categories` → createCategory (L719) +- `PUT community/forums/{groupId}/categories/{categoryId}` → renameCategory (L720) +- `POST community/forums/{groupId}/categories/reorder` → reorderCategories (L721) +- `DELETE community/forums/{groupId}/categories/{categoryId}` → deleteCategory (L722) +- `GET community/forums/{groupId}/categories/{categoryId}/threads` → threads (L723) +- `POST community/forums/{groupId}/categories/{categoryId}/threads` → createThread (L724) +- `GET community/forums/{groupId}/threads/{threadId}/posts` → posts (L725) +- `POST community/forums/{groupId}/threads/{threadId}/posts` → reply (L726) +- `GET community/forums/{groupId}/threads` → threads (L732) +- `PUT community/forums/{groupId}/posts/{postId}` → editPost (L733) +- `DELETE community/forums/{groupId}/posts/{postId}` → deletePost (L734) +- `DELETE community/forums/{groupId}/threads/{threadId}` → deleteThread (L735) +- `POST community/forums/{groupId}/preview` → preview (L736) +- `POST community/forums/{groupId}/posts/{postId}/reactions` → addReaction (L741) +- `DELETE community/forums/{groupId}/posts/{postId}/reactions` → removeReaction (L742) + +**CommunityChannelController** (39; all under `community/groups/{id}/channels`) +- `GET` (index, L754), `POST` (store, L755) +- `POST categories` (L756), `PUT categories/{categoryId}` (L757), `DELETE categories/{categoryId}` (L758) +- `GET personal-categories` (L762), `POST personal-categories` (L763), `PUT personal-categories/{pcId}` (L764), `DELETE personal-categories/{pcId}` (L765) +- `PUT last-active` (L766) +- `GET {channelId}` (show, L767), `PUT {channelId}` (update, L768), `PUT {channelId}/visibility` (L769) +- `POST {channelId}/archive` (L770), `POST {channelId}/restore` (L771) +- `POST {channelId}/members/{userId}` (L772), `DELETE {channelId}/members/{userId}` (L773) +- `POST {channelId}/read` (L776), `POST {channelId}/favorite` (L777), `DELETE {channelId}/favorite` (L778) +- `POST {channelId}/mute` (L779), `DELETE {channelId}/mute` (L780) +- `POST {channelId}/join` (L781), `POST {channelId}/leave` (L782), `PUT {channelId}/placement` (L783) +- `PUT {channelId}/notify-pref` (L788), `GET {channelId}/members` (L789) +- `GET {channelId}/messages` (L794), `POST {channelId}/messages` (L795), `POST {channelId}/attachments` (L796) +- `POST {channelId}/messages/{messageId}/reactions` (L849), `DELETE …/reactions` (L850) +- `DELETE {channelId}/messages/{messageId}` (L851), `PATCH {channelId}/messages/{messageId}` (L852) +- `GET {channelId}/messages/{messageId}/replies` (L858) +- `POST {channelId}/messages/{messageId}/pin` (L868), `DELETE …/pin` (L869), `GET {channelId}/pins` (L870) +- `GET {channelId}/messages/{messageId}/unfurl-image/{kind}` (L880) + +**CommunityCommandController** (6) +- `POST community/groups/{id}/channels/{channelId}/command` → dispatch (L802) +- `GET community/groups/{id}/channels/{channelId}/commands` → available (L803) +- `POST community/groups/{id}/command` → dispatchGroup (L804) +- `GET community/groups/{id}/commands` → availableGroup (L805) +- `POST community/dm/{convId}/command` → dispatchDm (L806) +- `GET community/dm/{convId}/commands` → availableDm (L807) + +**CommunityCallGuestController** (8) +- `GET community/groups/{id}/channels/{channelId}/video/guest-link` → showLink (L823) +- `PUT …/video/guest-link` → updateLink (L824) +- `GET …/video/guests` → guests (L826) +- `POST …/video/guests/{guestSessionId}/admit` (L827), `…/deny` (L828), `…/remove` (L829) +- `PUT …/video/guests/{guestSessionId}/screen-share` → screenShare (L830) +- `POST community/call-guest/{code}/knock` → knockAsAccount +call-guest-entry (L832) + +**CommunitySearchController** (1) +- `GET community/groups/{id}/search` → search (L890) + +**CommunitySharedNoteController** (16) +- `GET community/notes/public` (L908), `GET …/public/count` (L909), `GET …/public/{id}` (L910) +- `GET community/notes/groups/{groupId}` (L911), `GET …/groups/{groupId}/count` (L912), `GET …/groups/{groupId}/{entryId}` (L913) +- `POST community/notes/{entryId}/share` (L914), `GET …/{entryId}/state` (L915) +- `DELETE …/{entryId}/public` (L916), `DELETE …/{entryId}/groups/{groupId}` (L917), `DELETE …/{entryId}` (L918) +- `GET …/{entryId}` (detail, L920), `POST …/{entryId}/public` (L921), `POST …/{entryId}/groups/{groupId}` (L922), `PUT …/{entryId}/include-flags` (L923), `GET …/{entryId}/share-state` (L924) + +**Push** (4) +- `POST push/subscription` → subscribe (L929), `PATCH push/subscription` → patch (L930), `DELETE push/subscription` → unsubscribe (L931) +- `GET push/vapid-public-key` → closure returning `config('golem15.herald::herald.vapid.public_key')` (L934) + +**Bot and webhook** (5) +- `GET /api/v1/conversations` → BotRestController::conversations (L1025) +- `GET /api/v1/conversations/{id}/messages` → messages (L1028) +- `POST /api/v1/conversations/{id}/messages` → send (L1031) +- `GET /api/v1/realtime/token` → closure, 401 `{"error":"Invalid token"}`, 503 `{"error":"WebSocket not configured"}` (L1041-1053) +- `POST /hooks/{token}` → WebhookIngestController::handle, `{token}` is `[A-Za-z0-9]+` (L1075) + +### Routes that none of the three clients calls (17) + +Method: every `.ts`, `.vue` and `sw.js` under `vue-wavepath-app/src` (tests excluded), `wavepath-mcp/src` and `hubot-wavepath/src` was scanned for request call sites, then the candidates were checked by hand. "Called" means a request-building call site exists in client source. Whether a UI path reaches it is what the D-07 proxy sessions establish. + +| # | Route | Why no client calls it | +|---|-------|------------------------| +| 1 | `PUT community/forums/{g}/categories/{c}` | No call site in `api/forumApi.ts` | +| 2 | `POST community/forums/{g}/categories/reorder` | No call site | +| 3 | `DELETE community/forums/{g}/categories/{c}` | No call site | +| 4 | `POST community/groups/{id}/channels/categories` | No call site. `channelApi.categories` issues a `GET` on this path, for which **no route exists**, and nothing calls that function | +| 5 | `PUT …/channels/categories/{c}` | No call site | +| 6 | `DELETE …/channels/categories/{c}` | No call site | +| 7 | `GET …/channels/{channelId}` | No call site (the SPA only `PUT`s this path) | +| 8 | `POST …/channels/{channelId}/restore` | No call site | +| 9 | `POST …/channels/{channelId}/mute` | `channelApi.mute` is a wrapper over `notify-pref` (`api/channelApi.ts:262`) | +| 10 | `DELETE …/channels/{channelId}/mute` | `channelApi.unmute` is a wrapper over `notify-pref` (`api/channelApi.ts:265`) | +| 11 | `GET community/notes/{entryId}` | `routes.php:919`: "Compatibility routes kept for test suites that use the pre-Plan-04 paths." | +| 12 | `POST community/notes/{entryId}/public` | Same compatibility block | +| 13 | `POST community/notes/{entryId}/groups/{groupId}` | Same compatibility block | +| 14 | `PUT community/notes/{entryId}/include-flags` | Same compatibility block | +| 15 | `GET community/notes/{entryId}/share-state` | Same compatibility block | +| 16 | `POST /hooks/{token}` | Called by outside webhook posters only; the SPA only displays the URL | +| 17 | `GET community/groups/{id}/attachments/{messageId}/webhook-icon` | No client builds this URL. The server emits it as `sender_avatar` of a webhook message, and the browser loads it as an image, so it does appear in a proxy session once the scenario has a webhook message | + +Called: 173 by the SPA (the `PATCH push/subscription` call is in `src/sw.js:136`), 4 by `hubot-wavepath` (`src/rest.mjs`). `wavepath-mcp`: zero `[SHELL: wavepath-mcp/src/client.ts:56-111]`. + +D-11 gives uncalled routes no "client path" cases, but D-15 still requires every corpus route `ported` with passing cases. For these 17 the cases are the denial and validation cases plus one hand-written success case each. Confirm with the user that hand-written success cases are acceptable for uncalled routes, or drop them from the corpus (see Open Questions). + +## Gap map (task 2) + +What the Go shared plugins already provide `[SHELL: classes/*.go and routes.go of each sibling repo]`, and what the app plugin `golem15.wavepath` must port. PHP sizes are line counts of the files at `a08ed0a`. + +Generic rule that follows from the code: the `/_wave` handlers cannot reuse the plugins' `api` handlers, because the envelopes differ. WavePath answers `{"data":…}` on success and `{"error":true,"message":…,"code":…,"errors":…}` on failure, with codes `'VALIDATION_FAILED'`, `'NOT_FOUND'`, `'FORBIDDEN'` `[VERIFIED: /media/nvme/dev/jz/wavepath.org/plugins/golem15/wavepath/classes/responses/ApiResponse.php:9-48]`. The Go chat API writes `{"error":"Validation failed","errors":{…}}`. App handlers call the plugins' `classes` services (looked up with `app.Lookup[*chatclasses.Service]()` and friends, as `sm-demo-app/plugins/demo/chat_api.go` does) and write WavePath's envelope. + +| Route family (routes) | Covered by Go plugin services | The app plugin ports | +|---|---|---| +| Groups, join, members, invites (9+12+5) | `sm-userfriends-plugin` `GroupService`: Create, Update, Delete, Get, List, View, Join, JoinByCode, PreviewByCode, AddMember, Leave, Kick, Ban, Unban, Promote, Demote, Transfer, Members, Banned, Invite, MintInvite, RevokeInvite | Controllers 413+419+184 lines: group summary and detail serializers, roster flags (unclaimed imports, bot badge, status badge), `invite/custom` (no custom-code method exists in the Go service; grep for "custom" in `group_service.go` is empty), group image upload (no image method found), `bot` flag routes over chatbots' BotFlag, `community_mode`. Group lifecycle wiring (below) | +| Friends (8) | `FriendshipService`: Request, Accept, List, Incoming, Sent, Reject, Cancel, Unfriend, AreFriends, ResolveTarget | Controller 350 lines: envelope, avatar and status decoration | +| Group main chat (15) | `sm-chat-plugin` `Service`: GetGroupChat, GetMessages, GetThreadReplies, SendMessage(With), EditMessage, DeleteMessage, MarkAsRead, SendTypingIndicator, ToggleMute, StorePendingAttachment, AttachmentForDownload, MessagesAPI, Emit* | Controller 1076 lines and `CommunityChatService` 560 lines. The row serializer merges onto the shared row: `is_mine`, host `reactions`, `unfurl`, `metadata`, `sender_avatar` (uploaded, then gravatar, then identicon), `is_bot`, webhook identity, guest identity, `root_id`, `parent` preview, four thread-footer fields, tombstone scrub `[VERIFIED: controllers/api/CommunityChatController.php:179-243]`. Collapsed-threads view from the user's `collapsed_threads` column. Group mute (`GroupChatMute` model). Unfurl and webhook-icon serving | +| Channels (39) | `sm-chatchannels-plugin` `ChannelService` (about 55 methods: channels, categories, personal categories, prefs, placement, notify-pref, last-active, members, visibility, archive, pins, mentions) | Controller 2270 lines (the largest): gates with 404 collapse, channel list with unread and mention counts, per-channel messages, send, edit, delete, reactions, replies, pins with previews, attachments | +| DM (14) and thread mute (1) | `Service.GetOrCreateDm` is context-scoped; WavePath DMs are global and friendship-gated. `MuteThread` exists | Controller 1054 lines and `CommunityDmService` 198 lines: global (context-null) DM start and inbox, participant gate with a single 404, the rich surface. `ThreadSubscription` (host table) for thread follow and mute: decide whether it maps onto chat's `ThreadMute` or stays a host table | +| Commands (6) | `sm-chatbots-plugin` `Dispatcher.Dispatch`, `Registry.Catalog` | Controller 332 lines: three surface gates, `unknown_command` 422, `GroupForbiddenException` to 403, the `/kick` command (108 lines) | +| Reactions (chat and forum, 8 routes) | Chat has its own additive reactions (`golem15_chat_reactions`, shape `{key,count,user_ids}`) | **Different in PHP**: reactions are a host model in `golem15_wavepath_reactions`, polymorphic over chat messages and forum posts `[VERIFIED: Plugin.php:339-356]`, summary shape `{emoji,count,reacted,users}` `[SHELL: classes/services/ReactionService.php:56]`. Port the host model and `ReactionService` (109 lines); do not map onto the chat plugin's reactions (table names are binding for the later import) | +| Emoji (3), prefs (1), status (3), presence (2) | — | Controllers 154+61+181+124 lines, `PresenceService` 175 lines, `UserStatusBadge`, models `CustomEmoji`, `UserStatus`. Presence reads Centrifugo's presence API and publishes on `presence:wave:group:{id}` | +| Search (1) | `sm-chatchannels-plugin` indexer over `beachcomber`; generic `Search` handler | Controller 109 lines and `MessageSearchService` 289 lines (visible-channel allow-list, `in:` and `from:` operators). Needs a search backend on both sides (see pitfalls) | +| Video (11) | `sm-chatvideo-plugin` `VideoService`: Start, Join, Leave, End, Status, CallLink, Reconcile; LiveKit client through fetchguard | Controller 493 lines and host `CommunityVideoService` 719 lines: channel calls, in-chat call card, `channel_id` in `video:*` signals, room-full, `CallNotifier` 271 lines (incoming-call push) | +| Guest calls (10 + 8) | Nothing (all host) | `GuestCallController` 286, `CommunityCallGuestController` 358, `classes/guest/*` 1507 lines (service, cookie, identity, LiveKit gateway, thread service, user factory, purge listener), middleware `WaveGuestSession`, models `CallGuestLink`, `CallGuestSession`, Turnstile verification, job `KickRemovedGuestJob`, command `wave.purge-call-guests` | +| Forums (16) | `sm-forum-plugin` `ForumService` covers all 14 non-reaction routes, including reorder and preview | Controller 720 lines: gate, serializers, author decoration, the two reaction routes over the host model, `WaveForumAccessResolver` (84 lines) | +| Shared notes (16) | Nothing | Controller 504 lines, `SharedNoteService` 165, `SharedNoteSerializer` 113, model `SharedNoteGroup`. **Needs `DiaryEntry`**, which the phase boundary lists as out of scope. A minimal read model plus fixture rows is required (see Open Questions) | +| Push (4) | `sm-herald-plugin` `SubscriptionService`: Subscribe, Patch, Unsubscribe; sender | Controller 173 lines (SSRF endpoint rule), `WaveHeraldProfile` 217, `WavePresenceGate` 282, `WaveNotificationDispatcher` 302, job `ProcessMessageNotificationsJob` | +| Webhooks: CRUD (5) and ingest (1) | Nothing | 338+185 lines, `SlackPayloadParser` 160, `WebhookChannelResolver` 107, `WebhookIdentity` 184, `WebhookIconProxy` 144, model `Webhook` (HMAC blind index) | +| Bot REST (4) | `sm-chatbots-plugin` `BotAuthResolver` seam | `BotRestController` 205, `BotConversationReach` 130 (added in `a08ed0a`), `WaveBotAuthResolver` 53, the `wave_token` guard (`ApiTokenGuard` 89, `ApiTokenManager` 88, `WaveScopePublic` 47), model `ApiToken`, realtime token for the bot | +| Realtime (2 extra) | lighthouse token and subscribe routes; authorizers for `chat`, `video`, `user` from the plugins | `wave` namespace authorizer (`WaveGroupChannelAuthorizer`) and presence channels | +| Link unfurl (cross-cutting) | Nothing | `UnfurlService` 654, `OgParser` 251, `SafeHttpFetcher` 187, `SsrfGuard` 349, model `LinkUnfurl`, job `ResolveUnfurlJob`, signal `unfurl.resolved`. Go should use `fetchguard` instead of porting `SsrfGuard` | + +### Host seams named in D-03 (all in `Plugin.php` at `a08ed0a`) + +`[VERIFIED: /media/nvme/dev/jz/wavepath.org/plugins/golem15/wavepath/Plugin.php:160-558]` + +| Seam | PHP wiring | Go counterpart | +|------|------------|----------------| +| `wave` channel authorizer | `->register('wave', WaveGroupChannelAuthorizer::class)` (165-166) | `lighthouse.Registry.Register("wave", …)` | +| Group context adapter | `registerAdapter(FriendGroup::class, GroupChatContextAdapter::class)` (179-183) | `chatcontracts.Registry.Add` with the group alias. Check first whether sm-userfriends-plugin already registers a context for groups; a second `Add` for the same alias may be refused `[ASSUMED]` | +| Channel context adapter | `registerAdapter(Channel::class, ChannelChatContextAdapter::class)` (190-194) | `Registry.Add` with `chanmodels.ChannelAlias`, as `sm-demo-app/plugins/demo/chat.go` does | +| Forum access resolver | bind `ForumAccessResolver` (203-206) | `ForumService.SetAccessResolver` | +| Channel access resolver | bind `ChannelAccessResolver` (215-218) | `ChannelService.SetAccessResolver` | +| Bot auth resolver | bind `BotAuthResolver` (228-231) | `chatbots.Plugin.SetBotAuthResolver`. No app wires it today | +| Herald profile, presence gate | bind `HeraldProfile`, `PresenceGate` (243-250) | `herald.Plugin.SetHeraldProfile`, `SetPresenceGate`. No app wires them today | +| Herald endpoint guard | bind `EndpointGuard` (259-262) | No Go contract; the sender uses `fetchguard.PublicOnlyMode`. Compare behaviour on a refused endpoint | +| `/kick` command | `$slashRegistry->register(KickCommand::class)` (294-297) | `botclasses.Registry.Register` | +| Host reactions relation | `Message::extend` and forum `Post::extend` morphMany (343-356) | Host model with a `reactable_type` morph column | +| Notification dispatch | `Message` afterCreate dispatches `ProcessMessageNotificationsJob` on queue `notifications` (376-386) | Listener on `events.MessageCreated` enqueuing a River job | +| Group wind-down | `FriendGroup` beforeDelete: sever sockets, end active video sessions, delete `SharedNoteGroup` rows (403-443) | Listener on `userfriends.GroupDeleted` `[VERIFIED: sm-userfriends-plugin/events/events.go:8-11]`: `"userfriends.GroupCreated"`, `"userfriends.GroupDeleted"`, `"userfriends.MemberJoined"`, `"userfriends.MemberLeft"`. D-03 also names removing the forum context: `ForumService.DeleteContext` | +| New-group seed | `FriendGroup` afterCreate: conversation, then `adoptConversation` with `'name' => 'general'`, `'slug' => 'general'`, `'visibility' => 'public'`, `'is_system' => true`, `'is_default' => true` (459-481) | Listener on `GroupCreated` calling `Service.GetGroupChat` and `ChannelService.AdoptConversation` | +| Member auto-join | `GroupMember` afterCreate calls `onMemberJoined` (487-495) | Listener on `MemberJoined` | +| Guest purge | listen `'golem15.user.deleting'` (552-558) | Listener on `user.Deleting` | + +`sm-demo-app` wires only the context registry, the channel access resolver, the forum context, video call policy and slash commands. It has no listener on the userfriends events and never sets the herald or bot seams `[SHELL: grep over sm-demo-app/plugins/demo]`. These seams therefore have no production consumer yet, and this phase is their first real use. Expect seam defects. + +### User columns the corpus touches + +The PHP host extends the shared user table (`collapsed_threads`, `is_full_member`, handle and status data). The app plugin adds them with a companion migration (DATA-11). `sm-user-plugin` changes only if a recorded route cannot be served otherwise (CONTEXT). The exact column list comes from `wavepath/updates/` at `a08ed0a`; it was not enumerated in this research. + +## Deltas since the old freeze (task 3) + +| Plugin | Old freeze | Pin now | Delta | +|--------|-----------|---------|-------| +| chat | `943b712` | `fbfbcf9` | 2 commits: `75b98b0` "stream attachment responses with Range support", `fbfbcf9` "zero Content-Length on 416 range responses". Files: `classes/AttachmentStreamer.php` (+181), `classes/AttachmentResponse.php` (+41), `controllers/api/ChatApiController.php` (13 lines), `routes.php` (2 lines), `tests/unit/AttachmentStreamerTest.php` (+204) | +| chatchannels, chatbots, chatvideo, forum, herald, userfriends | as P19 and P19.1 | unchanged | **No delta.** Nothing to port in these six for D-12 | +| wavepath | never frozen | `a08ed0a` | Whole community surface. Notable recent work: guest calls (99.1, 2026-10-12, 14 commits), unclaimed-import flags on roster, counts, push and presence (99-05, 2026-10-13), group `community_mode` (`34ba3ff`, 2026-10-15), bot reach (`a08ed0a`, 2026-11-13: `BotConversationReach.php` +130, `BotRestController.php`, `meta.group_ids` for adapter discovery) | +| hubot-wavepath | — | `b545869` | 2026-11-13: "instant conversation discovery + answer post-join messages" | + +### The chat attachment delta in detail + +PHP now answers attachment downloads through `AttachmentStreamer` `[SHELL: git show fbfbcf9:classes/AttachmentStreamer.php]`: +- headers `'Cache-Control' => 'private, no-store, no-cache, must-revalidate, max-age=0'`, `'Accept-Ranges' => 'bytes'`, an explicit `Content-Type` falling back to `'application/octet-stream'`; +- `Content-Disposition` from Symfony's `setContentDisposition` on `basename($filename)` (the RFC 6266 form with `filename*=utf-8''…` for non-ASCII names); +- `Range` and `If-Range` with 206 and 416; auto ETag off, `Last-Modified` on; +- an open-ended range at or past the end (`bytes=-`) answers 416 with `Content-Range: bytes */`, no body and zero `Content-Length`. + +Go today `[VERIFIED: sm-chat-plugin/api/download.go:49-75]`: reads the blob with `bucket.NewReader`, sets `Content-Type`, a hand-built `Content-Disposition` (`disp+"; filename=\""+name+"\""`), `Content-Length`, then `io.Copy`. No `Range`, no `Accept-Ranges`, no `Cache-Control`. + +Port into sm-chat-plugin as an exported streamer in `classes` that the plugin's own handler and the app's group, channel and DM download handlers share (in PHP the WavePath controllers import `Golem15\Chat\Classes\AttachmentStreamer` too `[VERIFIED: CommunityChatController.php:5]`). `blob.Reader` implements `Seek` in the pinned `gocloud.dev v0.46.0` (`blob/blob.go:159`) and `Bucket.NewRangeReader` exists (`blob.go:1027`) `[SHELL: module cache]`. `http.ServeContent` alone will not match PHP: its 416 has a text body, and it answers multi-range requests with `multipart/byteranges`, which Symfony's `BinaryFileResponse` does not `[ASSUMED]`. Write a small single-range handler and let the recorded cases define the edges. This changes the generic `/_chat/api/v1/attachments` route too, so it is a D-14 release (headers only, no field change). + +## tide readiness (task 4) + +### What exists and fits + +- Spec recording, manifest record and replay with resume and batches, pending versus ported status, strict replay over ported routes `[VERIFIED: modules/tide/manifest.go:18-28, 268-319, 459-513]`. `MaxBatch = 15`. +- Loopback recording proxy with sessions, capture rules and variable scrubbing. +- Multipart uploads with a fixed boundary (attachment, emoji and image uploads). +- Fake Centrifugo recorder, broadcast goldens, `NormalizePublications`, `DiffPublications` `[VERIFIED: modules/tide/centrifugo_golden.go:177-238]`. +- Upstream sidecars, asserting fake, CONNECT recording proxy with a parity CA. +- JSON masking of `id`, `*_id`, `*_ids` and `*_at` on replay `[VERIFIED: modules/tide/normalize.go:144-160]`. +- Cookie JWT works on the Go side with no change: the user plugin's guard reads `[]string{"token", "auth_token"}` after the bearer header `[VERIFIED: sm-user-plugin/classes/session_user.go:21]`. + +### Gaps (each fix is generic and names no application) + +| # | Gap | Evidence | Addition | +|---|-----|----------|----------| +| T-1 | **Relative-time strings are compared exactly.** PHP emits `'created_at_human' => $this->created_at->diffForHumans()` on every message row. Only keys ending `_at` (and `checkpoint`) are date-masked, and a `NormalizeRule` can only disable a mask. A seeded message reads "3 weeks ago" today and "5 weeks ago" at the re-record | `[VERIFIED: normalize.go:144-146, 173-184]`; PHP row `[SHELL: git show fbfbcf9:models/Message.php:209]` | Mask keys ending `_human` by shape (non-empty string), or add a mask rule to `NormalizeRule`. **Blocker for every message route** | +| T-2 | **One broadcast golden per CLI run.** `RecordBroadcasts` keeps the publications of one `Step` and runs earlier steps as setup. D-10 needs a golden for every writing case (about 110 writing routes, several cases each) | `[SHELL: modules/tide/centrifugo.go:160-203]` | Broadcast sidecars: let manifest recording run with the recorder attached and write `.broadcasts.yaml` per case (as upstream sidecars do), and give the replay side a helper that compares a case's publications. **Blocker for D-10 at this scale** | +| T-3 | **Broadcast normalisation is album-shaped.** `*_at` is masked only under `$.data.payload.album`, and only `$.data.payload.id` gets the bare `{{id}}`. Chat, video and presence payloads carry `conversation_id`, `sender_id`, `root_id`, `channel_id`, `edited_at`, `read_at` at other paths | `[VERIFIED: centrifugo_golden.go:287-347]` | Mask Carbon and ISO `*_at` values anywhere under `$.data.payload`; keep id masking variable-driven and seed deterministic ids (see pitfalls) | +| T-4 | **Upstream sidecars refuse per-request credentials.** `"Authorization"` is a compared header, and a write is refused unless the value is fully masked by a vars entry. LiveKit calls carry a freshly signed bearer JWT; web push carries `Authorization: vapid t=, k=` | `[VERIFIED: modules/tide/upstream.go:120-128, 635-638, 655-666]` | A declared "minted" credential class: written as a shape placeholder and compared by scheme, with an optional claims comparison for JWTs | +| T-5 | **Upstream bodies are compared as JSON or bytes.** LiveKit bodies are Twirp protobuf with ids inside; web-push bodies are `aes128gcm` ciphertext with a random salt and key, and the PHP library pads to 2820 bytes by default (`automaticPadding = Encryption::MAX_COMPATIBILITY_PAYLOAD_LENGTH`, `= 2820`) `[SHELL: vendor/minishlink/web-push/src/WebPush.php:42, Encryption.php:21]` | — | A body comparer hook on `UpstreamFake` per content type or host (the app supplies a protobuf-aware and a decrypting comparer), plus an "opaque body" mode | +| T-6 | **No cookie capture.** Capture sources are `response.json`, `response.json.query`, `response.header`, `response.query`, `response.location.query`, `response.form`, `request.form`, `request.header`, `request.query`. `response.header` on `Set-Cookie` returns the whole header. The guest credential exists only as the `wave_guest` cookie. The scrubber's cookie pattern knows only `auth_token=` | `[SHELL: modules/tide/variables.go:268-347]`, `[VERIFIED: variables.go:24]` | A `response.cookie` capture source (cookie by name), and cookie-value detection that is not tied to one cookie name | +| T-7 | **Recorded and compared response headers are fixed lists** without `Accept-Ranges`, `Content-Range`, `Content-Length`, `Last-Modified`, `Retry-After`, `X-RateLimit-*` | `[VERIFIED: modules/tide/record.go:125-140]`, `[VERIFIED: modules/tide/diff.go:35-60]` | Per-route or per-step extra recorded headers, so the Range cases (206, 416) and the 429 cases assert their headers | +| T-8 | **Proxy rules accept two client names.** `ClientNuxt = "nuxt"`, `ClientMCP = "mcp"`, anything else is an error | `[VERIFIED: modules/tide/rules.go:14-16, 60-65]` | Accept any non-empty client label (the SPA can use `nuxt` today; the bot cannot) | +| T-9 | **The fake Centrifugo is static.** Presence always answers `{"result":{"presence":{}}}`; `unsubscribe` is answered but not recorded; any other API method is 404. PHP calls `publish`, `broadcast`, `unsubscribe` and `presence` `[SHELL: websockets/classes/CentrifugoClient.php:101-275]` | `[VERIFIED: modules/tide/centrifugo.go:60-101]` | Optional recording of `unsubscribe` calls (kick, ban, leave sever sockets), and scriptable presence answers so a "recipient online, no push" case can be recorded. Without this, every recorded push decision sees everyone offline | +| T-10 | **No repeat for 429 cases.** A manifest case is one request. The ten bucket cases need 6 to 301 requests inside one minute | `[VERIFIED: manifest.go:382-424]` | A `repeat` count on a spec step (only the last response is kept), or generated multi-step flows. A repeat is cheaper and keeps fixtures small | + +Not a gap: there is no path rewrite and none is needed (D-01). + +### Upstream vendors the corpus reaches + +D-11 names LiveKit and web push. The code has three more outbound calls that fire inside corpus requests when the queue is `sync`: + +| Vendor call | Trigger | Recording approach | +|-------------|---------|--------------------| +| LiveKit room service (Twirp) | video start, join, end, guest admit, remove, screen-share, reconcile | Script mode with protobuf response bodies generated by a Go helper in `sm-wavepath-app` (the proxy's forward mode uses `fetchguard.PublicOnlyMode` and cannot reach a local LiveKit). `LIVEKIT_URL` must be an `https`/`wss` host name so the PHP SDK goes through `HTTPS_PROXY` | +| Web push endpoints | every message with an offline mentioned or DM recipient, incoming calls | Script mode answering 201. Endpoints in the scenario must be real public push host names, because the PHP SSRF guard resolves them first | +| Link unfurl (page, `og:image`, favicon) | any sent message whose text holds an http(s) URL (`ResolveUnfurlJob`) | Script mode. Keep URLs out of scenario messages except in the unfurl cases | +| Webhook icon proxy | webhook ingest with a remote `icon_url` | Script mode | +| Cloudflare Turnstile `siteverify` (`https://challenges.cloudflare.com/turnstile/v0/siteverify`) | guest knock, account knock | Script mode, success and failure answers | + +Guzzle reads `HTTPS_PROXY` from the environment in every SAPI, and `HTTP_PROXY` only under `cli` `[SHELL: vendor/guzzlehttp/guzzle/src/Client.php:351-364]`, so all five must be `https`. The unfurl fetcher and the push sender pin a validated IP with `CURLOPT_RESOLVE` `[SHELL: classes/services/SafeHttpFetcher.php:91-102; herald/classes/PushSender.php:118-127]`. Whether a pinned request still tunnels through the proxy with its host name intact was **not observed**; it needs a short spike before the upstream cases are planned in detail. + +## PHP stack from outside the checkout (task 5) + +### What this machine has + +| Dependency | Required by | Available | Version | Fallback | +|------------|-------------|-----------|---------|----------| +| PHP CLI | PHP reference server | yes | 8.5.11, with `pdo_mysql`, `pdo_pgsql`, `pdo_sqlite`, `curl`, `gd`, `imagick`, `intl`, `redis`, `sodium` | `setup.sh` suppresses deprecations with `-d error_reporting=8191` for "Laravel 9.x on PHP 8.4+" | +| Composer vendor dir | PHP boot | yes | `vendor/autoload.php` present; `laravel/framework 9.x-dev`, `winter/storm v1.2.13`, `guzzlehttp/guzzle 7.15.3`, `symfony/http-foundation v6.4.43`, `minishlink/web-push v10.1.0`, `agence104/livekit-server-sdk 1.3.5` | — | +| MariaDB server | PHP database (production engine), OIDC export | installed (`mariadb 13.0.2` client), service inactive and disabled; images `mariadb:11`, `mariadb:10.11` present | — | Start a throwaway container on a loopback port | +| SQLite | PHP database alternative | yes | 3.54.0 | The PHP test suite runs on it | +| Docker | MariaDB, Typesense, testcontainers | yes | 29.9.1; user is in the `docker` group | CLAUDE.md: if the socket is denied, run through `sudo -u golem` | +| Postgres | Go replay | testcontainers; local 5432 and two containers also run | 16 and 18 images | — | +| Centrifugo | proxy sessions only | binary v6.5.1, image `centrifugo/centrifugo:v6`; something listens on `*:8787` | — | The tide recorder replaces it during scripted recording | +| LiveKit server | proxy sessions only | `livekit-server 1.13.1` | — | The upstream proxy replaces it during scripted recording | +| Typesense | group search | images `typesense/typesense:30.2`, `26.0`; no server binary | — | `SCOUT_DRIVER=null` makes search return nothing | +| Node, pnpm, npm | SPA and hubot proxy sessions | Node 24.22.0, pnpm 12.14.0, npm 12.2.1 | — | — | +| Go | everything | go 1.27.2 | — | — | + +Nothing listens on 3306, 6379, 8001, 8108 or 7880. The local `.env` of the checkout was not read (a guard blocks secret files), so the developer's real database engine and name are **not observed**. `storage/database.sqlite` is dated May 29 and is clearly not the live dev database. `.env.example` defaults to `DB_CONNECTION=mysql`; `config/database.php:16` defaults to `env('DB_CONNECTION', 'sqlite')`. + +**Missing with no fallback:** none. +**Missing with a fallback:** a running MariaDB (container), Typesense (container or null driver). + +### Recommended shape + +Copy `fonoteka.go/parity/php_parity.sh` `[SHELL: read in full]`, which never writes inside the PHP checkout: every setting is a process environment override (Laravel's dotenv does not overwrite variables that already exist), and the database is created under a parity root outside the checkout. Recommended for WavePath: + +1. **Database: an isolated MariaDB database, not the dev database.** D-08 permits writing to the dev database, but an isolated one is safer next to another agent's uncommitted work, repeatable for the D-06 re-record, and matches the production engine. A `mariadb:11` container on a loopback port, database name containing `parity`, schema from `php artisan winter:up`. The script refuses any `DB_DATABASE` without `parity` in its name, as fonoteka's does. SQLite also works for the community corpus `[ASSUMED]` but the OIDC export (`scripts/winter-export.sql`) is MySQL dialect, run with `mysql -N -B --raw`. +2. **Submodules at the pins:** `git -C plugins/golem15/chat checkout fbfbcf9` (and journal). This changes the other agent's working tree, which D-08 allows; the script should print what it changed and offer the reverse. Alternative with no change to the checkout: a `git worktree` of the superproject under the parity root with submodules at the pins and the existing `vendor/` linked in. Decide with the user. +3. **Environment overlay** (names from the code): + - `DB_CONNECTION`, `DB_HOST`, `DB_PORT`, `DB_DATABASE`, `DB_USERNAME`, `DB_PASSWORD` + - `CACHE_DRIVER=file` (rate limits need a real cache), `SESSION_DRIVER=array`, `QUEUE_CONNECTION=sync` (publishes, push and unfurl run inside the request), `MAIL_MAILER=array`, `APP_URL=http://127.0.0.1:`, `APP_DEBUG=false` + - `CENTRIFUGO_API_URL=http://127.0.0.1:8424/api`, `CENTRIFUGO_API_KEY`, `CENTRIFUGO_SECRET` (at least 32 bytes), `CENTRIFUGO_PROXY_SECRET`, `BROADCAST_DRIVER=centrifugo`, `BROADCAST_ENABLED=true` + - `LIVEKIT_URL`, `LIVEKIT_API_KEY`, `LIVEKIT_API_SECRET`, `LIVEKIT_ADMIN_URL`, `VIDEO_MAX_PARTICIPANTS`, `VIDEO_TOKEN_TTL` `[SHELL: chatvideo/config/config.php:4-11]` + - `VAPID_SUBJECT`, `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` `[SHELL: herald/config/herald.php:14-16]` (test-only key pair, the same pair in the Go config) + - `TURNSTILE_SECRET`, `TURNSTILE_SITE_KEY`, `JWT_SECRET`, `APP_KEY` (test-only) + - `SCOUT_DRIVER` and `TYPESENSE_*`, or `SCOUT_DRIVER=null` + - `HTTPS_PROXY=http://127.0.0.1:8425`, `NO_PROXY=127.0.0.1,localhost`, and the parity CA through `php -d curl.cainfo=… -d openssl.cafile=…` on the built-in server, exactly as `php_parity.sh serve` does +4. **Scenario reset:** `php artisan tinker --execute="require '/parity/wavepath_reset.php';"` run with the overlay, the fonoteka mechanism. The script writes JWTs, token secrets and ids only to `$PARITY_VARS_OUT` (mode 0600, outside the fixtures). Set id floors per table (fonoteka uses 10000000 steps) so that ids of different tables never collide when values are scrubbed into variables. +5. **Fail closed:** refuse to serve when the upstream proxy or the recorder is not listening, when the database name lacks `parity`, or when the target is not loopback. With `QUEUE_CONNECTION=sync` a missing proxy would send real requests to push services. +6. **Two modes.** Proxy mode (D-07, once): real Centrifugo and `livekit-server --dev` so the SPA and the bot work end to end, `summer parity:proxy` in front of PHP, sessions driven by Playwright (model: `fonoteka.go/parity/capture_clients.mjs`, 598 lines) and by the bot. Record mode (unattended, D-06): tide recorder and upstream proxy, `summer parity:record` over the manifest. + +`fonoteka.go/scripts/dev-stack.sh` (845 lines) is the model for the fail-closed style: `refuse:` lines stop, `warn:` lines do not, an env file parsed as data and never executed, loopback checks, recorded process groups, `up`, `down`, `status`, `check`. + +## The `sm-wavepath-app` skeleton (task 6) + +Models: `fonoteka.go` (parity layout) and `sm-demo-app` (mounts all seven plugins). + +``` +sm-wavepath-app/ +├── summer.yaml # module, binary, plugins (ids below) +├── go.mod # replace git.golem15.com/golem15/summercms => ../summercms.go +├── go.work # use . and ./plugins/golem15/ +├── .gitmodules # plugins/golem15/{user,chat,chatchannels,chatbots,chatvideo,forum,herald,userfriends} +├── main.go, plugins.gen.go # generated by summer build +├── config/ # app config, including test-only parity values +├── plugins/golem15/wavepath/ # the in-repo app plugin, id golem15.wavepath +│ ├── plugin.go, routes.go, buckets.go +│ ├── api/ # one file per PHP controller +│ ├── classes/ # host services and seam implementations +│ ├── models/, updates/ # host tables, companion user columns +│ └── jobs/, console/ +├── parity/ +│ ├── README.md +│ ├── manifest.yaml # 196 routes, auth groups, freeze commits +│ ├── routes.snapshot # digest of routes.php at a08ed0a +│ ├── capture-rules.yaml +│ ├── accepted-differences.yaml # D-13, signed entries +│ ├── scenario.md # the one scenario, both seeders follow it +│ ├── wavepath_reset.php # PHP seeder +│ ├── fixtureplugin/ # Go seeder (D-04) +│ ├── php_parity.sh # reset | serve | artisan | script | rows +│ ├── capture_clients.mjs # proxy sessions (SPA with Playwright, bot) +│ ├── check_corpus.go # manifest versus routes.php, secrets, coverage +│ ├── fixtures/{seed,routes,clients,broadcasts,files}/ +│ ├── upstream/scripts/ # vendor answers for script mode +│ ├── parity_test.go, broadcast_test.go, upstream_replay_test.go +└── scripts/ + ├── parity-stack.sh # the D-08 stack script + └── check-parity.sh # the D-15 gate (name is discretion) +``` + +`summer.yaml` plugin entries, from `sm-demo-app/summer.yaml` `[SHELL]`: `golem15.user` (`git.golem15.com/golem15/sm-user-plugin`), `golem15.chat`, `golem15.chatchannels`, `golem15.chatbots`, `golem15.chatvideo`, `golem15.forum`, `golem15.herald`, `golem15.userfriends`, then the app plugin last. Suggested module path `git.golem15.com/golem15/sm-wavepath-app` and app plugin module `…/sm-wavepath-app/plugins/golem15/wavepath` `[ASSUMED: follows the fonoteka pattern; the module path is the user's call, CONTEXT discretion]`. Fonoteka's app plugin is `git.golem15.com/golem15/fonoteka/plugins/golem15/fonoteka`. + +Note on D-04's wording: in fonoteka the Go scenario seeder is test code (`parity/fonoteka_seed_test.go`, 1397 lines, plus the seed hooks in `parity_test.go`); `parity/fixtureplugin` is a small callback fixture, not the seeder. D-04 asks for a fixture plugin, so build one, but copy the seeding style from `fonoteka_seed_test.go`. + +Replay model to copy: `go test ./parity` starts one testcontainers Postgres, fails rather than skips without Docker, serves the app in process through `httptest`, runs seed hooks registered by name, replays every `ported` route strictly and reports `pending` ones as skipped, never as passed. + +## Consumer gate (task 7) + +| Consumer | Mounts | How it builds and tests | What to check | +|----------|--------|-------------------------|---------------| +| `sm-bm-app` (module `git.golem15.com/jakub/sm-bm-app`) | chat, chatchannels, chatbots as submodules under `plugins/golem15/`, listed in `go.work` and replaced in `go.mod` | `go build ./...`, `go test ./...` at the repo root (`chat_test.go`: `TestChatMounted`; `realtime_test.go`: `TestRealtimeDefaultDriver`, `TestRealtimeRoutes`, `TestRealtimeConfigDefaults`, `TestRemoteKeyOverride`), `scripts/build.sh` | Its own Vite frontend in `frontend/`: `src/api/chat.ts`, `src/api/types.ts`, `src/stores/chat.ts`, `src/lib/chatEvents.ts`. Its plugin `plugins/jz/bm/classes/chat_context.go` implements the chat context. It has an untracked `.planning` file from another session; leave it | +| `sm-demo-app` | all seven plus moderation | `go test ./...` (`chat_test.go`, `realtime_test.go`, `video_test.go`, `moderation_test.go`, `seed_chat_test.go`), `scripts/check-all.sh`, `scripts/check-chat.cjs` | `vue-demo-app` pins `vue-chat-layer#v0.1.1`, `vue-chatvideo-layer#v0.1.2`, `vue-forum-layer#v0.1.0`, `vue-userfriends-layer#v0.1.0` | + +Gate procedure per changed plugin (CONTEXT, `.planning/notes/core-plugins-own-repos.md`): commit in the plugin repo, point `sm-bm-app` and `sm-demo-app` submodules at the new commit locally, build and test both, grep both frontends and the four layers for any renamed or removed field, then tag, push, post the changelog, and bump the pointers as separate commits. Pushing and tagging need the user's go-ahead. + +Shared message row fields today `[SHELL: sm-chat-plugin/classes/serialize.go]`: `id`, `conversation_id`, `sender_id`, `sender_name`, `sender_avatar`, `content`, `type`, `attachments`, `created_at`, `created_at_human`, `edited_at`, `deleted_at`, `is_mine`, `root_id`, `thread_summary` (omitempty), `reactions` (omitempty), `metadata` (omitempty). + +Most likely D-14 triggers found in this research: +1. **Attachment `url`.** PHP emits `url("/api/chat/attachments/{$this->id}/{$file->id}")`, an absolute URL on the legacy path `[SHELL: Message.php:197]`. Go emits `/_chat/api/v1/attachments/{messageId}/{fileId}`. The `/_wave` responses carry this field. Either the app's row serializer rewrites it (no shared change), or the shared serializer changes (a published field change for bm, demo and vue-chat-layer). Prefer the app-side rewrite; take the question to the user if a shared change looks necessary. +2. **Download headers** (the Range delta): additive, no field change. +3. Anything else the replay finds in the shared serializers of channels, forum, friends, video and push. + +The WavePath row is assembled by the app (shared row plus host extras, minus Go-only keys such as `thread_summary` where PHP has none at that position), so most message-row differences can be absorbed in the app plugin without touching the shared serializer. + +## Folded todos (task 8) + +### OIDC parity recording + +Runbook: `../sm-oauthserver-plugin/testdata/parity/README.md` (96 lines) `[SHELL: read in full]`. Ten spec flows in a fixed order (`discovery`, `jwks`, `authorize_errors`, `login_handoff`, `consent_allow`, `consent_silent`, `token_errors`, `userinfo_errors`, `consent_deny`, `authorizations`), recorded in place with `summer parity:record --spec … --output … --update true`, **without `--rules`**. Done when `PHASE194_REQUIRE_PARITY=1 go test -count=1 -run '^(TestPHPParityReplay|TestIDTokenShapeParity)$' -v ./...` passes in the plugin repo. + +What the D-08 stack must add for it: +- A parity user and an OIDC client "Parity RP" (redirect URI `https://rp.example.test/callback`, scopes `openid`, `profile`, `email`, active, not a development client, no consent yet). The runbook marks these as human steps in the backend; with a scripted stack they can be created by the reset script. +- The parity user's session JWT (`session_token`), minted by the reset script instead of copied from a browser. +- The export `mysql -N -B --raw < scripts/winter-export.sql`, which needs MySQL or MariaDB (`JSON_OBJECT`). This is the main reason to run the parity stack on MariaDB. +- A vars file at `~/.config/summercms/parity-oauthserver.vars`, mode 0600, outside both repositories. +- After recording: delete every `Set-Cookie` entry, write `seed.json`, `winter-export.jsonl` (hashes only) and `id_token_shape.json`. Known open differences: `Cache-Control` on OIDC redirects (Go `no-store, private`, PHP `no-cache, private`) and id_token header member order. + +`sm-oauthserver-plugin` has an uncommitted `go.work` change from another session; do not stage it. + +### Slash text that names no command + +Finding: **WavePath does not post it as text either.** The proposed fix in the todo ("otherwise post as text") does not match WavePath. + +- PHP dispatcher: strips one leading `/`, splits on the first whitespace run, and returns `null` when the trigger is empty or unknown `[SHELL: chatbots/classes/CommandDispatcher.php:42-56]`. The controller turns `null` into 422 with `['content' => ['unknown_command']]`; its header comment says "never a silent post" `[SHELL: CommunityCommandController.php:163-196]`. +- SPA: when the surface has a command list, a `/` input whose first token is not in the list returns `'unknown-command'` before any request: nothing is sent, the composer text is kept and a hint is shown. A known trigger is dispatched. A bare `/` (empty token) and any `/` text on a surface with an empty command list (the compact call composer) go to the normal send route and are posted as text `[SHELL: vue-wavepath-app/src/stores/channelChatStore.ts:663-719; components/chat/MessageComposer.vue:270-285]`. +- The message send route itself never inspects `/`. +- `vue-chat-layer` today: `if (content.startsWith('/') && !sent.length)` dispatches every such text to the server and shows the 422 as an error row; the draft is kept `[SHELL: vue-chat-layer/app/composables/useChat.ts:824-829, 1182-1206]`. + +So the observable outcome is the same in both: an unknown `/` text is refused and kept. The differences are that WavePath decides in the client from the catalog (no request), and that a bare `/` is posted. Options for the layer: +1. Match WavePath exactly: check the first token against the loaded catalog; unknown → refuse locally with the hint; bare `/` → normal send. This does not let "/r/golang is great" through. +2. Add a `//` escape on top (strip one slash and post as text). WavePath has no escape, so this is a layer-only addition and cannot conflict with backend parity. + +Recommend 1 plus 2, and ask the user, because the todo's stated goal (such text can be posted) is only met by the escape. No backend change either way. + +### Moderation seams + +`sm-demo-app/plugins/demo/moderation.go` `[SHELL: read in full]` listens on `chatevents.MessageSaving` and `forumevents.PostSaving` and uses the `sm-moderation-plugin` filter (`Filter.Check`, `Filter.CheckHTML`). The three seams it needs do not exist yet: + +| Seam | State | Addition | +|------|-------|----------| +| User name and surname | `sm-user-plugin` has no pre-save event. Its event names are `user.Created`, `user.Deleting`, `user.Deactivating`, `user.BackendLinked`, `user.BackendUnlinked`, `user.AccessRevoked`, `golem15.user.login` `[SHELL: sm-user-plugin/classes/events.go:11-30]` | An additive `user.Saving` event fired before registration and profile update, with a rejection type that maps to the 422 the route already uses. Core plugin: additive only, no behaviour change without a listener | +| Friend-group name and description | `sm-userfriends-plugin` fires only after-save events `[VERIFIED: sm-userfriends-plugin/events/events.go:8-11]` | An additive `GroupSaving` event in `GroupService.Create` and `Update`, before the transaction | +| Attachment filenames | `MessageSaving` has `ConversationID`, `ActorID`, `MessageID`, `RootID`, `Content`, `Op` and no file names `[VERIFIED: sm-chat-plugin/events/events.go:61-68]` | An additive field with the names of the attachments being claimed. Filenames first exist at upload time (`StorePendingAttachment`), so decide whether to check at upload or at send; at send is what the todo asks | + +Each seam is a plugin release with the D-14 gate, a README update, and a listener in the demo's `moderation.go`. With no listener nothing changes, so PHP parity is untouched. These three are independent of the corpus and can run in parallel with it. + +## Standard Stack + +No new dependency is needed. Everything is already decided in `.planning/research/STACK.md` and present in the repos. + +| Library | Version here | Purpose | +|---------|--------------|---------| +| `tide` (framework module) | in-repo | Record, replay, broadcast goldens, upstream sidecars | +| `github.com/goccy/go-yaml` | v1.19.2 | YAML (never `gopkg.in/yaml.v3`) | +| `github.com/testcontainers/testcontainers-go` | v0.44.0 | Postgres for `go test ./parity` | +| `gocloud.dev` | v0.46.0 | Blob storage, range reads for the attachment delta | +| `github.com/livekit/server-sdk-go/v2`, `github.com/livekit/protocol` | v2.19.0, v1.51.1-… (already in sm-chatvideo-plugin) | LiveKit; reuse `protocol` to build and decode Twirp bodies in the parity suite | +| `github.com/SherClockHolmes/webpush-go` | v1.4.0 (already in sm-herald-plugin) | Web push | +| `github.com/riverqueue/river` | v0.47.0 | Jobs (notifications, unfurl, guest kick) | + +A decrypting comparer for push payloads needs only the standard library (`crypto/ecdh`, `crypto/hkdf`, `crypto/aes`, `crypto/cipher`) `[ASSUMED]`. + +## Package Legitimacy Audit + +No external package is installed by this phase. All libraries above are already in the `go.mod` files of the framework and the shared plugins. If planning adds one, CLAUDE.md requires a research doc or decision note naming it, and the legitimacy check runs then. + +**Packages removed due to [SLOP] verdict:** none +**Packages flagged as suspicious [SUS]:** none + +## Architecture Patterns + +### Data flow + +``` + SPA (Playwright) ─┐ ┌─> tide Centrifugo recorder :8424 ──> .broadcasts.yaml + hubot-wavepath ──┼─> summer parity:proxy ──┤ + (proxy mode, once)│ :8422 │ + │ ├─> PHP built-in server (WavePath at a08ed0a, MariaDB *parity*) + spec flows ───────┴─> summer parity:record ─┘ │ HTTPS_PROXY + (record mode, unattended) └─> tide upstream proxy :8425 ──> .upstream.yaml + (script answers: LiveKit, push, unfurl, icon, Turnstile) + fixtures/routes/*.yaml + broadcasts + upstream sidecars (committed in sm-wavepath-app/parity) + │ + v + go test ./parity ── testcontainers Postgres ── fixture plugin seeds the scenario + │ + ├─ ReplayManifest over httptest (app plugin + seven shared plugins) + │ ├─ lighthouse publishes into an in-process recorder ──> DiffPublications against the golden + │ └─ fetchguard transport = UpstreamFake ──────────────> Verify against the sidecar + └─ pending routes: skipped, never passed; ported routes: strict + │ + v + scripts/check-parity.sh: zero pending, all goldens asserted, accepted-differences signed, + sm-bm-app and sm-demo-app build and test +``` + +### Pattern 1: host handler over plugin services + +```go +// Sketch. Names are discretion; the envelope and codes are PHP's. +func (p *Plugin) groupMessages(w http.ResponseWriter, r *http.Request) { + group, user, ok := p.gateGroup(w, r) // 404 NOT_FOUND / 403 FORBIDDEN in WavePath's envelope + if !ok { + return + } + chat, _ := p.app.Lookup[*chatclasses.Service]() + conv, err := chat.GetGroupChat(r.Context(), user.ID, groupAlias, group.ID) + // rows := chat.GetMessages(...); base := chat.MessagesAPI(...) + // decorate each row: is_mine, reactions (host), unfurl, metadata, sender_avatar, + // is_bot, webhook identity, guest identity, root_id, parent, thread footer, tombstone scrub + writeSuccess(w, http.StatusOK, map[string]any{"messages": rows, "conversation_id": conv.ID}) +} +``` + +One row decorator shared by the group, channel, DM, thread, pin and guest surfaces. PHP stresses "serializer key-symmetry": the list row, the send response and the thread row carry the identical key set. + +### Pattern 2: one scenario, deterministic ids + +Seed every scenario row with an explicit id on both sides and set per-table sequence floors, so new rows get the same ids in PHP and Go when a case starts from the reset state. Capture ids created in a case into `id:*` variables. This is what makes upstream bodies (ids inside protobuf) and channel names comparable. + +### Pattern 3: reset per stateful case + +Fonoteka records each stateful case from a fresh reset. For 196 routes use a database snapshot restore on the PHP side (dump once after `winter:up` plus the scenario, restore per case) and a Postgres template database on the Go side. + +### Anti-patterns to avoid +- **Reusing the plugins' `api` handlers behind `/_wave`:** the envelope and error codes differ. +- **Mapping WavePath reactions onto the chat plugin's reactions:** different table, key name and summary shape. +- **Hand-writing fixture bodies:** every fixture comes from PHP. +- **Recording against the developer's database or with real vendor credentials.** +- **Naming WavePath in `summercms.go`** (tide README, docs, tests, scripts). +- **Counting a pending route as a pass.** + +## Don't Hand-Roll + +| Problem | Don't build | Use instead | Why | +|---------|-------------|-------------|-----| +| SSRF checks for unfurl, icons, push endpoints | A port of `SsrfGuard` (349 lines) | `fetchguard` (`PublicOnlyMode`, `IsPrivateAddr`) | Already the framework's guarded client; herald uses it | +| Recording, diffing, masking | App-local diff code | `tide`, extended generically | One toolkit for every port | +| LiveKit calls and tokens | A second client | `sm-chatvideo-plugin` `classes/livekit.go` | Already ported and tested | +| Push encryption and VAPID | Own crypto | `sm-herald-plugin` sender | Already ported | +| Markdown for forum posts | A new renderer | `sm-forum-plugin` renderer | Ported with its security tests | +| Mentions, handles | A new parser | `sm-chatchannels-plugin` `MentionParser` | Ported | +| Rate limiting | Custom counters | `surf` buckets (stack two throttles for the two-limit buckets) | 429 body and headers are already PHP-shaped | +| YAML | `gopkg.in/yaml.v3` | `goccy/go-yaml` | Project rule | + +**Key insight:** the risk is not missing libraries. It is the volume of host logic and the number of places where PHP's output is assembled from several sources. + +## Common Pitfalls + +### Pitfall 1: treating the phase as an alias layer +**What goes wrong:** plans sized for 194 thin routes, then weeks of host logic. +**Why:** WavePath's controllers hold the product logic; the plugins are deliberately host-blind. +**How to avoid:** size by PHP lines per controller family (table above). **Warning sign:** a plan that lists more than about 40 routes. + +### Pitfall 2: nondeterministic strings +**What goes wrong:** replay fails on `created_at_human`, invite codes, webhook tokens, guest codes, LiveKit tokens, call-link codes, file disk names. +**How to avoid:** T-1 for relative times; capture every server-minted secret into a variable at recording; never let one reach a fixture (the scrubber refuses JWT-shaped values but does not know opaque codes). + +### Pitfall 3: the queue changes what a request does +**What goes wrong:** with `QUEUE_CONNECTION=sync`, a send also publishes, pushes and unfurls inside the request. PHP production uses queues (`broadcasts`, `notifications`, a separate unfurl queue). +**How to avoid:** record with `sync` so each golden holds everything the step caused; on the Go side run River jobs inline in the parity test before collecting publications. Order of publications inside one step may differ between a sync PHP run and Go; fonoteka has an unordered comparison helper (`assertMatchesGoldenUnordered`). + +### Pitfall 4: rate-limit state leaks between cases +**What goes wrong:** 240 requests per minute per user is easy to hit during a recording run; a 429 lands in an unrelated fixture. +**How to avoid:** clear the PHP cache between batches or pace the run; give the ten 429 cases their own users and guest sessions; reset the Go limiter per case. + +### Pitfall 5: the working tree is not the pinned commit +**What goes wrong:** recording chat at `943b712` when the freeze says `fbfbcf9`. +**How to avoid:** the stack script compares `git submodule status` with the pins and refuses on a `+` line; the manifest stores the pins. + +### Pitfall 6: presence is always empty in the recorder +**What goes wrong:** every push decision is recorded as "offline", and the presence snapshot is always empty. +**How to avoid:** T-9, or accept and document that online branches are not in the corpus. + +### Pitfall 7: search needs a backend +**What goes wrong:** `SCOUT_DRIVER=typesense` with no Typesense fails model saves (the PHP `phpunit.xml` comment says so); `null` makes the search route return nothing, which is a weak fixture. +**How to avoid:** run Typesense containers on both sides for the search cases, or record search with the null driver and note it. Decide with the user. + +### Pitfall 8: pinned outbound requests and the proxy +**What goes wrong:** unfurl and push pin an IP; if such requests bypass the proxy or reach it by IP, script matching fails or a request leaves the machine. +**How to avoid:** a spike before planning the upstream cases; the stack script fails closed. + +### Pitfall 9: shared files and other sessions +**What goes wrong:** staging another session's edits (`STATE.md`, `state.json`, cabana, the oauthserver `go.work`, the bm `.planning` file). +**How to avoid:** stage by path; plugin first, then pointer bumps as separate commits. + +### Pitfall 10: the 17 uncalled routes +**What goes wrong:** no proxy session produces their requests, so they have no fixtures and stay pending forever. +**How to avoid:** hand-written spec cases, or remove them from the corpus by decision. + +## Code Examples + +### Manifest route with cases (shape from `tide.Manifest`) +```yaml +# Source: modules/tide/manifest.go (Manifest, Route, RouteCase) +version: 1 +auth_groups: [jwt, guest, bot, webhook, realtime] +seed: + spec: seed/bootstrap.yaml +routes: + - id: POST__wave_api_v1_community_groups_id_messages jwt + method: POST + path: /_wave/api/v1/community/groups/{id}/messages + auth_group: jwt + status: pending + seed_hook: community + cases: + - id: member-send + status: 201 + request: + method: POST + path: /_wave/api/v1/community/groups/{{id:group}}/messages + headers: {Cookie: "token={{jwt:alice}}", Content-Type: application/json} + body: '{"content":"hello"}' + capture: + - {from: response.json, path: data.message.id, as: "id:message"} + - id: no-cookie + status: 401 + - id: non-member + status: 404 +``` +`[ASSUMED: the Cookie header and the exact denial statuses come from the recording, not from this sketch]` + +### Replaying one case with its side effects (target shape after T-2, T-4, T-5) +```go +// Source: pattern of fonoteka.go/parity/upstream_replay_test.go and broadcast_goldens_test.go +fake := caseUpstream(t, fixturePath, store) // tide.NewUpstreamFake over .upstream.yaml +switchTransport.set(fake) // fetchguard.WithTransport hands it to herald and chatvideo +rec.Reset() // in-process tide.CentrifugoRecorder +res, err := tide.ReplayFlow(ctx, flow, tide.ReplayConfig{Target: srv.URL, Store: store, BaseDir: dir}) +// run queued jobs inline, then: +norm, _ := tide.NormalizePublications(rec.Publications(), store) +diffs := tide.DiffPublications(golden.Publications, norm) +if err := fake.Verify(); err != nil { t.Fatal(err) } +``` + +## State of the Art + +| Old approach | Current approach | When changed | Impact | +|--------------|------------------|--------------|--------| +| Plugin goldens built from PHP fixtures, no live PHP (P19, P19.1: "live capture NOT RUN") | Live PHP recording through tide | This phase | First time the chat family meets real PHP output; expect real differences | +| Freeze at chat `943b712` | Freeze at `fbfbcf9` | D-12 | Attachment streaming with Range | +| Fonoteka broadcast goldens, 7 hand-picked events | A golden for every writing case | D-10 | Needs T-2 | +| Upstream sidecars for JSON vendors with static API keys | Signed and encrypted vendor calls | D-11 | Needs T-4, T-5 | + +## Sizing and split (task 9) + +Honest estimate, in plans of the size this project usually runs (one large plan is roughly one executor session): + +| Area | Work | Plans | +|------|------|------:| +| A. tide additions T-1 to T-10 | Framework code, README, docs pages, generic tests | 1 | +| B. App skeleton, PHP stack script, scenario on both sides, manifest of 196 routes | New repo, submodules, `php_parity.sh`, `wavepath_reset.php`, fixture plugin, `check_corpus.go` | 1 | +| C. Proxy sessions, spec flows, full PHP recording (fixtures, broadcast sidecars, upstream scripts and sidecars), PHP self-replay green | Playwright journeys, bot session, hand-written denial, 422 and 429 cases | 1 to 2 | +| D. Foundation slice: envelope, cookie actor, buckets, user columns, contexts, resolvers, `wave` and presence authorizers, realtime routes, groups, members, invites, join, friends, group lifecycle | about 36 routes, about 1.5k PHP lines of controllers plus seams | 1 | +| E. Messaging: row decorator, group chat, channels, DM, threads, commands, host reactions, emoji, prefs, attachments with the Range delta, pins | about 80 routes, about 6k PHP lines | 2 | +| F. Presence, status, notifications and push, unfurl, webhooks, bot REST with the token guard, search | about 25 routes, about 4k PHP lines | 1 to 2 | +| G. Video and guests with LiveKit sidecars | 29 routes, about 3.5k PHP lines | 1 to 2 | +| H. Forums and shared notes (with the minimal diary model) | 32 routes, about 1.5k PHP lines | 1 | +| I. Shared-plugin parity fixes, releases, consumer gate, changelog posts | recurring; one closing pass | 1 | +| J. Folded todos: OIDC recording, slash fix, three moderation seams | three repos plus the demo and a layer | 1 | +| K. Gate script, accepted-differences sign-off, security review, unit tests | last plan | 1 | +| **Total** | | **12 to 15** | + +That is three phases by this project's lean-planning rule. Earlier phases reached 14 plans (Phase 6) and 10 (Phase 8), so one phase is possible, but the plan-count checkpoint should offer the split. + +**Recommended split:** + +| Phase | Scope | Closes when | +|-------|-------|-------------| +| **31 Corpus and harness** | A, B, C, D, plus J (the OIDC recording needs only the PHP stack; slash and moderation are independent) and its own unit-test plan | tide gaps closed; all 196 routes recorded with broadcast and upstream sidecars; PHP self-replay green; the foundation slice `ported`; the gate script exists and reports the pending count | +| **31.1 Messaging** | E, the chat Range release with the consumer gate, unit tests | all group chat, channel, DM, thread, command, reaction and emoji routes `ported` | +| **31.2 Satellites and close-out** | F, G, H, I, K | D-15: zero pending, every golden asserted, signed accepted differences, bm and demo green, security review done | + +This moves D-15's "the phase closes at zero pending" to 31.2 and restates the criteria of 31 and 31.1 as partial. D-15 is a locked decision, so **the split needs the user's confirmation** at the plan-count checkpoint. If the user keeps one phase, use the same order as waves. + +Dependencies between areas: A before C (recording needs T-1, T-2, T-6, T-7, T-10; T-4, T-5 and T-9 before the upstream and presence cases). B before C. C before any port work is verified, but D can start in parallel with C. E before F, G and H (they reuse the row decorator and gates). J is independent. + +## Assumptions Log + +| # | Claim | Section | Risk if wrong | +|---|-------|---------|---------------| +| A1 | WavePath's schema and the community surface run on a fresh MariaDB (and on SQLite) from `winter:up` | PHP stack | Stack script needs a different bootstrap; the dev database would have to be used | +| A2 | WavePath boots and serves on PHP 8.5.11 with Laravel 9 | PHP stack | A second PHP version is needed (`setup.sh` allows `PHP=php83`); none was checked for | +| A3 | Requests pinned with `CURLOPT_RESOLVE` still tunnel through `HTTPS_PROXY` with their host name | tide readiness | Unfurl, icon and push upstream cases need a different capture method | +| A4 | The PHP LiveKit SDK sends through Guzzle and honours `HTTPS_PROXY` when `LIVEKIT_URL` is an https or wss host | tide readiness | LiveKit calls cannot be captured by the upstream proxy as is | +| A5 | PHP and Go produce comparable protobuf for the same LiveKit request once ids are deterministic | tide readiness | A decoding comparer is mandatory, not optional | +| A6 | Web-push ciphertext can be decrypted in the parity suite with the scenario's subscription private key, so plaintext payloads can be compared | tide readiness, Standard Stack | Push parity falls back to count, endpoint and headers only | +| A7 | surf bucket names are global across plugins, so `community-join` and `call-link` collide with the app's buckets | Corpus | None if wrong; if right, the app must reuse or rename | +| A8 | A second `Registry.Add` for the group alias is refused if sm-userfriends-plugin already registers one | Gap map | Group context wiring needs a plugin change or an override API | +| A9 | `http.ServeContent` differs from Symfony on 416 bodies and multi-range requests | Deltas | Less custom code than expected | +| A10 | Suggested module path `git.golem15.com/golem15/sm-wavepath-app` | Skeleton | Rename before the first commit; costly later (D-02) | +| A11 | The local `.env` of the checkout points at a database other than the stale `storage/database.sqlite` | PHP stack | Irrelevant if the isolated database is used | +| A12 | `community_mode` and other host columns live in `wavepath/updates/` and extend shared tables | Gap map | More companion migrations than expected | +| A13 | Denial statuses in the example manifest (401, 404) | Code Examples | None; the recording defines them | +| A14 | `GroupService` in PHP userfriends has `attachImage` and custom invite codes live on `GroupInvite` | Gap map | The gap sits in the app plugin instead of sm-userfriends-plugin | + +## Open Questions + +1. **Split into 31, 31.1, 31.2?** Known: 12 to 15 large plans. Unclear: whether the user wants D-15's zero-pending gate on one phase. Recommendation: propose the split at the plan-count checkpoint. +2. **`wavepath-mcp` has no route in the corpus.** Success criterion 1 names it as a recording client. Recommendation: correct the criterion to two clients in the first planning commit, or widen D-09 to the `/api/v1` token routes (that pulls diary, practices, trainings and stats into scope, which the boundary excludes). +3. **Shared notes need the diary.** D-09 includes `community/notes` (16 routes); the boundary excludes the diary. Recommendation: a minimal `DiaryEntry` read model and fixture rows in the app plugin, flagged as provisional for WavePath's agent; or drop `notes` from the corpus. Needs the user. +4. **The 17 uncalled routes.** Keep with hand-written cases, or drop from the corpus? Recommendation: keep `/hooks/{token}` and `webhook-icon` (real traffic, just not from the three clients); ask about the five compatibility note routes and the nine unused channel and forum routes. +5. **Which database for the PHP stack.** Recommendation: an isolated MariaDB container. D-08 allows the dev database; confirm the user prefers isolation. +6. **Checking out `chat` and `journal` at their pins** changes the other agent's working tree. Recommendation: do it with a printed notice, or use a worktree under the parity root. Needs the user or the other agent. +7. **Search backend for recording.** Typesense on both sides, or the null driver? +8. **Slash behaviour.** WavePath refuses unknown slash text; the todo wants it postable. Recommendation: catalog check plus a `//` escape. Needs the user. +9. **Attachment `url`** (absolute legacy path in PHP). App-side rewrite or shared serializer change? Recommendation: app-side; confirm when the first fixture shows the real value. +10. **Where does login come from on replay?** `/_wave/api/v1/auth/login` is outside the corpus. Recommendation: both seeders mint the session JWTs into the vars store, and requests carry `Cookie: token={{jwt:…}}`. This needs the same `JWT_SECRET` and claim shape on both sides, which the user plugin port already matched (Phase 7). +11. **Remote for `sm-wavepath-app`.** Creating it and pushing need the user's go-ahead; the plan should stop at a checkpoint there. + +## Environment Availability + +See "PHP stack from outside the checkout" for the table. Summary: PHP 8.5.11, Composer vendor dir, Docker 29.9.1, Go 1.27.2, Node 24.22.0, pnpm 12.14.0, Centrifugo v6.5.1 and livekit-server 1.13.1 are present. MariaDB server is installed but not running; images `mariadb:11` and `typesense/typesense:30.2` are local. No dependency is missing without a fallback. + +## Validation Architecture + +### Test Framework +| Property | Value | +|----------|-------| +| Framework | Go `testing` (go 1.27), testcontainers Postgres for parity; Vitest in the vue layers | +| Config file | none in `sm-wavepath-app` yet (Wave 0) | +| Quick run command | `go test -short ./...` in each touched repo | +| Full suite command | `go vet ./... && go test ./...` in `summercms.go`, `sm-wavepath-app` and each changed plugin; `scripts/check-parity.sh` in `sm-wavepath-app` | + +### Phase Requirements → Test Map +| Req | Behavior | Test type | Automated command | File exists? | +|-----|----------|-----------|-------------------|--------------| +| SC-1 | Every corpus route is recorded from PHP | corpus check | `go run ./parity/check_corpus.go --manifest parity/manifest.yaml --routes --require-recorded --check-secrets` | no, Wave 0 | +| SC-1 | PHP self-replay is green | manual-run script (needs the PHP stack) | `summer parity:replay --manifest … --self-check true` | no, Wave 0 | +| SC-1 | Go replays every ported route; pending never passes | integration | `go test ./parity -run TestParityCorpus` | no, Wave 0 | +| SC-1 | Zero pending at close | gate | `scripts/check-parity.sh` | no, Wave 0 | +| SC-2 | Publications of each writing case match the golden | integration | `go test ./parity -run TestBroadcasts` | no, Wave 0 | +| SC-2 | Channel authorization routes replay | integration | `go test ./parity -run 'TestParityCorpus/.*realtime'` | no, Wave 0 | +| D-11 | Vendor calls match the sidecars | integration | `go test ./parity -run TestUpstreamSidecarsAreReplayed` | no, Wave 0 | +| SC-3 | bm builds and passes with the new plugin commits | integration | `cd ../sm-bm-app && go build ./... && go test ./...` | yes | +| SC-3 | demo builds and passes | integration | `cd ../sm-demo-app && go test ./...` | yes | +| SC-3 | Framework docs name no application | docs check | `summer docs:build --check`; `go test ./cmd/summer -run TestDocsTree` | yes | +| SC-4 | tide additions | unit | `go test ./modules/tide/...` | yes (extend) | +| SC-4 | App plugin host services | unit | `go test -short ./plugins/golem15/wavepath/...` | no, Wave 0 | +| D-12 | Attachment Range, 206 and 416 | unit and parity | `go test -short ./... -run TestAttachmentRange` in sm-chat-plugin | no, Wave 0 | +| Todo | OIDC parity | integration | `PHASE194_REQUIRE_PARITY=1 go test -count=1 -run '^(TestPHPParityReplay|TestIDTokenShapeParity)$' ./...` in sm-oauthserver-plugin | yes (skips today) | +| Todo | Moderation seams fire and reject | unit | `go test -short ./...` in user, userfriends, chat; `go test ./... -run TestModeration` in sm-demo-app | partly | +| Todo | Slash handling in the layer | unit | the layer's Vitest suite | to check | + +### Sampling Rate +- **Per task commit:** `go vet ./... && go test -short ./...` in the touched repo. +- **Per wave merge:** `go test ./...` (Docker) in the touched repos; `go test ./parity` in `sm-wavepath-app`. +- **Phase gate:** `scripts/check-parity.sh` green before `/msd-verify-work`. + +### Wave 0 Gaps +- [ ] `sm-wavepath-app` repo, `go.mod`, `go.work`, submodules, `summer.yaml` +- [ ] `parity/parity_test.go` with a `TestMain` that calls `flag.Parse()` and checks `testing.Short()` +- [ ] `parity/check_corpus.go` and `routes.snapshot` +- [ ] `parity/fixtureplugin` and `wavepath_reset.php` for the scenario +- [ ] `scripts/parity-stack.sh`, `parity/php_parity.sh` +- [ ] `scripts/check-parity.sh` +- [ ] tide tests for each addition (T-1 to T-10) + +## Security Domain + +`security_enforcement` is not set in `.planning/config.json`, so it is enabled. CONTEXT asks for the security-review agent. + +### Applicable ASVS Categories + +| ASVS Category | Applies | Standard Control | +|---------------|---------|------------------| +| V2 Authentication | yes | `bouncer` JWT guard with the `token` cookie; the `wave_` token guard with an HMAC blind index and scope `chat:bot`; webhook URL token (40 characters, blind index); guest cookie | +| V3 Session Management | yes | Guest session cookie `wave_guest`, read from the raw cookie bag in PHP; confine it to the guest routes; purge after the grace period | +| V4 Access Control | yes | Group visibility gate, channel and forum access resolvers (deny-all defaults), 404 collapse instead of 403 where PHP does so, cross-group id checks on every nested id | +| V5 Input Validation | yes | Laravel rule strings ported through the validator; Slack payload parser; markdown sanitizer of the forum plugin | +| V6 Cryptography | yes | No hand-rolled crypto: VAPID and push through herald, LiveKit tokens through chatvideo, `crypto/subtle` for token comparison | +| V12 Files | yes | Private attachments only through authenticated routes; explicit `Content-Type`, never sniffed; `Cache-Control: private, no-store, …`; emoji and image upload type and size checks | +| V13 API | yes | Separate auth groups that must never overlap: cookie JWT, guest, bot token, webhook | + +### Known Threat Patterns + +| Pattern | STRIDE | Standard Mitigation | +|---------|--------|---------------------| +| IDOR on message, channel, thread, pin and file ids | Information disclosure | Gate first, then load scoped to the gated conversation; one 404 for missing and forbidden | +| Auth-group crossover (a `wave_` bearer reaching cookie routes, a guest cookie reaching member routes) | Elevation of privilege | Separate route groups and guards; a test that lists each group's routes | +| SSRF through unfurl URLs, webhook icons, push endpoints | Tampering, Information disclosure | `fetchguard.PublicOnlyMode`, byte caps, no redirects into private ranges | +| Invite, call-link and guest code enumeration | Information disclosure | Tight buckets (`community-join`, `call-link`, `call-guest-*`), uniform 404 | +| Webhook flooding and token guessing | Denial of service | `wave-webhook` bucket keyed per webhook, IP key for unknown tokens | +| Stored XSS through inline-served uploads | Tampering | Explicit content type, `attachment` disposition for unsafe types (`classes.IsInlineUnsafe`) | +| Secrets in committed fixtures | Information disclosure | tide scrubbing and refusal, `check_corpus --check-secrets`, vars file mode 0600 outside the repo, test-only keys | +| Recording run reaching real vendors | Information disclosure | Fail-closed stack script, script-mode upstream proxy, no real credentials in the overlay | +| D-13 security exceptions | — | Go keeps the safe behaviour; each case is a signed entry in the accepted-differences file | + +## Project Constraints (from CLAUDE.md) + +- Work goes through MSD. Lean planning: few, large plans; present the plan count with one-line scopes and wait for confirmation. Unit tests are the last plan of every phase. Update `STATE.md` only through `msd_run query state.*`. Mirror phase progress in g15office. +- `go vet` and `go test ./...` green at every commit. Docker tests skip under `-short`; a `TestMain` that starts containers calls `flag.Parse()` and checks `testing.Short()`. +- Framework code, READMEs, docs and examples never name a consuming application. The gate script therefore lives in `sm-wavepath-app`. +- A change to a module's exported API, config keys, CLI commands or dependencies updates that module's `README.md` and the affected `docs/` pages in the same commit; every identifier in a README must exist (`summer docs:build --check`). +- YAML through `goccy/go-yaml`. A new dependency needs a research doc or decision note. +- Core plugins (user, blog, pages, payment) take no breaking change unless asked. `sm-user-plugin` changes are additive only. +- Plugin first (commit, push, tag), then the pointer bump in each app as a separate commit. No push, tag or deploy without the user's go-ahead. Tag only on the default branch, and only at phase completion for the framework; plugin patch tags in between are fine. +- Every pushed plugin tag gets a post on `/changelog/plugins` the same day, written from `scripts/changelog-post.py` in `../sm-summercmsio-app`; never print or mint the journal token. +- No co-author tags. One logical change per commit; planning docs and code in separate commits. Stage by path, never `git add -A`; leave other sessions' edits alone. +- `/media/nvme/dev/jz/wavepath.org` belongs to another agent: no commit there (D-08). + +## Sources + +### Primary (HIGH confidence, read in this session) +- `/media/nvme/dev/jz/wavepath.org/plugins/golem15/wavepath/routes.php` (all 1087 lines, at `a08ed0a`) +- `…/wavepath/Plugin.php:160-558`, `…/controllers/api/CommunityChatController.php:24-403`, `…/classes/responses/ApiResponse.php` +- `modules/tide/README.md`, `modules/tide/manifest.go`, `centrifugo_golden.go`, and ranges of `centrifugo.go`, `rules.go`, `record.go`, `diff.go`, `normalize.go`, `upstream.go`, `variables.go` +- `sm-chat-plugin/api/download.go`, `sm-chat-plugin/events/events.go:40-68`, `sm-userfriends-plugin/events/events.go`, `sm-user-plugin/classes/session_user.go:17-30` +- `31-CONTEXT.md`, `.planning/config.json` + +### Secondary (seen through shell commands in this session) +- `git` state of `wavepath.org` and its submodules; `git show fbfbcf9:` for the chat delta +- PHP controllers, services and vendor packages (line counts, selected ranges) +- Route and service lists of the seven Go plugins; `sm-demo-app` and `sm-bm-app` layout +- `fonoteka.go/parity/README.md` (sections), `php_parity.sh` (full), `scripts/dev-stack.sh` (header) +- `sm-oauthserver-plugin/testdata/parity/README.md` (full), the three todo files +- Client sources: `vue-wavepath-app/src`, `wavepath-mcp/src`, `hubot-wavepath/src` +- Local environment probes (versions, docker images, listening ports) + +### Tertiary (LOW confidence) +- Behaviour of Symfony `BinaryFileResponse`, `http.ServeContent`, cURL with a pinned address behind a proxy: from training knowledge, not checked (A3, A9) + +No web source was used. The research-plan seam was not run: every question was answerable from local code. + +## Metadata + +**Confidence breakdown:** +- Corpus count and route table: HIGH. Parsed from the pinned file and read in full. +- Uncalled routes: MEDIUM-HIGH. Static scan plus manual checks; the proxy sessions are the final word. +- Gap map: MEDIUM. Service lists and PHP sizes are measured; method-level equivalence was not checked route by route. +- tide gaps: HIGH for T-1 to T-10 as code facts; the proposed additions are designs, not tested. +- PHP stack: MEDIUM. Tools are present; nothing was started. +- Sizing: MEDIUM. Based on line counts and the fonoteka precedent. + +**Research date:** 2026-11-13 +**Valid until:** 2026-11-27 for the pins and working-tree states (the WavePath repo is active and another agent works in it); 30 days for the tide and plugin analysis.