From 49ee00f924b91a7380d4a4d3a057c574193dbc3c Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:51:45 +0000 Subject: [PATCH 01/78] docs(specs): add project membership behavior (follow, apply, admins) One record per person per project moves follower -> applicant -> member, with admin as a flag on a member. Replaces the single maintainer and open join; applications open, then accepted or closed. Co-Authored-By: Claude Fable 5.2 --- specs/behaviors/project-membership.md | 249 ++++++++++++++++++++++++++ 1 file changed, 249 insertions(+) create mode 100644 specs/behaviors/project-membership.md diff --git a/specs/behaviors/project-membership.md b/specs/behaviors/project-membership.md new file mode 100644 index 00000000..e0056c49 --- /dev/null +++ b/specs/behaviors/project-membership.md @@ -0,0 +1,249 @@ +# Behavior: Project Membership + +## Rule + +A person's relationship to a project is **one record**, a +[ProjectMembership](../data-model.md#projectmembership), that moves through +three states: **follower → applicant → member**. A member may also be a +**project admin**. The record is created by the first step (a follow, an +application, or an admin adding someone) and removed when the person stops +following. + +- **Project admins run the project.** Only project admins (and staff) edit the + project, add and remove members, make or unmake admins, post and manage + needs, and decide applications. A project has any number of admins; there is + no single maintainer. +- **Joining is by application or by an admin's add.** There is no open join. A + person applies, picking one or more of the project's open + [needs](help-wanted-roles.md) or writing their own offer. An application + is `open` until it is `accepted` or `closed`, the same vocabulary as needs. An admin can also add anyone with an account directly. +- **Following is open.** Any signed-in person can follow a project with one + click and no approval. Followers get the project's updates by email. + Applicants, members and admins are inherently following: they get everything + a follower gets. +- **Only members are public on the site.** A project page lists members and + admins. Followers and applicants appear as a count at most; applicants are + visible to the project's admins and staff. A follow or an application gives + a spam account no link from a real project's page to its profile. + +## Applies To + +- [data-model.md → ProjectMembership](../data-model.md#projectmembership) +- [api/projects-members.md](../api/projects-members.md) — follow, add, remove, leave, admin flag +- [api/projects-applications.md](../api/projects-applications.md) — apply, accept, close +- [api/agent-applications.md](../api/agent-applications.md) — the agent feed and decisions on an admin's behalf +- [behaviors/authorization.md](authorization.md) — the `project-admin` marker +- [behaviors/help-wanted-roles.md](help-wanted-roles.md) — needs, which applications select +- [screens/project-detail.md](../screens/project-detail.md), [screens/project-applications.md](../screens/project-applications.md) + +## States + +| State | Meaning | Public on the site | Gets project emails | +| ----- | ------- | ------------------ | ------------------- | +| `follower` | Follows the project. No standing on it. | In the follower count only | Yes | +| `applicant` | Has an open application. Still following. | In the follower count only | Yes | +| `member` | On the project. Listed on the project page. | Yes, with `role` | Yes | + +`isAdmin` is a flag on a `member` record. It is `false` in every other state. + +There is no "none" record: a person with no record has no relationship to the +project. + +## Transitions + +```text + follow apply + (none) ─────────────▶ follower ─────────────▶ applicant + │ ◀─────────────── │ ◀────────────────── │ │ + │ unfollow │ close (admin, │ │ accept + │ │ applicant or site) │ ▼ + │ apply (also follows) │ member ◀──▶ member + admin + └──────────────────────────────────────────────┘ │ promote / demote + │ + add (from none, follower or applicant) ───────────▶│ + │ leave ──▶ follower + │ remove ─▶ (none) +``` + +| Transition | From | To | Who | Notes | +| ---------- | ---- | -- | --- | ----- | +| **follow** | none | follower | self (`user`) | One click, no approval. | +| **unfollow** | follower | none | self | Deletes the record. Applicants close their application first; members leave first. | +| **apply** | none, follower | applicant | self (`user`) | Selects open needs and/or writes an offer. Applying from none creates the record already following. Refused while the [re-apply wait](#re-apply-limits) runs. | +| **accept** | applicant | member | `project-admin` \| `staff`, or an agent on a project admin's behalf ([agent-applications.md](../api/agent-applications.md)) | `via = application`. Optionally marks the selected needs filled. | +| **close** | applicant | follower | `project-admin` \| `staff`, or an agent on a project admin's behalf ("Close application"); the applicant themselves; or the site, 30 days after the application became visible to admins with no decision | `application.status = closed`, with who closed it (`closedBy`: `admin`, `applicant` or `site`) kept on the record. An admin may add a note, which goes to the applicant by email and is never stored. The person stays a follower. | +| **add** | none, follower, applicant | member | `project-admin` \| `staff` | Immediate; no confirmation step. `via = added`. Adding an applicant also resolves their application as `accepted`. The added person gets an email notice. | +| **promote** | member | member + admin | `project-admin` \| `staff` | Only a member can be made admin. | +| **demote** | member + admin | member | `project-admin` \| `staff` | Any admin may demote any admin, themselves included. Leaving no admin needs [confirmation](#the-last-admin). | +| **leave** | member | follower | self | The person keeps following; `role`, `isAdmin` and `joinedAt` are cleared. Leaving with `alsoUnfollow` deletes the record instead. | +| **remove** | member | none | `project-admin` \| `staff` | Deletes the record: a person an admin removed is not left following. They may follow again. | +| **update role** | member | member | `project-admin` \| `staff`, or self for their own `role` | Freeform label. | + +Every transition is one write through the write mutex and one public commit +([storage.md](storage.md#commit-message-shape)), `Action: +project-membership.` (`follow`, `unfollow`, `apply`, `accept`, +`close`, `add`, `promote`, `demote`, `leave`, `remove`, `update`). A commit's message body never quotes the offer text; the record's +diff is the record. A close by the site is committed as the site (`cfp-api`), +once per sweep run, listing the records it closed. + +### Project creation + +Creating a project writes the creator's membership as `member`, +`isAdmin = true`, `role = "Founder"`, `via = created`, in the same commit as +the project. + +### The last admin + +A project may end up with no admin, and that is a state the site handles +rather than forbids: people must always be able to leave. A **leave**, +**demote** or **remove** that would leave the project with no admin who is an +active member is refused with `409 last_admin` unless the request carries +`confirmLastAdmin: true`. Staff may do the same with the same confirmation. + +### Re-apply limits + +- **One application at a time** per person per project: the record has one + state. +- **After an admin closes an application,** the person may not apply to that project again for + **30 days** from `application.closedAt` (`409 reapply_too_soon` with + `reapplyAfter`). The project page tells them the date. +- **After they close it themselves, or the site closes it for age,** they may + apply again at once. +- **Site-wide:** at most **3** open applications per person across all + projects, and at most **5** applications submitted per person in any rolling + 24 hours (`429 rate_limited`). These sit on top of the general write limits + in [conventions.md](../api/conventions.md#rate-limiting). + +## Applying + +An application selects **zero or more open needs** of the project and carries +an **offer**: free text, 1–1,500 characters, required when no need is +selected and optional otherwise ("Tell the admins what you'd like to help +with"). The offer is plain text everywhere: never rendered as markdown, never +auto-linked, on screens and in email. + +Applying is available when **all** hold; otherwise the project page explains +why instead of showing the button: + +1. The caller is signed in (`user`), is not an agent account, and has no + record on the project in state `applicant` or `member`. +2. The project is not soft-deleted. +3. The project **has an active admin**: at least one `member` record with + `isAdmin = true` whose person is not deactivated and has a deliverable email + (a private profile email with no `emailBounce.inactive`) or a + [linked Slack account](../api/slack-link.md). When none, the page says: + "This project doesn't have an active admin right now. If you're interested + in picking up the torch, talk to the organizers," linking to + [`/chat`](../screens/chat.md). Following stays available. +4. No re-apply wait is running. + +### New-account hold + +An application from an account under **24 hours** old is recorded at once but +**held**: admins are not notified and it is not listed to them until the +account is 24 hours old (`application.visibleAt`). This gives spam review its +first day, when most spam is caught +([api/moderation.md](../api/moderation.md)). The applicant sees their +application as sent either way. + +### What admins see + +On the [Applications screen](../screens/project-applications.md) and in the +notification, facts only: the applicant's name and profile link, account age, +whether a GitHub account is linked, their other projects as a member, the +needs they picked, and the offer. Never spam scores, evaluator verdicts or +any private field; those stay with staff. + +### Accepting + +Accept writes, in one commit: `state = member`, `via = application`, +`joinedAt = now`, `role` (the admin may edit it; it defaults to the title of +the first selected need, or empty), and `application.status = accepted`, +`decidedById` and `decidedAt`. If the admin ticks "mark filled" for any selected need, +the same commit adds the person to that need's `filledByIds` and sets it +`filled` ([help-wanted-roles.md](help-wanted-roles.md)). The applicant gets an +email. + +### Closing + +"Close application" writes `state = follower`, `application.status = closed`, +`closedBy = admin`, `closedAt` and `decidedById`. The record keeps the +application (needs, offer, how it was closed) as the history; there is one +application per record, so the next application replaces it. The admin may +write a note (≤ 1,000 chars) that is emailed to the applicant and **never +stored**: the data repo is public by design and a written reason does not +belong in it. The applicant gets a short, kind email whether or not there is a +note. It says the project "isn't taking this on right now" and that they are +still following; nothing in the copy reads as a rejection. + +An applicant closing their own application (`closedBy = applicant`) and the +site closing one for age (`closedBy = site`) write the same fields, without +`decidedById`. + +## Spam and deactivated accounts + +- **Hidden everywhere.** Records whose person is deactivated (by themselves or + by a spam vote) are left out of every list, count, admin view, notification + and agent feed, the way deactivated people are left out of public lists + ([person-lifecycle.md](person-lifecycle.md)). They are not changed: a `legit` + vote that reactivates the person brings them back as they were. A held or + open application's 30-day clock keeps running while hidden. +- **Purge** deletes the person's records in every state with the rest of their + data ([person-lifecycle.md](person-lifecycle.md#purge-cascading-hard-delete-admin-only)). +- **No reward.** An application or a follow puts nothing on a project's public + page. The only path onto the public member list is an admin's decision. + +## Notifications + +Email goes through the notifier ([architecture.md](../architecture.md)), +fire-and-forget: a transition succeeds whether or not mail is delivered. +Recipients' addresses are read from their private profiles at send time and +never written to any record or commit. + +| Event | To | Content | +| ----- | -- | ------- | +| Application visible to admins (at once, or when the hold ends) | each active admin of the project | Applicant facts, picked needs, offer, link to the Applications screen | +| Open 14 days with no decision | each active admin, once | Reminder, same link | +| Accept | applicant | Welcome to the project, with its chat channel if set | +| Close by an admin | applicant | The project isn't taking this on right now; the admin's note if any; they are still following | +| Close by the site (age) | applicant | No one got to it in time; they may apply again, and they are still following | +| Add | the added person | Who added them, and how to leave from the project page | +| New project update or new open need | every follower, applicant and member except the poster, unless `muted` | The update or need, a link to the project, a "mute these emails" link to the project page | + +Follower email is capped at **3 per project per 24 hours**; posts past the cap +send nothing (they are on the page). A person mutes a project's email by +setting `muted` on their own record from the project page; muting does not +change their state. + +A notifier that finds no deliverable address for a recipient logs and skips +that recipient; it never falls back to another person. + +## Migration from single maintainers + +A one-shot migration script (see [storage.md → Schema migrations](storage.md#schema-migrations)) +moves every record to this model in one commit: + +- Every existing membership becomes `state = member`, `via = legacy`, keeping + `role` and `joinedAt`. +- A membership becomes `isAdmin = true` when its `isMaintainer` was true **or** + its person is the project's `maintainerId`. (This union also settles the + live projects whose flag and `maintainerId` disagree.) +- `isMaintainer` is removed from memberships and `maintainerId` from projects. +- A project whose `maintainerId` names a person with no membership gets no + membership from it; if no other admin results, the project has no admin + until staff add one. +- The `help-wanted-interest` sheet is dropped, with any records it holds. + +Staff keep every project-admin power on every project, so a project with no +admin can be given one from its Manage Members panel by staff. + +## Principles + +**Local:** + +- **The site is a door that admins open.** When convenience for a would-be + joiner and an admin's control of their roster conflict, the admin wins: + nothing reaches the public member list without an admin's act (or the + person's own founding of the project). +- **Following asks nothing of anyone.** It never needs approval, never shows a + name on the site, and never blocks or delays any other transition. From 9480e65681e3de15b1fbc62137b2d9ee1fc6eb24 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:52:50 +0000 Subject: [PATCH 02/78] docs(specs): model membership states, project admins and on-behalf grants ProjectMembership gains state, isAdmin, via, muted and an embedded application; Project.maintainerId and the help-wanted-interest sheet go. Authorization replaces the maintainer marker with project-admin and adds one narrow on-behalf-of exception for application decisions. Co-Authored-By: Claude Fable 5.2 --- specs/api/conventions.md | 6 +- specs/behaviors/authorization.md | 61 +++++++++++++++--- specs/data-model.md | 107 ++++++++++++++++++------------- 3 files changed, 116 insertions(+), 58 deletions(-) diff --git a/specs/api/conventions.md b/specs/api/conventions.md index ab401a19..5a4482ce 100644 --- a/specs/api/conventions.md +++ b/specs/api/conventions.md @@ -85,13 +85,13 @@ Per-endpoint auth requirements appear in each endpoint table. The vocabulary: | -------- | --------- | | `public` | No authentication required. | | `user` | Any signed-in person. | -| `member` | Signed-in person who has a `ProjectMembership` record for the project. | -| `maintainer` | Signed-in person who is the project's `maintainerId` (or who has `isMaintainer = true` in their `ProjectMembership` record). | +| `member` | Signed-in person whose `ProjectMembership` record for the project has `state = member`. | +| `project-admin` | Signed-in person with a `member` record on the project that has `isAdmin = true`. | | `staff` | `accountLevel` ∈ `{staff, administrator}`. | | `administrator` | `accountLevel = administrator`. | | `self` | The acting person matches the resource's owner (e.g., editing your own profile). | -When multiple are listed (`maintainer | staff`), any one suffices. Cross-cutting rules in [behaviors/authorization.md](../behaviors/authorization.md). +When multiple are listed (`project-admin | staff`), any one suffices. Cross-cutting rules in [behaviors/authorization.md](../behaviors/authorization.md). ## Pagination diff --git a/specs/behaviors/authorization.md b/specs/behaviors/authorization.md index 95b70893..e69ae384 100644 --- a/specs/behaviors/authorization.md +++ b/specs/behaviors/authorization.md @@ -32,14 +32,16 @@ Authorization rules in endpoint and screen specs use these markers. The vocabula | `public` | Always passes. | | `user` | Session is valid and not revoked. `accountLevel != anonymous`. | | `self` | The current user matches the resource owner (their own profile, their own session, their own membership). | -| `member` | Current user has a `ProjectMembership` record for the target project. | -| `maintainer` | Current user is the project's `maintainerId` (or equivalent `isMaintainer = true` on their membership). | +| `member` | Current user has a `ProjectMembership` record for the target project with `state = member`. A follower or applicant record does not satisfy it. | +| `project-admin` | Current user has a `member` record for the target project with `isAdmin = true` ([project-membership.md](project-membership.md)). Not to be confused with the `administrator` account level. | | `poster` / `author` | Current user authored the resource (a buzz item, an update, a help-wanted role). | | `staff` | `accountLevel ∈ {staff, administrator}`. | | `administrator` | `accountLevel = administrator`. | | `agent:` | The request carries an active [agent grant](#agent-grants) that includes ``. | -When multiple markers separated by `|` are listed (`maintainer | staff`), any one satisfying suffices. +When multiple markers separated by `|` are listed (`project-admin | staff`), any one satisfying suffices. + +Staff hold every project-admin power on every project. A staff action on a project where they are not an admin carries the usual `Actor-Account-Level` trailer, so it stays auditable. ## Permission hints in responses @@ -56,7 +58,7 @@ Detail endpoints (e.g., `GET /api/projects/:slug`) return a `permissions` object The hint is **not authoritative**. Every mutation endpoint re-evaluates the rule. A client that lies to itself ("set canEdit to true") can't bypass anything. -`alreadyExpressedInterest` and similar "state about the caller" fields appear alongside `canX` flags when relevant. +"State about the caller" fields appear alongside `canX` flags when relevant — for example the caller's own membership on a project (`viewer.state`, `viewer.reapplyAfter`; [api/projects.md](../api/projects.md#project-shape)). ## Session model — stateless JWTs @@ -147,10 +149,16 @@ session, a browser sign-in, or staff powers. broken token is loud. A request with both a grant and a session cookie is refused the same way. - **What it satisfies.** Only `agent:` markers for its own scopes. For - every other marker — `user`, `self`, `staff`, and the optional-session - behaviour of `public` reads — the caller is anonymous. A grant cannot edit a - profile, join a project, refresh into a cookie session, or reach any endpoint - that does not name its scope. + every other marker — `user`, `self`, `member`, `project-admin`, `staff`, and + the optional-session behaviour of `public` reads — the caller is anonymous. + A grant cannot edit a profile, follow or apply to a project, refresh into a + cookie session, or reach any endpoint that does not name its scope. +- **Acting for a person: one narrow exception.** A grant never acts as a + person, with one exception: `projects:applications:decide` lets an agent + record a project admin's **accept** or **close** of one application on that + admin's behalf ([On behalf of a project admin](#on-behalf-of-a-project-admin)). + No other scope acts for anyone, and no future scope does so without its own + spec change naming the one action it covers. - **Who it is.** The request's `person` is the agent account, so commits are authored by it and self-checks (no voting on yourself) apply. The commit adds `Actor-Kind: agent` and `Grant-Id: ` ([storage.md](storage.md#commit-message-shape)). @@ -168,6 +176,40 @@ session, a browser sign-in, or staff powers. logged (the `authorization` header is redacted from request logs), or written to either data store; only its hash is kept, in the private store. +### On behalf of a project admin + +Project admins may answer an application in Slack, through the ops bot, +rather than on the site. The site lets the bot record that answer only when +it can name a person who could have made it themselves: + +- **Who is named.** The request names the deciding person by their Slack user + id. The site resolves it through the verified link on that person's private + profile ([api/slack-link.md](../api/slack-link.md)); an id with no link is + refused. A self-typed `slackHandle` never counts. +- **What is checked.** The named person must, at that moment, satisfy + `project-admin` for the application's project and not be deactivated. Staff + powers do not carry over: a staff member who is not an admin of the project + decides on the site, not through an agent. +- **What it reaches.** Accept or close of an open application, nothing else + — not adding, removing or promoting members, not editing needs or the + project. The grant must also hold `projects:applications:read` and + `slack:link`. +- **Both names on the record.** The commit is authored by the agent account + with `Actor-Kind: agent`, `Grant-Id: ` and `On-Behalf-Of: `; + the record stores `decidedById` (the admin), `decidedVia = agent` and + `agentGrantId`. `git log --grep='^On-Behalf-Of: '` lists every such act. +- **The admin hears about it.** The site emails the named admin a + confirmation of each decision recorded for them, so a decision they did not + make surfaces at once. Accepting is undone by removing the member; a close + is undone by any admin adding the person directly, which no re-apply wait + blocks. +- **Limits.** At most 30 decisions per agent in any rolling 24 hours + (`429 rate_limited`). + +The site cannot see the Slack conversation. That the admin really said so is +the agent's duty, and the bot's operators answer for it; revoking the grant +stops it at once. + Why not a staff account with a long-lived session: the session JWT lives in cookies minted by a browser sign-in, its refresh token is not rotated, and it carries the full `staff` level (every staff endpoint, every member's email, @@ -194,7 +236,8 @@ Staff-relevant actions that get audit attention by virtue of being commits: - Account-level changes (admin grants/revokes staff) - Project soft-deletes and restores - Tag merges and deletions -- Help-wanted role transitions when performed by staff (not by the project's own maintainer) +- Help-wanted role transitions and membership changes when performed by staff (not by one of the project's own admins) +- Decisions an agent recorded on a project admin's behalf (`On-Behalf-Of` trailer) - Member removals when performed by staff Common audit queries: diff --git a/specs/data-model.md b/specs/data-model.md index 38f3f86c..d3d40a99 100644 --- a/specs/data-model.md +++ b/specs/data-model.md @@ -20,15 +20,11 @@ Only `people` and `projects` have soft-delete (`deletedAt`). PUBLIC (gitsheets) ───────────────────────────────────────────────────── Person ──*── ProjectMembership ──*── Project - │ │ role │ - │ │ joinedAt │ - │ │ isMaintainer │ - │ │ - └── owns ──────────────────────────┴── Project.maintainerId (denormalized) - ProjectUpdate (one-to-many, authored by Person) - ProjectBuzz (one-to-many, posted by Person) - HelpWantedRole (one-to-many) - HelpWantedInterestExpression (one-to-many) + │ state: follower | applicant | member + │ isAdmin (members only) ProjectUpdate (one-to-many, authored by Person) + │ role, via, joinedAt ProjectBuzz (one-to-many, posted by Person) + │ application (embedded) HelpWantedRole (one-to-many; "needs") + └── application.roleIds ──▶ HelpWantedRole BlogPost ──── authored-by ──── Person (0:1; staff-authored long-form posts) @@ -48,7 +44,7 @@ SlugHistory ── points at any renamed entity by (entityType, oldSlug) PRIVATE (S3-compatible bucket) ───────────────────────────────────────── -Person.id ──── PrivateProfile (1:1; email, newsletter prefs) +Person.id ──── PrivateProfile (1:1; email, newsletter prefs, linked Slack user) └── LegacyPasswordCredential (0:1; from laddr import, drains to zero) The audit log for public data is the commit log itself — see @@ -74,7 +70,7 @@ The user/member of the brigade. Replaces laddr's `Emergence\People\Person`. Stor | lastName | string nullable | | | bio | string nullable | markdown | | avatarKey | string nullable | gitsheets attachment key (e.g., `people//avatar.jpg`). If absent, fall back to a generic-avatar placeholder (no email-based gravatar — emails aren't in the public record). | -| slackHandle | string nullable | Slack username (without `@`) for contact + help-wanted Slack DM delivery. Self-edited; not verified. | +| slackHandle | string nullable | Slack username (without `@`), shown for contact. Self-edited; not verified, so never used to route anything — the verified link is `PrivateProfile.slack` ([api/slack-link.md](api/slack-link.md)). | | accountLevel | enum | `user` \| `staff` \| `administrator`. Default `user`. See [behaviors/authorization.md](behaviors/authorization.md). | | githubUserId | int nullable | GitHub's numeric user ID (stable across renames). Set when the Person links a GitHub identity — see [behaviors/account-migration.md](behaviors/account-migration.md). | | githubLogin | string nullable | GitHub username (mutable on GitHub's side; updated on every login). | @@ -124,6 +120,7 @@ The sensitive complement to a Person. Stored in the **private store** (S3-compat | email | string | the user's most-recent GitHub-verified primary email. Refreshed on every OAuth login. Lowercased for canonical form. | | emailRefreshedAt | iso8601 | when `email` was last refreshed from GitHub | | newsletter | object nullable | newsletter subscription state (see below) | +| slack | object nullable | the verified link to a Slack user: `{ teamId, userId, linkedAt }`. Set and cleared only by [api/slack-link.md](api/slack-link.md). | | updatedAt | iso8601 | | The `newsletter` sub-object: @@ -144,12 +141,14 @@ The `newsletter` sub-object: - `byEmail: Map` — for laddr-migration claim flow and "find candidate when GitHub gives us a verified email" - `byUnsubscribeToken: Map` — for newsletter unsubscribe handler +- `bySlackUserId: Map` — resolves the Slack user an agent names ([api/agent-applications.md](api/agent-applications.md)) **Uniqueness:** - `personId` (one profile per Person) - `email` (case-insensitive) — enforced; if a GitHub OAuth login surfaces an email that matches an _unlinked_ legacy Person, the account-claim flow kicks in instead of letting the email collide. - `unsubscribeToken` +- `slack.userId` within `slack.teamId` — one site account per Slack user ## Newsletter sends _(deferred from v1)_ @@ -214,7 +213,7 @@ is (its hash is private — [private-storage.md](behaviors/private-storage.md)). | id | uuid | | | personSlug | string | the agent account. Follows renames like other slug references. | | label | string | 1–80 chars; what and where (e.g. "ops bot, host vm-1") | -| scopes | string[] | from `moderation:read`, `moderation:vote`, `moderation:purge`; `moderation:purge` requires `moderation:read` | +| scopes | string[] | from the scope table in [api/agents.md → Grants](api/agents.md#grants): `moderation:read`, `moderation:vote`, `moderation:purge`, `slack:link`, `projects:applications:read`, `projects:applications:decide`; `moderation:purge` requires `moderation:read`, `projects:applications:decide` requires `projects:applications:read` and `slack:link` | | createdAt | iso8601 | | | createdBySlug | string | the administrator who minted it | | expiresAt | iso8601 | at most 180 days after `createdAt` | @@ -298,8 +297,7 @@ question. | summary | string nullable | short tagline shown on cards; ≤ 280 chars. NEW — laddr derived this from the README first line. We split it out. | | overview | string nullable | long-form project description in markdown. Renamed from laddr's `README` because it is _not_ the same thing as the project's GitHub README — see [deferred.md](deferred.md#cached-github-readme-on-project-pages) for the planned cached-github-readme alongside. | | stage | enum | `commenting` \| `bootstrapping` \| `prototyping` \| `testing` \| `maintaining` \| `drifting` \| `hibernating`. Default `commenting`. See [behaviors/project-stages.md](behaviors/project-stages.md). | -| maintainerId | uuid nullable | references people.id | -| createdById | uuid nullable | references people.id — who created the project on the site; set once on create, never changed (a maintainer change leaves it alone). Absent on projects imported from laddr. Purge uses it ([person-lifecycle.md](behaviors/person-lifecycle.md#purge-cascading-hard-delete-admin-only)). | +| createdById | uuid nullable | references people.id — who created the project on the site; set once on create, never changed (admin changes leave it alone). Absent on projects imported from laddr. Purge uses it ([person-lifecycle.md](behaviors/person-lifecycle.md#purge-cascading-hard-delete-admin-only)). | | usersUrl | string nullable | public-facing site for the project | | developersUrl | string nullable | repo URL | | chatChannel | string nullable | slack channel name, stored without `#` | @@ -324,32 +322,68 @@ question. - `featuredProjectIds: Set` - `projectsByStage: Map>` — for stage filter + facets +A project has no maintainer field. Who runs it is the set of its members with `isAdmin = true` ([behaviors/project-membership.md](behaviors/project-membership.md)); laddr's `MaintainerID` and the earlier `maintainerId` were migrated into that flag. + **Uniqueness:** `slug`, `legacyId` (when present). ## ProjectMembership -Join record between Person and Project. Was laddr's `project_members`. +A person's one relationship to a project: following it, applying to it, or on it. Was laddr's `project_members` (members only). The states, transitions and who may make each one are in [behaviors/project-membership.md](behaviors/project-membership.md). **Sheet:** `project-memberships` **Path template:** `project-memberships/${projectSlug}/${personSlug}.toml` -The composite path makes "list members of project X" a single directory traversal. +The composite path makes "everyone related to project X" a single directory traversal. The record lives in the public data repo in every state, applications included; the **site** shows only members publicly (followers and applicants as a count; applicants in full to the project's admins and staff). | Field | Type | Notes | | ------- | ------ | ------- | | id | uuid | | | projectSlug | string | references `projects.slug`; path field | | personSlug | string | references `people.slug`; path field | -| role | string nullable | freeform. Examples: "Founder", "Designer", "Backend Engineer". | -| isMaintainer | bool | denormalizes `Project.maintainerId` resolving to this member. Update both within the same gitsheets commit when changing the maintainer. | -| joinedAt | iso8601 | | +| state | enum | `follower` \| `applicant` \| `member` | +| isAdmin | bool | project admin. Default `false`; `true` only when `state = member`. Any number per project. | +| role | string nullable | freeform public label, members only. Examples: "Founder", "Designer", "Backend Engineer". ≤ 80 chars. | +| via | enum nullable | how the person became a member: `created` (founded the project) \| `added` (by an admin or staff) \| `application` (accepted) \| `legacy` (migrated). Set when `state` becomes `member`; cleared on leave. | +| muted | bool | default `false`. The person turned off this project's follower email. | +| followedAt | iso8601 | when the record was created (every state follows). | +| joinedAt | iso8601 nullable | when the person became a member; absent unless `state = member`. | +| application | table nullable | the person's latest application to the project, kept after it is decided (see below). Absent if they never applied. | | createdAt | iso8601 | | | updatedAt | iso8601 | | +The `application` table: + +| Field | Type | Notes | +| ------- | ------ | ------- | +| status | enum | `open` \| `accepted` \| `closed` — the vocabulary of needs | +| roleIds | uuid[] | the needs (help-wanted role ids) the applicant selected; may be empty | +| offer | string nullable | plain text, 1–1,500 chars; required when `roleIds` is empty | +| submittedAt | iso8601 | | +| visibleAt | iso8601 | when admins may see it and are notified: `submittedAt`, or the applicant's `createdAt + 24h` if later ([new-account hold](behaviors/project-membership.md#new-account-hold)) | +| remindedAt | iso8601 nullable | when the 14-day reminder went to admins | +| decidedById | uuid nullable | references people.id — the project admin or staff member who accepted or closed it; absent when the applicant or the site closed it | +| decidedAt | iso8601 nullable | | +| decidedVia | enum nullable | `site` \| `agent` — `agent` when an agent recorded the decision on the admin's behalf ([api/agent-applications.md](api/agent-applications.md)) | +| agentGrantId | uuid nullable | the grant, when `decidedVia = agent` | +| closedBy | enum nullable | `admin` \| `applicant` \| `site`; set when `status = closed` | +| closedAt | iso8601 nullable | set when `status = closed` | + +A closing note an admin writes is emailed and **never stored**. No field holds an email address or any other private detail. + +**Validators:** + +- `isAdmin = true` only when `state = member` +- `role`, `via`, `joinedAt` present only when `state = member` (`via` and `joinedAt` required then) +- `state = applicant` iff `application.status = open` +- `application.offer` present when `application.roleIds` is empty +- `closedBy` and `closedAt` present iff `application.status = closed`; `decidedById` present when `status = accepted` or `closedBy = admin` + **Secondary in-memory indices:** - `membershipsByPerson: Map>` — for "my projects" - `membershipsByProject: Map>` — already implicit in path template +- `adminsByProject: Map>` — authorization and the active-admin check +- `openApplications: sorted by application.visibleAt` — the reminder and close-for-age sweep, and the agent feed **Uniqueness:** `(projectSlug, personSlug)`. @@ -495,7 +529,7 @@ This composite path makes "things with tag X" a single directory traversal in th ## HelpWantedRole _(new — not in laddr)_ -A specific volunteer "ask" a maintainer posts on their project. See [behaviors/help-wanted-roles.md](behaviors/help-wanted-roles.md) for the rule set. +A specific volunteer "ask" — a **need** — a project admin posts on their project. See [behaviors/help-wanted-roles.md](behaviors/help-wanted-roles.md) for the rule set. **Sheet:** `help-wanted-roles` **Path template:** `help-wanted-roles/${projectSlug}/${id}.toml` @@ -511,7 +545,8 @@ The `id` is used as the filename (rather than a derived slug) because role title | description | string | markdown. Required. | | commitmentHoursPerWeek | int nullable | rough estimate. 0 = flexible/unspecified. | | status | enum | `open` \| `filled` \| `closed`. Default `open`. | -| filledById | uuid nullable | references people.id. Set when status moves to `filled`. | +| detailsUrl | string nullable | HTTPS link to task-level detail (a GitHub issue, label or doc). | +| filledByIds | uuid[] | references people.id. The people who filled the need; may be empty (filled without attribution) and may hold several. | | filledAt | iso8601 nullable | | | closedAt | iso8601 nullable | | | createdAt | iso8601 | | @@ -522,25 +557,6 @@ The `id` is used as the filename (rather than a derived slug) because role title - `helpWantedByProject: Map>` — implicit in path template - `openHelpWanted: Set` — for the `/help-wanted` global browse and the `?helpWanted=true` project filter -## HelpWantedInterestExpression - -Tracks who has expressed interest in which role. - -**Sheet:** `help-wanted-interest` -**Path template:** `help-wanted-interest/${roleId}/${personSlug}.toml` - -| Field | Type | Notes | -| ------- | ------ | ------- | -| id | uuid | | -| roleId | uuid | references help-wanted-roles.id; path field (roles are keyed by id) | -| personSlug | string | references `people.slug`; path field | -| message | string nullable | ≤ 2,000 chars plain text. Included verbatim in the notification email/DM. | -| createdAt | iso8601 | | - -Used for the 30-day per-person-per-role rate cap on `POST /express-interest` (see [api/projects-help-wanted.md](api/projects-help-wanted.md)). The composite path makes the rate-cap check a path-exists test. - -**Uniqueness:** `(roleId, personSlug)` _within the trailing 30 days_ — enforced by the API (read the existing record if any, check `createdAt`, accept-or-reject). - ## Event _(new — replaces Meetup.com)_ A single gathering at one venue over one contiguous span: a hack night, a workshop, one day of a hackathon. Staff-authored; members RSVP. Rules in [behaviors/events.md](behaviors/events.md). Events are **flat** — one record is one thing you can RSVP to. Two optional structures hang off it: a link to an [EventSeries](#eventseries-new) ("Launchpad 2018", "Monthly Hack Nights") and an embedded **agenda** of time slots within the event. A program that moves between venues or spans days is a series of events, not one event. @@ -690,7 +706,6 @@ See [behaviors/storage.md](behaviors/storage.md#commits-are-the-audit-log) for t | From | To | Cardinality | Field | | ------ | ---- | -----------: | ---- | -| Project | Person | many-to-one (maintainer) | `Project.maintainerId` | | ProjectMembership | Project | many-to-one | `ProjectMembership.projectSlug` | | ProjectMembership | Person | many-to-one | `ProjectMembership.personSlug` | | ProjectUpdate | Project | many-to-one | `ProjectUpdate.projectSlug` | @@ -699,9 +714,9 @@ See [behaviors/storage.md](behaviors/storage.md#commits-are-the-audit-log) for t | ProjectBuzz | Person | many-to-one (postedBy) | `ProjectBuzz.postedById` | | BlogPost | Person | many-to-one (author) | `BlogPost.authorId` | | HelpWantedRole | Project | many-to-one | `HelpWantedRole.projectSlug` | -| HelpWantedRole | Person | many-to-one (postedBy / filledBy) | `HelpWantedRole.postedById`, `filledById` | -| HelpWantedInterestExpression | HelpWantedRole | many-to-one | `roleId` | -| HelpWantedInterestExpression | Person | many-to-one | `personSlug` | +| HelpWantedRole | Person | many-to-one (postedBy); many-to-many (filledBy) | `HelpWantedRole.postedById`, `filledByIds` | +| ProjectMembership | HelpWantedRole | many-to-many (selected needs) | `ProjectMembership.application.roleIds` | +| ProjectMembership | Person | many-to-one (decided by) | `ProjectMembership.application.decidedById` | | TagAssignment | Tag | many-to-one | `tagId` | | TagAssignment | Project \| Person \| HelpWantedRole \| BlogPost | polymorphic | `taggableType + taggableId` | | Event | Person | many-to-one (createdBy) | `Event.createdById` | @@ -721,9 +736,9 @@ Cascading deletes are not enforced by gitsheets; the API's mutation services del | `projects.Title` | `projects.title` | | `projects.README` | `projects.overview` (renamed: GitHub READMEs are a different thing; see [deferred.md](deferred.md#cached-github-readme-on-project-pages)) | | `projects.Stage` (TitleCase) | `projects.stage` (lowercase) | -| `projects.MaintainerID` | `projects.maintainerId` | +| `projects.MaintainerID` | `ProjectMembership.isAdmin = true` on that person's membership (migrated; see [behaviors/project-membership.md](behaviors/project-membership.md#migration-from-single-maintainers)) | | `projects.UsersUrl` / `DevelopersUrl` / `ChatChannel` | `projects.usersUrl` / `developersUrl` / `chatChannel` | -| `project_members` | `project-memberships` sheet | +| `project_members` | `project-memberships` sheet, `state = member` | | `project_updates.Number` | `ProjectUpdate.number` | | `project_buzz.Headline` / `URL` / `Published` / `Summary` / `ImageID` | `ProjectBuzz.headline` / `url` / `publishedAt` / `summary` / `imageKey` | | `tags.Handle` (e.g., `topic.transit`) | `tags.namespace = 'topic'`, `tags.slug = 'transit'` | From 09f101103c38066f2e9bd825ddd0d95485417675 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:54:17 +0000 Subject: [PATCH 03/78] docs(specs): specify follow, applications and admin endpoints Members API gains follow/unfollow/mute and admin promote/demote, loses open join. New applications API: apply, accept, close. Projects drop change-maintainer; needs drop express-interest and fill by many. Co-Authored-By: Claude Fable 5.2 --- specs/api/projects-applications.md | 166 +++++++++++++++++++++++++++++ specs/api/projects-help-wanted.md | 62 ++++------- specs/api/projects-members.md | 127 +++++++++++++++------- specs/api/projects.md | 59 +++++----- specs/data-model.md | 1 + 5 files changed, 304 insertions(+), 111 deletions(-) create mode 100644 specs/api/projects-applications.md diff --git a/specs/api/projects-applications.md b/specs/api/projects-applications.md new file mode 100644 index 00000000..3fc887a9 --- /dev/null +++ b/specs/api/projects-applications.md @@ -0,0 +1,166 @@ +# API: Project Applications + +Apply to join a project, and decide applications. An application is not a record of its own: it is the `application` table on the person's [ProjectMembership](../data-model.md#projectmembership), and applying moves the record to `state = applicant`. An application is `open`, then `accepted` or `closed` — the same words as [needs](../behaviors/help-wanted-roles.md). Rules, limits and emails: [behaviors/project-membership.md](../behaviors/project-membership.md). + +## Endpoints + +| Method | Path | Auth | Summary | +| ------ | ---- | ---- | ------- | +| `POST` | `/api/projects/:slug/applications` | user | Apply (or re-apply) to the project. | +| `POST` | `/api/projects/:slug/applications/mine/close` | user (self) | Close your own open application. | +| `GET` | `/api/projects/:slug/applications` | project-admin \| staff | List the project's applications. | +| `POST` | `/api/projects/:slug/applications/:personSlug/accept` | project-admin \| staff | Accept: the applicant becomes a member. | +| `POST` | `/api/projects/:slug/applications/:personSlug/close` | project-admin \| staff | "Close application": the applicant stays a follower. | + +Applications are addressed by the applicant's slug: a person has at most one application per project. + +## POST /api/projects/:slug/applications + +### Request + +```json +{ + "roleIds": [""], + "offer": "I've built two React apps and have about 4 hours a week." +} +``` + +| Field | Required | Notes | +| ----- | -------- | ----- | +| roleIds | no | Open needs of this project. Each must exist, belong to the project and have `status = open`. Default `[]`. | +| offer | when `roleIds` is empty | Plain text, 1–1,500 chars. | + +Creates the record (`state = applicant`) or moves the caller's `follower` record to `applicant`, replacing any earlier, decided application on it. `application.visibleAt` is `now`, or the caller's `createdAt + 24h` if later. Admins are emailed when `visibleAt` arrives. + +### Response — 201 + +```json +{ "success": true, "data": { "state": "applicant", "application": Application } } +``` + +### Errors + +- `409 conflict`, `error.code`: + - `already_member` — the caller is a member + - `application_open` — the caller already has an open application here + - `no_active_admin` — the project has no active admin ([Applying](../behaviors/project-membership.md#applying)) + - `reapply_too_soon` — an admin closed the caller's last application here under 30 days ago; `error.details.reapplyAfter` gives the date +- `422 validation_failed` — unknown, foreign or not-open `roleIds`; missing or too-long `offer`; caller is an agent account +- `429 rate_limited` — more than 3 open applications site-wide, or 5 submitted in 24 hours + +## POST /api/projects/:slug/applications/mine/close + +No body. Closes the caller's open application (`closedBy = applicant`); the caller stays a follower. + +### Response — 200 + +### Errors + +- `404 not_found` — no open application + +## GET /api/projects/:slug/applications + +### Query + +| Param | Type | Notes | +| ----- | ---- | ----- | +| `status` | enum | `open` (default) \| `accepted` \| `closed` \| `all` | +| `page`, `perPage` | int | Default `perPage = 20`. | + +Lists records with an `application`, newest `submittedAt` first. Leaves out applications whose `visibleAt` is in the future (the new-account hold) and applicants who are deactivated. Staff see the same list as an admin. + +### Response — 200 + +```json +{ + "success": true, + "data": [ + { + "person": PersonAvatar, + "applicant": { + "accountCreatedAt": "...", + "hasGitHubLink": true, + "memberOf": [{ "slug": "phlask", "title": "PHLASK" }] + }, + "state": "applicant", + "application": Application + } + ], + "metadata": { "counts": { "open": 2, "accepted": 5, "closed": 3 } } +} +``` + +`applicant` holds facts only — never spam scores, votes, or private fields. + +### Application shape + +```json +{ + "status": "open", + "roles": [{ "id": "", "title": "Frontend dev", "status": "open" }], + "offer": "I've built two React apps...", + "submittedAt": "...", + "visibleAt": "...", + "decidedBy": PersonAvatar | null, + "decidedAt": null, + "decidedVia": null, + "closedBy": null, + "closedAt": null +} +``` + +The applicant sees their own application in this shape as `viewer.application` on `GET /api/projects/:slug`, without `decidedBy`. + +## POST /api/projects/:slug/applications/:personSlug/accept + +### Request + +```json +{ "role": "Frontend dev", "fillRoleIds": [""], "isAdmin": false } +``` + +| Field | Required | Notes | +| ----- | -------- | ----- | +| role | no | Defaults to the title of the first selected need, else absent. ≤ 80 chars. | +| fillRoleIds | no | Subset of the application's `roleIds` that are still open. Each gets the applicant added to `filledByIds` and moves to `filled`. | +| isAdmin | no | Default `false`. | + +One commit: membership to `member` (`via = application`), `application.status = accepted` with `decidedById`, `decidedAt`, `decidedVia = site`, and any fills. The applicant is emailed. + +### Response — 200 + +```json +{ "success": true, "data": ProjectMembership } +``` + +### Errors + +- `404 not_found` — no open application from that person (or they are deactivated, or still held) +- `422 validation_failed` — `fillRoleIds` not a subset of the application's open needs + +## POST /api/projects/:slug/applications/:personSlug/close + +### Request + +```json +{ "note": "We're full on frontend this season — keep an eye on our needs." } +``` + +| Field | Required | Notes | +| ----- | -------- | ----- | +| note | no | Plain text, ≤ 1,000 chars. **Emailed to the applicant and never stored** or written to the commit. | + +Sets `state = follower`, `application.status = closed`, `closedBy = admin`, `closedAt`, `decidedById`, `decidedAt`, `decidedVia = site`. The applicant gets an email that says the project isn't taking this on right now, with the note if any, and that they're still following. + +### Response — 200 + +### Errors + +- `404 not_found` — as for accept + +## Notes + +- **Commits.** `Action: project-membership.apply`, `…accept`, `…close`. The commit body never quotes `offer` or `note`. A close by the site for age is one sweep commit by `cfp-api`. +- **Sweeps.** An in-process job (daily, and shortly after boot) sends the 14-day reminder to admins, closes applications open 30 days past `visibleAt` (`closedBy = site`), and sends notifications whose `visibleAt` has arrived. Sends are at most once: the job records `notifiedAt` or `remindedAt` on the application, in its own commit, before sending (the same pattern as event reminders, [behaviors/events.md](../behaviors/events.md#reminders)). An application from an account old enough is notified in the request that creates it, recording `notifiedAt` in that commit. +- **Agents** read open applications and record decisions on an admin's behalf through [agent-applications.md](agent-applications.md), not these endpoints. +- **Visibility.** The data repo holds applications like every membership record. The site shows them only to the applicant, the project's admins and staff. diff --git a/specs/api/projects-help-wanted.md b/specs/api/projects-help-wanted.md index 33ae1d28..dfc918b9 100644 --- a/specs/api/projects-help-wanted.md +++ b/specs/api/projects-help-wanted.md @@ -1,18 +1,19 @@ # API: Project Help-Wanted Roles -Specific volunteer asks posted by project maintainers — the new feature in v1. See [data-model.md](../data-model.md#helpwantedrole) and [behaviors/help-wanted-roles.md](../behaviors/help-wanted-roles.md). +Specific volunteer asks — **needs** — posted by project admins. People apply to a project selecting one or more open needs ([projects-applications.md](projects-applications.md)). See [data-model.md](../data-model.md#helpwantedrole) and [behaviors/help-wanted-roles.md](../behaviors/help-wanted-roles.md). ## Endpoints | Method | Path | Auth | Summary | | ------ | ---- | ---- | ------- | | `GET` | `/api/projects/:slug/help-wanted` | public | List a project's help-wanted roles (open and closed). | -| `POST` | `/api/projects/:slug/help-wanted` | maintainer \| staff | Post a new role. | -| `PATCH` | `/api/projects/:slug/help-wanted/:roleId` | poster \| maintainer \| staff | Edit a role. | -| `POST` | `/api/projects/:slug/help-wanted/:roleId/express-interest` | user | Express interest in a role (notifies the maintainer). | -| `POST` | `/api/projects/:slug/help-wanted/:roleId/fill` | maintainer \| staff | Mark as filled, optionally by a specific person. | -| `POST` | `/api/projects/:slug/help-wanted/:roleId/close` | maintainer \| staff | Close without filling (cancelled, expired). | -| `POST` | `/api/projects/:slug/help-wanted/:roleId/reopen` | maintainer \| staff | Reopen a previously filled/closed role. | +| `POST` | `/api/projects/:slug/help-wanted` | project-admin \| staff | Post a new role. | +| `PATCH` | `/api/projects/:slug/help-wanted/:roleId` | project-admin \| staff | Edit a role. | +| `POST` | `/api/projects/:slug/help-wanted/:roleId/fill` | project-admin \| staff | Mark as filled, by zero or more people. | +| `POST` | `/api/projects/:slug/help-wanted/:roleId/close` | project-admin \| staff | Close without filling (cancelled, no longer needed). | +| `POST` | `/api/projects/:slug/help-wanted/:roleId/reopen` | project-admin \| staff | Reopen a previously filled/closed role. | + +"Express interest" is gone: a person interested in a need applies to the project with that need selected. `POST …/express-interest` answers `410 gone` for one release, then `404`. A poster who is no longer an admin can no longer edit their role. | `GET` | `/api/help-wanted` | public | Cross-project browse of open roles. | ## GET /api/projects/:slug/help-wanted @@ -40,6 +41,7 @@ Specific volunteer asks posted by project maintainers — the new feature in v1. "title": "React developer for admin dashboard", "description": "Markdown details on what we need.", "commitmentHoursPerWeek": 4, + "detailsUrl": "https://github.com/example/repo/issues?q=label%3Afrontend", "tags": { "tech": ["react", "typescript"] } @@ -51,6 +53,7 @@ Specific volunteer asks posted by project maintainers — the new feature in v1. | title | yes | 1–120 chars. | | description | yes | Markdown. 1–4,000 chars. | | commitmentHoursPerWeek | no | Int ≥ 0. 0 means flexible/unspecified. | +| detailsUrl | no | HTTPS URL to task-level detail. | | tags | no | Same shape as projects. Tags are scoped via `taggableType = 'help_wanted_role'`. | ### Response — 201 @@ -59,9 +62,11 @@ Specific volunteer asks posted by project maintainers — the new feature in v1. { "success": true, "data": HelpWantedRole } ``` +Applications may select only `open` roles. An open application that selected a role keeps the id after the role closes; the Applications screen shows the role's current status. + ## PATCH /api/projects/:slug/help-wanted/:roleId -Editable fields: `title`, `description`, `commitmentHoursPerWeek`, `tags`. Status changes go through the dedicated transition endpoints. +Editable fields: `title`, `description`, `commitmentHoursPerWeek`, `detailsUrl`, `tags`. Status changes go through the dedicated transition endpoints. ### Response — 200 @@ -69,44 +74,20 @@ Editable fields: `title`, `description`, `commitmentHoursPerWeek`, `tags`. Statu { "success": true, "data": HelpWantedRole } ``` -## POST /api/projects/:slug/help-wanted/:roleId/express-interest - -Records that the current user is interested. The maintainer is notified via email and (if configured) a Slack DM. Self-service interest does not change the role's status. - -### Request - -```json -{ "message": "Hi! I'd love to help. I've shipped 3 React dashboards before." } -``` - -| Field | Required | Notes | -| ----- | -------- | ----- | -| message | no | ≤ 2,000 chars plain text. Included in the notification verbatim. | - -### Response — 202 - -```json -{ "success": true, "data": { "delivered": true } } -``` - -### Errors - -- `409 conflict` with `error.code = "already_expressed"` — caller has already expressed interest in this role within the last 30 days -- `409 conflict` with `error.code = "role_not_open"` — role is filled or closed - ## POST /api/projects/:slug/help-wanted/:roleId/fill ### Request ```json -{ "filledBySlug": "newperson" } +{ "filledBySlugs": ["newperson"], "keepOpen": false } ``` | Field | Required | Notes | | ----- | -------- | ----- | -| filledBySlug | no | Person slug. If omitted, role is marked filled without attribution. | +| filledBySlugs | no | Slugs of the project's **members** who filled it. Omitted or empty marks it filled without attribution. | +| keepOpen | no | `true` records the people in `filledByIds` but leaves the need `open`, for a need several people can fill. Default `false`. | -Sets `status = 'filled'`, `filledAt = now()`, and (if provided) `filledById`. Also adds `filledBy` as a project member with role `"Help-wanted: "` if they aren't already a member — see [behaviors/help-wanted-roles.md](../behaviors/help-wanted-roles.md). +Adds the people to `filledByIds` and, unless `keepOpen`, sets `status = 'filled'`, `filledAt = now()`. Filling never adds anyone to the project: a person must already be a member (`422`, `error.code = "not_a_member"` otherwise). To bring someone new in for a need, accept their application with "mark filled", or add them first — see [behaviors/help-wanted-roles.md](../behaviors/help-wanted-roles.md). ### Response — 200 @@ -126,7 +107,7 @@ Sets `status = 'closed'`, `closedAt = now()`. Does not modify project membership ## POST /api/projects/:slug/help-wanted/:roleId/reopen -Reverts to `status = 'open'`, clears `filledAt`/`filledById`/`closedAt`. Membership added by a previous `fill` is **not** auto-removed. +Reverts to `status = 'open'`, clears `filledAt`/`filledByIds`/`closedAt`. Memberships are untouched. ### Response — 200 @@ -176,15 +157,14 @@ Cross-project browse of open roles. Used by the `/help-wanted` screen. "descriptionHtml": "<p>...</p>", "commitmentHoursPerWeek": 4, "status": "open", - "filledBy": PersonAvatar | null, + "detailsUrl": "https://..." | null, + "filledBy": [PersonAvatar, ...], "filledAt": null, "closedAt": null, "tags": { "topic": [...], "tech": [...] }, - "interestCount": 3, "permissions": { "canEdit": false, - "canExpressInterest": true, - "alreadyExpressedInterest": false, + "canApply": true, "canFill": false, "canClose": false }, diff --git a/specs/api/projects-members.md b/specs/api/projects-members.md index 5f4d352d..b3f6b3f5 100644 --- a/specs/api/projects-members.md +++ b/specs/api/projects-members.md @@ -1,36 +1,73 @@ # API: Project Memberships -Manage the roster of people on a project. See [data-model.md](../data-model.md#projectmembership). +Follow a project, and manage who is on it. One [ProjectMembership](../data-model.md#projectmembership) record per person per project carries every state; the rules, transitions and who may make each one are in [behaviors/project-membership.md](../behaviors/project-membership.md). Applying and deciding applications are in [projects-applications.md](projects-applications.md). ## Endpoints | Method | Path | Auth | Summary | | ------ | ---- | ---- | ------- | -| `POST` | `/api/projects/:slug/members` | maintainer \| staff | Add a member by person slug. | -| `PATCH` | `/api/projects/:slug/members/:personSlug` | maintainer \| staff | Update role. | -| `DELETE` | `/api/projects/:slug/members/:personSlug` | maintainer \| staff | Remove a member. | -| `POST` | `/api/projects/:slug/members/join` | user | Join the project as the current user. | -| `POST` | `/api/projects/:slug/members/leave` | user (self) | Leave the project. | +| `POST` | `/api/projects/:slug/follow` | user | Follow the project. | +| `DELETE` | `/api/projects/:slug/follow` | user (self) | Stop following (followers only). | +| `PATCH` | `/api/projects/:slug/follow` | user (self) | Mute or unmute this project's follower email. | +| `POST` | `/api/projects/:slug/members` | project-admin \| staff | Add a person as a member, at once. | +| `PATCH` | `/api/projects/:slug/members/:personSlug` | project-admin \| staff; self for own `role` | Update `role` and `isAdmin`. | +| `DELETE` | `/api/projects/:slug/members/:personSlug` | project-admin \| staff | Remove a member (deletes the record). | +| `POST` | `/api/projects/:slug/members/leave` | user (self) | Leave the project (member → follower). | -Listing memberships is part of `GET /api/projects/:slug` — there is no separate `GET /api/projects/:slug/members` for v1. +There is no join endpoint: membership comes from an accepted application or an admin's add. `POST /api/projects/:slug/members/join` answers `410 gone` (`error.code = "join_removed"`) for one release after this change, then `404`. + +Listing members is part of `GET /api/projects/:slug` (members only). Applicants are listed by `GET /api/projects/:slug/applications` to admins and staff. Followers are never listed by any endpoint; the project shows their count. + +Every endpoint here treats a person who is deactivated as absent, and refuses agent accounts as the subject (`422`, `error.code = "agent_account"`): an agent never follows, applies or joins. + +## POST /api/projects/:slug/follow + +No body. Creates a `follower` record. If the caller already has a record in any state, `200` with it unchanged (following is inherent in every state). + +### Response — 201 / 200 + +```json +{ "success": true, "data": { "state": "follower", "muted": false, "followedAt": "..." } } +``` + +## DELETE /api/projects/:slug/follow + +Deletes the caller's `follower` record. + +### Response — 204 + +### Errors + +- `409 conflict` with `error.code = "not_a_follower"` — the caller is an applicant (close the application first) or a member (leave first) +- `404 not_found` — no record + +## PATCH /api/projects/:slug/follow + +```json +{ "muted": true } +``` + +Works in every state. Changes only `muted`. + +### Response — 200 ## POST /api/projects/:slug/members -Add an existing person to the project. The person must already have an account. +Add an existing person as a member, immediately. No confirmation from them. ### Request ```json -{ - "personSlug": "newperson", - "role": "Backend Engineer" -} +{ "personSlug": "newperson", "role": "Backend Engineer", "isAdmin": false } ``` | Field | Required | Notes | | ----- | -------- | ----- | -| personSlug | yes | Existing person's slug. | -| role | no | Freeform string, ≤ 80 chars. Null/missing means no role label. | +| personSlug | yes | Existing, active person's slug. | +| role | no | Freeform, ≤ 80 chars. Absent means no label. | +| isAdmin | no | Default `false`. | + +Works whether the person has no record, is a follower, or is an applicant (an applicant's open application becomes `accepted`, decided by the caller). Sets `state = member`, `via = added`, `joinedAt = now`. The person gets an email notice saying who added them and that they can leave from the project page. ### Response — 201 @@ -40,67 +77,79 @@ Add an existing person to the project. The person must already have an account. ### Errors -- `404 not_found` — person doesn't exist -- `409 conflict` with `error.code = "already_member"` — person is already on the project +- `404 not_found` — person doesn't exist or is deactivated +- `409 conflict` with `error.code = "already_member"` ## PATCH /api/projects/:slug/members/:personSlug -Update the membership row. Only `role` is editable; transferring the maintainer flag is done via `POST /api/projects/:slug/change-maintainer`. - -### Request - ```json -{ "role": "Designer" } +{ "role": "Designer", "isAdmin": true } ``` +| Field | Who | Notes | +| ----- | --- | ----- | +| role | project-admin, staff, or the member themselves | ≤ 80 chars; `null` clears. | +| isAdmin | project-admin, staff | `true` promotes, `false` demotes. Any admin may demote any admin. | +| confirmLastAdmin | — | Required `true` when the change leaves the project with no active admin. | + +Only `member` records can be patched (`409 not_a_member` otherwise). A promote commits `Action: project-membership.promote`, a demote `…demote`, a role-only change `…update`. + ### Response — 200 ```json { "success": true, "data": ProjectMembership } ``` +### Errors + +- `409 conflict` with `error.code = "last_admin"` — demote would leave no active admin and `confirmLastAdmin` is not `true` +- `409 conflict` with `error.code = "not_a_member"` + ## DELETE /api/projects/:slug/members/:personSlug -Remove the member. Cannot remove the current maintainer — respond `409 conflict` with `error.code = "cannot_remove_maintainer"`. Use `change-maintainer` first. +Removes a member: deletes the record. The person is not left following; they may follow again. Query `?confirmLastAdmin=true` when removing the last active admin. An admin removing themselves should leave instead; this endpoint allows it. ### Response — 204 -## POST /api/projects/:slug/members/join +### Errors -Add the current user to the project. No body. Used by the "Join project" affordance on the project page. +- `409 conflict` with `error.code = "last_admin"` +- `409 conflict` with `error.code = "not_a_member"` — the person is a follower or applicant (followers are not admins' to manage) -### Response — 201 +## POST /api/projects/:slug/members/leave ```json -{ "success": true, "data": ProjectMembership } +{ "alsoUnfollow": false, "confirmLastAdmin": false } ``` -`role` is null on self-join. The user can then `PATCH` their own membership to set a role, or the maintainer can. +Both fields optional. Moves the caller from `member` to `follower` (clearing `role`, `isAdmin`, `via`, `joinedAt`), or deletes the record when `alsoUnfollow` is `true`. -### Errors - -- `409 conflict` with `error.code = "already_member"` - -## POST /api/projects/:slug/members/leave - -Remove the current user. The current user cannot leave if they are the maintainer; transfer first. - -### Response — 204 +### Response — 200 (still following) / 204 (record deleted) ### Errors -- `409 conflict` with `error.code = "cannot_remove_maintainer"` -- `404 not_found` — user is not a member +- `409 conflict` with `error.code = "last_admin"` +- `409 conflict` with `error.code = "not_a_member"` ## ProjectMembership response shape +Members, as listed on `GET /api/projects/:slug` (public): + ```json { "id": "<uuid>", "projectSlug": "squadquest", "person": PersonAvatar, "role": "Designer", - "isMaintainer": true, + "isAdmin": true, + "via": "application", "joinedAt": "..." } ``` + +Ordered admins first, then `role` ascending, then full name. `via` is shown only to project admins and staff (`null` for others). + +## Notes + +- Every write here is one commit, `Action: project-membership.<transition>` per [project-membership.md](../behaviors/project-membership.md#transitions). +- Staff hold project-admin powers on every project ([authorization.md](../behaviors/authorization.md#per-context-markers)). diff --git a/specs/api/projects.md b/specs/api/projects.md index 9f0bbab9..ae1485e1 100644 --- a/specs/api/projects.md +++ b/specs/api/projects.md @@ -10,11 +10,10 @@ See [data-model.md](../data-model.md#project) for the entity shape, [behaviors/p | --- | --- | --- | --- | | `GET` | `/api/projects` | public | List/browse projects with filters and sort. | | `GET` | `/api/projects/:slug` | public | Fetch a single project. | -| `POST` | `/api/projects` | user | Create a new project (caller becomes maintainer). | -| `PATCH` | `/api/projects/:slug` | maintainer \| staff | Update fields. | +| `POST` | `/api/projects` | user | Create a new project (caller becomes its first admin). | +| `PATCH` | `/api/projects/:slug` | project-admin \| staff | Update fields. | | `DELETE` | `/api/projects/:slug` | staff | Soft-delete a project. | | `POST` | `/api/projects/:slug/restore` | staff | Undo a soft-delete. | -| `POST` | `/api/projects/:slug/change-maintainer` | maintainer \| staff | Reassign the maintainer to another existing member. | ## GET /api/projects @@ -26,8 +25,8 @@ See [data-model.md](../data-model.md#project) for the entity shape, [behaviors/p | `stage` | enum | `commenting` \| `bootstrapping` \| `prototyping` \| `testing` \| `maintaining` \| `drifting` \| `hibernating` | | `stageIn` | csv-of-enum | Multi-value filter. | | `tag` | string | Tag handle in `<namespace>.<slug>` form (e.g., `tech.flutter`). Repeatable; **OR within namespace, AND across namespaces.** `?tag=topic.transit&tag=topic.mapping&tag=tech.python` returns projects that are tagged `(topic.transit OR topic.mapping) AND tech.python`. Matches the conventional faceted-search behavior — within a facet group users widen, across groups they narrow. | -| `maintainer` | string | Person slug. | -| `memberSlug` | string | Person slug — returns projects where this person is in `project-memberships`. | +| `admin` | string | Person slug — projects where this person is a member with `isAdmin = true`. `maintainer` is accepted as an alias so old links keep working. | +| `memberSlug` | string | Person slug — projects where this person has a `state = member` record. | | `helpWanted` | bool | If `true`, only projects with at least one `helpWantedRoles.status = 'open'`. | | `featured` | bool | If `true`, only projects with `featured = true`. Used by the home page. | | `sort` | sort spec | Default `-updatedAt`, except that a request with `q` and no `sort` lists in relevance order. Allowed keys: `createdAt`, `updatedAt`, `title`, `stage` (stage ordered by `project-stages.md` rank), `activity` — the project's most recent sign of life: the latest of an RSVP naming it (`updatedAt`), a project update (`createdAt`), or a buzz item logged (`createdAt`, not the article's `publishedAt`). Projects with no activity sort after every project that has some, in either direction, then by `-updatedAt`. Used by the home page to top up "Join a Project". | @@ -76,9 +75,9 @@ The summary shape used in lists; smaller than the detail response. "summary": "Realtime community events without Facebook.", "stage": "testing", "overviewExcerpt": "SquadQuest is a different kind of civic technology...", // <= 600 chars, plain text (markdown stripped) - "maintainer": { "slug": "chris", "fullName": "Chris Alfano", "avatarUrl": "..." } | null, - "memberCount": 5, - "members": [PersonAvatar, ...], // first 10 by role then alpha + "admins": [PersonAvatar, ...], // members with isAdmin, by joinedAt + "memberCount": 5, // state = member only + "members": [PersonAvatar, ...], // first 10: admins first, then role, then alpha "links": { "usersUrl": "https://squadquest.app", "developersUrl": "https://github.com/SquadQuest/SquadQuest", @@ -115,15 +114,26 @@ Fetches a single project by slug. "overviewHtml": "<h2>Markdown source ...", // sanitized HTML rendered server-side "stage": "testing", "stageProgress": 0.5, // derived; see project-stages.md - "maintainer": Person | null, - "memberships": [ProjectMembership, ...], // includes all members + "memberships": [ProjectMembership, ...], // state = member only, admins first + "followerCount": 12, // records in state follower or applicant + "hasActiveAdmin": true, // see project-membership.md → Applying + "viewer": { // the caller's own record; null when signed out or none + "state": "follower", // follower | applicant | member + "isAdmin": false, + "muted": false, + "application": Application | null, // projects-applications.md, without decidedBy + "reapplyAfter": null // set while the re-apply wait runs + } | null, "openHelpWantedRoles": [HelpWantedRole, ...], "tags": { "topic": [Tag, ...], "tech": [Tag, ...], "event": [Tag, ...] }, "links": { "usersUrl": "...", "developersUrl": "...", "chatChannel": "..." }, - "counts": { "updates": 12, "buzz": 3, "members": 5 }, + "counts": { "updates": 12, "buzz": 3, "members": 5, "followers": 12, "openApplications": 2 }, "permissions": { "canEdit": true, "canManageMembers": false, + "canReviewApplications": false, + "canFollow": true, + "canApply": true, "canPostUpdate": true, "canLogBuzz": true, "canPostHelpWanted": true, @@ -135,6 +145,8 @@ Fetches a single project by slug. } ``` +`counts.openApplications` is `null` unless the caller is a project admin or staff. Follower and applicant counts, and the members list, leave out deactivated people. No endpoint lists followers. + `permissions` is the *current caller's* permissions on this project — the frontend uses it to decide which actions to render. The server still enforces the same rules on each mutation endpoint. `deletedAt` is `null` for active projects. It is non-null only when a soft-deleted project is fetched by staff (non-staff get `404`), so the SPA can render the soft-delete banner with a Restore action. @@ -145,7 +157,7 @@ Fetches a single project by slug. ## POST /api/projects -Create a new project. Caller becomes the maintainer, is added as a `Founder` membership, and is recorded as the project's `createdById` (never changed afterwards; not part of any request or update). +Create a new project. Caller gets a membership with `state = member`, `isAdmin = true`, `role = "Founder"`, `via = created`, and is recorded as the project's `createdById` (never changed afterwards; not part of any request or update). ### Request @@ -186,14 +198,13 @@ Update one or more fields. Field-level. Omitted fields are unchanged. Tags, if p ### Allowed fields by role -| Field | maintainer | staff | +| Field | project-admin | staff | | --- | :---: | :---: | | title, summary, overview, usersUrl, developersUrl, chatChannel | ✓ | ✓ | | stage | ✓ | ✓ | | tags.{topic,tech,event} | ✓ | ✓ | | slug | – | ✓ | | featured, featuredImageKey | – | ✓ | -| maintainerId | – | – (use change-maintainer) | ### Response — 200 @@ -203,7 +214,7 @@ Update one or more fields. Field-level. Omitted fields are unchanged. Tags, if p ### Errors -- `403 forbidden` — caller is not maintainer or staff +- `403 forbidden` — caller is not a project admin or staff - `422 validation_failed` - `409 conflict` — slug change collides @@ -228,23 +239,9 @@ Unset `deletedAt`. { "success": true, "data": Project } ``` -## POST /api/projects/:slug/change-maintainer - -### Request - -```json -{ "personSlug": "another-member" } -``` - -The new maintainer must already be a member (a `project-memberships` record exists for them). If not, respond `409 conflict` with `error.code = "not_a_member"`. +## Admins -The previous maintainer remains a member with their old role (or `"Maintainer (former)"` if their role was previously `null`). - -### Response — 200 - -```json -{ "success": true, "data": Project } -``` +A project has no single maintainer. Its admins are its members with `isAdmin = true`, managed through [projects-members.md](projects-members.md) (`PATCH …/members/:personSlug` with `isAdmin`). The former `POST /api/projects/:slug/change-maintainer` is removed; it answers `410 gone` for one release, then `404`. ## Notes diff --git a/specs/data-model.md b/specs/data-model.md index d3d40a99..4ce5cf46 100644 --- a/specs/data-model.md +++ b/specs/data-model.md @@ -360,6 +360,7 @@ The `application` table: | offer | string nullable | plain text, 1–1,500 chars; required when `roleIds` is empty | | submittedAt | iso8601 | | | visibleAt | iso8601 | when admins may see it and are notified: `submittedAt`, or the applicant's `createdAt + 24h` if later ([new-account hold](behaviors/project-membership.md#new-account-hold)) | +| notifiedAt | iso8601 nullable | when admins were emailed about it (at most once) | | remindedAt | iso8601 nullable | when the 14-day reminder went to admins | | decidedById | uuid nullable | references people.id — the project admin or staff member who accepted or closed it; absent when the applicant or the site closed it | | decidedAt | iso8601 nullable | | From 056983559c56fb849417f45e59168c428107ed3f Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:54:38 +0000 Subject: [PATCH 04/78] docs(specs): make help-wanted roles the needs applications select Retire express-interest (and its two defects: no recipient address, private list in the public repo). Fill names members, several per need, and never adds anyone; accepting an application can mark needs filled. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- specs/behaviors/help-wanted-roles.md | 36 +++++++++++++--------------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/specs/behaviors/help-wanted-roles.md b/specs/behaviors/help-wanted-roles.md index 4403d963..12011642 100644 --- a/specs/behaviors/help-wanted-roles.md +++ b/specs/behaviors/help-wanted-roles.md @@ -2,7 +2,9 @@ ## Rule -A "help-wanted role" is a concrete, time-boxed volunteer ask attached to a project: "We need a React dev for ~4 hrs/wk to build the admin dashboard." Roles live on projects, have a status lifecycle, attract interest expressions from prospective volunteers, and roll up into a cross-project browse. +A "help-wanted role" is a concrete, time-boxed volunteer ask attached to a project: "We need a React dev for ~4 hrs/wk to build the admin dashboard." Roles live on projects, have a status lifecycle, are what people select when they [apply to join](project-membership.md#applying), and roll up into a cross-project browse. On screen they are called **needs** where the project's own admins manage them, and "Help Wanted" on the public board. + +**Zoom level: roles, not tasks.** A need is a standing ask that lasts weeks ("Frontend dev, React, ~4 hrs/wk, to build the admin dashboard"), not a ticket ("fix issue #212"). Tasks churn daily and already live where the work happens; `detailsUrl` points there. A role maps onto joining: someone accepted for it becomes a member with that label. This is the headline new feature in v1. It exists because the laddr project directory left "how to actually contribute" up to each project's overview/README and Slack channel — high friction for newcomers. @@ -28,23 +30,21 @@ This is the headline new feature in v1. It exists because the laddr project dire | Status | Set by | Set when | | ------ | ------ | -------- | | `open` | system | On creation. On `reopen`. | -| `filled` | maintainer/staff | A volunteer is committed; `filledAt = now`, optional `filledById`. | -| `closed` | maintainer/staff | Cancelled, expired, no-longer-needed. `closedAt = now`. | +| `filled` | project-admin/staff | Volunteers are committed; `filledAt = now`; `filledByIds` names zero or more members. Also set by accepting an application with "mark filled". | +| `closed` | project-admin/staff | Cancelled, expired, no-longer-needed. `closedAt = now`. | Transitions are explicit endpoints, not a generic PATCH on `status`. This makes the audit trail clean and the UI obvious. See [api/projects-help-wanted.md](../api/projects-help-wanted.md) for endpoint details. ## Side effects -- **Fill with attribution** — if `filledBySlug` is passed and that person isn't already a member of the project, add them as a member with role `"Help-wanted: <role.title>"`. The maintainer can edit that role string later. -- **Express interest** notifies the project's maintainer: - - Email — required (we always have the maintainer's email) - - Slack DM — optional, fires only if the maintainer has linked Slack (deferred field) or if there's a project Slack channel; falls back to email only -- **Express-interest rate cap** — a single person can only express interest in the *same* role once per 30 days. Different roles on the same project are fine. +- **Fill names members only.** Filling adds people to `filledByIds`; it never adds anyone to the project. The ways in are an accepted application (whose "mark filled" fills the selected needs in the same commit) or an admin's add ([project-membership.md](project-membership.md)). +- **Several people per need.** A fill with `keepOpen` records who filled it and leaves it open, for a need more than one person can fill. +- **Posting an open need emails followers** — the project's followers, applicants and members, subject to the follower-email cap ([project-membership.md → Notifications](project-membership.md#notifications)). ## Auto-aging -- Roles with `status = 'open'` and no activity (no interest expressions, no edits) for 90 days send an email reminder to the maintainer: "Is this still open?". Two clickable actions: "Still open" (extends 90 days), "Close it" (sets status closed). -- After 180 days of no activity, status auto-flips to `closed` with `closedBy` recorded as the system. Maintainer is notified. +- Roles with `status = 'open'` and no activity (no applications selecting them, no edits) for 90 days send an email reminder to the project's active admins: "Is this still open?". Two clickable actions: "Still open" (extends 90 days), "Close it" (sets status closed). +- After 180 days of no activity, status auto-flips to `closed` recorded as closed by the site. The admins are notified. Deferred to a follow-up release; v1 ships without this and we measure how stale the help-wanted board gets organically before tuning. @@ -53,7 +53,8 @@ Deferred to a follow-up release; v1 ships without this and we measure how stale - The **Project Detail** page renders the project's open roles inline (between Overview and Activity). Closed/filled roles are accessible via a "View all roles" link. - The **Help-Wanted Index** shows roles where `status = open` across all (non-deleted) projects. - The **Home Page** rail shows the 4 most recently created open roles. -- Cards always show: title, project (where shown out-of-context), description excerpt, commitment chip, tag chips, and one of: "Express Interest" / "Interest Sent ✓" / "Sign in to express interest". +- Cards always show: title, project (where shown out-of-context), description excerpt, commitment chip, tag chips, a "Details" link when `detailsUrl` is set, and one of: "Apply" (opens the apply form with this need selected) / "Application sent ✓" (the caller has an open application selecting it) / "Member" (the caller is on the project) / "Sign in to apply". When the project has no active admin, the button is replaced by "Not taking applications". +- No card shows how many people applied for a need. ## Tags @@ -66,21 +67,18 @@ Browse defaults sort by `-createdAt`. Tag facets surface in `metadata.facets`. - An integer estimate per week. - `0` means "flexible / unspecified" — show as "Flexible commitment" in the chip. - `null` means "not set" — equivalent to `0` for display. We always render *something* so the chip layout doesn't shift. -- The field is non-binding — it's a hint to volunteers, not a contract. Maintainers can edit it any time. +- The field is non-binding — it's a hint to volunteers, not a contract. Project admins can edit it any time. -## Interest expressions +## Interest expressions (retired) -- Store a record in the `help-wanted-interest` sheet (see [data-model.md](../data-model.md#helpwantedinterestexpression)): - - `id`, `roleId`, `personId`, `message`, `createdAt` -- The list of interest expressions is **not** publicly visible. The role's `interestCount` is, so callers can see "this role has 3 interested people." -- The maintainer of the project can see the full list (people + messages) via a deferred endpoint `GET /api/projects/:slug/help-wanted/:roleId/interest`. Not in v1's API spec yet; promote when needed. +The earlier "express interest" feature, its `help-wanted-interest` sheet and its public `interestCount` are retired in favour of [applications](project-membership.md#applying), which select needs. Two defects went with it: interest notifications never reached anyone (the route passed no recipient address to the notifier), and interest messages were written to the public data repo while this spec called the list private. Applications are public in the data repo by decision, shown on the site only to admins and staff, and notify every active admin by reading their addresses from the private store at send time. ## Why a separate concept from project memberships -Memberships answer "who's on this project." Help-wanted answers "who do we need." A project can have any number of help-wanted roles open while also having stable membership; the two are independent. A filled role becomes a membership but the role record stays around for accountability and reopenability. +Memberships answer "who's on this project." Help-wanted answers "who do we need." A project can have any number of help-wanted roles open while also having stable membership; the two are independent. An application links them — it selects needs — and a filled role keeps its record for accountability and reopenability. ## Open questions - Should a role specify *required* tags vs *helpful* tags? Probably not in v1 — extra knobs without proof we need them. -- Should we allow non-maintainers to "endorse" a help-wanted role? Probably not — endorsement makes sense for projects, not for tasks. +- Should we allow non-admins to "endorse" a help-wanted role? Probably not — endorsement makes sense for projects, not for tasks. - Should we cross-reference Slack `#projectname` channel join links? Worth doing once Slack integration exists. From f1cd93abf5547dc5dc4d49c9246e44664876ef7f Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:55:48 +0000 Subject: [PATCH 05/78] docs(specs): add follow/apply to screens and an Applications screen Project page gets a Join block (follow, apply, application state, the no-active-admin message) and lists members only. New admin-only Applications screen with Accept and Close application. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- specs/api/people.md | 11 ++-- specs/screens/admin-members.md | 7 ++- specs/screens/help-wanted-index.md | 11 ++-- specs/screens/home.md | 2 +- specs/screens/people-index.md | 2 +- specs/screens/person-detail.md | 4 +- specs/screens/project-applications.md | 67 +++++++++++++++++++++ specs/screens/project-detail.md | 84 +++++++++++++++++---------- specs/screens/project-edit.md | 4 +- specs/screens/project-table-card.md | 2 +- specs/screens/projects-index.md | 2 +- 11 files changed, 146 insertions(+), 50 deletions(-) create mode 100644 specs/screens/project-applications.md diff --git a/specs/api/people.md b/specs/api/people.md index c92e2464..a7139b83 100644 --- a/specs/api/people.md +++ b/specs/api/people.md @@ -55,7 +55,8 @@ See [data-model.md](../data-model.md#person). "fullName": "Chris Alfano", "avatarUrl": "https://...", "bioExcerpt": "First ~200 chars of bio, markdown stripped.", - "memberOfCount": 7, // active project memberships + "memberOfCount": 7, // projects where state = member + "adminOfCount": 2, // of those, isAdmin "tags": [{ "namespace": "tech", "slug": "typescript", "title": "TypeScript" }, ...], "createdAt": "..." } @@ -85,11 +86,11 @@ See [data-model.md](../data-model.md#person). "accountLevel": "staff", // visible to self and staff only; "user" otherwise "deletedAt": null, // ISO timestamp if deactivated; null otherwise. Visible to self + staff only (always null to others) "tags": { "topic": [Tag, ...], "tech": [Tag, ...] }, - "memberships": [ + "memberships": [ // state = member only; follows and applications are never listed { "project": { "slug": "squadquest", "title": "SquadQuest", "stage": "testing" }, "role": "Founder", - "isMaintainer": true, + "isAdmin": true, "joinedAt": "..." }, ... ], @@ -205,7 +206,7 @@ Self or staff. Clears `deletedAt`. Person becomes visible again. ## POST /api/people/:slug/purge -Administrator-only. Atomically hard-deletes the person record and cascades: project-memberships, help-wanted-interest, event-rsvps, person tag-assignments, project-updates (authored), project-buzz (posted), and blog-posts (authored). It also hard-deletes every project the person created that nobody else touched, with all of that project's records — the rule is in [person-lifecycle.md](../behaviors/person-lifecycle.md#purge-cascading-hard-delete-admin-only). All in one gitsheets commit. Git-revertable. +Administrator-only. Atomically hard-deletes the person record and cascades: project-memberships (every state), event-rsvps, person tag-assignments, project-updates (authored), project-buzz (posted), and blog-posts (authored). It also hard-deletes every project the person created that nobody else touched, with all of that project's records — the rule is in [person-lifecycle.md](../behaviors/person-lifecycle.md#purge-cascading-hard-delete-admin-only). All in one gitsheets commit. Git-revertable. Unlike the offline spam-prune (which nulls `authorId` on updates), purge DELETES the authored content — it is the on-demand garbage-collection path for spam accounts. @@ -261,7 +262,7 @@ When a deactivated person is referenced in a serialized response (e.g. project m { "slug": null, "fullName": "Deactivated user", "avatarUrl": null, "deactivated": true } ``` -This placeholder shape applies to the `PersonAvatar` reference type used in: project memberships, project-update `author`, project-buzz `postedBy`, help-wanted `postedBy`/`filledBy`, blog-post `author`, and event-rsvp `person`. +This placeholder shape applies to the `PersonAvatar` reference type used in: project memberships, project-update `author`, project-buzz `postedBy`, help-wanted `postedBy`/`filledBy`, application `decidedBy`, blog-post `author`, and event-rsvp `person`. ## POST /api/people/:slug/account-level diff --git a/specs/screens/admin-members.md b/specs/screens/admin-members.md index 3c848910..a11375af 100644 --- a/specs/screens/admin-members.md +++ b/specs/screens/admin-members.md @@ -62,7 +62,7 @@ See [api/moderation.md](../api/moderation.md). the domain is a button that searches `@domain` across the whole roster, so one throwaway address leads to every account from that domain), bio excerpt, compact footprint counts (`2 projects · 1 update · 1 RSVP · 3 tags`; - updates, buzz, posts, help-wanted interest and RSVPs only when non-zero), and + updates, buzz, posts, applications and RSVPs only when non-zero), and the vote state: - no vote → two buttons **Spam** / **Not spam** - voted → a badge `Spam · by {voter} · {when}` or `Not spam · …` with a @@ -103,8 +103,9 @@ See [api/moderation.md](../api/moderation.md). ### Expanded row / detail Full bio (rendered markdown, server-side), then the footprint as lists with -links: project memberships (role, joined), authored updates, buzz, blog posts, -help-wanted interest, event RSVPs (the event linked, its date, and when they +links: project memberships (members: role, joined, admin; follows and +applications: the project and state), authored updates, buzz, blog posts, +event RSVPs (the event linked, its date, and when they RSVP'd; past events included), tags. Then the vote history, newest first, each with voter, verdict, reasoning, and time; an agent's vote is marked "AI agent" and shows its flags, and once a human has voted the agent's votes read "overruled" diff --git a/specs/screens/help-wanted-index.md b/specs/screens/help-wanted-index.md index a85c0a8e..9195cf3d 100644 --- a/specs/screens/help-wanted-index.md +++ b/specs/screens/help-wanted-index.md @@ -27,7 +27,7 @@ - H1 "Help Wanted" with badge showing `metadata.totalItems` - Intro paragraph: "Concrete, time-boxed ways to contribute to Code for Philly projects." -- Right side: "Post a role" button → opens a project picker (only projects the user can post help-wanted on are listed); clicking a project navigates to `/projects/:slug` with the post-role modal open. Visible to any user who maintains at least one project. +- Right side: "Post a role" button → opens a project picker (only projects the user can post help-wanted on are listed); clicking a project navigates to `/projects/:slug` with the post-role modal open. Visible to any user who is an admin of at least one project. ### Sidebar @@ -49,7 +49,8 @@ For each role: - Commitment chip ("~4 hrs/week" or "Flexible commitment") - Tag chips - Footer: poster avatar + name, "posted {relativeTime}" -- Right edge: "Express Interest" button (signed-in users only; replaced with "Sign in to express interest" link for anonymous) +- Right edge: the need's action per [help-wanted-roles.md](../behaviors/help-wanted-roles.md#display-rules-across-screens) — "Apply", "Application sent ✓", "Member", "Sign in to apply", or "Not taking applications" when the project has no active admin +- "Details" link if `detailsUrl` Empty state: "No open roles match your filters." with a "Clear filters" button if any are active. @@ -62,7 +63,7 @@ Same conventions as other index screens. | Action | API call | On success | | ------ | -------- | ---------- | | Filter | URL state | Re-fetch | -| Express interest | `POST /api/projects/:slug/help-wanted/:roleId/express-interest` (inline modal asks for optional message) | Button becomes "Interest Sent ✓"; refresh card state | +| Apply | Opens the project's apply form with this need ticked (other open needs of the project are listed too); submits `POST /api/projects/:slug/applications` | Button becomes "Application sent ✓" | | Navigate to project | Navigation | – | | Post a role | Picker → navigation to `/projects/:slug?openModal=help-wanted` | – | @@ -74,9 +75,9 @@ Same conventions as other index screens. ## Authorization -| Caller | Express interest | Post a role | Manage role status | +| Caller | Apply | Post a role | Manage role status | | ------ | :--------------: | :---------: | :----------------: | | Anonymous | – | – | – | -| User | ✓ | only for projects they maintain | only for projects they maintain | +| User | ✓ (not on projects they're a member of) | only for projects they're an admin of | only for projects they're an admin of | | Staff | ✓ | any project | any project | | Administrator | ✓ | any project | any project | diff --git a/specs/screens/home.md b/specs/screens/home.md index 2dee8657..1a98a138 100644 --- a/specs/screens/home.md +++ b/specs/screens/home.md @@ -119,7 +119,7 @@ Three side-by-side cards. Slack comes first: it's where a newcomer actually meet | Featured projects | visible | visible | | Get involved | visible — "Start a Project" routes through `/login?return=/projects/create` | visible — "Start a Project" links to the in-app `/projects/create` form | | Activity stream | visible | visible | -| Help-wanted rail | visible | visible — "Express interest" CTA on each card (deferred polish; v1 just links to project page) | +| Help-wanted rail | visible | visible — cards link to the project page, where "Apply" lives | There are no staff- or admin-only home sections. diff --git a/specs/screens/people-index.md b/specs/screens/people-index.md index bf74326e..39f5cf28 100644 --- a/specs/screens/people-index.md +++ b/specs/screens/people-index.md @@ -41,7 +41,7 @@ Each card: - Avatar (large, square with rounded corners) - Full name (linked to `/members/<slug>`) -- "Maintainer of N project(s)" if `memberOfCount > 0` (with maintainer count specifically; computed on the API as part of `PersonListItem`) +- "Member of N project(s)" if `memberOfCount > 0` (members only, not follows; computed on the API as part of `PersonListItem`), with "admin of M" when `adminOfCount > 0` - Up to 3 top tags as chips - Hover state lifts the card; whole card is clickable diff --git a/specs/screens/person-detail.md b/specs/screens/person-detail.md index 96050800..d0ec18d8 100644 --- a/specs/screens/person-detail.md +++ b/specs/screens/person-detail.md @@ -32,10 +32,10 @@ For each membership: - Project title + slug (linked) - Stage badge - Role chip (e.g., "Designer") if present -- "Maintainer" chip if `isMaintainer` +- "Admin" chip if `isAdmin` - Joined date -Ordered by `isMaintainer DESC, joinedAt DESC`. If empty: "Not a member of any projects yet." With a "Browse projects" link. +Lists only memberships with `state = member` — never what a person follows or applied to, on anyone's profile including their own. Ordered by `isAdmin DESC, joinedAt DESC`. If empty: "Not a member of any projects yet." With a "Browse projects" link. ### Recent activity diff --git a/specs/screens/project-applications.md b/specs/screens/project-applications.md new file mode 100644 index 00000000..c3bf4ddc --- /dev/null +++ b/specs/screens/project-applications.md @@ -0,0 +1,67 @@ +# Screen: Project Applications + +## Route + +`/projects/:slug/applications` — requires `project-admin | staff` for the project (anyone else gets 403; anonymous redirected to `/login?return=…`). Linked from the project page's "Applications (N)" action and from every application email. + +## Data Requirements + +- `GET /api/projects/:slug` — title, open needs, `permissions.canReviewApplications` +- `GET /api/projects/:slug/applications?status=<tab>` — the list ([api/projects-applications.md](../api/projects-applications.md)) + +## Display Rules + +### Header + +- H1 "Applications" with the project title linked back to `/projects/:slug` +- Tabs: **Open** (default, with count), **Accepted**, **Closed** +- A line under the tabs: "Applicants can't see each other, and only this project's admins and site staff can see this page." + +### Application cards + +One per application, newest first: + +- Applicant avatar, full name (linked to `/members/<slug>`) +- Facts row: "Joined {relative accountCreatedAt}", "GitHub linked" or "No GitHub linked", "Member of: {project links}" or "Not on any other project" +- **Needs picked** — each as a chip with its title; a need no longer open shows its status ("filled", "closed") beside it +- **Offer** — plain text, line breaks kept, never linked or rendered as markdown +- "Applied {relative submittedAt}" +- On the Accepted and Closed tabs: who decided and when ("Accepted by {name}, 3 days ago"; "Closed by {name}" / "Closed by the applicant" / "Closed — no one got to it in 30 days"), and "via the ops bot" when `decidedVia = agent` + +Open cards carry two buttons: + +- **Accept** → dialog: role label (pre-filled with the first picked need's title, editable), a "Mark filled" checkbox per picked need that is still open, and "Make admin" (unchecked). Submit calls accept. +- **Close application** → dialog: optional note (1,000 chars) with the hint "Sent to them by email; not saved anywhere." The dialog shows what they'll receive: that the project isn't taking this on right now, the note, and that they're still following. Submit calls close. + +Empty states: Open — "No open applications." Accepted / Closed — "None yet." + +## Actions + +| Action | API call | On success | +| ------ | -------- | ---------- | +| Accept | `POST /api/projects/:slug/applications/:personSlug/accept` | Card leaves Open; toast "{name} is now a member" | +| Close application | `POST /api/projects/:slug/applications/:personSlug/close` | Card leaves Open; toast "Application closed" | +| Switch tab | URL `?status=` | Re-fetch | + +## Navigation + +**To here:** project page "Applications (N)"; links in the new-application and reminder emails; the ops bot's Slack message. + +**From here:** `/projects/:slug`, `/members/<slug>`. + +## Authorization + +| Caller | Sees | Decides | +| ------ | ---- | ------- | +| Project admin | ✓ | ✓ | +| Staff / administrator | ✓ (every project) | ✓ | +| Anyone else | 403 | – | + +Applications from deactivated applicants, and those still in the [new-account hold](../behaviors/project-membership.md#new-account-hold), are not listed. + +## Principles + +**Local:** + +- **Facts, not verdicts.** The screen states what the site knows about an applicant and never scores or labels them. Judging is the admin's job; spam handling stays with staff. +- **A close is not a rejection.** Copy on this screen and in what the applicant receives never says "declined" or "rejected"; the project isn't taking it on right now, and the person stays a follower. diff --git a/specs/screens/project-detail.md b/specs/screens/project-detail.md index 7d4a3b4f..3363c6fc 100644 --- a/specs/screens/project-detail.md +++ b/specs/screens/project-detail.md @@ -28,6 +28,7 @@ If slug is unknown or soft-deleted (and caller isn't staff): 404 page. - "Post Update" → opens modal (`permissions.canPostUpdate`) - "Post Help-Wanted Role" → opens modal (`permissions.canPostHelpWanted`) - "Manage Members" → opens modal (`permissions.canManageMembers`) + - "Applications (N)" → `/projects/:slug/applications` (`permissions.canReviewApplications`; N is `counts.openApplications`, hidden when 0) - "Delete Project" — `permissions.canDelete` (administrator) ### Main column (two-thirds width at lg, full at sm) @@ -44,7 +45,9 @@ If slug is unknown or soft-deleted (and caller isn't staff): 404 page. - Description (rendered markdown, truncated to 4 lines with "Read more") - Commitment chip if set ("~4 hrs/week" or "Flexible commitment") - Tag chips - - Action button — "Express Interest" if `permissions.canExpressInterest && !alreadyExpressedInterest`; "Interest Sent ✓" if already; hidden if not signed in (replaced by "Sign in to express interest" link) + - "Details" link if `detailsUrl` + - Action button per [help-wanted-roles.md → Display rules](../behaviors/help-wanted-roles.md#display-rules-across-screens): "Apply" (opens the apply form with this need selected), "Application sent ✓", or "Sign in to apply"; nothing for members + - For project admins: a role menu with Fill / Close / Reopen - If `permissions.canPostHelpWanted`: "Post new role" button at top of section - If there are no open roles AND the caller can't post: hide the whole section @@ -57,31 +60,47 @@ If slug is unknown or soft-deleted (and caller isn't staff): 404 page. ### Sidebar (one-third width at lg, full below) -1. **Project Info** +1. **Join** _(top of the sidebar)_ + + The caller's relationship to the project, from `viewer`, `permissions` and `hasActiveAdmin`: + + | Caller | Shows | + | ------ | ----- | + | Anonymous | "Sign in to follow or apply" → `/login?return=/projects/<slug>` | + | Signed in, no record | **Follow** button; **Apply to join** button (if `permissions.canApply`) | + | Follower | "Following ✓" (menu: Mute emails / Unfollow); **Apply to join** (if `permissions.canApply`) | + | Follower in the re-apply wait | "Following ✓"; "You can apply again on {reapplyAfter}" | + | Applicant | "Application sent ✓ {relative submittedAt}" with "View" (shows the needs and offer they sent) and "Close my application" | + | Member | "You're a member" (and "Admin" if `isAdmin`); menu: Mute emails / Leave project | + | Project has no active admin (anyone not a member) | In place of Apply: "This project doesn't have an active admin right now. If you're interested in picking up the torch, talk to the organizers." linking to `/chat`. Follow stays. | + + Below, muted: "{followerCount} following" when `followerCount > 0`. No names. + +2. **Project Info** Block of stacked CTAs: - "Users' Site" → `usersUrl` (primary button) - "Developers' Site" → `developersUrl` (success button) - "Chat Channel" → `/chat?channel=<chatChannel>` (success button) — falls back to plain text `#channel-name` if no chat linker configured -2. **Members** +3. **Members** - Heading "Members" - - Avatar grid: each member, maintainer largest (64px) and outlined, others 48px - - Hover tooltip shows full name + role + - Avatar grid of `memberships` (members only — never followers or applicants): admins first, 64px and marked "Admin"; others 48px + - Hover tooltip shows full name + role (+ "Admin") - "+ Add" button (if `permissions.canManageMembers`) opens add-member modal -3. **Tags** +4. **Tags** - "Tech:" then a list of tag chips (linked to tag pages) — if `tags.tech.length` - "Topics:" then chips — if `tags.topic.length` - "Events:" then chips — if `tags.event.length` -4. **Share** +5. **Share** - "Copy link" button (copies `https://codeforphilly.org/projects/<slug>`) - "Share to Slack" button — opens a system share or copies a pre-formatted Slack message - "Table card" button → `/projects/<slug>/table-card`, a printable sign with a QR code for the project's table at a hack night ([project-table-card.md](project-table-card.md)) - _Twitter/X share removed_, see [deferred.md](../deferred.md) -5. **Info** +6. **Info** - "Created" relative time + tooltip with absolute - "Last updated" relative time + tooltip with absolute - "Stage: <name>" with link "What does this stage mean?" → opens a modal with the full description from [behaviors/project-stages.md](../behaviors/project-stages.md) @@ -99,12 +118,13 @@ If slug is unknown or soft-deleted (and caller isn't staff): 404 page. | Post update | `POST /api/projects/:slug/updates`; modal then refetch activity | Modal submit | | Log buzz | Navigation to `/projects/:slug/buzz/new` | "Log Buzz" button | | Post help-wanted | `POST /api/projects/:slug/help-wanted`; modal then refetch help-wanted | Modal submit | -| Add member | `POST /api/projects/:slug/members` | Modal submit | -| Manage members | Modal listing memberships with role + remove + change-maintainer buttons | "Manage Members" | -| Join project | `POST /api/projects/:slug/members/join` | Sidebar "Join Project" button (visible to user who isn't a member yet) | -| Express interest in role | `POST /api/projects/:slug/help-wanted/:roleId/express-interest` | Card button | -| Mark role filled / close / reopen | Respective endpoints; modal with optional `filledBySlug` | Role card menu | -| Change maintainer | `POST /api/projects/:slug/change-maintainer` with `personSlug` | Manage members modal | +| Add member | `POST /api/projects/:slug/members` (person picker, role, "Make admin" checkbox) | Modal submit | +| Manage members | Modal listing members with role edit, "Make admin" / "Remove admin", and Remove; a change that leaves no active admin asks to confirm | "Manage Members" | +| Follow / unfollow / mute | `POST` / `DELETE` / `PATCH /api/projects/:slug/follow` | Join block | +| Apply to join | Opens the apply form: the project's open needs as checkboxes (one pre-ticked when opened from a need card), and "Tell the admins what you'd like to help with" (required if no need is ticked, 1,500 chars). Note under it: "This project's admins and site staff see your application." Submits `POST /api/projects/:slug/applications` | "Apply to join" / need card "Apply" | +| Close my application | `POST /api/projects/:slug/applications/mine/close` after a confirm | Join block | +| Leave project | `POST /api/projects/:slug/members/leave`; the dialog offers "Also stop following" and, for the last active admin, explains the project will have no admin | Join block menu | +| Mark role filled / close / reopen | Respective endpoints; the fill dialog picks members (several allowed) and "keep open" | Role card menu | | Delete project | `DELETE /api/projects/:slug` then redirect to `/projects` | "Delete Project" button → confirm modal | All modals are shadcn `Dialog` components. Forms post via fetch, show server validation errors inline (matching `error.fields`), and close on success. @@ -116,6 +136,8 @@ All modals are shadcn `Dialog` components. Forms post via fetch, show server val **From here:** - `/projects` (back) +- `/projects/<slug>/applications` (project admins and staff) +- `/chat` (no-active-admin message) - `/members/<slug>` (member avatars, author links) - `/projects/<slug>/edit` - `/projects/<slug>/updates/<number>` (permalink on individual updates) @@ -129,19 +151,21 @@ All modals are shadcn `Dialog` components. Forms post via fetch, show server val `permissions` on the response is authoritative for UI gating. Server enforces the same rules on every mutation; the response is just a hint to suppress disabled buttons. -| Action | Anonymous | User (non-member) | Member | Maintainer | Staff | Admin | -| ------ | :-------: | :---------------: | :----: | :--------: | :---: | :---: | -| View project | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | -| Join project | – | ✓ | – | – | – | – | -| Leave project | – | – | ✓ | – (must transfer first) | – | – | -| Post update | – | – | ✓ | ✓ | ✓ | ✓ | -| Log buzz | – | ✓ | ✓ | ✓ | ✓ | ✓ | -| Add member | – | – | – | ✓ | ✓ | ✓ | -| Remove member | – | – | – | ✓ (not self if maintainer) | ✓ | ✓ | -| Change maintainer | – | – | – | ✓ | ✓ | ✓ | -| Post help-wanted role | – | – | – | ✓ | ✓ | ✓ | -| Express interest | – | ✓ | ✓ | ✓ | ✓ | ✓ | -| Edit project | – | – | – | ✓ | ✓ | ✓ | -| Edit slug | – | – | – | – | ✓ | ✓ | -| Delete project | – | – | – | – | – | ✓ | -| Restore project | – | – | – | – | ✓ | ✓ | +Columns: a **user** has no record or is a follower; an **applicant** has an open application; **project admin** is a member with `isAdmin`. + +| Action | Anonymous | User / follower | Applicant | Member | Project admin | Staff | Administrator | +| ------ | :-------: | :-------------: | :-------: | :----: | :-----------: | :---: | :-----------: | +| View project, members, open needs | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| Follow / unfollow | – | ✓ | – (inherent) | – (inherent) | – (inherent) | ✓ | ✓ | +| Apply to join | – | ✓ (active admin, no wait) | – | – | – | ✓ | ✓ | +| Close own application | – | – | ✓ | – | – | – | – | +| Leave project | – | – | – | ✓ | ✓ (confirm if last) | – | – | +| Post update | – | – | – | ✓ | ✓ | ✓ | ✓ | +| Log buzz | – | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| Add / remove members, make or remove admins | – | – | – | – | ✓ | ✓ | ✓ | +| See and decide applications | – | – | – | – | ✓ | ✓ | ✓ | +| Post / edit / fill / close / reopen needs | – | – | – | – | ✓ | ✓ | ✓ | +| Edit project | – | – | – | – | ✓ | ✓ | ✓ | +| Edit slug | – | – | – | – | – | ✓ | ✓ | +| Delete project | – | – | – | – | – | – | ✓ | +| Restore project | – | – | – | – | – | ✓ | ✓ | diff --git a/specs/screens/project-edit.md b/specs/screens/project-edit.md index dad8c174..02e69ccc 100644 --- a/specs/screens/project-edit.md +++ b/specs/screens/project-edit.md @@ -41,6 +41,8 @@ In order: | Events | Multi-select with chips | – | Same | | Featured | Checkbox | – | Staff-only, hidden for non-staff. Adds to home page rotation. | +Admins and members are managed on the project page (Manage Members), not on this form. + When `permissions.canChangeStage === false` on edit, the Stage select is disabled with a tooltip. v1: this is always true if `permissions.canEdit` is true. ### Validation @@ -86,7 +88,7 @@ Bottom of the form, in a "Danger zone" section with red outline: Same matrix as [project-detail.md](project-detail.md): - `/projects/create` — any `user` or above -- `/projects/:slug/edit` — `maintainer` or `staff` +- `/projects/:slug/edit` — `project-admin` or `staff` - Slug field visibility — `staff` only on edit - Featured toggle — `staff` only - Delete — `administrator` only diff --git a/specs/screens/project-table-card.md b/specs/screens/project-table-card.md index a8384a5f..292ad214 100644 --- a/specs/screens/project-table-card.md +++ b/specs/screens/project-table-card.md @@ -58,4 +58,4 @@ fits one US Letter or A4 page in portrait, black on white. Project", and it is also what a curious passer-by should see. A link that joins on arrival would make scanning a commitment. - **Anyone can print one.** The project page is public, so its card is - too; whoever is staffing the table doesn't have to be the maintainer. + too; whoever is staffing the table doesn't have to be an admin. diff --git a/specs/screens/projects-index.md b/specs/screens/projects-index.md index 42208574..e8733754 100644 --- a/specs/screens/projects-index.md +++ b/specs/screens/projects-index.md @@ -65,7 +65,7 @@ For each project (ProjectListItem): - **Title** — linked to `/projects/<slug>` - **Stage badge** — color per [behaviors/project-stages.md](../behaviors/project-stages.md) - **Summary or overviewExcerpt** — `summary` if set, otherwise `overviewExcerpt` (truncated to 600 chars, server-rendered markdown stripped to plain text) -- **Member avatars** — `members` (max 10, maintainer largest at 64px, others 48px), ordered by `isMaintainer DESC, role asc, fullName asc`. Hover/tooltip shows name + role. +- **Member avatars** — `members` (members only, max 10, admins largest at 64px, others 48px), ordered by `isAdmin DESC, role asc, fullName asc`. Hover/tooltip shows name + role. - **Tag chips** — up to 5, mixed namespaces, color-coded by namespace. "+N more" for additional tags. - **Action buttons** — "Public Site" if `usersUrl`, "Developers" if `developersUrl`, "Chat" if `chatChannel` - **Help-wanted badge** — if `openHelpWantedCount > 0`, a yellow pill "Help wanted (3)" linking to the project page anchored at the help-wanted section From 80dee5aba9bd96fbb73da1548396e2a6ca9900db Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:56:37 +0000 Subject: [PATCH 06/78] docs(specs): add Slack account linking and the agent applications API A one-time code DMed to the ops bot links a site account to a Slack user. New agent scopes: slack:link, projects:applications:read (event feed) and projects:applications:decide (on a named admin's behalf). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- specs/api/agent-applications.md | 122 +++++++++++++++++++++++++++++ specs/api/agents.md | 20 ++++- specs/api/slack-link.md | 86 ++++++++++++++++++++ specs/behaviors/private-storage.md | 9 ++- specs/screens/account.md | 11 ++- 5 files changed, 239 insertions(+), 9 deletions(-) create mode 100644 specs/api/agent-applications.md create mode 100644 specs/api/slack-link.md diff --git a/specs/api/agent-applications.md b/specs/api/agent-applications.md new file mode 100644 index 00000000..ad9d0591 --- /dev/null +++ b/specs/api/agent-applications.md @@ -0,0 +1,122 @@ +# API: Agent applications feed and decisions + +What an [agent](agents.md) needs to coordinate project applications in Slack: +a feed of application events to read, and one endpoint to record a project +admin's accept or close on their behalf. Email from the site stays the first +channel; Slack is the second, and every decision still lands as a site write +naming a person. + +The site stays the record and the authority. The bot is a place for admins to +see an application and say yes or no; it never decides one itself. + +## Endpoints + +| Method | Path | Auth | Summary | +| ------ | ---- | ---- | ------- | +| `GET` | `/api/agent/events` | agent:projects:applications:read | Application events after a cursor. | +| `POST` | `/api/agent/applications/:projectSlug/:personSlug/decision` | agent:projects:applications:decide | Accept or close an open application for a named project admin. | + +## GET /api/agent/events + +### Query + +| Param | Type | Notes | +| ----- | ---- | ----- | +| `after` | string | Opaque cursor from a previous response. Omitted: events from the last 7 days. | +| `limit` | int | 1–200, default 100. | + +### Response — 200 + +```json +{ + "success": true, + "data": [ + { + "cursor": "…", + "type": "application.visible", + "at": "…", + "project": { "slug": "phlask", "title": "PHLASK", "chatChannel": "phlask" }, + "applicant": { "slug": "newperson", "fullName": "New Person", "accountCreatedAt": "…", "hasGitHubLink": true, "memberOf": [] }, + "application": { "status": "open", "roles": [{ "id": "…", "title": "Frontend dev" }], "offer": "…", "submittedAt": "…" }, + "admins": [{ "slug": "jane", "fullName": "Jane Doe", "slackUserId": "U…" }, { "slug": "sam", "fullName": "Sam Roe", "slackUserId": null }] + } + ], + "metadata": { "next": "…" } +} +``` + +Event types, each derived from the membership records (the feed is a view, +not a stored log): + +| Type | When (`at`) | +| ---- | ----------- | +| `application.visible` | the application's `visibleAt` arrived (admins were notified) | +| `application.reminder` | the 14-day reminder went out (`remindedAt`) | +| `application.accepted` | accepted (`decidedAt`), with `decidedBy` and `decidedVia` | +| `application.closed` | closed (`closedAt`), with `closedBy` and, for an admin close, `decidedBy` | + +- `admins` lists the project's active admins; `slackUserId` is set only for an + admin with a verified [Slack link](slack-link.md). No email address, ever. +- Applications from deactivated applicants produce no events, and their + earlier events drop out of the feed. +- Ordered by `at`, then record id. The cursor is stable across restarts + (it encodes the last `at` and id). + +## POST /api/agent/applications/:projectSlug/:personSlug/decision + +Records an accept or a close that a project admin made in Slack. + +### Request + +```json +{ + "decision": "accept", + "onBehalfOf": { "slackTeamId": "T…", "slackUserId": "U…" }, + "role": "Frontend dev", + "fillRoleIds": ["…"], + "note": null +} +``` + +| Field | Required | Notes | +| ----- | -------- | ----- | +| decision | yes | `accept` \| `close` | +| onBehalfOf | yes | The Slack user who decided. Must resolve through a verified link to a person who is, now, an active project admin of `:projectSlug` ([authorization.md → On behalf of a project admin](../behaviors/authorization.md#on-behalf-of-a-project-admin)). | +| role, fillRoleIds | no | As for the site's accept ([projects-applications.md](projects-applications.md)). | +| note | no | For `close`: emailed to the applicant, never stored. | + +Same effects as the site's accept and close, except: `decidedById` is the +named admin, `decidedVia = agent`, `agentGrantId` is the grant, and the commit +is authored by the agent with `Actor-Kind: agent`, `Grant-Id` and +`On-Behalf-Of: <admin slug>`. The site emails the named admin a confirmation +("The ops bot recorded that you accepted …"), with a link to the Applications +screen. + +### Response — 200 + +```json +{ "success": true, "data": { "state": "member", "decidedBy": { "slug": "jane" } } } +``` + +### Errors + +- `403 forbidden` (`error.code = "not_project_admin"`) — the Slack user is not + linked, or the linked person is not an active admin of this project +- `404 not_found` — no open, visible application from that person +- `429 rate_limited` — more than 30 decisions per agent in 24 hours + +## What the agent must never do + +These are duties of the agent's operators; the site enforces what it can +(the admin check, the scope, the limits) and the rest is policy: + +- Decide on its own, or on anyone's word but the named admin's own message. +- Add, remove or promote members, or touch needs or the project. No scope + allows it. +- Show an application's offer to anyone but that project's admins and staff. +- Judge applicants for admins. It may repeat the facts the feed gives (account + age, GitHub linked, other projects), never a verdict. + +What it may do alone: notify admins, remind them, and treat an obvious spam +account through its moderation scopes as it would any spam ([moderation.md](moderation.md)). +A spam vote deactivates the account, which hides its application everywhere. diff --git a/specs/api/agents.md b/specs/api/agents.md index b2fb211c..63dc5b15 100644 --- a/specs/api/agents.md +++ b/specs/api/agents.md @@ -3,8 +3,8 @@ An **agent** is an automated moderator: a program, not a person, that staff let act on the [admin members roster](../screens/admin-members.md). It has its own site account and reaches the API with a **grant**: a bearer token an -administrator mints for it, scoped to moderation and nothing else. It can do -two things, each under its own scope: +administrator mints for it, with a fixed list of narrow scopes. For +moderation it can do two things, each under its own scope: - **Vote** `spam` / `not spam` on a member who only *looks* like spam. Its votes are labeled as an agent's in the data and on the roster, they **stage** @@ -20,6 +20,12 @@ immediately. For signups that are obviously spam but haven't posted anything spammy, log a spam vote to put them in the 3-day purge queue pending doing anything that makes them not look like spam." +It can also help coordinate project applications in Slack: link members' Slack +accounts, read a feed of applications, and record a project admin's accept or +close on that admin's behalf ([agent-applications.md](agent-applications.md)). +That last is the only scope that acts for a person +([authorization.md → On behalf of a project admin](../behaviors/authorization.md#on-behalf-of-a-project-admin)). + The first agent is Code for Philly's ops bot. The site does not care what runs behind a grant; it cares that the grant is narrow, attributable and revocable. @@ -79,6 +85,9 @@ and a hard expiry. | `moderation:read` | `GET /api/admin/members` and `GET /api/admin/members/:slug`, with the redactions in [moderation.md → Agent callers](moderation.md#agent-callers). | | `moderation:vote` | `POST /api/admin/members/:slug/vote` and `DELETE /api/admin/members/:slug/vote`, within the [agent vote rules](moderation.md#agent-votes). | | `moderation:purge` | `POST /api/admin/members/:slug/purge`, within the [agent purge rules](moderation.md#agent-purges). | +| `slack:link` | `POST /api/agent/slack-links`: redeem a member's linking code ([slack-link.md](slack-link.md)). | +| `projects:applications:read` | `GET /api/agent/events`: application events with the offer text and the admins' linked Slack ids ([agent-applications.md](agent-applications.md)). | +| `projects:applications:decide` | `POST /api/agent/applications/:projectSlug/:personSlug/decision`: accept or close an open application on a named, verified project admin's behalf. Requires `projects:applications:read` and `slack:link`. | There are no other scopes. A grant does not make its holder `user`, `self` or `staff` anywhere else ([authorization.md → Agent grants](../behaviors/authorization.md#agent-grants)). @@ -87,7 +96,10 @@ There are no other scopes. A grant does not make its holder `user`, `self` or administrator can let an agent stage votes without letting it delete anything. A grant with `moderation:purge` must also carry `moderation:read` (`422` otherwise): an agent that cannot read the roster cannot check what it is about -to delete. Scopes are fixed for a grant's life; adding purge to an agent is a +to delete. Likewise `projects:applications:decide` requires +`projects:applications:read` and `slack:link` (`422` otherwise), and is never +implied by them: reading applications does not let an agent decide them. +Scopes are fixed for a grant's life; adding purge to an agent is a new grant and a revoke of the old one, so the change is its own public `agent.grant` commit. @@ -226,7 +238,7 @@ are committed as the agent: [moderation.md](moderation.md#agent-votes).) ## Errors - `422 validation_failed` — unknown scope, `moderation:purge` without - `moderation:read`, `expiresInDays` out of range, missing `bio` or `grant`, + `moderation:read`, `projects:applications:decide` without its two companions, `expiresInDays` out of range, missing `bio` or `grant`, bad or taken slug, or a slug with moderation history (`slug_retired`) - `404 not_found` — not an administrator (staff for `GET` and `withdraw-votes`), or no such agent or grant diff --git a/specs/api/slack-link.md b/specs/api/slack-link.md new file mode 100644 index 00000000..4b0c2449 --- /dev/null +++ b/specs/api/slack-link.md @@ -0,0 +1,86 @@ +# API: Slack account link + +A verified link between a site account and a Slack user, so the ops bot can +reach project admins in Slack and, when allowed, act on what they say there +([agent-applications.md](agent-applications.md)). Both sides are proven: the +site knows who is signed in when it issues a code, and Slack knows who sent +the code to the bot. + +The site is already the SAML sign-in for the Slack workspace +([saml.md](saml.md)), but it does not learn the Slack user id from that, and +the self-typed `Person.slackHandle` proves nothing. This link is the only +mapping anything routes on. + +## Endpoints + +| Method | Path | Auth | Summary | +| ------ | ---- | ---- | ------- | +| `POST` | `/api/account/slack-link/code` | user (self) | Issue a one-time linking code. | +| `DELETE` | `/api/account/slack-link` | user (self) | Remove the caller's link. | +| `POST` | `/api/agent/slack-links` | agent:slack:link | Redeem a code for the Slack user who sent it. | + +## POST /api/account/slack-link/code + +No body. Returns a fresh code and invalidates any earlier unredeemed code for +the caller. + +```json +{ "success": true, "data": { "code": "K7Q-4MZP", "expiresAt": "..." } } +``` + +- 8 characters from an unambiguous alphabet (no `0/O`, `1/I/L`), shown with a + hyphen; matched case-insensitively, hyphen optional. +- Lives **10 minutes**, redeemable once. +- Held **in memory only**, as a hash; a restart drops pending codes and the + member asks for a new one. Codes are never written to either store or a log. +- Counts as a credential endpoint for rate limiting + ([conventions.md](conventions.md#rate-limiting)); at most 5 codes per account + per hour. +- Refused for agent accounts (`422`). + +## POST /api/agent/slack-links + +The bot calls this when a member DMs it a code. + +```json +{ "code": "K7Q-4MZP", "slackTeamId": "T…", "slackUserId": "U…" } +``` + +On success, in the same request: sets `PrivateProfile.slack = { teamId, +userId, linkedAt }` for the person who issued the code and consumes the code. +`slackTeamId` must be the workspace the site serves (configured; mismatch +`422`). + +```json +{ "success": true, "data": { "personSlug": "jane", "linkedAt": "..." } } +``` + +The bot replies to the member in the DM; the site emails nothing. + +### Errors + +- `404 not_found` (`error.code = "code_invalid"`) — unknown, expired or used + code; one response for all three +- `409 conflict` (`error.code = "slack_user_linked"`) — that Slack user is + already linked to a different site account; the member disconnects the other + account first +- `429 rate_limited` — more than 10 failed redemptions per agent per hour + (guessing); further calls are refused for an hour + +## DELETE /api/account/slack-link + +Clears `PrivateProfile.slack`. `204`. No error if there was none. + +## Notes + +- **Private only.** The link lives on the private profile + ([private-storage.md](../behaviors/private-storage.md)), changes no public + record, and makes no public commit. The Slack user id is returned only to + agents holding `projects:applications:read`, for the admins of an + application they read ([agent-applications.md](agent-applications.md)). +- **One account per Slack user** (in-memory index `bySlackUserId`); one Slack + user per account (a new link replaces the old). +- **Purge** removes it with the private profile. **Deactivation** leaves it in + place but the deactivated person is never resolved as an admin. +- `GET /api/auth/me` reports `slack: { linked, linkedAt }` to the person + themselves. diff --git a/specs/behaviors/private-storage.md b/specs/behaviors/private-storage.md index 893f4a16..8287da4d 100644 --- a/specs/behaviors/private-storage.md +++ b/specs/behaviors/private-storage.md @@ -75,13 +75,16 @@ the agent account deletes its lines with the rest of its private data. "status": "ok", "checkedAt": "2026-09-18T20:00:00Z" }, "lastSlackSsoAt": "2026-09-18T01:12:00Z", + "slack": { "teamId": "T…", "userId": "U…", "linkedAt": "2026-11-20T…" }, "emailBounce": { "type": "HardBounce", "bouncedAt": "2026-09-10T...", "description": "…", "inactive": true }, "updatedAt": "2026-05-15T18:42:00Z" } ``` -The three trailing fields are optional and exist for staff moderation -([api/moderation.md](../api/moderation.md)): +`slack` is optional: the verified link to a Slack user, set and cleared only by +[api/slack-link.md](../api/slack-link.md); it is what an agent's Slack user id +resolves through. The other three trailing fields are optional and exist for +staff moderation ([api/moderation.md](../api/moderation.md)): - `github` — what GitHub said about the linked account, captured at every GitHub sign-in ([api/auth.md](../api/auth.md)) and refreshed by the roster's probe @@ -181,6 +184,8 @@ The filesystem backend doesn't replicate versioning. Dev mode is lossy by design - **Authentication credentials** (passwords, hashed or otherwise) for the *active* system. v1 has no password auth — only GitHub OAuth — so this is trivially true. The `legacy-passwords.jsonl` is the one exception, drains to zero, and is treated as one-shot migration data. - **Auth tokens.** JWT signing keys live in the deploy environment, not the bucket. Revocation state is in-memory only (see [behaviors/authorization.md](authorization.md)). Agent grant tokens are not stored either — only their hashes (above). - **Public records.** Anything that the public site displays — project READMEs, member profiles, tags, help-wanted listings — stays in the public gitsheets repo. +- **Project follows and applications.** They are `project-memberships` records in the public repo by decision ([project-membership.md](project-membership.md)); the site limits who sees them, but they hold nothing private. The one private piece of that flow is an admin's closing note, which is emailed and never stored at all. +- **Slack linking codes.** Held in memory only, hashed, for ten minutes. ## Audit diff --git a/specs/screens/account.md b/specs/screens/account.md index 69c10794..eb844e65 100644 --- a/specs/screens/account.md +++ b/specs/screens/account.md @@ -8,7 +8,7 @@ A self-service settings hub for the current user's identity, sessions, newslette ## Data Requirements -- `GET /api/auth/me` — current person + account level + `hasGitHubLink` + `lastLoginMethod` (returns the self-view including the private-store email + newsletter prefs) +- `GET /api/auth/me` — current person + account level + `hasGitHubLink` + `lastLoginMethod` + `slack` (`{ linked, linkedAt }`) (returns the self-view including the private-store email + newsletter prefs) - `GET /api/auth/sessions` — list of remembered sessions - `POST /api/auth/link-github` — invoked from the "Connect GitHub" banner when `hasGitHubLink === false` @@ -29,7 +29,10 @@ The card's contents depend on `me.hasGitHubLink`: - For GitHub-linked users: "Sourced from GitHub on every sign-in. To change, update your primary email on GitHub and sign back in here." - For password-only users (no GitHub link): "Imported from your Code for Philly account at cutover." - Refresh timestamp ("Last updated when you signed in on {date}") -- **Slack** — placeholder row with a greyed-out "Connect Slack" button (the linking flow isn't yet specified; the row signals direction) +- **Slack** — the verified link to a Slack user ([api/slack-link.md](../api/slack-link.md)), from `me.slack`: + - Not linked: "Connect Slack" button. It shows a one-time code and the instruction "Send this code in a direct message to the ops bot in the Code for Philly Slack within 10 minutes," with the bot's name linked to a DM with it. The row polls `GET /api/auth/me` while the code is live and turns linked when the bot confirms it. + - Linked: "Connected to Slack ✓ since {linkedAt}" with "Disconnect". Under it: "Lets the ops bot send you project notices in Slack and act on your replies, such as accepting an application you answer there." + - The row never shows the Slack user id. **State B — GitHub not yet linked** (`me.hasGitHubLink === false`) @@ -44,7 +47,7 @@ The "Connect GitHub" button posts to `POST /api/auth/link-github` (the SPA submi Below the banner, the rest of Card 1 still renders: - **Email** — same display as State A's password-only variant -- **Slack** — same placeholder +- **Slack** — same row as State A The banner is the **only** nag mechanism in v1. No modal interrupts, no toast on every sign-in, no email reminders. Per [behaviors/account-migration.md](../behaviors/account-migration.md#the-nag-banner-on-account). @@ -97,6 +100,8 @@ That post-onboarding claim flow follows the same shape as the OAuth-callback cla | ------ | -------- | ---------- | | Connect GitHub (when unlinked) | `POST /api/auth/link-github` (redirects to GitHub OAuth) | Callback returns to `/account`; banner disappears | | Toggle newsletter | `PATCH /api/people/<slug>/newsletter` | Re-fetch me, success toast | +| Connect Slack | `POST /api/account/slack-link/code` | Show the code and its expiry | +| Disconnect Slack | `DELETE /api/account/slack-link` after a confirm | Row returns to "Connect Slack" | | Revoke session | `POST /api/auth/sessions/:jti/revoke` | Remove row from list | | Sign out | `POST /api/auth/logout` | Redirect to `/` | | Claim another legacy account | Navigate to `/account/claim-legacy` | – | From eaccb1d7120ae4b3e6ef3d8dc46c0019df26d15a Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:57:19 +0000 Subject: [PATCH 07/78] docs(specs): carry membership states through purge, moderation and storage Purge and prune take follows and applications; deactivation hides them. Agent purge treats an admin-chosen membership as shared. Footprints count applications and follows; storage drops the interest sheet and gains the On-Behalf-Of trailer. Remaining maintainer wording goes. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- specs/README.md | 4 ++-- specs/api/agents.md | 3 +++ specs/api/moderation.md | 34 +++++++++++++--------------- specs/architecture.md | 6 ++--- specs/behaviors/account-migration.md | 2 +- specs/behaviors/person-lifecycle.md | 21 +++++++++-------- specs/behaviors/project-stages.md | 2 +- specs/behaviors/slug-handles.md | 2 +- specs/behaviors/spam-exclusion.md | 5 ++-- specs/behaviors/storage.md | 5 ++-- 10 files changed, 42 insertions(+), 42 deletions(-) diff --git a/specs/README.md b/specs/README.md index f920fc11..a0e875ec 100644 --- a/specs/README.md +++ b/specs/README.md @@ -56,13 +56,13 @@ specs/ Specs declare *what* must be true, not *how* to implement it. **Good** — declarative, testable: -> "Each project card shows: title (linked), stage badge, README excerpt truncated to 600 characters, member avatars (maintainer largest, ordered by role then alphabetically), and a button row for Public Site / Developers / Chat Channel where each URL is present." +> "Each project card shows: title (linked), stage badge, README excerpt truncated to 600 characters, member avatars (admins largest, ordered by role then alphabetically), and a button row for Public Site / Developers / Chat Channel where each URL is present." **Too vague** — implementer still has to guess: > "The project card shows project info." **Too detailed** — duplicates the code: -> "Map over `project.members.sortBy(m => m.role === 'maintainer' ? 0 : 1).map(...)` and render an `<Avatar size={m.role === 'maintainer' ? 64 : 48}>`..." +> "Map over `project.members.sortBy(m => m.isAdmin ? 0 : 1).map(...)` and render an `<Avatar size={m.isAdmin ? 64 : 48}>`..." ## Spec drift auditing diff --git a/specs/api/agents.md b/specs/api/agents.md index 63dc5b15..10dd698a 100644 --- a/specs/api/agents.md +++ b/specs/api/agents.md @@ -57,6 +57,9 @@ by GitHub sign-in: itself does), and an agent is created with its first grant, so an agent whose every grant has been revoked or has expired is still an agent account, under every rule below. +- It never follows, applies to, or joins a project, and is never a project + admin (`422`, `error.code = "agent_account"`); it acts on applications only + through its scopes. - It can never be raised to staff: `POST /api/people/:slug/account-level` refuses (`409 conflict`, `error.code = "agent_account"`) for a person with any grant on record. Agents are never staff, so an agent's vote and a human's diff --git a/specs/api/moderation.md b/specs/api/moderation.md index 143563b3..eebbb73a 100644 --- a/specs/api/moderation.md +++ b/specs/api/moderation.md @@ -93,7 +93,7 @@ vote nobody had cast on it.) "lastSlackSsoAt": "2026-09-18T01:15:00Z", "emailBounce": null, "bioExcerpt": "first ~160 chars of bio, markdown stripped", - "footprint": { "memberships": 2, "updates": 1, "buzz": 0, "blogPosts": 0, "helpWantedInterest": 1, "tags": 3, "rsvps": 1 }, + "footprint": { "memberships": 2, "applications": 1, "follows": 3, "updates": 1, "buzz": 0, "blogPosts": 0, "tags": 3, "rsvps": 1 }, "latestVote": { "verdict": "legit", "voter": { "slug": "chris", "fullName": "Chris Alfano" }, "evaluatedAt": "…" }, "stagedVote": null, "purgeAfter": null, @@ -124,9 +124,9 @@ Field notes: `github-new-account` (< 30 days), `github-no-activity` (0 repos and 0 followers), `slug-purged-before` (a [`spam-purges`](../data-model.md#spampurge) record names this slug: an earlier account under it was purged as spam). - Informational: `slack-sso`, `has-footprint` (any membership, update, buzz - item, blog post or help-wanted interest; tags and RSVPs do not count toward - it). + Informational: `slack-sso`, `has-footprint` (any membership in state + `member`, application, update, buzz item or blog post; follows, tags and + RSVPs do not count toward it). - `footprint` counts the member's records of each kind in the detail's `footprint` lists below; `rsvps` counts every event RSVP on record for the member, past and upcoming events alike. @@ -166,11 +166,12 @@ The row above, plus the full footprint and vote history: "data": { "person": { …Person as GET /api/people/:slug for staff, including email and deletedAt… }, "footprint": { - "memberships": [ { "project": { "slug", "title" }, "role", "joinedAt" } ], + "memberships": [ { "project": { "slug", "title" }, "role", "isAdmin", "via", "joinedAt" } ], + "applications": [ { "project": { "slug", "title" }, "status", "submittedAt", "closedBy" } ], + "follows": [ { "project": { "slug", "title" }, "followedAt" } ], "updates": [ { "project": { "slug", "title" }, "number", "title", "postedAt" } ], "buzz": [ { "project": { "slug", "title" }, "slug", "title", "postedAt" } ], "blogPosts": [ { "slug", "title", "postedAt" } ], - "helpWantedInterest": [ { "project": { "slug", "title" }, "role": { "title" }, "createdAt" } ], "tags": [ { "handle", "type" } ], "rsvps": [ { "event": { "slug", "title", "startsAt" }, "createdAt" } ] }, @@ -446,18 +447,15 @@ and runs its checks under the same lock. 6. **Nothing shared.** The member must not have created a project anyone else has touched (the rule in [person-lifecycle.md → Purge](../behaviors/person-lifecycle.md#purge-cascading-hard-delete-admin-only)), - and must not be a maintainer of any project with another member: - `409 shared_project`. A purge must never take a project or leave one - without its maintainer on an agent's say-so. - **Being a plain member of someone else's project does not block.** Joining - is self-service (`POST /api/projects/:slug/members/join`, any signed-in - user, no maintainer acceptance), so it carries no one else's judgment, and - spam accounts join real projects to borrow their credibility. The purge - removes the member's own membership and anything they posted there; the - project and everyone else's records are untouched. (A membership a - maintainer *added* would be different, but the membership record does not - say who added it; the agent's own policy treats a maintainer-added - membership as a reason not to act — see the plan.) + must not be an admin of any project with another member, and must not + hold a membership an admin chose (`via = added` or `application`) on a + project with another member: `409 shared_project`. A purge must never take + a project, leave one without its admins, or overrule an admin's choice of + member on an agent's say-so. + **Following or applying to someone else's project does not block.** Both + are self-service and carry no one else's judgment. The purge removes the + member's follows and applications and anything they posted; the project and + everyone else's records are untouched. 7. **The evidence goes with the purge.** Every evidence record must be one the purge deletes (the member's own record, a project the purge takes, or an update, buzz item or role they authored that goes with them): diff --git a/specs/architecture.md b/specs/architecture.md index e114cdce..a5fed30f 100644 --- a/specs/architecture.md +++ b/specs/architecture.md @@ -4,7 +4,7 @@ Foundational tech decisions for the codeforphilly.org rewrite. Everything downst ## Goal -A 1:1 modernization of [laddr](https://github.com/CodeForPhilly/laddr) as customized for [codeforphilly.org](https://codeforphilly.org). Same product surface, healthier foundation. Extending v1 features with a new **help-wanted roles** capability so project maintainers can advertise concrete asks. +A 1:1 modernization of [laddr](https://github.com/CodeForPhilly/laddr) as customized for [codeforphilly.org](https://codeforphilly.org). Same product surface, healthier foundation. Extending v1 features with a new **help-wanted roles** capability so project admins can advertise concrete asks that people apply for. Out of scope for v1: see [deferred.md](deferred.md). @@ -25,7 +25,7 @@ Out of scope for v1: see [deferred.md](deferred.md). | File uploads (avatars, buzz images) | **gitsheets attachments** | Binary blobs stored alongside their record via gitsheets' `setAttachment` API; served via streaming `GET /api/attachments/<key>`. | | Background jobs | **In-process timers + an in-memory queue** | At single-replica civic scale we don't need Redis/BullMQ for fan-out. Image thumbnailing, scheduled rollups, and async git pushes run in the same process. | | Logging | **pino** (Fastify default) | Pretty in dev, JSON in prod. | -| Email | **Postmark** (transactional) | For notifications like "help wanted interest expressed" and newsletter delivery (when that ships). Server token, not per-user OAuth. Postmark is what the legacy site already sends through, so the `codeforphilly.org` sender domain is already verified there. | +| Email | **Postmark** (transactional) | For notifications like "new application to your project" and newsletter delivery (when that ships). Server token, not per-user OAuth. Postmark is what the legacy site already sends through, so the `codeforphilly.org` sender domain is already verified there. | ### What we deliberately *don't* use @@ -218,7 +218,7 @@ Three levels, matching laddr's `Person.AccountLevel`: | Level | Who | Can | | ------- | ----- | ----- | | **Anonymous** | Not signed in | Browse public content; view profiles, projects, updates, buzz | -| **User** | Signed-in member | Update own profile; post project updates on projects they're a member of; post buzz to any project; create new projects (auto-becomes maintainer) | +| **User** | Signed-in member | Update own profile; post project updates on projects they're a member of; post buzz to any project; follow and apply to projects; create new projects (becomes the first admin) | | **Staff** | Trusted contributor | Edit any project; manage project members; promote help-wanted to highlighted; moderate content | | **Administrator** | Org leadership | All Staff powers + manage users + irreversible deletes + impersonate | diff --git a/specs/behaviors/account-migration.md b/specs/behaviors/account-migration.md index 10b4d71e..ccb9617c 100644 --- a/specs/behaviors/account-migration.md +++ b/specs/behaviors/account-migration.md @@ -218,7 +218,7 @@ If a user signs in fresh via GitHub (no auto-link), then later realizes they had a legacy account, the merge direction is **legacy-survives, fresh-folds-in**: -- All records authored by the fresh Person (updates, buzz, help-wanted, memberships) are re-pointed to the legacy Person's `id` +- All records authored by the fresh Person (updates, buzz, help-wanted, memberships in every state) are re-pointed to the legacy Person's `id`. Where both hold a membership on the same project, the one further along (member over applicant over follower; admin over not) is kept and the other deleted - The fresh Person is deleted (hard-delete; its `id` is gone) - The legacy Person gains the GitHub identity link - Anyone whose URL referenced the fresh Person's slug gets a 90-day `slug-history` redirect diff --git a/specs/behaviors/person-lifecycle.md b/specs/behaviors/person-lifecycle.md index 93ff666d..d4897c2e 100644 --- a/specs/behaviors/person-lifecycle.md +++ b/specs/behaviors/person-lifecycle.md @@ -14,7 +14,8 @@ The privacy / self-removal path — members should be able to remove themselves; - **Who:** a person may deactivate/reactivate their OWN account; staff and administrators may deactivate/reactivate ANY account. - **Mechanism:** sets `person.deletedAt = now()` (reactivate clears it). The record and relationships stay intact. -- **Visibility while deactivated:** excluded from public list endpoints; `GET /api/people/:slug` returns 404 for non-staff (staff may still fetch it, with `deletedAt` populated). Anywhere a deactivated person is referenced (project member grids, project-update/project-buzz authors, help-wanted "posted by", blog author) the serialized reference is a **"Deactivated user" placeholder** (no slug link, generic avatar) rather than the person — substitute, do not omit, so counts/history stay coherent. +- **Visibility while deactivated:** excluded from public list endpoints; `GET /api/people/:slug` returns 404 for non-staff (staff may still fetch it, with `deletedAt` populated). Anywhere a deactivated person is referenced (project member grids, project-update/project-buzz authors, help-wanted "posted by", an application's "decided by", blog author) the serialized reference is a **"Deactivated user" placeholder** (no slug link, generic avatar) rather than the person — substitute, do not omit, so counts/history stay coherent. +- **Their follows and applications go quiet.** A deactivated person's `project-memberships` records in state `follower` or `applicant` are left out of follower counts, admin views, notifications and the agent feed; a member's record still shows as the placeholder above. Nothing is rewritten, so reactivation restores them as they were ([project-membership.md → Spam and deactivated accounts](project-membership.md#spam-and-deactivated-accounts)). - **Login is NOT blocked** — a deactivated user can still authenticate and reactivate themselves. No session revocation. - **Surfaces:** self at `/account` ("Deactivate my account" / "Reactivate"); staff/admin via a person "Danger Zone"; and the **admin members screen**, where a `spam` vote deactivates the person in the same transaction that records the vote ([api/moderation.md](../api/moderation.md)). - **Deciding votes:** the human votes on a person, when there are any; otherwise the votes of agents that hold an active grant ([api/moderation.md → Agent votes](../api/moderation.md#agent-votes)). An agent vote stops deciding the moment any human votes on the person, and while its agent holds no active grant. Only votes on **this account** count: a vote older than the person's `createdAt`, or dated at or before the newest `spam-purges` record for the slug that names another person, was cast on an earlier account under the same slug and is ignored here and everywhere below ([api/moderation.md → Votes belong to one account](../api/moderation.md#votes-belong-to-one-account)). @@ -25,12 +26,12 @@ The privacy / self-removal path — members should be able to remove themselves; The garbage-collection path for spam — the runtime sibling of the offline spam-prune (behaviors/spam-exclusion.md). - **Who:** administrators; the [scheduled spam purge](#scheduled-spam-purge); and, for a new member who posted spam only, an agent holding `moderation:purge` ([Agent purge](#agent-purge)). (The heading keeps its old name so links to it hold.) -- **Mechanism:** one write-mutex transaction that hard-deletes: the `people` record; their `project-membership`; their `help-wanted-interest`; their `event-rsvps`; their person `tag-assignment`; AND their authored `project-update`, `project-buzz`, and `blog-post` records (unlike the prune which nulls authorId — purge DELETES the content, it's garbage). Their **private** data goes in the same transaction: private profile, legacy password credential, password-reset tokens, account-claim requests naming them, and their session metadata. A purged person leaves nothing behind in either store. +- **Mechanism:** one write-mutex transaction that hard-deletes: the `people` record; their `project-memberships` in every state (follows and applications too); their `event-rsvps`; their person `tag-assignment`; AND their authored `project-update`, `project-buzz`, and `blog-post` records (unlike the prune which nulls authorId — purge DELETES the content, it's garbage). Their **private** data goes in the same transaction: private profile (with any Slack link), legacy password credential, password-reset tokens, account-claim requests naming them, and their session metadata. A purged person leaves nothing behind in either store. - **Projects only they touched go too.** In the same transaction, purge hard-deletes every project the person created that nobody else has touched — spam accounts create spam projects, and a project left behind with no members is a soft-deleted husk an admin can't clear. A project qualifies when both hold: - 1. **Created by the person:** `createdById` is the person; for a project with no `createdById` (imported from laddr, or created before the field existed), the person is its `maintainerId`. - 2. **No one else touched it:** every membership is the person's, every update was authored by them, every buzz posted by them, every help-wanted role posted by them with no interest from anyone else, and no RSVP from anyone else names the project. + 1. **Created by the person:** `createdById` is the person; for a project with no `createdById` (imported from laddr, or created before the field existed), the person is one of its admins. + 2. **No one else touched it:** every `member` record is the person's, every update was authored by them, every buzz posted by them, every help-wanted role posted by them, and no RSVP from anyone else names the project. Other people's follows and applications do not count as touching it: they are one-click acts that carry no work, and counting them would let anyone shield a spam project by following it. - A qualifying project is deleted with everything that hangs off it: the project record and its attachments, its memberships, updates, buzz, help-wanted roles and their interest, its tag-assignments, and RSVPs naming it (slug-history entries are left to expire). A project anyone else touched is left exactly as it is (the person's own records on it are removed as above). + A qualifying project is deleted with everything that hangs off it: the project record and its attachments, its memberships in every state, updates, buzz, help-wanted roles, its tag-assignments, and RSVPs naming it (slug-history entries are left to expire). A project anyone else touched is left exactly as it is (the person's own records on it are removed as above). Attachments (avatars, buzz images) go with the records they hang off. - **Atomic + git-revertable** (one commit). - **Surface:** person "Danger Zone" (admin only), behind a confirm dialog. @@ -49,14 +50,14 @@ project, update, buzz item or help-wanted role — without the three-day wait - **Narrower than an administrator's purge by precondition, not by a smaller cascade.** The API refuses unless the member joined in the last 7 days, is a signed-up `user` with no human vote, no standing `legit` vote and no Slack - sign-in, created no project anyone else touched and maintains no project with - other members; the agent cites 1–5 records the member authored, which the API + sign-in, created no project anyone else touched and is an admin of no project with + other members, and holds no membership an admin chose (`via` `added` or + `application`) on a project with other members; the agent cites 1–5 records the member authored, which the API checks exist, are theirs and go with the purge; at most 5 a day per agent. Within those fences the cascade is the one above, so nothing an agent purge reaches belongs to anyone else, and the spam it cites is removed with the - account. A plain membership on someone else's project does not block (a - self-service join is no one else's judgment); the membership goes and the - project stays. + account. Following or applying to someone else's project does not block (no one + else's judgment is in it); those records go and the project stays. - **One commit per purge**, authored by the agent, with the reason in the body and `Evidence:` trailers; a `spam-purges` record (`by = "agent-<slug>"`) and the agent's `spam` vote record are written in the same commit. diff --git a/specs/behaviors/project-stages.md b/specs/behaviors/project-stages.md index 38880cdc..d6c119e3 100644 --- a/specs/behaviors/project-stages.md +++ b/specs/behaviors/project-stages.md @@ -30,7 +30,7 @@ The description column is the canonical short text. Render it in tooltips on sta ## Transition policy -v1 imposes no transition restrictions. Anyone permitted to edit a project (`maintainer | staff`) can set any stage. +v1 imposes no transition restrictions. Anyone permitted to edit a project (`project-admin | staff`) can set any stage. We track the desired-but-deferred policy for a future release: diff --git a/specs/behaviors/slug-handles.md b/specs/behaviors/slug-handles.md index 559f83e9..c26121de 100644 --- a/specs/behaviors/slug-handles.md +++ b/specs/behaviors/slug-handles.md @@ -73,7 +73,7 @@ Slugs **can** change. When they do: - The entity's attachments (avatar, featured image) move with the record, and any on-record attachment key (`avatarKey`, `featuredImageKey`) is rewritten to the new path. A rename changes the handle and nothing else about the entity. - **Every record that references the old slug is rewritten in the same commit**: its reference field takes the new slug, and since the slug is part of that record's path, the record moves too. The set of referencing sheets comes from the references the schemas declare ([data-model.md → References](../data-model.md)), not from a hand-kept list: - a project rename rewrites its `project-memberships`, `project-updates`, `project-buzz` and `help-wanted-roles`; - - a person rename rewrites their `project-memberships`, `help-wanted-interest`, `event-rsvps` and `person-evaluations`; + - a person rename rewrites their `project-memberships` (every state), `event-rsvps` and `person-evaluations`; - an event rename rewrites its `event-rsvps` (an event whose `startsAt` crosses a year boundary moves its RSVPs to the new `year` the same way). After a rename, no record anywhere holds the old slug as a reference. diff --git a/specs/behaviors/spam-exclusion.md b/specs/behaviors/spam-exclusion.md index 70a6abec..41d950f7 100644 --- a/specs/behaviors/spam-exclusion.md +++ b/specs/behaviors/spam-exclusion.md @@ -121,8 +121,7 @@ Applied to `published`, re-runnably. For each pruned person: 1. Delete the `people` record. 2. Cascade-delete records that belong to that person: - - `project-membership` where `personId` matches - - `help-wanted-interest` where `personId` matches + - `project-membership` where `personId` matches (every state: follows and applications too) - `event-rsvps` where `personSlug` matches - `tag-assignment` where `taggableType = "person"` and the taggable is that person 3. Unlink (do **not** delete) `project-update` records whose `authorId` is the @@ -143,7 +142,7 @@ deactivates the person immediately — [person-lifecycle.md](./person-lifecycle. and for the scheduled spam purge; the public read services stay spam-unaware. After a prune, `published` holds only kept people (legit + uncertain + unevaluated minus confident spam), so the in-memory state, indices, and FTS are built over that smaller set. Dangling -references are avoided by the cascade, so member lists, help-wanted interest, and +references are avoided by the cascade, so member lists, follows, applications and person tags never point at a removed person. ## Re-runnability & operations diff --git a/specs/behaviors/storage.md b/specs/behaviors/storage.md index ce21403a..4e954778 100644 --- a/specs/behaviors/storage.md +++ b/specs/behaviors/storage.md @@ -10,7 +10,7 @@ The two stores are siblings, not nested. Most mutations touch only one side; the ## Applies To -- Public records in [data-model.md](../data-model.md) — Person (public fields), Project, ProjectMembership, ProjectUpdate, ProjectBuzz, Tag, TagAssignment, HelpWantedRole, HelpWantedInterestExpression, Revocation, SlugHistory +- Public records in [data-model.md](../data-model.md) — Person (public fields), Project, ProjectMembership, ProjectUpdate, ProjectBuzz, Tag, TagAssignment, HelpWantedRole, Revocation, SlugHistory - [architecture.md](../architecture.md) — process model, deploy, dev experience - [behaviors/private-storage.md](private-storage.md) — the private sibling - [behaviors/legacy-id-mapping.md](legacy-id-mapping.md) — `legacyId` lookups happen against the in-memory state @@ -112,7 +112,6 @@ Each entity lives in one sheet. The path template determines how records are sto | ProjectBuzz | `project-buzz` | `project-buzz/${projectSlug}/${slug}.toml` | | BlogPost | `blog-posts` | `blog-posts/${slug}.md` (markdown format, body in `body`) | | HelpWantedRole | `help-wanted-roles` | `help-wanted-roles/${projectSlug}/${id}.toml` | -| HelpWantedInterestExpression | `help-wanted-interest` | `help-wanted-interest/${roleId}/${personSlug}.toml` | | Event | `events` | `events/${year}/${slug}.md` — markdown body `description`; `year` rendered from `startsAt` | | EventRsvp | `event-rsvps` | `event-rsvps/${year}/${eventSlug}/${personSlug}.toml` | | EventSeries | `event-series` | `event-series/${slug}.md` — markdown body `description` | @@ -271,7 +270,7 @@ Rules: - The **author and committer identity is pseudonymous** in the public repo: `<Person.fullName> <<slug>@users.noreply.codeforphilly.org>`. **Real email addresses are never written as commit authors** — git stores author identity forever and the data repo is public. The pseudonymous form keeps `git log --author=<slug>` and `git blame` working naturally for audit purposes without leaking PII. - For anonymous requests, author is `Anonymous <anon@users.noreply.codeforphilly.org>`. - For system/automated commits (migration import, reconciliation), author is `Code for Philly API <api@users.noreply.codeforphilly.org>`. - - For requests made with an [agent grant](authorization.md#agent-grants), author is the agent account's pseudonymous identity like any person's, and the commit adds two trailers: `Actor-Kind: agent` and `Grant-Id: <grant id>` (never the token). `git log --grep='^Actor-Kind: agent$'` lists everything agents did. An agent purge also carries `Purge-Id: <spam-purges id>` and one `Evidence: <data-repo path>[#<field>]` per cited record, with the agent's reason as the body ([api/moderation.md → Agent purges](../api/moderation.md#agent-purges)); the reason may not contain a URL, so the spam link is never republished in a commit message. + - For requests made with an [agent grant](authorization.md#agent-grants), author is the agent account's pseudonymous identity like any person's, and the commit adds two trailers: `Actor-Kind: agent` and `Grant-Id: <grant id>` (never the token). `git log --grep='^Actor-Kind: agent$'` lists everything agents did. A decision an agent records for a project admin adds `On-Behalf-Of: <admin slug>` ([authorization.md → On behalf of a project admin](authorization.md#on-behalf-of-a-project-admin)). An agent purge also carries `Purge-Id: <spam-purges id>` and one `Evidence: <data-repo path>[#<field>]` per cited record, with the agent's reason as the body ([api/moderation.md → Agent purges](../api/moderation.md#agent-purges)); the reason may not contain a URL, so the spam link is never republished in a commit message. - **`User-Ip` and `User-Agent` trailers are NOT included.** The public commit history is forever-public; client IPs and user agents are PII that doesn't belong there. If a security incident needs request forensics, that's what the optional access-log sidecar (private store) is for — not the public git log. - The **trailers** follow git's standard trailer format (parseable by `git interpret-trailers --parse`). Key convention is HTTP-header style: first letter capitalized, multi-word keys hyphenated, rest lowercase. Examples: `Subject-Type`, `Response-Code`. Single-word keys: `Action`, `Reason`, `Host`. - `Action` is namespaced with a dot (`project.soft-delete`, `tag.merge`, `account-level.change`) so trailer filters like `git log --grep='^Action: project\.'` work cleanly. From e609131d24bd5c87462d1329f0c8140f93ae7a4b Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:57:33 +0000 Subject: [PATCH 08/78] docs(specs): defer project review, application switches, wider Slack acts Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- specs/deferred.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/specs/deferred.md b/specs/deferred.md index f29515d3..22098357 100644 --- a/specs/deferred.md +++ b/specs/deferred.md @@ -96,6 +96,21 @@ When a deferred item is promoted, move it from this file into the relevant spec, - **What:** A month-grid rendering of `/events`; events in the header typeahead. - **Why deferred:** With roughly one event a month, the grouped list is denser and clearer, and the `webcal://` feed puts events in the member's own calendar. Promote if the list outgrows a screen. +### Review of new projects + +- **What:** New projects held (hidden, or in a staff queue) until a person looks, before they appear in the directory. +- **Why deferred:** Out of scope for the membership redesign by the operator's decision. Project creation, not joining, is where most spam has come from since cutover, so this is the likely next step; [project-membership.md](behaviors/project-membership.md) closes the join path only. + +### Per-project "not taking applications" switch and admin email preferences + +- **What:** A project-level toggle that turns Apply off while admins exist, and a per-admin, per-project mute for application emails. +- **Why deferred:** Closing needs and the no-active-admin state cover the common cases; add when admins ask. Today every active admin gets every application email. + +### Decisions from Slack beyond applications + +- **What:** Using the same verified Slack link and on-behalf-of pattern for other admin acts (stale-need reminders answered in Slack, staff review of new projects, the spam queue). +- **Why deferred:** Each act needs its own scope and spec change ([authorization.md](behaviors/authorization.md#on-behalf-of-a-project-admin)); applications are the first. + ### Project comments - **What:** Inline comments on project pages (the `Comment::class` references in laddr's Project model). Largely commented-out in the template even in laddr — the feature was half-built. From 4f7da6943d8cf4705896422c538b2b7600f3863b Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:57:56 +0000 Subject: [PATCH 09/78] docs(specs): leave the interest sheet's removal to the needs retirement Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- specs/behaviors/project-membership.md | 1 - 1 file changed, 1 deletion(-) diff --git a/specs/behaviors/project-membership.md b/specs/behaviors/project-membership.md index e0056c49..c616e705 100644 --- a/specs/behaviors/project-membership.md +++ b/specs/behaviors/project-membership.md @@ -232,7 +232,6 @@ moves every record to this model in one commit: - A project whose `maintainerId` names a person with no membership gets no membership from it; if no other admin results, the project has no admin until staff add one. -- The `help-wanted-interest` sheet is dropped, with any records it holds. Staff keep every project-admin power on every project, so a project with no admin can be given one from its Manage Members panel by staff. From b4550699d3f85d391664bd717dd2ca7fada2f432 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:00:20 +0000 Subject: [PATCH 10/78] chore(plans): plan the project membership redesign as seven slices membership-admins first; follow and applications on it; needs after applications; Slack linking independent; the agent feed and decisions last, each awaiting the ops bot's side. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- plans/agent-application-feed.md | 54 +++++++++++++ plans/agent-decide-on-behalf.md | 63 +++++++++++++++ plans/membership-admins.md | 128 +++++++++++++++++++++++++++++++ plans/membership-applications.md | 97 +++++++++++++++++++++++ plans/membership-follow.md | 71 +++++++++++++++++ plans/needs-on-applications.md | 73 ++++++++++++++++++ plans/slack-account-link.md | 71 +++++++++++++++++ 7 files changed, 557 insertions(+) create mode 100644 plans/agent-application-feed.md create mode 100644 plans/agent-decide-on-behalf.md create mode 100644 plans/membership-admins.md create mode 100644 plans/membership-applications.md create mode 100644 plans/membership-follow.md create mode 100644 plans/needs-on-applications.md create mode 100644 plans/slack-account-link.md diff --git a/plans/agent-application-feed.md b/plans/agent-application-feed.md new file mode 100644 index 00000000..70cd3939 --- /dev/null +++ b/plans/agent-application-feed.md @@ -0,0 +1,54 @@ +--- +status: planned +depends: [membership-applications, slack-account-link] +specs: + - specs/api/agent-applications.md + - specs/api/agents.md +awaits: + - "CodeForPhilly/grittybot — heartbeat stream that reads GET /api/agent/events and DMs admins, marked as AI (bot repo, by PR)" + - "GrittyBot Slack app gains mpim:write (group DMs), merged in the bot repo and installed by a workspace admin" +--- + +# Plan: Application event feed for agents + +## Scope + +The read side of Slack coordination: an agent with +`projects:applications:read` reads application events, including the offer +and the linked Slack ids of the project's active admins, so it can DM them. + +**In:** `GET /api/agent/events` with the four event types, opaque stable +cursor, 7-day default window, deactivated applicants excluded; admins with +`slackUserId` only when linked; no email anywhere. + +**Out:** decisions ([`agent-decide-on-behalf`](agent-decide-on-behalf.md)); +the bot's stream and DMs (awaited). + +## Implements + +- [agent-applications.md](../specs/api/agent-applications.md) — GET /api/agent/events +- [agents.md](../specs/api/agents.md) — `projects:applications:read` + +## Approach + +Derive events from membership records' `application` timestamps +(`visibleAt` once `notifiedAt` is set, `remindedAt`, `decidedAt`, `closedAt`) +over the `openApplications` index plus recently decided records; sort by +`(at, record id)`; encode the cursor as base64url of that pair. + +## Validation + +- [ ] Tests: each event type appears once at the right `at`; paging with `next` returns every event exactly once across pages and across a restart +- [ ] Tests: a held application yields nothing until notified; a deactivated applicant's events vanish +- [ ] Tests: `admins[].slackUserId` is set only for linked, active admins; no field anywhere carries an email (schema test on the response) +- [ ] A grant without the scope is refused +- [ ] End to end: an application on sandbox produces an AI-marked DM to its linked admin (awaits the bot PR and `mpim:write`) +- [ ] `npm run type-check && npm run lint && npm test` clean + +## Risks / unknowns + +- **Offer text leaves the site.** The bot receives it to DM admins; the bot's policy forbids showing it to anyone else ([agent-applications.md](../specs/api/agent-applications.md#what-the-agent-must-never-do)). + +## Notes + +## Follow-ups diff --git a/plans/agent-decide-on-behalf.md b/plans/agent-decide-on-behalf.md new file mode 100644 index 00000000..6e28ba7e --- /dev/null +++ b/plans/agent-decide-on-behalf.md @@ -0,0 +1,63 @@ +--- +status: planned +depends: [agent-application-feed, needs-on-applications] +specs: + - specs/api/agent-applications.md + - specs/behaviors/authorization.md + - specs/behaviors/storage.md + - specs/api/agents.md + - specs/screens/project-applications.md +awaits: + - "CodeForPhilly/grittybot — DM reply/button handling that records an admin's accept or close via the decision endpoint (bot repo, by PR)" +--- + +# Plan: Agent records an admin's decision from Slack + +## Scope + +The one place a grant acts for a person: an agent with +`projects:applications:decide` records a named, verified project admin's +accept or close of one open application. + +**In:** `POST /api/agent/applications/:projectSlug/:personSlug/decision`; +resolution of `onBehalfOf` through the Slack link; the live project-admin +check (staff powers do not carry over); same effects as the site's accept and +close with `decidedVia = agent` and `agentGrantId`; `On-Behalf-Of` trailer; +confirmation email to the named admin; 30 per agent per day; "via the ops +bot" on the Applications screen. + +**Out:** any other on-behalf act ([deferred.md](../specs/deferred.md)). + +## Implements + +- [agent-applications.md](../specs/api/agent-applications.md) — the decision endpoint +- [authorization.md](../specs/behaviors/authorization.md) — On behalf of a project admin +- [storage.md](../specs/behaviors/storage.md) — `On-Behalf-Of` trailer +- [agents.md](../specs/api/agents.md) — `projects:applications:decide` +- [project-applications.md](../specs/screens/project-applications.md) — "via the ops bot" + +## Approach + +Reuse the site accept/close service with an actor that carries the agent +(for authorship and trailers) and the deciding person (for `decidedById` and +the authorization check). The authorization check is the same function the +site uses for `project-admin`, run against the resolved person with staff +override disabled. + +## Validation + +- [ ] Tests: a linked active admin's accept and close succeed; commit author is the agent with `Actor-Kind: agent`, `Grant-Id` and `On-Behalf-Of: <admin slug>`; the record has `decidedById` = admin, `decidedVia = agent`, `agentGrantId` +- [ ] Tests: unlinked Slack user, linked non-admin, linked staff who is not a project admin, and a deactivated admin all get `403 not_project_admin` +- [ ] Tests: the grant cannot add, remove, promote or touch needs through any route +- [ ] Tests: the named admin gets one confirmation email per decision; the 31st decision in 24 hours → `429` +- [ ] `git log --grep='^On-Behalf-Of: '` on the test repo lists exactly the agent's decisions +- [ ] End to end: an admin answers in a Slack DM and the application moves on the site (awaits the bot PR) +- [ ] `npm run type-check && npm run lint && npm test` clean + +## Risks / unknowns + +- **A stolen token can decide for any linked admin.** Bounded by the daily cap, visible through the confirmation email to the admin, reversible (remove the member; re-add after a close), and stopped by revoking the grant. + +## Notes + +## Follow-ups diff --git a/plans/membership-admins.md b/plans/membership-admins.md new file mode 100644 index 00000000..e4a09996 --- /dev/null +++ b/plans/membership-admins.md @@ -0,0 +1,128 @@ +--- +status: planned +depends: [] +specs: + - specs/behaviors/project-membership.md + - specs/data-model.md + - specs/behaviors/authorization.md + - specs/api/conventions.md + - specs/api/projects-members.md + - specs/api/projects.md + - specs/api/people.md + - specs/api/moderation.md + - specs/behaviors/person-lifecycle.md + - specs/behaviors/account-migration.md + - specs/behaviors/project-stages.md + - specs/screens/project-detail.md + - specs/screens/project-edit.md + - specs/screens/person-detail.md + - specs/screens/people-index.md + - specs/screens/projects-index.md +--- + +# Plan: Project admins and the membership record + +## Scope + +The foundation slice: the one-record membership model, any number of project +admins in place of the single maintainer, and the end of open join. After +this plan, people join a project only when an admin adds them; following and +applying arrive in [`membership-follow`](membership-follow.md) and +[`membership-applications`](membership-applications.md). + +**In:** + +- `project-memberships` contract v3: `state`, `isAdmin`, `via`, `muted`, + `followedAt`, optional `joinedAt`, and the full `application` table (unused + until applications ship, so the contract moves once). `projects` contract v3 + without `maintainerId`. +- The migration script (every membership → `member`, `via = legacy`; admins + from `isMaintainer` ∪ `maintainerId`; drop both old fields). +- The `project-admin` marker everywhere `maintainer` was; staff override. +- Members API: add (any prior state, notice email), patch `role`/`isAdmin` + (promote/demote), remove (deletes record), leave (→ follower, or delete with + `alsoUnfollow`), `last_admin` with `confirmLastAdmin`. `join` and + `change-maintainer` answer `410 gone`. +- Project create writes the founder as admin. `GET /api/projects/:slug`: + `memberships` members only, admins first; `hasActiveAdmin`; `viewer` + (state/isAdmin; `application` and `reapplyAfter` stay `null` until + applications ship); `counts.members` members only. List item `admins`; + `admin` filter with `maintainer` alias; `memberSlug` members only. +- People: `memberOfCount`/`adminOfCount`, `memberships` members only, `isAdmin`. +- Moderation: agent purge rule 6 (admin of a shared project, or a `via` + `added`/`application` membership on a shared project, blocks); purge's + `createdById` fallback uses "an admin"; purge and account merge handle + memberships in every state. +- Screens: Manage Members (make/remove admin, remove, confirm last admin), Add + Member with "Make admin", Join block's member row (Leave / Mute), admin + chips and ordering on project, person, people and projects lists. + +**Out:** follow endpoints and follower email ([`membership-follow`](membership-follow.md)); +applications and the no-active-admin Apply state +([`membership-applications`](membership-applications.md)); needs changes +([`needs-on-applications`](needs-on-applications.md)). + +## Implements + +- [project-membership.md](../specs/behaviors/project-membership.md) — States, the add/promote/demote/leave/remove/update transitions, Project creation, The last admin, Migration from single maintainers, the Add notification +- [data-model.md](../specs/data-model.md) — ProjectMembership (all fields), Project without `maintainerId` +- [authorization.md](../specs/behaviors/authorization.md), [conventions.md](../specs/api/conventions.md) — `member` and `project-admin` markers; staff override +- [projects-members.md](../specs/api/projects-members.md) — every endpoint except follow +- [projects.md](../specs/api/projects.md) — create, Project and list shapes, `admin` filter, Admins section +- [people.md](../specs/api/people.md), [moderation.md](../specs/api/moderation.md) (Agent purges rule 6), [person-lifecycle.md](../specs/behaviors/person-lifecycle.md), [account-migration.md](../specs/behaviors/account-migration.md) (merge) +- Screens: project-detail (Members, Manage Members, Add Member, member row of Join), project-edit, person-detail, people-index, projects-index + +## Approach + +1. **Schemas and contracts.** Update `ProjectMembershipSchema` and + `ProjectSchema` in `@cfp/shared` with the validators in data-model.md; + generate `project-memberships/v3.json` and `projects/v3.json`. Push them on + a branch, adopt on the data repo's `empty`, `fixture` and `legacy-import` + branches and mirror into `apps/api/gitsheets/` in the same PR + ([storage.md → Order of a change](../specs/behaviors/storage.md#schema-contracts)). + Adoption on `published` goes out with the release. +2. **Migration** at `apps/api/scripts/migrations/<ts>-project-admins.ts`: one + tree write, one commit, idempotent (a second run changes nothing). It + prints counts only: memberships migrated, admins set, projects left with + no admin. Run on `fixture` and `legacy-import` in the data-repo PR; on + `published` immediately before deploy. +3. **In-memory state.** `adminsByProject` index; `isProjectAdmin(caller, + slug)` replaces `isMaintainerOf`; `hasActiveAdmin(slug)` (an admin who is + not deactivated and has a deliverable email or a Slack link — the Slack half + reads `PrivateProfile.slack`, absent until + [`slack-account-link`](slack-account-link.md)). Public serializers filter + `state = member` and deactivated people. +4. **Routes.** Rework `project-membership.write.ts` around the transition + table; each transition is one commit with `Action: + project-membership.<transition>`. `410` handlers for `join` and + `change-maintainer` carry a removal note for the release after next. +5. **Notifier.** `notifyMemberAdded` (who added them, how to leave), reading + the address from the private profile at send time. +6. **Web.** Join block member row, Manage Members modal, admin markers and + ordering. Remove the Join button. + +## Validation + +- [ ] `project-memberships/v3` and `projects/v3` are generated, committed, adopted on the data repo's `empty`, `fixture` and `legacy-import` branches, and mirrored; CI's contract and mirror checks pass +- [ ] Migration on a copy of `legacy-import`: every membership is `state = member`, `via = legacy`; a membership is admin iff it was `isMaintainer` or its person was the project's `maintainerId`; no record keeps `isMaintainer`, no project keeps `maintainerId`; a second run makes no commit; output is counts only +- [ ] Creating a project writes the founder membership (`member`, admin, `Founder`, `via = created`) in the project's commit +- [ ] Tests: a project admin and staff can add (from no record, follower and applicant records written by fixture), promote, demote, remove and relabel; a plain member gets `403`; a member may change only their own `role` +- [ ] Tests: demote, remove or leave that would leave no active admin returns `409 last_admin` without `confirmLastAdmin` and succeeds with it +- [ ] Tests: leave moves the record to `follower` clearing `role`/`isAdmin`/`via`/`joinedAt`; `alsoUnfollow` deletes it; remove deletes it +- [ ] `POST …/members/join` and `POST …/change-maintainer` return `410 gone` +- [ ] Add sends one notice email to the added person (notifier test double), with no address written to any record or commit +- [ ] `GET /api/projects/:slug` lists members only, admins first; `memberOfCount`/`adminOfCount` and person `memberships` count members only; a follower fixture appears in none of them +- [ ] Agent purge test: a member added by an admin to a project with another member is refused `409 shared_project`; a follower-only footprint is not +- [ ] Account merge test: two records on one project collapse to the one further along +- [ ] Browser: on a project page as admin, make a co-admin, remove admin from yourself with the last-admin confirmation, add a member; as a non-member, no Join button exists +- [ ] `npm run type-check && npm run lint && npm test` clean + +## Risks / unknowns + +- **Dormant admins.** Most live projects are hibernating; their migrated admins may never answer. `hasActiveAdmin` only checks for a deliverable email, not recent activity. Watch how many applications close for age after launch. +- **Contract lockstep.** Three contract bumps across this DAG (`project-memberships`, `projects` here; `help-wanted-roles`, `agent-grants` later) each need a data-repo adoption and a `published` adoption at deploy. Batch the `published` adoptions per release. +- **Old links.** `?maintainer=` on `/projects` keeps working as an alias; anything else that read `maintainerId` (exports, the scrubbed snapshot) must be found by grep before the field goes. + +## Notes + +## Follow-ups diff --git a/plans/membership-applications.md b/plans/membership-applications.md new file mode 100644 index 00000000..53fde1c0 --- /dev/null +++ b/plans/membership-applications.md @@ -0,0 +1,97 @@ +--- +status: planned +depends: [membership-admins] +specs: + - specs/behaviors/project-membership.md + - specs/api/projects-applications.md + - specs/api/projects.md + - specs/api/moderation.md + - specs/behaviors/person-lifecycle.md + - specs/screens/project-detail.md + - specs/screens/project-applications.md + - specs/screens/admin-members.md +--- + +# Plan: Apply to join, with email to admins + +## Scope + +The application flow on the site, with email as the only channel: a person +applies (selecting open needs and/or writing an offer), the project's active +admins are emailed, and an admin accepts or closes it on the Applications +screen. + +**In:** + +- `POST /api/projects/:slug/applications`, `…/mine/close`, `GET …/applications`, + `…/:personSlug/accept`, `…/:personSlug/close`, with every error in the API + spec; `roleIds` validated against the project's open needs. +- Re-apply wait (30 days after an admin close), the 3-open and 5-per-day + limits, the 24-hour new-account hold (`visibleAt`). +- The sweep: notify at `visibleAt` (`notifiedAt`), 14-day reminder + (`remindedAt`), close for age at 30 days (`closedBy = site`, one commit per + run by `cfp-api`). +- Emails: new application and reminder to each active admin (addresses read + from private profiles at send time); accepted, closed-by-admin (with the + unstored note) and closed-for-age to the applicant. +- `hasActiveAdmin` gates Apply; the no-active-admin message. +- `viewer.application`, `viewer.reapplyAfter`, `permissions.canApply`, + `canReviewApplications`, `counts.openApplications`. +- Hidden applications of deactivated applicants; purge deletes them. +- Screens: the Applications screen; the apply form; Join block applicant and + re-apply rows; "Applications (N)" action. +- `applications` in the moderation footprint and on `/admin/members`. + +**Out:** "mark filled" on accept and need-card Apply buttons +([`needs-on-applications`](needs-on-applications.md)); agent feed and +decisions ([`agent-application-feed`](agent-application-feed.md), +[`agent-decide-on-behalf`](agent-decide-on-behalf.md)). + +## Implements + +- [project-membership.md](../specs/behaviors/project-membership.md) — apply, accept, close transitions; Re-apply limits; Applying; New-account hold; What admins see; Accepting (without fills); Closing; Spam and deactivated accounts; Notifications (application rows) +- [projects-applications.md](../specs/api/projects-applications.md) — all endpoints, shapes, sweeps +- [projects.md](../specs/api/projects.md) — `viewer`, `hasActiveAdmin`, application permissions and counts +- [moderation.md](../specs/api/moderation.md), [admin-members.md](../specs/screens/admin-members.md) — `applications` footprint +- [person-lifecycle.md](../specs/behaviors/person-lifecycle.md) — deactivation hides applications +- [project-detail.md](../specs/screens/project-detail.md), [project-applications.md](../specs/screens/project-applications.md) + +## Approach + +1. Application write service over the membership record; each transition one + commit; commit bodies never quote `offer` or `note`. +2. `openApplications` index ordered by `visibleAt`; the sweep runs daily and + shortly after boot, like event reminders, and records `notifiedAt` / + `remindedAt` in its own commit before sending. +3. One notifier method per email kind; one resolver `activeAdminRecipients(slug)` + that reads each admin's private-profile email and skips undeliverable ones. + This is the fix for the old null-recipient defect, so it gets its own test. +4. Applicant facts (`accountCreatedAt`, `hasGitHubLink`, `memberOf`) from + public records only. +5. Web: apply form (needs as checkboxes, offer box, the visibility note), + Applications screen with Accept and Close application dialogs, Join block + rows. Copy follows the screen's principles: never "declined" or "rejected". + +## Validation + +- [ ] Tests: apply from no record and from follower → `applicant`, `application.status = open`; second apply → `409 application_open`; member → `409 already_member`; no active admin → `409 no_active_admin`; empty `roleIds` without `offer` → `422`; a closed or foreign role id → `422` +- [ ] Tests: admin close → `follower`, `closedBy = admin`, `decidedById` set; re-apply within 30 days → `409 reapply_too_soon` with `reapplyAfter`; after applicant close or close-for-age, re-apply succeeds at once +- [ ] Tests: the 4th open application site-wide and the 6th in 24 hours return `429` +- [ ] Tests: an account under 24 hours old applies; the application is not listed to admins and no email goes until `visibleAt`; the sweep then notifies once +- [ ] Tests: the sweep sends the 14-day reminder once and closes at 30 days in one `cfp-api` commit; a second run the same day does nothing +- [ ] Notifier test double: a new visible application emails every active admin of the project and no one else; an admin with a hard-bounced address is skipped; the close note appears in the applicant's email and in no record, commit message or log line +- [ ] A deactivated applicant's application disappears from the list, counts and emails, and returns unchanged on reactivation; purge deletes it +- [ ] The project page shows the no-active-admin message (with `/chat` link) instead of Apply on a fixture project whose only admin is deactivated +- [ ] Applications screen: project admin and staff see it; a plain member gets 403 +- [ ] Browser: apply as a new user with an offer, see "Application sent"; as the admin, accept from the Applications screen and see the person in Members; repeat and close, and see the applicant return to "Following ✓" with the re-apply date +- [ ] `npm run type-check && npm run lint && npm test` clean + +## Risks / unknowns + +- **Postmark.** New email kinds go through the existing server token and stream; that production has the sender and stream for them is unverified. Send one of each on sandbox before release. +- **Applications into the void.** Admins with a working address who never read mail will see applications close for age. The applicant email says so kindly; the agent feed's staff nudge is the backstop. +- **Applications in the public data repo.** Offer text is public to anyone with the data repo. The site's visibility rule does not change that; the apply form's note says who sees it on the site. + +## Notes + +## Follow-ups diff --git a/plans/membership-follow.md b/plans/membership-follow.md new file mode 100644 index 00000000..47cb317f --- /dev/null +++ b/plans/membership-follow.md @@ -0,0 +1,71 @@ +--- +status: planned +depends: [membership-admins] +specs: + - specs/behaviors/project-membership.md + - specs/api/projects-members.md + - specs/api/projects.md + - specs/api/moderation.md + - specs/behaviors/help-wanted-roles.md + - specs/screens/project-detail.md + - specs/screens/admin-members.md +--- + +# Plan: Follow a project + +## Scope + +Open, one-click following, with follower email for new updates and new needs. +Followers are never listed; the project page shows a count. + +**In:** `POST`/`DELETE`/`PATCH /api/projects/:slug/follow`; `followerCount` +and `counts.followers` (follower + applicant records, deactivated people +excluded); `viewer.muted`; the Join block's anonymous, no-record and follower +rows with the Mute / Unfollow menu and the "{n} following" line; follower +email on a new project update and a new open need, to followers, applicants +and members except the poster, skipping `muted`, capped at 3 per project per +24 hours; `follows` in the moderation footprint (count and detail list) and +on `/admin/members`. + +**Out:** applying ([`membership-applications`](membership-applications.md)). + +## Implements + +- [project-membership.md](../specs/behaviors/project-membership.md) — follow and unfollow transitions; Notifications (the follower row and cap); Spam and deactivated accounts (for follows) +- [projects-members.md](../specs/api/projects-members.md) — the three follow endpoints +- [projects.md](../specs/api/projects.md) — `followerCount`, `counts.followers`, `viewer.muted`, `permissions.canFollow` +- [help-wanted-roles.md](../specs/behaviors/help-wanted-roles.md) — "posting an open need emails followers" +- [moderation.md](../specs/api/moderation.md), [admin-members.md](../specs/screens/admin-members.md) — `follows` footprint +- [project-detail.md](../specs/screens/project-detail.md) — Join block follow rows, follower count + +## Approach + +1. Follow endpoints on the membership write service; follow on an existing + record of any state is a `200` no-op with no commit. Agent accounts refused. +2. Follower count from an in-memory count per project, maintained on every + membership write and on deactivate/reactivate. +3. Follower email: hooks after the update-post and need-post commits; the cap + is an in-memory per-project counter of sends in the last 24 hours (reset on + restart is acceptable, like rate limits). Each email links to the project + page, where Mute lives. +4. Web: Join block rows; "Following ✓" menu. + +## Validation + +- [ ] Tests: follow creates a `follower` record and commit `Action: project-membership.follow`; following again changes nothing and makes no commit; unfollow deletes it; unfollow as applicant or member returns `409 not_a_follower` +- [ ] Tests: `PATCH …/follow` toggles `muted` in every state and nothing else +- [ ] `followerCount` counts follower and applicant records and leaves out a deactivated follower; no endpoint returns a follower's identity (checked against project, people and list responses) +- [ ] Notifier test double: a new update emails each follower, applicant and member except the poster and muted records; the fourth post in 24 hours sends nothing +- [ ] Posting an open need sends the same follower email +- [ ] `/admin/members` footprint shows follows (count on the row when non-zero, list in the detail) +- [ ] Browser: as a signed-in non-member, Follow, see "Following ✓" and the count rise, Mute, Unfollow +- [ ] `npm run type-check && npm run lint && npm test` clean + +## Risks / unknowns + +- **Follow as a spam vector.** A follow is not public on the site, but it is a record in the data repo. If spam accounts follow en masse, follower counts inflate until spam review deactivates them (which drops them from counts). +- **Email volume.** The per-project cap bounds one project; a person following many active projects could still get a lot. Watch bounce and complaint rates in Postmark. + +## Notes + +## Follow-ups diff --git a/plans/needs-on-applications.md b/plans/needs-on-applications.md new file mode 100644 index 00000000..2a349979 --- /dev/null +++ b/plans/needs-on-applications.md @@ -0,0 +1,73 @@ +--- +status: planned +depends: [membership-applications] +specs: + - specs/behaviors/help-wanted-roles.md + - specs/api/projects-help-wanted.md + - specs/api/projects-applications.md + - specs/data-model.md + - specs/behaviors/storage.md + - specs/behaviors/slug-handles.md + - specs/behaviors/spam-exclusion.md + - specs/screens/project-detail.md + - specs/screens/help-wanted-index.md + - specs/screens/home.md +--- + +# Plan: Needs on applications, and retiring express-interest + +## Scope + +Make help-wanted roles the needs people apply for, and remove the old +interest feature with its two defects. + +**In:** `help-wanted-roles` contract v3 (`filledByIds`, `detailsUrl`); +fill by several members with `keepOpen`, never adding anyone; "mark filled" +on accept (`fillRoleIds`); need cards' Apply / Application sent / Member / +Sign in / Not taking applications states on the project page, `/help-wanted` +and home rail; `detailsUrl` on cards and forms; the role menu for project +admins; `express-interest` → `410`; the `help-wanted-interest` sheet, schema, +contract, indices and every reference (purge, prune, slug rename, account +claim) removed; `interestCount` gone. + +**Out:** the 90-day stale-need reminder stays deferred as its spec says. + +## Implements + +- [help-wanted-roles.md](../specs/behaviors/help-wanted-roles.md) — lifecycle by project-admin, Side effects, Display rules, Interest expressions (retired) +- [projects-help-wanted.md](../specs/api/projects-help-wanted.md) — auth markers, `detailsUrl`, fill with `filledBySlugs`/`keepOpen`, shape without `interestCount` +- [projects-applications.md](../specs/api/projects-applications.md) — `fillRoleIds` on accept +- [data-model.md](../specs/data-model.md) — HelpWantedRole; HelpWantedInterestExpression removed +- [storage.md](../specs/behaviors/storage.md), [slug-handles.md](../specs/behaviors/slug-handles.md), [spam-exclusion.md](../specs/behaviors/spam-exclusion.md) — interest sheet gone +- Screens: project-detail (need cards), help-wanted-index, home + +## Approach + +1. Schema and contract v3 for `help-wanted-roles`; a migration turning any + `filledById` into `filledByIds` (live data has no roles; fixtures may). +2. Drop the `help-wanted-interest` sheet from the data repo's `empty`, + `fixture` and `legacy-import` branches and the API mirror; remove its + schema, loader, incremental-reload entry, reference cascade, account-claim + re-pointing, purge and prune steps. Leave `contracts/…/help-wanted-interest/` + files in place (published contracts are immutable) but unused. +3. Accept with `fillRoleIds` writes the fills in the accept commit. +4. Web: need-card states shared by project page, index and rail; fill dialog + with member multi-picker and "keep open". + +## Validation + +- [ ] `help-wanted-roles/v3` adopted and mirrored; the `help-wanted-interest` sheet is absent from `empty`, `fixture`, `legacy-import` and `apps/api/gitsheets/`; grep finds no runtime reference to it +- [ ] `POST …/express-interest` returns `410 gone`; no response carries `interestCount` +- [ ] Tests: fill with two member slugs records both and sets `filled`; `keepOpen` records them and stays `open`; a non-member slug → `422 not_a_member`; fill never creates a membership +- [ ] Tests: accept with `fillRoleIds` fills those needs in the same commit; a role not in the application or not open → `422` +- [ ] Need cards show the right one of Apply / Application sent / Member / Sign in to apply / Not taking applications for each caller state (component tests) +- [ ] Browser: from `/help-wanted`, Apply on a need opens the apply form with it ticked; as admin, accept with "mark filled" and see the need leave the board +- [ ] `npm run type-check && npm run lint && npm test` clean + +## Risks / unknowns + +- **Interest records on `published`.** The sketch found no help-wanted roles on live data, so no interest records; confirm with a count before dropping the sheet, and stop if any exist. + +## Notes + +## Follow-ups diff --git a/plans/slack-account-link.md b/plans/slack-account-link.md new file mode 100644 index 00000000..1b8cd7d3 --- /dev/null +++ b/plans/slack-account-link.md @@ -0,0 +1,71 @@ +--- +status: planned +depends: [] +specs: + - specs/api/slack-link.md + - specs/api/agents.md + - specs/data-model.md + - specs/behaviors/private-storage.md + - specs/behaviors/person-lifecycle.md + - specs/screens/account.md +awaits: + - "CodeForPhilly/grittybot — DM handler that takes a linking code and calls POST /api/agent/slack-links (bot repo, by PR)" +--- + +# Plan: Link a site account to a Slack user + +## Scope + +The verified link the ops bot needs before it can reach admins in Slack or +act on their word. + +**In:** `PrivateProfile.slack` and the `bySlackUserId` index; `POST +/api/account/slack-link/code` (in-memory hashed codes, 10 minutes, single +use, rate limited); `DELETE /api/account/slack-link`; `POST +/api/agent/slack-links` under `slack:link`; the three new agent scopes in the +`agent-grants` schema and contract v2, with the companion rules at mint (the +read and decide endpoints themselves land in later plans); `me.slack`; the +Account screen's Slack row; purge removes the link. + +**Out:** the bot's side (awaited); anything that uses the link. + +## Implements + +- [slack-link.md](../specs/api/slack-link.md) — all of it +- [agents.md](../specs/api/agents.md) — Grants scope table and companion rules +- [data-model.md](../specs/data-model.md) — PrivateProfile `slack`, AgentGrant scopes +- [private-storage.md](../specs/behaviors/private-storage.md) — `slack` on profiles; codes not stored +- [person-lifecycle.md](../specs/behaviors/person-lifecycle.md) — purge takes the link +- [account.md](../specs/screens/account.md) — Slack row + +## Approach + +1. Extend `PrivateProfileSchema`; index on load and on write. +2. Code store: a `Map<sha256(code), {personId, expiresAt}>` plus a + per-person latest-code pointer; swept on read. +3. Agent route under the existing grant middleware; failed-redemption counter + per grant. +4. `AGENT_SCOPES` gains the three scopes; mint enforces the companion rules; + `agent-grants/v2` contract adopted and mirrored. +5. Web: Slack row with code display and polling of `/api/auth/me`. + +## Validation + +- [ ] Tests: a code redeems once for the person who issued it; expired, reused and unknown codes all return the same `404 code_invalid`; issuing a new code voids the old one +- [ ] Tests: a Slack user linked to account A cannot be linked to B (`409 slack_user_linked`); disconnect clears it; wrong `slackTeamId` → `422` +- [ ] Tests: a grant without `slack:link` gets `401`/`403` on the agent route; 11 failed redemptions in an hour are refused +- [ ] No code or Slack id appears in either data store's public side, any commit, or request logs (log redaction test) +- [ ] Minting `projects:applications:decide` without `projects:applications:read` and `slack:link` returns `422` +- [ ] `agent-grants/v2` adopted and mirrored; CI passes +- [ ] Browser: Account → Connect Slack shows a code; redeeming it with a test grant via the API turns the row to "Connected" +- [ ] End to end with the ops bot in the real workspace (awaits the bot PR) +- [ ] `npm run type-check && npm run lint && npm test` clean + +## Risks / unknowns + +- **Restart drops codes.** Acceptable: a member asks for a new code. Single replica keeps the in-memory store coherent. +- **Bot compromise.** A stolen `slack:link` token cannot link anyone without a code only the signed-in person sees. + +## Notes + +## Follow-ups From 4df3ad1bd5b31321bd0d683544be0728074dd3ef Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:16:40 +0000 Subject: [PATCH 11/78] docs(specs): keep deactivated members as placeholders on member lists project-membership.md and projects.md said deactivated people are left out of the members list, while person-lifecycle.md (and the site today) show a deactivated member as the "Deactivated user" placeholder so counts and history stay coherent. Follower and applicant records still go quiet; a deactivated member keeps the placeholder, gets no email and is never an active admin. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- specs/api/projects.md | 2 +- specs/behaviors/project-membership.md | 15 +++++++++------ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/specs/api/projects.md b/specs/api/projects.md index ae1485e1..6e30dc22 100644 --- a/specs/api/projects.md +++ b/specs/api/projects.md @@ -145,7 +145,7 @@ Fetches a single project by slug. } ``` -`counts.openApplications` is `null` unless the caller is a project admin or staff. Follower and applicant counts, and the members list, leave out deactivated people. No endpoint lists followers. +`counts.openApplications` is `null` unless the caller is a project admin or staff. Follower and applicant counts leave out deactivated people; a deactivated member stays in `memberships` as the "Deactivated user" placeholder ([person-lifecycle.md](../behaviors/person-lifecycle.md)). No endpoint lists followers. `permissions` is the *current caller's* permissions on this project — the frontend uses it to decide which actions to render. The server still enforces the same rules on each mutation endpoint. diff --git a/specs/behaviors/project-membership.md b/specs/behaviors/project-membership.md index c616e705..1c835147 100644 --- a/specs/behaviors/project-membership.md +++ b/specs/behaviors/project-membership.md @@ -182,12 +182,15 @@ site closing one for age (`closedBy = site`) write the same fields, without ## Spam and deactivated accounts -- **Hidden everywhere.** Records whose person is deactivated (by themselves or - by a spam vote) are left out of every list, count, admin view, notification - and agent feed, the way deactivated people are left out of public lists - ([person-lifecycle.md](person-lifecycle.md)). They are not changed: a `legit` - vote that reactivates the person brings them back as they were. A held or - open application's 30-day clock keeps running while hidden. +- **Hidden everywhere.** Follower and applicant records whose person is + deactivated (by themselves or by a spam vote) are left out of every list, + count, admin view, notification and agent feed, the way deactivated people + are left out of public lists ([person-lifecycle.md](person-lifecycle.md)). + A deactivated member stays on the member list as the "Deactivated user" + placeholder, gets no email, and never counts as an active admin. No record + is changed: a `legit` vote that reactivates the person brings them back as + they were. A held or open application's 30-day clock keeps running while + hidden. - **Purge** deletes the person's records in every state with the rest of their data ([person-lifecycle.md](person-lifecycle.md#purge-cascading-hard-delete-admin-only)). - **No reward.** An application or a follow puts nothing on a project's public From 77ed6925365fccb6357291e359fcd4aa869d6766 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:16:44 +0000 Subject: [PATCH 12/78] chore(plans): mark membership-admins in-progress Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- plans/membership-admins.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plans/membership-admins.md b/plans/membership-admins.md index e4a09996..ce3b0278 100644 --- a/plans/membership-admins.md +++ b/plans/membership-admins.md @@ -1,5 +1,5 @@ --- -status: planned +status: in-progress depends: [] specs: - specs/behaviors/project-membership.md From dec168bf35cda956458360ddf3bfdc825d2a17a2 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:18:07 +0000 Subject: [PATCH 13/78] feat(shared): one membership record with states, admins and applications ProjectMembership gains state (follower | applicant | member), isAdmin, via, muted, followedAt, an optional joinedAt and the full application table, with the cross-field validators from specs/data-model.md. isMaintainer goes. Project loses maintainerId: who runs a project is its admins. Both contracts move to v3; the application table ships now so the contract moves once across the membership plans. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../project-memberships/v3.json | 165 ++++++++++++++++++ contracts/codeforphilly.org/projects/v3.json | 93 ++++++++++ packages/shared/src/contracts.ts | 4 +- packages/shared/src/schemas/index.ts | 17 +- .../shared/src/schemas/project-membership.ts | 99 +++++++++-- packages/shared/src/schemas/project.ts | 1 - packages/shared/tests/schemas.test.ts | 64 ++++--- 7 files changed, 407 insertions(+), 36 deletions(-) create mode 100644 contracts/codeforphilly.org/project-memberships/v3.json create mode 100644 contracts/codeforphilly.org/projects/v3.json diff --git a/contracts/codeforphilly.org/project-memberships/v3.json b/contracts/codeforphilly.org/project-memberships/v3.json new file mode 100644 index 00000000..656c9d20 --- /dev/null +++ b/contracts/codeforphilly.org/project-memberships/v3.json @@ -0,0 +1,165 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://codeforphilly.org/project-memberships/v3", + "title": "Project membership", + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "projectSlug": { + "type": "string", + "minLength": 1 + }, + "personSlug": { + "type": "string", + "minLength": 1 + }, + "state": { + "type": "string", + "enum": [ + "follower", + "applicant", + "member" + ] + }, + "isAdmin": { + "default": false, + "type": "boolean" + }, + "role": { + "type": "string" + }, + "via": { + "type": "string", + "enum": [ + "created", + "added", + "application", + "legacy" + ] + }, + "muted": { + "default": false, + "type": "boolean" + }, + "followedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + "joinedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + "application": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "open", + "accepted", + "closed" + ] + }, + "roleIds": { + "default": [], + "type": "array", + "items": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "offer": { + "type": "string", + "minLength": 1, + "maxLength": 1500 + }, + "submittedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + "visibleAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + "notifiedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + "remindedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + "decidedById": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "decidedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + "decidedVia": { + "type": "string", + "enum": [ + "site", + "agent" + ] + }, + "agentGrantId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "closedBy": { + "type": "string", + "enum": [ + "admin", + "applicant", + "site" + ] + }, + "closedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + } + }, + "required": [ + "status", + "submittedAt", + "visibleAt" + ] + }, + "createdAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + "updatedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + } + }, + "required": [ + "createdAt", + "followedAt", + "id", + "personSlug", + "projectSlug", + "state", + "updatedAt" + ] +} diff --git a/contracts/codeforphilly.org/projects/v3.json b/contracts/codeforphilly.org/projects/v3.json new file mode 100644 index 00000000..42960f2b --- /dev/null +++ b/contracts/codeforphilly.org/projects/v3.json @@ -0,0 +1,93 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://codeforphilly.org/projects/v3", + "title": "Project", + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "legacyId": { + "type": "integer" + }, + "slug": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9-_]{1,79}$" + }, + "title": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "summary": { + "type": "string", + "maxLength": 280 + }, + "overview": { + "type": "string" + }, + "stage": { + "default": "commenting", + "type": "string", + "enum": [ + "commenting", + "bootstrapping", + "prototyping", + "testing", + "maintaining", + "drifting", + "hibernating" + ] + }, + "createdById": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "usersUrl": { + "type": "string", + "format": "uri", + "pattern": "^https:\\/\\/.*" + }, + "developersUrl": { + "type": "string", + "format": "uri", + "pattern": "^https:\\/\\/.*" + }, + "chatChannel": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9_-]{0,40}$" + }, + "featured": { + "default": false, + "type": "boolean" + }, + "featuredImageKey": { + "type": "string" + }, + "deletedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + "createdAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + "updatedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + } + }, + "required": [ + "createdAt", + "id", + "slug", + "title", + "updatedAt" + ] +} diff --git a/packages/shared/src/contracts.ts b/packages/shared/src/contracts.ts index 47f2508d..77cd6348 100644 --- a/packages/shared/src/contracts.ts +++ b/packages/shared/src/contracts.ts @@ -49,8 +49,8 @@ interface SheetContract { export const SHEET_CONTRACTS = { people: { schema: PersonSchema, version: 1, title: 'Person' }, - projects: { schema: ProjectSchema, version: 2, title: 'Project' }, - 'project-memberships': { schema: ProjectMembershipSchema, version: 2, title: 'Project membership' }, + projects: { schema: ProjectSchema, version: 3, title: 'Project' }, + 'project-memberships': { schema: ProjectMembershipSchema, version: 3, title: 'Project membership' }, 'project-updates': { schema: ProjectUpdateSchema, version: 2, title: 'Project update' }, 'project-buzz': { schema: ProjectBuzzSchema, version: 2, title: 'Project buzz' }, 'blog-posts': { schema: BlogPostSchema, version: 1, title: 'Blog post' }, diff --git a/packages/shared/src/schemas/index.ts b/packages/shared/src/schemas/index.ts index 4a02b137..67373218 100644 --- a/packages/shared/src/schemas/index.ts +++ b/packages/shared/src/schemas/index.ts @@ -4,8 +4,21 @@ export type { Person } from './person.js'; export { ProjectSchema } from './project.js'; export type { Project } from './project.js'; -export { ProjectMembershipSchema } from './project-membership.js'; -export type { ProjectMembership } from './project-membership.js'; +export { + APPLICATION_OFFER_MAX, + APPLICATION_STATUSES, + MEMBERSHIP_STATES, + MEMBERSHIP_VIAS, + ProjectApplicationSchema, + ProjectMembershipSchema, +} from './project-membership.js'; +export type { + ApplicationStatus, + MembershipState, + MembershipVia, + ProjectApplication, + ProjectMembership, +} from './project-membership.js'; export { ProjectUpdateSchema } from './project-update.js'; export type { ProjectUpdate } from './project-update.js'; diff --git a/packages/shared/src/schemas/project-membership.ts b/packages/shared/src/schemas/project-membership.ts index 4a1998d2..ab33b69b 100644 --- a/packages/shared/src/schemas/project-membership.ts +++ b/packages/shared/src/schemas/project-membership.ts @@ -2,20 +2,97 @@ import { z } from 'zod'; import { references } from '../references.js'; +const datetime = () => z.string().datetime({ offset: true }); + +export const MEMBERSHIP_STATES = ['follower', 'applicant', 'member'] as const; +export type MembershipState = (typeof MEMBERSHIP_STATES)[number]; + +export const MEMBERSHIP_VIAS = ['created', 'added', 'application', 'legacy'] as const; +export type MembershipVia = (typeof MEMBERSHIP_VIAS)[number]; + +export const APPLICATION_STATUSES = ['open', 'accepted', 'closed'] as const; +export type ApplicationStatus = (typeof APPLICATION_STATUSES)[number]; + +/** Offer length bound (specs/behaviors/project-membership.md → Applying). */ +export const APPLICATION_OFFER_MAX = 1500; + /** - * A person's membership in a project. Keyed on disk by both handles + * A person's latest application to a project, kept on the membership record + * after it is decided (specs/data-model.md → ProjectMembership). + */ +export const ProjectApplicationSchema = z.object({ + status: z.enum(APPLICATION_STATUSES), + roleIds: z.array(z.string().uuid()).default([]), + offer: z.string().min(1).max(APPLICATION_OFFER_MAX).nullable().optional(), + submittedAt: datetime(), + visibleAt: datetime(), + notifiedAt: datetime().nullable().optional(), + remindedAt: datetime().nullable().optional(), + decidedById: z.string().uuid().nullable().optional(), + decidedAt: datetime().nullable().optional(), + decidedVia: z.enum(['site', 'agent']).nullable().optional(), + agentGrantId: z.string().uuid().nullable().optional(), + closedBy: z.enum(['admin', 'applicant', 'site']).nullable().optional(), + closedAt: datetime().nullable().optional(), +}); + +export type ProjectApplication = z.infer<typeof ProjectApplicationSchema>; + +/** + * A person's one relationship to a project: follower, applicant or member + * (specs/behaviors/project-membership.md). Keyed on disk by both handles * (`project-memberships/${projectSlug}/${personSlug}`), so it references * both by slug (specs/data-model.md → References). + * + * The cross-field validators of specs/data-model.md run here; the published + * contract carries only the field shapes. */ -export const ProjectMembershipSchema = z.object({ - id: z.string().uuid(), - projectSlug: z.string().min(1).meta(references('projects.slug')), - personSlug: z.string().min(1).meta(references('people.slug')), - role: z.string().nullable().optional(), - isMaintainer: z.boolean().default(false), - joinedAt: z.string().datetime({ offset: true }), - createdAt: z.string().datetime({ offset: true }), - updatedAt: z.string().datetime({ offset: true }), -}); +export const ProjectMembershipSchema = z + .object({ + id: z.string().uuid(), + projectSlug: z.string().min(1).meta(references('projects.slug')), + personSlug: z.string().min(1).meta(references('people.slug')), + state: z.enum(MEMBERSHIP_STATES), + isAdmin: z.boolean().default(false), + role: z.string().nullable().optional(), + via: z.enum(MEMBERSHIP_VIAS).nullable().optional(), + muted: z.boolean().default(false), + followedAt: datetime(), + joinedAt: datetime().nullable().optional(), + application: ProjectApplicationSchema.nullable().optional(), + createdAt: datetime(), + updatedAt: datetime(), + }) + .superRefine((m, ctx) => { + const issue = (path: (string | number)[], message: string): void => { + ctx.addIssue({ code: 'custom', path, message }); + }; + const member = m.state === 'member'; + if (m.isAdmin && !member) issue(['isAdmin'], 'isAdmin is true only when state = member'); + if (member) { + if (m.via == null) issue(['via'], 'via is required when state = member'); + if (m.joinedAt == null) issue(['joinedAt'], 'joinedAt is required when state = member'); + } else { + if (m.role != null) issue(['role'], 'role is present only when state = member'); + if (m.via != null) issue(['via'], 'via is present only when state = member'); + if (m.joinedAt != null) issue(['joinedAt'], 'joinedAt is present only when state = member'); + } + const app = m.application ?? null; + if ((m.state === 'applicant') !== (app?.status === 'open')) { + issue(['state'], 'state = applicant iff application.status = open'); + } + if (app) { + if (app.roleIds.length === 0 && app.offer == null) { + issue(['application', 'offer'], 'offer is required when no need is selected'); + } + const closed = app.status === 'closed'; + if (closed !== (app.closedBy != null) || closed !== (app.closedAt != null)) { + issue(['application', 'closedBy'], 'closedBy and closedAt are present iff status = closed'); + } + if ((app.status === 'accepted' || app.closedBy === 'admin') && app.decidedById == null) { + issue(['application', 'decidedById'], 'decidedById is required when accepted or closed by an admin'); + } + } + }); export type ProjectMembership = z.infer<typeof ProjectMembershipSchema>; diff --git a/packages/shared/src/schemas/project.ts b/packages/shared/src/schemas/project.ts index 7f74f6bb..ca63c295 100644 --- a/packages/shared/src/schemas/project.ts +++ b/packages/shared/src/schemas/project.ts @@ -10,7 +10,6 @@ export const ProjectSchema = z.object({ stage: z .enum(['commenting', 'bootstrapping', 'prototyping', 'testing', 'maintaining', 'drifting', 'hibernating']) .default('commenting'), - maintainerId: z.string().uuid().nullable().optional(), /** Who created the project on the site; never changed. Absent on laddr imports. */ createdById: z.string().uuid().nullable().optional(), usersUrl: z.string().url().startsWith('https://').nullable().optional(), diff --git a/packages/shared/tests/schemas.test.ts b/packages/shared/tests/schemas.test.ts index 8204ea7a..821b1e08 100644 --- a/packages/shared/tests/schemas.test.ts +++ b/packages/shared/tests/schemas.test.ts @@ -137,29 +137,53 @@ describe('ProjectSchema', () => { }); describe('ProjectMembershipSchema', () => { - it('accepts a valid membership', () => { - const result = ProjectMembershipSchema.safeParse({ - id: uuid, - projectSlug: 'transit-app', - personSlug: 'janedoe', - isMaintainer: false, - joinedAt: now, - createdAt: now, - updatedAt: now, - }); - expect(result.success).toBe(true); + const base = { + id: uuid, + projectSlug: 'transit-app', + personSlug: 'janedoe', + followedAt: now, + createdAt: now, + updatedAt: now, + }; + const member = { ...base, state: 'member', via: 'added', joinedAt: now }; + + it('accepts a follower, a member and an admin', () => { + expect(ProjectMembershipSchema.safeParse({ ...base, state: 'follower' }).success).toBe(true); + expect(ProjectMembershipSchema.safeParse(member).success).toBe(true); + expect(ProjectMembershipSchema.safeParse({ ...member, isAdmin: true, role: 'Founder' }).success).toBe(true); }); it('rejects missing projectSlug', () => { - const result = ProjectMembershipSchema.safeParse({ - id: uuid, - personSlug: 'janedoe', - isMaintainer: false, - joinedAt: now, - createdAt: now, - updatedAt: now, - }); - expect(result.success).toBe(false); + const { projectSlug: _, ...rest } = member; + expect(ProjectMembershipSchema.safeParse(rest).success).toBe(false); + }); + + it('allows isAdmin, role, via and joinedAt only on members', () => { + for (const extra of [{ isAdmin: true }, { role: 'Designer' }, { via: 'added' }, { joinedAt: now }]) { + expect(ProjectMembershipSchema.safeParse({ ...base, state: 'follower', ...extra }).success).toBe(false); + } + expect(ProjectMembershipSchema.safeParse({ ...member, via: null }).success).toBe(false); + expect(ProjectMembershipSchema.safeParse({ ...member, joinedAt: null }).success).toBe(false); + }); + + it('ties state = applicant to an open application', () => { + const open = { status: 'open', roleIds: [], offer: 'I can help', submittedAt: now, visibleAt: now }; + expect(ProjectMembershipSchema.safeParse({ ...base, state: 'applicant', application: open }).success).toBe(true); + expect(ProjectMembershipSchema.safeParse({ ...base, state: 'applicant' }).success).toBe(false); + expect(ProjectMembershipSchema.safeParse({ ...base, state: 'follower', application: open }).success).toBe(false); + }); + + it('requires an offer when no need is selected, and the close and decision fields', () => { + const app = { status: 'open', roleIds: [], submittedAt: now, visibleAt: now }; + expect(ProjectMembershipSchema.safeParse({ ...base, state: 'applicant', application: app }).success).toBe(false); + const closed = { ...app, offer: 'x', status: 'closed', closedBy: 'admin', closedAt: now }; + expect(ProjectMembershipSchema.safeParse({ ...base, state: 'follower', application: closed }).success).toBe(false); + expect( + ProjectMembershipSchema.safeParse({ ...base, state: 'follower', application: { ...closed, decidedById: uuid } }).success, + ).toBe(true); + expect( + ProjectMembershipSchema.safeParse({ ...base, state: 'follower', application: { ...closed, closedAt: null } }).success, + ).toBe(false); }); }); From 00d71a48fab582634f8b12f6670ab07566fb01ba Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:18:07 +0000 Subject: [PATCH 14/78] chore(api): declare the v3 membership and project contracts Vendored with `gitsheets contracts adopt` from the generated v3 documents; provenance lands when the data repo adopts from the published URL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../project-memberships/v3.toml | 127 ++++++++++++++++++ .../codeforphilly.org/projects/v3.toml | 75 +++++++++++ apps/api/gitsheets/project-memberships.toml | 2 +- apps/api/gitsheets/projects.toml | 2 +- 4 files changed, 204 insertions(+), 2 deletions(-) create mode 100644 apps/api/gitsheets/contracts/codeforphilly.org/project-memberships/v3.toml create mode 100644 apps/api/gitsheets/contracts/codeforphilly.org/projects/v3.toml diff --git a/apps/api/gitsheets/contracts/codeforphilly.org/project-memberships/v3.toml b/apps/api/gitsheets/contracts/codeforphilly.org/project-memberships/v3.toml new file mode 100644 index 00000000..aa24459f --- /dev/null +++ b/apps/api/gitsheets/contracts/codeforphilly.org/project-memberships/v3.toml @@ -0,0 +1,127 @@ +"$id" = "https://codeforphilly.org/project-memberships/v3" +"$schema" = "http://json-schema.org/draft-07/schema#" +required = ["createdAt", "followedAt", "id", "personSlug", "projectSlug", "state", "updatedAt"] +title = "Project membership" +type = "object" + +[properties.application] +required = ["status", "submittedAt", "visibleAt"] +type = "object" + +[properties.application.properties.agentGrantId] +format = "uuid" +pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" +type = "string" + +[properties.application.properties.closedAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.application.properties.closedBy] +enum = ["admin", "applicant", "site"] +type = "string" + +[properties.application.properties.decidedAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.application.properties.decidedById] +format = "uuid" +pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" +type = "string" + +[properties.application.properties.decidedVia] +enum = ["site", "agent"] +type = "string" + +[properties.application.properties.notifiedAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.application.properties.offer] +maxLength = 1500 +minLength = 1 +type = "string" + +[properties.application.properties.remindedAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.application.properties.roleIds] +default = [] +type = "array" + +[properties.application.properties.roleIds.items] +format = "uuid" +pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" +type = "string" + +[properties.application.properties.status] +enum = ["open", "accepted", "closed"] +type = "string" + +[properties.application.properties.submittedAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.application.properties.visibleAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.createdAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.followedAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.id] +format = "uuid" +pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" +type = "string" + +[properties.isAdmin] +default = false +type = "boolean" + +[properties.joinedAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.muted] +default = false +type = "boolean" + +[properties.personSlug] +minLength = 1 +type = "string" + +[properties.projectSlug] +minLength = 1 +type = "string" + +[properties.role] +type = "string" + +[properties.state] +enum = ["follower", "applicant", "member"] +type = "string" + +[properties.updatedAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.via] +enum = ["created", "added", "application", "legacy"] +type = "string" diff --git a/apps/api/gitsheets/contracts/codeforphilly.org/projects/v3.toml b/apps/api/gitsheets/contracts/codeforphilly.org/projects/v3.toml new file mode 100644 index 00000000..e14256af --- /dev/null +++ b/apps/api/gitsheets/contracts/codeforphilly.org/projects/v3.toml @@ -0,0 +1,75 @@ +"$id" = "https://codeforphilly.org/projects/v3" +"$schema" = "http://json-schema.org/draft-07/schema#" +required = ["createdAt", "id", "slug", "title", "updatedAt"] +title = "Project" +type = "object" + +[properties.chatChannel] +pattern = "^[a-z0-9][a-z0-9_-]{0,40}$" +type = "string" + +[properties.createdAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.createdById] +format = "uuid" +pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" +type = "string" + +[properties.deletedAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.developersUrl] +format = "uri" +pattern = '^https:\/\/.*' +type = "string" + +[properties.featured] +default = false +type = "boolean" + +[properties.featuredImageKey] +type = "string" + +[properties.id] +format = "uuid" +pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" +type = "string" + +[properties.legacyId] +type = "integer" + +[properties.overview] +type = "string" + +[properties.slug] +pattern = "^[a-z0-9][a-z0-9-_]{1,79}$" +type = "string" + +[properties.stage] +default = "commenting" +enum = ["commenting", "bootstrapping", "prototyping", "testing", "maintaining", "drifting", "hibernating"] +type = "string" + +[properties.summary] +maxLength = 280 +type = "string" + +[properties.title] +maxLength = 200 +minLength = 1 +type = "string" + +[properties.updatedAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.usersUrl] +format = "uri" +pattern = '^https:\/\/.*' +type = "string" diff --git a/apps/api/gitsheets/project-memberships.toml b/apps/api/gitsheets/project-memberships.toml index bbc3f6b3..bc23925d 100644 --- a/apps/api/gitsheets/project-memberships.toml +++ b/apps/api/gitsheets/project-memberships.toml @@ -1,4 +1,4 @@ [gitsheet] root = 'project-memberships' path = '${{ projectSlug }}/${{ personSlug }}' -implements = ["codeforphilly.org/project-memberships/v2"] +implements = ["codeforphilly.org/project-memberships/v3"] diff --git a/apps/api/gitsheets/projects.toml b/apps/api/gitsheets/projects.toml index e0ee4c2e..b3e45c8a 100644 --- a/apps/api/gitsheets/projects.toml +++ b/apps/api/gitsheets/projects.toml @@ -1,4 +1,4 @@ [gitsheet] root = 'projects' path = '${{ slug }}' -implements = ["codeforphilly.org/projects/v2"] +implements = ["codeforphilly.org/projects/v3"] From e80732c3e7563431910b0ecba6ff97ddcf16b231 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:47:29 +0000 Subject: [PATCH 15/78] feat(api): project admins replace the single maintainer Who runs a project is now its members with isAdmin: the project-admin marker replaces maintainer everywhere, staff keep every admin power, and member means a record in state member. The members API makes the transitions of project-membership.md, one commit each: add (from no record, follower or applicant, resolving an open application as accepted, with a notice email to the added person), promote, demote and update via PATCH, remove, and leave to follower or, with alsoUnfollow, deleted. A change that leaves no active admin answers 409 last_admin unless confirmLastAdmin is sent. Open join and change-maintainer answer 410 for one release. Project create writes the founder as an admin (via created). The project lists members only, admins first, with hasActiveAdmin and the caller's own record as viewer; the list item carries admins, the admin filter keeps maintainer as an alias, and memberSlug, memberOfCount and person memberships count members only, with adminOfCount beside them. An account merge keeps whichever record is further along. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/src/auth/require.ts | 25 +- apps/api/src/lib/errors.ts | 22 +- apps/api/src/lib/response.ts | 10 +- apps/api/src/notify/email-notifier.ts | 11 + apps/api/src/notify/index.ts | 15 + apps/api/src/notify/membership-templates.ts | 81 +++++ apps/api/src/plugins/services.ts | 2 +- apps/api/src/routes/projects-members.ts | 173 +++++----- apps/api/src/routes/projects.ts | 50 +-- apps/api/src/services/account-claim.ts | 34 +- apps/api/src/services/help-wanted.write.ts | 25 +- apps/api/src/services/memberships.ts | 147 +++++++++ apps/api/src/services/permissions.ts | 61 ++-- apps/api/src/services/person.ts | 14 +- .../src/services/project-membership.write.ts | 302 +++++++++++------- apps/api/src/services/project.ts | 63 ++-- apps/api/src/services/project.write.ts | 80 +---- apps/api/src/services/serializers/person.ts | 11 +- apps/api/src/services/serializers/project.ts | 93 +++--- apps/api/src/store/memory/state.ts | 9 + 20 files changed, 785 insertions(+), 443 deletions(-) create mode 100644 apps/api/src/notify/membership-templates.ts create mode 100644 apps/api/src/services/memberships.ts diff --git a/apps/api/src/auth/require.ts b/apps/api/src/auth/require.ts index e78b293c..06940bb5 100644 --- a/apps/api/src/auth/require.ts +++ b/apps/api/src/auth/require.ts @@ -6,13 +6,13 @@ * boundary for defense-in-depth: routes call requireAuth(request, markers) * first; services then call requireAuthMarker(session, marker, ctx) again * with full entity context (project, owned-resource, self) to decide - * `self`, `member`, `maintainer`, `poster`/`author` cases. + * `self`, `member`, `project-admin`, `poster`/`author` cases. */ import { AGENT_SCOPES, type Project, type ProjectMembership } from '@cfp/shared/schemas'; import { ForbiddenError, UnauthenticatedError } from '../lib/errors.js'; import type { SessionContext } from './middleware.js'; -/** A marker expression: `user`, `maintainer | staff`, `self | staff`, etc. */ +/** A marker expression: `user`, `project-admin | staff`, `self | staff`, etc. */ export type MarkerExpression = string; export interface AuthContext { @@ -21,7 +21,7 @@ export interface AuthContext { /** When `self` is in the expression — the resource owner's personId or slug. */ readonly selfId?: string; readonly selfSlug?: string; - /** When `maintainer` / `member` are in the expression — the project + its memberships. */ + /** When `project-admin` / `member` are in the expression — the project + its memberships. */ readonly project?: Project; readonly memberships?: readonly ProjectMembership[]; /** When `poster`/`author` is in the expression — the resource owner's personId. */ @@ -47,18 +47,23 @@ function isSelf(session: SessionContext, ctx: AuthContext): boolean { return false; } -function isMaintainer(session: SessionContext, ctx: AuthContext): boolean { +/** `project-admin`: a `member` record on the project with `isAdmin`. */ +function isProjectAdmin(session: SessionContext, ctx: AuthContext): boolean { if (!session.person || !ctx.project) return false; - if (ctx.project.maintainerId === session.person.id) return true; return (ctx.memberships ?? []).some( - (m) => m.personSlug === session.person!.slug && m.isMaintainer, + (m) => + m.personSlug === session.person!.slug && + m.projectSlug === ctx.project!.slug && + m.state === 'member' && + m.isAdmin, ); } +/** `member`: a record on the project in state `member` (not a follower or applicant). */ function isMember(session: SessionContext, ctx: AuthContext): boolean { if (!session.person || !ctx.project) return false; return (ctx.memberships ?? []).some( - (m) => m.personSlug === session.person!.slug && m.projectSlug === ctx.project!.slug, + (m) => m.personSlug === session.person!.slug && m.projectSlug === ctx.project!.slug && m.state === 'member', ); } @@ -74,7 +79,7 @@ const MARKER_TOKENS = new Set([ 'staff', 'administrator', 'member', - 'maintainer', + 'project-admin', 'poster', 'author', ]); @@ -88,7 +93,7 @@ function isAgentMarker(token: string): boolean { } /** - * Check a marker expression like `maintainer | staff` against the session. + * Check a marker expression like `project-admin | staff` against the session. * * Throws `UnauthenticatedError` if any non-`public` marker is required and the * caller is anonymous; throws `ForbiddenError` if the caller is authenticated @@ -134,7 +139,7 @@ export function requireAuth(expression: MarkerExpression, ctx: AuthContext): Ses if (token === 'staff' && isStaff(session)) return session; if (token === 'administrator' && isAdministrator(session)) return session; if (token === 'self' && isSelf(session, ctx)) return session; - if (token === 'maintainer' && isMaintainer(session, ctx)) return session; + if (token === 'project-admin' && isProjectAdmin(session, ctx)) return session; if (token === 'member' && isMember(session, ctx)) return session; if ((token === 'poster' || token === 'author') && isOwner(session, ctx)) return session; } diff --git a/apps/api/src/lib/errors.ts b/apps/api/src/lib/errors.ts index 5436492e..aeb15ef1 100644 --- a/apps/api/src/lib/errors.ts +++ b/apps/api/src/lib/errors.ts @@ -77,10 +77,23 @@ export class ApiNotFoundError extends Error { /** Thrown on unique-constraint / slug conflicts (409). */ export class ConflictError extends Error { readonly code: string; - constructor(message: string, code = 'conflict') { + /** `error.details`, when a spec names extra facts (e.g. `reapplyAfter`). */ + readonly details?: Record<string, unknown>; + constructor(message: string, code = 'conflict', details?: Record<string, unknown>) { super(message); this.name = 'ConflictError'; this.code = code; + this.details = details; + } +} + +/** Thrown by a retired endpoint during its one-release grace period (410). */ +export class GoneError extends Error { + readonly code: string; + constructor(message: string, code = 'gone') { + super(message); + this.name = 'GoneError'; + this.code = code; } } @@ -136,7 +149,12 @@ export function mapError( } if (err instanceof ConflictError) { - void reply.code(409).send(errorResponse(err.code, err.message, traceId)); + void reply.code(409).send(errorResponse(err.code, err.message, traceId, undefined, err.details)); + return; + } + + if (err instanceof GoneError) { + void reply.code(410).send(errorResponse(err.code, err.message, traceId)); return; } diff --git a/apps/api/src/lib/response.ts b/apps/api/src/lib/response.ts index 745f5b06..fe0afbca 100644 --- a/apps/api/src/lib/response.ts +++ b/apps/api/src/lib/response.ts @@ -34,6 +34,7 @@ export interface ErrorDetail { readonly message: string; readonly traceId?: string; readonly fields?: Record<string, string>; + readonly details?: Record<string, unknown>; } export interface ErrorResponse { @@ -71,8 +72,15 @@ export function errorResponse( message: string, traceId?: string, fields?: Record<string, string>, + details?: Record<string, unknown>, ): ErrorResponse { - const error: ErrorDetail = { code, message, ...(traceId ? { traceId } : {}), ...(fields ? { fields } : {}) }; + const error: ErrorDetail = { + code, + message, + ...(traceId ? { traceId } : {}), + ...(fields ? { fields } : {}), + ...(details ? { details } : {}), + }; return { success: false, error, diff --git a/apps/api/src/notify/email-notifier.ts b/apps/api/src/notify/email-notifier.ts index 05198d4a..16c419a1 100644 --- a/apps/api/src/notify/email-notifier.ts +++ b/apps/api/src/notify/email-notifier.ts @@ -21,6 +21,7 @@ import type { EventUpdatedNotification, HelpWantedFillNotification, HelpWantedInterestNotification, + MemberAddedNotification, Notifier, PasswordResetNotification, WelcomeNotification, @@ -37,6 +38,7 @@ import { renderPasswordResetEmail, renderWelcomeEmail, } from './templates.js'; +import { renderMemberAddedEmail } from './membership-templates.js'; import type { EmailAttachment, EmailTransport } from './transport.js'; /** Common shape of every template renderer's output. */ @@ -87,6 +89,15 @@ export class EmailNotifier implements Notifier { ); } + async notifyMemberAdded(n: MemberAddedNotification): Promise<{ delivered: boolean }> { + const ctx = { kind: 'membership.added', project: n.projectSlug }; + if (!n.email) { + this.#log.warn(ctx, 'member added: no email address; skipped'); + return { delivered: false }; + } + return this.#deliver('member added', ctx, n.email, renderMemberAddedEmail(n, this.#siteHost)); + } + async notifyWelcomeOnSignup(n: WelcomeNotification): Promise<{ delivered: boolean }> { const ctx = { kind: 'auth.welcome', slug: n.slug }; if (!n.email) { diff --git a/apps/api/src/notify/index.ts b/apps/api/src/notify/index.ts index 2b189042..bdeee996 100644 --- a/apps/api/src/notify/index.ts +++ b/apps/api/src/notify/index.ts @@ -108,7 +108,17 @@ export interface EventReminderNotification { readonly planLine: string | null; } +/** An admin added someone to a project (project-membership.md → Notifications). */ +export interface MemberAddedNotification { + readonly email: string; + readonly fullName: string; + readonly projectTitle: string; + readonly projectSlug: string; + readonly addedByName: string; +} + export interface Notifier { + notifyMemberAdded(n: MemberAddedNotification): Promise<{ delivered: boolean }>; notifyHelpWantedInterest(n: HelpWantedInterestNotification): Promise<{ delivered: boolean }>; notifyHelpWantedFilled(n: HelpWantedFillNotification): Promise<{ delivered: boolean }>; notifyWelcomeOnSignup(n: WelcomeNotification): Promise<{ delivered: boolean }>; @@ -131,6 +141,11 @@ export class LoggingNotifier implements Notifier { this.#log = log; } + async notifyMemberAdded(n: MemberAddedNotification): Promise<{ delivered: boolean }> { + this.#log.info({ kind: 'membership.added', project: n.projectSlug }, 'member added notification'); + return { delivered: true }; + } + async notifyHelpWantedInterest(n: HelpWantedInterestNotification): Promise<{ delivered: boolean }> { this.#log.info({ kind: 'help-wanted.interest', ...n }, 'help-wanted interest notification'); return { delivered: true }; diff --git a/apps/api/src/notify/membership-templates.ts b/apps/api/src/notify/membership-templates.ts new file mode 100644 index 00000000..d09b9e87 --- /dev/null +++ b/apps/api/src/notify/membership-templates.ts @@ -0,0 +1,81 @@ +/** + * Email templates for project membership notices + * (specs/behaviors/project-membership.md → Notifications). + * + * Every body is built from plain-text blocks: user text (an offer, a note) + * is escaped and shown with its line breaks, never rendered as markdown and + * never turned into a link by us. + */ +import type { MemberAddedNotification } from './index.js'; + +export interface MembershipEmail { + readonly subject: string; + readonly text: string; + readonly html: string; +} + +/** A block of an email: a paragraph, a quoted piece of someone's text, or a link. */ +export type Block = + | { readonly p: string } + | { readonly quote: string } + | { readonly link: string; readonly label: string }; + +function escapeHtml(s: string): string { + return s + .replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +export function projectUrl(siteHost: string, projectSlug: string): string { + return `https://${siteHost}/projects/${encodeURIComponent(projectSlug)}`; +} + +/** Render blocks to the text and HTML bodies, with a footer saying why it was sent. */ +export function renderBlocks(subject: string, blocks: readonly Block[], footer: string): MembershipEmail { + const text = [ + ...blocks.map((b) => + 'p' in b ? b.p : 'quote' in b ? b.quote.split('\n').map((l) => `> ${l}`).join('\n') : `${b.label}: ${b.link}`, + ), + `— Code for Philly`, + '', + footer, + ].join('\n\n'); + + const body = blocks + .map((b) => + 'p' in b + ? ` <p>${escapeHtml(b.p)}</p>` + : 'quote' in b + ? ` <blockquote style="white-space: pre-wrap; border-left: 3px solid #ddd; margin: 0; padding-left: 0.75rem; color: #333;">${escapeHtml(b.quote)}</blockquote>` + : ` <p><a href="${escapeHtml(b.link)}">${escapeHtml(b.label)}</a></p>`, + ) + .join('\n'); + + const html = `<!DOCTYPE html> +<html lang="en"> +<body style="font-family: system-ui, sans-serif; max-width: 32rem; margin: 0 auto; padding: 1rem; color: #111;"> +${body} + <p>— Code for Philly</p> + <hr style="border: none; border-top: 1px solid #eee; margin: 2rem 0;"> + <p style="color: #666; font-size: 0.875rem;">${escapeHtml(footer)}</p> +</body> +</html>`; + + return { subject, text, html }; +} + +export function renderMemberAddedEmail(n: MemberAddedNotification, siteHost: string): MembershipEmail { + const url = projectUrl(siteHost, n.projectSlug); + return renderBlocks( + `You've been added to ${n.projectTitle}`, + [ + { p: `Hi ${n.fullName}, ${n.addedByName} added you as a member of ${n.projectTitle} on Code for Philly.` }, + { p: `You're listed on the project page now. If this isn't for you, you can leave the project from that page at any time.` }, + { link: url, label: 'Open the project' }, + ], + `You're receiving this because a project admin added you to ${n.projectTitle}.`, + ); +} diff --git a/apps/api/src/plugins/services.ts b/apps/api/src/plugins/services.ts index 92d8b316..14b01016 100644 --- a/apps/api/src/plugins/services.ts +++ b/apps/api/src/plugins/services.ts @@ -108,7 +108,7 @@ async function servicesPlugin(fastify: FastifyInstance): Promise<void> { const githubAccount = new GitHubAccountService(state); fastify.decorate('services', { - projects: new ProjectService(state, fts), + projects: new ProjectService(state, fts, fastify.store.private), people: new PersonService(state, fts, fastify.store.private), tags: new TagService(state), projectUpdates: new ProjectUpdateService(state), diff --git a/apps/api/src/routes/projects-members.ts b/apps/api/src/routes/projects-members.ts index 5cf7890c..364a24d5 100644 --- a/apps/api/src/routes/projects-members.ts +++ b/apps/api/src/routes/projects-members.ts @@ -1,60 +1,57 @@ /** - * Project membership routes (writes only): + * Project membership routes (specs/api/projects-members.md): * POST /api/projects/:slug/members * PATCH /api/projects/:slug/members/:personSlug * DELETE /api/projects/:slug/members/:personSlug - * POST /api/projects/:slug/members/join * POST /api/projects/:slug/members/leave + * POST /api/projects/:slug/members/join (410: removed) */ -import type { FastifyInstance } from 'fastify'; +import type { FastifyInstance, FastifyRequest } from 'fastify'; +import type { ProjectMembership } from '@cfp/shared/schemas'; import { ok } from '../lib/response.js'; +import { GoneError } from '../lib/errors.js'; import { buildTransactionOptions } from '../store/commit-meta.js'; import { personBySlug } from '../store/memory/state.js'; +import { serializeProjectMembership } from '../services/serializers/project.js'; +import { hasDeliverableEmail, isProjectAdmin } from '../services/memberships.js'; +import type { MembershipPatch } from '../services/project-membership.write.js'; -interface MembershipResponseShape { - readonly id: string; - readonly projectSlug: string; - readonly person: { slug: string; fullName: string; avatarUrl: string | null }; - readonly role: string | null; - readonly isMaintainer: boolean; - readonly joinedAt: string; -} +const SLUG_PARAMS = { + type: 'object', + properties: { slug: { type: 'string' }, personSlug: { type: 'string' } }, + required: ['slug', 'personSlug'], +} as const; -function serializeMembership( - m: { id: string; role?: string | null; isMaintainer: boolean; joinedAt: string }, - projectSlug: string, - person: { slug: string; fullName: string; avatarKey?: string | null }, -): MembershipResponseShape { - return { - id: m.id, - projectSlug, - person: { - slug: person.slug, - fullName: person.fullName, - avatarUrl: person.avatarKey ? `/api/attachments/${person.avatarKey}` : null, - }, - role: m.role ?? null, - isMaintainer: m.isMaintainer, - joinedAt: m.joinedAt, +export async function projectMembershipRoutes(fastify: FastifyInstance): Promise<void> { + /** `via` is shown only to project admins and staff. */ + const canSeeVia = (request: FastifyRequest, projectSlug: string): boolean => { + const level = request.session.accountLevel; + if (level === 'staff' || level === 'administrator') return true; + const slug = request.session.person?.slug; + return slug !== undefined && isProjectAdmin(fastify.inMemoryState, projectSlug, slug); }; -} + const respond = (m: ProjectMembership, showVia: boolean) => + ok(serializeProjectMembership(m, personBySlug(fastify.inMemoryState, m.personSlug), { showVia })); -export async function projectMembershipRoutes(fastify: FastifyInstance): Promise<void> { - // POST /api/projects/:slug/members + // POST /api/projects/:slug/members — add fastify.post('/api/projects/:slug/members', { schema: { tags: ['project-memberships'], - summary: 'Add a member', + summary: 'Add a person as a member, at once', params: { type: 'object', properties: { slug: { type: 'string' } }, required: ['slug'] }, body: { type: 'object', - properties: { personSlug: { type: 'string' }, role: { type: ['string', 'null'] } }, + properties: { + personSlug: { type: 'string' }, + role: { type: ['string', 'null'] }, + isAdmin: { type: 'boolean' }, + }, required: ['personSlug'], }, }, }, async (request, reply) => { const { slug } = request.params as { slug: string }; - const body = request.body as { personSlug: string; role?: string | null }; + const body = request.body as { personSlug: string; role?: string | null; isAdmin?: boolean }; const result = await fastify.store.transact( buildTransactionOptions({ request, @@ -63,37 +60,55 @@ export async function projectMembershipRoutes(fastify: FastifyInstance): Promise subjectSlug: `${slug}/${body.personSlug}`, responseCode: 201, }), - async (tx) => - fastify.services.projectMembershipsWrite.add(tx, slug, body, request.session), + async (tx) => fastify.services.projectMembershipsWrite.add(tx, slug, body, request.session), ); result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); - const person = personBySlug(fastify.inMemoryState, result.value.membership.personSlug)!; + + // The added person hears about it: fire-and-forget, address read at send time. + const { person, project } = result.value; + const addedByName = request.session.person?.fullName ?? 'A project admin'; + void (async () => { + const profile = await fastify.store.private.getProfile(person.id); + if (!profile || !hasDeliverableEmail(profile)) { + fastify.log.info({ project: project.slug, person: person.slug }, 'member added: no deliverable email; skipped'); + return; + } + await fastify.notifier.notifyMemberAdded({ + email: profile.email, + fullName: person.fullName, + projectTitle: project.title, + projectSlug: project.slug, + addedByName, + }); + })().catch((err: unknown) => fastify.log.error({ err }, 'member added notification failed')); + reply.code(201); - return ok(serializeMembership(result.value.membership, slug, person)); + return respond(result.value.membership, true); }); - // PATCH /api/projects/:slug/members/:personSlug + // PATCH /api/projects/:slug/members/:personSlug — promote / demote / update fastify.patch('/api/projects/:slug/members/:personSlug', { schema: { tags: ['project-memberships'], - summary: 'Update a membership role', - params: { - type: 'object', - properties: { slug: { type: 'string' }, personSlug: { type: 'string' } }, - required: ['slug', 'personSlug'], - }, + summary: 'Update a member: role, admin flag', + params: SLUG_PARAMS, body: { type: 'object', - properties: { role: { type: ['string', 'null'] } }, + properties: { + role: { type: ['string', 'null'] }, + isAdmin: { type: 'boolean' }, + confirmLastAdmin: { type: 'boolean' }, + }, }, }, }, async (request) => { const { slug, personSlug } = request.params as { slug: string; personSlug: string }; - const body = (request.body ?? {}) as { role?: string | null }; + const body = (request.body ?? {}) as MembershipPatch; + const transition = fastify.services.projectMembershipsWrite.patchTransition(slug, personSlug, body); const result = await fastify.store.transact( buildTransactionOptions({ request, - action: 'project-membership.update', + action: `project-membership.${transition}`, subjectType: 'project-membership', subjectSlug: `${slug}/${personSlug}`, responseCode: 200, @@ -102,23 +117,23 @@ export async function projectMembershipRoutes(fastify: FastifyInstance): Promise fastify.services.projectMembershipsWrite.update(tx, slug, personSlug, body, request.session), ); result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); - const person = personBySlug(fastify.inMemoryState, result.value.membership.personSlug)!; - return ok(serializeMembership(result.value.membership, slug, person)); + return respond(result.value.membership, canSeeVia(request, slug)); }); - // DELETE /api/projects/:slug/members/:personSlug + // DELETE /api/projects/:slug/members/:personSlug — remove fastify.delete('/api/projects/:slug/members/:personSlug', { schema: { tags: ['project-memberships'], - summary: 'Remove a member', - params: { + summary: 'Remove a member (deletes the record)', + params: SLUG_PARAMS, + querystring: { type: 'object', - properties: { slug: { type: 'string' }, personSlug: { type: 'string' } }, - required: ['slug', 'personSlug'], + properties: { confirmLastAdmin: { type: 'boolean' } }, }, }, }, async (request, reply) => { const { slug, personSlug } = request.params as { slug: string; personSlug: string }; + const { confirmLastAdmin } = (request.query ?? {}) as { confirmLastAdmin?: boolean }; const result = await fastify.store.transact( buildTransactionOptions({ request, @@ -128,59 +143,59 @@ export async function projectMembershipRoutes(fastify: FastifyInstance): Promise responseCode: 204, }), async (tx) => - fastify.services.projectMembershipsWrite.remove(tx, slug, personSlug, request.session), + fastify.services.projectMembershipsWrite.remove(tx, slug, personSlug, { confirmLastAdmin }, request.session), ); result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); return reply.code(204).send(); }); - // POST /api/projects/:slug/members/join + // POST /api/projects/:slug/members/join — removed: membership comes from an + // accepted application or an admin's add. Answers 410 for one release; + // remove this handler in the release after next, so the path 404s. fastify.post('/api/projects/:slug/members/join', { schema: { tags: ['project-memberships'], - summary: 'Join the project as the current user', + summary: 'Removed: apply to join instead', params: { type: 'object', properties: { slug: { type: 'string' } }, required: ['slug'] }, }, - }, async (request, reply) => { - const { slug } = request.params as { slug: string }; - const result = await fastify.store.transact( - buildTransactionOptions({ - request, - action: 'project-membership.join', - subjectType: 'project-membership', - subjectSlug: slug, - responseCode: 201, - }), - async (tx) => - fastify.services.projectMembershipsWrite.join(tx, slug, request.session), + }, async () => { + throw new GoneError( + 'Open join is gone: apply to the project, or ask one of its admins to add you', + 'join_removed', ); - result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); - const person = personBySlug(fastify.inMemoryState, result.value.membership.personSlug)!; - reply.code(201); - return ok(serializeMembership(result.value.membership, slug, person)); }); - // POST /api/projects/:slug/members/leave + // POST /api/projects/:slug/members/leave — member → follower, or deleted fastify.post('/api/projects/:slug/members/leave', { schema: { tags: ['project-memberships'], summary: 'Leave the project', params: { type: 'object', properties: { slug: { type: 'string' } }, required: ['slug'] }, + body: { + type: ['object', 'null'], + properties: { + alsoUnfollow: { type: 'boolean' }, + confirmLastAdmin: { type: 'boolean' }, + }, + }, }, }, async (request, reply) => { const { slug } = request.params as { slug: string }; + const body = (request.body ?? {}) as { alsoUnfollow?: boolean; confirmLastAdmin?: boolean }; + const code = body.alsoUnfollow === true ? 204 : 200; const result = await fastify.store.transact( buildTransactionOptions({ request, action: 'project-membership.leave', subjectType: 'project-membership', - subjectSlug: slug, - responseCode: 204, + subjectSlug: `${slug}/${request.session.person?.slug ?? 'anon'}`, + responseCode: code, }), - async (tx) => - fastify.services.projectMembershipsWrite.leave(tx, slug, request.session), + async (tx) => fastify.services.projectMembershipsWrite.leave(tx, slug, body, request.session), ); result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); - return reply.code(204).send(); + const m = result.value.membership; + if (!m) return reply.code(204).send(); + return ok({ state: m.state, muted: m.muted === true, followedAt: m.followedAt }); }); } diff --git a/apps/api/src/routes/projects.ts b/apps/api/src/routes/projects.ts index 4bce90ad..3d9659b3 100644 --- a/apps/api/src/routes/projects.ts +++ b/apps/api/src/routes/projects.ts @@ -6,11 +6,11 @@ * PATCH /api/projects/:slug * DELETE /api/projects/:slug * POST /api/projects/:slug/restore - * POST /api/projects/:slug/change-maintainer + * POST /api/projects/:slug/change-maintainer (410: removed) */ import type { FastifyInstance, FastifyRequest } from 'fastify'; import { ok, paginated } from '../lib/response.js'; -import { ApiNotFoundError, ApiValidationError } from '../lib/errors.js'; +import { ApiNotFoundError, ApiValidationError, GoneError } from '../lib/errors.js'; import { getCallerSession } from '../services/permissions.js'; import { buildTransactionOptions } from '../store/commit-meta.js'; import type { CreateProjectInput, UpdateProjectInput } from '../services/project.write.js'; @@ -30,6 +30,7 @@ export async function projectRoutes(fastify: FastifyInstance): Promise<void> { stage: { type: 'string' }, stageIn: { type: 'string' }, tag: { type: 'array', items: { type: 'string' } }, + admin: { type: 'string' }, maintainer: { type: 'string' }, memberSlug: { type: 'string' }, helpWanted: { type: 'boolean' }, @@ -51,7 +52,8 @@ export async function projectRoutes(fastify: FastifyInstance): Promise<void> { stage: q['stage'] as string | undefined, stageIn: q['stageIn'] ? String(q['stageIn']).split(',') : undefined, tag: q['tag'] as string[] | undefined, - maintainer: q['maintainer'] as string | undefined, + // `maintainer` stays as an alias so old links keep working (specs/api/projects.md). + admin: (q['admin'] ?? q['maintainer']) as string | undefined, memberSlug: q['memberSlug'] as string | undefined, helpWanted: q['helpWanted'] as boolean | undefined, featured: q['featured'] as boolean | undefined, @@ -121,7 +123,7 @@ export async function projectRoutes(fastify: FastifyInstance): Promise<void> { const { slug } = request.params as { slug: string }; const caller = getCallerSession(request); - const project = fastify.services.projects.get(slug, caller); + const project = await fastify.services.projects.get(slug, caller); if (!project) { throw new ApiNotFoundError(`Project '${slug}' not found`); } @@ -150,7 +152,7 @@ export async function projectRoutes(fastify: FastifyInstance): Promise<void> { ); result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); reply.code(201); - return ok(fastify.services.projects.get(result.value.project.slug, getCallerSession(request))); + return ok(await fastify.services.projects.get(result.value.project.slug, getCallerSession(request))); }); // PATCH /api/projects/:slug @@ -175,7 +177,7 @@ export async function projectRoutes(fastify: FastifyInstance): Promise<void> { async (tx) => fastify.services.projectsWrite.update(tx, slug, input, request.session), ); result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); - return ok(fastify.services.projects.get(result.value.project.slug, getCallerSession(request))); + return ok(await fastify.services.projects.get(result.value.project.slug, getCallerSession(request))); }); // DELETE /api/projects/:slug @@ -221,41 +223,23 @@ export async function projectRoutes(fastify: FastifyInstance): Promise<void> { async (tx) => fastify.services.projectsWrite.restore(tx, slug, request.session), ); result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); - return ok(fastify.services.projects.get(result.value.project.slug, getCallerSession(request))); + return ok(await fastify.services.projects.get(result.value.project.slug, getCallerSession(request))); }); - // POST /api/projects/:slug/change-maintainer + // POST /api/projects/:slug/change-maintainer — removed: a project has any + // number of admins, managed through PATCH …/members/:personSlug + // (specs/api/projects.md → Admins). Answers 410 for one release; remove + // this handler in the release after next, so the path 404s. fastify.post('/api/projects/:slug/change-maintainer', { schema: { tags: ['projects'], - summary: 'Transfer maintainer to another member', + summary: 'Removed: make admins through PATCH …/members/:personSlug', params: { type: 'object', properties: { slug: { type: 'string' } }, required: ['slug'] }, - body: { - type: 'object', - properties: { personSlug: { type: 'string' } }, - required: ['personSlug'], - }, }, - }, async (request) => { - const { slug } = request.params as { slug: string }; - const { personSlug } = request.body as { personSlug: string }; - if (!personSlug) { - throw new ApiValidationError('personSlug required', { personSlug: 'required' }); - } - const result = await fastify.store.transact( - buildTransactionOptions({ - request, - action: 'project.change-maintainer', - subjectType: 'project', - subjectSlug: slug, - responseCode: 200, - extraTrailers: { 'New-Maintainer-Slug': personSlug }, - }), - async (tx) => - fastify.services.projectsWrite.changeMaintainer(tx, slug, personSlug, request.session), + }, async () => { + throw new GoneError( + 'A project has no single maintainer any more; make admins with PATCH /api/projects/:slug/members/:personSlug', ); - result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); - return ok(fastify.services.projects.get(result.value.project.slug, getCallerSession(request))); }); } diff --git a/apps/api/src/services/account-claim.ts b/apps/api/src/services/account-claim.ts index bb9a8f7d..971d5372 100644 --- a/apps/api/src/services/account-claim.ts +++ b/apps/api/src/services/account-claim.ts @@ -45,10 +45,17 @@ import type { import { verifyLegacyPassword } from '../auth/legacy-password.js'; import { isAgentAccount } from '../auth/agent-grant.js'; import { GitHubAccountService } from './github-account.js'; +import { membershipOf, membershipsOfPerson } from './memberships.js'; import type { ResolvedGitHubIdentity } from '../auth/github-client.js'; const SLUG_HISTORY_TTL_DAYS = 90; +/** How far along a record is: admin > member > applicant > follower. */ +function membershipRank(m: ProjectMembership): number { + if (m.state === 'member') return m.isAdmin ? 3 : 2; + return m.state === 'applicant' ? 1 : 0; +} + function nowIso(): string { return new Date().toISOString(); } @@ -172,7 +179,7 @@ export class AccountClaimService { personId: person.id, slug: person.slug, fullName: person.fullName, - memberOfCount: this.#state.membershipsByPerson.get(person.slug)?.size ?? 0, + memberOfCount: membershipsOfPerson(this.#state, person.slug).filter((m) => m.state === 'member').length, lastActiveAt: person.updatedAt, matchedVia, matchedEmail, @@ -365,7 +372,7 @@ export class AccountClaimService { personId: person.id, slug: person.slug, fullName: person.fullName, - memberOfCount: this.#state.membershipsByPerson.get(person.slug)?.size ?? 0, + memberOfCount: membershipsOfPerson(this.#state, person.slug).filter((m) => m.state === 'member').length, lastActiveAt: person.updatedAt, matchedVia, matchedEmail, @@ -584,21 +591,22 @@ export class AccountClaimService { const reMemberships: ProjectMembership[] = []; const removedMemberships: ProjectMembership[] = []; const requesterMembershipIds = this.#state.membershipsByPerson.get(requester.slug) ?? new Set(); - for (const mId of requesterMembershipIds) { + for (const mId of [...requesterMembershipIds]) { const m = this.#state.projectMemberships.get(mId); if (!m) continue; - // If the claimed Person already has a membership in this project, - // drop the requester's duplicate rather than creating two. - const claimedMemberships = this.#state.membershipsByPerson.get(claimed.slug) ?? new Set(); - const claimedHasIt = [...claimedMemberships].some((id) => { - const cm = this.#state.projectMemberships.get(id); - return cm?.projectSlug === m.projectSlug; - }); - if (claimedHasIt) { + // Both hold a record on this project: keep the one further along + // (member over applicant over follower; admin over not) and delete the + // other (specs/behaviors/account-migration.md). + const theirs = membershipOf(this.#state, m.projectSlug, claimed.slug); + if (theirs && membershipRank(theirs) >= membershipRank(m)) { await tx.public['project-memberships'].delete(m); removedMemberships.push(m); continue; } + if (theirs) { + await tx.public['project-memberships'].delete(theirs); + removedMemberships.push(theirs); + } const updated: ProjectMembership = ProjectMembershipSchema.parse({ ...m, personSlug: claimed.slug }); // Path template uses {projectSlug}/{personSlug}, so re-pointing the // person moves the file: delete the old key, then upsert the new one. @@ -787,8 +795,10 @@ export class MergeApply { stateApply.upsertSlugHistory(i.slugHistory); // Re-pointed records keep their ids, so upserting them replaces the old // index entries (index* unindexes the previous version of an id). - for (const m of i.reMemberships) stateApply.upsertMembership(m); + // Removals first: a dropped record and the re-pointed one share a + // (project, person) pair, and the admin index is keyed by that pair. for (const m of i.removedMemberships) stateApply.removeMembership(m); + for (const m of i.reMemberships) stateApply.upsertMembership(m); for (const u of i.reUpdates) stateApply.upsertProjectUpdate(u); for (const b of i.reBuzz) stateApply.upsertProjectBuzz(b); for (const r of i.reRoles) stateApply.upsertHelpWantedRole(r); diff --git a/apps/api/src/services/help-wanted.write.ts b/apps/api/src/services/help-wanted.write.ts index d16131be..f6d7885d 100644 --- a/apps/api/src/services/help-wanted.write.ts +++ b/apps/api/src/services/help-wanted.write.ts @@ -1,11 +1,11 @@ /** * Help-wanted role writes: - * - POST /api/projects/:slug/help-wanted (maintainer | staff) - * - PATCH /api/projects/:slug/help-wanted/:roleId (poster | maintainer | staff) + * - POST /api/projects/:slug/help-wanted (project-admin | staff) + * - PATCH /api/projects/:slug/help-wanted/:roleId (poster | project-admin | staff) * - POST /api/projects/:slug/help-wanted/:roleId/express-interest (user, rate-cap) - * - POST /api/projects/:slug/help-wanted/:roleId/fill (maintainer | staff) - * - POST /api/projects/:slug/help-wanted/:roleId/close (maintainer | staff) - * - POST /api/projects/:slug/help-wanted/:roleId/reopen (maintainer | staff) + * - POST /api/projects/:slug/help-wanted/:roleId/fill (project-admin | staff) + * - POST /api/projects/:slug/help-wanted/:roleId/close (project-admin | staff) + * - POST /api/projects/:slug/help-wanted/:roleId/reopen (project-admin | staff) * * Side effects per specs/behaviors/help-wanted-roles.md: * - fill with attribution → adds the person as a project member if not yet @@ -58,7 +58,7 @@ export class HelpWantedWriteService { session: SessionContext, ): Promise<{ role: HelpWantedRole; stateApply: StateApply }> { const { project, memberships } = this.#projectOrThrow(projectSlug); - requireAuth('maintainer | staff', { session, project, memberships }); + requireAuth('project-admin | staff', { session, project, memberships }); if (!input.title || input.title.length < 1 || input.title.length > 120) { throw new ApiValidationError('title required, 1-120 chars', { title: 'required' }); @@ -133,7 +133,7 @@ export class HelpWantedWriteService { // Poster, project maintainer, or staff can edit. Use a two-step check: // first try maintainer | staff, fall back to a per-poster check. if (session.person?.id !== existing.postedById) { - requireAuth('maintainer | staff', { session, project, memberships }); + requireAuth('project-admin | staff', { session, project, memberships }); } else { requireAuth('user', { session }); } @@ -259,7 +259,7 @@ export class HelpWantedWriteService { }> { const { project, memberships } = this.#projectOrThrow(projectSlug); const role = this.#roleOrThrow(project.slug, roleId); - requireAuth('maintainer | staff', { session, project, memberships }); + requireAuth('project-admin | staff', { session, project, memberships }); let filledBy: Person | null = null; if (input.filledBySlug) { @@ -287,12 +287,15 @@ export class HelpWantedWriteService { // Membership side-effect if (filledBy && !memberships.some((m) => m.personSlug === filledBy!.slug)) { + // Replaced by members-only fills in plans/needs-on-applications.md. const membership: ProjectMembership = ProjectMembershipSchema.parse({ id: uuidv7(), projectSlug: project.slug, personSlug: filledBy.slug, + state: 'member', role: `Help-wanted: ${role.title}`, - isMaintainer: false, + via: 'added', + followedAt: now, joinedAt: now, createdAt: now, updatedAt: now, @@ -313,7 +316,7 @@ export class HelpWantedWriteService { ): Promise<{ role: HelpWantedRole; stateApply: StateApply }> { const { project, memberships } = this.#projectOrThrow(projectSlug); const role = this.#roleOrThrow(project.slug, roleId); - requireAuth('maintainer | staff', { session, project, memberships }); + requireAuth('project-admin | staff', { session, project, memberships }); const now = nowIso(); const updated: HelpWantedRole = HelpWantedRoleSchema.parse({ @@ -337,7 +340,7 @@ export class HelpWantedWriteService { ): Promise<{ role: HelpWantedRole; stateApply: StateApply }> { const { project, memberships } = this.#projectOrThrow(projectSlug); const role = this.#roleOrThrow(project.slug, roleId); - requireAuth('maintainer | staff', { session, project, memberships }); + requireAuth('project-admin | staff', { session, project, memberships }); const updated: HelpWantedRole = HelpWantedRoleSchema.parse({ ...role, diff --git a/apps/api/src/services/memberships.ts b/apps/api/src/services/memberships.ts new file mode 100644 index 00000000..2ad37af5 --- /dev/null +++ b/apps/api/src/services/memberships.ts @@ -0,0 +1,147 @@ +/** + * Read helpers over the one-record membership model + * (specs/behaviors/project-membership.md). Every caller that asks "who is on + * this project", "who runs it" or "does it have an active admin" goes + * through here, so the state rules live in one place. + */ +import type { Person, PrivateProfile, ProjectMembership } from '@cfp/shared/schemas'; + +import { personBySlug, type InMemoryState } from '../store/memory/state.js'; +import type { PrivateStore } from '../store/private/interface.js'; + +/** Every record on a project, in any state. */ +export function membershipsOfProject(state: InMemoryState, projectSlug: string): ProjectMembership[] { + const out: ProjectMembership[] = []; + for (const id of state.membershipsByProject.get(projectSlug) ?? []) { + const m = state.projectMemberships.get(id); + if (m) out.push(m); + } + return out; +} + +/** Every record a person holds, in any state. */ +export function membershipsOfPerson(state: InMemoryState, personSlug: string): ProjectMembership[] { + const out: ProjectMembership[] = []; + for (const id of state.membershipsByPerson.get(personSlug) ?? []) { + const m = state.projectMemberships.get(id); + if (m) out.push(m); + } + return out; +} + +/** The one record (projectSlug, personSlug), if any. */ +export function membershipOf( + state: InMemoryState, + projectSlug: string, + personSlug: string, +): ProjectMembership | undefined { + for (const id of state.membershipsByPerson.get(personSlug) ?? []) { + const m = state.projectMemberships.get(id); + if (m && m.projectSlug === projectSlug) return m; + } + return undefined; +} + +/** `state = member` records of a project. */ +export function membersOfProject(state: InMemoryState, projectSlug: string): ProjectMembership[] { + return membershipsOfProject(state, projectSlug).filter((m) => m.state === 'member'); +} + +/** The `project-admin` marker: a `member` record with `isAdmin`. */ +export function isProjectAdmin(state: InMemoryState, projectSlug: string, personSlug: string): boolean { + return state.adminsByProject.get(projectSlug)?.has(personSlug) ?? false; +} + +/** The `member` marker: a record in state `member`. */ +export function isProjectMember(state: InMemoryState, projectSlug: string, personSlug: string): boolean { + return membershipOf(state, projectSlug, personSlug)?.state === 'member'; +} + +/** Admins of a project as people, deactivated ones included. */ +export function adminPeople(state: InMemoryState, projectSlug: string): Person[] { + const out: Person[] = []; + for (const slug of state.adminsByProject.get(projectSlug) ?? []) { + const p = personBySlug(state, slug); + if (p) out.push(p); + } + return out; +} + +/** + * Admins who are not deactivated. The last-admin rule + * (project-membership.md → The last admin) counts these. + */ +export function activeAdminSlugs(state: InMemoryState, projectSlug: string): string[] { + return adminPeople(state, projectSlug) + .filter((p) => !p.deletedAt) + .map((p) => p.slug); +} + +/** + * Whether a change that takes `personSlug` out of the admins leaves the + * project with no admin who is an active member. + */ +export function wouldLeaveNoActiveAdmin(state: InMemoryState, projectSlug: string, personSlug: string): boolean { + if (!isProjectAdmin(state, projectSlug, personSlug)) return false; + return activeAdminSlugs(state, projectSlug).every((slug) => slug === personSlug); +} + +/** A private profile's address works: present and not marked inactive by a bounce. */ +export function hasDeliverableEmail(profile: PrivateProfile | null | undefined): boolean { + return Boolean(profile?.email) && profile?.emailBounce?.inactive !== true; +} + +/** + * A verified Slack link on the profile (specs/api/slack-link.md). The field + * arrives with the Slack-linking plan; until then no profile carries it. + */ +export function hasSlackLink(profile: PrivateProfile | null | undefined): boolean { + const slack = (profile as { slack?: unknown } | null | undefined)?.slack; + return slack !== undefined && slack !== null; +} + +/** + * The admins who can actually hear about the project: not deactivated, and + * reachable by a deliverable email or a linked Slack account + * (project-membership.md → Applying, condition 3). + */ +export async function activeAdmins( + state: InMemoryState, + privateStore: PrivateStore, + projectSlug: string, +): Promise<Array<{ person: Person; profile: PrivateProfile | null }>> { + const out: Array<{ person: Person; profile: PrivateProfile | null }> = []; + for (const person of adminPeople(state, projectSlug)) { + if (person.deletedAt) continue; + const profile = await privateStore.getProfile(person.id); + if (hasDeliverableEmail(profile) || hasSlackLink(profile)) out.push({ person, profile }); + } + return out; +} + +export async function hasActiveAdmin( + state: InMemoryState, + privateStore: PrivateStore, + projectSlug: string, +): Promise<boolean> { + return (await activeAdmins(state, privateStore, projectSlug)).length > 0; +} + +/** Member ordering: admins first, then `role` ascending (unlabelled last), then full name. */ +export function compareMembers( + peopleBySlug: ReadonlyMap<string, Person>, +): (a: ProjectMembership, b: ProjectMembership) => number { + return (a, b) => { + if (a.isAdmin !== b.isAdmin) return a.isAdmin ? -1 : 1; + const ra = a.role ?? ''; + const rb = b.role ?? ''; + if (ra !== rb) { + if (!ra) return 1; + if (!rb) return -1; + return ra.localeCompare(rb); + } + const na = peopleBySlug.get(a.personSlug)?.fullName ?? ''; + const nb = peopleBySlug.get(b.personSlug)?.fullName ?? ''; + return na.localeCompare(nb); + }; +} diff --git a/apps/api/src/services/permissions.ts b/apps/api/src/services/permissions.ts index cb574e98..aea7767d 100644 --- a/apps/api/src/services/permissions.ts +++ b/apps/api/src/services/permissions.ts @@ -36,6 +36,9 @@ export function getCallerSession(request: FastifyRequest): CallerSession | undef export interface ProjectPermissions { readonly canEdit: boolean; readonly canManageMembers: boolean; + readonly canReviewApplications: boolean; + readonly canFollow: boolean; + readonly canApply: boolean; readonly canPostUpdate: boolean; readonly canLogBuzz: boolean; readonly canPostHelpWanted: boolean; @@ -73,41 +76,63 @@ function isStaff(caller: CallerSession | undefined): boolean { return caller?.accountLevel === 'staff' || caller?.accountLevel === 'administrator'; } -function isMaintainerOf( +/** The caller's own record on the project, if any. */ +function ownRecord( caller: CallerSession | undefined, project: Project, - memberships: ProjectMembership[], -): boolean { - if (!caller) return false; - if (project.maintainerId === caller.id) return true; - return memberships.some((m) => m.personSlug === caller.slug && m.isMaintainer); + memberships: readonly ProjectMembership[], +): ProjectMembership | undefined { + if (!caller) return undefined; + return memberships.find((m) => m.projectSlug === project.slug && m.personSlug === caller.slug); } -function isMemberOf( +/** `project-admin` (specs/behaviors/authorization.md): a member record with `isAdmin`. */ +function isProjectAdminOf( caller: CallerSession | undefined, - projectSlug: string, - memberships: ProjectMembership[], + project: Project, + memberships: readonly ProjectMembership[], ): boolean { - if (!caller) return false; - return memberships.some((m) => m.projectSlug === projectSlug && m.personSlug === caller.slug); + const own = ownRecord(caller, project, memberships); + return own?.state === 'member' && own.isAdmin; +} + +/** Facts the permission hints need beyond the records themselves. */ +export interface ProjectPermissionContext { + /** The project has an active admin (project-membership.md → Applying). */ + readonly hasActiveAdmin?: boolean; + /** The caller is an agent account, which never follows or applies. */ + readonly callerIsAgent?: boolean; + /** A re-apply wait is running for the caller. */ + readonly reapplyWaitRunning?: boolean; } export function computeProjectPermissions( caller: CallerSession | undefined, project: Project, - memberships: ProjectMembership[], + memberships: readonly ProjectMembership[], + ctx: ProjectPermissionContext = {}, ): ProjectPermissions { const staff = isStaff(caller); - const maintainer = isMaintainerOf(caller, project, memberships); - const member = isMemberOf(caller, project.slug, memberships); + const admin = isProjectAdminOf(caller, project, memberships); + const own = ownRecord(caller, project, memberships); + const member = own?.state === 'member'; const authenticated = caller !== undefined; + const personal = authenticated && !ctx.callerIsAgent && !project.deletedAt; return { - canEdit: maintainer || staff, - canManageMembers: maintainer || staff, + canEdit: admin || staff, + canManageMembers: admin || staff, + canReviewApplications: admin || staff, + canFollow: personal && own === undefined, + canApply: + personal && + own?.state !== 'applicant' && + own?.state !== 'member' && + ctx.hasActiveAdmin === true && + ctx.reapplyWaitRunning !== true, canPostUpdate: member || staff, canLogBuzz: authenticated, - canPostHelpWanted: maintainer || staff, + canPostHelpWanted: admin || staff, canDelete: staff, }; } @@ -203,7 +228,7 @@ export function computeHelpWantedPermissions( alreadyExpressedInterest: boolean, ): HelpWantedPermissions { const staff = isStaff(caller); - const maintainer = isMaintainerOf(caller, project, memberships); + const maintainer = isProjectAdminOf(caller, project, memberships); const isPoster = caller !== undefined && caller.id === role.postedById; const authenticated = caller !== undefined; diff --git a/apps/api/src/services/person.ts b/apps/api/src/services/person.ts index b48a355b..5f1b314e 100644 --- a/apps/api/src/services/person.ts +++ b/apps/api/src/services/person.ts @@ -197,7 +197,9 @@ export class PersonService { } #serializeListItem(person: Person): PersonListItem { - const memberOfCount = this.#state.membershipsByPerson.get(person.slug)?.size ?? 0; + const memberships = this.#getMembershipsForPerson(person.slug); + const memberOfCount = memberships.length; + const adminOfCount = memberships.filter((m) => m.isAdmin).length; const tagAssignments = [...(this.#state.tagAssignmentsByTaggable.get(person.id) ?? [])] .map((taId) => this.#state.tagAssignments.get(taId)) @@ -205,16 +207,24 @@ export class PersonService { return serializePersonListItem(person, { memberOfCount, + adminOfCount, tagAssignments, allTags: this.#state.tags, }); } + /** + * The person's `member` records, admin first then newest joined. Follows + * and applications are never listed, on anyone's profile. + */ #getMembershipsForPerson(personSlug: string): ProjectMembership[] { const mIds = this.#state.membershipsByPerson.get(personSlug) ?? new Set(); return [...mIds] .map((id) => this.#state.projectMemberships.get(id)) - .filter((m): m is ProjectMembership => m !== undefined); + .filter((m): m is ProjectMembership => m !== undefined && m.state === 'member') + .sort((a, b) => + a.isAdmin !== b.isAdmin ? (a.isAdmin ? -1 : 1) : (b.joinedAt ?? '').localeCompare(a.joinedAt ?? ''), + ); } #getProjectsForMemberships(memberships: ProjectMembership[]): Map<string, Project> { diff --git a/apps/api/src/services/project-membership.write.ts b/apps/api/src/services/project-membership.write.ts index bf850cc8..c0883f37 100644 --- a/apps/api/src/services/project-membership.write.ts +++ b/apps/api/src/services/project-membership.write.ts @@ -1,10 +1,18 @@ /** - * Project membership writes: - * - POST /api/projects/:slug/members (maintainer | staff) - * - PATCH /api/projects/:slug/members/:slug (maintainer | staff) - * - DELETE /api/projects/:slug/members/:slug (maintainer | staff) - * - POST /api/projects/:slug/members/join (user) - * - POST /api/projects/:slug/members/leave (user, self) + * Project membership writes — the transitions of + * specs/behaviors/project-membership.md that the members API makes + * (specs/api/projects-members.md): + * + * - POST /api/projects/:slug/members add (project-admin | staff) + * - PATCH /api/projects/:slug/members/:personSlug promote / demote / update + * (project-admin | staff; self for own role) + * - DELETE /api/projects/:slug/members/:personSlug remove (project-admin | staff) + * - POST /api/projects/:slug/members/leave leave (user, self) + * + * Every transition is one write and one commit; the route names it in the + * `Action` trailer. A change that takes the last active admin out needs + * `confirmLastAdmin` (project-membership.md → The last admin). Every + * endpoint treats a deactivated person as absent. */ import { uuidv7 } from 'uuidv7'; import { @@ -16,18 +24,68 @@ import { import type { DualStoreTx } from '../store/store.js'; import type { InMemoryState } from '../store/memory/state.js'; import { StateApply } from '../store/state-apply.js'; -import { - ApiNotFoundError, - ApiValidationError, - ConflictError, -} from '../lib/errors.js'; +import { ApiNotFoundError, ApiValidationError, ConflictError } from '../lib/errors.js'; import { requireAuth } from '../auth/require.js'; +import { isAgentAccount } from '../auth/agent-grant.js'; import type { SessionContext } from '../auth/middleware.js'; +import { membershipOf, membershipsOfProject, wouldLeaveNoActiveAdmin } from './memberships.js'; + +const ROLE_MAX = 80; function nowIso(): string { return new Date().toISOString(); } +export type PatchTransition = 'promote' | 'demote' | 'update'; + +export interface MembershipPatch { + readonly role?: string | null; + readonly isAdmin?: boolean; + readonly confirmLastAdmin?: boolean; +} + +export interface MembershipResult { + readonly membership: ProjectMembership; + readonly stateApply: StateApply; +} + +export function checkRole(role: string | null | undefined): void { + if (role !== undefined && role !== null && role.length > ROLE_MAX) { + throw new ApiValidationError(`role too long (max ${ROLE_MAX} chars)`, { role: 'too_long' }); + } +} + +function lastAdminConflict(): ConflictError { + return new ConflictError( + 'This change would leave the project with no active admin; resend with confirmLastAdmin', + 'last_admin', + ); +} + +/** The record as a follower: member-only fields cleared, everything else kept. */ +export function asFollower(m: ProjectMembership, now: string): ProjectMembership { + return ProjectMembershipSchema.parse({ + ...m, + state: 'follower', + isAdmin: false, + role: null, + via: null, + joinedAt: null, + updatedAt: now, + }); +} + +/** Refuse an agent account as the subject of a membership act (specs/api/agents.md). */ +export function refuseAgent(state: InMemoryState, person: Person): void { + if (isAgentAccount(state, person.slug)) { + throw new ApiValidationError( + 'An agent account never follows, applies to or joins a project', + { personSlug: 'agent_account' }, + 'agent_account', + ); + } +} + export class ProjectMembershipWriteService { readonly #state: InMemoryState; @@ -35,179 +93,187 @@ export class ProjectMembershipWriteService { this.#state = state; } + /** + * add — none, follower or applicant → member, at once (`via = added`). An + * applicant's open application resolves as accepted, decided by the caller. + */ async add( tx: DualStoreTx, projectSlug: string, - input: { personSlug: string; role?: string | null }, + input: { personSlug: string; role?: string | null; isAdmin?: boolean }, session: SessionContext, - ): Promise<{ membership: ProjectMembership; stateApply: StateApply }> { + ): Promise<MembershipResult & { person: Person; project: Project }> { const { project, memberships } = this.#projectOrThrow(projectSlug); - requireAuth('maintainer | staff', { session, project, memberships }); - - const { person } = this.#personOrThrow(input.personSlug); - if (memberships.some((m) => m.personSlug === person.slug)) { - throw new ConflictError( - `${person.slug} is already a member of this project`, - 'already_member', - ); - } - if (input.role !== undefined && input.role !== null && input.role.length > 80) { - throw new ApiValidationError('role too long (max 80 chars)', { role: 'too_long' }); + requireAuth('project-admin | staff', { session, project, memberships }); + + const person = this.#personOrThrow(input.personSlug); + refuseAgent(this.#state, person); + checkRole(input.role); + + const existing = membershipOf(this.#state, project.slug, person.slug); + if (existing?.state === 'member') { + throw new ConflictError(`${person.slug} is already a member of this project`, 'already_member'); } - return this.#createMembership(tx, project, person, { + const now = nowIso(); + const application = + existing?.application?.status === 'open' + ? { + ...existing.application, + status: 'accepted' as const, + decidedById: session.person!.id, + decidedAt: now, + decidedVia: 'site' as const, + } + : (existing?.application ?? null); + + const membership = ProjectMembershipSchema.parse({ + id: existing?.id ?? uuidv7(), + projectSlug: project.slug, + personSlug: person.slug, + state: 'member', + isAdmin: input.isAdmin === true, role: input.role ?? null, - isMaintainer: false, + via: 'added', + muted: existing?.muted ?? false, + followedAt: existing?.followedAt ?? now, + joinedAt: now, + application, + createdAt: existing?.createdAt ?? now, + updatedAt: now, }); + + await tx.public['project-memberships'].upsert(membership); + return { membership, stateApply: new StateApply().upsertMembership(membership), person, project }; + } + + /** Which transition a PATCH makes, for the commit's `Action` trailer. */ + patchTransition(projectSlug: string, personSlug: string, input: MembershipPatch): PatchTransition { + const existing = membershipOf(this.#state, projectSlug, personSlug); + if (input.isAdmin === true && existing?.isAdmin !== true) return 'promote'; + if (input.isAdmin === false && existing?.isAdmin === true) return 'demote'; + return 'update'; } + /** promote / demote / update role on a `member` record. */ async update( tx: DualStoreTx, projectSlug: string, personSlug: string, - input: { role?: string | null }, + input: MembershipPatch, session: SessionContext, - ): Promise<{ membership: ProjectMembership; stateApply: StateApply }> { + ): Promise<MembershipResult> { const { project, memberships } = this.#projectOrThrow(projectSlug); - requireAuth('maintainer | staff', { session, project, memberships }); + const person = this.#personOrThrow(personSlug); - const { person } = this.#personOrThrow(personSlug); - const membership = memberships.find((m) => m.personSlug === person.slug); - if (!membership) { - throw new ApiNotFoundError(`${person.slug} is not a member of this project`); + // The admin flag is project-admin | staff; a member may relabel themselves. + if (input.isAdmin !== undefined) { + requireAuth('project-admin | staff', { session, project, memberships }); + } else { + requireAuth('project-admin | staff | self', { session, project, memberships, selfSlug: person.slug }); } - if (input.role !== undefined && input.role !== null && input.role.length > 80) { - throw new ApiValidationError('role too long (max 80 chars)', { role: 'too_long' }); + const existing = membershipOf(this.#state, project.slug, person.slug); + if (!existing) throw new ApiNotFoundError(`${person.slug} has no record on this project`); + if (existing.state !== 'member') { + throw new ConflictError(`${person.slug} is not a member of this project`, 'not_a_member'); + } + checkRole(input.role); + if (input.isAdmin === true) refuseAgent(this.#state, person); + if ( + input.isAdmin === false && + input.confirmLastAdmin !== true && + wouldLeaveNoActiveAdmin(this.#state, project.slug, person.slug) + ) { + throw lastAdminConflict(); } - const updated: ProjectMembership = ProjectMembershipSchema.parse({ - ...membership, - role: input.role === undefined ? membership.role : input.role, + const updated = ProjectMembershipSchema.parse({ + ...existing, + role: input.role === undefined ? (existing.role ?? null) : input.role, + isAdmin: input.isAdmin ?? existing.isAdmin, updatedAt: nowIso(), }); await tx.public['project-memberships'].upsert(updated); - - const stateApply = new StateApply().upsertMembership(updated); - return { membership: updated, stateApply }; + return { membership: updated, stateApply: new StateApply().upsertMembership(updated) }; } + /** remove — member → none. A person an admin removed is not left following. */ async remove( tx: DualStoreTx, projectSlug: string, personSlug: string, + opts: { confirmLastAdmin?: boolean }, session: SessionContext, ): Promise<{ stateApply: StateApply }> { const { project, memberships } = this.#projectOrThrow(projectSlug); - requireAuth('maintainer | staff', { session, project, memberships }); + requireAuth('project-admin | staff', { session, project, memberships }); - const { person } = this.#personOrThrow(personSlug); - const membership = memberships.find((m) => m.personSlug === person.slug); - if (!membership) { - throw new ApiNotFoundError(`${person.slug} is not a member of this project`); + const person = this.#personOrThrow(personSlug); + const existing = membershipOf(this.#state, project.slug, person.slug); + if (!existing) throw new ApiNotFoundError(`${person.slug} has no record on this project`); + if (existing.state !== 'member') { + // Followers and applicants are not admins' to manage. + throw new ConflictError(`${person.slug} is not a member of this project`, 'not_a_member'); } - if (project.maintainerId === person.id) { - throw new ConflictError( - 'Cannot remove the current maintainer; transfer first', - 'cannot_remove_maintainer', - ); + if (opts.confirmLastAdmin !== true && wouldLeaveNoActiveAdmin(this.#state, project.slug, person.slug)) { + throw lastAdminConflict(); } - await tx.public['project-memberships'].delete(membership); - - const stateApply = new StateApply().removeMembership(membership); - return { stateApply }; - } - - async join( - tx: DualStoreTx, - projectSlug: string, - session: SessionContext, - ): Promise<{ membership: ProjectMembership; stateApply: StateApply }> { - requireAuth('user', { session }); - const { project, memberships } = this.#projectOrThrow(projectSlug); - const person = session.person!; - - if (memberships.some((m) => m.personSlug === person.slug)) { - throw new ConflictError('Already a member of this project', 'already_member'); - } - - return this.#createMembership(tx, project, person, { role: null, isMaintainer: false }); + await tx.public['project-memberships'].delete(existing); + return { stateApply: new StateApply().removeMembership(existing) }; } + /** + * leave — member → follower (role, isAdmin, via and joinedAt cleared), or + * the record deleted with `alsoUnfollow`. + */ async leave( tx: DualStoreTx, projectSlug: string, + opts: { alsoUnfollow?: boolean; confirmLastAdmin?: boolean }, session: SessionContext, - ): Promise<{ stateApply: StateApply }> { + ): Promise<{ membership: ProjectMembership | null; stateApply: StateApply }> { requireAuth('user', { session }); - const { project, memberships } = this.#projectOrThrow(projectSlug); + const { project } = this.#projectOrThrow(projectSlug); const person = session.person!; - const membership = memberships.find((m) => m.personSlug === person.slug); - if (!membership) { - throw new ApiNotFoundError(`You are not a member of this project`); + const existing = membershipOf(this.#state, project.slug, person.slug); + if (!existing || existing.state !== 'member') { + throw new ConflictError('You are not a member of this project', 'not_a_member'); } - if (project.maintainerId === person.id) { - throw new ConflictError( - 'Cannot leave as the current maintainer; transfer first', - 'cannot_remove_maintainer', - ); + if (opts.confirmLastAdmin !== true && wouldLeaveNoActiveAdmin(this.#state, project.slug, person.slug)) { + throw lastAdminConflict(); } - await tx.public['project-memberships'].delete(membership); + if (opts.alsoUnfollow === true) { + await tx.public['project-memberships'].delete(existing); + return { membership: null, stateApply: new StateApply().removeMembership(existing) }; + } - const stateApply = new StateApply().removeMembership(membership); - return { stateApply }; + const follower = asFollower(existing, nowIso()); + await tx.public['project-memberships'].upsert(follower); + return { membership: follower, stateApply: new StateApply().upsertMembership(follower) }; } // --------------------------------------------------------------------------- // helpers // --------------------------------------------------------------------------- - async #createMembership( - tx: DualStoreTx, - project: Project, - person: Person, - opts: { role: string | null; isMaintainer: boolean }, - ): Promise<{ membership: ProjectMembership; stateApply: StateApply }> { - const now = nowIso(); - const membership: ProjectMembership = ProjectMembershipSchema.parse({ - id: uuidv7(), - projectSlug: project.slug, - personSlug: person.slug, - role: opts.role, - isMaintainer: opts.isMaintainer, - joinedAt: now, - createdAt: now, - updatedAt: now, - }); - - await tx.public['project-memberships'].upsert(membership); - - const stateApply = new StateApply().upsertMembership(membership); - return { membership, stateApply }; - } - #projectOrThrow(slug: string): { project: Project; memberships: ProjectMembership[] } { const id = this.#state.projectIdBySlug.get(slug); if (!id) throw new ApiNotFoundError(`Project '${slug}' not found`); const p = this.#state.projects.get(id); if (!p || p.deletedAt) throw new ApiNotFoundError(`Project '${slug}' not found`); - - const mIds = this.#state.membershipsByProject.get(p.slug) ?? new Set(); - const memberships = [...mIds] - .map((mId) => this.#state.projectMemberships.get(mId)) - .filter((m): m is ProjectMembership => m !== undefined); - return { project: p, memberships }; + return { project: p, memberships: membershipsOfProject(this.#state, p.slug) }; } - #personOrThrow(slug: string): { person: Person } { + /** The subject person; a deactivated person is absent to every members endpoint. */ + #personOrThrow(slug: string): Person { const id = this.#state.personIdBySlug.get(slug); - if (!id) throw new ApiNotFoundError(`Person '${slug}' not found`); - const p = this.#state.people.get(id); + const p = id ? this.#state.people.get(id) : undefined; if (!p || p.deletedAt) throw new ApiNotFoundError(`Person '${slug}' not found`); - return { person: p }; + return p; } } diff --git a/apps/api/src/services/project.ts b/apps/api/src/services/project.ts index 84804b30..8caa4acb 100644 --- a/apps/api/src/services/project.ts +++ b/apps/api/src/services/project.ts @@ -4,6 +4,8 @@ import type { HelpWantedRole, Person, Project, ProjectMembership, Tag } from '@cfp/shared/schemas'; import type { InMemoryState } from '../store/memory/state.js'; import type { FtsEngine } from '../store/fts.js'; +import type { PrivateStore } from '../store/private/interface.js'; +import { hasActiveAdmin, isProjectAdmin, membersOfProject, membershipOf } from './memberships.js'; import { computeProjectFacets, type ProjectFacets } from '../store/memory/facets.js'; import type { CallerSession } from './permissions.js'; import { computeProjectPermissions } from './permissions.js'; @@ -12,6 +14,7 @@ import { serializeProjectListItem, type ProjectDetail, type ProjectListItem, + type ProjectViewer, } from './serializers/project.js'; export interface ProjectListOptions { @@ -19,7 +22,8 @@ export interface ProjectListOptions { readonly stage?: string; readonly stageIn?: string[]; readonly tag?: string[]; - readonly maintainer?: string; + /** Person slug: projects where they are an admin (`maintainer` is the route's alias). */ + readonly admin?: string; readonly memberSlug?: string; readonly helpWanted?: boolean; readonly featured?: boolean; @@ -89,10 +93,12 @@ function compareProjects( export class ProjectService { readonly #state: InMemoryState; readonly #fts: FtsEngine; + readonly #privateStore: PrivateStore | undefined; - constructor(state: InMemoryState, fts: FtsEngine) { + constructor(state: InMemoryState, fts: FtsEngine, privateStore?: PrivateStore) { this.#state = state; this.#fts = fts; + this.#privateStore = privateStore; } list(opts: ProjectListOptions): ProjectListResult | { error: 'invalid_sort' | 'invalid_filter' } { @@ -110,16 +116,6 @@ export class ProjectService { if (!opts.sort) ftsRank = new Map(slugs.map((slug, i) => [slug, i])); } - let memberPersonId: string | undefined; - if (opts.memberSlug) { - memberPersonId = this.#state.personIdBySlug.get(opts.memberSlug); - // Empty match below if memberPersonId is undefined — predicate returns false. - } - - let maintainerPersonId: string | undefined; - if (opts.maintainer) { - maintainerPersonId = this.#state.personIdBySlug.get(opts.maintainer); - } // Tag filters grouped by namespace. OR within namespace, AND across // namespaces (per specs/api/projects.md). Unknown handles are dropped @@ -185,7 +181,7 @@ export class ProjectService { if (stageInSet && !stageInSet.has(p.stage)) return false; } if (opts.featured !== undefined && p.featured !== opts.featured) return false; - if (opts.maintainer && p.maintainerId !== maintainerPersonId) return false; + if (opts.admin && !isProjectAdmin(this.#state, p.slug, opts.admin)) return false; // Tag predicate — for each namespace's filter set the project must // include at least one matching tag (OR within namespace). Across @@ -206,18 +202,8 @@ export class ProjectService { } } - if (opts.memberSlug) { - if (!memberPersonId) return false; - const personMemberships = this.#state.membershipsByPerson.get(opts.memberSlug); - if (!personMemberships) return false; - let found = false; - for (const mId of personMemberships) { - if (this.#state.projectMemberships.get(mId)?.projectSlug === p.slug) { - found = true; - break; - } - } - if (!found) return false; + if (opts.memberSlug && membershipOf(this.#state, p.slug, opts.memberSlug)?.state !== 'member') { + return false; } if (opts.helpWanted) { @@ -271,7 +257,7 @@ export class ProjectService { return { items, totalItems, facets }; } - get(slug: string, caller?: CallerSession): ProjectDetail | null { + async get(slug: string, caller?: CallerSession): Promise<ProjectDetail | null> { const projectId = this.#state.projectIdBySlug.get(slug); if (!projectId) return null; const project = this.#state.projects.get(projectId); @@ -281,11 +267,12 @@ export class ProjectService { caller?.accountLevel === 'staff' || caller?.accountLevel === 'administrator'; if (project.deletedAt && !isStaff) return null; - const memberships = this.#getMembershipsForProject(project.slug); + const allRecords = this.#getMembershipsForProject(project.slug); + const memberships = allRecords.filter((m) => m.state === 'member'); const memberPeople = this.#getPeopleForMemberships(memberships); - const maintainer = project.maintainerId - ? (this.#state.people.get(project.maintainerId) ?? null) - : null; + const activeAdmin = this.#privateStore + ? await hasActiveAdmin(this.#state, this.#privateStore, project.slug) + : false; const openHelpWantedRoles = this.#getOpenHelpWantedRoles(project.slug); const helpWantedTags = this.#getHelpWantedTags(openHelpWantedRoles.map((r) => r.id)); @@ -295,12 +282,18 @@ export class ProjectService { const updateCount = this.#state.updatesByProject.get(project.slug)?.size ?? 0; const buzzCount = this.#state.buzzByProject.get(project.slug)?.size ?? 0; - const permissions = computeProjectPermissions(caller, project, memberships); + const permissions = computeProjectPermissions(caller, project, allRecords); + const own = caller ? allRecords.find((m) => m.personSlug === caller.slug) : undefined; + const viewer: ProjectViewer | null = own + ? { state: own.state, isAdmin: own.isAdmin === true, muted: own.muted === true, application: null, reapplyAfter: null } + : null; return serializeProjectDetail(project, { - maintainer, memberships, memberPeople, + showVia: permissions.canManageMembers, + hasActiveAdmin: activeAdmin, + viewer, openHelpWantedRoles, helpWantedTags, tags: projectTags, @@ -332,11 +325,8 @@ export class ProjectService { } #serializeListItem(project: Project): ProjectListItem { - const memberships = this.#getMembershipsForProject(project.slug); + const memberships = membersOfProject(this.#state, project.slug); const memberPeople = this.#getPeopleForMemberships(memberships); - const maintainer = project.maintainerId - ? (this.#state.people.get(project.maintainerId) ?? null) - : null; const openHelpWantedCount = [...(this.#state.helpWantedByProject.get(project.slug) ?? [])] .filter((rId) => this.#state.helpWantedRoles.get(rId)?.status === 'open').length; @@ -346,7 +336,6 @@ export class ProjectService { .filter((ta): ta is NonNullable<typeof ta> => ta !== undefined); return serializeProjectListItem(project, { - maintainer, memberships, memberPeople, openHelpWantedCount, diff --git a/apps/api/src/services/project.write.ts b/apps/api/src/services/project.write.ts index ecc42188..de62f227 100644 --- a/apps/api/src/services/project.write.ts +++ b/apps/api/src/services/project.write.ts @@ -1,6 +1,6 @@ /** * ProjectService write methods: create, update, soft-delete, restore, - * change-maintainer + slug-rename machinery. + * slug-rename machinery. * * Each method takes a `tx` (dual-store transaction context) and an actor * session. It stages gitsheets writes inside the transaction and returns @@ -149,7 +149,6 @@ export class ProjectWriteService { summary: input.summary ?? null, overview: input.overview ?? null, stage, - maintainerId: session.person!.id, createdById: session.person!.id, usersUrl: input.usersUrl ?? null, developersUrl: input.developersUrl ?? null, @@ -169,8 +168,11 @@ export class ProjectWriteService { id: uuidv7(), projectSlug: project.slug, personSlug: session.person!.slug, + state: 'member', + isAdmin: true, role: 'Founder', - isMaintainer: true, + via: 'created', + followedAt: now, joinedAt: now, createdAt: now, updatedAt: now, @@ -210,7 +212,7 @@ export class ProjectWriteService { const existing = this.#requireExisting(slug); const memberships = this.#membershipsFor(existing.slug); - requireAuth('maintainer | staff', { session, project: existing, memberships }); + requireAuth('project-admin | staff', { session, project: existing, memberships }); const staff = isStaff(session); @@ -388,76 +390,6 @@ export class ProjectWriteService { return { project: updated, stateApply }; } - // --------------------------------------------------------------------------- - // change-maintainer - // --------------------------------------------------------------------------- - - async changeMaintainer( - tx: DualStoreTx, - slug: string, - newMaintainerSlug: string, - session: SessionContext, - ): Promise<ProjectWriteResult> { - const existing = this.#requireExisting(slug); - const memberships = this.#membershipsFor(existing.slug); - requireAuth('maintainer | staff', { session, project: existing, memberships }); - - const newMaintainerId = this.#state.personIdBySlug.get(newMaintainerSlug); - if (!newMaintainerId) { - throw new ApiNotFoundError(`Person '${newMaintainerSlug}' not found`); - } - const newMaintainerPerson = this.#state.people.get(newMaintainerId); - if (!newMaintainerPerson) { - throw new ApiNotFoundError(`Person '${newMaintainerSlug}' not found`); - } - - const newMaintainerMembership = memberships.find((m) => m.personSlug === newMaintainerPerson.slug); - if (!newMaintainerMembership) { - throw new ConflictError( - `${newMaintainerSlug} is not a member of this project`, - 'not_a_member', - ); - } - - const now = nowIso(); - const stateApply = new StateApply(); - - // Old maintainer keeps membership; flip isMaintainer where appropriate. - const oldMaintainerSlug = existing.maintainerId - ? this.#state.personSlugById.get(existing.maintainerId) - : undefined; - const oldMaintainerMembership = memberships.find( - (m) => m.personSlug === oldMaintainerSlug && m.isMaintainer, - ); - if (oldMaintainerMembership && oldMaintainerMembership.personSlug !== newMaintainerPerson.slug) { - const updatedOld: ProjectMembership = ProjectMembershipSchema.parse({ - ...oldMaintainerMembership, - isMaintainer: false, - role: oldMaintainerMembership.role ?? 'Maintainer (former)', - updatedAt: now, - }); - await tx.public['project-memberships'].upsert(updatedOld); - stateApply.upsertMembership(updatedOld); - } - - const updatedNew: ProjectMembership = ProjectMembershipSchema.parse({ - ...newMaintainerMembership, - isMaintainer: true, - updatedAt: now, - }); - await tx.public['project-memberships'].upsert(updatedNew); - stateApply.upsertMembership(updatedNew); - - const updatedProject: Project = ProjectSchema.parse({ - ...existing, - maintainerId: newMaintainerId, - updatedAt: now, - }); - await tx.public.projects.upsert(updatedProject); - stateApply.upsertProject(updatedProject); - - return { project: updatedProject, stateApply }; - } // --------------------------------------------------------------------------- // helpers diff --git a/apps/api/src/services/serializers/person.ts b/apps/api/src/services/serializers/person.ts index e6b267fa..938d7f22 100644 --- a/apps/api/src/services/serializers/person.ts +++ b/apps/api/src/services/serializers/person.ts @@ -23,7 +23,10 @@ export interface PersonListItem { readonly fullName: string; readonly avatarUrl: string | null; readonly bioExcerpt: string; + /** Projects where the person's record is `state = member`. */ readonly memberOfCount: number; + /** Of those, the ones where they are an admin. */ + readonly adminOfCount: number; readonly tags: TagItem[]; readonly createdAt: string; } @@ -35,7 +38,7 @@ export interface PersonMembershipSummary { readonly stage: string; }; readonly role: string | null; - readonly isMaintainer: boolean; + readonly isAdmin: boolean; readonly joinedAt: string; } @@ -77,6 +80,7 @@ export function serializePersonListItem( person: Person, opts: { memberOfCount: number; + adminOfCount: number; tagAssignments: TagAssignment[]; allTags: Map<string, Tag>; }, @@ -96,6 +100,7 @@ export function serializePersonListItem( avatarUrl: person.avatarKey ? `/api/attachments/${person.avatarKey}` : null, bioExcerpt, memberOfCount: opts.memberOfCount, + adminOfCount: opts.adminOfCount, tags: personTags.map((t) => ({ namespace: t.namespace, slug: t.slug, title: t.title })), createdAt: person.createdAt, }; @@ -142,8 +147,8 @@ export function serializePersonDetail( stage: project?.stage ?? 'commenting', }, role: m.role ?? null, - isMaintainer: m.isMaintainer, - joinedAt: m.joinedAt, + isAdmin: m.isAdmin, + joinedAt: m.joinedAt ?? m.createdAt, }; }); diff --git a/apps/api/src/services/serializers/project.ts b/apps/api/src/services/serializers/project.ts index 4c7b0ac5..ecd7b9c9 100644 --- a/apps/api/src/services/serializers/project.ts +++ b/apps/api/src/services/serializers/project.ts @@ -11,6 +11,7 @@ import type { } from '@cfp/shared/schemas'; import { renderMarkdown } from './common.js'; import type { ProjectPermissions } from '../permissions.js'; +import { compareMembers } from '../memberships.js'; import { groupTagsByNamespace, serializePersonAvatar, @@ -27,7 +28,8 @@ export interface ProjectListItem { readonly summary: string | null; readonly stage: string; readonly overviewExcerpt: string; - readonly maintainer: PersonAvatar | null; + /** Members with `isAdmin`, by `joinedAt`. */ + readonly admins: PersonAvatar[]; readonly memberCount: number; readonly members: PersonAvatar[]; readonly links: { @@ -40,15 +42,27 @@ export interface ProjectListItem { readonly updatedAt: string; } +/** specs/api/projects-members.md → ProjectMembership response shape. */ export interface ProjectMembershipResponse { readonly id: string; readonly projectSlug: string; readonly person: PersonAvatar; readonly role: string | null; - readonly isMaintainer: boolean; + readonly isAdmin: boolean; + /** Shown only to project admins and staff; `null` for everyone else. */ + readonly via: string | null; readonly joinedAt: string; } +/** The caller's own record (specs/api/projects.md → Project shape `viewer`). */ +export interface ProjectViewer { + readonly state: 'follower' | 'applicant' | 'member'; + readonly isAdmin: boolean; + readonly muted: boolean; + readonly application: unknown | null; + readonly reapplyAfter: string | null; +} + export interface ProjectDetail { readonly id: string; readonly slug: string; @@ -58,8 +72,9 @@ export interface ProjectDetail { readonly overviewHtml: string; readonly stage: string; readonly stageProgress: number; - readonly maintainer: PersonAvatar | null; readonly memberships: ProjectMembershipResponse[]; + readonly hasActiveAdmin: boolean; + readonly viewer: ProjectViewer | null; readonly openHelpWantedRoles: HelpWantedRoleSummary[]; readonly tags: { topic: TagItem[]; tech: TagItem[]; event: TagItem[] }; readonly links: { @@ -103,29 +118,27 @@ function stageProgress(stage: string): number { return idx / (STAGE_ORDER.length - 1); } -/** - * Member order: the maintainer first, then by full name. `memberPeople` is - * keyed by person slug, the handle memberships reference people by. - */ -function byMaintainerThenName( - project: Project, - memberPeople: Map<string, Person>, -): (a: ProjectMembership, b: ProjectMembership) => number { - return (a, b) => { - const pa = memberPeople.get(a.personSlug); - const pb = memberPeople.get(b.personSlug); - const aIsMaintainer = pa !== undefined && pa.id === project.maintainerId; - const bIsMaintainer = pb !== undefined && pb.id === project.maintainerId; - if (aIsMaintainer) return -1; - if (bIsMaintainer) return 1; - return (pa?.fullName ?? '').localeCompare(pb?.fullName ?? ''); +/** One member record in the public response shape. */ +export function serializeProjectMembership( + m: ProjectMembership, + person: Person | undefined, + opts: { showVia: boolean }, +): ProjectMembershipResponse { + return { + id: m.id, + projectSlug: m.projectSlug, + person: serializePersonAvatar(person) ?? { slug: null, fullName: 'Unknown', avatarUrl: null }, + role: m.role ?? null, + isAdmin: m.isAdmin === true, + via: opts.showVia ? (m.via ?? null) : null, + joinedAt: m.joinedAt ?? m.createdAt, }; } export function serializeProjectListItem( project: Project, opts: { - maintainer: Person | null; + /** `state = member` records only. */ memberships: ProjectMembership[]; memberPeople: Map<string, Person>; openHelpWantedCount: number; @@ -145,8 +158,13 @@ export function serializeProjectListItem( .map((ta) => opts.allTags.get(ta.tagId)) .filter((t): t is Tag => t !== undefined); - // First 10 members: maintainer first, then by fullName - const sortedMemberships = [...opts.memberships].sort(byMaintainerThenName(project, opts.memberPeople)); + // First 10 members: admins first, then role, then full name. + const sortedMemberships = [...opts.memberships].sort(compareMembers(opts.memberPeople)); + const admins = opts.memberships + .filter((m) => m.isAdmin) + .sort((a, b) => (a.joinedAt ?? '').localeCompare(b.joinedAt ?? '')) + .map((m) => serializePersonAvatar(opts.memberPeople.get(m.personSlug))) + .filter((a): a is PersonAvatar => a !== null); const members = sortedMemberships .slice(0, 10) @@ -162,7 +180,7 @@ export function serializeProjectListItem( summary: project.summary ?? null, stage: project.stage, overviewExcerpt, - maintainer: serializePersonAvatar(opts.maintainer), + admins, memberCount: opts.memberships.length, members, links: { @@ -179,9 +197,13 @@ export function serializeProjectListItem( export function serializeProjectDetail( project: Project, opts: { - maintainer: Person | null; + /** `state = member` records only. */ memberships: ProjectMembership[]; memberPeople: Map<string, Person>; + /** Show each member's `via` (project admins and staff). */ + showVia: boolean; + hasActiveAdmin: boolean; + viewer: ProjectViewer | null; openHelpWantedRoles: HelpWantedRole[]; helpWantedTags: Map<string, Tag[]>; tags: Tag[]; @@ -194,23 +216,9 @@ export function serializeProjectDetail( const tagsByNamespace = groupTagsByNamespace(opts.tags); - const memberships: ProjectMembershipResponse[] = opts.memberships - .sort(byMaintainerThenName(project, opts.memberPeople)) - .map((m) => { - const person = opts.memberPeople.get(m.personSlug); - return { - id: m.id, - projectSlug: project.slug, - person: serializePersonAvatar(person) ?? { - slug: null, - fullName: 'Unknown', - avatarUrl: null, - }, - role: m.role ?? null, - isMaintainer: m.isMaintainer, - joinedAt: m.joinedAt, - }; - }); + const memberships: ProjectMembershipResponse[] = [...opts.memberships] + .sort(compareMembers(opts.memberPeople)) + .map((m) => serializeProjectMembership(m, opts.memberPeople.get(m.personSlug), { showVia: opts.showVia })); const openHelpWantedRoles: HelpWantedRoleSummary[] = opts.openHelpWantedRoles.map((role) => { const roleTags = opts.helpWantedTags.get(role.id) ?? []; @@ -233,8 +241,9 @@ export function serializeProjectDetail( overviewHtml, stage: project.stage, stageProgress: stageProgress(project.stage), - maintainer: serializePersonAvatar(opts.maintainer), memberships, + hasActiveAdmin: opts.hasActiveAdmin, + viewer: opts.viewer, openHelpWantedRoles, tags: tagsByNamespace, links: { diff --git a/apps/api/src/store/memory/state.ts b/apps/api/src/store/memory/state.ts index 24c2529f..30348a9b 100644 --- a/apps/api/src/store/memory/state.ts +++ b/apps/api/src/store/memory/state.ts @@ -75,6 +75,12 @@ export interface InMemoryState { membershipsByProject: Map<string, Set<string>>; /** personSlug → Set<membershipId> */ membershipsByPerson: Map<string, Set<string>>; + /** + * projectSlug → Set<personSlug> of `member` records with `isAdmin` + * (specs/data-model.md → ProjectMembership): authorization and the + * active-admin check. + */ + adminsByProject: Map<string, Set<string>>; /** projectSlug → Set<updateId> */ updatesByProject: Map<string, Set<string>>; @@ -238,6 +244,7 @@ export function createEmptyState(): InMemoryState { tagIdByHandle: new Map(), membershipsByProject: new Map(), membershipsByPerson: new Map(), + adminsByProject: new Map(), updatesByProject: new Map(), updateByProjectAndNumber: new Map(), buzzByProject: new Map(), @@ -380,6 +387,7 @@ export function indexMembership(state: InMemoryState, m: ProjectMembership): voi state.projectMemberships.set(m.id, m); addToSet(state.membershipsByProject, m.projectSlug, m.id); addToSet(state.membershipsByPerson, m.personSlug, m.id); + if (m.state === 'member' && m.isAdmin) addToSet(state.adminsByProject, m.projectSlug, m.personSlug); } /** Add or replace a project update and update secondary indices. */ @@ -519,6 +527,7 @@ export function unindexMembership(state: InMemoryState, m: ProjectMembership): v state.projectMemberships.delete(m.id); removeFromSet(state.membershipsByProject, m.projectSlug, m.id); removeFromSet(state.membershipsByPerson, m.personSlug, m.id); + if (m.state === 'member' && m.isAdmin) removeFromSet(state.adminsByProject, m.projectSlug, m.personSlug); } export function unindexProjectUpdate(state: InMemoryState, update: ProjectUpdate): void { From 82101026786422ed2652812e20d1ec2d387cddf2 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:47:29 +0000 Subject: [PATCH 16/78] feat(moderation): admins and admin-chosen members block agent purges Agent purge rule 6 now refuses when the member is an admin of a project with other members, or holds a membership an admin chose (via added or application) on one; following or applying never blocks. A purge takes an older project with no createdById when the person is one of its admins, and only member records count as someone else touching a project. The moderation footprint lists memberships with isAdmin and via, members only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/src/services/agent-purge.ts | 38 ++++++++++++-------------- apps/api/src/services/moderation.ts | 23 ++++++++++++---- apps/api/src/services/project-purge.ts | 27 ++++++++++++------ 3 files changed, 53 insertions(+), 35 deletions(-) diff --git a/apps/api/src/services/agent-purge.ts b/apps/api/src/services/agent-purge.ts index 7a45bb30..bedfd906 100644 --- a/apps/api/src/services/agent-purge.ts +++ b/apps/api/src/services/agent-purge.ts @@ -34,6 +34,7 @@ import { agentTextProblem } from './agent-text.js'; import { validateFlags } from './moderation.js'; import { purgePeople } from './person-purge.js'; import { isTouchedByOthers, projectsCreatedBy, purgeableProjects } from './project-purge.js'; +import { membershipsOfPerson } from './memberships.js'; import { agentVotesOnAccount, hasHumanVote } from './votes.js'; /** Agent purge limits — specs/api/moderation.md → Agent purges. */ @@ -231,18 +232,26 @@ export class AgentPurgeService { if (profile?.lastSlackSsoAt) { throw new ConflictError('This member has signed into Slack; a person decides', 'established_member'); } - // 6. Nothing shared: no created project anyone else touched, no - // maintainership of a project with another member. A plain membership of - // someone else's project does not block. + // 6. Nothing shared: no created project anyone else touched; not an + // admin of a project with another member; no membership an admin chose + // (`via` added or application) on a project with another member. + // Following or applying to someone else's project does not block. for (const project of projectsCreatedBy(this.#state, [member])) { if (isTouchedByOthers(this.#state, project, [member])) { throw new ConflictError(`This member created '${project.slug}', which others have touched`, 'shared_project'); } } - for (const project of this.#maintained(member)) { - if (this.#hasOtherMember(project, member)) { - throw new ConflictError(`This member maintains '${project.slug}', which has other members`, 'shared_project'); - } + for (const m of membershipsOfPerson(this.#state, member.slug)) { + if (m.state !== 'member') continue; + const chosen = m.isAdmin || m.via === 'added' || m.via === 'application'; + const project = projectBySlug(this.#state, m.projectSlug); + if (!chosen || !project || !this.#hasOtherMember(project, member)) continue; + throw new ConflictError( + m.isAdmin + ? `This member is an admin of '${project.slug}', which has other members` + : `An admin chose this member for '${project.slug}', which has other members`, + 'shared_project', + ); } // 7. The evidence goes with the purge. const projects = purgeableProjects(this.#state, [member]); @@ -308,22 +317,11 @@ export class AgentPurgeService { }); } - /** Projects `member` maintains: by membership flag or as the project's maintainer. */ - #maintained(member: Person): Project[] { - const out = new Map<string, Project>(); - for (const p of this.#state.projects.values()) if (p.maintainerId === member.id) out.set(p.id, p); - for (const mid of this.#state.membershipsByPerson.get(member.slug) ?? []) { - const m = this.#state.projectMemberships.get(mid); - const p = m?.isMaintainer ? projectBySlug(this.#state, m.projectSlug) : undefined; - if (p) out.set(p.id, p); - } - return [...out.values()]; - } - + /** Another person holds a `member` record on the project. */ #hasOtherMember(project: Project, member: Person): boolean { for (const mid of this.#state.membershipsByProject.get(project.slug) ?? []) { const m = this.#state.projectMemberships.get(mid); - if (m && m.personSlug !== member.slug) return true; + if (m && m.state === 'member' && m.personSlug !== member.slug) return true; } return false; } diff --git a/apps/api/src/services/moderation.ts b/apps/api/src/services/moderation.ts index fccec0d8..94f7c4e1 100644 --- a/apps/api/src/services/moderation.ts +++ b/apps/api/src/services/moderation.ts @@ -10,6 +10,7 @@ * vote is staged and fenced by the rules in moderation.md → Agent votes. */ import { spamPurgeDueAt } from './spam-purge.js'; +import { membershipsOfPerson } from './memberships.js'; import { agentVotesOnAccount, hasHumanVote, @@ -96,6 +97,7 @@ export interface EarlierPurgeView { } export interface FootprintCounts { + /** Records in state `member`. */ readonly memberships: number; readonly updates: number; readonly buzz: number; @@ -156,7 +158,13 @@ export interface ProjectRef { } export interface MemberFootprint { - readonly memberships: Array<{ project: ProjectRef; role: string; joinedAt: string }>; + readonly memberships: Array<{ + project: ProjectRef; + role: string | null; + isAdmin: boolean; + via: string | null; + joinedAt: string; + }>; readonly updates: Array<{ project: ProjectRef; number: number; title: string; postedAt: string }>; readonly buzz: Array<{ project: ProjectRef; slug: string; title: string; postedAt: string }>; readonly blogPosts: Array<{ slug: string; title: string; postedAt: string }>; @@ -556,7 +564,7 @@ export class ModerationService { ? { type: profile.emailBounce.type, bouncedAt: profile.emailBounce.bouncedAt } : null; const footprint: FootprintCounts = { - memberships: this.#state.membershipsByPerson.get(p.slug)?.size ?? 0, + memberships: membershipsOfPerson(this.#state, p.slug).filter((m) => m.state === 'member').length, updates: authored.updates.get(p.id) ?? 0, buzz: authored.buzz.get(p.id) ?? 0, blogPosts: authored.blogPosts.get(p.id) ?? 0, @@ -613,11 +621,14 @@ export class ModerationService { return project ? { slug: project.slug, title: project.title } : null; }; - const memberships = [...(s.membershipsByPerson.get(slug) ?? [])] - .map((mid) => s.projectMemberships.get(mid)) + const records = membershipsOfPerson(s, slug); + const memberships = records + .filter((m) => m.state === 'member') .flatMap((m) => { - const project = m ? projectRef(m.projectSlug) : null; - return m && project ? [{ project, role: m.role ?? (m.isMaintainer ? 'maintainer' : 'member'), joinedAt: m.joinedAt }] : []; + const project = projectRef(m.projectSlug); + return project + ? [{ project, role: m.role ?? null, isAdmin: m.isAdmin, via: m.via ?? null, joinedAt: m.joinedAt ?? m.createdAt }] + : []; }); const updates = [...s.projectUpdates.values()] diff --git a/apps/api/src/services/project-purge.ts b/apps/api/src/services/project-purge.ts index d503910d..60c21ca3 100644 --- a/apps/api/src/services/project-purge.ts +++ b/apps/api/src/services/project-purge.ts @@ -1,6 +1,6 @@ /** * The projects a person purge takes with it — specs/behaviors/person-lifecycle.md - * → Purge: projects the person created (`createdById`, or `maintainerId` when + * → Purge: projects the person created (`createdById`, or being one of its admins when * a project has no `createdById`) that nobody else touched, deleted with * everything that hangs off them. */ @@ -24,18 +24,27 @@ function batchOf(people: readonly Person[]): Batch { return { ids: new Set(people.map((p) => p.id)), slugs: new Set(people.map((p) => p.slug)) }; } -/** Whether someone in the batch created `project` — the field, else the maintainer for older records. */ -function createdBy(project: Project, batch: Batch): boolean { - const creator = project.createdById ?? project.maintainerId; - return !!creator && batch.ids.has(creator); +/** + * Whether someone in the batch created `project`: the field, else (for laddr + * imports and older records) someone in the batch is one of its admins. + */ +function createdBy(state: InMemoryState, project: Project, batch: Batch): boolean { + if (project.createdById) return batch.ids.has(project.createdById); + for (const slug of state.adminsByProject.get(project.slug) ?? []) { + if (batch.slugs.has(slug)) return true; + } + return false; } /** Whether anyone outside the batch has a record on `project`. */ function touchedByOthers(state: InMemoryState, project: Project, batch: Batch): boolean { const outsiderSlug = (slug: string | undefined) => !slug || !batch.slugs.has(slug); const outsiderId = (id: string | null | undefined) => !id || !batch.ids.has(id); + // Only members touch a project: other people's follows and applications + // are one-click acts and never shield it (person-lifecycle.md → Purge). for (const id of idsIn(state.membershipsByProject, project.slug)) { - if (outsiderSlug(state.projectMemberships.get(id)?.personSlug)) return true; + const m = state.projectMemberships.get(id); + if (m && m.state === 'member' && outsiderSlug(m.personSlug)) return true; } for (const id of idsIn(state.updatesByProject, project.slug)) { if (outsiderId(state.projectUpdates.get(id)?.authorId)) return true; @@ -55,10 +64,10 @@ function touchedByOthers(state: InMemoryState, project: Project, batch: Batch): return false; } -/** Projects someone in `people` created (the field, else the maintainer for older records). */ +/** Projects someone in `people` created (the field, else an admin for older records). */ export function projectsCreatedBy(state: InMemoryState, people: readonly Person[]): Project[] { const batch = batchOf(people); - return [...state.projects.values()].filter((p) => createdBy(p, batch)); + return [...state.projects.values()].filter((p) => createdBy(state, p, batch)); } /** Whether anyone outside `people` has a record on `project`. */ @@ -70,7 +79,7 @@ export function isTouchedByOthers(state: InMemoryState, project: Project, people export function purgeableProjects(state: InMemoryState, people: readonly Person[]): Project[] { const batch = batchOf(people); return [...state.projects.values()] - .filter((p) => createdBy(p, batch) && !touchedByOthers(state, p, batch)) + .filter((p) => createdBy(state, p, batch) && !touchedByOthers(state, p, batch)) .sort((a, b) => a.title.localeCompare(b.title)); } From baaa4055c37f297ba9dcdb0a1dd7fe8867e1ebae Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:47:29 +0000 Subject: [PATCH 17/78] feat(api): migrate single maintainers to project admins scripts/migrations/202611290000-project-admins.ts rewrites every membership to state member, via legacy, and makes it an admin when it was isMaintainer or its person was the project's maintainerId; both old fields go. One tree write, one commit, a no-op on a second run, counts only in its output. Run it while the sheets still declare v2, then adopt the v3 contracts. The laddr importer writes the same shape. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/package.json | 3 +- apps/api/scripts/import-laddr/translators.ts | 14 +- .../migrations/202611290000-project-admins.ts | 267 ++++++++++++++++++ 3 files changed, 278 insertions(+), 6 deletions(-) create mode 100644 apps/api/scripts/migrations/202611290000-project-admins.ts diff --git a/apps/api/package.json b/apps/api/package.json index ba6f4d8d..5c198167 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -18,7 +18,8 @@ "script:cutover-mailout": "tsx scripts/cutover-mailout.ts", "script:prune-spam": "tsx scripts/prune-spam.ts", "check:sheet-configs": "tsx scripts/check-sheet-configs.ts", - "script:migrate-slug-references": "tsx scripts/migrations/202610150400-slug-references.ts" + "script:migrate-slug-references": "tsx scripts/migrations/202610150400-slug-references.ts", + "script:migrate-project-admins": "tsx scripts/migrations/202611290000-project-admins.ts" }, "dependencies": { "@aws-sdk/client-s3": "^3.1048.0", diff --git a/apps/api/scripts/import-laddr/translators.ts b/apps/api/scripts/import-laddr/translators.ts index 877df097..6ebe4839 100644 --- a/apps/api/scripts/import-laddr/translators.ts +++ b/apps/api/scripts/import-laddr/translators.ts @@ -447,7 +447,6 @@ export function translateProject(row: RawProject, ctx: TranslateCtx): Project { title, overview: nonEmptyStr(row.README) ?? undefined, stage: normalizeStage(nonEmptyStr(row.Stage), ctx.warnings, legacyId), - maintainerId: maintainerId ?? undefined, usersUrl: validHttps(nonEmptyStr(row.UsersUrl)) ?? undefined, developersUrl: validHttps(nonEmptyStr(row.DevelopersUrl)) ?? undefined, chatChannel: normalizeChatChannel(nonEmptyStr(row.ChatChannel)) ?? undefined, @@ -504,8 +503,8 @@ export interface MembershipResult { /** * Translate a project-membership row. `projectMaintainerLegacyId` is the - * project's `MaintainerID` so we can denormalize `isMaintainer` per the data - * model (`ProjectMembership.isMaintainer == (Project.maintainerId == personId)`). + * project's laddr `MaintainerID`: that person's membership becomes a project + * admin (specs/data-model.md → ProjectMembership). */ export function translateMembership( row: RawMembership, @@ -525,15 +524,20 @@ export function translateMembership( const joinedAt = epochToIsoOr(row.Created, ctx.now); const role = nonEmptyStr(row.Role); - const isMaintainer = projectMaintainerLegacyId === personLegacyId; + // laddr's maintainer becomes a project admin (specs/behaviors/project-membership.md + // → Migration from single maintainers); every laddr membership is a member. + const isAdmin = projectMaintainerLegacyId === personLegacyId; return { membership: { id: idFor(ctx, `project-memberships/${projectLegacyId}-${personLegacyId}`), projectSlug, personSlug, + state: 'member', + isAdmin, role: role ?? undefined, - isMaintainer, + via: 'legacy', + followedAt: joinedAt, joinedAt, createdAt: joinedAt, updatedAt: joinedAt, diff --git a/apps/api/scripts/migrations/202611290000-project-admins.ts b/apps/api/scripts/migrations/202611290000-project-admins.ts new file mode 100644 index 00000000..a23cecfa --- /dev/null +++ b/apps/api/scripts/migrations/202611290000-project-admins.ts @@ -0,0 +1,267 @@ +/** + * Migration: single maintainers → project admins on one membership record + * (plans/membership-admins.md, specs/behaviors/project-membership.md → + * Migration from single maintainers). + * + * project-memberships every record → state = member, via = legacy, + * followedAt = joinedAt; isAdmin = isMaintainer OR the + * person is the project's maintainerId; isMaintainer + * removed. role and joinedAt kept. + * projects maintainerId removed. + * + * A project whose maintainerId names a person with no membership gets no + * membership from it; if no other admin results, it has no admin until + * staff add one. + * + * One tree write, one commit on `--branch`. Re-running is a no-op (no + * commit). It prints counts only, never names. + * + * Order at deploy: run this on a branch whose sheets still declare the v2 + * contracts (the rewritten records satisfy v2, which is open for extension + * and only requires what members keep), THEN adopt the v3 contracts with + * `gitsheets contracts adopt --sheet …`, which validates every record. + * Adopting v3 first fails: v2-shape records lack `state` and `followedAt`. + * Running it after adoption also works (the records it writes satisfy v3). + * + * Usage: + * npm run -w apps/api script:migrate-project-admins -- \ + * --data-repo=/path/to/codeforphilly-data.git --branch=fixture [--dry-run] + * + * --data-repo Bare clone of the data repo. Falls back to $CFP_DATA_REPO_PATH. + * --branch Branch to migrate (required). Must exist locally. + * --dry-run Count and report without committing. + */ +import { resolve } from 'node:path'; + +import { ProjectMembershipSchema } from '@cfp/shared/schemas'; +import { openRepo } from 'gitsheets'; + +const AUTHOR = { name: 'Code for Philly API', email: 'api@users.noreply.codeforphilly.org' }; + +type Rec = Record<string, unknown>; + +export interface MigrateAdminsOptions { + readonly dataRepo: string; + readonly branch: string; + readonly dryRun?: boolean; +} + +export interface MigrateAdminsResult { + /** Membership records rewritten (0 on a re-run). */ + readonly membershipsMigrated: number; + /** Memberships that are admins after the run. */ + readonly admins: number; + /** Projects rewritten to drop `maintainerId` (0 on a re-run). */ + readonly projectsMigrated: number; + /** Live projects with no admin after the run. */ + readonly projectsWithoutAdmin: number; + /** The migration commit, or null for a dry run or a no-op. */ + readonly commitHash: string | null; +} + +export class MigrationError extends Error { + constructor( + message: string, + readonly problems: readonly string[], + ) { + super(`${message}:\n${problems.map((p) => ` - ${p}`).join('\n')}`); + this.name = 'MigrationError'; + } +} + +interface TxSheet { + query(): AsyncIterable<Rec>; + upsert(record: Rec): Promise<unknown>; +} + +async function readAll(sheet: TxSheet): Promise<Rec[]> { + const out: Rec[] = []; + for await (const r of sheet.query()) out.push(Object.fromEntries(Object.entries(r))); + return out; +} + +function sameRecord(a: Rec, b: Rec): boolean { + const keys = new Set([...Object.keys(a), ...Object.keys(b)]); + for (const k of keys) { + if (JSON.stringify(a[k]) !== JSON.stringify(b[k])) return false; + } + return true; +} + +const str = (v: unknown): string | undefined => (typeof v === 'string' && v !== '' ? v : undefined); + +/** + * One membership in the v3 shape. Pure. A record already in the new shape + * (it has a `state`) keeps its state and fields; only a leftover + * `isMaintainer` is folded in. + */ +export function migrateMembership(record: Rec, maintainerSlugOfProject: ReadonlyMap<string, string>): Rec { + const next: Rec = { ...record }; + const projectSlug = str(record['projectSlug']); + const personSlug = str(record['personSlug']); + const wasMaintainer = + record['isMaintainer'] === true || + (projectSlug !== undefined && personSlug !== undefined && maintainerSlugOfProject.get(projectSlug) === personSlug); + delete next['isMaintainer']; + + if (str(record['state']) === undefined) { + next['state'] = 'member'; + next['via'] = 'legacy'; + next['followedAt'] = str(record['joinedAt']) ?? str(record['createdAt']); + next['isAdmin'] = wasMaintainer || record['isAdmin'] === true; + } else if (wasMaintainer && next['state'] === 'member') { + next['isAdmin'] = true; + } + if (next['muted'] === undefined) next['muted'] = false; + if (next['isAdmin'] === undefined) next['isAdmin'] = false; + return next; +} + +export async function migrateProjectAdmins(opts: MigrateAdminsOptions): Promise<MigrateAdminsResult> { + const repo = await openRepo({ gitDir: opts.dataRepo }); + const ref = `refs/heads/${opts.branch}`; + if ((await repo.resolveRef(ref)) === null) { + throw new Error(`branch '${opts.branch}' not found in ${opts.dataRepo}`); + } + + let membershipsMigrated = 0; + let projectsMigrated = 0; + let admins = 0; + let projectsWithoutAdmin = 0; + let wrote = false; + + const result = await repo.transact( + { + parent: ref, + branch: ref, + message: + 'migrate: single maintainers become project admins\n\n' + + 'Every project membership becomes state = member, via = legacy; a\n' + + 'membership is an admin when it was isMaintainer or its person was the\n' + + "project's maintainerId. isMaintainer and maintainerId are removed\n" + + '(codeforphilly-ng plans/membership-admins.md).\n', + author: AUTHOR, + trailers: { Action: 'migrate.project-admins' }, + }, + async (tx) => { + const sheetOf = (name: string): TxSheet => tx.sheet(name) as unknown as TxSheet; + const people = await readAll(sheetOf('people')); + const projects = await readAll(sheetOf('projects')); + const memberships = await readAll(sheetOf('project-memberships')); + + const slugByPersonId = new Map<string, string>(); + for (const p of people) { + const id = str(p['id']); + const slug = str(p['slug']); + if (id && slug) slugByPersonId.set(id, slug); + } + const maintainerSlugOfProject = new Map<string, string>(); + for (const p of projects) { + const slug = str(p['slug']); + const maintainer = str(p['maintainerId']); + const personSlug = maintainer ? slugByPersonId.get(maintainer) : undefined; + if (slug && personSlug) maintainerSlugOfProject.set(slug, personSlug); + } + + // Plan every rewrite; write nothing unless every result is valid. + const problems: string[] = []; + const plan: Array<{ sheet: string; next: Rec }> = []; + const adminProjects = new Set<string>(); + for (const record of memberships) { + const next = migrateMembership(record, maintainerSlugOfProject); + const parsed = ProjectMembershipSchema.safeParse(next); + if (!parsed.success) { + problems.push( + `project-memberships/${String(record['projectSlug'])}/${String(record['personSlug'])}: ` + + parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; '), + ); + continue; + } + if (next['isAdmin'] === true) { + admins += 1; + adminProjects.add(String(next['projectSlug'])); + } + if (!sameRecord(record, next)) plan.push({ sheet: 'project-memberships', next }); + } + for (const record of projects) { + if (!('maintainerId' in record)) continue; + const next = { ...record }; + delete next['maintainerId']; + plan.push({ sheet: 'projects', next }); + } + for (const p of projects) { + if (!p['deletedAt'] && !adminProjects.has(String(p['slug']))) projectsWithoutAdmin += 1; + } + if (problems.length > 0) { + throw new MigrationError(`${problems.length} record(s) would not be valid; nothing written`, problems); + } + + for (const { sheet, next } of plan) { + if (sheet === 'projects') projectsMigrated += 1; + else membershipsMigrated += 1; + if (!opts.dryRun) await sheetOf(sheet).upsert(next); + } + wrote = !opts.dryRun && plan.length > 0; + }, + ); + + return { + membershipsMigrated, + admins, + projectsMigrated, + projectsWithoutAdmin, + commitHash: wrote ? result.commitHash : null, + }; +} + +// --------------------------------------------------------------------------- +// CLI +// --------------------------------------------------------------------------- + +function parseArgs(argv: readonly string[]): MigrateAdminsOptions { + const opts: Record<string, string | true> = {}; + for (const a of argv) { + if (!a.startsWith('--')) continue; + const eq = a.indexOf('='); + if (eq === -1) opts[a.slice(2)] = true; + else opts[a.slice(2, eq)] = a.slice(eq + 1); + } + const dataRepo = + typeof opts['data-repo'] === 'string' && opts['data-repo'] !== '' + ? opts['data-repo'] + : process.env['CFP_DATA_REPO_PATH']; + if (!dataRepo) { + process.stderr.write('missing --data-repo=<path> (or set CFP_DATA_REPO_PATH)\n'); + process.exit(2); + } + const branch = opts['branch']; + if (typeof branch !== 'string' || branch === '') { + process.stderr.write('missing --branch=<name>\n'); + process.exit(2); + } + return { dataRepo: resolve(dataRepo), branch, dryRun: opts['dry-run'] === true }; +} + +async function main(): Promise<void> { + const args = parseArgs(process.argv.slice(2)); + console.log(`[migrate] ${args.dataRepo} ${args.branch}${args.dryRun ? ' (dry run)' : ''}`); + const r = await migrateProjectAdmins(args); + console.log(` memberships migrated ${r.membershipsMigrated}`); + console.log(` admins ${r.admins}`); + console.log(` projects migrated ${r.projectsMigrated}`); + console.log(` projects with no admin ${r.projectsWithoutAdmin}`); + if (args.dryRun) console.log('(dry run: nothing written)'); + else if (r.commitHash) console.log(`commit: ${r.commitHash} on ${args.branch}`); + else console.log('(no changes: already migrated)'); +} + +const isMain = + process.argv[1] !== undefined && + import.meta.url.endsWith(process.argv[1].replace(/\\/g, '/')); + +if (isMain) { + main().catch((err: unknown) => { + console.error(err instanceof Error ? err.message : err); + process.exit(1); + }); +} From 8f2b77a95ecf6dde20497e86edaf2e0c9b4cf869 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:47:29 +0000 Subject: [PATCH 18/78] test(api): cover admin transitions, the last-admin rule and the migration Fixtures move to the v3 membership shape. New tests cover who may add, promote, demote, relabel, remove and leave, the last-admin confirmation, the 410s, members-only read shapes, the founder membership, agent purge rule 6 for an admin-added member and a follower, the merge keeping the record further along, and the migration against old-shape fixtures, idempotent and in deploy order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/tests/account-claim.test.ts | 41 +++ apps/api/tests/agent-purge.test.ts | 33 +- apps/api/tests/helpers/seed-fixtures.ts | 6 +- .../tests/migration-project-admins.test.ts | 164 +++++++++ .../tests/migration-slug-references.test.ts | 6 +- apps/api/tests/people-lifecycle.test.ts | 29 +- apps/api/tests/project-filters.test.ts | 1 - apps/api/tests/project-membership.test.ts | 338 ++++++++++++++++++ apps/api/tests/prune-spam.test.ts | 4 +- apps/api/tests/reload-swap.test.ts | 3 +- apps/api/tests/scrub-data.test.ts | 2 +- apps/api/tests/spam-purge.test.ts | 5 +- apps/api/tests/write-api.test.ts | 18 +- packages/shared/tests/schemas.test.ts | 3 +- 14 files changed, 610 insertions(+), 43 deletions(-) create mode 100644 apps/api/tests/migration-project-admins.test.ts create mode 100644 apps/api/tests/project-membership.test.ts diff --git a/apps/api/tests/account-claim.test.ts b/apps/api/tests/account-claim.test.ts index fe9ee23c..7ed2b88f 100644 --- a/apps/api/tests/account-claim.test.ts +++ b/apps/api/tests/account-claim.test.ts @@ -71,6 +71,10 @@ async function seedPerson( await seedRawToml(repoDir, `people/${slug}.toml`, lines.join('\n'), `seed person ${slug}`); } +function mergeProjectId(slug: string): string { + return slug === 'merge-one' ? '01951a3c-0000-7000-8000-0000ddddddd1' : '01951a3c-0000-7000-8000-0000ddddddd2'; +} + async function seedPrivateProfile( privatePath: string, personId: string, @@ -640,6 +644,31 @@ describe('Post-onboarding /account-claim/legacy search + merge approval', () => githubLinkedAt: '2026-04-01T00:00:00Z', }); await seedPrivateProfile(privateStore.path, staffId, 'staff2@example.com'); + // Both people hold a record on the same two projects: the merge keeps + // the one further along on each (specs/behaviors/account-migration.md). + for (const slug of ['merge-one', 'merge-two']) { + await seedRawToml( + dataRepo.path, + `projects/${slug}.toml`, + [`id = "${mergeProjectId(slug)}"`, `slug = "${slug}"`, `title = "${slug}"`, `stage = "commenting"`, + `createdAt = "2026-05-01T00:00:00Z"`, `updatedAt = "2026-05-01T00:00:00Z"`].join('\n'), + `seed ${slug}`, + ); + } + const record = (n: number, project: string, person: string, fields: string[]) => + seedRawToml( + dataRepo.path, + `project-memberships/${project}/${person}.toml`, + [`id = "01951a3c-0000-7000-8000-0000eeeeee0${n}"`, `projectSlug = "${project}"`, `personSlug = "${person}"`, + `followedAt = "2026-05-01T00:00:00Z"`, `createdAt = "2026-05-01T00:00:00Z"`, `updatedAt = "2026-05-01T00:00:00Z"`, + ...fields].join('\n'), + `seed ${project}/${person}`, + ); + const member = (admin: boolean) => [`state = "member"`, `isAdmin = ${admin}`, `via = "legacy"`, `joinedAt = "2026-05-01T00:00:00Z"`]; + await record(1, 'merge-one', 'legacy-old', [`state = "follower"`]); + await record(2, 'merge-one', 'fresh-new', member(false)); + await record(3, 'merge-two', 'legacy-old', member(true)); + await record(4, 'merge-two', 'fresh-new', member(false)); app = await buildTestApp(dataRepo.path, privateStore.path); }, 60_000); @@ -729,6 +758,18 @@ describe('Post-onboarding /account-claim/legacy search + merge approval', () => const history = await app.store.public['slug-history'].get('person/fresh-new'); expect(history?.oldSlug).toBe('fresh-new'); expect(history?.newSlug).toBe('legacy-old'); + + // One record per project survives, the one further along. + const records = (project: string) => + [...(app.inMemoryState.membershipsByProject.get(project) ?? [])].map((id) => app.inMemoryState.projectMemberships.get(id)!); + const one = records('merge-one'); + expect(one).toHaveLength(1); + expect(one[0]).toMatchObject({ personSlug: 'legacy-old', state: 'member', id: '01951a3c-0000-7000-8000-0000eeeeee02' }); + const two = records('merge-two'); + expect(two).toHaveLength(1); + expect(two[0]).toMatchObject({ personSlug: 'legacy-old', state: 'member', isAdmin: true }); + expect([...(app.inMemoryState.adminsByProject.get('merge-two') ?? [])]).toEqual(['legacy-old']); + await expect(app.store.public['project-memberships'].get('merge-one/fresh-new')).resolves.toBeFalsy(); }); }); diff --git a/apps/api/tests/agent-purge.test.ts b/apps/api/tests/agent-purge.test.ts index c1b4d7ba..c618fd4a 100644 --- a/apps/api/tests/agent-purge.test.ts +++ b/apps/api/tests/agent-purge.test.ts @@ -43,6 +43,7 @@ const N = { rolePoster: 19, imported: 20, ownProject: 21, + addedAnn: 22, }; const BURST = 40; const GH_ID = 987_654; @@ -51,16 +52,28 @@ const NOW_ISO = new Date().toISOString(); const ROLE_ID = fid(700); const AVATAR = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10]); -const membership = (n: number, projectSlug: string, personSlug: string, isMaintainer = false): Rec => ({ +const membership = (n: number, projectSlug: string, personSlug: string, isAdmin = false, via = 'legacy'): Rec => ({ id: fid(n), projectSlug, personSlug, - role: isMaintainer ? 'Maintainer' : 'Member', - isMaintainer, + state: 'member', + isAdmin, + role: isAdmin ? 'Admin' : 'Member', + via, + followedAt: minutesAgo(1), joinedAt: minutesAgo(1), createdAt: minutesAgo(1), updatedAt: minutesAgo(1), }); +const follow = (n: number, projectSlug: string, personSlug: string): Rec => ({ + id: fid(n), + projectSlug, + personSlug, + state: 'follower', + followedAt: minutesAgo(1), + createdAt: minutesAgo(1), + updatedAt: minutesAgo(1), +}); const project = (n: number, slug: string, creator: number, over: Rec = {}): Rec => ({ id: fid(n), slug, @@ -68,7 +81,6 @@ const project = (n: number, slug: string, creator: number, over: Rec = {}): Rec summary: `Summary of ${slug}`, stage: 'commenting', createdById: fid(creator), - maintainerId: fid(creator), createdAt: daysAgo(30), updatedAt: daysAgo(30), ...over, @@ -109,6 +121,7 @@ describe('agent purge', () => { personRecord(N.rolePoster, 'role-poster', { createdAt: daysAgo(1), ...bio }), personRecord(N.imported, 'imported', { createdAt: daysAgo(1), legacyId: 1234, ...bio }), personRecord(N.ownProject, 'own-project', { createdAt: daysAgo(1) }), + personRecord(N.addedAnn, 'added-ann', { createdAt: daysAgo(1), ...bio }), ...Array.from({ length: 6 }, (_, i) => personRecord(BURST + i, `burst-${i}`, { createdAt: minutesAgo(5), ...bio })), ], projects: [ @@ -119,7 +132,10 @@ describe('agent purge', () => { 'project-memberships': [ membership(600, 'real-project', 'maintainer-mae', true), membership(601, 'real-project', 'helper-hal'), - membership(602, 'real-project', 'site-name'), + // A spam account following a real project: no one else's judgment. + follow(602, 'real-project', 'site-name'), + // An admin chose this member: a purge would overrule them. + membership(608, 'real-project', 'added-ann', false, 'added'), membership(603, 'shared-proj', 'shared-creator', true), membership(604, 'shared-proj', 'helper-hal'), membership(605, 'real-project', 'co-maintainer', true), @@ -363,7 +379,7 @@ describe('agent purge', () => { }); }); - describe('case 2: a site name that self-joined a real project', () => { + describe('case 2: a site name that followed a real project', () => { it('purges them and their own records; the project and everyone else stay', async () => { const res = await purge('site-name', { reason: 'Site name as member name; bio advertises a streaming service.', @@ -375,7 +391,7 @@ describe('agent purge', () => { expect(state.personIdBySlug.has('site-name')).toBe(false); expect(state.projectIdBySlug.has('real-project')).toBe(true); const left = [...(state.membershipsByProject.get('real-project') ?? [])].map((m) => state.projectMemberships.get(m)!.personSlug).sort(); - expect(left).toEqual(['co-maintainer', 'helper-hal', 'maintainer-mae', 'role-poster']); + expect(left).toEqual(['added-ann', 'co-maintainer', 'helper-hal', 'maintainer-mae', 'role-poster']); expect(state.updateByProjectAndNumber.has('real-project:1')).toBe(true); expect(state.updateByProjectAndNumber.has('real-project:2')).toBe(false); const msg = await env.git('log', '-1', '--format=%B'); @@ -429,9 +445,10 @@ describe('agent purge', () => { await refused('slacker', payload, 409, 'established_member'); }); - it('rule 6: created a project someone else joined, or maintains one with other members (409 shared_project)', async () => { + it('rule 6: created a project someone else joined, admins one with other members, or was chosen by an admin (409 shared_project)', async () => { await refused('shared-creator', payload, 409, 'shared_project'); await refused('co-maintainer', payload, 409, 'shared_project'); + await refused('added-ann', payload, 409, 'shared_project'); }); it('evidence that is empty or not theirs (422 evidence_invalid)', async () => { diff --git a/apps/api/tests/helpers/seed-fixtures.ts b/apps/api/tests/helpers/seed-fixtures.ts index 9b606239..ef7eca93 100644 --- a/apps/api/tests/helpers/seed-fixtures.ts +++ b/apps/api/tests/helpers/seed-fixtures.ts @@ -161,7 +161,6 @@ export async function seedFixtures(repoPath: string): Promise<SeededFixtures> { summary: 'Realtime community events without Facebook.', overview: '## Overview\n\nSquadQuest is a civic app.', stage: 'testing', - maintainerId: personId, featured: false, createdAt: NOW, updatedAt: NOW2, @@ -200,8 +199,11 @@ export async function seedFixtures(repoPath: string): Promise<SeededFixtures> { id: membershipId, projectSlug, personSlug, + state: 'member', + isAdmin: true, role: 'Founder', - isMaintainer: true, + via: 'legacy', + followedAt: NOW, joinedAt: NOW, createdAt: NOW, updatedAt: NOW, diff --git a/apps/api/tests/migration-project-admins.test.ts b/apps/api/tests/migration-project-admins.test.ts new file mode 100644 index 00000000..a62afb8c --- /dev/null +++ b/apps/api/tests/migration-project-admins.test.ts @@ -0,0 +1,164 @@ +/** + * Migration: single maintainers → project admins + * (scripts/migrations/202611290000-project-admins.ts). + * + * Fixtures are old-shape records (isMaintainer on memberships, maintainerId + * on projects) committed as raw TOML on a repo whose sheet configs declare + * the current contracts. People are made up. + */ +import { execFile } from 'node:child_process'; +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { promisify } from 'node:util'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { migrateProjectAdmins } from '../scripts/migrations/202611290000-project-admins.js'; +import { loadInMemoryState } from '../src/store/memory/loader.js'; +import { openPublicStore } from '../src/store/public.js'; +import { createFullDataRepo } from './helpers/test-full-repo.js'; + +const exec = promisify(execFile); +const GITSHEETS_CLI = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', 'node_modules', '.bin', 'gitsheets'); + +const NOW = '2026-05-15T18:42:00Z'; +const id = (n: number): string => `01951a3c-0000-7000-8000-${String(n).padStart(12, '0')}`; +const PEOPLE = { alice: id(1), bob: id(2), carol: id(3), dave: id(4), erin: id(5) }; +const PROJECTS = { alpha: id(10), beta: id(11) }; + +let data: { path: string; cleanup: () => Promise<void> }; + +async function git(...args: string[]): Promise<string> { + return (await exec('git', ['--git-dir', data.path, ...args])).stdout.trim(); +} + +const toml = (fields: Record<string, string | number | boolean>): string => + `${Object.entries(fields) + .map(([k, v]) => `${k} = ${typeof v === 'string' ? JSON.stringify(v) : String(v)}`) + .join('\n')}\n`; + +async function seedFiles(files: Record<string, string>): Promise<void> { + const wt = await mkdtemp(join(tmpdir(), 'cfp-migrate-admins-')); + try { + const run = (...args: string[]) => exec('git', args, { cwd: wt }); + await exec('git', ['clone', '--no-local', data.path, wt]); + await run('config', 'user.email', 'test@example.org'); + await run('config', 'user.name', 'cfp test'); + await run('config', 'commit.gpgsign', 'false'); + await run('config', 'core.hooksPath', '/dev/null'); + for (const [rel, content] of Object.entries(files)) { + await mkdir(dirname(join(wt, rel)), { recursive: true }); + await writeFile(join(wt, rel), content); + await run('add', rel); + } + await run('commit', '-m', 'seed old-shape records'); + await run('push', 'origin', 'main'); + } finally { + await rm(wt, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); + } +} + +const membership = (n: number, project: string, person: string, extra: Record<string, string | boolean> = {}) => + toml({ id: id(n), projectSlug: project, personSlug: person, joinedAt: NOW, createdAt: NOW, updatedAt: NOW, ...extra }); + +/** + * alpha: maintainerId = alice (her flag is false), bob isMaintainer, carol plain. + * beta: maintainerId = dave, who has no membership; erin plain → no admin. + */ +async function seedOldShape(): Promise<void> { + const files: Record<string, string> = {}; + for (const [slug, pid] of Object.entries(PEOPLE)) { + files[`people/${slug}.toml`] = toml({ id: pid, slug, fullName: slug, accountLevel: 'user', createdAt: NOW, updatedAt: NOW }); + } + files['projects/alpha.toml'] = toml({ + id: PROJECTS.alpha, slug: 'alpha', title: 'Alpha', stage: 'testing', featured: false, + maintainerId: PEOPLE.alice, createdAt: NOW, updatedAt: NOW, + }); + files['projects/beta.toml'] = toml({ + id: PROJECTS.beta, slug: 'beta', title: 'Beta', stage: 'testing', featured: false, + maintainerId: PEOPLE.dave, createdAt: NOW, updatedAt: NOW, + }); + files['project-memberships/alpha/alice.toml'] = membership(20, 'alpha', 'alice', { isMaintainer: false, role: 'Founder' }); + files['project-memberships/alpha/bob.toml'] = membership(21, 'alpha', 'bob', { isMaintainer: true }); + files['project-memberships/alpha/carol.toml'] = membership(22, 'alpha', 'carol', { role: 'Designer' }); + files['project-memberships/beta/erin.toml'] = membership(23, 'beta', 'erin', { isMaintainer: false }); + await seedFiles(files); +} + +beforeEach(async () => { + data = await createFullDataRepo(); + await seedOldShape(); +}); + +afterEach(async () => { + await data.cleanup(); +}); + +describe('project-admins migration', () => { + it('makes every membership a legacy member and admins from isMaintainer ∪ maintainerId', async () => { + const result = await migrateProjectAdmins({ dataRepo: data.path, branch: 'main' }); + expect(result).toMatchObject({ membershipsMigrated: 4, admins: 2, projectsMigrated: 2, projectsWithoutAdmin: 1 }); + expect(result.commitHash).toBe(await git('rev-parse', 'main')); + expect(await git('log', '-1', '--format=%B', 'main')).toContain('Action: migrate.project-admins'); + + for (const path of ['alpha/alice', 'alpha/bob', 'alpha/carol', 'beta/erin']) { + const rec = await git('show', `main:project-memberships/${path}.toml`); + expect(rec, path).toContain('state = "member"'); + expect(rec, path).toContain('via = "legacy"'); + expect(rec, path).toContain(`followedAt = "${NOW}"`); + expect(rec, path).toContain(`joinedAt = "${NOW}"`); + expect(rec, path).not.toContain('isMaintainer'); + } + expect(await git('show', 'main:project-memberships/alpha/alice.toml')).toContain('role = "Founder"'); + expect(await git('show', 'main:project-memberships/alpha/carol.toml')).toContain('role = "Designer"'); + for (const slug of ['alpha', 'beta']) { + expect(await git('show', `main:projects/${slug}.toml`)).not.toContain('maintainerId'); + } + // dave named by maintainerId but had no membership: none is created. + await expect(git('show', 'main:project-memberships/beta/dave.toml')).rejects.toThrow(); + + const { store } = await openPublicStore(data.path); + const state = await loadInMemoryState(store); + expect([...(state.adminsByProject.get('alpha') ?? [])].sort()).toEqual(['alice', 'bob']); + expect(state.adminsByProject.get('beta')).toBeUndefined(); + + // gitsheets' own conformance gate agrees with the v3 contracts. + await exec(GITSHEETS_CLI, ['contracts', 'verify', '--git-dir', data.path, '--ref', 'main']); + }); + + it('is idempotent: a second run makes no commit', async () => { + const first = await migrateProjectAdmins({ dataRepo: data.path, branch: 'main' }); + const second = await migrateProjectAdmins({ dataRepo: data.path, branch: 'main' }); + expect(second.commitHash).toBeNull(); + expect(second).toMatchObject({ membershipsMigrated: 0, projectsMigrated: 0, admins: 2, projectsWithoutAdmin: 1 }); + expect(await git('rev-parse', 'main')).toBe(first.commitHash); + }); + + it('runs on a branch still declaring v2, whose records then pass the v3 contracts (deploy order)', async () => { + const config = (sheet: string, v: number, root: string, path: string): string => + `[gitsheet]\nroot = '${root}'\npath = '${path}'\nimplements = ["codeforphilly.org/${sheet}/v${v}"]\n`; + const declare = (v: number) => + seedFiles({ + '.gitsheets/project-memberships.toml': config('project-memberships', v, 'project-memberships', '${{ projectSlug }}/${{ personSlug }}'), + '.gitsheets/projects.toml': config('projects', v, 'projects', '${{ slug }}'), + }); + // Old-shape records fail v3, so adoption must come after the migration. + await expect(exec(GITSHEETS_CLI, ['contracts', 'verify', '--git-dir', data.path, '--ref', 'main'])).rejects.toThrow(); + await declare(2); + const result = await migrateProjectAdmins({ dataRepo: data.path, branch: 'main' }); + expect(result.membershipsMigrated).toBe(4); + await exec(GITSHEETS_CLI, ['contracts', 'verify', '--git-dir', data.path, '--ref', 'main']); + await declare(3); + await exec(GITSHEETS_CLI, ['contracts', 'verify', '--git-dir', data.path, '--ref', 'main']); + }); + + it('a dry run counts without writing', async () => { + const before = await git('rev-parse', 'main'); + const result = await migrateProjectAdmins({ dataRepo: data.path, branch: 'main', dryRun: true }); + expect(result.commitHash).toBeNull(); + expect(result.membershipsMigrated).toBe(4); + expect(await git('rev-parse', 'main')).toBe(before); + }); +}); diff --git a/apps/api/tests/migration-slug-references.test.ts b/apps/api/tests/migration-slug-references.test.ts index 6f77a34d..a917fcde 100644 --- a/apps/api/tests/migration-slug-references.test.ts +++ b/apps/api/tests/migration-slug-references.test.ts @@ -100,7 +100,7 @@ async function seedOldShape(overrides: Record<string, string | Buffer> = {}): Pr { 'project-memberships/proj/jane.toml': toml({ id: ID.membership, projectId: ID.project, personId: ID.jane, projectSlug: 'proj', personSlug: 'jane', - isMaintainer: true, joinedAt: NOW, createdAt: NOW, updatedAt: NOW, + state: 'member', isAdmin: true, via: 'legacy', followedAt: NOW, joinedAt: NOW, createdAt: NOW, updatedAt: NOW, }), 'project-updates/proj/1.toml': toml({ id: ID.update, projectId: ID.project, projectSlug: 'proj', authorId: ID.jane, body: 'Shipped', @@ -201,7 +201,7 @@ describe('slug-references migration', () => { // still resolves, so the message names the current slug. 'project-memberships/proj/bob-old.toml': toml({ id: '01951a3c-0000-7000-8000-0000000000b1', projectId: ID.project, personId: ID.bob, - projectSlug: 'proj', personSlug: 'bob-old', isMaintainer: false, joinedAt: NOW, createdAt: NOW, updatedAt: NOW, + projectSlug: 'proj', personSlug: 'bob-old', state: 'member', via: 'legacy', followedAt: NOW, joinedAt: NOW, createdAt: NOW, updatedAt: NOW, }), // A record whose parent is gone entirely. 'project-updates/gone/1.toml': toml({ @@ -228,7 +228,7 @@ describe('slug-references migration', () => { "[gitsheet]\nroot = 'project-memberships'\npath = '${{ projectSlug }}/${{ personSlug }}'\nimplements = [\"codeforphilly.org/project-memberships/v1\"]\n", }); await expect(migrateSlugReferences({ dataRepo: data.path, branch: 'main' })).rejects.toThrow( - /project-memberships declares \[codeforphilly.org\/project-memberships\/v1\], not codeforphilly.org\/project-memberships\/v2/, + /project-memberships declares \[codeforphilly.org\/project-memberships\/v1\], not codeforphilly.org\/project-memberships\/v3/, ); }); }); diff --git a/apps/api/tests/people-lifecycle.test.ts b/apps/api/tests/people-lifecycle.test.ts index fed7295a..f1e1e510 100644 --- a/apps/api/tests/people-lifecycle.test.ts +++ b/apps/api/tests/people-lifecycle.test.ts @@ -288,7 +288,6 @@ describe('POST /api/people/:slug/purge', () => { `slug = "test-project"`, `title = "Test Project"`, `stage = "prototyping"`, - `maintainerId = "${IDS.admin}"`, `createdAt = "2026-05-01T00:00:00Z"`, `updatedAt = "2026-05-01T00:00:00Z"`, ].join('\n'); @@ -298,7 +297,9 @@ describe('POST /api/people/:slug/purge', () => { `id = "${IDS.membership}"`, `projectSlug = "test-project"`, `personSlug = "alice"`, - `isMaintainer = false`, + `state = "member"`, + `via = "legacy"`, + `followedAt = "2026-05-01T00:00:00Z"`, `joinedAt = "2026-05-01T00:00:00Z"`, `updatedAt = "2026-05-01T00:00:00Z"`, ].join('\n'); @@ -421,12 +422,15 @@ describe('POST /api/people/:slug/purge — projects only they touched', () => { await seedRawToml(dataRepo.path, `projects/${slug}.toml`, toml, `seed ${slug}`); } - async function seedMember(projectSlug: string, personSlug: string): Promise<void> { + async function seedMember(projectSlug: string, personSlug: string, isAdmin = false): Promise<void> { const toml = [ `id = "${uid()}"`, `projectSlug = "${projectSlug}"`, `personSlug = "${personSlug}"`, - `isMaintainer = false`, + `isAdmin = ${isAdmin}`, + `state = "member"`, + `via = "legacy"`, + `followedAt = "2026-05-01T00:00:00Z"`, `joinedAt = "2026-05-01T00:00:00Z"`, `updatedAt = "2026-05-01T00:00:00Z"`, ].join('\n'); @@ -467,7 +471,7 @@ describe('POST /api/people/:slug/purge — projects only they touched', () => { } // Created by the spammer and touched by nobody else: goes. - await seedProject('spam-created', projectId(1), [`createdById = "${P.spammer}"`, `maintainerId = "${P.spammer}"`]); + await seedProject('spam-created', projectId(1), [`createdById = "${P.spammer}"`]); await seedMember('spam-created', 'spammer'); await seedUpdate('spam-created', P.spammer); const role = [ @@ -481,12 +485,12 @@ describe('POST /api/people/:slug/purge — projects only they touched', () => { ].join('\n'); await seedRawToml(dataRepo.path, `help-wanted-roles/spam-created/${role.match(/id = "([^"]+)"/)![1]}.toml`, role, 'seed role'); - // No createdById (older record): the maintainer stands in. Goes. - await seedProject('spam-legacy', projectId(2), [`maintainerId = "${P.spammer}"`]); - await seedMember('spam-legacy', 'spammer'); + // No createdById (older record): being one of its admins stands in. Goes. + await seedProject('spam-legacy', projectId(2), []); + await seedMember('spam-legacy', 'spammer', true); // Created by the spammer, but someone else is a member: stays. - await seedProject('bob-joined', projectId(3), [`createdById = "${P.spammer}"`, `maintainerId = "${P.spammer}"`]); + await seedProject('bob-joined', projectId(3), [`createdById = "${P.spammer}"`]); await seedMember('bob-joined', 'spammer'); await seedMember('bob-joined', 'bob'); @@ -495,7 +499,7 @@ describe('POST /api/people/:slug/purge — projects only they touched', () => { await seedUpdate('bob-posted', P.bob); // Created by bob, the spammer only joined: stays. - await seedProject('bobs-project', projectId(5), [`createdById = "${P.bob}"`, `maintainerId = "${P.spammer}"`]); + await seedProject('bobs-project', projectId(5), [`createdById = "${P.bob}"`]); await seedMember('bobs-project', 'spammer'); app = await buildApp({ @@ -583,7 +587,6 @@ describe('Deactivated person reference placeholder', () => { `slug = "test-project"`, `title = "Test Project"`, `stage = "prototyping"`, - `maintainerId = "${IDS.admin}"`, `createdAt = "2026-05-01T00:00:00Z"`, `updatedAt = "2026-05-01T00:00:00Z"`, ].join('\n'); @@ -593,7 +596,9 @@ describe('Deactivated person reference placeholder', () => { `id = "${IDS.membership}"`, `projectSlug = "test-project"`, `personSlug = "alice"`, - `isMaintainer = false`, + `state = "member"`, + `via = "legacy"`, + `followedAt = "2026-05-01T00:00:00Z"`, `joinedAt = "2026-05-01T00:00:00Z"`, `updatedAt = "2026-05-01T00:00:00Z"`, ].join('\n'); diff --git a/apps/api/tests/project-filters.test.ts b/apps/api/tests/project-filters.test.ts index 1e3631ff..89f9f7ac 100644 --- a/apps/api/tests/project-filters.test.ts +++ b/apps/api/tests/project-filters.test.ts @@ -41,7 +41,6 @@ function makeProject(slug: string, overrides: Partial<Project> = {}): Project { summary: null, overview: null, stage: 'prototyping', - maintainerId: null, featured: false, deletedAt: null, createdAt: NOW, diff --git a/apps/api/tests/project-membership.test.ts b/apps/api/tests/project-membership.test.ts new file mode 100644 index 00000000..eb7b9128 --- /dev/null +++ b/apps/api/tests/project-membership.test.ts @@ -0,0 +1,338 @@ +/** + * Project admins and the membership record (plans/membership-admins.md): + * the add / promote / demote / update / remove / leave transitions of + * specs/behaviors/project-membership.md, who may make each one, the + * last-admin rule, the retired endpoints, and the members-only read shapes. + * + * Every person here is invented; addresses are example.org. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { + createAgent, + daysAgo, + fid, + personRecord, + privateProfile, + startAgentTestEnv, + type AgentTestEnv, + type Rec, +} from './helpers/agent-fixtures.js'; + +const P = { ada: 1, ben: 2, cal: 3, dee: 4, eve: 5, sam: 6, root: 7, gone: 8 }; +const T = '2026-05-01T00:00:00.000Z'; + +const member = (n: number, person: string, over: Rec = {}): Rec => ({ + id: fid(100 + n), + projectSlug: 'proj', + personSlug: person, + state: 'member', + isAdmin: false, + via: 'legacy', + followedAt: T, + joinedAt: T, + createdAt: T, + updatedAt: T, + ...over, +}); + +const RECORDS: Record<string, Rec[]> = { + people: [ + personRecord(P.ada, 'ada'), + personRecord(P.ben, 'ben'), + personRecord(P.cal, 'cal'), + personRecord(P.dee, 'dee'), + personRecord(P.eve, 'eve'), + personRecord(P.sam, 'sam', { accountLevel: 'staff' }), + personRecord(P.root, 'root', { accountLevel: 'administrator' }), + personRecord(P.gone, 'gone', { deletedAt: daysAgo(1) }), + ], + projects: [{ id: fid(50), slug: 'proj', title: 'Proj', stage: 'testing', featured: false, createdAt: T, updatedAt: T }], + 'project-memberships': [ + member(1, 'ada', { isAdmin: true, role: 'Founder' }), + member(2, 'ben', { role: 'Designer' }), + { id: fid(103), projectSlug: 'proj', personSlug: 'cal', state: 'follower', muted: true, followedAt: daysAgo(5), createdAt: daysAgo(5), updatedAt: daysAgo(5) }, + { + id: fid(104), + projectSlug: 'proj', + personSlug: 'dee', + state: 'applicant', + followedAt: T, + application: { status: 'open', roleIds: [], offer: 'I can help with maps.', submittedAt: T, visibleAt: T }, + createdAt: T, + updatedAt: T, + }, + ], +}; + +const PROFILES = [ + privateProfile(fid(P.ada), 'ada@example.org'), + privateProfile(fid(P.ben), 'ben@example.org'), + privateProfile(fid(P.cal), 'cal@example.org'), + privateProfile(fid(P.eve), 'eve@example.org'), +]; + +type Level = 'user' | 'staff' | 'administrator'; + +describe('project membership: admins and the membership record', () => { + let env: AgentTestEnv; + + beforeEach(async () => { + env = await startAgentTestEnv({ records: RECORDS, profiles: PROFILES }); + }); + afterEach(async () => { + await env.close(); + }); + + const call = async ( + who: number | null, + method: 'GET' | 'POST' | 'PATCH' | 'DELETE', + url: string, + payload?: Rec, + level: Level = 'user', + ) => + env.app.inject({ + method, + url, + ...(who !== null ? { cookies: { cfp_session: await env.cookie(who, level) } } : {}), + ...(payload !== undefined ? { payload } : {}), + }); + const record = (person: string) => { + const s = env.app.inMemoryState; + for (const id of s.membershipsByPerson.get(person) ?? []) { + const m = s.projectMemberships.get(id); + if (m?.projectSlug === 'proj') return m; + } + return undefined; + }; + const lastAction = async () => (await env.git('log', '-1', '--format=%B')).match(/^Action: (.+)$/m)?.[1]; + const errCode = (res: { json: () => unknown }) => (res.json() as { error: { code: string } }).error.code; + + describe('add', () => { + it('a project admin adds a person with no record; they get one notice email', async () => { + const spy = vi.spyOn(env.app.notifier, 'notifyMemberAdded'); + const res = await call(P.ada, 'POST', '/api/projects/proj/members', { personSlug: 'eve', role: 'Mapper' }); + expect(res.statusCode, res.body).toBe(201); + expect(res.json<{ data: Rec }>().data).toMatchObject({ role: 'Mapper', isAdmin: false, via: 'added' }); + expect(record('eve')).toMatchObject({ state: 'member', via: 'added', role: 'Mapper' }); + expect(await lastAction()).toBe('project-membership.add'); + await vi.waitFor(() => expect(spy).toHaveBeenCalledTimes(1)); + expect(spy.mock.calls[0]![0]).toMatchObject({ email: 'eve@example.org', projectSlug: 'proj', addedByName: 'Test ada' }); + // No address is written to any record or commit. + expect(await env.git('log', '-p', '--format=%B%n%an <%ae>')).not.toContain('@example.org'); + }); + + it('adds a follower, keeping the record and when they followed', async () => { + const res = await call(P.ada, 'POST', '/api/projects/proj/members', { personSlug: 'cal', isAdmin: true }); + expect(res.statusCode, res.body).toBe(201); + expect(record('cal')).toMatchObject({ id: fid(103), state: 'member', isAdmin: true, via: 'added', muted: true }); + expect(record('cal')!.followedAt).toBe(RECORDS['project-memberships']![2]!['followedAt']); + }); + + it('adds an applicant, resolving their application as accepted by the caller', async () => { + const res = await call(P.ada, 'POST', '/api/projects/proj/members', { personSlug: 'dee' }); + expect(res.statusCode, res.body).toBe(201); + const m = record('dee')!; + expect(m).toMatchObject({ state: 'member', via: 'added' }); + expect(m.application).toMatchObject({ status: 'accepted', decidedById: fid(P.ada), decidedVia: 'site', offer: 'I can help with maps.' }); + }); + + it('staff may add; a plain member gets 403; a member again is 409 already_member', async () => { + expect((await call(P.sam, 'POST', '/api/projects/proj/members', { personSlug: 'eve' }, 'staff')).statusCode).toBe(201); + expect((await call(P.ben, 'POST', '/api/projects/proj/members', { personSlug: 'cal' })).statusCode).toBe(403); + const again = await call(P.ada, 'POST', '/api/projects/proj/members', { personSlug: 'ben' }); + expect(again.statusCode).toBe(409); + expect(errCode(again)).toBe('already_member'); + }); + + it('a deactivated person is absent (404); an agent account is refused (422 agent_account)', async () => { + expect((await call(P.ada, 'POST', '/api/projects/proj/members', { personSlug: 'gone' })).statusCode).toBe(404); + await createAgent(env, await env.cookie(P.root, 'administrator'), { slug: 'helper-bot', scopes: ['moderation:read'] }); + const res = await call(P.ada, 'POST', '/api/projects/proj/members', { personSlug: 'helper-bot' }); + expect(res.statusCode).toBe(422); + expect(errCode(res)).toBe('agent_account'); + }); + }); + + describe('promote, demote, update', () => { + it('names each transition in the commit and changes only what it says', async () => { + let res = await call(P.ada, 'PATCH', '/api/projects/proj/members/ben', { isAdmin: true }); + expect(res.statusCode, res.body).toBe(200); + expect(await lastAction()).toBe('project-membership.promote'); + expect(record('ben')).toMatchObject({ isAdmin: true, role: 'Designer' }); + + res = await call(P.ben, 'PATCH', '/api/projects/proj/members/ada', { isAdmin: false }); + expect(res.statusCode, res.body).toBe(200); + expect(await lastAction()).toBe('project-membership.demote'); + + res = await call(P.ben, 'PATCH', '/api/projects/proj/members/ada', { role: 'Advisor' }); + expect(res.statusCode, res.body).toBe(200); + expect(await lastAction()).toBe('project-membership.update'); + expect(record('ada')).toMatchObject({ isAdmin: false, role: 'Advisor' }); + }); + + it('staff may promote; a plain member may change only their own role', async () => { + expect((await call(P.sam, 'PATCH', '/api/projects/proj/members/ben', { isAdmin: true }, 'staff')).statusCode).toBe(200); + await call(P.sam, 'PATCH', '/api/projects/proj/members/ben', { isAdmin: false }, 'staff'); + + expect((await call(P.ben, 'PATCH', '/api/projects/proj/members/ben', { role: 'Lead designer' })).statusCode).toBe(200); + expect(record('ben')!.role).toBe('Lead designer'); + expect((await call(P.ben, 'PATCH', '/api/projects/proj/members/ada', { role: 'x' })).statusCode).toBe(403); + expect((await call(P.ben, 'PATCH', '/api/projects/proj/members/ben', { isAdmin: true })).statusCode).toBe(403); + }); + + it('only member records can be patched (409 not_a_member); a role over 80 chars is 422', async () => { + const res = await call(P.ada, 'PATCH', '/api/projects/proj/members/cal', { role: 'x' }); + expect(res.statusCode).toBe(409); + expect(errCode(res)).toBe('not_a_member'); + expect((await call(P.ada, 'PATCH', '/api/projects/proj/members/ben', { role: 'x'.repeat(81) })).statusCode).toBe(422); + }); + }); + + describe('the last admin', () => { + it('demote, remove or leave that leaves no active admin is 409 last_admin without confirmLastAdmin', async () => { + for (const res of [ + await call(P.ada, 'PATCH', '/api/projects/proj/members/ada', { isAdmin: false }), + await call(P.ada, 'DELETE', '/api/projects/proj/members/ada'), + await call(P.ada, 'POST', '/api/projects/proj/members/leave', {}), + await call(P.sam, 'DELETE', '/api/projects/proj/members/ada', undefined, 'staff'), + ]) { + expect(res.statusCode, res.body).toBe(409); + expect(errCode(res)).toBe('last_admin'); + } + expect(record('ada')).toMatchObject({ state: 'member', isAdmin: true }); + }); + + it('succeeds with the confirmation, leaving a project with no admin that staff can fix', async () => { + const res = await call(P.ada, 'PATCH', '/api/projects/proj/members/ada', { isAdmin: false, confirmLastAdmin: true }); + expect(res.statusCode, res.body).toBe(200); + expect(env.app.inMemoryState.adminsByProject.get('proj')).toBeUndefined(); + const fix = await call(P.sam, 'PATCH', '/api/projects/proj/members/ben', { isAdmin: true }, 'staff'); + expect(fix.statusCode).toBe(200); + expect([...(env.app.inMemoryState.adminsByProject.get('proj') ?? [])]).toEqual(['ben']); + }); + + it('a deactivated co-admin does not count as active', async () => { + await call(P.ada, 'PATCH', '/api/projects/proj/members/ben', { isAdmin: true }); + await call(P.sam, 'POST', '/api/people/ben/deactivate', {}, 'staff'); + const res = await call(P.ada, 'POST', '/api/projects/proj/members/leave', {}); + expect(res.statusCode).toBe(409); + expect(errCode(res)).toBe('last_admin'); + }); + + it('removing the last admin with ?confirmLastAdmin=true succeeds', async () => { + const res = await call(P.sam, 'DELETE', '/api/projects/proj/members/ada?confirmLastAdmin=true', undefined, 'staff'); + expect(res.statusCode, res.body).toBe(204); + expect(record('ada')).toBeUndefined(); + }); + }); + + describe('leave and remove', () => { + it('leave moves a member to follower, clearing role, isAdmin, via and joinedAt', async () => { + const res = await call(P.ben, 'POST', '/api/projects/proj/members/leave', {}); + expect(res.statusCode, res.body).toBe(200); + expect(res.json<{ data: Rec }>().data).toMatchObject({ state: 'follower' }); + const m = record('ben')!; + expect(m).toMatchObject({ id: fid(102), state: 'follower', isAdmin: false, followedAt: T }); + expect(m.role ?? null).toBeNull(); + expect(m.via ?? null).toBeNull(); + expect(m.joinedAt ?? null).toBeNull(); + expect(await lastAction()).toBe('project-membership.leave'); + const toml = await env.git('show', 'HEAD:project-memberships/proj/ben.toml'); + expect(toml).not.toMatch(/^(role|via|joinedAt) =/m); + }); + + it('leave with alsoUnfollow deletes the record (204)', async () => { + const res = await call(P.ben, 'POST', '/api/projects/proj/members/leave', { alsoUnfollow: true }); + expect(res.statusCode).toBe(204); + expect(record('ben')).toBeUndefined(); + }); + + it('leave by a non-member is 409 not_a_member', async () => { + const res = await call(P.cal, 'POST', '/api/projects/proj/members/leave', {}); + expect(res.statusCode).toBe(409); + expect(errCode(res)).toBe('not_a_member'); + }); + + it('remove deletes the record; followers are not admins’ to remove; a member cannot remove', async () => { + expect((await call(P.ben, 'DELETE', '/api/projects/proj/members/ada')).statusCode).toBe(403); + const res = await call(P.ada, 'DELETE', '/api/projects/proj/members/ben'); + expect(res.statusCode).toBe(204); + expect(record('ben')).toBeUndefined(); + expect(await lastAction()).toBe('project-membership.remove'); + const follower = await call(P.ada, 'DELETE', '/api/projects/proj/members/cal'); + expect(follower.statusCode).toBe(409); + expect(errCode(follower)).toBe('not_a_member'); + }); + }); + + describe('retired endpoints', () => { + it('POST …/members/join and POST …/change-maintainer answer 410', async () => { + const join = await call(P.eve, 'POST', '/api/projects/proj/members/join'); + expect(join.statusCode).toBe(410); + expect(errCode(join)).toBe('join_removed'); + const change = await call(P.ada, 'POST', '/api/projects/proj/change-maintainer', { personSlug: 'ben' }); + expect(change.statusCode).toBe(410); + expect(errCode(change)).toBe('gone'); + expect(record('eve')).toBeUndefined(); + }); + }); + + describe('read shapes', () => { + it('the project lists members only, admins first, with via only for admins and staff', async () => { + const anon = (await call(null, 'GET', '/api/projects/proj')).json<{ data: Rec }>().data; + const memberships = anon['memberships'] as Array<{ person: { slug: string }; isAdmin: boolean; via: string | null }>; + expect(memberships.map((m) => m.person.slug)).toEqual(['ada', 'ben']); + expect(memberships[0]!.isAdmin).toBe(true); + expect(memberships.every((m) => m.via === null)).toBe(true); + expect(anon['counts']).toMatchObject({ members: 2 }); + expect(anon['viewer']).toBeNull(); + expect(anon['hasActiveAdmin']).toBe(true); + + const asAdmin = (await call(P.ada, 'GET', '/api/projects/proj')).json<{ data: Rec }>().data; + expect((asAdmin['memberships'] as Array<{ via: string }>)[0]!.via).toBe('legacy'); + expect(asAdmin['viewer']).toMatchObject({ state: 'member', isAdmin: true, muted: false }); + + const asFollower = (await call(P.cal, 'GET', '/api/projects/proj')).json<{ data: Rec }>().data; + expect(asFollower['viewer']).toMatchObject({ state: 'follower', isAdmin: false, muted: true }); + }); + + it('no follower or applicant appears in any person or list response', async () => { + const list = (await call(null, 'GET', '/api/projects?memberSlug=cal')).json<{ data: unknown[] }>(); + expect(list.data).toHaveLength(0); + const byAdmin = (await call(null, 'GET', '/api/projects?admin=ada')).json<{ data: Array<{ slug: string; admins: Array<{ slug: string }>; memberCount: number }> }>(); + expect(byAdmin.data.map((p) => p.slug)).toEqual(['proj']); + expect(byAdmin.data[0]!.admins.map((a) => a.slug)).toEqual(['ada']); + expect(byAdmin.data[0]!.memberCount).toBe(2); + const alias = (await call(null, 'GET', '/api/projects?maintainer=ada')).json<{ data: unknown[] }>(); + expect(alias.data).toHaveLength(1); + expect((await call(null, 'GET', '/api/projects?admin=ben')).json<{ data: unknown[] }>().data).toHaveLength(0); + + const cal = (await call(null, 'GET', '/api/people/cal')).json<{ data: { memberships: unknown[] } }>().data; + expect(cal.memberships).toEqual([]); + const ada = (await call(null, 'GET', '/api/people/ada')).json<{ data: { memberships: Array<{ isAdmin: boolean }> } }>().data; + expect(ada.memberships).toEqual([expect.objectContaining({ isAdmin: true, role: 'Founder' })]); + + const people = (await call(null, 'GET', '/api/people?perPage=100')).json<{ data: Array<{ slug: string; memberOfCount: number; adminOfCount: number }> }>().data; + const bySlug = Object.fromEntries(people.map((p) => [p.slug, p])); + expect(bySlug['ada']).toMatchObject({ memberOfCount: 1, adminOfCount: 1 }); + expect(bySlug['ben']).toMatchObject({ memberOfCount: 1, adminOfCount: 0 }); + expect(bySlug['cal']).toMatchObject({ memberOfCount: 0, adminOfCount: 0 }); + expect(bySlug['dee']).toMatchObject({ memberOfCount: 0 }); + }); + + it('creating a project writes the founder as admin in the same commit', async () => { + const res = await call(P.eve, 'POST', '/api/projects', { title: 'Fresh Thing', slug: 'fresh-thing' }); + expect(res.statusCode, res.body).toBe(201); + const s = env.app.inMemoryState; + const [id] = [...(s.membershipsByProject.get('fresh-thing') ?? [])]; + expect(s.projectMemberships.get(id!)).toMatchObject({ + personSlug: 'eve', state: 'member', isAdmin: true, role: 'Founder', via: 'created', + }); + const files = await env.git('show', '--name-only', '--format=', 'HEAD'); + expect(files).toContain('projects/fresh-thing.toml'); + expect(files).toContain('project-memberships/fresh-thing/eve.toml'); + expect(await env.git('show', 'HEAD:projects/fresh-thing.toml')).not.toContain('maintainerId'); + }); + }); +}); diff --git a/apps/api/tests/prune-spam.test.ts b/apps/api/tests/prune-spam.test.ts index 34f972af..20402aa5 100644 --- a/apps/api/tests/prune-spam.test.ts +++ b/apps/api/tests/prune-spam.test.ts @@ -149,8 +149,8 @@ describe('prune-spam', () => { { personSlug: 'human-flipflop', evaluator: 'human-b', verdict: 'spam', confidence: 1, flags: [], evaluatedAt: LATER }, ], memberships: [ - { id: uuid(101), projectSlug: 'proj', personSlug: 'member-spammer', role: 'Member', isMaintainer: false, joinedAt: NOW, createdAt: NOW, updatedAt: NOW }, - { id: uuid(102), projectSlug: 'proj', personSlug: 'human-spam-member', role: 'Member', isMaintainer: false, joinedAt: NOW, createdAt: NOW, updatedAt: NOW }, + { id: uuid(101), projectSlug: 'proj', personSlug: 'member-spammer', state: 'member', role: 'Member', via: 'legacy', followedAt: NOW, joinedAt: NOW, createdAt: NOW, updatedAt: NOW }, + { id: uuid(102), projectSlug: 'proj', personSlug: 'human-spam-member', state: 'member', role: 'Member', via: 'legacy', followedAt: NOW, joinedAt: NOW, createdAt: NOW, updatedAt: NOW }, ], extra: async (tx) => { await tx.sheet('tag-assignments').upsert({ id: uuid(301), tagId: uuid(400), taggableType: 'person', taggableId: uuid(1), createdAt: NOW }); diff --git a/apps/api/tests/reload-swap.test.ts b/apps/api/tests/reload-swap.test.ts index 192355dd..797948d6 100644 --- a/apps/api/tests/reload-swap.test.ts +++ b/apps/api/tests/reload-swap.test.ts @@ -67,7 +67,6 @@ function makeProject(n: number, slug: string, legacyId: number): Project { summary: null, overview: null, stage: 'prototyping', - maintainerId: null, featured: false, deletedAt: null, createdAt: NOW, @@ -113,7 +112,7 @@ function makeAssignment(n: number, tagId: string, projectId: string): TagAssignm * this test is about index bookkeeping, not record validation. */ function makeMembership(n: number, projectSlug: string, personSlug: string): ProjectMembership { - return { id: uuid(n), projectSlug, personSlug, role: 'member', createdAt: NOW, updatedAt: NOW } as unknown as ProjectMembership; + return { id: uuid(n), projectSlug, personSlug, state: 'member', isAdmin: true, role: 'member', via: 'legacy', muted: false, followedAt: NOW, joinedAt: NOW, createdAt: NOW, updatedAt: NOW } as ProjectMembership; } function makeUpdate(n: number, projectSlug: string, number: number): ProjectUpdate { diff --git a/apps/api/tests/scrub-data.test.ts b/apps/api/tests/scrub-data.test.ts index 113a6e1b..1a927fa1 100644 --- a/apps/api/tests/scrub-data.test.ts +++ b/apps/api/tests/scrub-data.test.ts @@ -740,7 +740,7 @@ describe('scrubRepo', () => { await tx.sheet('people').upsert({ id: uuid(1), slug: 'alice', fullName: 'Alice Smith', accountLevel: 'user', createdAt: NOW, updatedAt: NOW }); await tx.sheet('projects').upsert({ id: uuid(2), slug: 'proj', title: 'Proj', stage: 'bootstrapping', createdAt: NOW, updatedAt: NOW }); await tx.sheet('project-memberships').upsert({ - id: uuid(3), projectSlug: 'proj', personSlug: 'alice', isMaintainer: false, + id: uuid(3), projectSlug: 'proj', personSlug: 'alice', state: 'member', via: 'legacy', followedAt: NOW, joinedAt: NOW, createdAt: NOW, updatedAt: NOW, }); await tx.sheet('event-rsvps').upsert({ diff --git a/apps/api/tests/spam-purge.test.ts b/apps/api/tests/spam-purge.test.ts index cf38d9ca..b903104d 100644 --- a/apps/api/tests/spam-purge.test.ts +++ b/apps/api/tests/spam-purge.test.ts @@ -64,7 +64,9 @@ describe('scheduled spam purge', () => { `id = "01951a3c-0000-7000-8000-c${n}000000cafe"`, `projectSlug = "${projectSlug}"`, `personSlug = "${personSlug}"`, - `isMaintainer = false`, + `state = "member"`, + `via = "legacy"`, + `followedAt = "2026-05-01T00:00:00Z"`, `joinedAt = "2026-05-01T00:00:00Z"`, `updatedAt = "2026-05-01T00:00:00Z"`, ].join('\n'); @@ -91,7 +93,6 @@ describe('scheduled spam purge', () => { `title = "Ring project"`, `stage = "commenting"`, `createdById = "${ID.ringleader}"`, - `maintainerId = "${ID.ringleader}"`, `createdAt = "2026-05-01T00:00:00Z"`, `updatedAt = "2026-05-01T00:00:00Z"`, ].join('\n'); diff --git a/apps/api/tests/write-api.test.ts b/apps/api/tests/write-api.test.ts index 682d6d6f..bb792a90 100644 --- a/apps/api/tests/write-api.test.ts +++ b/apps/api/tests/write-api.test.ts @@ -92,7 +92,7 @@ describe('POST /api/projects', () => { const body = res.json<{ success: boolean; data: { slug: string; memberships: unknown[]; permissions: { canEdit: boolean } } }>(); expect(body.data.slug).toBe('my-new-project'); expect(body.data.memberships.length).toBe(1); - // Author becomes maintainer → canEdit true + // The founder becomes the first admin → canEdit true expect(body.data.permissions.canEdit).toBe(true); // Subsequent GET returns the same project @@ -163,7 +163,7 @@ describe('POST /api/projects', () => { // --------------------------------------------------------------------------- describe('PATCH /api/projects/:slug', () => { - it('lets the maintainer edit', async () => { + it('lets a project admin edit', async () => { const cookie = await userCookie(fixtures.personId); const res = await app!.inject({ method: 'PATCH', @@ -176,7 +176,7 @@ describe('PATCH /api/projects/:slug', () => { expect(body.data.summary).toBe('A new summary.'); }); - it('rejects non-maintainer non-staff with 403', async () => { + it('rejects a non-admin non-staff caller with 403', async () => { // Create another user via a project create, then try to PATCH the seeded project const cookie = await userCookie('01951a3c-0000-7000-8000-000000099999'); const res = await app!.inject({ @@ -188,7 +188,7 @@ describe('PATCH /api/projects/:slug', () => { // 401 if our anonymous-with-id session is treated as anonymous due to // no matching person record. The session middleware looks up the person; // missing person → personId set but person null → still authenticated in - // requireAuth, then fails maintainer | staff → 403. + // requireAuth, then fails project-admin | staff → 403. expect([401, 403]).toContain(res.statusCode); }); @@ -296,7 +296,7 @@ describe('DELETE /api/projects/:slug', () => { // --------------------------------------------------------------------------- describe('Project memberships', () => { - it('maintainer can add a member', async () => { + it('a project admin adding an existing member gets 409 already_member', async () => { // Seed a second person first via a staff project create (uses uniqueness) // For brevity, we use an inline approach: create another person via a // direct write through the public store would be nicer, but we'll create @@ -316,7 +316,7 @@ describe('Project memberships', () => { expect(body.error.code).toBe('already_member'); }); - it('cannot remove the current maintainer', async () => { + it('removing the last admin needs confirmLastAdmin (fuller cases in project-membership.test.ts)', async () => { const cookie = await userCookie(fixtures.personId); const res = await app!.inject({ method: 'DELETE', @@ -325,7 +325,7 @@ describe('Project memberships', () => { }); expect(res.statusCode).toBe(409); const body = res.json<{ error: { code: string } }>(); - expect(body.error.code).toBe('cannot_remove_maintainer'); + expect(body.error.code).toBe('last_admin'); }); }); @@ -435,7 +435,7 @@ describe('Project buzz', () => { // --------------------------------------------------------------------------- describe('Help-wanted', () => { - it('maintainer can post a role; FTS picks it up', async () => { + it('a project admin can post a role; FTS picks it up', async () => { const cookie = await userCookie(fixtures.personId); const res = await app!.inject({ method: 'POST', @@ -617,7 +617,7 @@ describe('cross-cutting', () => { expect(body.data.some((p) => p.slug === 'bayou-heron')).toBe(true); }); - it('GET project permissions flip across anonymous → maintainer → staff', async () => { + it('GET project permissions flip across anonymous → project admin → staff', async () => { const anon = await app!.inject({ method: 'GET', url: `/api/projects/${fixtures.projectSlug}`, diff --git a/packages/shared/tests/schemas.test.ts b/packages/shared/tests/schemas.test.ts index 821b1e08..8c5ea475 100644 --- a/packages/shared/tests/schemas.test.ts +++ b/packages/shared/tests/schemas.test.ts @@ -154,7 +154,8 @@ describe('ProjectMembershipSchema', () => { }); it('rejects missing projectSlug', () => { - const { projectSlug: _, ...rest } = member; + const rest: Record<string, unknown> = { ...member }; + delete rest['projectSlug']; expect(ProjectMembershipSchema.safeParse(rest).success).toBe(false); }); From 93a3426cc7464cdc7b29fef155b0dbe134bc96c5 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:47:29 +0000 Subject: [PATCH 19/78] feat(web): manage admins, the member row of the Join block, admin chips Manage Members makes and removes admins and asks before a change that leaves no active admin; Add Member has Make admin. The Join button is gone: the sidebar's Join block shows a signed-out visitor the sign-in link and a member their row with Leave (also stop following, last-admin warning). Admins are marked and sized on the project page, project cards, person pages, people cards and the moderation footprint. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/web/src/components/PersonCard.tsx | 1 + apps/web/src/components/ProjectCard.tsx | 4 +- .../src/components/modals/AddMemberModal.tsx | 15 +- .../components/modals/ManageMembersModal.tsx | 168 ++++++++++-------- .../components/modals/PostRolePickerModal.tsx | 4 +- apps/web/src/components/project/JoinBlock.tsx | 154 ++++++++++++++++ apps/web/src/lib/api.ts | 73 ++++++-- apps/web/src/pages/AdminMembers.tsx | 3 +- apps/web/src/screens/PersonDetail.tsx | 8 +- apps/web/src/screens/ProjectDetail.tsx | 54 +----- apps/web/tests/ManageMembersModal.test.tsx | 56 ++++++ apps/web/tests/ProjectDetail.test.tsx | 40 +++-- apps/web/tests/ProjectEdit.test.tsx | 3 +- apps/web/tests/ProjectsIndex.test.tsx | 2 +- 14 files changed, 417 insertions(+), 168 deletions(-) create mode 100644 apps/web/src/components/project/JoinBlock.tsx create mode 100644 apps/web/tests/ManageMembersModal.test.tsx diff --git a/apps/web/src/components/PersonCard.tsx b/apps/web/src/components/PersonCard.tsx index ed591ceb..1b92a1b9 100644 --- a/apps/web/src/components/PersonCard.tsx +++ b/apps/web/src/components/PersonCard.tsx @@ -29,6 +29,7 @@ export function PersonCard({ person }: PersonCardProps) { {person.memberOfCount > 0 && ( <p className="text-xs text-muted-foreground mt-0.5"> Member of {person.memberOfCount} project{person.memberOfCount === 1 ? '' : 's'} + {person.adminOfCount > 0 && <>, admin of {person.adminOfCount}</>} </p> )} {person.tags.length > 0 && ( diff --git a/apps/web/src/components/ProjectCard.tsx b/apps/web/src/components/ProjectCard.tsx index 61c5ce2d..51a3211d 100644 --- a/apps/web/src/components/ProjectCard.tsx +++ b/apps/web/src/components/ProjectCard.tsx @@ -32,12 +32,12 @@ export function ProjectCard({ project }: ProjectCardProps) { {project.members.length > 0 && ( <div className="flex items-center -space-x-2 mb-3"> {project.members.slice(0, 8).map((m) => { - const isMaintainer = m.slug === project.maintainer?.slug; + const isAdmin = project.admins.some((a) => a.slug !== null && a.slug === m.slug); return ( // No title here: PersonAvatar already emits the member's name, // so this produced two identical tooltips stacked. <div key={m.slug} className="ring-2 ring-card rounded-full"> - <PersonAvatar person={m} size={isMaintainer ? 36 : 28} /> + <PersonAvatar person={m} size={isAdmin ? 36 : 28} /> </div> ); })} diff --git a/apps/web/src/components/modals/AddMemberModal.tsx b/apps/web/src/components/modals/AddMemberModal.tsx index ee9ff3ca..60c315f2 100644 --- a/apps/web/src/components/modals/AddMemberModal.tsx +++ b/apps/web/src/components/modals/AddMemberModal.tsx @@ -12,6 +12,7 @@ import { import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; +import { Checkbox } from '@/components/ui/checkbox'; import { api, ApiError } from '@/lib/api'; interface AddMemberModalProps { @@ -24,12 +25,14 @@ export function AddMemberModal({ open, onOpenChange, projectSlug }: AddMemberMod const queryClient = useQueryClient(); const [personSlug, setPersonSlug] = useState(''); const [role, setRole] = useState(''); + const [makeAdmin, setMakeAdmin] = useState(false); const [submitting, setSubmitting] = useState(false); const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({}); const reset = () => { setPersonSlug(''); setRole(''); + setMakeAdmin(false); setFieldErrors({}); }; @@ -42,6 +45,7 @@ export function AddMemberModal({ open, onOpenChange, projectSlug }: AddMemberMod await api.projects.addMember(projectSlug, { personSlug: personSlug.trim(), role: role.trim() || null, + isAdmin: makeAdmin, }); await queryClient.invalidateQueries({ queryKey: ['project', projectSlug] }); toast.success(`Added ${personSlug.trim()}`); @@ -69,7 +73,8 @@ export function AddMemberModal({ open, onOpenChange, projectSlug }: AddMemberMod <DialogHeader> <DialogTitle>Add Member</DialogTitle> <DialogDescription> - The person must already have an account on Code for Philly. + The person must already have an account on Code for Philly. They're added at once + and get an email saying who added them and how to leave. </DialogDescription> </DialogHeader> <div className="py-4 space-y-4"> @@ -104,6 +109,14 @@ export function AddMemberModal({ open, onOpenChange, projectSlug }: AddMemberMod maxLength={80} /> </div> + <div className="flex items-center gap-2"> + <Checkbox + id="member-admin" + checked={makeAdmin} + onCheckedChange={(v) => setMakeAdmin(v === true)} + /> + <Label htmlFor="member-admin">Make admin</Label> + </div> </div> <DialogFooter> <Button type="button" variant="outline" onClick={() => onOpenChange(false)}> diff --git a/apps/web/src/components/modals/ManageMembersModal.tsx b/apps/web/src/components/modals/ManageMembersModal.tsx index 2303b5be..23e533fd 100644 --- a/apps/web/src/components/modals/ManageMembersModal.tsx +++ b/apps/web/src/components/modals/ManageMembersModal.tsx @@ -20,6 +20,27 @@ interface ManageMembersModalProps { project: ProjectDetail; } +export const LAST_ADMIN_WARNING = + 'This leaves the project with no active admin. Nobody will be able to accept applications or manage members until site staff add one. Continue?'; + +/** + * Run a change; if the API says it would leave no active admin + * (`409 last_admin`), ask once and resend with the confirmation. + */ +export async function withLastAdminConfirm(run: (confirmLastAdmin: boolean) => Promise<unknown>): Promise<boolean> { + try { + await run(false); + return true; + } catch (err) { + if (err instanceof ApiError && err.code === 'last_admin') { + if (!window.confirm(LAST_ADMIN_WARNING)) return false; + await run(true); + return true; + } + throw err; + } +} + export function ManageMembersModal({ open, onOpenChange, project }: ManageMembersModalProps) { const queryClient = useQueryClient(); const [busySlug, setBusySlug] = useState<string | null>(null); @@ -28,60 +49,59 @@ export function ManageMembersModal({ open, onOpenChange, project }: ManageMember const refresh = () => queryClient.invalidateQueries({ queryKey: ['project', project.slug] }); - const handleRemove = async (personSlug: string, rowKey: string) => { - if (!window.confirm(`Remove ${personSlug} from this project?`)) return; + const act = async (rowKey: string, run: () => Promise<boolean>, success: string, failure: string) => { setBusySlug(rowKey); try { - await api.projects.removeMember(project.slug, personSlug); - toast.success(`Removed ${personSlug}`); - await refresh(); - } catch (err) { - if (err instanceof ApiError && err.code === 'cannot_remove_maintainer') { - toast.error('Transfer maintainer first'); - } else if (err instanceof ApiError) { - toast.error(err.message); - } else { - toast.error('Remove failed'); + if (await run()) { + toast.success(success); + await refresh(); } + } catch (err) { + toast.error(err instanceof ApiError ? err.message : failure); } finally { setBusySlug(null); } }; - const handleChangeMaintainer = async (personSlug: string, rowKey: string) => { - if (!window.confirm(`Make ${personSlug} the maintainer? You'll become a regular member.`)) return; - setBusySlug(rowKey); - try { - await api.projects.changeMaintainer(project.slug, personSlug); - toast.success(`Maintainer transferred to ${personSlug}`); - await refresh(); - } catch (err) { - toast.error(err instanceof ApiError ? err.message : 'Transfer failed'); - } finally { - setBusySlug(null); - } + const handleRemove = (personSlug: string, name: string, rowKey: string) => { + if (!window.confirm(`Remove ${name} from this project? They won't be left following it.`)) return; + void act( + rowKey, + () => withLastAdminConfirm((confirmLastAdmin) => api.projects.removeMember(project.slug, personSlug, { confirmLastAdmin })), + `Removed ${name}`, + 'Remove failed', + ); + }; + + const handleAdmin = (personSlug: string, name: string, rowKey: string, isAdmin: boolean) => { + void act( + rowKey, + () => + withLastAdminConfirm((confirmLastAdmin) => + api.projects.updateMember(project.slug, personSlug, { isAdmin, confirmLastAdmin }), + ), + isAdmin ? `${name} is now an admin` : `${name} is no longer an admin`, + 'Update failed', + ); }; - const handleSaveRole = async (rowKey: string, personSlug: string) => { + const handleSaveRole = (rowKey: string, personSlug: string) => { const role = editingRole[rowKey]; if (role === undefined) return; - setBusySlug(rowKey); - try { - await api.projects.updateMember(project.slug, personSlug, { - role: role.trim() || null, - }); - toast.success('Role updated'); - setEditingRole((m) => { - const next = { ...m }; - delete next[rowKey]; - return next; - }); - await refresh(); - } catch (err) { - toast.error(err instanceof ApiError ? err.message : 'Update failed'); - } finally { - setBusySlug(null); - } + void act( + rowKey, + async () => { + await api.projects.updateMember(project.slug, personSlug, { role: role.trim() || null }); + setEditingRole((m) => { + const next = { ...m }; + delete next[rowKey]; + return next; + }); + return true; + }, + 'Role updated', + 'Update failed', + ); }; return ( @@ -90,7 +110,7 @@ export function ManageMembersModal({ open, onOpenChange, project }: ManageMember <DialogHeader> <DialogTitle>Manage Members</DialogTitle> <DialogDescription> - Edit roles, transfer maintainer, or remove members. + Edit roles, make or remove admins, or remove members. A project can have any number of admins. </DialogDescription> </DialogHeader> <div className="py-4"> @@ -100,12 +120,13 @@ export function ManageMembersModal({ open, onOpenChange, project }: ManageMember // person.slug may be null for deactivated members (placeholder shape). const rowKey = m.id; const personSlug = m.person.slug; + const name = m.person.fullName; const isEditingThisRow = editingRole[rowKey] !== undefined; return ( <li key={m.id} className="py-3 flex items-center gap-3"> <PersonAvatar person={m.person} size={32} asLink={false} /> <div className="flex-1 min-w-0"> - <div className="font-medium truncate">{m.person.fullName}</div> + <div className="font-medium truncate">{name}</div> {isEditingThisRow ? ( <Input value={editingRole[rowKey] ?? ''} @@ -114,29 +135,30 @@ export function ManageMembersModal({ open, onOpenChange, project }: ManageMember } placeholder="Role" aria-label="Role" + maxLength={80} className="h-7 mt-1 text-xs" /> ) : ( <div className="text-xs text-muted-foreground"> {m.role ?? <em>No role</em>} - {m.isMaintainer && ( + {m.isAdmin && ( <span className="ml-2 inline-flex items-center rounded-full bg-primary/15 text-primary px-1.5 py-0.5"> - Maintainer + Admin </span> )} </div> )} </div> - <div className="flex items-center gap-1"> + <div className="flex items-center gap-1 flex-wrap justify-end"> {/* Deactivated members: no edit actions available. */} - {m.person.deactivated ? ( + {m.person.deactivated || !personSlug ? ( <span className="text-xs text-muted-foreground italic">Deactivated</span> ) : isEditingThisRow ? ( <> <Button type="button" size="sm" - onClick={() => personSlug && handleSaveRole(rowKey, personSlug)} + onClick={() => handleSaveRole(rowKey, personSlug)} disabled={busySlug === rowKey} > Save @@ -165,38 +187,34 @@ export function ManageMembersModal({ open, onOpenChange, project }: ManageMember type="button" size="sm" variant="outline" - aria-label={`Edit role for ${m.person.fullName}`} + aria-label={`Edit role for ${name}`} onClick={() => setEditingRole((r) => ({ ...r, [rowKey]: m.role ?? '' })) } > Edit role </Button> - {!m.isMaintainer && ( - <Button - type="button" - size="sm" - variant="outline" - aria-label={`Make maintainer: ${m.person.fullName}`} - onClick={() => personSlug && handleChangeMaintainer(personSlug, rowKey)} - disabled={busySlug === rowKey} - > - Make maintainer - </Button> - )} - {!m.isMaintainer && ( - <Button - type="button" - size="sm" - variant="ghost" - aria-label={`Remove ${m.person.fullName}`} - onClick={() => personSlug && handleRemove(personSlug, rowKey)} - disabled={busySlug === rowKey} - className="text-destructive hover:text-destructive" - > - Remove - </Button> - )} + <Button + type="button" + size="sm" + variant="outline" + aria-label={m.isAdmin ? `Remove admin: ${name}` : `Make admin: ${name}`} + onClick={() => handleAdmin(personSlug, name, rowKey, !m.isAdmin)} + disabled={busySlug === rowKey} + > + {m.isAdmin ? 'Remove admin' : 'Make admin'} + </Button> + <Button + type="button" + size="sm" + variant="ghost" + aria-label={`Remove ${name}`} + onClick={() => handleRemove(personSlug, name, rowKey)} + disabled={busySlug === rowKey} + className="text-destructive hover:text-destructive" + > + Remove + </Button> </> )} </div> diff --git a/apps/web/src/components/modals/PostRolePickerModal.tsx b/apps/web/src/components/modals/PostRolePickerModal.tsx index bf897ca4..86598b55 100644 --- a/apps/web/src/components/modals/PostRolePickerModal.tsx +++ b/apps/web/src/components/modals/PostRolePickerModal.tsx @@ -22,7 +22,7 @@ export function PostRolePickerModal({ open, onOpenChange }: PostRolePickerModalP const navigate = useNavigate(); // Staff/admin can post on any project; everyone else only on the ones they - // maintain. Fetch the most relevant slice for the picker. + // are an admin of. Fetch the most relevant slice for the picker. const isStaff = person?.accountLevel === 'staff' || person?.accountLevel === 'administrator'; @@ -30,7 +30,7 @@ export function PostRolePickerModal({ open, onOpenChange }: PostRolePickerModalP queryKey: ['post-role-picker', person?.slug, isStaff], queryFn: () => { if (isStaff) return api.projects.list({ perPage: 50, sort: '-updatedAt' }); - return api.projects.list({ maintainer: person!.slug, perPage: 50 }); + return api.projects.list({ admin: person!.slug, perPage: 50 }); }, enabled: open && !!person, }); diff --git a/apps/web/src/components/project/JoinBlock.tsx b/apps/web/src/components/project/JoinBlock.tsx new file mode 100644 index 00000000..ecd3581f --- /dev/null +++ b/apps/web/src/components/project/JoinBlock.tsx @@ -0,0 +1,154 @@ +/** + * The Join block at the top of the project sidebar: the caller's + * relationship to the project (specs/screens/project-detail.md → Join). + */ +import { useState } from 'react'; +import { Link } from 'react-router'; +import { Button } from '@/components/ui/button'; +import { Checkbox } from '@/components/ui/checkbox'; +import { Label } from '@/components/ui/label'; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from '@/components/ui/dropdown-menu'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { api, ApiError, type ProjectDetail } from '@/lib/api'; + +interface JoinBlockProps { + project: ProjectDetail; + signedIn: boolean; + /** Refetch the project after a change. */ + onChanged: () => Promise<unknown>; +} + +export function JoinBlock({ project, signedIn, onChanged }: JoinBlockProps) { + const viewer = project.viewer; + const [leaveOpen, setLeaveOpen] = useState(false); + + if (!signedIn) { + return ( + <section aria-label="Join this project"> + <Button asChild variant="outline" className="w-full"> + <Link to={`/login?return=${encodeURIComponent(`/projects/${project.slug}`)}`}> + Sign in to follow or apply + </Link> + </Button> + </section> + ); + } + + if (viewer?.state !== 'member') return null; + + return ( + <section aria-label="Your membership" className="space-y-2"> + <div className="flex items-center justify-between gap-2 rounded-md border border-border p-3"> + <p className="text-sm"> + You're a member + {viewer.isAdmin && ( + <span className="ml-2 inline-flex items-center rounded-full bg-primary/15 text-primary px-1.5 py-0.5 text-xs"> + Admin + </span> + )} + </p> + <DropdownMenu> + <DropdownMenuTrigger asChild> + <Button size="sm" variant="ghost" aria-label="Membership options"> + ⋯ + </Button> + </DropdownMenuTrigger> + <DropdownMenuContent align="end"> + <DropdownMenuItem onSelect={() => setLeaveOpen(true)}>Leave project</DropdownMenuItem> + </DropdownMenuContent> + </DropdownMenu> + </div> + <LeaveDialog project={project} open={leaveOpen} onOpenChange={setLeaveOpen} onChanged={onChanged} /> + </section> + ); +} + +function LeaveDialog({ + project, + open, + onOpenChange, + onChanged, +}: { + project: ProjectDetail; + open: boolean; + onOpenChange: (open: boolean) => void; + onChanged: () => Promise<unknown>; +}) { + const [alsoUnfollow, setAlsoUnfollow] = useState(false); + const [lastAdmin, setLastAdmin] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + + const close = (o: boolean) => { + if (!o) { + setAlsoUnfollow(false); + setLastAdmin(false); + setError(null); + } + onOpenChange(o); + }; + + const leave = async () => { + setBusy(true); + setError(null); + try { + await api.projects.leave(project.slug, { alsoUnfollow, confirmLastAdmin: lastAdmin }); + close(false); + await onChanged(); + } catch (err) { + if (err instanceof ApiError && err.code === 'last_admin') setLastAdmin(true); + else setError(err instanceof ApiError ? err.message : 'Something went wrong. Please try again.'); + } finally { + setBusy(false); + } + }; + + return ( + <Dialog open={open} onOpenChange={close}> + <DialogContent> + <DialogHeader> + <DialogTitle>Leave {project.title}?</DialogTitle> + <DialogDescription> + You'll come off the member list. Unless you also stop following, you'll still get the + project's updates by email. + </DialogDescription> + </DialogHeader> + <div className="flex items-center gap-2 py-2"> + <Checkbox id="leave-unfollow" checked={alsoUnfollow} onCheckedChange={(v) => setAlsoUnfollow(v === true)} /> + <Label htmlFor="leave-unfollow">Also stop following</Label> + </div> + {lastAdmin && ( + <p className="text-sm text-amber-800 bg-amber-50 border border-amber-300 rounded-md p-3" role="alert"> + You're the project's last active admin. If you leave, the project will have no admin: nobody + can accept applications or manage members until site staff add one. + </p> + )} + {error && ( + <p className="text-sm text-destructive" role="alert"> + {error} + </p> + )} + <DialogFooter> + <Button variant="outline" onClick={() => close(false)} disabled={busy}> + Cancel + </Button> + <Button variant="destructive" onClick={() => void leave()} disabled={busy}> + {busy ? 'Leaving…' : lastAdmin ? 'Leave anyway' : 'Leave project'} + </Button> + </DialogFooter> + </DialogContent> + </Dialog> + ); +} diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index f8619732..8662374d 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -65,6 +65,7 @@ export interface ErrorEnvelope { readonly message: string; readonly traceId?: string; readonly fields?: Record<string, string>; + readonly details?: Record<string, unknown>; }; readonly metadata: ResponseMeta; } @@ -74,14 +75,24 @@ export class ApiError extends Error { readonly code: string; readonly fields?: Record<string, string>; readonly traceId?: string; - - constructor(status: number, code: string, message: string, fields?: Record<string, string>, traceId?: string) { + /** `error.details`, when the API names extra facts (e.g. `reapplyAfter`). */ + readonly details?: Record<string, unknown>; + + constructor( + status: number, + code: string, + message: string, + fields?: Record<string, string>, + traceId?: string, + details?: Record<string, unknown>, + ) { super(message); this.name = 'ApiError'; this.status = status; this.code = code; this.fields = fields; this.traceId = traceId; + this.details = details; } get isServerError(): boolean { @@ -111,7 +122,8 @@ export interface ProjectListItem { readonly summary: string | null; readonly stage: string; readonly overviewExcerpt: string; - readonly maintainer: PersonAvatar | null; + /** Members with `isAdmin`, by joinedAt. */ + readonly admins: PersonAvatar[]; readonly memberCount: number; readonly members: PersonAvatar[]; readonly links: { @@ -130,13 +142,29 @@ export interface ProjectMembershipResponse { readonly projectSlug: string; readonly person: PersonAvatar; readonly role: string | null; - readonly isMaintainer: boolean; + readonly isAdmin: boolean; + /** Shown to project admins and staff only; null for everyone else. */ + readonly via: 'created' | 'added' | 'application' | 'legacy' | null; readonly joinedAt: string; } +export type MembershipState = 'follower' | 'applicant' | 'member'; + +/** The caller's own record on a project (specs/api/projects.md → Project shape). */ +export interface ProjectViewer { + readonly state: MembershipState; + readonly isAdmin: boolean; + readonly muted: boolean; + readonly application: unknown | null; + readonly reapplyAfter: string | null; +} + export interface ProjectPermissions { readonly canEdit: boolean; readonly canManageMembers: boolean; + readonly canReviewApplications: boolean; + readonly canFollow: boolean; + readonly canApply: boolean; readonly canPostUpdate: boolean; readonly canLogBuzz: boolean; readonly canPostHelpWanted: boolean; @@ -160,8 +188,10 @@ export interface ProjectDetail { readonly overviewHtml: string; readonly stage: string; readonly stageProgress: number; - readonly maintainer: PersonAvatar | null; + /** Members only, admins first. */ readonly memberships: ProjectMembershipResponse[]; + readonly hasActiveAdmin: boolean; + readonly viewer: ProjectViewer | null; readonly openHelpWantedRoles: HelpWantedRoleSummary[]; readonly tags: { topic: TagItem[]; tech: TagItem[]; event: TagItem[] }; readonly links: { @@ -187,6 +217,7 @@ export interface PersonListItem { readonly avatarUrl: string | null; readonly bioExcerpt: string; readonly memberOfCount: number; + readonly adminOfCount: number; readonly tags: TagItem[]; readonly createdAt: string; } @@ -194,7 +225,7 @@ export interface PersonListItem { export interface PersonMembershipSummary { readonly project: { readonly slug: string; readonly title: string; readonly stage: string }; readonly role: string | null; - readonly isMaintainer: boolean; + readonly isAdmin: boolean; readonly joinedAt: string; } @@ -565,7 +596,7 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> { const err = body as ErrorEnvelope; const code = err?.error?.code ?? 'unknown_error'; const message = err?.error?.message ?? `Request failed with status ${res.status}`; - throw new ApiError(res.status, code, message, err?.error?.fields, err?.error?.traceId); + throw new ApiError(res.status, code, message, err?.error?.fields, err?.error?.traceId, err?.error?.details); } return body as T; @@ -576,7 +607,7 @@ export interface ProjectListParams { stage?: string; stageIn?: string; tag?: string[]; - maintainer?: string; + admin?: string; memberSlug?: string; helpWanted?: boolean; featured?: boolean; @@ -681,10 +712,18 @@ export type UpdateHelpWantedInput = Partial<CreateHelpWantedInput>; export interface AddMemberInput { personSlug: string; role?: string | null; + isAdmin?: boolean; } export interface UpdateMembershipInput { role?: string | null; + isAdmin?: boolean; + confirmLastAdmin?: boolean; +} + +export interface LeaveProjectInput { + alsoUnfollow?: boolean; + confirmLastAdmin?: boolean; } export interface ExpressInterestInput { @@ -851,7 +890,7 @@ interface ProjectRef { } export interface MemberFootprint { - readonly memberships: Array<{ project: ProjectRef; role: string; joinedAt: string }>; + readonly memberships: Array<{ project: ProjectRef; role: string | null; isAdmin: boolean; via: string | null; joinedAt: string }>; readonly updates: Array<{ project: ProjectRef; number: number; title: string; postedAt: string }>; readonly buzz: Array<{ project: ProjectRef; slug: string; title: string; postedAt: string }>; readonly blogPosts: Array<{ slug: string; title: string; postedAt: string }>; @@ -947,14 +986,10 @@ export const api = { request(`/api/projects/${encodeURIComponent(slug)}`, { method: 'DELETE' }), restore: (slug: string): Promise<SuccessEnvelope<ProjectDetail>> => request(`/api/projects/${encodeURIComponent(slug)}/restore`, { method: 'POST' }), - join: (slug: string): Promise<void> => - request(`/api/projects/${encodeURIComponent(slug)}/members/join`, { method: 'POST' }), - leave: (slug: string): Promise<void> => - request(`/api/projects/${encodeURIComponent(slug)}/members/leave`, { method: 'POST' }), - changeMaintainer: (slug: string, personSlug: string): Promise<SuccessEnvelope<ProjectDetail>> => - request(`/api/projects/${encodeURIComponent(slug)}/change-maintainer`, { + leave: (slug: string, input: LeaveProjectInput = {}): Promise<unknown> => + request(`/api/projects/${encodeURIComponent(slug)}/members/leave`, { method: 'POST', - body: JSON.stringify({ personSlug }), + body: JSON.stringify(input), }), updates: (slug: string, params: { page?: number; perPage?: number } = {}): Promise<PaginatedEnvelope<ProjectUpdateResponse>> => request(`/api/projects/${encodeURIComponent(slug)}/updates${buildQuery(params)}`), @@ -987,9 +1022,11 @@ export const api = { `/api/projects/${encodeURIComponent(slug)}/members/${encodeURIComponent(personSlug)}`, { method: 'PATCH', body: JSON.stringify(input) }, ), - removeMember: (slug: string, personSlug: string): Promise<void> => + removeMember: (slug: string, personSlug: string, opts: { confirmLastAdmin?: boolean } = {}): Promise<void> => request( - `/api/projects/${encodeURIComponent(slug)}/members/${encodeURIComponent(personSlug)}`, + `/api/projects/${encodeURIComponent(slug)}/members/${encodeURIComponent(personSlug)}${ + opts.confirmLastAdmin ? '?confirmLastAdmin=true' : '' + }`, { method: 'DELETE' }, ), }, diff --git a/apps/web/src/pages/AdminMembers.tsx b/apps/web/src/pages/AdminMembers.tsx index aee5f3d6..e3d624fc 100644 --- a/apps/web/src/pages/AdminMembers.tsx +++ b/apps/web/src/pages/AdminMembers.tsx @@ -455,7 +455,8 @@ function MemberDetailView({ slug }: { slug: string }) { 'Projects', footprint.memberships.map((m) => ( <li key={`${m.project.slug}-${m.joinedAt}`}> - <Link to={`/projects/${m.project.slug}`} className="hover:underline">{m.project.title}</Link> — {m.role}, joined {formatAbsoluteDate(m.joinedAt)} + <Link to={`/projects/${m.project.slug}`} className="hover:underline">{m.project.title}</Link> — {m.role ?? 'member'} + {m.isAdmin ? ', admin' : ''}, joined {formatAbsoluteDate(m.joinedAt)} </li> )), )} diff --git a/apps/web/src/screens/PersonDetail.tsx b/apps/web/src/screens/PersonDetail.tsx index e5d80f9d..89a5d8f8 100644 --- a/apps/web/src/screens/PersonDetail.tsx +++ b/apps/web/src/screens/PersonDetail.tsx @@ -123,9 +123,9 @@ export function PersonDetail() { } }; - // Memberships sorted: maintainer desc, joinedAt desc + // Memberships sorted: admin desc, joinedAt desc const memberships = [...person.memberships].sort((a, b) => { - if (a.isMaintainer !== b.isMaintainer) return a.isMaintainer ? -1 : 1; + if (a.isAdmin !== b.isAdmin) return a.isAdmin ? -1 : 1; return b.joinedAt.localeCompare(a.joinedAt); }); @@ -200,9 +200,9 @@ export function PersonDetail() { {m.role} </span> )} - {m.isMaintainer && ( + {m.isAdmin && ( <span className="inline-flex items-center rounded-full bg-primary/15 text-primary px-2 py-0.5 text-xs"> - Maintainer + Admin </span> )} </div> diff --git a/apps/web/src/screens/ProjectDetail.tsx b/apps/web/src/screens/ProjectDetail.tsx index b99da35f..0d41ae18 100644 --- a/apps/web/src/screens/ProjectDetail.tsx +++ b/apps/web/src/screens/ProjectDetail.tsx @@ -31,6 +31,7 @@ import { AddMemberModal } from '@/components/modals/AddMemberModal'; import { ManageMembersModal } from '@/components/modals/ManageMembersModal'; import { ExpressInterestModal } from '@/components/modals/ExpressInterestModal'; import { FillRoleModal } from '@/components/modals/FillRoleModal'; +import { JoinBlock } from '@/components/project/JoinBlock'; import { useAuth } from '@/hooks/useAuth'; import { api, ApiError, type HelpWantedRoleResponse } from '@/lib/api'; import { formatRelativeTime, formatAbsoluteDate } from '@/lib/time'; @@ -160,18 +161,6 @@ export function ProjectDetail({ anchor }: ProjectDetailProps = {}) { const helpWantedRoles = helpWantedQ.data?.data ?? []; const perms = project.permissions; - // #113 — Join / Leave the project. The endpoints exist; the UI was missing. - // The project response carries no per-viewer membership flag, so membership is - // derived from the members list + the signed-in user. - const myMembership = person - ? project.memberships.find((m) => m.person.slug === person.slug) - : undefined; - const isMember = myMembership !== undefined; - const maintainerCount = project.memberships.filter((m) => m.isMaintainer).length; - // A sole maintainer must transfer the role before leaving (project-detail.md authz). - const isSoleMaintainer = (myMembership?.isMaintainer ?? false) && maintainerCount === 1; - const canJoin = isSignedIn && !isMember; - const canLeave = isMember && !isSoleMaintainer; // Only staff can see a soft-deleted project at all (non-staff get 404), so a // non-null deletedAt here means the viewer is staff; gate anyway for clarity. const isStaff = person?.accountLevel === 'staff' || person?.accountLevel === 'administrator'; @@ -426,40 +415,7 @@ export function ProjectDetail({ anchor }: ProjectDetailProps = {}) { {/* Sidebar */} <aside className="space-y-6"> - {/* Membership — #113 Join / Leave */} - {(canJoin || isMember) && ( - <section className="space-y-2"> - {canJoin && ( - <Button - className="w-full" - disabled={memberBusy} - onClick={() => void runMembership(() => api.projects.join(slug))} - > - {memberBusy ? 'Joining…' : 'Join Project'} - </Button> - )} - {canLeave && ( - <Button - variant="outline" - className="w-full" - disabled={memberBusy} - onClick={() => void runMembership(() => api.projects.leave(slug))} - > - {memberBusy ? 'Leaving…' : 'Leave project'} - </Button> - )} - {isMember && isSoleMaintainer && ( - <p className="text-xs text-muted-foreground"> - You're the sole maintainer. Transfer the maintainer role before you can leave. - </p> - )} - {memberError && ( - <p className="text-sm text-destructive" role="alert"> - {memberError} - </p> - )} - </section> - )} + <JoinBlock project={project} signedIn={isSignedIn} onChanged={() => projectQ.refetch()} /> {/* Project info */} <section> @@ -516,9 +472,9 @@ export function ProjectDetail({ anchor }: ProjectDetailProps = {}) { <PersonAvatar key={m.id} person={m.person} - size={m.isMaintainer ? 56 : 40} - title={`${m.person.fullName}${m.role ? ` · ${m.role}` : ''}${m.isMaintainer ? ' · Maintainer' : ''}`} - className={m.isMaintainer ? 'ring-2 ring-primary' : ''} + size={m.isAdmin ? 64 : 48} + title={`${m.person.fullName}${m.role ? ` · ${m.role}` : ''}${m.isAdmin ? ' · Admin' : ''}`} + className={m.isAdmin ? 'ring-2 ring-primary' : ''} /> ))} </div> diff --git a/apps/web/tests/ManageMembersModal.test.tsx b/apps/web/tests/ManageMembersModal.test.tsx new file mode 100644 index 00000000..954d9edf --- /dev/null +++ b/apps/web/tests/ManageMembersModal.test.tsx @@ -0,0 +1,56 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { renderScreen, mockOk } from './test-utils.js'; +import { ManageMembersModal } from '../src/components/modals/ManageMembersModal.js'; +import type { ProjectDetail } from '../src/lib/api.js'; + +const PROJECT = { + slug: 'sample-project', + title: 'Sample Project', + memberships: [ + { id: 'm0', projectSlug: 'sample-project', role: 'Founder', isAdmin: true, via: 'created', joinedAt: '2026-01-01T00:00:00Z', person: { slug: 'me', fullName: 'Me Person', avatarUrl: null } }, + { id: 'm1', projectSlug: 'sample-project', role: null, isAdmin: false, via: 'added', joinedAt: '2026-02-01T00:00:00Z', person: { slug: 'pat', fullName: 'Pat Example', avatarUrl: null } }, + ], +} as unknown as ProjectDetail; + +const json = (status: number, body: unknown) => + new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); + +describe('ManageMembersModal', () => { + afterEach(() => vi.restoreAllMocks()); + + it('makes a member an admin', async () => { + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(json(200, mockOk({}))); + renderScreen(<ManageMembersModal open onOpenChange={() => {}} project={PROJECT} />); + await userEvent.click(screen.getByRole('button', { name: 'Make admin: Pat Example' })); + await waitFor(() => expect(fetchSpy).toHaveBeenCalled()); + const [url, init] = fetchSpy.mock.calls[0]!; + expect(url).toBe('/api/projects/sample-project/members/pat'); + expect(JSON.parse(String((init as RequestInit).body))).toEqual({ isAdmin: true, confirmLastAdmin: false }); + }); + + it('asks before removing the last admin, then resends with confirmLastAdmin', async () => { + const fetchSpy = vi + .spyOn(globalThis, 'fetch') + .mockResolvedValueOnce(json(409, { success: false, error: { code: 'last_admin', message: 'no admin left' } })) + .mockResolvedValueOnce(json(200, mockOk({}))); + const confirm = vi.spyOn(window, 'confirm').mockReturnValue(true); + renderScreen(<ManageMembersModal open onOpenChange={() => {}} project={PROJECT} />); + await userEvent.click(screen.getByRole('button', { name: 'Remove admin: Me Person' })); + await waitFor(() => expect(fetchSpy).toHaveBeenCalledTimes(2)); + expect(confirm).toHaveBeenCalledWith(expect.stringMatching(/no active admin/)); + const body = JSON.parse(String((fetchSpy.mock.calls[1]![1] as RequestInit).body)); + expect(body).toEqual({ isAdmin: false, confirmLastAdmin: true }); + }); + + it('sends nothing more when the last-admin warning is declined', async () => { + const fetchSpy = vi + .spyOn(globalThis, 'fetch') + .mockResolvedValueOnce(json(409, { success: false, error: { code: 'last_admin', message: 'no admin left' } })); + vi.spyOn(window, 'confirm').mockReturnValue(false); + renderScreen(<ManageMembersModal open onOpenChange={() => {}} project={PROJECT} />); + await userEvent.click(screen.getByRole('button', { name: 'Remove admin: Me Person' })); + await waitFor(() => expect(fetchSpy).toHaveBeenCalledTimes(1)); + }); +}); diff --git a/apps/web/tests/ProjectDetail.test.tsx b/apps/web/tests/ProjectDetail.test.tsx index 4c323a65..38d30064 100644 --- a/apps/web/tests/ProjectDetail.test.tsx +++ b/apps/web/tests/ProjectDetail.test.tsx @@ -14,7 +14,8 @@ const PROJECT = { overviewHtml: '<h3>Hello</h3>', stage: 'prototyping', stageProgress: 0.4, - maintainer: null, + hasActiveAdmin: true, + viewer: null, memberships: [], openHelpWantedRoles: [], tags: { topic: [], tech: [{ namespace: 'tech', slug: 'react', title: 'React' }], event: [] }, @@ -23,6 +24,9 @@ const PROJECT = { permissions: { canEdit: false, canManageMembers: false, + canReviewApplications: false, + canFollow: false, + canApply: false, canPostUpdate: false, canLogBuzz: false, canPostHelpWanted: false, @@ -258,29 +262,37 @@ describe('ProjectDetail', () => { ); } - it('shows "Join Project" for a signed-in non-member', async () => { - mockSignedIn(PROJECT); // memberships: [] + it('has no Join button for a signed-in non-member: joining is by application or an admin', async () => { + mockSignedIn(PROJECT); // memberships: [], viewer: null renderDetail(); - await waitFor(() => { - expect(screen.getByRole('button', { name: /join project/i })).toBeInTheDocument(); - }); - expect(screen.queryByRole('button', { name: /leave project/i })).not.toBeInTheDocument(); + await screen.findByRole('heading', { name: 'Sample Project', level: 1 }); + expect(screen.queryByRole('button', { name: /join/i })).not.toBeInTheDocument(); + expect(screen.queryByText(/you're a member/i)).not.toBeInTheDocument(); }); - it('shows "Leave project" for a member (not sole maintainer)', async () => { + it('shows the member row with Leave for a member, and marks admins', async () => { const asMember = { ...PROJECT, memberships: [ - { id: 'm1', role: 'contributor', isMaintainer: false, joinedAt: '2026-02-01T00:00:00Z', person: { slug: 'me', fullName: 'Me Person', avatarUrl: null } }, + { id: 'm0', projectSlug: 'sample-project', role: 'Founder', isAdmin: true, via: null, joinedAt: '2026-01-01T00:00:00Z', person: { slug: 'boss', fullName: 'Boss Person', avatarUrl: null } }, + { id: 'm1', projectSlug: 'sample-project', role: 'contributor', isAdmin: false, via: null, joinedAt: '2026-02-01T00:00:00Z', person: { slug: 'me', fullName: 'Me Person', avatarUrl: null } }, ], - counts: { ...PROJECT.counts, members: 1 }, + viewer: { state: 'member', isAdmin: false, muted: false, application: null, reapplyAfter: null }, + counts: { ...PROJECT.counts, members: 2 }, } as unknown as typeof PROJECT; mockSignedIn(asMember); renderDetail(); - await waitFor(() => { - expect(screen.getByRole('button', { name: /leave project/i })).toBeInTheDocument(); - }); - expect(screen.queryByRole('button', { name: /join project/i })).not.toBeInTheDocument(); + expect(await screen.findByText(/you're a member/i)).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /membership options/i })).toBeInTheDocument(); + expect(screen.getByTitle('Boss Person · Founder · Admin')).toBeInTheDocument(); + }); + + it('asks a signed-out visitor to sign in to follow or apply', async () => { + renderDetail(); + expect(await screen.findByRole('link', { name: /sign in to follow or apply/i })).toHaveAttribute( + 'href', + '/login?return=%2Fprojects%2Fsample-project', + ); }); it('shows the soft-delete banner + Restore for staff viewing a deleted project', async () => { diff --git a/apps/web/tests/ProjectEdit.test.tsx b/apps/web/tests/ProjectEdit.test.tsx index ab737eab..79230153 100644 --- a/apps/web/tests/ProjectEdit.test.tsx +++ b/apps/web/tests/ProjectEdit.test.tsx @@ -23,7 +23,8 @@ const NEW_PROJECT = { overviewHtml: '', stage: 'commenting', stageProgress: 0.1, - maintainer: null, + hasActiveAdmin: true, + viewer: null, memberships: [], openHelpWantedRoles: [], tags: { topic: [], tech: [], event: [] }, diff --git a/apps/web/tests/ProjectsIndex.test.tsx b/apps/web/tests/ProjectsIndex.test.tsx index fc7f9f0b..b8acf964 100644 --- a/apps/web/tests/ProjectsIndex.test.tsx +++ b/apps/web/tests/ProjectsIndex.test.tsx @@ -11,7 +11,7 @@ const SAMPLE_PROJECT = { summary: 'A great civic project', stage: 'maintaining', overviewExcerpt: 'Overview excerpt', - maintainer: null, + admins: [], memberCount: 0, members: [], links: { usersUrl: null, developersUrl: null, chatChannel: null }, From df17984ebc3656c4da436e1c3e0ba8ffe24fed84 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:51:03 +0000 Subject: [PATCH 20/78] chore(plans): mark membership-admins done (PR #269) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- plans/membership-admins.md | 96 +++++++++++++++++++++++++++++++++----- plans/membership-follow.md | 4 ++ 2 files changed, 88 insertions(+), 12 deletions(-) diff --git a/plans/membership-admins.md b/plans/membership-admins.md index ce3b0278..c365b3d0 100644 --- a/plans/membership-admins.md +++ b/plans/membership-admins.md @@ -1,5 +1,5 @@ --- -status: in-progress +status: done depends: [] specs: - specs/behaviors/project-membership.md @@ -18,6 +18,7 @@ specs: - specs/screens/person-detail.md - specs/screens/people-index.md - specs/screens/projects-index.md +pr: 269 --- # Plan: Project admins and the membership record @@ -105,17 +106,17 @@ applications and the no-active-admin Apply state - [ ] `project-memberships/v3` and `projects/v3` are generated, committed, adopted on the data repo's `empty`, `fixture` and `legacy-import` branches, and mirrored; CI's contract and mirror checks pass - [ ] Migration on a copy of `legacy-import`: every membership is `state = member`, `via = legacy`; a membership is admin iff it was `isMaintainer` or its person was the project's `maintainerId`; no record keeps `isMaintainer`, no project keeps `maintainerId`; a second run makes no commit; output is counts only -- [ ] Creating a project writes the founder membership (`member`, admin, `Founder`, `via = created`) in the project's commit -- [ ] Tests: a project admin and staff can add (from no record, follower and applicant records written by fixture), promote, demote, remove and relabel; a plain member gets `403`; a member may change only their own `role` -- [ ] Tests: demote, remove or leave that would leave no active admin returns `409 last_admin` without `confirmLastAdmin` and succeeds with it -- [ ] Tests: leave moves the record to `follower` clearing `role`/`isAdmin`/`via`/`joinedAt`; `alsoUnfollow` deletes it; remove deletes it -- [ ] `POST …/members/join` and `POST …/change-maintainer` return `410 gone` -- [ ] Add sends one notice email to the added person (notifier test double), with no address written to any record or commit -- [ ] `GET /api/projects/:slug` lists members only, admins first; `memberOfCount`/`adminOfCount` and person `memberships` count members only; a follower fixture appears in none of them -- [ ] Agent purge test: a member added by an admin to a project with another member is refused `409 shared_project`; a follower-only footprint is not -- [ ] Account merge test: two records on one project collapse to the one further along -- [ ] Browser: on a project page as admin, make a co-admin, remove admin from yourself with the last-admin confirmation, add a member; as a non-member, no Join button exists -- [ ] `npm run type-check && npm run lint && npm test` clean +- [x] Creating a project writes the founder membership (`member`, admin, `Founder`, `via = created`) in the project's commit +- [x] Tests: a project admin and staff can add (from no record, follower and applicant records written by fixture), promote, demote, remove and relabel; a plain member gets `403`; a member may change only their own `role` +- [x] Tests: demote, remove or leave that would leave no active admin returns `409 last_admin` without `confirmLastAdmin` and succeeds with it +- [x] Tests: leave moves the record to `follower` clearing `role`/`isAdmin`/`via`/`joinedAt`; `alsoUnfollow` deletes it; remove deletes it +- [x] `POST …/members/join` and `POST …/change-maintainer` return `410 gone` +- [x] Add sends one notice email to the added person (notifier test double), with no address written to any record or commit +- [x] `GET /api/projects/:slug` lists members only, admins first; `memberOfCount`/`adminOfCount` and person `memberships` count members only; a follower fixture appears in none of them +- [x] Agent purge test: a member added by an admin to a project with another member is refused `409 shared_project`; a follower-only footprint is not +- [x] Account merge test: two records on one project collapse to the one further along +- [x] Browser: on a project page as admin, make a co-admin, remove admin from yourself with the last-admin confirmation, add a member; as a non-member, no Join button exists +- [x] `npm run type-check && npm run lint && npm test` clean ## Risks / unknowns @@ -125,4 +126,75 @@ applications and the no-active-admin Apply state ## Notes +- **Not verified here: the data repo.** The v3 contracts are generated, + committed and mirrored into `apps/api/gitsheets/` (vendored with + `gitsheets contracts adopt`; provenance lands when the data repo adopts + from the published URL), and `check-contracts` passes. Adopting them on + the data repo's `empty`, `fixture` and `legacy-import` branches is work in + `codeforphilly-data` that this branch could not do, so the first criterion + stays open; CI's `check:sheet-configs` will report drift until it lands. +- **Not verified here: the migration on a copy of `legacy-import`.** It ran + only against made-up fixtures (`tests/migration-project-admins.test.ts`): + the admin union (a flag-only admin, a `maintainerId`-only admin, a plain + member, a `maintainerId` naming someone with no membership), no + `isMaintainer`/`maintainerId` left, counts-only output, no commit on a + second run, and `gitsheets contracts verify` passing. Closes out when it is + run on a copy of `legacy-import` in the data-repo PR. +- **Deploy order for the migration.** v2-shape memberships lack `state` and + `followedAt`, so adopting v3 first fails (`contracts adopt --sheet` + validates every record; the test shows `verify` rejecting them). Run the + migration while the sheets declare v2 (its records satisfy v2, which is + open for extension), then adopt v3, then deploy. The test exercises that + order. The old API reading migrated records in that window sees no + maintainers, so do it in the maintenance window right before the deploy. +- **Spec fix in this PR.** `project-membership.md` and `projects.md` said + deactivated people are left out of the members list; `person-lifecycle.md` + and the site show them as the "Deactivated user" placeholder. Fixed in + `docs(specs): keep deactivated members as placeholders on member lists`: + follower and applicant records go quiet, a deactivated member keeps the + placeholder, gets no email and is never an active admin. The Approach line + above ("filter … deactivated people") predates that fix. +- **"Active" in the last-admin rule** counts admins who are not deactivated. + `hasActiveAdmin` (the Apply gate) additionally needs a deliverable email or + a Slack link; the last-admin check does not, so an admin whose address + bounced still counts as someone running the project. +- **`hasActiveAdmin`'s Slack half** reads `PrivateProfile.slack` loosely + (present and non-null). No profile carries it until + [`slack-account-link`](slack-account-link.md) adds the field, at which point + it works with no change here. +- `ProjectService.get` is async now (it reads private profiles for + `hasActiveAdmin`). The project detail and list item no longer carry + `maintainer`; the list item carries `admins`. +- `permissions.canApply` stays `false` until + [`membership-applications`](membership-applications.md) passes + `hasActiveAdmin` into it; `canFollow` is computed but has no endpoint until + [`membership-follow`](membership-follow.md). +- The help-wanted fill side effect still adds the filler as a member + (now `via = added`, v3 shape) until + [`needs-on-applications`](needs-on-applications.md) makes fills + members-only. +- In-memory `adminsByProject` index (personSlugs of `member` records with + `isAdmin`), maintained by `indexMembership`/`unindexMembership`. The + account merge applies removals before upserts because a dropped record and + the re-pointed one share the (project, person) key that index uses. +- Error envelopes can carry `error.details` now (`ConflictError` takes it); + retired endpoints throw `GoneError` (410). `join` answers + `error.code = "join_removed"`, `change-maintainer` `gone`. +- Browser check done against a local app on a throwaway data repo of + made-up people: made a co-admin, removed admin from a co-admin and then + from myself with the last-admin confirmation (the project then had + `hasActiveAdmin = false`), staff added a member with Make admin (notice + logged), a member left from the Join block, and a signed-in non-member saw + no Join button. + ## Follow-ups + +- Tracked as: adopt `project-memberships/v3` and `projects/v3` on the data + repo's `empty`, `fixture` and `legacy-import` branches (and run the + migration on `fixture` and `legacy-import`) in a `codeforphilly-data` PR; + migrate then adopt on `published` right before the release deploys. +- Tracked as: delete the `410` handlers for `POST …/members/join` and + `POST …/change-maintainer` in the release after next (comments at both + handlers say so), so the paths answer `404`. +- Deferred to [`membership-follow`](membership-follow.md) — the Join block's + member row gets Mute emails beside Leave once `PATCH …/follow` exists. diff --git a/plans/membership-follow.md b/plans/membership-follow.md index 47cb317f..49c0b97f 100644 --- a/plans/membership-follow.md +++ b/plans/membership-follow.md @@ -49,6 +49,9 @@ on `/admin/members`. restart is acceptable, like rate limits). Each email links to the project page, where Mute lives. 4. Web: Join block rows; "Following ✓" menu. +5. The member row of the Join block (built in + [`membership-admins`](membership-admins.md) with Leave only) gets "Mute + emails" beside Leave, through the same `PATCH …/follow`. ## Validation @@ -58,6 +61,7 @@ on `/admin/members`. - [ ] Notifier test double: a new update emails each follower, applicant and member except the poster and muted records; the fourth post in 24 hours sends nothing - [ ] Posting an open need sends the same follower email - [ ] `/admin/members` footprint shows follows (count on the row when non-zero, list in the detail) +- [ ] The Join block's member row offers Mute emails beside Leave (deferred from [`membership-admins`](membership-admins.md)) - [ ] Browser: as a signed-in non-member, Follow, see "Following ✓" and the count rise, Mute, Unfollow - [ ] `npm run type-check && npm run lint && npm test` clean From 72398e9f377185f83a40ec3fcc027e4cfe6053a7 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:51:07 +0000 Subject: [PATCH 21/78] chore(plans): mark membership-follow in-progress Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- plans/membership-follow.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plans/membership-follow.md b/plans/membership-follow.md index 49c0b97f..fc2c939b 100644 --- a/plans/membership-follow.md +++ b/plans/membership-follow.md @@ -1,5 +1,5 @@ --- -status: planned +status: in-progress depends: [membership-admins] specs: - specs/behaviors/project-membership.md From b9ed09ac4f378e3129843e8f58440bb46dc77cff Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:51:11 +0000 Subject: [PATCH 22/78] docs(specs): show follows on the roster row when non-zero api/moderation.md counts follows in each row's footprint and the membership-follow plan shows them on /admin/members, but the row's list of counts shown when non-zero left follows out. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- specs/screens/admin-members.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/specs/screens/admin-members.md b/specs/screens/admin-members.md index a11375af..1cd5cf03 100644 --- a/specs/screens/admin-members.md +++ b/specs/screens/admin-members.md @@ -62,7 +62,7 @@ See [api/moderation.md](../api/moderation.md). the domain is a button that searches `@domain` across the whole roster, so one throwaway address leads to every account from that domain), bio excerpt, compact footprint counts (`2 projects · 1 update · 1 RSVP · 3 tags`; - updates, buzz, posts, applications and RSVPs only when non-zero), and + updates, buzz, posts, applications, follows and RSVPs only when non-zero), and the vote state: - no vote → two buttons **Spam** / **Not spam** - voted → a badge `Spam · by {voter} · {when}` or `Not spam · …` with a From 3dd2aa16be22e8707a2177781bbe061786b523b5 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:03:54 +0000 Subject: [PATCH 23/78] feat(api): follow, unfollow and mute a project POST /follow makes a follower record in one commit; a caller with a record in any state gets it back with no commit, since every state follows. DELETE /follow removes a follower record (409 not_a_follower for applicants and members), and PATCH /follow sets muted in any state and nothing else. Agent accounts are refused. The project carries followerCount and counts.followers: follower and applicant records, deactivated people left out, never names. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/src/routes/projects-members.ts | 75 ++++++++++++++++++- apps/api/src/services/memberships.ts | 14 ++++ .../src/services/project-membership.write.ts | 74 ++++++++++++++++++ apps/api/src/services/project.ts | 3 +- apps/api/src/services/serializers/project.ts | 6 ++ 5 files changed, 170 insertions(+), 2 deletions(-) diff --git a/apps/api/src/routes/projects-members.ts b/apps/api/src/routes/projects-members.ts index 364a24d5..d5cb5fa1 100644 --- a/apps/api/src/routes/projects-members.ts +++ b/apps/api/src/routes/projects-members.ts @@ -5,11 +5,14 @@ * DELETE /api/projects/:slug/members/:personSlug * POST /api/projects/:slug/members/leave * POST /api/projects/:slug/members/join (410: removed) + * POST /api/projects/:slug/follow + * DELETE /api/projects/:slug/follow + * PATCH /api/projects/:slug/follow */ import type { FastifyInstance, FastifyRequest } from 'fastify'; import type { ProjectMembership } from '@cfp/shared/schemas'; import { ok } from '../lib/response.js'; -import { GoneError } from '../lib/errors.js'; +import { ApiValidationError, GoneError } from '../lib/errors.js'; import { buildTransactionOptions } from '../store/commit-meta.js'; import { personBySlug } from '../store/memory/state.js'; import { serializeProjectMembership } from '../services/serializers/project.js'; @@ -198,4 +201,74 @@ export async function projectMembershipRoutes(fastify: FastifyInstance): Promise if (!m) return reply.code(204).send(); return ok({ state: m.state, muted: m.muted === true, followedAt: m.followedAt }); }); + + const followShape = (m: ProjectMembership) => ({ state: m.state, muted: m.muted === true, followedAt: m.followedAt }); + const PROJECT_PARAMS = { type: 'object', properties: { slug: { type: 'string' } }, required: ['slug'] } as const; + + // POST /api/projects/:slug/follow — follow; any existing record is a 200 no-op + fastify.post('/api/projects/:slug/follow', { + schema: { tags: ['project-memberships'], summary: 'Follow the project', params: PROJECT_PARAMS }, + }, async (request, reply) => { + const { slug } = request.params as { slug: string }; + const existing = fastify.services.projectMembershipsWrite.ownRecord(slug, request.session); + if (existing) return ok(followShape(existing)); + const result = await fastify.store.transact( + buildTransactionOptions({ + request, + action: 'project-membership.follow', + subjectType: 'project-membership', + subjectSlug: `${slug}/${request.session.person!.slug}`, + responseCode: 201, + }), + async (tx) => fastify.services.projectMembershipsWrite.follow(tx, slug, request.session), + ); + result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); + reply.code(201); + return ok(followShape(result.value.membership)); + }); + + // DELETE /api/projects/:slug/follow — unfollow (followers only) + fastify.delete('/api/projects/:slug/follow', { + schema: { tags: ['project-memberships'], summary: 'Stop following the project', params: PROJECT_PARAMS }, + }, async (request, reply) => { + const { slug } = request.params as { slug: string }; + const result = await fastify.store.transact( + buildTransactionOptions({ + request, + action: 'project-membership.unfollow', + subjectType: 'project-membership', + subjectSlug: `${slug}/${request.session.person?.slug ?? 'anon'}`, + responseCode: 204, + }), + async (tx) => fastify.services.projectMembershipsWrite.unfollow(tx, slug, request.session), + ); + result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); + return reply.code(204).send(); + }); + + // PATCH /api/projects/:slug/follow — mute / unmute, in any state + fastify.patch('/api/projects/:slug/follow', { + schema: { + tags: ['project-memberships'], + summary: "Mute or unmute this project's follower email", + params: PROJECT_PARAMS, + body: { type: 'object', properties: { muted: { type: 'boolean' } } }, + }, + }, async (request) => { + const { slug } = request.params as { slug: string }; + const { muted } = (request.body ?? {}) as { muted?: boolean }; + if (typeof muted !== 'boolean') throw new ApiValidationError('muted (boolean) is required', { muted: 'required' }); + const result = await fastify.store.transact( + buildTransactionOptions({ + request, + action: 'project-membership.update', + subjectType: 'project-membership', + subjectSlug: `${slug}/${request.session.person?.slug ?? 'anon'}`, + responseCode: 200, + }), + async (tx) => fastify.services.projectMembershipsWrite.setMuted(tx, slug, muted, request.session), + ); + result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); + return ok(followShape(result.value.membership)); + }); } diff --git a/apps/api/src/services/memberships.ts b/apps/api/src/services/memberships.ts index 2ad37af5..5559a104 100644 --- a/apps/api/src/services/memberships.ts +++ b/apps/api/src/services/memberships.ts @@ -57,6 +57,20 @@ export function isProjectMember(state: InMemoryState, projectSlug: string, perso return membershipOf(state, projectSlug, personSlug)?.state === 'member'; } +/** + * The project's follower count: records in state follower or applicant + * whose person is not deactivated (specs/api/projects.md → Project shape). + */ +export function followerCount(state: InMemoryState, projectSlug: string): number { + let n = 0; + for (const m of membershipsOfProject(state, projectSlug)) { + if (m.state === 'member') continue; + const p = personBySlug(state, m.personSlug); + if (p && !p.deletedAt) n += 1; + } + return n; +} + /** Admins of a project as people, deactivated ones included. */ export function adminPeople(state: InMemoryState, projectSlug: string): Person[] { const out: Person[] = []; diff --git a/apps/api/src/services/project-membership.write.ts b/apps/api/src/services/project-membership.write.ts index c0883f37..863dea69 100644 --- a/apps/api/src/services/project-membership.write.ts +++ b/apps/api/src/services/project-membership.write.ts @@ -8,6 +8,9 @@ * (project-admin | staff; self for own role) * - DELETE /api/projects/:slug/members/:personSlug remove (project-admin | staff) * - POST /api/projects/:slug/members/leave leave (user, self) + * - POST /api/projects/:slug/follow follow (user) + * - DELETE /api/projects/:slug/follow unfollow (user, self; followers only) + * - PATCH /api/projects/:slug/follow update (user, self; `muted` only) * * Every transition is one write and one commit; the route names it in the * `Action` trailer. A change that takes the last active admin out needs @@ -257,6 +260,77 @@ export class ProjectMembershipWriteService { return { membership: follower, stateApply: new StateApply().upsertMembership(follower) }; } + /** + * The caller's record on a project, for the follow no-op: following is + * inherent in every state, so a caller with any record gets it back + * unchanged, with no write and no commit. + */ + ownRecord(projectSlug: string, session: SessionContext): ProjectMembership | undefined { + requireAuth('user', { session }); + const { project } = this.#projectOrThrow(projectSlug); + refuseAgent(this.#state, session.person!); + return membershipOf(this.#state, project.slug, session.person!.slug); + } + + /** follow — none → follower. One click, no approval. */ + async follow(tx: DualStoreTx, projectSlug: string, session: SessionContext): Promise<MembershipResult> { + requireAuth('user', { session }); + const { project } = this.#projectOrThrow(projectSlug); + const person = session.person!; + refuseAgent(this.#state, person); + if (membershipOf(this.#state, project.slug, person.slug)) { + throw new ConflictError('You already have a record on this project', 'already_following'); + } + const now = nowIso(); + const membership = ProjectMembershipSchema.parse({ + id: uuidv7(), + projectSlug: project.slug, + personSlug: person.slug, + state: 'follower', + isAdmin: false, + muted: false, + followedAt: now, + createdAt: now, + updatedAt: now, + }); + await tx.public['project-memberships'].upsert(membership); + return { membership, stateApply: new StateApply().upsertMembership(membership) }; + } + + /** unfollow — follower → none. Applicants close their application first; members leave first. */ + async unfollow(tx: DualStoreTx, projectSlug: string, session: SessionContext): Promise<{ stateApply: StateApply }> { + requireAuth('user', { session }); + const { project } = this.#projectOrThrow(projectSlug); + const existing = membershipOf(this.#state, project.slug, session.person!.slug); + if (!existing) throw new ApiNotFoundError('You are not following this project'); + if (existing.state !== 'follower') { + throw new ConflictError( + existing.state === 'applicant' + ? 'Close your application before you stop following' + : 'Leave the project before you stop following', + 'not_a_follower', + ); + } + await tx.public['project-memberships'].delete(existing); + return { stateApply: new StateApply().removeMembership(existing) }; + } + + /** Mute or unmute the project's follower email, in any state. Changes only `muted`. */ + async setMuted( + tx: DualStoreTx, + projectSlug: string, + muted: boolean, + session: SessionContext, + ): Promise<MembershipResult> { + requireAuth('user', { session }); + const { project } = this.#projectOrThrow(projectSlug); + const existing = membershipOf(this.#state, project.slug, session.person!.slug); + if (!existing) throw new ApiNotFoundError('You are not following this project'); + const updated = ProjectMembershipSchema.parse({ ...existing, muted, updatedAt: nowIso() }); + await tx.public['project-memberships'].upsert(updated); + return { membership: updated, stateApply: new StateApply().upsertMembership(updated) }; + } + // --------------------------------------------------------------------------- // helpers // --------------------------------------------------------------------------- diff --git a/apps/api/src/services/project.ts b/apps/api/src/services/project.ts index 8caa4acb..f7beb72c 100644 --- a/apps/api/src/services/project.ts +++ b/apps/api/src/services/project.ts @@ -5,7 +5,7 @@ import type { HelpWantedRole, Person, Project, ProjectMembership, Tag } from '@c import type { InMemoryState } from '../store/memory/state.js'; import type { FtsEngine } from '../store/fts.js'; import type { PrivateStore } from '../store/private/interface.js'; -import { hasActiveAdmin, isProjectAdmin, membersOfProject, membershipOf } from './memberships.js'; +import { followerCount, hasActiveAdmin, isProjectAdmin, membersOfProject, membershipOf } from './memberships.js'; import { computeProjectFacets, type ProjectFacets } from '../store/memory/facets.js'; import type { CallerSession } from './permissions.js'; import { computeProjectPermissions } from './permissions.js'; @@ -292,6 +292,7 @@ export class ProjectService { memberships, memberPeople, showVia: permissions.canManageMembers, + followerCount: followerCount(this.#state, project.slug), hasActiveAdmin: activeAdmin, viewer, openHelpWantedRoles, diff --git a/apps/api/src/services/serializers/project.ts b/apps/api/src/services/serializers/project.ts index ecd7b9c9..683f301c 100644 --- a/apps/api/src/services/serializers/project.ts +++ b/apps/api/src/services/serializers/project.ts @@ -73,6 +73,8 @@ export interface ProjectDetail { readonly stage: string; readonly stageProgress: number; readonly memberships: ProjectMembershipResponse[]; + /** Records in state follower or applicant, deactivated people left out. No names. */ + readonly followerCount: number; readonly hasActiveAdmin: boolean; readonly viewer: ProjectViewer | null; readonly openHelpWantedRoles: HelpWantedRoleSummary[]; @@ -86,6 +88,7 @@ export interface ProjectDetail { readonly updates: number; readonly buzz: number; readonly members: number; + readonly followers: number; }; readonly permissions: ProjectPermissions; readonly featured: boolean; @@ -202,6 +205,7 @@ export function serializeProjectDetail( memberPeople: Map<string, Person>; /** Show each member's `via` (project admins and staff). */ showVia: boolean; + followerCount: number; hasActiveAdmin: boolean; viewer: ProjectViewer | null; openHelpWantedRoles: HelpWantedRole[]; @@ -242,6 +246,7 @@ export function serializeProjectDetail( stage: project.stage, stageProgress: stageProgress(project.stage), memberships, + followerCount: opts.followerCount, hasActiveAdmin: opts.hasActiveAdmin, viewer: opts.viewer, openHelpWantedRoles, @@ -255,6 +260,7 @@ export function serializeProjectDetail( updates: opts.updateCount, buzz: opts.buzzCount, members: opts.memberships.length, + followers: opts.followerCount, }, permissions: opts.permissions, featured: project.featured, From 6195eae5f8feee9990497c8328a6be9bf078d256 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:03:54 +0000 Subject: [PATCH 24/78] feat(api): email followers about new updates and needs A new project update or open need goes to every follower, applicant and member except the poster, skipping muted records and deactivated people, at most three posts per project in 24 hours (an in-process counter, like the rate limits). Addresses come from private profiles at send time; each email links the post and the project page, where Mute lives. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/src/notify/email-notifier.ts | 22 +++- apps/api/src/notify/index.ts | 36 ++++++ apps/api/src/notify/membership-templates.ts | 33 +++++- apps/api/src/plugins/services.ts | 15 +++ apps/api/src/routes/projects-help-wanted.ts | 10 ++ apps/api/src/routes/projects-updates.ts | 10 ++ apps/api/src/services/follower-mail.ts | 122 ++++++++++++++++++++ 7 files changed, 246 insertions(+), 2 deletions(-) create mode 100644 apps/api/src/services/follower-mail.ts diff --git a/apps/api/src/notify/email-notifier.ts b/apps/api/src/notify/email-notifier.ts index 16c419a1..a16fc9b3 100644 --- a/apps/api/src/notify/email-notifier.ts +++ b/apps/api/src/notify/email-notifier.ts @@ -22,7 +22,9 @@ import type { HelpWantedFillNotification, HelpWantedInterestNotification, MemberAddedNotification, + NewNeedNotification, Notifier, + ProjectUpdateNotification, PasswordResetNotification, WelcomeNotification, } from './index.js'; @@ -38,7 +40,7 @@ import { renderPasswordResetEmail, renderWelcomeEmail, } from './templates.js'; -import { renderMemberAddedEmail } from './membership-templates.js'; +import { renderMemberAddedEmail, renderNewNeedEmail, renderProjectUpdateEmail } from './membership-templates.js'; import type { EmailAttachment, EmailTransport } from './transport.js'; /** Common shape of every template renderer's output. */ @@ -98,6 +100,24 @@ export class EmailNotifier implements Notifier { return this.#deliver('member added', ctx, n.email, renderMemberAddedEmail(n, this.#siteHost)); } + async notifyProjectUpdate(n: ProjectUpdateNotification): Promise<{ delivered: boolean }> { + const ctx = { kind: 'follower.update', project: n.projectSlug, number: n.number }; + if (!n.email) { + this.#log.warn(ctx, 'follower update: no email address; skipped'); + return { delivered: false }; + } + return this.#deliver('follower update', ctx, n.email, renderProjectUpdateEmail(n, this.#siteHost)); + } + + async notifyNewNeed(n: NewNeedNotification): Promise<{ delivered: boolean }> { + const ctx = { kind: 'follower.need', project: n.projectSlug, roleId: n.roleId }; + if (!n.email) { + this.#log.warn(ctx, 'follower need: no email address; skipped'); + return { delivered: false }; + } + return this.#deliver('follower need', ctx, n.email, renderNewNeedEmail(n, this.#siteHost)); + } + async notifyWelcomeOnSignup(n: WelcomeNotification): Promise<{ delivered: boolean }> { const ctx = { kind: 'auth.welcome', slug: n.slug }; if (!n.email) { diff --git a/apps/api/src/notify/index.ts b/apps/api/src/notify/index.ts index bdeee996..c288d8cd 100644 --- a/apps/api/src/notify/index.ts +++ b/apps/api/src/notify/index.ts @@ -117,8 +117,34 @@ export interface MemberAddedNotification { readonly addedByName: string; } +/** Fields every follower email carries (project-membership.md → Notifications). */ +interface FollowerEmailBase { + readonly email: string; + readonly fullName: string; + readonly projectTitle: string; + readonly projectSlug: string; +} + +/** A new project update, to the project's followers, applicants and members. */ +export interface ProjectUpdateNotification extends FollowerEmailBase { + readonly number: number; + readonly authorName: string; + /** Plain-text excerpt of the update. */ + readonly excerpt: string; +} + +/** A new open need, to the project's followers, applicants and members. */ +export interface NewNeedNotification extends FollowerEmailBase { + readonly roleId: string; + readonly title: string; + /** Plain-text excerpt of the need's description. */ + readonly excerpt: string; +} + export interface Notifier { notifyMemberAdded(n: MemberAddedNotification): Promise<{ delivered: boolean }>; + notifyProjectUpdate(n: ProjectUpdateNotification): Promise<{ delivered: boolean }>; + notifyNewNeed(n: NewNeedNotification): Promise<{ delivered: boolean }>; notifyHelpWantedInterest(n: HelpWantedInterestNotification): Promise<{ delivered: boolean }>; notifyHelpWantedFilled(n: HelpWantedFillNotification): Promise<{ delivered: boolean }>; notifyWelcomeOnSignup(n: WelcomeNotification): Promise<{ delivered: boolean }>; @@ -146,6 +172,16 @@ export class LoggingNotifier implements Notifier { return { delivered: true }; } + async notifyProjectUpdate(n: ProjectUpdateNotification): Promise<{ delivered: boolean }> { + this.#log.info({ kind: 'follower.update', project: n.projectSlug, number: n.number }, 'follower update notification'); + return { delivered: true }; + } + + async notifyNewNeed(n: NewNeedNotification): Promise<{ delivered: boolean }> { + this.#log.info({ kind: 'follower.need', project: n.projectSlug, roleId: n.roleId }, 'follower need notification'); + return { delivered: true }; + } + async notifyHelpWantedInterest(n: HelpWantedInterestNotification): Promise<{ delivered: boolean }> { this.#log.info({ kind: 'help-wanted.interest', ...n }, 'help-wanted interest notification'); return { delivered: true }; diff --git a/apps/api/src/notify/membership-templates.ts b/apps/api/src/notify/membership-templates.ts index d09b9e87..e3783c16 100644 --- a/apps/api/src/notify/membership-templates.ts +++ b/apps/api/src/notify/membership-templates.ts @@ -6,7 +6,7 @@ * is escaped and shown with its line breaks, never rendered as markdown and * never turned into a link by us. */ -import type { MemberAddedNotification } from './index.js'; +import type { MemberAddedNotification, NewNeedNotification, ProjectUpdateNotification } from './index.js'; export interface MembershipEmail { readonly subject: string; @@ -79,3 +79,34 @@ export function renderMemberAddedEmail(n: MemberAddedNotification, siteHost: str `You're receiving this because a project admin added you to ${n.projectTitle}.`, ); } + +const FOLLOWER_FOOTER = (projectTitle: string): string => + `You're receiving this because you follow ${projectTitle} on Code for Philly. To stop these emails, choose "Mute emails" on the project page.`; + +export function renderProjectUpdateEmail(n: ProjectUpdateNotification, siteHost: string): MembershipEmail { + const url = projectUrl(siteHost, n.projectSlug); + return renderBlocks( + `${n.projectTitle}: update #${n.number}`, + [ + { p: `${n.authorName} posted an update to ${n.projectTitle}:` }, + { quote: n.excerpt }, + { link: `${url}/updates/${n.number}`, label: 'Read the update' }, + { link: url, label: 'Mute these emails on the project page' }, + ], + FOLLOWER_FOOTER(n.projectTitle), + ); +} + +export function renderNewNeedEmail(n: NewNeedNotification, siteHost: string): MembershipEmail { + const url = projectUrl(siteHost, n.projectSlug); + return renderBlocks( + `${n.projectTitle} needs help: ${n.title}`, + [ + { p: `${n.projectTitle} posted a new need: ${n.title}.` }, + { quote: n.excerpt }, + { link: `${url}#help-wanted`, label: 'See the need and apply' }, + { link: url, label: 'Mute these emails on the project page' }, + ], + FOLLOWER_FOOTER(n.projectTitle), + ); +} diff --git a/apps/api/src/plugins/services.ts b/apps/api/src/plugins/services.ts index 14b01016..6049ac50 100644 --- a/apps/api/src/plugins/services.ts +++ b/apps/api/src/plugins/services.ts @@ -40,6 +40,7 @@ import { LoggingNotifier, type Notifier } from '../notify/index.js'; import { EmailNotifier } from '../notify/email-notifier.js'; import { PostmarkTransport } from '../notify/postmark-transport.js'; import { ServerClient } from 'postmark'; +import { FollowerMailer } from '../services/follower-mail.js'; declare module 'fastify' { interface FastifyInstance { @@ -75,6 +76,8 @@ declare module 'fastify' { inMemoryState: InMemoryState; fts: FtsEngine; notifier: Notifier; + /** Follower email for new updates and needs, with the per-project cap. */ + followerMailer: FollowerMailer; } } @@ -105,6 +108,18 @@ async function servicesPlugin(fastify: FastifyInstance): Promise<void> { fastify.decorate('inMemoryState', state); fastify.decorate('fts', fts); fastify.decorate('notifier', notifier); + // Reads fastify.notifier per send, so a test spy on the notifier sees it. + fastify.decorate( + 'followerMailer', + new FollowerMailer({ + state, + privateStore: fastify.store.private, + get notifier() { + return fastify.notifier; + }, + log: fastify.log, + }), + ); const githubAccount = new GitHubAccountService(state); fastify.decorate('services', { diff --git a/apps/api/src/routes/projects-help-wanted.ts b/apps/api/src/routes/projects-help-wanted.ts index 952ba3e7..a07113da 100644 --- a/apps/api/src/routes/projects-help-wanted.ts +++ b/apps/api/src/routes/projects-help-wanted.ts @@ -204,6 +204,16 @@ export async function helpWantedRoutes(fastify: FastifyInstance): Promise<void> async (tx) => fastify.services.helpWantedWrite.create(tx, slug, body, request.session), ); result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); + // Posting an open need emails followers (help-wanted-roles.md → Side effects). + const role = result.value.role; + void fastify.followerMailer + .notify(role.projectSlug, role.postedById, { + kind: 'need', + roleId: role.id, + title: role.title, + description: role.description, + }) + .catch((err: unknown) => fastify.log.error({ err }, 'follower email for need failed')); reply.code(201); return ok(serializeRoleResponse(result.value.role, request)); }); diff --git a/apps/api/src/routes/projects-updates.ts b/apps/api/src/routes/projects-updates.ts index 88465732..a2542b20 100644 --- a/apps/api/src/routes/projects-updates.ts +++ b/apps/api/src/routes/projects-updates.ts @@ -173,6 +173,16 @@ export async function projectUpdateRoutes(fastify: FastifyInstance): Promise<voi async (tx) => fastify.services.projectUpdatesWrite.create(tx, slug, body, request.session), ); result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); + // Followers hear about it (project-membership.md → Notifications); fire-and-forget. + const update = result.value.update; + void fastify.followerMailer + .notify(update.projectSlug, update.authorId ?? null, { + kind: 'update', + number: update.number, + body: update.body, + authorName: request.session.person?.fullName ?? 'A project member', + }) + .catch((err: unknown) => fastify.log.error({ err }, 'follower email for update failed')); reply.code(201); const caller = getCallerSession(request); const fetched = fastify.services.projectUpdates.getForProject( diff --git a/apps/api/src/services/follower-mail.ts b/apps/api/src/services/follower-mail.ts new file mode 100644 index 00000000..2773fe17 --- /dev/null +++ b/apps/api/src/services/follower-mail.ts @@ -0,0 +1,122 @@ +/** + * Follower email — specs/behaviors/project-membership.md → Notifications. + * + * A new project update or a new open need goes to every follower, applicant + * and member of the project except the poster, skipping muted records and + * deactivated people, at most 3 posts per project in any 24 hours. Posts past + * the cap send nothing (they are on the page). The cap is an in-process + * counter: a restart resets it, as it does the rate limits. + * + * Fire-and-forget: callers do not await delivery, and a failure never fails + * the post. Addresses are read from private profiles at send time. + */ +import type { FastifyBaseLogger } from 'fastify'; + +import type { Notifier } from '../notify/index.js'; +import { personBySlug, type InMemoryState } from '../store/memory/state.js'; +import type { PrivateStore } from '../store/private/interface.js'; +import { hasDeliverableEmail, membershipsOfProject } from './memberships.js'; +import { renderMarkdown, truncate } from './serializers/common.js'; + +export const FOLLOWER_EMAIL_CAP = 3; +export const FOLLOWER_EMAIL_WINDOW_MS = 24 * 60 * 60 * 1000; +const EXCERPT_CHARS = 500; + +export type FollowerPost = + | { readonly kind: 'update'; readonly number: number; readonly body: string; readonly authorName: string } + | { readonly kind: 'need'; readonly roleId: string; readonly title: string; readonly description: string }; + +export interface FollowerMailerDeps { + readonly state: InMemoryState; + readonly privateStore: PrivateStore; + readonly notifier: Notifier; + readonly log: FastifyBaseLogger; +} + +export class FollowerMailer { + readonly #d: FollowerMailerDeps; + /** projectSlug → send times (ms) inside the window. */ + readonly #sends = new Map<string, number[]>(); + + constructor(deps: FollowerMailerDeps) { + this.#d = deps; + } + + /** + * Take one slot in the project's cap. False when three posts have already + * gone out in the last 24 hours. + */ + #takeSlot(projectSlug: string, now: number): boolean { + const recent = (this.#sends.get(projectSlug) ?? []).filter((t) => now - t < FOLLOWER_EMAIL_WINDOW_MS); + if (recent.length >= FOLLOWER_EMAIL_CAP) { + this.#sends.set(projectSlug, recent); + return false; + } + recent.push(now); + this.#sends.set(projectSlug, recent); + return true; + } + + /** Who hears about a post on the project: everyone with a record but the poster, unmuted and active. */ + recipients(projectSlug: string, posterId: string | null): Array<{ personId: string; fullName: string }> { + const out: Array<{ personId: string; fullName: string }> = []; + for (const m of membershipsOfProject(this.#d.state, projectSlug)) { + if (m.muted === true) continue; + const person = personBySlug(this.#d.state, m.personSlug); + if (!person || person.deletedAt || person.id === posterId) continue; + out.push({ personId: person.id, fullName: person.fullName }); + } + return out; + } + + /** + * Email the project's followers about a post. Resolves with how many emails + * were attempted; `capped` when the post was past the cap and nothing went. + */ + async notify( + projectSlug: string, + posterId: string | null, + post: FollowerPost, + now: Date = new Date(), + ): Promise<{ attempted: number; capped: boolean }> { + const project = this.#d.state.projects.get(this.#d.state.projectIdBySlug.get(projectSlug) ?? ''); + if (!project || project.deletedAt) return { attempted: 0, capped: false }; + const recipients = this.recipients(projectSlug, posterId); + if (recipients.length === 0) return { attempted: 0, capped: false }; + if (!this.#takeSlot(projectSlug, now.getTime())) { + this.#d.log.info({ project: projectSlug, kind: post.kind }, 'follower email: over the 3-per-24h cap; skipped'); + return { attempted: 0, capped: true }; + } + + let attempted = 0; + for (const r of recipients) { + const profile = await this.#d.privateStore.getProfile(r.personId); + if (!profile || !hasDeliverableEmail(profile)) { + this.#d.log.info({ project: projectSlug, kind: post.kind }, 'follower email: no deliverable address; skipped'); + continue; + } + attempted += 1; + const base = { email: profile.email, fullName: r.fullName, projectTitle: project.title, projectSlug }; + try { + if (post.kind === 'update') { + await this.#d.notifier.notifyProjectUpdate({ + ...base, + number: post.number, + authorName: post.authorName, + excerpt: truncate(renderMarkdown(post.body).excerpt, EXCERPT_CHARS), + }); + } else { + await this.#d.notifier.notifyNewNeed({ + ...base, + roleId: post.roleId, + title: post.title, + excerpt: truncate(renderMarkdown(post.description).excerpt, EXCERPT_CHARS), + }); + } + } catch (err) { + this.#d.log.error({ err, project: projectSlug, kind: post.kind }, 'follower email: send threw'); + } + } + return { attempted, capped: false }; + } +} From f668b1dc141f833ee73f94b58701687dd4c8b22d Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:03:54 +0000 Subject: [PATCH 25/78] feat(moderation): follows in the member footprint The roster row counts follows and the detail lists them with when; they never count toward has-footprint. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/src/services/moderation.ts | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/apps/api/src/services/moderation.ts b/apps/api/src/services/moderation.ts index 94f7c4e1..3c625138 100644 --- a/apps/api/src/services/moderation.ts +++ b/apps/api/src/services/moderation.ts @@ -99,6 +99,8 @@ export interface EarlierPurgeView { export interface FootprintCounts { /** Records in state `member`. */ readonly memberships: number; + /** Records in state `follower`; never counted toward `has-footprint`. */ + readonly follows: number; readonly updates: number; readonly buzz: number; readonly blogPosts: number; @@ -165,6 +167,7 @@ export interface MemberFootprint { via: string | null; joinedAt: string; }>; + readonly follows: Array<{ project: ProjectRef; followedAt: string }>; readonly updates: Array<{ project: ProjectRef; number: number; title: string; postedAt: string }>; readonly buzz: Array<{ project: ProjectRef; slug: string; title: string; postedAt: string }>; readonly blogPosts: Array<{ slug: string; title: string; postedAt: string }>; @@ -563,8 +566,10 @@ export class ModerationService { const emailBounce = profile?.emailBounce ? { type: profile.emailBounce.type, bouncedAt: profile.emailBounce.bouncedAt } : null; + const records = membershipsOfPerson(this.#state, p.slug); const footprint: FootprintCounts = { - memberships: membershipsOfPerson(this.#state, p.slug).filter((m) => m.state === 'member').length, + memberships: records.filter((m) => m.state === 'member').length, + follows: records.filter((m) => m.state === 'follower').length, updates: authored.updates.get(p.id) ?? 0, buzz: authored.buzz.get(p.id) ?? 0, blogPosts: authored.blogPosts.get(p.id) ?? 0, @@ -631,6 +636,14 @@ export class ModerationService { : []; }); + const follows = records + .filter((m) => m.state === 'follower') + .flatMap((m) => { + const project = projectRef(m.projectSlug); + return project ? [{ project, followedAt: m.followedAt }] : []; + }) + .sort((a, b) => b.followedAt.localeCompare(a.followedAt)); + const updates = [...s.projectUpdates.values()] .filter((u) => u.authorId === id) .flatMap((u) => { @@ -680,7 +693,7 @@ export class ModerationService { }) .sort((a, b) => b.createdAt.localeCompare(a.createdAt)); - return { memberships, updates, buzz, blogPosts, helpWantedInterest, tags, rsvps }; + return { memberships, follows, updates, buzz, blogPosts, helpWantedInterest, tags, rsvps }; } #voteView(rec: PersonEvaluation): VoteView { From 796f9228cbcc5c875af8cd4d6876bb27689529a4 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:03:54 +0000 Subject: [PATCH 26/78] test(api): cover follow, mute, the follower count and follower email Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/tests/membership-templates.test.ts | 44 ++++ apps/api/tests/project-follow.test.ts | 236 ++++++++++++++++++++ 2 files changed, 280 insertions(+) create mode 100644 apps/api/tests/membership-templates.test.ts create mode 100644 apps/api/tests/project-follow.test.ts diff --git a/apps/api/tests/membership-templates.test.ts b/apps/api/tests/membership-templates.test.ts new file mode 100644 index 00000000..986befb4 --- /dev/null +++ b/apps/api/tests/membership-templates.test.ts @@ -0,0 +1,44 @@ +/** + * Membership email templates (specs/behaviors/project-membership.md → + * Notifications): who added you, follower email with its mute link, and + * user text shown as escaped plain text. + */ +import { describe, expect, it } from 'vitest'; + +import { + renderMemberAddedEmail, + renderNewNeedEmail, + renderProjectUpdateEmail, +} from '../src/notify/membership-templates.js'; + +const HOST = 'example.org'; +const base = { email: 'pat@example.org', fullName: 'Pat Example', projectTitle: 'Proj', projectSlug: 'proj' }; + +describe('membership email templates', () => { + it('the added notice says who added them and how to leave', () => { + const e = renderMemberAddedEmail({ ...base, addedByName: 'Ada Admin' }, HOST); + expect(e.subject).toBe("You've been added to Proj"); + expect(e.text).toContain('Ada Admin added you as a member of Proj'); + expect(e.text).toContain('leave the project from that page'); + expect(e.text).toContain('https://example.org/projects/proj'); + }); + + it('follower email links the post and the project page, where Mute lives', () => { + const u = renderProjectUpdateEmail({ ...base, number: 4, authorName: 'Ben', excerpt: 'Shipped it.' }, HOST); + expect(u.text).toContain('https://example.org/projects/proj/updates/4'); + expect(u.text).toMatch(/Mute these emails on the project page: https:\/\/example.org\/projects\/proj/); + const n = renderNewNeedEmail({ ...base, roleId: 'r1', title: 'Designer', excerpt: 'Draw maps.' }, HOST); + expect(n.subject).toBe('Proj needs help: Designer'); + expect(n.text).toContain('> Draw maps.'); + }); + + it('escapes user text in HTML and never turns it into links', () => { + const e = renderProjectUpdateEmail( + { ...base, number: 1, authorName: 'Ben', excerpt: '<script>x</script> see https://spam.example' }, + HOST, + ); + expect(e.html).not.toContain('<script>'); + expect(e.html).toContain('<script>'); + expect(e.html).not.toContain('href="https://spam.example"'); + }); +}); diff --git a/apps/api/tests/project-follow.test.ts b/apps/api/tests/project-follow.test.ts new file mode 100644 index 00000000..6deb181b --- /dev/null +++ b/apps/api/tests/project-follow.test.ts @@ -0,0 +1,236 @@ +/** + * Following a project (plans/membership-follow.md): the follow / unfollow / + * mute endpoints, the follower count, follower email for new updates and + * needs with its cap, and follows in the moderation footprint. + * + * Every person here is invented; addresses are example.org. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { mintSessionFor } from '../src/auth/issue.js'; +import { + JWT_KEY, + createAgent, + daysAgo, + fid, + personRecord, + privateProfile, + startAgentTestEnv, + type AgentTestEnv, + type Rec, +} from './helpers/agent-fixtures.js'; + +const P = { ada: 1, ben: 2, cal: 3, dee: 4, eve: 5, fay: 6, sam: 7, root: 8, quiet: 9 }; +const T = '2026-05-01T00:00:00.000Z'; + +const rec = (n: number, person: string, state: 'follower' | 'applicant' | 'member', over: Rec = {}): Rec => ({ + id: fid(100 + n), + projectSlug: 'proj', + personSlug: person, + state, + isAdmin: false, + muted: false, + followedAt: T, + createdAt: T, + updatedAt: T, + ...(state === 'member' ? { via: 'legacy', joinedAt: T } : {}), + ...(state === 'applicant' + ? { application: { status: 'open', roleIds: [], offer: 'Happy to help.', submittedAt: T, visibleAt: T } } + : {}), + ...over, +}); + +const RECORDS: Record<string, Rec[]> = { + people: [ + personRecord(P.ada, 'ada'), + personRecord(P.ben, 'ben'), + personRecord(P.cal, 'cal'), + personRecord(P.dee, 'dee'), + personRecord(P.eve, 'eve'), + personRecord(P.fay, 'fay', { deletedAt: daysAgo(1) }), + personRecord(P.sam, 'sam', { accountLevel: 'staff' }), + personRecord(P.root, 'root', { accountLevel: 'administrator' }), + personRecord(P.quiet, 'quiet'), + ], + projects: [{ id: fid(50), slug: 'proj', title: 'Proj', stage: 'testing', featured: false, createdAt: T, updatedAt: T }], + 'project-memberships': [ + rec(1, 'ada', 'member', { isAdmin: true, role: 'Founder' }), + rec(2, 'ben', 'member'), + rec(3, 'cal', 'follower'), + rec(4, 'dee', 'applicant'), + rec(6, 'fay', 'follower'), + rec(9, 'quiet', 'follower', { muted: true }), + ], +}; +const PROFILES = Object.entries(P).map(([slug, n]) => privateProfile(fid(n), `${slug}@example.org`)); + +type Level = 'user' | 'staff' | 'administrator'; + +describe('following a project', () => { + let env: AgentTestEnv; + + beforeEach(async () => { + env = await startAgentTestEnv({ records: RECORDS, profiles: PROFILES }); + }); + afterEach(async () => { + await env.close(); + }); + + const call = async (who: number | null, method: 'GET' | 'POST' | 'PATCH' | 'DELETE', url: string, payload?: Rec, level: Level = 'user') => + env.app.inject({ + method, + url, + ...(who !== null ? { cookies: { cfp_session: await env.cookie(who, level) } } : {}), + ...(payload !== undefined ? { payload } : {}), + }); + const record = (person: string) => { + const s = env.app.inMemoryState; + for (const id of s.membershipsByPerson.get(person) ?? []) { + const m = s.projectMemberships.get(id); + if (m?.projectSlug === 'proj') return m; + } + return undefined; + }; + const head = async () => (await env.git('rev-parse', 'HEAD')).trim(); + const lastAction = async () => (await env.git('log', '-1', '--format=%B')).match(/^Action: (.+)$/m)?.[1]; + const errCode = (res: { json: () => unknown }) => (res.json() as { error: { code: string } }).error.code; + + describe('follow and unfollow', () => { + it('follow creates a follower record in its own commit; following again changes nothing', async () => { + const res = await call(P.eve, 'POST', '/api/projects/proj/follow'); + expect(res.statusCode, res.body).toBe(201); + expect(res.json<{ data: Rec }>().data).toMatchObject({ state: 'follower', muted: false }); + expect(record('eve')).toMatchObject({ state: 'follower', isAdmin: false }); + expect(await lastAction()).toBe('project-membership.follow'); + + const before = await head(); + const again = await call(P.eve, 'POST', '/api/projects/proj/follow'); + expect(again.statusCode).toBe(200); + expect(await head()).toBe(before); + }); + + it('a member or applicant following gets their record back unchanged, with no commit', async () => { + const before = await head(); + for (const who of [P.ada, P.dee]) { + const res = await call(who, 'POST', '/api/projects/proj/follow'); + expect(res.statusCode).toBe(200); + } + expect(await head()).toBe(before); + expect(record('ada')).toMatchObject({ state: 'member', isAdmin: true }); + }); + + it('unfollow deletes a follower record; applicants and members get 409 not_a_follower; no record is 404', async () => { + const res = await call(P.cal, 'DELETE', '/api/projects/proj/follow'); + expect(res.statusCode).toBe(204); + expect(record('cal')).toBeUndefined(); + expect(await lastAction()).toBe('project-membership.unfollow'); + for (const who of [P.dee, P.ben]) { + const r = await call(who, 'DELETE', '/api/projects/proj/follow'); + expect(r.statusCode).toBe(409); + expect(errCode(r)).toBe('not_a_follower'); + } + expect((await call(P.eve, 'DELETE', '/api/projects/proj/follow')).statusCode).toBe(404); + }); + + it('anonymous callers get 401; an agent account is refused (422 agent_account)', async () => { + expect((await call(null, 'POST', '/api/projects/proj/follow')).statusCode).toBe(401); + const agent = await createAgent(env, await env.cookie(P.root, 'administrator'), { slug: 'helper-bot', scopes: ['moderation:read'] }); + const cookie = (await mintSessionFor(agent.personId, 'user', JWT_KEY)).accessToken; + const res = await env.app.inject({ method: 'POST', url: '/api/projects/proj/follow', cookies: { cfp_session: cookie } }); + expect(res.statusCode).toBe(422); + expect(errCode(res)).toBe('agent_account'); + }); + }); + + describe('mute', () => { + it('toggles muted in every state and nothing else', async () => { + for (const [who, slug] of [[P.cal, 'cal'], [P.dee, 'dee'], [P.ada, 'ada']] as const) { + const before = record(slug)!; + const res = await call(who, 'PATCH', '/api/projects/proj/follow', { muted: true }); + expect(res.statusCode, res.body).toBe(200); + const after = record(slug)!; + expect(after.muted).toBe(true); + const bare = (m: object) => Object.fromEntries(Object.entries(m).filter(([k, v]) => v != null && k !== 'muted' && k !== 'updatedAt')); + expect(bare(after)).toEqual(bare(before)); + await call(who, 'PATCH', '/api/projects/proj/follow', { muted: false }); + expect(record(slug)!.muted).toBe(false); + } + expect((await call(P.eve, 'PATCH', '/api/projects/proj/follow', { muted: true })).statusCode).toBe(404); + }); + }); + + describe('follower count', () => { + it('counts followers and applicants, leaves out a deactivated follower, and names no one', async () => { + const data = (await call(null, 'GET', '/api/projects/proj')).json<{ data: Rec }>().data; + // cal, dee, quiet; fay is deactivated. + expect(data['followerCount']).toBe(3); + expect(data['counts']).toMatchObject({ members: 2, followers: 3 }); + + const responses = [ + (await call(null, 'GET', '/api/projects/proj')).body, + (await call(null, 'GET', '/api/projects')).body, + (await call(null, 'GET', '/api/people/ada')).body, + ]; + for (const body of responses) { + for (const slug of ['cal', 'dee', 'quiet', 'fay']) expect(body).not.toContain(`"${slug}"`); + } + + await call(P.sam, 'POST', '/api/people/cal/deactivate', {}, 'staff'); + expect((await call(null, 'GET', '/api/projects/proj')).json<{ data: Rec }>().data['followerCount']).toBe(2); + await call(P.sam, 'POST', '/api/people/cal/reactivate', {}, 'staff'); + expect((await call(null, 'GET', '/api/projects/proj')).json<{ data: Rec }>().data['followerCount']).toBe(3); + }); + }); + + describe('follower email', () => { + it('a new update emails every follower, applicant and member but the poster and muted records', async () => { + const spy = vi.spyOn(env.app.notifier, 'notifyProjectUpdate'); + const res = await call(P.ben, 'POST', '/api/projects/proj/updates', { body: 'We shipped the **map**.' }); + expect(res.statusCode, res.body).toBe(201); + await vi.waitFor(() => expect(spy).toHaveBeenCalledTimes(3)); + const to = spy.mock.calls.map((c) => c[0].email).sort(); + // ada (member), cal (follower), dee (applicant); not ben (poster), quiet (muted), fay (deactivated). + expect(to).toEqual(['ada@example.org', 'cal@example.org', 'dee@example.org']); + expect(spy.mock.calls[0]![0]).toMatchObject({ projectSlug: 'proj', number: 1, excerpt: 'We shipped the map.' }); + }); + + it('the fourth post in 24 hours sends nothing', async () => { + const spy = vi.spyOn(env.app.notifier, 'notifyProjectUpdate'); + for (let i = 1; i <= 3; i++) { + await call(P.ben, 'POST', '/api/projects/proj/updates', { body: `Update ${i}` }); + await vi.waitFor(() => expect(spy).toHaveBeenCalledTimes(3 * i)); + } + const fourth = await call(P.ben, 'POST', '/api/projects/proj/updates', { body: 'Update 4' }); + expect(fourth.statusCode).toBe(201); + await new Promise((r) => setTimeout(r, 200)); + expect(spy).toHaveBeenCalledTimes(9); + }); + + it('posting an open need sends the same follower email', async () => { + const spy = vi.spyOn(env.app.notifier, 'notifyNewNeed'); + const res = await call(P.ada, 'POST', '/api/projects/proj/help-wanted', { + title: 'Map designer', + description: 'Help us draw the *routes*.', + }); + expect(res.statusCode, res.body).toBe(201); + await vi.waitFor(() => expect(spy).toHaveBeenCalledTimes(3)); + expect(spy.mock.calls.map((c) => c[0].email).sort()).toEqual(['ben@example.org', 'cal@example.org', 'dee@example.org']); + expect(spy.mock.calls[0]![0]).toMatchObject({ title: 'Map designer', excerpt: 'Help us draw the routes.' }); + }); + }); + + describe('moderation footprint', () => { + it('counts follows on the roster row and lists them in the detail, never as footprint', async () => { + const staff = { cookies: { cfp_session: await env.cookie(P.sam, 'staff') } }; + const list = await env.app.inject({ method: 'GET', url: '/api/admin/members?perPage=100', ...staff }); + expect(list.statusCode, list.body).toBe(200); + const cal = list.json<{ data: Array<{ slug: string; footprint: Rec; signals: string[] }> }>().data.find((r) => r.slug === 'cal')!; + expect(cal.footprint).toMatchObject({ memberships: 0, follows: 1 }); + expect(cal.signals).not.toContain('has-footprint'); + const detail = await env.app.inject({ method: 'GET', url: '/api/admin/members/cal', ...staff }); + expect(detail.json<{ data: { footprint: { follows: unknown[] } } }>().data.footprint.follows).toEqual([ + { project: { slug: 'proj', title: 'Proj' }, followedAt: T }, + ]); + }); + }); +}); From f67c0b6fbc2a7fcd49013d15186b7b818a675253 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:03:54 +0000 Subject: [PATCH 27/78] feat(web): follow from the Join block, with mute and the follower count MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed in with no record: Follow. A follower sees Following ✓ with Mute emails and Unfollow; a member's row gains Mute emails beside Leave. '{n} following' shows under the block, never names. The roster row and detail show follows. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/web/src/components/project/JoinBlock.tsx | 111 ++++++++++++++---- apps/web/src/lib/api.ts | 14 +++ apps/web/src/pages/AdminMembers.tsx | 9 ++ apps/web/tests/ProjectDetail.test.tsx | 39 +++++- 4 files changed, 152 insertions(+), 21 deletions(-) diff --git a/apps/web/src/components/project/JoinBlock.tsx b/apps/web/src/components/project/JoinBlock.tsx index ecd3581f..020832c4 100644 --- a/apps/web/src/components/project/JoinBlock.tsx +++ b/apps/web/src/components/project/JoinBlock.tsx @@ -33,46 +33,117 @@ interface JoinBlockProps { export function JoinBlock({ project, signedIn, onChanged }: JoinBlockProps) { const viewer = project.viewer; const [leaveOpen, setLeaveOpen] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + + const run = async (fn: () => Promise<unknown>) => { + setBusy(true); + setError(null); + try { + await fn(); + await onChanged(); + } catch (err) { + setError(err instanceof ApiError ? err.message : 'Something went wrong. Please try again.'); + } finally { + setBusy(false); + } + }; + + const followingLine = + project.followerCount > 0 ? ( + <p className="text-xs text-muted-foreground">{project.followerCount} following</p> + ) : null; + const errorLine = error ? ( + <p className="text-sm text-destructive" role="alert"> + {error} + </p> + ) : null; + const muteItem = viewer ? ( + <DropdownMenuItem onSelect={() => void run(() => api.projects.setMuted(project.slug, !viewer.muted))}> + {viewer.muted ? 'Unmute emails' : 'Mute emails'} + </DropdownMenuItem> + ) : null; if (!signedIn) { return ( - <section aria-label="Join this project"> + <section aria-label="Join this project" className="space-y-2"> <Button asChild variant="outline" className="w-full"> <Link to={`/login?return=${encodeURIComponent(`/projects/${project.slug}`)}`}> Sign in to follow or apply </Link> </Button> + {followingLine} </section> ); } - if (viewer?.state !== 'member') return null; + if (viewer?.state === 'member') { + return ( + <section aria-label="Your membership" className="space-y-2"> + <div className="flex items-center justify-between gap-2 rounded-md border border-border p-3"> + <p className="text-sm"> + You're a member + {viewer.isAdmin && ( + <span className="ml-2 inline-flex items-center rounded-full bg-primary/15 text-primary px-1.5 py-0.5 text-xs"> + Admin + </span> + )} + {viewer.muted && <span className="ml-2 text-xs text-muted-foreground">(emails muted)</span>} + </p> + <DropdownMenu> + <DropdownMenuTrigger asChild> + <Button size="sm" variant="ghost" aria-label="Membership options" disabled={busy}> + ⋯ + </Button> + </DropdownMenuTrigger> + <DropdownMenuContent align="end"> + {muteItem} + <DropdownMenuItem onSelect={() => setLeaveOpen(true)}>Leave project</DropdownMenuItem> + </DropdownMenuContent> + </DropdownMenu> + </div> + {followingLine} + {errorLine} + <LeaveDialog project={project} open={leaveOpen} onOpenChange={setLeaveOpen} onChanged={onChanged} /> + </section> + ); + } - return ( - <section aria-label="Your membership" className="space-y-2"> - <div className="flex items-center justify-between gap-2 rounded-md border border-border p-3"> - <p className="text-sm"> - You're a member - {viewer.isAdmin && ( - <span className="ml-2 inline-flex items-center rounded-full bg-primary/15 text-primary px-1.5 py-0.5 text-xs"> - Admin - </span> - )} - </p> + if (viewer?.state === 'follower') { + return ( + <section aria-label="Following this project" className="space-y-2"> <DropdownMenu> <DropdownMenuTrigger asChild> - <Button size="sm" variant="ghost" aria-label="Membership options"> - ⋯ + <Button variant="outline" className="w-full" disabled={busy}> + Following ✓{viewer.muted ? ' (muted)' : ''} </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> - <DropdownMenuItem onSelect={() => setLeaveOpen(true)}>Leave project</DropdownMenuItem> + {muteItem} + <DropdownMenuItem onSelect={() => void run(() => api.projects.unfollow(project.slug))}> + Unfollow + </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> - </div> - <LeaveDialog project={project} open={leaveOpen} onOpenChange={setLeaveOpen} onChanged={onChanged} /> - </section> - ); + {followingLine} + {errorLine} + </section> + ); + } + + if (viewer === null && project.permissions.canFollow) { + return ( + <section aria-label="Join this project" className="space-y-2"> + <Button className="w-full" disabled={busy} onClick={() => void run(() => api.projects.follow(project.slug))}> + {busy ? 'Following…' : 'Follow'} + </Button> + {followingLine} + {errorLine} + </section> + ); + } + + return followingLine ? <section className="space-y-2">{followingLine}</section> : null; } function LeaveDialog({ diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index 8662374d..59f376da 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -190,6 +190,8 @@ export interface ProjectDetail { readonly stageProgress: number; /** Members only, admins first. */ readonly memberships: ProjectMembershipResponse[]; + /** Followers and applicants, as a count only. */ + readonly followerCount: number; readonly hasActiveAdmin: boolean; readonly viewer: ProjectViewer | null; readonly openHelpWantedRoles: HelpWantedRoleSummary[]; @@ -203,6 +205,7 @@ export interface ProjectDetail { readonly updates: number; readonly buzz: number; readonly members: number; + readonly followers: number; }; readonly permissions: ProjectPermissions; readonly featured: boolean; @@ -854,6 +857,7 @@ export interface MemberRow { readonly bioExcerpt: string; readonly footprint: { readonly memberships: number; + readonly follows: number; readonly updates: number; readonly buzz: number; readonly blogPosts: number; @@ -891,6 +895,7 @@ interface ProjectRef { export interface MemberFootprint { readonly memberships: Array<{ project: ProjectRef; role: string | null; isAdmin: boolean; via: string | null; joinedAt: string }>; + readonly follows: Array<{ project: ProjectRef; followedAt: string }>; readonly updates: Array<{ project: ProjectRef; number: number; title: string; postedAt: string }>; readonly buzz: Array<{ project: ProjectRef; slug: string; title: string; postedAt: string }>; readonly blogPosts: Array<{ slug: string; title: string; postedAt: string }>; @@ -986,6 +991,15 @@ export const api = { request(`/api/projects/${encodeURIComponent(slug)}`, { method: 'DELETE' }), restore: (slug: string): Promise<SuccessEnvelope<ProjectDetail>> => request(`/api/projects/${encodeURIComponent(slug)}/restore`, { method: 'POST' }), + follow: (slug: string): Promise<unknown> => + request(`/api/projects/${encodeURIComponent(slug)}/follow`, { method: 'POST' }), + unfollow: (slug: string): Promise<void> => + request(`/api/projects/${encodeURIComponent(slug)}/follow`, { method: 'DELETE' }), + setMuted: (slug: string, muted: boolean): Promise<unknown> => + request(`/api/projects/${encodeURIComponent(slug)}/follow`, { + method: 'PATCH', + body: JSON.stringify({ muted }), + }), leave: (slug: string, input: LeaveProjectInput = {}): Promise<unknown> => request(`/api/projects/${encodeURIComponent(slug)}/members/leave`, { method: 'POST', diff --git a/apps/web/src/pages/AdminMembers.tsx b/apps/web/src/pages/AdminMembers.tsx index e3d624fc..282586fa 100644 --- a/apps/web/src/pages/AdminMembers.tsx +++ b/apps/web/src/pages/AdminMembers.tsx @@ -333,6 +333,7 @@ function MemberRowView({ fp.buzz ? `${fp.buzz} buzz` : null, fp.blogPosts ? `${fp.blogPosts} post${fp.blogPosts === 1 ? '' : 's'}` : null, fp.helpWantedInterest ? `${fp.helpWantedInterest} help-wanted` : null, + fp.follows ? `${fp.follows} follow${fp.follows === 1 ? '' : 's'}` : null, fp.rsvps ? `${fp.rsvps} RSVP${fp.rsvps === 1 ? '' : 's'}` : null, `${fp.tags} tag${fp.tags === 1 ? '' : 's'}`, ].filter(Boolean); @@ -460,6 +461,14 @@ function MemberDetailView({ slug }: { slug: string }) { </li> )), )} + {section( + 'Follows', + (footprint.follows ?? []).map((f) => ( + <li key={f.project.slug}> + <Link to={`/projects/${f.project.slug}`} className="hover:underline">{f.project.title}</Link> — following since {formatAbsoluteDate(f.followedAt)} + </li> + )), + )} {section( 'Updates', footprint.updates.map((u) => ( diff --git a/apps/web/tests/ProjectDetail.test.tsx b/apps/web/tests/ProjectDetail.test.tsx index 38d30064..64cbe932 100644 --- a/apps/web/tests/ProjectDetail.test.tsx +++ b/apps/web/tests/ProjectDetail.test.tsx @@ -1,5 +1,6 @@ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'; import { screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; import { Routes, Route } from 'react-router'; import { renderScreen, mockOk, mockPaginated } from './test-utils.js'; import { ProjectDetail } from '../src/screens/ProjectDetail.js'; @@ -14,13 +15,14 @@ const PROJECT = { overviewHtml: '<h3>Hello</h3>', stage: 'prototyping', stageProgress: 0.4, + followerCount: 0, hasActiveAdmin: true, viewer: null, memberships: [], openHelpWantedRoles: [], tags: { topic: [], tech: [{ namespace: 'tech', slug: 'react', title: 'React' }], event: [] }, links: { usersUrl: 'https://example.com', developersUrl: null, chatChannel: 'sample' }, - counts: { updates: 0, buzz: 0, members: 0 }, + counts: { updates: 0, buzz: 0, members: 0, followers: 0 }, permissions: { canEdit: false, canManageMembers: false, @@ -287,6 +289,41 @@ describe('ProjectDetail', () => { expect(screen.getByTitle('Boss Person · Founder · Admin')).toBeInTheDocument(); }); + it('offers Follow to a signed-in person with no record, and shows the follower count', async () => { + mockSignedIn({ + ...PROJECT, + followerCount: 4, + permissions: { ...PROJECT.permissions, canFollow: true }, + } as unknown as typeof PROJECT); + renderDetail(); + expect(await screen.findByRole('button', { name: 'Follow' })).toBeInTheDocument(); + expect(screen.getByText('4 following')).toBeInTheDocument(); + }); + + it('shows "Following ✓" with Mute / Unfollow to a follower', async () => { + mockSignedIn({ + ...PROJECT, + followerCount: 1, + viewer: { state: 'follower', isAdmin: false, muted: false, application: null, reapplyAfter: null }, + } as unknown as typeof PROJECT); + renderDetail(); + const button = await screen.findByRole('button', { name: /following ✓/i }); + await userEvent.click(button); + expect(await screen.findByRole('menuitem', { name: 'Mute emails' })).toBeInTheDocument(); + expect(screen.getByRole('menuitem', { name: 'Unfollow' })).toBeInTheDocument(); + }); + + it('gives a member Mute emails beside Leave project', async () => { + mockSignedIn({ + ...PROJECT, + viewer: { state: 'member', isAdmin: false, muted: true, application: null, reapplyAfter: null }, + } as unknown as typeof PROJECT); + renderDetail(); + await userEvent.click(await screen.findByRole('button', { name: /membership options/i })); + expect(await screen.findByRole('menuitem', { name: 'Unmute emails' })).toBeInTheDocument(); + expect(screen.getByRole('menuitem', { name: 'Leave project' })).toBeInTheDocument(); + }); + it('asks a signed-out visitor to sign in to follow or apply', async () => { renderDetail(); expect(await screen.findByRole('link', { name: /sign in to follow or apply/i })).toHaveAttribute( From b382fd6ec1d818d0fc73d6261c1de5e21b8f7dac Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:04:04 +0000 Subject: [PATCH 28/78] chore(plans): mark membership-follow done (PR #269) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- plans/membership-follow.md | 47 ++++++++++++++++++++++++++++++-------- 1 file changed, 37 insertions(+), 10 deletions(-) diff --git a/plans/membership-follow.md b/plans/membership-follow.md index fc2c939b..7dd953e0 100644 --- a/plans/membership-follow.md +++ b/plans/membership-follow.md @@ -1,5 +1,5 @@ --- -status: in-progress +status: done depends: [membership-admins] specs: - specs/behaviors/project-membership.md @@ -9,6 +9,7 @@ specs: - specs/behaviors/help-wanted-roles.md - specs/screens/project-detail.md - specs/screens/admin-members.md +pr: 269 --- # Plan: Follow a project @@ -55,15 +56,15 @@ on `/admin/members`. ## Validation -- [ ] Tests: follow creates a `follower` record and commit `Action: project-membership.follow`; following again changes nothing and makes no commit; unfollow deletes it; unfollow as applicant or member returns `409 not_a_follower` -- [ ] Tests: `PATCH …/follow` toggles `muted` in every state and nothing else -- [ ] `followerCount` counts follower and applicant records and leaves out a deactivated follower; no endpoint returns a follower's identity (checked against project, people and list responses) -- [ ] Notifier test double: a new update emails each follower, applicant and member except the poster and muted records; the fourth post in 24 hours sends nothing -- [ ] Posting an open need sends the same follower email -- [ ] `/admin/members` footprint shows follows (count on the row when non-zero, list in the detail) -- [ ] The Join block's member row offers Mute emails beside Leave (deferred from [`membership-admins`](membership-admins.md)) -- [ ] Browser: as a signed-in non-member, Follow, see "Following ✓" and the count rise, Mute, Unfollow -- [ ] `npm run type-check && npm run lint && npm test` clean +- [x] Tests: follow creates a `follower` record and commit `Action: project-membership.follow`; following again changes nothing and makes no commit; unfollow deletes it; unfollow as applicant or member returns `409 not_a_follower` +- [x] Tests: `PATCH …/follow` toggles `muted` in every state and nothing else +- [x] `followerCount` counts follower and applicant records and leaves out a deactivated follower; no endpoint returns a follower's identity (checked against project, people and list responses) +- [x] Notifier test double: a new update emails each follower, applicant and member except the poster and muted records; the fourth post in 24 hours sends nothing +- [x] Posting an open need sends the same follower email +- [x] `/admin/members` footprint shows follows (count on the row when non-zero, list in the detail) +- [x] The Join block's member row offers Mute emails beside Leave (deferred from [`membership-admins`](membership-admins.md)) +- [x] Browser: as a signed-in non-member, Follow, see "Following ✓" and the count rise, Mute, Unfollow +- [x] `npm run type-check && npm run lint && npm test` clean ## Risks / unknowns @@ -72,4 +73,30 @@ on `/admin/members`. ## Notes +- **Spec fix in this PR.** `admin-members.md` listed the row's counts shown + when non-zero without follows, though `api/moderation.md` counts them and + this plan shows them; fixed in `docs(specs): show follows on the roster row + when non-zero`. +- **Follower count is computed on read**, not kept as a running counter: the + project's records are already indexed by project, so counting follower and + applicant records whose person is not deactivated is cheap and cannot drift + on deactivate/reactivate. Behaviour is the one the Approach describes. +- **The cap counts posts, not emails**: each update or need post takes one of + the project's three slots per rolling 24 hours, whatever the number of + recipients. A post with nobody to tell takes no slot. The counter is + in-process and resets on restart. +- Follower email goes out after the post's commit, fire-and-forget; the + notifier test double (a spy on `app.notifier`) sees each send. +- Muting is `PATCH /follow` with `Action: project-membership.update` (the + transition list has no separate mute action). +- Following when you already hold a record in any state answers `200` with + that record and makes no commit; the route checks before it takes the + write lock. +- Browser check done against a local app on a throwaway data repo of + made-up people: as a signed-in non-member, Follow → "Following ✓" with + "1 following", Mute (record `muted = true`), Unfollow (back to Follow); + as a member, Mute emails from the member row. + ## Follow-ups + +None. From 1959ab7d495a36dc8e3c70815e147e2bba2b68b1 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:04:09 +0000 Subject: [PATCH 29/78] chore(plans): mark membership-applications in-progress Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- plans/membership-applications.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plans/membership-applications.md b/plans/membership-applications.md index 53fde1c0..aad214a1 100644 --- a/plans/membership-applications.md +++ b/plans/membership-applications.md @@ -1,5 +1,5 @@ --- -status: planned +status: in-progress depends: [membership-admins] specs: - specs/behaviors/project-membership.md From 25170649f4267e327344e0e7be3f1af863f356cf Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:11:22 +0000 Subject: [PATCH 30/78] feat(api): apply to join a project, and accept or close applications POST /applications makes the caller an applicant with an open application (needs from the project's open needs and/or an offer of up to 1,500 characters), refused with application_open, already_member, no_active_admin or reapply_too_soon (with reapplyAfter in error.details), 422 for bad needs or offer and 429 past three open applications or five a day. An account under 24 hours old is held until visibleAt. Admins and staff list applications (held ones and deactivated applicants left out, facts only), accept (member via application, labelled by the first need) or close with a note that is emailed and never stored; the applicant may close their own. The project carries viewer.application, viewer.reapplyAfter, canApply (an active admin and no wait) and counts.openApplications for admins and staff. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/src/app.ts | 4 + apps/api/src/plugins/services.ts | 18 + apps/api/src/routes/projects-applications.ts | 202 ++++++++ apps/api/src/services/project-application.ts | 455 ++++++++++++++++++ .../src/services/project-membership.write.ts | 3 +- apps/api/src/services/project.ts | 22 +- apps/api/src/services/serializers/project.ts | 4 + 7 files changed, 705 insertions(+), 3 deletions(-) create mode 100644 apps/api/src/routes/projects-applications.ts create mode 100644 apps/api/src/services/project-application.ts diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index caf88421..32e9a89c 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -43,6 +43,7 @@ import markdownPlugin from './plugins/markdown.js'; import slugRedirectPlugin from './plugins/slug-redirect.js'; import legacyRedirectPlugin from './plugins/legacy-redirect.js'; import eventRemindersPlugin from './plugins/event-reminders.js'; +import applicationSweepPlugin from './plugins/application-sweep.js'; import spamPurgePlugin from './plugins/spam-purge.js'; import rateLimitPlugin from './plugins/rate-limit.js'; import idempotencyPlugin from './plugins/idempotency.js'; @@ -61,6 +62,7 @@ import { helpWantedRoutes } from './routes/projects-help-wanted.js'; import { eventRoutes } from './routes/events.js'; import { eventSeriesRoutes } from './routes/event-series.js'; import { projectMembershipRoutes } from './routes/projects-members.js'; +import { projectApplicationRoutes } from './routes/projects-applications.js'; import { previewRoutes } from './routes/preview.js'; import { attachmentRoutes } from './routes/attachments.js'; import { chatRoutes } from './routes/chat.js'; @@ -163,6 +165,7 @@ export async function buildApp(opts: BuildAppOptions = {}): Promise<FastifyInsta await fastify.register(slugRedirectPlugin); await fastify.register(legacyRedirectPlugin); await fastify.register(eventRemindersPlugin); + await fastify.register(applicationSweepPlugin); // ----- 7. Session middleware (JWT auth) ----- // Before rate-limit and idempotency: all three use onRequest hooks, which run @@ -214,6 +217,7 @@ export async function buildApp(opts: BuildAppOptions = {}): Promise<FastifyInsta await fastify.register(eventRoutes); await fastify.register(eventSeriesRoutes); await fastify.register(projectMembershipRoutes); + await fastify.register(projectApplicationRoutes); await fastify.register(previewRoutes); await fastify.register(attachmentRoutes); await fastify.register(chatRoutes); diff --git a/apps/api/src/plugins/services.ts b/apps/api/src/plugins/services.ts index 6049ac50..d5bf713f 100644 --- a/apps/api/src/plugins/services.ts +++ b/apps/api/src/plugins/services.ts @@ -41,6 +41,8 @@ import { EmailNotifier } from '../notify/email-notifier.js'; import { PostmarkTransport } from '../notify/postmark-transport.js'; import { ServerClient } from 'postmark'; import { FollowerMailer } from '../services/follower-mail.js'; +import { ProjectApplicationService } from '../services/project-application.js'; +import { ApplicationNotices } from '../services/application-notices.js'; declare module 'fastify' { interface FastifyInstance { @@ -59,6 +61,7 @@ declare module 'fastify' { eventSeriesWrite: EventSeriesWriteService; projectsWrite: ProjectWriteService; projectMembershipsWrite: ProjectMembershipWriteService; + applications: ProjectApplicationService; projectUpdatesWrite: ProjectUpdateWriteService; projectBuzzWrite: ProjectBuzzWriteService; helpWantedWrite: HelpWantedWriteService; @@ -78,6 +81,8 @@ declare module 'fastify' { notifier: Notifier; /** Follower email for new updates and needs, with the per-project cap. */ followerMailer: FollowerMailer; + /** Application email to admins and applicants. */ + applicationNotices: ApplicationNotices; } } @@ -121,6 +126,18 @@ async function servicesPlugin(fastify: FastifyInstance): Promise<void> { }), ); + fastify.decorate( + 'applicationNotices', + new ApplicationNotices({ + state, + privateStore: fastify.store.private, + get notifier() { + return fastify.notifier; + }, + log: fastify.log, + }), + ); + const githubAccount = new GitHubAccountService(state); fastify.decorate('services', { projects: new ProjectService(state, fts, fastify.store.private), @@ -136,6 +153,7 @@ async function servicesPlugin(fastify: FastifyInstance): Promise<void> { eventSeriesWrite: new EventSeriesWriteService(state), projectsWrite: new ProjectWriteService(state), projectMembershipsWrite: new ProjectMembershipWriteService(state), + applications: new ProjectApplicationService(state, fastify.store.private), projectUpdatesWrite: new ProjectUpdateWriteService(state), projectBuzzWrite: new ProjectBuzzWriteService(state), helpWantedWrite: new HelpWantedWriteService(state), diff --git a/apps/api/src/routes/projects-applications.ts b/apps/api/src/routes/projects-applications.ts new file mode 100644 index 00000000..255e720e --- /dev/null +++ b/apps/api/src/routes/projects-applications.ts @@ -0,0 +1,202 @@ +/** + * Project application routes (specs/api/projects-applications.md): + * POST /api/projects/:slug/applications + * POST /api/projects/:slug/applications/mine/close + * GET /api/projects/:slug/applications + * POST /api/projects/:slug/applications/:personSlug/accept + * POST /api/projects/:slug/applications/:personSlug/close + * + * Commit bodies never quote the offer or a closing note (the default commit + * message carries the method and path only). The note is passed straight to + * the applicant's email and stored nowhere, logs included. + */ +import type { FastifyInstance } from 'fastify'; + +import { ok } from '../lib/response.js'; +import { buildTransactionOptions } from '../store/commit-meta.js'; +import { personBySlug } from '../store/memory/state.js'; +import { serializeApplication } from '../services/project-application.js'; +import { serializeProjectMembership } from '../services/serializers/project.js'; + +const PROJECT_PARAMS = { type: 'object', properties: { slug: { type: 'string' } }, required: ['slug'] } as const; +const PERSON_PARAMS = { + type: 'object', + properties: { slug: { type: 'string' }, personSlug: { type: 'string' } }, + required: ['slug', 'personSlug'], +} as const; + +export async function projectApplicationRoutes(fastify: FastifyInstance): Promise<void> { + const apps = () => fastify.services.applications; + + // POST /api/projects/:slug/applications — apply + fastify.post('/api/projects/:slug/applications', { + schema: { + tags: ['project-applications'], + summary: 'Apply to join the project', + params: PROJECT_PARAMS, + body: { + type: 'object', + properties: { + roleIds: { type: 'array', items: { type: 'string' } }, + offer: { type: ['string', 'null'] }, + }, + }, + }, + }, async (request, reply) => { + const { slug } = request.params as { slug: string }; + const body = (request.body ?? {}) as { roleIds?: string[]; offer?: string | null }; + const now = new Date(); + const result = await fastify.store.transact( + buildTransactionOptions({ + request, + action: 'project-membership.apply', + subjectType: 'project-membership', + subjectSlug: `${slug}/${request.session.person?.slug ?? 'anon'}`, + responseCode: 201, + }), + async (tx) => apps().apply(tx, slug, body, request.session, now), + ); + result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); + const m = result.value.membership; + apps().noteSubmission(m.personSlug, m.projectSlug, now); + // Old enough to skip the hold: admins hear now (notifiedAt is in this commit). + if (result.value.notifyNow) { + void fastify.applicationNotices + .toAdmins(m, false) + .catch((err: unknown) => fastify.log.error({ err }, 'application notice failed')); + } + reply.code(201); + return ok({ + state: m.state, + application: serializeApplication(fastify.inMemoryState, m.application!, { withDecidedBy: false }), + }); + }); + + // POST /api/projects/:slug/applications/mine/close — the applicant closes their own + fastify.post('/api/projects/:slug/applications/mine/close', { + schema: { tags: ['project-applications'], summary: 'Close your own open application', params: PROJECT_PARAMS }, + }, async (request) => { + const { slug } = request.params as { slug: string }; + const result = await fastify.store.transact( + buildTransactionOptions({ + request, + action: 'project-membership.close', + subjectType: 'project-membership', + subjectSlug: `${slug}/${request.session.person?.slug ?? 'anon'}`, + responseCode: 200, + extraTrailers: { 'Closed-By': 'applicant' }, + }), + async (tx) => apps().closeMine(tx, slug, request.session), + ); + result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); + const m = result.value.membership; + return ok({ + state: m.state, + application: serializeApplication(fastify.inMemoryState, m.application!, { withDecidedBy: false }), + }); + }); + + // GET /api/projects/:slug/applications — admins and staff + fastify.get('/api/projects/:slug/applications', { + schema: { + tags: ['project-applications'], + summary: "List the project's applications", + params: PROJECT_PARAMS, + querystring: { + type: 'object', + properties: { + status: { type: 'string' }, + page: { type: 'integer', minimum: 1 }, + perPage: { type: 'integer', minimum: 1, maximum: 100 }, + }, + }, + }, + }, async (request) => { + const { slug } = request.params as { slug: string }; + const q = request.query as { status?: string; page?: number; perPage?: number }; + const result = apps().list(slug, q, request.session); + const page = Math.max(1, q.page ?? 1); + const perPage = Math.min(100, Math.max(1, q.perPage ?? 20)); + return { + success: true, + data: result.items, + metadata: { + timestamp: new Date().toISOString(), + page, + perPage, + totalItems: result.totalItems, + totalPages: Math.ceil(result.totalItems / perPage), + counts: result.counts, + }, + }; + }); + + // POST /api/projects/:slug/applications/:personSlug/accept + fastify.post('/api/projects/:slug/applications/:personSlug/accept', { + schema: { + tags: ['project-applications'], + summary: 'Accept an application', + params: PERSON_PARAMS, + body: { + type: ['object', 'null'], + properties: { + role: { type: ['string', 'null'] }, + fillRoleIds: { type: 'array', items: { type: 'string' } }, + isAdmin: { type: 'boolean' }, + }, + }, + }, + }, async (request) => { + const { slug, personSlug } = request.params as { slug: string; personSlug: string }; + const body = (request.body ?? {}) as { role?: string | null; isAdmin?: boolean }; + const result = await fastify.store.transact( + buildTransactionOptions({ + request, + action: 'project-membership.accept', + subjectType: 'project-membership', + subjectSlug: `${slug}/${personSlug}`, + responseCode: 200, + }), + async (tx) => apps().accept(tx, slug, personSlug, body, request.session), + ); + result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); + const m = result.value.membership; + void fastify.applicationNotices + .toApplicant(m, 'accepted') + .catch((err: unknown) => fastify.log.error({ err }, 'application decision email failed')); + return ok(serializeProjectMembership(m, personBySlug(fastify.inMemoryState, m.personSlug), { showVia: true })); + }); + + // POST /api/projects/:slug/applications/:personSlug/close — "Close application" + fastify.post('/api/projects/:slug/applications/:personSlug/close', { + schema: { + tags: ['project-applications'], + summary: 'Close an application (the applicant stays a follower)', + params: PERSON_PARAMS, + body: { type: ['object', 'null'], properties: { note: { type: ['string', 'null'] } } }, + }, + }, async (request) => { + const { slug, personSlug } = request.params as { slug: string; personSlug: string }; + const body = (request.body ?? {}) as { note?: string | null }; + const result = await fastify.store.transact( + buildTransactionOptions({ + request, + action: 'project-membership.close', + subjectType: 'project-membership', + subjectSlug: `${slug}/${personSlug}`, + responseCode: 200, + extraTrailers: { 'Closed-By': 'admin' }, + }), + async (tx) => apps().close(tx, slug, personSlug, body, request.session), + ); + result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); + const { membership: m, note } = result.value; + void fastify.applicationNotices + .toApplicant(m, 'closed', note) + .catch((err: unknown) => fastify.log.error({ err }, 'application decision email failed')); + return ok({ + state: m.state, + application: serializeApplication(fastify.inMemoryState, m.application!, { withDecidedBy: true }), + }); + }); +} diff --git a/apps/api/src/services/project-application.ts b/apps/api/src/services/project-application.ts new file mode 100644 index 00000000..ca47541c --- /dev/null +++ b/apps/api/src/services/project-application.ts @@ -0,0 +1,455 @@ +/** + * Project applications — the apply / accept / close transitions of + * specs/behaviors/project-membership.md, made through + * specs/api/projects-applications.md. An application is the `application` + * table on the person's membership record; applying moves the record to + * `state = applicant`. + * + * Commit bodies never quote the offer or a closing note. A closing note is + * returned to the caller for the email and never stored. + */ +import { uuidv7 } from 'uuidv7'; +import { + APPLICATION_OFFER_MAX, + ProjectMembershipSchema, + type ApplicationStatus, + type Person, + type Project, + type ProjectApplication, + type ProjectMembership, +} from '@cfp/shared/schemas'; + +import { requireAuth } from '../auth/require.js'; +import type { SessionContext } from '../auth/middleware.js'; +import { ApiNotFoundError, ApiValidationError, ConflictError, RateLimitedError } from '../lib/errors.js'; +import { personBySlug, projectBySlug, type InMemoryState } from '../store/memory/state.js'; +import type { PrivateStore } from '../store/private/interface.js'; +import { StateApply } from '../store/state-apply.js'; +import type { DualStoreTx } from '../store/store.js'; +import { hasActiveAdmin, membershipOf, membershipsOfPerson, membershipsOfProject } from './memberships.js'; +import { asFollower, checkRole, refuseAgent } from './project-membership.write.js'; +import { serializePersonAvatar, type PersonAvatar } from './serializers/common.js'; + +const HOUR = 60 * 60 * 1000; +const DAY = 24 * HOUR; + +/** New-account hold (project-membership.md → New-account hold). */ +export const NEW_ACCOUNT_HOLD_MS = DAY; +/** After an admin closes an application (project-membership.md → Re-apply limits). */ +export const REAPPLY_WAIT_MS = 30 * DAY; +export const MAX_OPEN_APPLICATIONS = 3; +export const MAX_APPLICATIONS_PER_DAY = 5; +export const NOTE_MAX = 1000; + +const iso = (d: Date): string => d.toISOString(); + +/** When an admin-closed application's re-apply wait ends, if it is still running. */ +export function reapplyAfter(m: ProjectMembership | undefined, now: Date): string | null { + const app = m?.application; + if (!app || app.status !== 'closed' || app.closedBy !== 'admin' || !app.closedAt) return null; + const until = new Date(Date.parse(app.closedAt) + REAPPLY_WAIT_MS); + return until > now ? iso(until) : null; +} + +/** The application is visible to admins: the hold is over. */ +export function isVisible(app: ProjectApplication, now: Date): boolean { + return Date.parse(app.visibleAt) <= now.getTime(); +} + +/** Applications (in any status) whose applicant is not deactivated and whose hold is over. */ +export function visibleApplications(state: InMemoryState, projectSlug: string, now: Date): ProjectMembership[] { + return membershipsOfProject(state, projectSlug).filter((m) => { + if (!m.application || !isVisible(m.application, now)) return false; + const person = personBySlug(state, m.personSlug); + return person !== undefined && !person.deletedAt; + }); +} + +/** `counts.openApplications` for admins and staff. */ +export function openApplicationCount(state: InMemoryState, projectSlug: string, now: Date): number { + return visibleApplications(state, projectSlug, now).filter((m) => m.state === 'applicant').length; +} + +export interface ApplicationRoleRef { + readonly id: string; + readonly title: string; + readonly status: string; +} + +/** specs/api/projects-applications.md → Application shape. */ +export interface ApplicationResponse { + readonly status: ApplicationStatus; + readonly roles: ApplicationRoleRef[]; + readonly offer: string | null; + readonly submittedAt: string; + readonly visibleAt: string; + readonly decidedBy?: PersonAvatar | null; + readonly decidedAt: string | null; + readonly decidedVia: 'site' | 'agent' | null; + readonly closedBy: 'admin' | 'applicant' | 'site' | null; + readonly closedAt: string | null; +} + +export function serializeApplication( + state: InMemoryState, + app: ProjectApplication, + opts: { withDecidedBy: boolean }, +): ApplicationResponse { + const roles = app.roleIds.map((id) => { + const role = state.helpWantedRoles.get(id); + // A role deleted since keeps its id on the application; show it as closed. + return { id, title: role?.title ?? 'Removed need', status: role?.status ?? 'closed' }; + }); + const decider = app.decidedById ? state.people.get(app.decidedById) : undefined; + return { + status: app.status, + roles, + offer: app.offer ?? null, + submittedAt: app.submittedAt, + visibleAt: app.visibleAt, + ...(opts.withDecidedBy ? { decidedBy: decider ? serializePersonAvatar(decider) : null } : {}), + decidedAt: app.decidedAt ?? null, + decidedVia: app.decidedVia ?? null, + closedBy: app.closedBy ?? null, + closedAt: app.closedAt ?? null, + }; +} + +export interface ApplicationListItem { + readonly person: PersonAvatar; + readonly applicant: { + readonly accountCreatedAt: string; + readonly hasGitHubLink: boolean; + readonly memberOf: Array<{ slug: string; title: string }>; + }; + readonly state: ProjectMembership['state']; + readonly application: ApplicationResponse; +} + +/** Facts about an applicant, from public records only: never scores, votes or private fields. */ +export function applicantFacts(state: InMemoryState, person: Person, exceptProject: string): ApplicationListItem['applicant'] { + const memberOf = membershipsOfPerson(state, person.slug) + .filter((m) => m.state === 'member' && m.projectSlug !== exceptProject) + .map((m) => projectBySlug(state, m.projectSlug)) + .filter((p): p is Project => p !== undefined && !p.deletedAt) + .map((p) => ({ slug: p.slug, title: p.title })); + return { + accountCreatedAt: person.createdAt, + hasGitHubLink: typeof person.githubUserId === 'number', + memberOf, + }; +} + +export interface ApplyInput { + readonly roleIds?: string[]; + readonly offer?: string | null; +} + +export interface DecideResult { + readonly membership: ProjectMembership; + readonly stateApply: StateApply; + readonly project: Project; + readonly applicant: Person; +} + +export class ProjectApplicationService { + readonly #state: InMemoryState; + readonly #privateStore: PrivateStore; + /** personSlug → recent submissions; with the records, the 5-per-24h limit. */ + readonly #submissions = new Map<string, Array<{ project: string; at: number }>>(); + + constructor(state: InMemoryState, privateStore: PrivateStore) { + this.#state = state; + this.#privateStore = privateStore; + } + + // --------------------------------------------------------------------------- + // apply / close my application + // --------------------------------------------------------------------------- + + /** + * Every check apply makes, before the write lock: who may apply, the + * project's active admin, the re-apply wait, the needs and offer, and the + * site-wide limits. Returns the cleaned input. + */ + async checkApply( + projectSlug: string, + input: ApplyInput, + session: SessionContext, + now: Date, + ): Promise<{ project: Project; person: Person; roleIds: string[]; offer: string | null }> { + requireAuth('user', { session }); + const project = this.#projectOrThrow(projectSlug); + const person = session.person!; + refuseAgent(this.#state, person); + + const existing = membershipOf(this.#state, project.slug, person.slug); + if (existing?.state === 'member') throw new ConflictError('You are already a member of this project', 'already_member'); + if (existing?.state === 'applicant') { + throw new ConflictError('You already have an open application here', 'application_open'); + } + if (!(await hasActiveAdmin(this.#state, this.#privateStore, project.slug))) { + throw new ConflictError("This project doesn't have an active admin right now", 'no_active_admin'); + } + const wait = reapplyAfter(existing, now); + if (wait) { + throw new ConflictError('You can apply to this project again later', 'reapply_too_soon', { reapplyAfter: wait }); + } + + const roleIds = [...new Set(input.roleIds ?? [])]; + for (const id of roleIds) { + const role = this.#state.helpWantedRoles.get(id); + if (!role || role.projectSlug !== project.slug || role.status !== 'open') { + throw new ApiValidationError('Each selected need must be an open need of this project', { roleIds: 'invalid' }); + } + } + const offer = typeof input.offer === 'string' && input.offer.trim() !== '' ? input.offer : null; + if (offer !== null && offer.length > APPLICATION_OFFER_MAX) { + throw new ApiValidationError(`offer is at most ${APPLICATION_OFFER_MAX} characters`, { offer: 'too_long' }); + } + if (roleIds.length === 0 && offer === null) { + throw new ApiValidationError('Pick a need or tell the admins what you would like to help with', { offer: 'required' }); + } + + const open = membershipsOfPerson(this.#state, person.slug).filter((m) => m.state === 'applicant').length; + if (open >= MAX_OPEN_APPLICATIONS) throw new RateLimitedError(DAY / 1000); + const recent = this.#recentSubmissions(person.slug, now.getTime()); + if (recent.length >= MAX_APPLICATIONS_PER_DAY) { + const frees = recent[recent.length - MAX_APPLICATIONS_PER_DAY]! + DAY; + throw new RateLimitedError(Math.max(1, Math.ceil((frees - now.getTime()) / 1000))); + } + + return { project, person, roleIds, offer }; + } + + /** apply — none or follower → applicant. Call {@link checkApply} first, under the same request. */ + async apply( + tx: DualStoreTx, + projectSlug: string, + input: ApplyInput, + session: SessionContext, + now: Date = new Date(), + ): Promise<{ membership: ProjectMembership; stateApply: StateApply; project: Project; notifyNow: boolean }> { + const { project, person, roleIds, offer } = await this.checkApply(projectSlug, input, session, now); + const existing = membershipOf(this.#state, project.slug, person.slug); + + const holdEnds = Date.parse(person.createdAt) + NEW_ACCOUNT_HOLD_MS; + const visibleAt = new Date(Math.max(now.getTime(), holdEnds)); + const notifyNow = visibleAt.getTime() <= now.getTime(); + const at = iso(now); + + const membership = ProjectMembershipSchema.parse({ + id: existing?.id ?? uuidv7(), + projectSlug: project.slug, + personSlug: person.slug, + state: 'applicant', + isAdmin: false, + muted: existing?.muted ?? false, + followedAt: existing?.followedAt ?? at, + // One application per record: this one replaces any earlier, decided one. + application: { + status: 'open', + roleIds, + offer, + submittedAt: at, + visibleAt: iso(visibleAt), + notifiedAt: notifyNow ? at : null, + }, + createdAt: existing?.createdAt ?? at, + updatedAt: at, + }); + await tx.public['project-memberships'].upsert(membership); + return { membership, stateApply: new StateApply().upsertMembership(membership), project, notifyNow }; + } + + /** Record a submission for the per-day limit, once its commit has landed. */ + noteSubmission(personSlug: string, projectSlug: string, at: Date): void { + const list = this.#submissions.get(personSlug) ?? []; + list.push({ project: projectSlug, at: at.getTime() }); + this.#submissions.set(personSlug, list); + } + + /** Submission times in the last 24 hours: the in-process log and the records, deduplicated. */ + #recentSubmissions(personSlug: string, now: number): number[] { + const seen = new Set<string>(); + const times: number[] = []; + const add = (project: string, at: number) => { + const key = `${project}@${at}`; + if (now - at >= DAY || seen.has(key)) return; + seen.add(key); + times.push(at); + }; + for (const s of this.#submissions.get(personSlug) ?? []) add(s.project, s.at); + for (const m of membershipsOfPerson(this.#state, personSlug)) { + if (m.application) add(m.projectSlug, Date.parse(m.application.submittedAt)); + } + this.#submissions.set( + personSlug, + (this.#submissions.get(personSlug) ?? []).filter((s) => now - s.at < DAY), + ); + return times.sort((a, b) => a - b); + } + + /** close by the applicant — applicant → follower, `closedBy = applicant`. */ + async closeMine( + tx: DualStoreTx, + projectSlug: string, + session: SessionContext, + now: Date = new Date(), + ): Promise<{ membership: ProjectMembership; stateApply: StateApply }> { + requireAuth('user', { session }); + const project = this.#projectOrThrow(projectSlug); + const existing = membershipOf(this.#state, project.slug, session.person!.slug); + if (existing?.state !== 'applicant' || existing.application?.status !== 'open') { + throw new ApiNotFoundError('You have no open application here'); + } + const membership = this.#closed(existing, 'applicant', now, null); + await tx.public['project-memberships'].upsert(membership); + return { membership, stateApply: new StateApply().upsertMembership(membership) }; + } + + // --------------------------------------------------------------------------- + // admin side + // --------------------------------------------------------------------------- + + list( + projectSlug: string, + opts: { status?: string; page?: number; perPage?: number }, + session: SessionContext, + now: Date = new Date(), + ): { items: ApplicationListItem[]; totalItems: number; counts: Record<ApplicationStatus, number> } { + const project = this.#projectOrThrow(projectSlug); + requireAuth('project-admin | staff', { session, project, memberships: membershipsOfProject(this.#state, project.slug) }); + const status = opts.status ?? 'open'; + if (!['open', 'accepted', 'closed', 'all'].includes(status)) { + throw new ApiValidationError('status must be open, accepted, closed or all', { status: 'invalid' }); + } + + const visible = visibleApplications(this.#state, project.slug, now); + const counts: Record<ApplicationStatus, number> = { open: 0, accepted: 0, closed: 0 }; + for (const m of visible) counts[m.application!.status] += 1; + + const chosen = visible + .filter((m) => status === 'all' || m.application!.status === status) + .sort((a, b) => b.application!.submittedAt.localeCompare(a.application!.submittedAt)); + const page = Math.max(1, opts.page ?? 1); + const perPage = Math.min(100, Math.max(1, opts.perPage ?? 20)); + const items = chosen.slice((page - 1) * perPage, page * perPage).map((m) => { + const person = personBySlug(this.#state, m.personSlug)!; + return { + person: serializePersonAvatar(person)!, + applicant: applicantFacts(this.#state, person, project.slug), + state: m.state, + application: serializeApplication(this.#state, m.application!, { withDecidedBy: true }), + }; + }); + return { items, totalItems: chosen.length, counts }; + } + + /** accept — applicant → member (`via = application`). */ + async accept( + tx: DualStoreTx, + projectSlug: string, + personSlug: string, + input: { role?: string | null; isAdmin?: boolean }, + session: SessionContext, + now: Date = new Date(), + ): Promise<DecideResult> { + const { project, applicant, existing } = this.#openApplicationOrThrow(projectSlug, personSlug, session, now); + checkRole(input.role); + if (input.isAdmin === true) refuseAgent(this.#state, applicant); + const app = existing.application!; + const firstNeed = app.roleIds.length > 0 ? this.#state.helpWantedRoles.get(app.roleIds[0]!) : undefined; + const role = input.role === undefined ? (firstNeed?.title ?? null) : input.role; + const at = iso(now); + + const membership = ProjectMembershipSchema.parse({ + ...existing, + state: 'member', + isAdmin: input.isAdmin === true, + role: role === null ? null : role.slice(0, 80), + via: 'application', + joinedAt: at, + application: { ...app, status: 'accepted', decidedById: session.person!.id, decidedAt: at, decidedVia: 'site' }, + updatedAt: at, + }); + await tx.public['project-memberships'].upsert(membership); + return { membership, stateApply: new StateApply().upsertMembership(membership), project, applicant }; + } + + /** close by an admin ("Close application") — applicant → follower, `closedBy = admin`. */ + async close( + tx: DualStoreTx, + projectSlug: string, + personSlug: string, + input: { note?: string | null }, + session: SessionContext, + now: Date = new Date(), + ): Promise<DecideResult & { note: string | null }> { + const { project, applicant, existing } = this.#openApplicationOrThrow(projectSlug, personSlug, session, now); + const note = typeof input.note === 'string' && input.note.trim() !== '' ? input.note : null; + if (note !== null && note.length > NOTE_MAX) { + throw new ApiValidationError(`note is at most ${NOTE_MAX} characters`, { note: 'too_long' }); + } + const membership = this.#closed(existing, 'admin', now, session.person!.id); + await tx.public['project-memberships'].upsert(membership); + return { membership, stateApply: new StateApply().upsertMembership(membership), project, applicant, note }; + } + + // --------------------------------------------------------------------------- + // helpers + // --------------------------------------------------------------------------- + + /** The record closed: back to follower, the application kept as history. */ + #closed( + m: ProjectMembership, + closedBy: 'admin' | 'applicant' | 'site', + now: Date, + decidedById: string | null, + ): ProjectMembership { + const at = iso(now); + return asFollower(m, at, { + application: { + ...m.application!, + status: 'closed', + closedBy, + closedAt: at, + ...(decidedById ? { decidedById, decidedAt: at, decidedVia: 'site' as const } : {}), + }, + }); + } + + /** Close for age by the site sweep. */ + closedForAge(m: ProjectMembership, now: Date): ProjectMembership { + return this.#closed(m, 'site', now, null); + } + + #openApplicationOrThrow( + projectSlug: string, + personSlug: string, + session: SessionContext, + now: Date, + ): { project: Project; applicant: Person; existing: ProjectMembership } { + const project = this.#projectOrThrow(projectSlug); + requireAuth('project-admin | staff', { session, project, memberships: membershipsOfProject(this.#state, project.slug) }); + const applicant = personBySlug(this.#state, personSlug); + const existing = applicant ? membershipOf(this.#state, project.slug, applicant.slug) : undefined; + // Deactivated applicants and held applications are not there for admins. + if ( + !applicant || + applicant.deletedAt || + existing?.state !== 'applicant' || + existing.application?.status !== 'open' || + !isVisible(existing.application, now) + ) { + throw new ApiNotFoundError(`No open application from '${personSlug}'`); + } + return { project, applicant, existing }; + } + + #projectOrThrow(slug: string): Project { + const p = projectBySlug(this.#state, slug); + if (!p || p.deletedAt) throw new ApiNotFoundError(`Project '${slug}' not found`); + return p; + } +} diff --git a/apps/api/src/services/project-membership.write.ts b/apps/api/src/services/project-membership.write.ts index 863dea69..f2c7b273 100644 --- a/apps/api/src/services/project-membership.write.ts +++ b/apps/api/src/services/project-membership.write.ts @@ -66,9 +66,10 @@ function lastAdminConflict(): ConflictError { } /** The record as a follower: member-only fields cleared, everything else kept. */ -export function asFollower(m: ProjectMembership, now: string): ProjectMembership { +export function asFollower(m: ProjectMembership, now: string, over: Partial<ProjectMembership> = {}): ProjectMembership { return ProjectMembershipSchema.parse({ ...m, + ...over, state: 'follower', isAdmin: false, role: null, diff --git a/apps/api/src/services/project.ts b/apps/api/src/services/project.ts index f7beb72c..5a3fe509 100644 --- a/apps/api/src/services/project.ts +++ b/apps/api/src/services/project.ts @@ -6,6 +6,8 @@ import type { InMemoryState } from '../store/memory/state.js'; import type { FtsEngine } from '../store/fts.js'; import type { PrivateStore } from '../store/private/interface.js'; import { followerCount, hasActiveAdmin, isProjectAdmin, membersOfProject, membershipOf } from './memberships.js'; +import { openApplicationCount, reapplyAfter, serializeApplication } from './project-application.js'; +import { isAgentAccount } from '../auth/agent-grant.js'; import { computeProjectFacets, type ProjectFacets } from '../store/memory/facets.js'; import type { CallerSession } from './permissions.js'; import { computeProjectPermissions } from './permissions.js'; @@ -282,16 +284,32 @@ export class ProjectService { const updateCount = this.#state.updatesByProject.get(project.slug)?.size ?? 0; const buzzCount = this.#state.buzzByProject.get(project.slug)?.size ?? 0; - const permissions = computeProjectPermissions(caller, project, allRecords); + const now = new Date(); const own = caller ? allRecords.find((m) => m.personSlug === caller.slug) : undefined; + const wait = reapplyAfter(own, now); + const permissions = computeProjectPermissions(caller, project, allRecords, { + hasActiveAdmin: activeAdmin, + callerIsAgent: caller ? isAgentAccount(this.#state, caller.slug) : false, + reapplyWaitRunning: wait !== null, + }); const viewer: ProjectViewer | null = own - ? { state: own.state, isAdmin: own.isAdmin === true, muted: own.muted === true, application: null, reapplyAfter: null } + ? { + state: own.state, + isAdmin: own.isAdmin === true, + muted: own.muted === true, + // The applicant's own view: without decidedBy. + application: own.application + ? serializeApplication(this.#state, own.application, { withDecidedBy: false }) + : null, + reapplyAfter: wait, + } : null; return serializeProjectDetail(project, { memberships, memberPeople, showVia: permissions.canManageMembers, + openApplications: permissions.canReviewApplications ? openApplicationCount(this.#state, project.slug, now) : null, followerCount: followerCount(this.#state, project.slug), hasActiveAdmin: activeAdmin, viewer, diff --git a/apps/api/src/services/serializers/project.ts b/apps/api/src/services/serializers/project.ts index 683f301c..df4ee199 100644 --- a/apps/api/src/services/serializers/project.ts +++ b/apps/api/src/services/serializers/project.ts @@ -89,6 +89,8 @@ export interface ProjectDetail { readonly buzz: number; readonly members: number; readonly followers: number; + /** `null` unless the caller is a project admin or staff. */ + readonly openApplications: number | null; }; readonly permissions: ProjectPermissions; readonly featured: boolean; @@ -205,6 +207,7 @@ export function serializeProjectDetail( memberPeople: Map<string, Person>; /** Show each member's `via` (project admins and staff). */ showVia: boolean; + openApplications: number | null; followerCount: number; hasActiveAdmin: boolean; viewer: ProjectViewer | null; @@ -261,6 +264,7 @@ export function serializeProjectDetail( buzz: opts.buzzCount, members: opts.memberships.length, followers: opts.followerCount, + openApplications: opts.openApplications, }, permissions: opts.permissions, featured: project.featured, From 43de1fd3345ee96ea98b8000594f4b22036fbee4 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:11:22 +0000 Subject: [PATCH 31/78] feat(api): application email to admins and applicants, and the sweep Each active admin with a deliverable address hears about a visible application, read from the private store at send time; an admin whose address bounced is skipped and nobody stands in. Applicants hear when they are accepted, when an admin closes (with the note), and when the site closes for age. The sweep, shortly after boot and hourly, notifies held applications once they are visible and sends the 14-day reminder, recording notifiedAt/remindedAt in its own commit before sending, and closes applications 30 days past visibleAt in one cfp-api commit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/src/notify/email-notifier.ts | 28 ++- apps/api/src/notify/index.ts | 50 ++++ apps/api/src/notify/membership-templates.ts | 89 +++++++- apps/api/src/plugins/application-sweep.ts | 56 +++++ apps/api/src/services/application-notices.ts | 227 +++++++++++++++++++ 5 files changed, 448 insertions(+), 2 deletions(-) create mode 100644 apps/api/src/plugins/application-sweep.ts create mode 100644 apps/api/src/services/application-notices.ts diff --git a/apps/api/src/notify/email-notifier.ts b/apps/api/src/notify/email-notifier.ts index a16fc9b3..8c71a9fd 100644 --- a/apps/api/src/notify/email-notifier.ts +++ b/apps/api/src/notify/email-notifier.ts @@ -21,7 +21,9 @@ import type { EventUpdatedNotification, HelpWantedFillNotification, HelpWantedInterestNotification, + ApplicationDecisionNotification, MemberAddedNotification, + NewApplicationNotification, NewNeedNotification, Notifier, ProjectUpdateNotification, @@ -40,7 +42,13 @@ import { renderPasswordResetEmail, renderWelcomeEmail, } from './templates.js'; -import { renderMemberAddedEmail, renderNewNeedEmail, renderProjectUpdateEmail } from './membership-templates.js'; +import { + renderApplicationDecisionEmail, + renderMemberAddedEmail, + renderNewApplicationEmail, + renderNewNeedEmail, + renderProjectUpdateEmail, +} from './membership-templates.js'; import type { EmailAttachment, EmailTransport } from './transport.js'; /** Common shape of every template renderer's output. */ @@ -100,6 +108,24 @@ export class EmailNotifier implements Notifier { return this.#deliver('member added', ctx, n.email, renderMemberAddedEmail(n, this.#siteHost)); } + async notifyNewApplication(n: NewApplicationNotification): Promise<{ delivered: boolean }> { + const ctx = { kind: n.reminder ? 'application.reminder' : 'application.new', project: n.projectSlug }; + if (!n.email) { + this.#log.warn(ctx, 'application notice: no email address; skipped'); + return { delivered: false }; + } + return this.#deliver('application notice', ctx, n.email, renderNewApplicationEmail(n, this.#siteHost)); + } + + async notifyApplicationDecision(n: ApplicationDecisionNotification): Promise<{ delivered: boolean }> { + const ctx = { kind: `application.${n.outcome}`, project: n.projectSlug }; + if (!n.email) { + this.#log.warn(ctx, 'application decision: no email address; skipped'); + return { delivered: false }; + } + return this.#deliver('application decision', ctx, n.email, renderApplicationDecisionEmail(n, this.#siteHost)); + } + async notifyProjectUpdate(n: ProjectUpdateNotification): Promise<{ delivered: boolean }> { const ctx = { kind: 'follower.update', project: n.projectSlug, number: n.number }; if (!n.email) { diff --git a/apps/api/src/notify/index.ts b/apps/api/src/notify/index.ts index c288d8cd..cb3e3689 100644 --- a/apps/api/src/notify/index.ts +++ b/apps/api/src/notify/index.ts @@ -141,7 +141,45 @@ export interface NewNeedNotification extends FollowerEmailBase { readonly excerpt: string; } +/** One applicant fact line set, as admins see it (project-membership.md → What admins see). */ +export interface ApplicantFacts { + readonly accountCreatedAt: string; + readonly hasGitHubLink: boolean; + readonly memberOf: ReadonlyArray<{ readonly slug: string; readonly title: string }>; +} + +/** A new visible application, or its 14-day reminder, to one active admin. */ +export interface NewApplicationNotification { + readonly email: string; + /** The admin's name. */ + readonly fullName: string; + readonly projectTitle: string; + readonly projectSlug: string; + readonly applicantName: string; + readonly applicantSlug: string; + readonly facts: ApplicantFacts; + readonly needs: readonly string[]; + /** Plain text; shown as-is, never rendered or linked. */ + readonly offer: string | null; + readonly reminder: boolean; +} + +/** A decision on an application, to the applicant. */ +export interface ApplicationDecisionNotification { + readonly email: string; + /** The applicant's name. */ + readonly fullName: string; + readonly projectTitle: string; + readonly projectSlug: string; + /** accepted; closed by an admin (with the unstored note); closed by the site for age. */ + readonly outcome: 'accepted' | 'closed' | 'closed-for-age'; + readonly note: string | null; + readonly chatChannel: string | null; +} + export interface Notifier { + notifyNewApplication(n: NewApplicationNotification): Promise<{ delivered: boolean }>; + notifyApplicationDecision(n: ApplicationDecisionNotification): Promise<{ delivered: boolean }>; notifyMemberAdded(n: MemberAddedNotification): Promise<{ delivered: boolean }>; notifyProjectUpdate(n: ProjectUpdateNotification): Promise<{ delivered: boolean }>; notifyNewNeed(n: NewNeedNotification): Promise<{ delivered: boolean }>; @@ -172,6 +210,18 @@ export class LoggingNotifier implements Notifier { return { delivered: true }; } + async notifyNewApplication(n: NewApplicationNotification): Promise<{ delivered: boolean }> { + // Never the offer: it is the applicant's text, and logs are not where it belongs. + this.#log.info({ kind: n.reminder ? 'application.reminder' : 'application.new', project: n.projectSlug }, 'application notification'); + return { delivered: true }; + } + + async notifyApplicationDecision(n: ApplicationDecisionNotification): Promise<{ delivered: boolean }> { + // Never the note: it is emailed and stored nowhere, logs included. + this.#log.info({ kind: `application.${n.outcome}`, project: n.projectSlug }, 'application decision notification'); + return { delivered: true }; + } + async notifyProjectUpdate(n: ProjectUpdateNotification): Promise<{ delivered: boolean }> { this.#log.info({ kind: 'follower.update', project: n.projectSlug, number: n.number }, 'follower update notification'); return { delivered: true }; diff --git a/apps/api/src/notify/membership-templates.ts b/apps/api/src/notify/membership-templates.ts index e3783c16..2ff93a44 100644 --- a/apps/api/src/notify/membership-templates.ts +++ b/apps/api/src/notify/membership-templates.ts @@ -6,7 +6,13 @@ * is escaped and shown with its line breaks, never rendered as markdown and * never turned into a link by us. */ -import type { MemberAddedNotification, NewNeedNotification, ProjectUpdateNotification } from './index.js'; +import type { + ApplicationDecisionNotification, + MemberAddedNotification, + NewApplicationNotification, + NewNeedNotification, + ProjectUpdateNotification, +} from './index.js'; export interface MembershipEmail { readonly subject: string; @@ -110,3 +116,84 @@ export function renderNewNeedEmail(n: NewNeedNotification, siteHost: string): Me FOLLOWER_FOOTER(n.projectTitle), ); } + +function accountAge(createdAt: string, now: Date): string { + const days = Math.floor((now.getTime() - Date.parse(createdAt)) / 86_400_000); + if (days < 1) return 'today'; + if (days < 60) return `${days} day${days === 1 ? '' : 's'} ago`; + const months = Math.floor(days / 30); + if (months < 24) return `${months} months ago`; + return `${Math.floor(days / 365)} years ago`; +} + +export function renderNewApplicationEmail( + n: NewApplicationNotification, + siteHost: string, + now: Date = new Date(), +): MembershipEmail { + const url = `${projectUrl(siteHost, n.projectSlug)}/applications`; + const facts = [ + `Joined Code for Philly ${accountAge(n.facts.accountCreatedAt, now)}`, + n.facts.hasGitHubLink ? 'GitHub linked' : 'No GitHub linked', + n.facts.memberOf.length > 0 + ? `Member of: ${n.facts.memberOf.map((p) => p.title).join(', ')}` + : 'Not on any other project', + ].join(' · '); + const blocks: Block[] = [ + { + p: n.reminder + ? `Reminder: ${n.applicantName} applied to ${n.projectTitle} two weeks ago and is still waiting for an answer. Applications close by themselves 30 days after they arrive.` + : `${n.applicantName} applied to join ${n.projectTitle}.`, + }, + { p: facts }, + { p: n.needs.length > 0 ? `Needs picked: ${n.needs.join(', ')}` : 'No need picked.' }, + ]; + if (n.offer) blocks.push({ p: 'What they offered:' }, { quote: n.offer }); + blocks.push( + { link: url, label: 'Accept or close the application' }, + { link: `https://${siteHost}/members/${encodeURIComponent(n.applicantSlug)}`, label: `${n.applicantName}'s profile` }, + ); + return renderBlocks( + n.reminder ? `Still waiting: ${n.applicantName}'s application to ${n.projectTitle}` : `New application to ${n.projectTitle}`, + blocks, + `You're receiving this because you're an admin of ${n.projectTitle} on Code for Philly.`, + ); +} + +export function renderApplicationDecisionEmail(n: ApplicationDecisionNotification, siteHost: string): MembershipEmail { + const url = projectUrl(siteHost, n.projectSlug); + const footer = `You're receiving this because you applied to ${n.projectTitle} on Code for Philly.`; + if (n.outcome === 'accepted') { + const blocks: Block[] = [ + { p: `Hi ${n.fullName}, welcome to ${n.projectTitle}! Your application was accepted and you're now a member.` }, + ]; + if (n.chatChannel) { + blocks.push({ p: `The project talks in #${n.chatChannel} on the Code for Philly Slack.` }, { + link: `https://${siteHost}/chat?channel=${encodeURIComponent(n.chatChannel)}`, + label: `Open #${n.chatChannel}`, + }); + } + blocks.push({ link: url, label: 'Open the project' }); + return renderBlocks(`Welcome to ${n.projectTitle}`, blocks, footer); + } + if (n.outcome === 'closed') { + const blocks: Block[] = [ + { p: `Hi ${n.fullName}, thanks for applying to ${n.projectTitle}. The project isn't taking this on right now.` }, + ]; + if (n.note) blocks.push({ p: 'A note from the project:' }, { quote: n.note }); + blocks.push( + { p: "You're still following the project, so you'll hear about its updates and new needs." }, + { link: url, label: 'Open the project' }, + ); + return renderBlocks(`About your application to ${n.projectTitle}`, blocks, footer); + } + return renderBlocks( + `About your application to ${n.projectTitle}`, + [ + { p: `Hi ${n.fullName}, no one at ${n.projectTitle} got to your application in time, so it has closed after 30 days.` }, + { p: "You can apply again whenever you like, and you're still following the project." }, + { link: url, label: 'Open the project' }, + ], + footer, + ); +} diff --git a/apps/api/src/plugins/application-sweep.ts b/apps/api/src/plugins/application-sweep.ts new file mode 100644 index 00000000..1b09e66f --- /dev/null +++ b/apps/api/src/plugins/application-sweep.ts @@ -0,0 +1,56 @@ +/** + * Application sweep plugin — specs/api/projects-applications.md → Notes + * (Sweeps): runs shortly after boot and then hourly, the same shape as the + * event reminder sweep. In-process on purpose: its bookkeeping writes go + * through the store's single writer. + */ +import type { FastifyInstance } from 'fastify'; +import fp from 'fastify-plugin'; + +import { APPLICATION_SWEEP_INTERVAL_MS, ApplicationSweepService } from '../services/application-notices.js'; + +declare module 'fastify' { + interface FastifyInstance { + applicationSweep: ApplicationSweepService; + } +} + +async function applicationSweepPlugin(fastify: FastifyInstance): Promise<void> { + const service = new ApplicationSweepService({ + state: fastify.inMemoryState, + fts: fastify.fts, + store: fastify.store, + privateStore: fastify.store.private, + get notifier() { + return fastify.notifier; + }, + log: fastify.log, + applications: fastify.services.applications, + }); + fastify.decorate('applicationSweep', service); + + const run = (): void => { + void service.sweep().catch((err) => { + fastify.log.error({ err }, 'application sweep failed'); + }); + }; + + let interval: ReturnType<typeof setInterval> | undefined; + let first: ReturnType<typeof setTimeout> | undefined; + fastify.addHook('onReady', async () => { + // Tests boot many apps; the sweep is exercised directly there. + if (fastify.config.NODE_ENV === 'test') return; + first = setTimeout(run, 30_000); + interval = setInterval(run, APPLICATION_SWEEP_INTERVAL_MS); + }); + fastify.addHook('onClose', async () => { + if (first) clearTimeout(first); + if (interval) clearInterval(interval); + }); +} + +export default fp(applicationSweepPlugin, { + name: 'application-sweep', + fastify: '5.x', + dependencies: ['services'], +}); diff --git a/apps/api/src/services/application-notices.ts b/apps/api/src/services/application-notices.ts new file mode 100644 index 00000000..1d8707be --- /dev/null +++ b/apps/api/src/services/application-notices.ts @@ -0,0 +1,227 @@ +/** + * Application email and the application sweep — + * specs/behaviors/project-membership.md → Notifications, and + * specs/api/projects-applications.md → Notes (Sweeps). + * + * Every recipient address is read from the private store at send time and + * written nowhere. An admin with no deliverable address is skipped, never + * replaced by someone else (the old help-wanted interest email passed no + * recipient at all; this resolver is its fix). + * + * The sweep: notify admins when a held application becomes visible, send + * the 14-day reminder once, and close applications 30 days past visibleAt + * (`closedBy = site`). It records `notifiedAt` / `remindedAt` in its own + * commit before sending, and closes in one commit per run, both as + * `cfp-api`. Sends are at most once; a failed send is logged, not retried. + */ +import type { FastifyBaseLogger } from 'fastify'; +import type { Person, ProjectMembership } from '@cfp/shared/schemas'; + +import type { Notifier } from '../notify/index.js'; +import type { FtsEngine } from '../store/fts.js'; +import { personBySlug, projectBySlug, type InMemoryState } from '../store/memory/state.js'; +import type { PrivateStore } from '../store/private/interface.js'; +import { StateApply } from '../store/state-apply.js'; +import type { Store } from '../store/store.js'; +import { adminPeople, hasDeliverableEmail } from './memberships.js'; +import { applicantFacts, type ProjectApplicationService } from './project-application.js'; + +const DAY = 24 * 60 * 60 * 1000; +export const REMINDER_AFTER_MS = 14 * DAY; +export const CLOSE_AFTER_MS = 30 * DAY; +/** The sweep runs shortly after boot and then hourly (at least daily, as the spec asks). */ +export const APPLICATION_SWEEP_INTERVAL_MS = 60 * 60 * 1000; + +const SITE_AUTHOR = { name: 'cfp-api', email: 'api@codeforphilly.org' }; + +/** Each active admin of a project with a deliverable address. */ +export async function activeAdminRecipients( + state: InMemoryState, + privateStore: PrivateStore, + projectSlug: string, +): Promise<Array<{ person: Person; email: string }>> { + const out: Array<{ person: Person; email: string }> = []; + for (const person of adminPeople(state, projectSlug)) { + if (person.deletedAt) continue; + const profile = await privateStore.getProfile(person.id); + if (profile && hasDeliverableEmail(profile)) out.push({ person, email: profile.email }); + } + return out; +} + +export interface ApplicationNoticeDeps { + readonly state: InMemoryState; + readonly privateStore: PrivateStore; + readonly notifier: Notifier; + readonly log: FastifyBaseLogger; +} + +export class ApplicationNotices { + readonly #d: ApplicationNoticeDeps; + + constructor(deps: ApplicationNoticeDeps) { + this.#d = deps; + } + + /** Tell every active admin about a visible application (or remind them of it). Returns emails attempted. */ + async toAdmins(m: ProjectMembership, reminder: boolean): Promise<number> { + const { state } = this.#d; + const project = projectBySlug(state, m.projectSlug); + const applicant = personBySlug(state, m.personSlug); + const app = m.application; + if (!project || !applicant || applicant.deletedAt || !app) return 0; + const needs = app.roleIds.map((id) => state.helpWantedRoles.get(id)?.title).filter((t): t is string => !!t); + const facts = applicantFacts(state, applicant, project.slug); + let attempted = 0; + for (const { person, email } of await activeAdminRecipients(state, this.#d.privateStore, project.slug)) { + attempted += 1; + try { + await this.#d.notifier.notifyNewApplication({ + email, + fullName: person.fullName, + projectTitle: project.title, + projectSlug: project.slug, + applicantName: applicant.fullName, + applicantSlug: applicant.slug, + facts, + needs, + offer: app.offer ?? null, + reminder, + }); + } catch (err) { + this.#d.log.error({ err, project: project.slug }, 'application notice: send threw'); + } + } + if (attempted === 0) this.#d.log.info({ project: project.slug }, 'application notice: no admin with a deliverable address'); + return attempted; + } + + /** Tell the applicant the outcome. The note goes only into this email. */ + async toApplicant( + m: ProjectMembership, + outcome: 'accepted' | 'closed' | 'closed-for-age', + note: string | null = null, + ): Promise<boolean> { + const { state } = this.#d; + const project = projectBySlug(state, m.projectSlug); + const applicant = personBySlug(state, m.personSlug); + if (!project || !applicant || applicant.deletedAt) return false; + const profile = await this.#d.privateStore.getProfile(applicant.id); + if (!profile || !hasDeliverableEmail(profile)) { + this.#d.log.info({ project: project.slug, outcome }, 'application decision: no deliverable address; skipped'); + return false; + } + try { + await this.#d.notifier.notifyApplicationDecision({ + email: profile.email, + fullName: applicant.fullName, + projectTitle: project.title, + projectSlug: project.slug, + outcome, + note, + chatChannel: project.chatChannel ?? null, + }); + return true; + } catch (err) { + this.#d.log.error({ err, project: project.slug, outcome }, 'application decision: send threw'); + return false; + } + } +} + +export interface ApplicationSweepDeps extends ApplicationNoticeDeps { + readonly store: Store; + readonly fts: FtsEngine; + readonly applications: ProjectApplicationService; +} + +export interface SweepResult { + readonly notified: number; + readonly reminded: number; + readonly closed: number; +} + +export class ApplicationSweepService { + readonly #d: ApplicationSweepDeps; + readonly #notices: ApplicationNotices; + + constructor(deps: ApplicationSweepDeps) { + this.#d = deps; + this.#notices = new ApplicationNotices(deps); + } + + async sweep(now: Date = new Date()): Promise<SweepResult> { + const { state } = this.#d; + const t = now.getTime(); + const open = [...state.projectMemberships.values()].filter( + (m) => m.state === 'applicant' && m.application?.status === 'open', + ); + + // 1. Close for age: 30 days past visibleAt, hidden or not (the clock runs while hidden). + const toClose = open.filter((m) => t >= Date.parse(m.application!.visibleAt) + CLOSE_AFTER_MS); + if (toClose.length > 0) { + const closed = toClose.map((m) => this.#d.applications.closedForAge(m, now)); + await this.#d.store.transact( + { + message: + `applications: close ${closed.length} for age\n\n` + + 'Open 30 days after admins could see them, with no decision:\n' + + closed.map((m) => `- ${m.projectSlug}/${m.personSlug}`).join('\n') + + '\n', + author: SITE_AUTHOR, + trailers: { Action: 'project-membership.close', 'Closed-By': 'site' }, + }, + async (tx) => { + for (const m of closed) await tx.public['project-memberships'].upsert(m); + }, + ); + const apply = new StateApply(); + for (const m of closed) apply.upsertMembership(m); + apply.apply(state, this.#d.fts); + for (const m of closed) await this.#notices.toApplicant(m, 'closed-for-age'); + } + + // 2. Notices due on the rest, skipping hidden (deactivated) applicants. + const closedIds = new Set(toClose.map((m) => m.id)); + const due: Array<{ m: ProjectMembership; reminder: boolean }> = []; + for (const m of open) { + if (closedIds.has(m.id)) continue; + const person = personBySlug(state, m.personSlug); + if (!person || person.deletedAt) continue; + const app = m.application!; + const visibleAt = Date.parse(app.visibleAt); + if (visibleAt > t) continue; + if (!app.notifiedAt) due.push({ m, reminder: false }); + else if (!app.remindedAt && t >= visibleAt + REMINDER_AFTER_MS) due.push({ m, reminder: true }); + } + if (due.length > 0) { + const at = now.toISOString(); + const marked = due.map(({ m, reminder }) => ({ + reminder, + m: { ...m, application: { ...m.application!, ...(reminder ? { remindedAt: at } : { notifiedAt: at }) } }, + })); + await this.#d.store.transact( + { + message: + `applications: record ${marked.length} admin notice(s)\n\n` + + marked.map(({ m, reminder }) => `- ${m.projectSlug}/${m.personSlug}: ${reminder ? 'reminder' : 'new'}`).join('\n') + + '\n', + author: SITE_AUTHOR, + }, + async (tx) => { + for (const { m } of marked) await tx.public['project-memberships'].upsert(m); + }, + ); + const apply = new StateApply(); + for (const { m } of marked) apply.upsertMembership(m); + apply.apply(state, this.#d.fts); + for (const { m, reminder } of marked) await this.#notices.toAdmins(m, reminder); + } + + return { + notified: due.filter((d) => !d.reminder).length, + reminded: due.filter((d) => d.reminder).length, + closed: toClose.length, + }; + } +} From 4d7bab6ded428ac7b25213923ba4fa46592f7566 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:11:22 +0000 Subject: [PATCH 32/78] feat(moderation): applications in the member footprint Counted on the roster row and toward has-footprint, listed in the detail with project, status, submittedAt and closedBy. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/src/services/moderation.ts | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/apps/api/src/services/moderation.ts b/apps/api/src/services/moderation.ts index 3c625138..7dc94257 100644 --- a/apps/api/src/services/moderation.ts +++ b/apps/api/src/services/moderation.ts @@ -99,6 +99,8 @@ export interface EarlierPurgeView { export interface FootprintCounts { /** Records in state `member`. */ readonly memberships: number; + /** Records holding an application, in any status. */ + readonly applications: number; /** Records in state `follower`; never counted toward `has-footprint`. */ readonly follows: number; readonly updates: number; @@ -167,6 +169,12 @@ export interface MemberFootprint { via: string | null; joinedAt: string; }>; + readonly applications: Array<{ + project: ProjectRef; + status: string; + submittedAt: string; + closedBy: string | null; + }>; readonly follows: Array<{ project: ProjectRef; followedAt: string }>; readonly updates: Array<{ project: ProjectRef; number: number; title: string; postedAt: string }>; readonly buzz: Array<{ project: ProjectRef; slug: string; title: string; postedAt: string }>; @@ -282,7 +290,9 @@ export function computeSignals(input: { if (input.slugPurgedBefore) negative('slug-purged-before'); if (input.lastSlackSsoAt) signals.push('slack-sso'); const fp = input.footprint; - if (fp.memberships + fp.updates + fp.buzz + fp.blogPosts + fp.helpWantedInterest > 0) signals.push('has-footprint'); + if (fp.memberships + fp.applications + fp.updates + fp.buzz + fp.blogPosts + fp.helpWantedInterest > 0) { + signals.push('has-footprint'); + } return { signals, attention }; } @@ -569,6 +579,7 @@ export class ModerationService { const records = membershipsOfPerson(this.#state, p.slug); const footprint: FootprintCounts = { memberships: records.filter((m) => m.state === 'member').length, + applications: records.filter((m) => m.application).length, follows: records.filter((m) => m.state === 'follower').length, updates: authored.updates.get(p.id) ?? 0, buzz: authored.buzz.get(p.id) ?? 0, @@ -636,6 +647,15 @@ export class ModerationService { : []; }); + const applications = records + .filter((m) => m.application) + .flatMap((m) => { + const project = projectRef(m.projectSlug); + const a = m.application!; + return project ? [{ project, status: a.status, submittedAt: a.submittedAt, closedBy: a.closedBy ?? null }] : []; + }) + .sort((a, b) => b.submittedAt.localeCompare(a.submittedAt)); + const follows = records .filter((m) => m.state === 'follower') .flatMap((m) => { @@ -693,7 +713,7 @@ export class ModerationService { }) .sort((a, b) => b.createdAt.localeCompare(a.createdAt)); - return { memberships, follows, updates, buzz, blogPosts, helpWantedInterest, tags, rsvps }; + return { memberships, applications, follows, updates, buzz, blogPosts, helpWantedInterest, tags, rsvps }; } #voteView(rec: PersonEvaluation): VoteView { From 5d926ba3c2ce98916ac49f1f5862218bbc76e252 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:11:22 +0000 Subject: [PATCH 33/78] test(api): cover applications, limits, the hold, the sweep and their email Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/tests/project-applications.test.ts | 371 ++++++++++++++++++++ 1 file changed, 371 insertions(+) create mode 100644 apps/api/tests/project-applications.test.ts diff --git a/apps/api/tests/project-applications.test.ts b/apps/api/tests/project-applications.test.ts new file mode 100644 index 00000000..7a23b669 --- /dev/null +++ b/apps/api/tests/project-applications.test.ts @@ -0,0 +1,371 @@ +/** + * Applying to join a project (plans/membership-applications.md): apply, + * accept and close with who may make each, the re-apply wait, the + * site-wide limits, the new-account hold, the sweep, the emails, and + * applications of deactivated applicants. + * + * Every person here is invented; addresses are example.org. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { + daysAgo, + fid, + minutesAgo, + personRecord, + privateProfile, + startAgentTestEnv, + type AgentTestEnv, + type Rec, +} from './helpers/agent-fixtures.js'; + +const P = { + ada: 1, ben: 2, cal: 3, dee: 4, eve: 5, nina: 6, sam: 7, root: 8, bounce: 9, olly: 10, + rex: 11, quinn: 12, hal: 13, zed: 14, yan: 15, xia: 16, old1: 17, old2: 18, +}; +const ROLE = { open: fid(300), closed: fid(301), foreign: fid(302) }; +const T = '2026-05-01T00:00:00.000Z'; +const RECENT = minutesAgo(90); +const NOTE = 'We are full on frontend this season, sorry.'; +const OFFER = 'I have built two React apps and have about four hours a week.'; + +let n = 1000; +const rec = (project: string, person: string, state: 'follower' | 'applicant' | 'member', over: Rec = {}): Rec => ({ + id: fid(n++), + projectSlug: project, + personSlug: person, + state, + isAdmin: false, + muted: false, + followedAt: T, + createdAt: T, + updatedAt: T, + ...(state === 'member' ? { via: 'legacy', joinedAt: T } : {}), + ...over, +}); +const openApp = (over: Rec = {}): Rec => ({ + application: { status: 'open', roleIds: [], offer: 'Glad to help.', submittedAt: RECENT, visibleAt: RECENT, notifiedAt: RECENT, ...over }, +}); +const closedApp = (closedBy: 'admin' | 'applicant', closedAt: string): Rec => ({ + application: { + status: 'closed', roleIds: [], offer: 'Earlier offer.', submittedAt: closedAt, visibleAt: closedAt, + closedBy, closedAt, ...(closedBy === 'admin' ? { decidedById: fid(P.ada), decidedAt: closedAt, decidedVia: 'site' } : {}), + }, +}); +const project = (k: number, slug: string): Rec => ({ + id: fid(50 + k), slug, title: `Project ${slug}`, stage: 'testing', featured: false, chatChannel: slug, createdAt: T, updatedAt: T, +}); + +function records(): Record<string, Rec[]> { + n = 1000; + const people = Object.entries(P).map(([slug, k]) => + personRecord(k, slug, { + ...(slug === 'nina' ? { createdAt: minutesAgo(30) } : {}), + ...(slug === 'sam' ? { accountLevel: 'staff' } : {}), + ...(slug === 'root' ? { accountLevel: 'administrator' } : {}), + ...(slug === 'olly' ? { deletedAt: daysAgo(3) } : {}), + ...(slug === 'ben' ? { githubUserId: 4242, githubLogin: 'ben-gh' } : {}), + }), + ); + const others = ['p1', 'p2', 'p3', 'p4', 'p5']; + return { + people, + projects: [project(0, 'proj'), project(1, 'orphan'), ...others.map((s, i) => project(2 + i, s))], + 'help-wanted-roles': [ + { id: ROLE.open, projectSlug: 'proj', postedById: fid(P.ada), title: 'Frontend dev', description: 'React.', status: 'open', createdAt: T, updatedAt: T }, + { id: ROLE.closed, projectSlug: 'proj', postedById: fid(P.ada), title: 'Old need', description: 'Done.', status: 'closed', closedAt: T, createdAt: T, updatedAt: T }, + { id: ROLE.foreign, projectSlug: 'p1', postedById: fid(P.ada), title: 'Elsewhere', description: 'Not here.', status: 'open', createdAt: T, updatedAt: T }, + ], + 'project-memberships': [ + rec('proj', 'ada', 'member', { isAdmin: true, role: 'Founder' }), + rec('proj', 'bounce', 'member', { isAdmin: true }), + rec('proj', 'ben', 'member'), + rec('proj', 'cal', 'follower'), + rec('proj', 'dee', 'applicant', openApp({ roleIds: [ROLE.open] })), + rec('proj', 'hal', 'applicant', openApp()), + rec('proj', 'zed', 'follower', closedApp('admin', daysAgo(10))), + rec('proj', 'yan', 'follower', closedApp('admin', daysAgo(31))), + rec('proj', 'xia', 'follower', closedApp('applicant', daysAgo(1))), + rec('proj', 'old1', 'applicant', openApp({ visibleAt: daysAgo(15), submittedAt: daysAgo(15), notifiedAt: daysAgo(15) })), + rec('proj', 'old2', 'applicant', openApp({ visibleAt: daysAgo(31), submittedAt: daysAgo(31), notifiedAt: daysAgo(31), remindedAt: daysAgo(17) })), + rec('orphan', 'olly', 'member', { isAdmin: true }), + ...others.map((s) => rec(s, 'ada', 'member', { isAdmin: true })), + ...['p1', 'p2', 'p3'].map((s) => rec(s, 'rex', 'applicant', openApp({ submittedAt: daysAgo(3), visibleAt: daysAgo(3) }))), + ...others.map((s) => rec(s, 'quinn', 'follower', closedApp('applicant', minutesAgo(60)))), + ], + }; +} + +const PROFILES = Object.entries(P).map(([slug, k]) => + privateProfile(fid(k), `${slug}@example.org`, slug === 'bounce' + ? { emailBounce: { type: 'HardBounce', bouncedAt: T, inactive: true } } + : {}), +); + +type Level = 'user' | 'staff' | 'administrator'; + +describe('project applications', () => { + let env: AgentTestEnv; + + beforeEach(async () => { + env = await startAgentTestEnv({ records: records(), profiles: PROFILES }); + // hal is deactivated after seeding so their open application exists first. + env.app.inMemoryState.people.set(fid(P.hal), { ...env.app.inMemoryState.people.get(fid(P.hal))!, deletedAt: daysAgo(1) }); + }); + afterEach(async () => { + await env.close(); + }); + + const call = async (who: number | null, method: 'GET' | 'POST' | 'PATCH' | 'DELETE', url: string, payload?: Rec, level: Level = 'user') => + env.app.inject({ + method, + url, + ...(who !== null ? { cookies: { cfp_session: await env.cookie(who, level) } } : {}), + ...(payload !== undefined ? { payload } : {}), + }); + const record = (person: string, projectSlug = 'proj') => { + const s = env.app.inMemoryState; + for (const id of s.membershipsByPerson.get(person) ?? []) { + const m = s.projectMemberships.get(id); + if (m?.projectSlug === projectSlug) return m; + } + return undefined; + }; + const head = async () => (await env.git('rev-parse', 'HEAD')).trim(); + const lastAction = async () => (await env.git('log', '-1', '--format=%B')).match(/^Action: (.+)$/m)?.[1]; + const errOf = (res: { json: () => unknown }) => (res.json() as { error: { code: string; details?: Rec } }).error; + const apply = (who: number, payload: Rec, slug = 'proj') => call(who, 'POST', `/api/projects/${slug}/applications`, payload); + + describe('apply', () => { + it('from no record: an open application, admins with a working address emailed at once', async () => { + const spy = vi.spyOn(env.app.notifier, 'notifyNewApplication'); + const res = await apply(P.eve, { roleIds: [ROLE.open], offer: OFFER }); + expect(res.statusCode, res.body).toBe(201); + expect(res.json<{ data: Rec }>().data).toMatchObject({ + state: 'applicant', + application: { status: 'open', roles: [{ id: ROLE.open, title: 'Frontend dev', status: 'open' }], offer: OFFER }, + }); + const m = record('eve')!; + expect(m.state).toBe('applicant'); + expect(m.application).toMatchObject({ status: 'open', notifiedAt: m.application!.submittedAt }); + expect(await lastAction()).toBe('project-membership.apply'); + // The commit message never quotes the offer. + expect(await env.git('log', '-1', '--format=%B')).not.toContain('React apps'); + await vi.waitFor(() => expect(spy).toHaveBeenCalledTimes(1)); + // bounce is an admin with a hard-bounced address: skipped, nobody else stands in. + expect(spy.mock.calls[0]![0]).toMatchObject({ + email: 'ada@example.org', applicantSlug: 'eve', needs: ['Frontend dev'], offer: OFFER, reminder: false, + }); + }); + + it('from follower: the same record becomes an applicant', async () => { + const before = record('cal')!; + const res = await apply(P.cal, { offer: 'Docs and testing.' }); + expect(res.statusCode, res.body).toBe(201); + expect(record('cal')).toMatchObject({ id: before.id, state: 'applicant', followedAt: before.followedAt }); + }); + + it('refuses with the error each case names', async () => { + const cases: Array<[number, Rec, number, string, string?]> = [ + [P.dee, { offer: 'Again' }, 409, 'application_open'], + [P.ben, { offer: 'Me too' }, 409, 'already_member'], + [P.eve, { offer: 'Hi' }, 409, 'no_active_admin', 'orphan'], + [P.eve, { roleIds: [] }, 422, 'validation_failed'], + [P.eve, { roleIds: [ROLE.closed] }, 422, 'validation_failed'], + [P.eve, { roleIds: [ROLE.foreign] }, 422, 'validation_failed'], + [P.eve, { offer: 'x'.repeat(1501) }, 422, 'validation_failed'], + ]; + for (const [who, payload, status, code, slug] of cases) { + const res = await apply(who, payload, slug); + expect(res.statusCode, `${code}: ${res.body}`).toBe(status); + expect(errOf(res).code).toBe(code); + } + expect((await call(null, 'POST', '/api/projects/proj/applications', { offer: 'x' })).statusCode).toBe(401); + }); + + it('the 4th open application site-wide and the 6th in 24 hours are 429', async () => { + const rex = await apply(P.rex, { offer: 'One more' }); + expect(rex.statusCode, rex.body).toBe(429); + expect(errOf(rex).code).toBe('rate_limited'); + const quinn = await apply(P.quinn, { offer: 'Sixth today' }); + expect(quinn.statusCode, quinn.body).toBe(429); + }); + }); + + describe('re-apply limits', () => { + it('an admin close starts a 30-day wait; an applicant or site close does not', async () => { + const zed = await apply(P.zed, { offer: 'Trying again' }); + expect(zed.statusCode).toBe(409); + expect(errOf(zed).code).toBe('reapply_too_soon'); + expect(errOf(zed).details?.['reapplyAfter']).toBe( + new Date(Date.parse(record('zed')!.application!.closedAt!) + 30 * 86_400_000).toISOString(), + ); + const page = (await call(P.zed, 'GET', '/api/projects/proj')).json<{ data: { viewer: Rec; permissions: Rec } }>().data; + expect(page.viewer['reapplyAfter']).toBe(errOf(zed).details?.['reapplyAfter']); + expect(page.permissions['canApply']).toBe(false); + + expect((await apply(P.yan, { offer: 'Month later' })).statusCode).toBe(201); + expect((await apply(P.xia, { offer: 'Changed my mind back' })).statusCode).toBe(201); + }); + + it('the applicant closing their own application may apply again at once', async () => { + const close = await call(P.dee, 'POST', '/api/projects/proj/applications/mine/close'); + expect(close.statusCode, close.body).toBe(200); + expect(record('dee')).toMatchObject({ state: 'follower', application: { status: 'closed', closedBy: 'applicant' } }); + expect(record('dee')!.application!.decidedById ?? null).toBeNull(); + expect((await call(P.dee, 'POST', '/api/projects/proj/applications/mine/close')).statusCode).toBe(404); + expect((await apply(P.dee, { offer: 'Back again' })).statusCode).toBe(201); + }); + }); + + describe('deciding', () => { + it('accept makes a member via application, labelled by the first need, and emails the applicant', async () => { + const spy = vi.spyOn(env.app.notifier, 'notifyApplicationDecision'); + const res = await call(P.ada, 'POST', '/api/projects/proj/applications/dee/accept', {}); + expect(res.statusCode, res.body).toBe(200); + expect(res.json<{ data: Rec }>().data).toMatchObject({ role: 'Frontend dev', via: 'application', isAdmin: false }); + expect(record('dee')).toMatchObject({ + state: 'member', via: 'application', role: 'Frontend dev', + application: { status: 'accepted', decidedById: fid(P.ada), decidedVia: 'site' }, + }); + expect(await lastAction()).toBe('project-membership.accept'); + await vi.waitFor(() => expect(spy).toHaveBeenCalledTimes(1)); + expect(spy.mock.calls[0]![0]).toMatchObject({ email: 'dee@example.org', outcome: 'accepted', chatChannel: 'proj' }); + }); + + it('close keeps them following, records who closed it, and emails the note without storing it', async () => { + const spy = vi.spyOn(env.app.notifier, 'notifyApplicationDecision'); + const logSpy = vi.spyOn(env.app.log, 'info'); + const res = await call(P.ada, 'POST', '/api/projects/proj/applications/dee/close', { note: NOTE }); + expect(res.statusCode, res.body).toBe(200); + expect(record('dee')).toMatchObject({ + state: 'follower', + application: { status: 'closed', closedBy: 'admin', decidedById: fid(P.ada), decidedVia: 'site' }, + }); + await vi.waitFor(() => expect(spy).toHaveBeenCalledTimes(1)); + expect(spy.mock.calls[0]![0]).toMatchObject({ email: 'dee@example.org', outcome: 'closed', note: NOTE }); + // The note is in no record, no commit and no log line. + expect(await env.git('log', '-p', '--format=%B')).not.toContain('full on frontend'); + expect(JSON.stringify(record('dee'))).not.toContain('full on frontend'); + // Fastify's own request lines carry the raw request to pino, whose serializers keep only + // method, URL and host; every line the app writes itself must leave the note out. + const ours = logSpy.mock.calls.filter((c) => !['incoming request', 'request completed'].includes(String(c[1]))); + expect(JSON.stringify(ours)).not.toContain('full on frontend'); + // Now in the re-apply wait. + expect(errOf(await apply(P.dee, { offer: 'Please?' })).code).toBe('reapply_too_soon'); + }); + + it('only project admins and staff decide; held, hidden or missing applications are 404', async () => { + expect((await call(P.ben, 'POST', '/api/projects/proj/applications/dee/accept', {})).statusCode).toBe(403); + expect((await call(P.ada, 'POST', '/api/projects/proj/applications/dee/close', { note: 'x'.repeat(1001) })).statusCode).toBe(422); + expect((await call(P.sam, 'POST', '/api/projects/proj/applications/dee/close', {}, 'staff')).statusCode).toBe(200); + expect((await call(P.ada, 'POST', '/api/projects/proj/applications/hal/accept', {})).statusCode).toBe(404); + expect((await call(P.ada, 'POST', '/api/projects/proj/applications/cal/accept', {})).statusCode).toBe(404); + expect((await call(P.ada, 'POST', '/api/projects/proj/applications/dee/close', {})).statusCode).toBe(404); + }); + }); + + describe('the Applications list', () => { + it('admins and staff see it, a member gets 403; facts only, newest first', async () => { + expect((await call(P.ben, 'GET', '/api/projects/proj/applications')).statusCode).toBe(403); + expect((await call(P.sam, 'GET', '/api/projects/proj/applications', undefined, 'staff')).statusCode).toBe(200); + const res = await call(P.ada, 'GET', '/api/projects/proj/applications'); + expect(res.statusCode, res.body).toBe(200); + const body = res.json<{ data: Array<{ person: { slug: string }; applicant: Rec; application: Rec }>; metadata: { counts: Rec } }>(); + // dee (visible), old1, old2; hal is deactivated and hidden. + expect(body.data.map((d) => d.person.slug)).toEqual(['dee', 'old1', 'old2']); + expect(body.data[0]!.applicant).toEqual({ accountCreatedAt: expect.any(String), hasGitHubLink: false, memberOf: [] }); + expect(body.metadata.counts).toMatchObject({ open: 3 }); + expect(JSON.stringify(body)).not.toMatch(/spam|verdict|email/i); + const closed = (await call(P.ada, 'GET', '/api/projects/proj/applications?status=closed')).json<{ data: Array<{ person: { slug: string } }> }>(); + expect(closed.data.map((d) => d.person.slug).sort()).toEqual(['xia', 'yan', 'zed']); + const page = (await call(P.ada, 'GET', '/api/projects/proj')).json<{ data: { counts: Rec; permissions: Rec } }>().data; + expect(page.counts['openApplications']).toBe(3); + expect(page.permissions['canReviewApplications']).toBe(true); + expect((await call(P.ben, 'GET', '/api/projects/proj')).json<{ data: { counts: Rec } }>().data.counts['openApplications']).toBeNull(); + }); + + it("a deactivated applicant's application is hidden and comes back unchanged on reactivation; purge deletes it", async () => { + const hal = record('hal')!; + await call(P.sam, 'POST', '/api/people/hal/reactivate', {}, 'staff'); + const list = (await call(P.ada, 'GET', '/api/projects/proj/applications')).json<{ data: Array<{ person: { slug: string } }> }>(); + expect(list.data.map((d) => d.person.slug)).toContain('hal'); + expect(record('hal')).toEqual(hal); + const purge = await call(P.root, 'POST', '/api/people/hal/purge', { confirm: 'hal' }, 'administrator'); + expect([200, 204]).toContain(purge.statusCode); + expect(record('hal')).toBeUndefined(); + }); + }); + + describe('new-account hold and the sweep', () => { + it('holds a new account: recorded, not listed, not emailed, until the sweep at visibleAt notifies once', async () => { + const spy = vi.spyOn(env.app.notifier, 'notifyNewApplication'); + const res = await apply(P.nina, { offer: 'New here!' }); + expect(res.statusCode, res.body).toBe(201); + const m = record('nina')!; + const visibleAt = Date.parse(m.application!.visibleAt); + expect(visibleAt).toBe(Date.parse(env.app.inMemoryState.people.get(fid(P.nina))!.createdAt) + 86_400_000); + expect(m.application!.notifiedAt ?? null).toBeNull(); + const list = (await call(P.ada, 'GET', '/api/projects/proj/applications')).json<{ data: Array<{ person: { slug: string } }> }>(); + expect(list.data.map((d) => d.person.slug)).not.toContain('nina'); + + await env.app.applicationSweep.sweep(new Date()); + expect(spy.mock.calls.filter((c) => c[0].applicantSlug === 'nina')).toHaveLength(0); + + const later = new Date(visibleAt + 60_000); + await env.app.applicationSweep.sweep(later); + expect(spy.mock.calls.filter((c) => c[0].applicantSlug === 'nina' && !c[0].reminder)).toHaveLength(1); + expect(record('nina')!.application!.notifiedAt).toBe(later.toISOString()); + await env.app.applicationSweep.sweep(new Date(visibleAt + 120_000)); + expect(spy.mock.calls.filter((c) => c[0].applicantSlug === 'nina' && !c[0].reminder)).toHaveLength(1); + }); + + it('reminds once at 14 days and closes at 30 in one cfp-api commit; a second run does nothing', async () => { + const notice = vi.spyOn(env.app.notifier, 'notifyNewApplication'); + const decision = vi.spyOn(env.app.notifier, 'notifyApplicationDecision'); + const before = await head(); + const result = await env.app.applicationSweep.sweep(new Date()); + expect(result).toMatchObject({ closed: 1, reminded: 1 }); + const log = (await env.git('log', '--format=%an|%s', `${before}..HEAD`)).trim().split('\n'); + expect(log).toHaveLength(2); + expect(log.every((l) => l.startsWith('cfp-api|'))).toBe(true); + expect(record('old2')).toMatchObject({ state: 'follower', application: { status: 'closed', closedBy: 'site' } }); + expect(record('old1')!.application!.remindedAt).toBeTruthy(); + expect(notice.mock.calls.filter((c) => c[0].reminder).map((c) => c[0].applicantSlug)).toEqual(['old1']); + expect(decision.mock.calls.map((c) => [c[0].email, c[0].outcome])).toEqual([['old2@example.org', 'closed-for-age']]); + + const after = await head(); + const again = await env.app.applicationSweep.sweep(new Date()); + expect(again).toEqual({ notified: 0, reminded: 0, closed: 0 }); + expect(await head()).toBe(after); + // After a close for age, they may apply again at once. + expect((await apply(P.old2, { offer: 'Still keen' })).statusCode).toBe(201); + }); + }); + + describe('no active admin', () => { + it('a project whose only admin is deactivated says so and offers no Apply', async () => { + const page = (await call(P.eve, 'GET', '/api/projects/orphan')).json<{ data: { hasActiveAdmin: boolean; permissions: Rec } }>().data; + expect(page.hasActiveAdmin).toBe(false); + expect(page.permissions['canApply']).toBe(false); + expect(page.permissions['canFollow']).toBe(true); + const ok = (await call(P.eve, 'GET', '/api/projects/proj')).json<{ data: { hasActiveAdmin: boolean; permissions: Rec } }>().data; + expect(ok.hasActiveAdmin).toBe(true); + expect(ok.permissions['canApply']).toBe(true); + }); + }); + + describe('moderation footprint', () => { + it('lists applications in the detail and counts them as footprint', async () => { + const staff = { cookies: { cfp_session: await env.cookie(P.sam, 'staff') } }; + const detail = await env.app.inject({ method: 'GET', url: '/api/admin/members/zed', ...staff }); + expect(detail.json<{ data: { footprint: { applications: unknown[] } } }>().data.footprint.applications).toEqual([ + expect.objectContaining({ project: { slug: 'proj', title: 'Project proj' }, status: 'closed', closedBy: 'admin' }), + ]); + const list = await env.app.inject({ method: 'GET', url: '/api/admin/members?perPage=100', ...staff }); + const row = list.json<{ data: Array<{ slug: string; footprint: Rec; signals: string[] }> }>().data.find((r) => r.slug === 'zed')!; + expect(row.footprint['applications']).toBe(1); + expect(row.signals).toContain('has-footprint'); + }); + }); +}); From 017b714b70c8ca12d02cd055ad6dfe9dc8cfac4c Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:12:09 +0000 Subject: [PATCH 34/78] docs(specs): hide a deactivated member from the public, name them to admins Operator decision, reversing the placeholder rule of 4df3ad1: a membership is not content, so a deactivated member gets no placeholder. Public member lists, member counts and project cards leave them out; the project's admins and staff still see the row with the person's name and a Deactivated label, so they know which member they approved went away and can remove the record (the one members-endpoint act allowed on a deactivated person). Content they posted keeps the Deactivated user author placeholder for everyone. No email, never an active admin, nothing rewritten. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- specs/api/people.md | 6 ++++-- specs/api/projects-members.md | 2 +- specs/api/projects.md | 2 +- specs/behaviors/person-lifecycle.md | 4 ++-- specs/behaviors/project-membership.md | 16 +++++++++++----- specs/screens/project-detail.md | 3 ++- 6 files changed, 21 insertions(+), 12 deletions(-) diff --git a/specs/api/people.md b/specs/api/people.md index a7139b83..b23f73d4 100644 --- a/specs/api/people.md +++ b/specs/api/people.md @@ -256,13 +256,15 @@ Administrator-only. What a purge of this person would delete beyond their own re ## Deactivated person placeholder -When a deactivated person is referenced in a serialized response (e.g. project member, update author, blog author, help-wanted postedBy), the reference must be substituted with a placeholder rather than omitted, so counts and history stay coherent: +When a deactivated person is referenced in a serialized response as the author or actor of something (e.g. update author, blog author, help-wanted postedBy), the reference must be substituted with a placeholder rather than omitted, so counts and history stay coherent: ```json { "slug": null, "fullName": "Deactivated user", "avatarUrl": null, "deactivated": true } ``` -This placeholder shape applies to the `PersonAvatar` reference type used in: project memberships, project-update `author`, project-buzz `postedBy`, help-wanted `postedBy`/`filledBy`, application `decidedBy`, blog-post `author`, and event-rsvp `person`. +Project memberships are not substituted: a deactivated member is left out of public member lists, and shown to project admins and staff with their name and `deactivated: true` ([projects.md](projects.md#project-shape)). + +This placeholder shape applies to the `PersonAvatar` reference type used in: project-update `author`, project-buzz `postedBy`, help-wanted `postedBy`/`filledBy`, application `decidedBy`, blog-post `author`, and event-rsvp `person`. ## POST /api/people/:slug/account-level diff --git a/specs/api/projects-members.md b/specs/api/projects-members.md index b3f6b3f5..8638e92a 100644 --- a/specs/api/projects-members.md +++ b/specs/api/projects-members.md @@ -18,7 +18,7 @@ There is no join endpoint: membership comes from an accepted application or an a Listing members is part of `GET /api/projects/:slug` (members only). Applicants are listed by `GET /api/projects/:slug/applications` to admins and staff. Followers are never listed by any endpoint; the project shows their count. -Every endpoint here treats a person who is deactivated as absent, and refuses agent accounts as the subject (`422`, `error.code = "agent_account"`): an agent never follows, applies or joins. +Every endpoint here treats a person who is deactivated as absent, except that a project admin or staff may remove a deactivated member's record (`DELETE …/members/:personSlug`), and refuses agent accounts as the subject (`422`, `error.code = "agent_account"`): an agent never follows, applies or joins. ## POST /api/projects/:slug/follow diff --git a/specs/api/projects.md b/specs/api/projects.md index 6e30dc22..b8dde397 100644 --- a/specs/api/projects.md +++ b/specs/api/projects.md @@ -145,7 +145,7 @@ Fetches a single project by slug. } ``` -`counts.openApplications` is `null` unless the caller is a project admin or staff. Follower and applicant counts leave out deactivated people; a deactivated member stays in `memberships` as the "Deactivated user" placeholder ([person-lifecycle.md](../behaviors/person-lifecycle.md)). No endpoint lists followers. +`counts.openApplications` is `null` unless the caller is a project admin or staff. Follower and applicant counts leave out deactivated people. A deactivated member is left out of `memberships`, `counts.members` and the list item's `members`, `admins` and `memberCount` for everyone except the project's admins and staff, who get that member's row in `memberships` with the person named as usual plus `deactivated: true` ([project-membership.md → Spam and deactivated accounts](../behaviors/project-membership.md#spam-and-deactivated-accounts)); `counts.members` counts active members only. No endpoint lists followers. `permissions` is the *current caller's* permissions on this project — the frontend uses it to decide which actions to render. The server still enforces the same rules on each mutation endpoint. diff --git a/specs/behaviors/person-lifecycle.md b/specs/behaviors/person-lifecycle.md index d4897c2e..025bb4fd 100644 --- a/specs/behaviors/person-lifecycle.md +++ b/specs/behaviors/person-lifecycle.md @@ -14,8 +14,8 @@ The privacy / self-removal path — members should be able to remove themselves; - **Who:** a person may deactivate/reactivate their OWN account; staff and administrators may deactivate/reactivate ANY account. - **Mechanism:** sets `person.deletedAt = now()` (reactivate clears it). The record and relationships stay intact. -- **Visibility while deactivated:** excluded from public list endpoints; `GET /api/people/:slug` returns 404 for non-staff (staff may still fetch it, with `deletedAt` populated). Anywhere a deactivated person is referenced (project member grids, project-update/project-buzz authors, help-wanted "posted by", an application's "decided by", blog author) the serialized reference is a **"Deactivated user" placeholder** (no slug link, generic avatar) rather than the person — substitute, do not omit, so counts/history stay coherent. -- **Their follows and applications go quiet.** A deactivated person's `project-memberships` records in state `follower` or `applicant` are left out of follower counts, admin views, notifications and the agent feed; a member's record still shows as the placeholder above. Nothing is rewritten, so reactivation restores them as they were ([project-membership.md → Spam and deactivated accounts](project-membership.md#spam-and-deactivated-accounts)). +- **Visibility while deactivated:** excluded from public list endpoints; `GET /api/people/:slug` returns 404 for non-staff (staff may still fetch it, with `deletedAt` populated). Anywhere a deactivated person is referenced as the author or actor of content (project-update/project-buzz authors, help-wanted "posted by", an application's "decided by", blog author) the serialized reference is a **"Deactivated user" placeholder** (no slug link, generic avatar) rather than the person — substitute, do not omit, so counts/history stay coherent. A project membership is not content and is not substituted: see the next point. +- **Their follows and applications go quiet.** A deactivated person's `project-memberships` records in state `follower` or `applicant` are left out of follower counts, admin views, notifications and the agent feed. A `member` record is left out of every public member list and count; the project's admins and staff still see it, named and labelled "Deactivated", so they can remove it. Nothing is rewritten, so reactivation restores them as they were ([project-membership.md → Spam and deactivated accounts](project-membership.md#spam-and-deactivated-accounts)). - **Login is NOT blocked** — a deactivated user can still authenticate and reactivate themselves. No session revocation. - **Surfaces:** self at `/account` ("Deactivate my account" / "Reactivate"); staff/admin via a person "Danger Zone"; and the **admin members screen**, where a `spam` vote deactivates the person in the same transaction that records the vote ([api/moderation.md](../api/moderation.md)). - **Deciding votes:** the human votes on a person, when there are any; otherwise the votes of agents that hold an active grant ([api/moderation.md → Agent votes](../api/moderation.md#agent-votes)). An agent vote stops deciding the moment any human votes on the person, and while its agent holds no active grant. Only votes on **this account** count: a vote older than the person's `createdAt`, or dated at or before the newest `spam-purges` record for the slug that names another person, was cast on an earlier account under the same slug and is ignored here and everywhere below ([api/moderation.md → Votes belong to one account](../api/moderation.md#votes-belong-to-one-account)). diff --git a/specs/behaviors/project-membership.md b/specs/behaviors/project-membership.md index 1c835147..3b7866aa 100644 --- a/specs/behaviors/project-membership.md +++ b/specs/behaviors/project-membership.md @@ -186,11 +186,17 @@ site closing one for age (`closedBy = site`) write the same fields, without deactivated (by themselves or by a spam vote) are left out of every list, count, admin view, notification and agent feed, the way deactivated people are left out of public lists ([person-lifecycle.md](person-lifecycle.md)). - A deactivated member stays on the member list as the "Deactivated user" - placeholder, gets no email, and never counts as an active admin. No record - is changed: a `legit` vote that reactivates the person brings them back as - they were. A held or open application's 30-day clock keeps running while - hidden. +- **A deactivated member is not shown to the public.** A membership is not + content, so it gets no placeholder: the public member list, member counts, + project cards and the person's profile leave it out. The project's admins + and staff still see the row, with the person's name and a "Deactivated" + label, so they know which member they approved went away and can remove + the record. A deactivated member gets no email and never counts as an + active admin. (Content they posted keeps the "Deactivated user" author + placeholder for everyone.) +- **Nothing is rewritten.** A `legit` vote that reactivates the person brings + every record back as it was. A held or open application's 30-day clock + keeps running while hidden. - **Purge** deletes the person's records in every state with the rest of their data ([person-lifecycle.md](person-lifecycle.md#purge-cascading-hard-delete-admin-only)). - **No reward.** An application or a follow puts nothing on a project's public diff --git a/specs/screens/project-detail.md b/specs/screens/project-detail.md index 3363c6fc..45fa4cf8 100644 --- a/specs/screens/project-detail.md +++ b/specs/screens/project-detail.md @@ -86,6 +86,7 @@ If slug is unknown or soft-deleted (and caller isn't staff): 404 page. 3. **Members** - Heading "Members" - Avatar grid of `memberships` (members only — never followers or applicants): admins first, 64px and marked "Admin"; others 48px + - A deactivated member appears only to project admins and staff, named and labelled "Deactivated"; the public never sees the row or counts it - Hover tooltip shows full name + role (+ "Admin") - "+ Add" button (if `permissions.canManageMembers`) opens add-member modal @@ -119,7 +120,7 @@ If slug is unknown or soft-deleted (and caller isn't staff): 404 page. | Log buzz | Navigation to `/projects/:slug/buzz/new` | "Log Buzz" button | | Post help-wanted | `POST /api/projects/:slug/help-wanted`; modal then refetch help-wanted | Modal submit | | Add member | `POST /api/projects/:slug/members` (person picker, role, "Make admin" checkbox) | Modal submit | -| Manage members | Modal listing members with role edit, "Make admin" / "Remove admin", and Remove; a change that leaves no active admin asks to confirm | "Manage Members" | +| Manage members | Modal listing members with role edit, "Make admin" / "Remove admin", and Remove; a change that leaves no active admin asks to confirm. A deactivated member's row shows their name with a "Deactivated" label and only Remove | "Manage Members" | | Follow / unfollow / mute | `POST` / `DELETE` / `PATCH /api/projects/:slug/follow` | Join block | | Apply to join | Opens the apply form: the project's open needs as checkboxes (one pre-ticked when opened from a need card), and "Tell the admins what you'd like to help with" (required if no need is ticked, 1,500 chars). Note under it: "This project's admins and site staff see your application." Submits `POST /api/projects/:slug/applications` | "Apply to join" / need card "Apply" | | Close my application | `POST /api/projects/:slug/applications/mine/close` after a confirm | Join block | From 476556af996219585414819a4e63d7fd5b55672f Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:14:10 +0000 Subject: [PATCH 35/78] fix(api): hide deactivated members from the public, name them to admins Builds the operator's rule from the spec change before it: public member lists, counts.members and project cards leave a deactivated member out; project admins and staff get the row with the person's name and deactivated: true, and may remove it, the one members act allowed on a deactivated person. Authored content keeps its placeholder author. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../src/services/project-membership.write.ts | 9 +- apps/api/src/services/project.ts | 14 ++- apps/api/src/services/serializers/project.ts | 15 +++- apps/api/tests/deactivated-members.test.ts | 86 +++++++++++++++++++ 4 files changed, 115 insertions(+), 9 deletions(-) create mode 100644 apps/api/tests/deactivated-members.test.ts diff --git a/apps/api/src/services/project-membership.write.ts b/apps/api/src/services/project-membership.write.ts index f2c7b273..4060b618 100644 --- a/apps/api/src/services/project-membership.write.ts +++ b/apps/api/src/services/project-membership.write.ts @@ -214,9 +214,12 @@ export class ProjectMembershipWriteService { const { project, memberships } = this.#projectOrThrow(projectSlug); requireAuth('project-admin | staff', { session, project, memberships }); - const person = this.#personOrThrow(personSlug); + // The one act allowed on a deactivated person: an admin removing their + // member record (projects-members.md). + const person = this.#personOrThrow(personSlug, { allowDeactivated: true }); const existing = membershipOf(this.#state, project.slug, person.slug); if (!existing) throw new ApiNotFoundError(`${person.slug} has no record on this project`); + if (person.deletedAt && existing.state !== 'member') throw new ApiNotFoundError(`Person '${personSlug}' not found`); if (existing.state !== 'member') { // Followers and applicants are not admins' to manage. throw new ConflictError(`${person.slug} is not a member of this project`, 'not_a_member'); @@ -345,10 +348,10 @@ export class ProjectMembershipWriteService { } /** The subject person; a deactivated person is absent to every members endpoint. */ - #personOrThrow(slug: string): Person { + #personOrThrow(slug: string, opts: { allowDeactivated?: boolean } = {}): Person { const id = this.#state.personIdBySlug.get(slug); const p = id ? this.#state.people.get(id) : undefined; - if (!p || p.deletedAt) throw new ApiNotFoundError(`Person '${slug}' not found`); + if (!p || (p.deletedAt && !opts.allowDeactivated)) throw new ApiNotFoundError(`Person '${slug}' not found`); return p; } } diff --git a/apps/api/src/services/project.ts b/apps/api/src/services/project.ts index 5a3fe509..b214d8e0 100644 --- a/apps/api/src/services/project.ts +++ b/apps/api/src/services/project.ts @@ -270,8 +270,8 @@ export class ProjectService { if (project.deletedAt && !isStaff) return null; const allRecords = this.#getMembershipsForProject(project.slug); - const memberships = allRecords.filter((m) => m.state === 'member'); - const memberPeople = this.#getPeopleForMemberships(memberships); + const allMembers = allRecords.filter((m) => m.state === 'member'); + const memberPeople = this.#getPeopleForMemberships(allMembers); const activeAdmin = this.#privateStore ? await hasActiveAdmin(this.#state, this.#privateStore, project.slug) : false; @@ -292,6 +292,10 @@ export class ProjectService { callerIsAgent: caller ? isAgentAccount(this.#state, caller.slug) : false, reapplyWaitRunning: wait !== null, }); + // A deactivated member is not shown to the public; admins and staff see the row. + const memberships = permissions.canManageMembers + ? allMembers + : allMembers.filter((m) => !memberPeople.get(m.personSlug)?.deletedAt); const viewer: ProjectViewer | null = own ? { state: own.state, @@ -344,8 +348,10 @@ export class ProjectService { } #serializeListItem(project: Project): ProjectListItem { - const memberships = membersOfProject(this.#state, project.slug); - const memberPeople = this.#getPeopleForMemberships(memberships); + const all = membersOfProject(this.#state, project.slug); + const memberPeople = this.#getPeopleForMemberships(all); + // Lists are public: a deactivated member is left out of members, admins and memberCount. + const memberships = all.filter((m) => !memberPeople.get(m.personSlug)?.deletedAt); const openHelpWantedCount = [...(this.#state.helpWantedByProject.get(project.slug) ?? [])] .filter((rId) => this.#state.helpWantedRoles.get(rId)?.status === 'open').length; diff --git a/apps/api/src/services/serializers/project.ts b/apps/api/src/services/serializers/project.ts index df4ee199..910ebc9c 100644 --- a/apps/api/src/services/serializers/project.ts +++ b/apps/api/src/services/serializers/project.ts @@ -132,7 +132,17 @@ export function serializeProjectMembership( return { id: m.id, projectSlug: m.projectSlug, - person: serializePersonAvatar(person) ?? { slug: null, fullName: 'Unknown', avatarUrl: null }, + // Not the "Deactivated user" placeholder: a membership is not content. Only + // project admins and staff are ever served a deactivated member's row, + // and they see who it is (project-membership.md → Spam and deactivated accounts). + person: person?.deletedAt + ? { + slug: person.slug, + fullName: person.fullName, + avatarUrl: person.avatarKey ? `/api/attachments/${person.avatarKey}` : null, + deactivated: true, + } + : (serializePersonAvatar(person) ?? { slug: null, fullName: 'Unknown', avatarUrl: null }), role: m.role ?? null, isAdmin: m.isAdmin === true, via: opts.showVia ? (m.via ?? null) : null, @@ -262,7 +272,8 @@ export function serializeProjectDetail( counts: { updates: opts.updateCount, buzz: opts.buzzCount, - members: opts.memberships.length, + // Active members only, whoever is asking. + members: opts.memberships.filter((m) => !opts.memberPeople.get(m.personSlug)?.deletedAt).length, followers: opts.followerCount, openApplications: opts.openApplications, }, diff --git a/apps/api/tests/deactivated-members.test.ts b/apps/api/tests/deactivated-members.test.ts new file mode 100644 index 00000000..62d91f4b --- /dev/null +++ b/apps/api/tests/deactivated-members.test.ts @@ -0,0 +1,86 @@ +/** + * A deactivated member (specs/behaviors/project-membership.md → Spam and + * deactivated accounts): left out of every public member list and count, + * shown by name with a Deactivated flag to the project's admins and staff, + * removable by them, and back as before on reactivation. Their authored + * content keeps the "Deactivated user" placeholder for everyone. + * + * Every person here is invented; addresses are example.org. + */ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { daysAgo, fid, personRecord, startAgentTestEnv, type AgentTestEnv, type Rec } from './helpers/agent-fixtures.js'; + +const P = { ada: 1, ben: 2, gus: 3, sam: 4, eve: 5 }; +const T = '2026-05-01T00:00:00.000Z'; +const member = (k: number, person: string, over: Rec = {}): Rec => ({ + id: fid(100 + k), projectSlug: 'proj', personSlug: person, state: 'member', isAdmin: false, muted: false, + via: 'legacy', followedAt: T, joinedAt: T, createdAt: T, updatedAt: T, ...over, +}); + +describe('a deactivated member', () => { + let env: AgentTestEnv; + beforeEach(async () => { + env = await startAgentTestEnv({ + records: { + people: [ + personRecord(P.ada, 'ada'), + personRecord(P.ben, 'ben'), + personRecord(P.gus, 'gus', { fullName: 'Gus Gone', deletedAt: daysAgo(1) }), + personRecord(P.sam, 'sam', { accountLevel: 'staff' }), + personRecord(P.eve, 'eve'), + ], + projects: [{ id: fid(50), slug: 'proj', title: 'Proj', stage: 'testing', featured: false, createdAt: T, updatedAt: T }], + 'project-memberships': [member(1, 'ada', { isAdmin: true }), member(2, 'ben'), member(3, 'gus', { role: 'Designer' })], + 'project-updates': [{ id: fid(200), projectSlug: 'proj', authorId: fid(P.gus), body: 'An old update.', number: 1, createdAt: T, updatedAt: T }], + }, + }); + }); + afterEach(async () => { + await env.close(); + }); + + const get = async (url: string, who?: number, level: 'user' | 'staff' = 'user') => + (await env.app.inject({ method: 'GET', url, ...(who ? { cookies: { cfp_session: await env.cookie(who, level) } } : {}) })).json<{ data: any }>().data; // eslint-disable-line @typescript-eslint/no-explicit-any -- test reads loosely typed JSON + + it('is left out of the public member list, counts and project cards', async () => { + for (const who of [undefined, P.eve, P.ben]) { + const p = await get('/api/projects/proj', who); + expect(p.memberships.map((m: { person: { slug: string } }) => m.person.slug)).toEqual(['ada', 'ben']); + expect(p.counts.members).toBe(2); + expect(JSON.stringify(p)).not.toContain('Gus Gone'); + expect(JSON.stringify(p.memberships)).not.toContain('Deactivated user'); + } + const [card] = await get('/api/projects'); + expect(card.memberCount).toBe(2); + expect(card.members.map((m: { slug: string }) => m.slug)).toEqual(['ada', 'ben']); + }); + + it('is shown by name with deactivated: true to project admins and staff, who can remove the record', async () => { + for (const [who, level] of [[P.ada, 'user'], [P.sam, 'staff']] as const) { + const p = await get('/api/projects/proj', who, level); + const gus = p.memberships.find((m: { person: { slug: string } }) => m.person.slug === 'gus'); + expect(gus).toMatchObject({ role: 'Designer', person: { slug: 'gus', fullName: 'Gus Gone', deactivated: true } }); + expect(p.counts.members).toBe(2); + } + const patch = await env.app.inject({ + method: 'PATCH', url: '/api/projects/proj/members/gus', payload: { role: 'x' }, + cookies: { cfp_session: await env.cookie(P.ada, 'user') }, + }); + expect(patch.statusCode).toBe(404); + const del = await env.app.inject({ + method: 'DELETE', url: '/api/projects/proj/members/gus', cookies: { cfp_session: await env.cookie(P.ada, 'user') }, + }); + expect(del.statusCode, del.body).toBe(204); + expect((await get('/api/projects/proj', P.ada)).memberships).toHaveLength(2); + }); + + it('comes back as before on reactivation; their content keeps the placeholder author meanwhile', async () => { + const update = await get('/api/projects/proj/updates/1'); + expect(update.author).toMatchObject({ slug: null, fullName: 'Deactivated user', deactivated: true }); + await env.app.inject({ method: 'POST', url: '/api/people/gus/reactivate', cookies: { cfp_session: await env.cookie(P.sam, 'staff') } }); + const p = await get('/api/projects/proj'); + expect(p.memberships.map((m: { person: { slug: string } }) => m.person.slug)).toContain('gus'); + expect(p.counts.members).toBe(3); + }); +}); From 9214cb454f1f9c850bde1275149088f55b45dbc7 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:14:10 +0000 Subject: [PATCH 36/78] fix(web): show a deactivated member to admins by name, with Remove only Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../components/modals/ManageMembersModal.tsx | 20 +++++++++++++++++-- apps/web/src/screens/ProjectDetail.tsx | 2 +- apps/web/tests/ManageMembersModal.test.tsx | 16 +++++++++++++++ 3 files changed, 35 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/modals/ManageMembersModal.tsx b/apps/web/src/components/modals/ManageMembersModal.tsx index 23e533fd..593b885f 100644 --- a/apps/web/src/components/modals/ManageMembersModal.tsx +++ b/apps/web/src/components/modals/ManageMembersModal.tsx @@ -150,9 +150,25 @@ export function ManageMembersModal({ open, onOpenChange, project }: ManageMember )} </div> <div className="flex items-center gap-1 flex-wrap justify-end"> - {/* Deactivated members: no edit actions available. */} + {/* A deactivated member: the public no longer sees them; admins + see who it is and may only remove the record. */} {m.person.deactivated || !personSlug ? ( - <span className="text-xs text-muted-foreground italic">Deactivated</span> + <> + <span className="text-xs rounded-full bg-muted px-1.5 py-0.5 text-muted-foreground">Deactivated</span> + {personSlug && ( + <Button + type="button" + size="sm" + variant="ghost" + aria-label={`Remove ${name}`} + onClick={() => handleRemove(personSlug, name, rowKey)} + disabled={busySlug === rowKey} + className="text-destructive hover:text-destructive" + > + Remove + </Button> + )} + </> ) : isEditingThisRow ? ( <> <Button diff --git a/apps/web/src/screens/ProjectDetail.tsx b/apps/web/src/screens/ProjectDetail.tsx index 0d41ae18..a22441ad 100644 --- a/apps/web/src/screens/ProjectDetail.tsx +++ b/apps/web/src/screens/ProjectDetail.tsx @@ -473,7 +473,7 @@ export function ProjectDetail({ anchor }: ProjectDetailProps = {}) { key={m.id} person={m.person} size={m.isAdmin ? 64 : 48} - title={`${m.person.fullName}${m.role ? ` · ${m.role}` : ''}${m.isAdmin ? ' · Admin' : ''}`} + title={`${m.person.fullName}${m.role ? ` · ${m.role}` : ''}${m.isAdmin ? ' · Admin' : ''}${m.person.deactivated ? ' · Deactivated' : ''}`} className={m.isAdmin ? 'ring-2 ring-primary' : ''} /> ))} diff --git a/apps/web/tests/ManageMembersModal.test.tsx b/apps/web/tests/ManageMembersModal.test.tsx index 954d9edf..7199631b 100644 --- a/apps/web/tests/ManageMembersModal.test.tsx +++ b/apps/web/tests/ManageMembersModal.test.tsx @@ -53,4 +53,20 @@ describe('ManageMembersModal', () => { await userEvent.click(screen.getByRole('button', { name: 'Remove admin: Me Person' })); await waitFor(() => expect(fetchSpy).toHaveBeenCalledTimes(1)); }); + + it('names a deactivated member, labels them and offers only Remove', () => { + const withGone = { + ...PROJECT, + memberships: [ + ...PROJECT.memberships, + { id: 'm2', projectSlug: 'sample-project', role: 'Designer', isAdmin: false, via: 'legacy', joinedAt: '2026-01-01T00:00:00Z', person: { slug: 'gus', fullName: 'Gus Gone', avatarUrl: null, deactivated: true } }, + ], + } as unknown as ProjectDetail; + renderScreen(<ManageMembersModal open onOpenChange={() => {}} project={withGone} />); + expect(screen.getAllByText('Gus Gone').length).toBeGreaterThan(0); + expect(screen.getByText('Deactivated')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Remove Gus Gone' })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Make admin: Gus Gone' })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Edit role for Gus Gone' })).not.toBeInTheDocument(); + }); }); From 50596899a3338aba0116ea0492cbd9eb683f40dc Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:29:08 +0000 Subject: [PATCH 37/78] test(api): a deactivated member is left out of the public member list The placeholder test for a membership predates the operator's rule that a membership is not content; authored content keeps its placeholder. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/tests/people-lifecycle.test.ts | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/apps/api/tests/people-lifecycle.test.ts b/apps/api/tests/people-lifecycle.test.ts index f1e1e510..2c4e369a 100644 --- a/apps/api/tests/people-lifecycle.test.ts +++ b/apps/api/tests/people-lifecycle.test.ts @@ -635,19 +635,17 @@ describe('Deactivated person reference placeholder', () => { await privateStore.cleanup(); }); - it('deactivated person reference in project membership shows placeholder', async () => { + it('a deactivated member is left out of the public member list (a membership is not content)', async () => { const res = await app.inject({ method: 'GET', url: '/api/projects/test-project' }); expect(res.statusCode).toBe(200); type MemberShape = { person: { slug: string | null; fullName: string; deactivated?: boolean } }; - const body = res.json<{ data: { memberships: MemberShape[] } }>(); + const body = res.json<{ data: { memberships: MemberShape[]; counts: { members: number } } }>(); - // alice should appear as "Deactivated user" placeholder - const placeholder = body.data.memberships.find( - (m) => m.person.fullName === 'Deactivated user', - ); - expect(placeholder).toBeDefined(); - expect(placeholder!.person.slug).toBeNull(); - expect(placeholder!.person.deactivated).toBe(true); + // alice is deactivated: no row, no placeholder, not counted + // (specs/behaviors/project-membership.md → Spam and deactivated accounts). + expect(body.data.memberships.some((m) => m.person.deactivated)).toBe(false); + expect(body.data.memberships.some((m) => m.person.slug === 'alice')).toBe(false); + expect(body.data.counts.members).toBe(body.data.memberships.length); }); }); From 538ce571c164129bd9dde8014994a1179e62f465 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:29:08 +0000 Subject: [PATCH 38/78] test(api): footprint fixtures carry applications and follows Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/tests/moderation-signals.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/api/tests/moderation-signals.test.ts b/apps/api/tests/moderation-signals.test.ts index c94ef4e0..f1d8f5a8 100644 --- a/apps/api/tests/moderation-signals.test.ts +++ b/apps/api/tests/moderation-signals.test.ts @@ -51,7 +51,7 @@ function profile(personId: string, extra: Partial<PrivateProfile> = {}): Private }; } -const NO_FOOTPRINT = { memberships: 0, updates: 0, buzz: 0, blogPosts: 0, helpWantedInterest: 0, tags: 0, rsvps: 0 }; +const NO_FOOTPRINT = { memberships: 0, applications: 0, follows: 0, updates: 0, buzz: 0, blogPosts: 0, helpWantedInterest: 0, tags: 0, rsvps: 0 }; describe('emailMatchesName', () => { it('matches when the local part contains a name token', () => { From d03af45174a29ee67f9acede579b4eacc14a6591 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:29:08 +0000 Subject: [PATCH 39/78] feat(web): apply from the project page, and an Applications screen for admins The Join block offers Apply to join (with Follow) when the project has an active admin, the re-apply date during the wait, the no-active-admin message with a link to /chat otherwise, and an applicant's sent application with View and Close my application. The apply form lists the open needs as checkboxes beside the offer and says who sees it. /projects/:slug/applications shows admins and staff each application as facts (account age, GitHub link, other projects, needs with their current status, the offer as plain text) with Accept (role, mark filled, make admin) and Close application (an emailed note, not saved). The roster shows applications. The header's Applications (N) link goes there. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/web/src/App.tsx | 2 + .../src/components/project/ApplyDialog.tsx | 135 +++++++ apps/web/src/components/project/JoinBlock.tsx | 80 +++- apps/web/src/lib/api.ts | 54 ++- apps/web/src/pages/AdminMembers.tsx | 10 + apps/web/src/screens/ProjectApplications.tsx | 344 ++++++++++++++++++ apps/web/src/screens/ProjectDetail.tsx | 21 +- apps/web/tests/ProjectApplications.test.tsx | 104 ++++++ apps/web/tests/ProjectDetail.test.tsx | 58 +++ 9 files changed, 804 insertions(+), 4 deletions(-) create mode 100644 apps/web/src/components/project/ApplyDialog.tsx create mode 100644 apps/web/src/screens/ProjectApplications.tsx create mode 100644 apps/web/tests/ProjectApplications.test.tsx diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 24589645..0ae48e46 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -11,6 +11,7 @@ import { ProjectDetail } from '@/screens/ProjectDetail'; import { ProjectEdit } from '@/screens/ProjectEdit'; import { ProjectBuzzNew } from '@/screens/ProjectBuzzNew'; import { ProjectTableCard } from '@/screens/ProjectTableCard'; +import { ProjectApplications } from '@/screens/ProjectApplications'; import { PeopleIndex } from '@/screens/PeopleIndex'; import { PersonDetail } from '@/screens/PersonDetail'; import { ProfileEdit } from '@/screens/ProfileEdit'; @@ -52,6 +53,7 @@ const router = createBrowserRouter([ { path: '/projects/:slug', element: <ProjectDetail /> }, { path: '/projects/:slug/edit', element: <ProjectEdit mode="edit" /> }, { path: '/projects/:slug/table-card', element: <ProjectTableCard /> }, + { path: '/projects/:slug/applications', element: <ProjectApplications /> }, { path: '/projects/:slug/updates/:number', element: <ProjectDetail anchor="update" /> }, { path: '/projects/:slug/buzz/:buzzSlug', element: <ProjectDetail anchor="buzz" /> }, { path: '/projects/:slug/buzz/new', element: <ProjectBuzzNew /> }, diff --git a/apps/web/src/components/project/ApplyDialog.tsx b/apps/web/src/components/project/ApplyDialog.tsx new file mode 100644 index 00000000..24496643 --- /dev/null +++ b/apps/web/src/components/project/ApplyDialog.tsx @@ -0,0 +1,135 @@ +/** + * The apply form (specs/screens/project-detail.md → Actions, "Apply to + * join"): the project's open needs as checkboxes, one pre-ticked when opened + * from a need card, and an offer that is required when no need is ticked. + */ +import { useState } from 'react'; +import { Button } from '@/components/ui/button'; +import { Checkbox } from '@/components/ui/checkbox'; +import { Label } from '@/components/ui/label'; +import { Textarea } from '@/components/ui/textarea'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { api, ApiError, type ProjectDetail } from '@/lib/api'; +import { formatAbsoluteDate } from '@/lib/time'; + +const OFFER_MAX = 1500; + +interface ApplyDialogProps { + project: ProjectDetail; + open: boolean; + onOpenChange: (open: boolean) => void; + /** A need ticked when the form opens (from a need card's Apply). */ + preselectedRoleId?: string | null; + onApplied: () => Promise<unknown>; +} + +export function ApplyDialog({ project, open, onOpenChange, preselectedRoleId, onApplied }: ApplyDialogProps) { + // Mounted fresh each time it opens (the parent keys it), so initial state is enough. + const [picked, setPicked] = useState<Set<string>>(() => new Set(preselectedRoleId ? [preselectedRoleId] : [])); + const [offer, setOffer] = useState(''); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + + const needs = project.openHelpWantedRoles; + const offerRequired = picked.size === 0; + const canSubmit = !busy && offer.length <= OFFER_MAX && (!offerRequired || offer.trim() !== ''); + + const toggle = (id: string, on: boolean) => + setPicked((s) => { + const next = new Set(s); + if (on) next.add(id); + else next.delete(id); + return next; + }); + + const submit = async (e: React.FormEvent) => { + e.preventDefault(); + setBusy(true); + setError(null); + try { + await api.projects.apply(project.slug, { roleIds: [...picked], offer: offer.trim() === '' ? null : offer }); + onOpenChange(false); + await onApplied(); + } catch (err) { + if (err instanceof ApiError && err.code === 'reapply_too_soon' && typeof err.details?.['reapplyAfter'] === 'string') { + setError(`You can apply to this project again on ${formatAbsoluteDate(err.details['reapplyAfter'])}.`); + } else if (err instanceof ApiError && err.code === 'rate_limited') { + setError('You have reached the limit on applications for now (three open at once, five a day). Try again later.'); + } else { + setError(err instanceof ApiError ? err.message : 'Something went wrong. Please try again.'); + } + } finally { + setBusy(false); + } + }; + + return ( + <Dialog open={open} onOpenChange={onOpenChange}> + <DialogContent> + <form onSubmit={submit}> + <DialogHeader> + <DialogTitle>Apply to join {project.title}</DialogTitle> + <DialogDescription> + Pick the needs you'd like to fill, tell the admins what you'd like to help with, or both. + </DialogDescription> + </DialogHeader> + <div className="space-y-4 py-4"> + {needs.length > 0 && ( + <fieldset className="space-y-2"> + <legend className="text-sm font-medium">Open needs</legend> + {needs.map((n) => ( + <div key={n.id} className="flex items-center gap-2"> + <Checkbox + id={`need-${n.id}`} + checked={picked.has(n.id)} + onCheckedChange={(v) => toggle(n.id, v === true)} + /> + <Label htmlFor={`need-${n.id}`}>{n.title}</Label> + </div> + ))} + </fieldset> + )} + <div className="space-y-1.5"> + <Label htmlFor="apply-offer"> + Tell the admins what you'd like to help with + {offerRequired && <span className="text-destructive"> *</span>} + </Label> + <Textarea + id="apply-offer" + value={offer} + onChange={(e) => setOffer(e.target.value)} + maxLength={OFFER_MAX} + rows={5} + required={offerRequired} + aria-describedby="apply-offer-note" + /> + <p id="apply-offer-note" className="text-xs text-muted-foreground"> + This project's admins and site staff see your application. {offer.length}/{OFFER_MAX} + </p> + </div> + {error && ( + <p className="text-sm text-destructive" role="alert"> + {error} + </p> + )} + </div> + <DialogFooter> + <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={busy}> + Cancel + </Button> + <Button type="submit" disabled={!canSubmit}> + {busy ? 'Sending…' : 'Send application'} + </Button> + </DialogFooter> + </form> + </DialogContent> + </Dialog> + ); +} diff --git a/apps/web/src/components/project/JoinBlock.tsx b/apps/web/src/components/project/JoinBlock.tsx index 020832c4..d93e69fd 100644 --- a/apps/web/src/components/project/JoinBlock.tsx +++ b/apps/web/src/components/project/JoinBlock.tsx @@ -22,17 +22,35 @@ import { DialogTitle, } from '@/components/ui/dialog'; import { api, ApiError, type ProjectDetail } from '@/lib/api'; +import { formatAbsoluteDate, formatRelativeTime } from '@/lib/time'; interface JoinBlockProps { project: ProjectDetail; signedIn: boolean; /** Refetch the project after a change. */ onChanged: () => Promise<unknown>; + /** Open the apply form. */ + onApply: () => void; } -export function JoinBlock({ project, signedIn, onChanged }: JoinBlockProps) { +/** The project has no active admin: the message in place of Apply. */ +function NoActiveAdmin() { + return ( + <p className="text-sm text-muted-foreground" role="note"> + This project doesn't have an active admin right now. If you're interested in picking up the torch,{' '} + {/* /chat is server-handled (specs/screens/chat.md): a full navigation. */} + <a href="/chat" className="text-primary underline hover:no-underline"> + talk to the organizers + </a> + . + </p> + ); +} + +export function JoinBlock({ project, signedIn, onChanged, onApply }: JoinBlockProps) { const viewer = project.viewer; const [leaveOpen, setLeaveOpen] = useState(false); + const [viewOpen, setViewOpen] = useState(false); const [busy, setBusy] = useState(false); const [error, setError] = useState<string | null>(null); @@ -64,6 +82,17 @@ export function JoinBlock({ project, signedIn, onChanged }: JoinBlockProps) { </DropdownMenuItem> ) : null; + // Apply, the re-apply date, or the no-active-admin message, for a non-member. + const applyLine = !project.hasActiveAdmin ? ( + <NoActiveAdmin /> + ) : viewer?.reapplyAfter ? ( + <p className="text-sm text-muted-foreground">You can apply again on {formatAbsoluteDate(viewer.reapplyAfter)}.</p> + ) : project.permissions.canApply ? ( + <Button className="w-full" onClick={onApply}> + Apply to join + </Button> + ) : null; + if (!signedIn) { return ( <section aria-label="Join this project" className="space-y-2"> @@ -125,6 +154,52 @@ export function JoinBlock({ project, signedIn, onChanged }: JoinBlockProps) { </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> + {applyLine} + {followingLine} + {errorLine} + </section> + ); + } + + if (viewer?.state === 'applicant' && viewer.application) { + const app = viewer.application; + return ( + <section aria-label="Your application" className="space-y-2"> + <div className="rounded-md border border-border p-3 space-y-2"> + <p className="text-sm"> + Application sent ✓{' '} + <span className="text-muted-foreground"> + <time dateTime={app.submittedAt} title={formatAbsoluteDate(app.submittedAt)}> + {formatRelativeTime(app.submittedAt)} + </time> + </span> + </p> + <div className="flex gap-2"> + <Button size="sm" variant="outline" onClick={() => setViewOpen((v) => !v)} aria-expanded={viewOpen}> + View + </Button> + <Button + size="sm" + variant="ghost" + disabled={busy} + onClick={() => { + if (!window.confirm('Close your application? You will keep following the project.')) return; + void run(() => api.projects.closeMyApplication(project.slug)); + }} + > + Close my application + </Button> + </div> + {viewOpen && ( + <div className="text-sm space-y-1 border-t border-border pt-2"> + <p> + <span className="font-medium">Needs:</span>{' '} + {app.roles.length > 0 ? app.roles.map((r) => r.title).join(', ') : 'none picked'} + </p> + {app.offer && <p className="whitespace-pre-wrap break-words">{app.offer}</p>} + </div> + )} + </div> {followingLine} {errorLine} </section> @@ -134,9 +209,10 @@ export function JoinBlock({ project, signedIn, onChanged }: JoinBlockProps) { if (viewer === null && project.permissions.canFollow) { return ( <section aria-label="Join this project" className="space-y-2"> - <Button className="w-full" disabled={busy} onClick={() => void run(() => api.projects.follow(project.slug))}> + <Button className="w-full" variant={applyLine ? 'outline' : 'default'} disabled={busy} onClick={() => void run(() => api.projects.follow(project.slug))}> {busy ? 'Following…' : 'Follow'} </Button> + {applyLine} {followingLine} {errorLine} </section> diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index 59f376da..d88859b4 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -150,12 +150,37 @@ export interface ProjectMembershipResponse { export type MembershipState = 'follower' | 'applicant' | 'member'; +/** specs/api/projects-applications.md → Application shape. */ +export interface ApplicationResponse { + readonly status: 'open' | 'accepted' | 'closed'; + readonly roles: ReadonlyArray<{ readonly id: string; readonly title: string; readonly status: string }>; + readonly offer: string | null; + readonly submittedAt: string; + readonly visibleAt: string; + readonly decidedBy?: PersonAvatar | null; + readonly decidedAt: string | null; + readonly decidedVia: 'site' | 'agent' | null; + readonly closedBy: 'admin' | 'applicant' | 'site' | null; + readonly closedAt: string | null; +} + +export interface ApplicationListItem { + readonly person: PersonAvatar; + readonly applicant: { + readonly accountCreatedAt: string; + readonly hasGitHubLink: boolean; + readonly memberOf: ReadonlyArray<{ readonly slug: string; readonly title: string }>; + }; + readonly state: MembershipState; + readonly application: ApplicationResponse; +} + /** The caller's own record on a project (specs/api/projects.md → Project shape). */ export interface ProjectViewer { readonly state: MembershipState; readonly isAdmin: boolean; readonly muted: boolean; - readonly application: unknown | null; + readonly application: ApplicationResponse | null; readonly reapplyAfter: string | null; } @@ -206,6 +231,8 @@ export interface ProjectDetail { readonly buzz: number; readonly members: number; readonly followers: number; + /** null unless the caller is a project admin or staff. */ + readonly openApplications: number | null; }; readonly permissions: ProjectPermissions; readonly featured: boolean; @@ -858,6 +885,7 @@ export interface MemberRow { readonly footprint: { readonly memberships: number; readonly follows: number; + readonly applications: number; readonly updates: number; readonly buzz: number; readonly blogPosts: number; @@ -896,6 +924,7 @@ interface ProjectRef { export interface MemberFootprint { readonly memberships: Array<{ project: ProjectRef; role: string | null; isAdmin: boolean; via: string | null; joinedAt: string }>; readonly follows: Array<{ project: ProjectRef; followedAt: string }>; + readonly applications: Array<{ project: ProjectRef; status: string; submittedAt: string; closedBy: string | null }>; readonly updates: Array<{ project: ProjectRef; number: number; title: string; postedAt: string }>; readonly buzz: Array<{ project: ProjectRef; slug: string; title: string; postedAt: string }>; readonly blogPosts: Array<{ slug: string; title: string; postedAt: string }>; @@ -1000,6 +1029,29 @@ export const api = { method: 'PATCH', body: JSON.stringify({ muted }), }), + apply: (slug: string, input: { roleIds: string[]; offer: string | null }): Promise<SuccessEnvelope<{ state: MembershipState; application: ApplicationResponse }>> => + request(`/api/projects/${encodeURIComponent(slug)}/applications`, { method: 'POST', body: JSON.stringify(input) }), + closeMyApplication: (slug: string): Promise<unknown> => + request(`/api/projects/${encodeURIComponent(slug)}/applications/mine/close`, { method: 'POST' }), + applications: ( + slug: string, + params: { status?: string; page?: number; perPage?: number } = {}, + ): Promise<PaginatedEnvelope<ApplicationListItem> & { metadata: { counts: Record<'open' | 'accepted' | 'closed', number> } }> => + request(`/api/projects/${encodeURIComponent(slug)}/applications${buildQuery(params)}`), + acceptApplication: ( + slug: string, + personSlug: string, + input: { role?: string | null; fillRoleIds?: string[]; isAdmin?: boolean }, + ): Promise<SuccessEnvelope<ProjectMembershipResponse>> => + request(`/api/projects/${encodeURIComponent(slug)}/applications/${encodeURIComponent(personSlug)}/accept`, { + method: 'POST', + body: JSON.stringify(input), + }), + closeApplication: (slug: string, personSlug: string, input: { note?: string | null }): Promise<unknown> => + request(`/api/projects/${encodeURIComponent(slug)}/applications/${encodeURIComponent(personSlug)}/close`, { + method: 'POST', + body: JSON.stringify(input), + }), leave: (slug: string, input: LeaveProjectInput = {}): Promise<unknown> => request(`/api/projects/${encodeURIComponent(slug)}/members/leave`, { method: 'POST', diff --git a/apps/web/src/pages/AdminMembers.tsx b/apps/web/src/pages/AdminMembers.tsx index 282586fa..c59f700e 100644 --- a/apps/web/src/pages/AdminMembers.tsx +++ b/apps/web/src/pages/AdminMembers.tsx @@ -333,6 +333,7 @@ function MemberRowView({ fp.buzz ? `${fp.buzz} buzz` : null, fp.blogPosts ? `${fp.blogPosts} post${fp.blogPosts === 1 ? '' : 's'}` : null, fp.helpWantedInterest ? `${fp.helpWantedInterest} help-wanted` : null, + fp.applications ? `${fp.applications} application${fp.applications === 1 ? '' : 's'}` : null, fp.follows ? `${fp.follows} follow${fp.follows === 1 ? '' : 's'}` : null, fp.rsvps ? `${fp.rsvps} RSVP${fp.rsvps === 1 ? '' : 's'}` : null, `${fp.tags} tag${fp.tags === 1 ? '' : 's'}`, @@ -461,6 +462,15 @@ function MemberDetailView({ slug }: { slug: string }) { </li> )), )} + {section( + 'Applications', + (footprint.applications ?? []).map((a) => ( + <li key={a.project.slug}> + <Link to={`/projects/${a.project.slug}`} className="hover:underline">{a.project.title}</Link> — {a.status} + {a.closedBy ? ` (closed by ${a.closedBy})` : ''}, applied {formatAbsoluteDate(a.submittedAt)} + </li> + )), + )} {section( 'Follows', (footprint.follows ?? []).map((f) => ( diff --git a/apps/web/src/screens/ProjectApplications.tsx b/apps/web/src/screens/ProjectApplications.tsx new file mode 100644 index 00000000..737085da --- /dev/null +++ b/apps/web/src/screens/ProjectApplications.tsx @@ -0,0 +1,344 @@ +/** + * /projects/:slug/applications — specs/screens/project-applications.md. + * Project admins and staff decide applications here. Facts, never verdicts; + * a close is never called a rejection. + */ +import { useState } from 'react'; +import { Link, Navigate, useLocation, useParams, useSearchParams } from 'react-router'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { toast } from 'sonner'; +import { Button } from '@/components/ui/button'; +import { Checkbox } from '@/components/ui/checkbox'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Textarea } from '@/components/ui/textarea'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { Breadcrumbs } from '@/components/Breadcrumbs'; +import { PersonAvatar } from '@/components/PersonAvatar'; +import { useAuth } from '@/hooks/useAuth'; +import { api, ApiError, type ApplicationListItem } from '@/lib/api'; +import { formatAbsoluteDate, formatRelativeTime } from '@/lib/time'; + +const TABS = [ + { status: 'open', label: 'Open' }, + { status: 'accepted', label: 'Accepted' }, + { status: 'closed', label: 'Closed' }, +] as const; +type Tab = (typeof TABS)[number]['status']; + +const NOTE_MAX = 1000; + +function decisionLine(item: ApplicationListItem): string | null { + const a = item.application; + const when = a.decidedAt ?? a.closedAt; + const ago = when ? `, ${formatRelativeTime(when)}` : ''; + const via = a.decidedVia === 'agent' ? ' via the ops bot' : ''; + if (a.status === 'accepted') return `Accepted by ${a.decidedBy?.fullName ?? 'an admin'}${ago}${via}`; + if (a.status === 'closed') { + if (a.closedBy === 'applicant') return `Closed by the applicant${ago}`; + if (a.closedBy === 'site') return 'Closed — no one got to it in 30 days'; + return `Closed by ${a.decidedBy?.fullName ?? 'an admin'}${ago}${via}`; + } + return null; +} + +export function ProjectApplications() { + const slug = useParams()['slug']!; + const location = useLocation(); + const { person, loading: authLoading } = useAuth(); + const [searchParams, setSearchParams] = useSearchParams(); + const raw = searchParams.get('status'); + const tab: Tab = raw === 'accepted' || raw === 'closed' ? raw : 'open'; + const [accepting, setAccepting] = useState<ApplicationListItem | null>(null); + const [closing, setClosing] = useState<ApplicationListItem | null>(null); + + const projectQ = useQuery({ queryKey: ['project', slug], queryFn: () => api.projects.get(slug), enabled: !!person }); + const listQ = useQuery({ + queryKey: ['project-applications', slug, tab], + queryFn: () => api.projects.applications(slug, { status: tab }), + enabled: !!person, + }); + + if (authLoading) return <div className="container mx-auto px-4 py-12 text-muted-foreground">Loading…</div>; + if (!person) return <Navigate to={`/login?return=${encodeURIComponent(location.pathname + location.search)}`} replace />; + + const forbidden = listQ.error instanceof ApiError && listQ.error.status === 403; + if (forbidden) { + return ( + <div className="container mx-auto px-4 py-16 text-center"> + <h1 className="text-2xl font-bold mb-2">You can't see this page</h1> + <p className="text-muted-foreground mb-4">Only this project's admins and site staff can see its applications.</p> + <Link to={`/projects/${slug}`} className="text-primary hover:underline">Back to the project</Link> + </div> + ); + } + + const project = projectQ.data?.data; + const counts = listQ.data?.metadata.counts; + const items = listQ.data?.data ?? []; + + return ( + <> + <Breadcrumbs + items={[ + { label: 'Projects', href: '/projects' }, + { label: project?.title ?? slug, href: `/projects/${slug}` }, + { label: 'Applications' }, + ]} + /> + <div className="container mx-auto px-4 py-8 max-w-3xl"> + <h1 className="text-3xl font-bold mb-1">Applications</h1> + <p className="mb-4"> + <Link to={`/projects/${slug}`} className="text-primary hover:underline">{project?.title ?? slug}</Link> + </p> + <nav aria-label="Application status" className="flex gap-2 mb-2"> + {TABS.map((t) => ( + <Button + key={t.status} + size="sm" + variant={tab === t.status ? 'default' : 'outline'} + aria-current={tab === t.status ? 'page' : undefined} + onClick={() => setSearchParams(t.status === 'open' ? {} : { status: t.status })} + > + {t.label} + {t.status === 'open' && counts ? ` (${counts.open})` : ''} + </Button> + ))} + </nav> + <p className="text-sm text-muted-foreground mb-6"> + Applicants can't see each other, and only this project's admins and site staff can see this page. + </p> + + {listQ.isLoading ? ( + <p className="text-muted-foreground">Loading applications…</p> + ) : items.length === 0 ? ( + <p className="text-muted-foreground">{tab === 'open' ? 'No open applications.' : 'None yet.'}</p> + ) : ( + <ul className="space-y-4"> + {items.map((item) => { + const a = item.application; + const decision = decisionLine(item); + return ( + <li key={`${item.person.slug}-${a.submittedAt}`} className="rounded-lg border border-border bg-card p-4 space-y-3"> + <div className="flex items-center gap-3"> + <PersonAvatar person={item.person} size={40} /> + <div> + {item.person.slug ? ( + <Link to={`/members/${item.person.slug}`} className="font-semibold hover:underline"> + {item.person.fullName} + </Link> + ) : ( + <span className="font-semibold">{item.person.fullName}</span> + )} + <p className="text-xs text-muted-foreground"> + Joined {formatRelativeTime(item.applicant.accountCreatedAt)} ·{' '} + {item.applicant.hasGitHubLink ? 'GitHub linked' : 'No GitHub linked'} ·{' '} + {item.applicant.memberOf.length > 0 ? ( + <> + Member of:{' '} + {item.applicant.memberOf.map((p, i) => ( + <span key={p.slug}> + {i > 0 && ', '} + <Link to={`/projects/${p.slug}`} className="hover:underline">{p.title}</Link> + </span> + ))} + </> + ) : ( + 'Not on any other project' + )} + </p> + </div> + </div> + <div className="text-sm"> + <span className="font-medium">Needs picked: </span> + {a.roles.length === 0 ? ( + <span className="text-muted-foreground">none</span> + ) : ( + <span className="inline-flex flex-wrap gap-1 align-middle"> + {a.roles.map((r) => ( + <span key={r.id} className="inline-flex items-center rounded-full bg-muted px-2 py-0.5 text-xs"> + {r.title} + {r.status !== 'open' && <span className="ml-1 text-muted-foreground">({r.status})</span>} + </span> + ))} + </span> + )} + </div> + {a.offer && ( + // Plain text: line breaks kept, never linked or rendered as markdown. + <p className="text-sm whitespace-pre-wrap break-words border-l-2 border-border pl-3">{a.offer}</p> + )} + <p className="text-xs text-muted-foreground"> + Applied <time dateTime={a.submittedAt} title={formatAbsoluteDate(a.submittedAt)}>{formatRelativeTime(a.submittedAt)}</time> + {decision && <> · {decision}</>} + </p> + {a.status === 'open' && ( + <div className="flex gap-2"> + <Button size="sm" aria-label={`Accept ${item.person.fullName}`} onClick={() => setAccepting(item)}> + Accept + </Button> + <Button + size="sm" + variant="outline" + aria-label={`Close application from ${item.person.fullName}`} + onClick={() => setClosing(item)} + > + Close application + </Button> + </div> + )} + </li> + ); + })} + </ul> + )} + </div> + {accepting && ( + <AcceptDialog slug={slug} item={accepting} onDone={() => setAccepting(null)} /> + )} + {closing && <CloseDialog slug={slug} item={closing} onDone={() => setClosing(null)} />} + </> + ); +} + +function useRefresh(slug: string) { + const queryClient = useQueryClient(); + return async () => { + await queryClient.invalidateQueries({ queryKey: ['project-applications', slug] }); + await queryClient.invalidateQueries({ queryKey: ['project', slug] }); + }; +} + +function AcceptDialog({ slug, item, onDone }: { slug: string; item: ApplicationListItem; onDone: () => void }) { + const refresh = useRefresh(slug); + const openNeeds = item.application.roles.filter((r) => r.status === 'open'); + const [role, setRole] = useState(item.application.roles[0]?.title ?? ''); + const [fill, setFill] = useState<Set<string>>(new Set()); + const [makeAdmin, setMakeAdmin] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + + const submit = async () => { + setBusy(true); + setError(null); + try { + await api.projects.acceptApplication(slug, item.person.slug!, { + role: role.trim() || null, + ...(fill.size > 0 ? { fillRoleIds: [...fill] } : {}), + isAdmin: makeAdmin, + }); + toast.success(`${item.person.fullName} is now a member`); + onDone(); + await refresh(); + } catch (err) { + setError(err instanceof ApiError ? err.message : 'Something went wrong. Please try again.'); + } finally { + setBusy(false); + } + }; + + return ( + <Dialog open onOpenChange={(o) => !o && onDone()}> + <DialogContent> + <DialogHeader> + <DialogTitle>Accept {item.person.fullName}</DialogTitle> + <DialogDescription>They become a member of the project and get a welcome email.</DialogDescription> + </DialogHeader> + <div className="space-y-4 py-2"> + <div className="space-y-1.5"> + <Label htmlFor="accept-role">Role</Label> + <Input id="accept-role" value={role} onChange={(e) => setRole(e.target.value)} maxLength={80} /> + </div> + {openNeeds.map((r) => ( + <div key={r.id} className="flex items-center gap-2"> + <Checkbox + id={`fill-${r.id}`} + checked={fill.has(r.id)} + onCheckedChange={(v) => + setFill((s) => { + const next = new Set(s); + if (v === true) next.add(r.id); + else next.delete(r.id); + return next; + }) + } + /> + <Label htmlFor={`fill-${r.id}`}>Mark filled: {r.title}</Label> + </div> + ))} + <div className="flex items-center gap-2"> + <Checkbox id="accept-admin" checked={makeAdmin} onCheckedChange={(v) => setMakeAdmin(v === true)} /> + <Label htmlFor="accept-admin">Make admin</Label> + </div> + {error && <p className="text-sm text-destructive" role="alert">{error}</p>} + </div> + <DialogFooter> + <Button variant="outline" onClick={onDone} disabled={busy}>Cancel</Button> + <Button onClick={() => void submit()} disabled={busy}>{busy ? 'Accepting…' : 'Accept'}</Button> + </DialogFooter> + </DialogContent> + </Dialog> + ); +} + +function CloseDialog({ slug, item, onDone }: { slug: string; item: ApplicationListItem; onDone: () => void }) { + const refresh = useRefresh(slug); + const [note, setNote] = useState(''); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + + const submit = async () => { + setBusy(true); + setError(null); + try { + await api.projects.closeApplication(slug, item.person.slug!, { note: note.trim() === '' ? null : note }); + toast.success('Application closed'); + onDone(); + await refresh(); + } catch (err) { + setError(err instanceof ApiError ? err.message : 'Something went wrong. Please try again.'); + } finally { + setBusy(false); + } + }; + + return ( + <Dialog open onOpenChange={(o) => !o && onDone()}> + <DialogContent> + <DialogHeader> + <DialogTitle>Close application from {item.person.fullName}</DialogTitle> + <DialogDescription> + They'll get a short email saying the project isn't taking this on right now, with your note if you + write one, and that they're still following the project. + </DialogDescription> + </DialogHeader> + <div className="space-y-1.5 py-2"> + <Label htmlFor="close-note">Note (optional)</Label> + <Textarea + id="close-note" + value={note} + onChange={(e) => setNote(e.target.value)} + maxLength={NOTE_MAX} + rows={4} + aria-describedby="close-note-hint" + /> + <p id="close-note-hint" className="text-xs text-muted-foreground"> + Sent to them by email; not saved anywhere. {note.length}/{NOTE_MAX} + </p> + {error && <p className="text-sm text-destructive" role="alert">{error}</p>} + </div> + <DialogFooter> + <Button variant="outline" onClick={onDone} disabled={busy}>Cancel</Button> + <Button onClick={() => void submit()} disabled={busy}>{busy ? 'Closing…' : 'Close application'}</Button> + </DialogFooter> + </DialogContent> + </Dialog> + ); +} diff --git a/apps/web/src/screens/ProjectDetail.tsx b/apps/web/src/screens/ProjectDetail.tsx index a22441ad..7b17e041 100644 --- a/apps/web/src/screens/ProjectDetail.tsx +++ b/apps/web/src/screens/ProjectDetail.tsx @@ -32,6 +32,7 @@ import { ManageMembersModal } from '@/components/modals/ManageMembersModal'; import { ExpressInterestModal } from '@/components/modals/ExpressInterestModal'; import { FillRoleModal } from '@/components/modals/FillRoleModal'; import { JoinBlock } from '@/components/project/JoinBlock'; +import { ApplyDialog } from '@/components/project/ApplyDialog'; import { useAuth } from '@/hooks/useAuth'; import { api, ApiError, type HelpWantedRoleResponse } from '@/lib/api'; import { formatRelativeTime, formatAbsoluteDate } from '@/lib/time'; @@ -90,6 +91,9 @@ export function ProjectDetail({ anchor }: ProjectDetailProps = {}) { const [memberBusy, setMemberBusy] = useState(false); const [memberError, setMemberError] = useState<string | null>(null); const [deleteOpen, setDeleteOpen] = useState(false); + // The apply form, and the need it opens with (from a need card's Apply). + const [apply, setApply] = useState<{ open: boolean; roleId: string | null; key: number }>({ open: false, roleId: null, key: 0 }); + const openApply = (roleId: string | null = null) => setApply((a) => ({ open: true, roleId, key: a.key + 1 })); // Allow ?openModal=help-wanted (from /help-wanted "Post a role" picker). // Use the state-sync pattern so we don't trigger a cascading re-render. @@ -228,6 +232,13 @@ export function ProjectDetail({ anchor }: ProjectDetailProps = {}) { <Link to={`/projects/${slug}/edit`}>Edit Project</Link> </Button> )} + {perms.canReviewApplications && ( + <Button asChild variant="outline"> + <Link to={`/projects/${slug}/applications`}> + Applications{project.counts.openApplications ? ` (${project.counts.openApplications})` : ''} + </Link> + </Button> + )} {(perms.canManageMembers || perms.canPostUpdate || perms.canLogBuzz || @@ -415,7 +426,7 @@ export function ProjectDetail({ anchor }: ProjectDetailProps = {}) { {/* Sidebar */} <aside className="space-y-6"> - <JoinBlock project={project} signedIn={isSignedIn} onChanged={() => projectQ.refetch()} /> + <JoinBlock project={project} signedIn={isSignedIn} onChanged={() => projectQ.refetch()} onApply={() => openApply()} /> {/* Project info */} <section> @@ -633,6 +644,14 @@ export function ProjectDetail({ anchor }: ProjectDetailProps = {}) { onOpenChange={setAddMemberOpen} projectSlug={slug} /> + <ApplyDialog + key={apply.key} + project={project} + open={apply.open} + onOpenChange={(open) => setApply((a) => ({ ...a, open }))} + preselectedRoleId={apply.roleId} + onApplied={() => projectQ.refetch()} + /> <ManageMembersModal open={manageMembersOpen} onOpenChange={setManageMembersOpen} diff --git a/apps/web/tests/ProjectApplications.test.tsx b/apps/web/tests/ProjectApplications.test.tsx new file mode 100644 index 00000000..38244685 --- /dev/null +++ b/apps/web/tests/ProjectApplications.test.tsx @@ -0,0 +1,104 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { Routes, Route } from 'react-router'; +import { renderScreen, mockOk } from './test-utils.js'; +import { ProjectApplications } from '../src/screens/ProjectApplications.js'; +import { AuthProvider } from '../src/hooks/useAuth.js'; + +// Radix checkboxes measure themselves with ResizeObserver, which jsdom lacks. +globalThis.ResizeObserver ??= class { + observe(): void {} + unobserve(): void {} + disconnect(): void {} +}; + +const json = (status: number, body: unknown) => + new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); + +const ITEM = { + person: { slug: 'pat', fullName: 'Pat Example', avatarUrl: null }, + applicant: { accountCreatedAt: '2026-10-01T00:00:00Z', hasGitHubLink: true, memberOf: [{ slug: 'other', title: 'Other Project' }] }, + state: 'applicant', + application: { + status: 'open', + roles: [{ id: 'r1', title: 'Frontend dev', status: 'open' }, { id: 'r2', title: 'Old need', status: 'filled' }], + offer: 'See https://example.org\nand **this**', + submittedAt: '2026-11-20T00:00:00Z', visibleAt: '2026-11-20T00:00:00Z', + decidedBy: null, decidedAt: null, decidedVia: null, closedBy: null, closedAt: null, + }, +}; + +function mockApi(listStatus = 200) { + return vi.spyOn(globalThis, 'fetch').mockImplementation(((input: string, init?: RequestInit) => { + if (input.startsWith('/api/auth/me')) { + return Promise.resolve(json(200, mockOk({ person: { id: 'u1', slug: 'ada', fullName: 'Ada', accountLevel: 'user', avatarUrl: null }, accountLevel: 'user' }))); + } + if (input.includes('/applications/pat/')) return Promise.resolve(json(200, mockOk({}))); + if (input.includes('/api/projects/proj/applications')) { + if (listStatus !== 200) return Promise.resolve(json(listStatus, { success: false, error: { code: 'forbidden', message: 'no' } })); + return Promise.resolve(json(200, { success: true, data: [ITEM], metadata: { page: 1, perPage: 20, totalItems: 1, totalPages: 1, counts: { open: 1, accepted: 0, closed: 0 } } })); + } + if (input.startsWith('/api/projects/proj')) return Promise.resolve(json(200, mockOk({ slug: 'proj', title: 'Proj' }))); + void init; + return Promise.resolve(new Response(null, { status: 404 })); + }) as typeof fetch); +} + +function render() { + renderScreen( + <AuthProvider> + <Routes> + <Route path="/projects/:slug/applications" element={<ProjectApplications />} /> + </Routes> + </AuthProvider>, + { initialEntries: ['/projects/proj/applications'] }, + ); +} + +describe('ProjectApplications', () => { + afterEach(() => vi.restoreAllMocks()); + + it('shows facts, picked needs with their status, and the offer as plain text', async () => { + mockApi(); + render(); + const links = await screen.findAllByRole('link', { name: 'Pat Example' }); + expect(links.every((l) => l.getAttribute('href') === '/members/pat')).toBe(true); + expect(screen.getByText(/GitHub linked/)).toBeInTheDocument(); + expect(screen.getByRole('link', { name: 'Other Project' })).toBeInTheDocument(); + expect(screen.getByText('(filled)')).toBeInTheDocument(); + // Never linked or rendered as markdown. + expect(screen.queryByRole('link', { name: 'https://example.org' })).not.toBeInTheDocument(); + expect(screen.getByText(/\*\*this\*\*/)).toBeInTheDocument(); + expect(screen.getByText(/only this project's admins and site staff can see this page/i)).toBeInTheDocument(); + expect(screen.queryByText(/reject|declin/i)).not.toBeInTheDocument(); + }); + + it('accepts with the role pre-filled from the first picked need', async () => { + const spy = mockApi(); + render(); + await userEvent.click(await screen.findByRole('button', { name: 'Accept Pat Example' })); + expect(screen.getByLabelText('Role')).toHaveValue('Frontend dev'); + await userEvent.click(screen.getByRole('button', { name: 'Accept' })); + await waitFor(() => expect(spy.mock.calls.some(([u]) => String(u).endsWith('/applications/pat/accept'))).toBe(true)); + }); + + it('closes with a note, telling the admin the note is not saved', async () => { + const spy = mockApi(); + render(); + await userEvent.click(await screen.findByRole('button', { name: 'Close application from Pat Example' })); + expect(screen.getByText(/not saved anywhere/i)).toBeInTheDocument(); + await userEvent.type(screen.getByLabelText(/note/i), 'Maybe next season'); + await userEvent.click(screen.getByRole('button', { name: 'Close application' })); + await waitFor(() => { + const call = spy.mock.calls.find(([u]) => String(u).endsWith('/applications/pat/close')); + expect(JSON.parse(String(call![1]!.body))).toEqual({ note: 'Maybe next season' }); + }); + }); + + it('a caller who is not an admin or staff sees the 403 message', async () => { + mockApi(403); + render(); + expect(await screen.findByText(/only this project's admins and site staff/i)).toBeInTheDocument(); + }); +}); diff --git a/apps/web/tests/ProjectDetail.test.tsx b/apps/web/tests/ProjectDetail.test.tsx index 64cbe932..78017a3a 100644 --- a/apps/web/tests/ProjectDetail.test.tsx +++ b/apps/web/tests/ProjectDetail.test.tsx @@ -6,6 +6,13 @@ import { renderScreen, mockOk, mockPaginated } from './test-utils.js'; import { ProjectDetail } from '../src/screens/ProjectDetail.js'; import { AuthProvider } from '../src/hooks/useAuth.js'; +// Radix checkboxes measure themselves with ResizeObserver, which jsdom lacks. +globalThis.ResizeObserver ??= class { + observe(): void {} + unobserve(): void {} + disconnect(): void {} +}; + const PROJECT = { id: 'p1', slug: 'sample-project', @@ -324,6 +331,57 @@ describe('ProjectDetail', () => { expect(screen.getByRole('menuitem', { name: 'Leave project' })).toBeInTheDocument(); }); + it('offers Apply to join, which opens the form with the open needs and the visibility note', async () => { + mockSignedIn({ + ...PROJECT, + openHelpWantedRoles: [{ id: 'r1', title: 'Frontend dev', commitmentHoursPerWeek: 4, status: 'open', tags: { topic: [], tech: [] } }], + permissions: { ...PROJECT.permissions, canFollow: true, canApply: true }, + } as unknown as typeof PROJECT); + renderDetail(); + await userEvent.click(await screen.findByRole('button', { name: 'Apply to join' })); + expect(await screen.findByRole('checkbox', { name: 'Frontend dev' })).toBeInTheDocument(); + expect(screen.getByText(/this project's admins and site staff see your application/i)).toBeInTheDocument(); + // No need ticked and no offer: nothing to send yet. + expect(screen.getByRole('button', { name: 'Send application' })).toBeDisabled(); + }); + + it('shows the no-active-admin message, linking /chat, in place of Apply; Follow stays', async () => { + mockSignedIn({ + ...PROJECT, + hasActiveAdmin: false, + permissions: { ...PROJECT.permissions, canFollow: true, canApply: false }, + } as unknown as typeof PROJECT); + renderDetail(); + expect(await screen.findByText(/doesn't have an active admin right now/i)).toBeInTheDocument(); + expect(screen.getByRole('link', { name: /talk to the organizers/i })).toHaveAttribute('href', '/chat'); + expect(screen.getByRole('button', { name: 'Follow' })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Apply to join' })).not.toBeInTheDocument(); + }); + + it('tells a follower in the re-apply wait when they can apply again', async () => { + mockSignedIn({ + ...PROJECT, + viewer: { state: 'follower', isAdmin: false, muted: false, application: null, reapplyAfter: '2026-12-20T00:00:00.000Z' }, + } as unknown as typeof PROJECT); + renderDetail(); + expect(await screen.findByText(/you can apply again on/i)).toBeInTheDocument(); + }); + + it('shows an applicant their sent application, with View and Close my application', async () => { + mockSignedIn({ + ...PROJECT, + viewer: { + state: 'applicant', isAdmin: false, muted: false, reapplyAfter: null, + application: { status: 'open', roles: [{ id: 'r1', title: 'Frontend dev', status: 'open' }], offer: 'I can help\nwith maps', submittedAt: '2026-11-01T00:00:00Z', visibleAt: '2026-11-01T00:00:00Z', decidedAt: null, decidedVia: null, closedBy: null, closedAt: null }, + }, + } as unknown as typeof PROJECT); + renderDetail(); + expect(await screen.findByText(/application sent ✓/i)).toBeInTheDocument(); + await userEvent.click(screen.getByRole('button', { name: 'View' })); + expect(screen.getByText(/Frontend dev/)).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Close my application' })).toBeInTheDocument(); + }); + it('asks a signed-out visitor to sign in to follow or apply', async () => { renderDetail(); expect(await screen.findByRole('link', { name: /sign in to follow or apply/i })).toHaveAttribute( From a99a6ed3325e08d74ddd6d07ae576f8d5fcb3367 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:37:51 +0000 Subject: [PATCH 40/78] chore(plans): mark membership-applications done (PR #269) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- plans/membership-applications.md | 92 +++++++++++++++++++++++++++----- 1 file changed, 80 insertions(+), 12 deletions(-) diff --git a/plans/membership-applications.md b/plans/membership-applications.md index aad214a1..4b103608 100644 --- a/plans/membership-applications.md +++ b/plans/membership-applications.md @@ -1,5 +1,5 @@ --- -status: in-progress +status: done depends: [membership-admins] specs: - specs/behaviors/project-membership.md @@ -10,6 +10,7 @@ specs: - specs/screens/project-detail.md - specs/screens/project-applications.md - specs/screens/admin-members.md +pr: 269 --- # Plan: Apply to join, with email to admins @@ -74,17 +75,17 @@ decisions ([`agent-application-feed`](agent-application-feed.md), ## Validation -- [ ] Tests: apply from no record and from follower → `applicant`, `application.status = open`; second apply → `409 application_open`; member → `409 already_member`; no active admin → `409 no_active_admin`; empty `roleIds` without `offer` → `422`; a closed or foreign role id → `422` -- [ ] Tests: admin close → `follower`, `closedBy = admin`, `decidedById` set; re-apply within 30 days → `409 reapply_too_soon` with `reapplyAfter`; after applicant close or close-for-age, re-apply succeeds at once -- [ ] Tests: the 4th open application site-wide and the 6th in 24 hours return `429` -- [ ] Tests: an account under 24 hours old applies; the application is not listed to admins and no email goes until `visibleAt`; the sweep then notifies once -- [ ] Tests: the sweep sends the 14-day reminder once and closes at 30 days in one `cfp-api` commit; a second run the same day does nothing -- [ ] Notifier test double: a new visible application emails every active admin of the project and no one else; an admin with a hard-bounced address is skipped; the close note appears in the applicant's email and in no record, commit message or log line -- [ ] A deactivated applicant's application disappears from the list, counts and emails, and returns unchanged on reactivation; purge deletes it -- [ ] The project page shows the no-active-admin message (with `/chat` link) instead of Apply on a fixture project whose only admin is deactivated -- [ ] Applications screen: project admin and staff see it; a plain member gets 403 -- [ ] Browser: apply as a new user with an offer, see "Application sent"; as the admin, accept from the Applications screen and see the person in Members; repeat and close, and see the applicant return to "Following ✓" with the re-apply date -- [ ] `npm run type-check && npm run lint && npm test` clean +- [x] Tests: apply from no record and from follower → `applicant`, `application.status = open`; second apply → `409 application_open`; member → `409 already_member`; no active admin → `409 no_active_admin`; empty `roleIds` without `offer` → `422`; a closed or foreign role id → `422` +- [x] Tests: admin close → `follower`, `closedBy = admin`, `decidedById` set; re-apply within 30 days → `409 reapply_too_soon` with `reapplyAfter`; after applicant close or close-for-age, re-apply succeeds at once +- [x] Tests: the 4th open application site-wide and the 6th in 24 hours return `429` +- [x] Tests: an account under 24 hours old applies; the application is not listed to admins and no email goes until `visibleAt`; the sweep then notifies once +- [x] Tests: the sweep sends the 14-day reminder once and closes at 30 days in one `cfp-api` commit; a second run the same day does nothing +- [x] Notifier test double: a new visible application emails every active admin of the project and no one else; an admin with a hard-bounced address is skipped; the close note appears in the applicant's email and in no record, commit message or log line +- [x] A deactivated applicant's application disappears from the list, counts and emails, and returns unchanged on reactivation; purge deletes it +- [x] The project page shows the no-active-admin message (with `/chat` link) instead of Apply on a fixture project whose only admin is deactivated +- [x] Applications screen: project admin and staff see it; a plain member gets 403 +- [x] Browser: apply as a new user with an offer, see "Application sent"; as the admin, accept from the Applications screen and see the person in Members; repeat and close, and see the applicant return to "Following ✓" with the re-apply date +- [x] `npm run type-check && npm run lint && npm test` clean ## Risks / unknowns @@ -94,4 +95,71 @@ decisions ([`agent-application-feed`](agent-application-feed.md), ## Notes +- **Operator decision during this plan: deactivated members.** The operator + reversed the placeholder rule this PR first wrote (`4df3ad1`): a + membership is not content, so a deactivated member is left out of every + public member list and count, and the project's admins and staff see the + row with the person's name and a "Deactivated" label so they know which + member they approved went away and can remove it (the one members act + allowed on a deactivated person). Authored content keeps the "Deactivated + user" placeholder for everyone. Spec in `017b714`, code in `476556a` and + `9214cb4`, tests in `tests/deactivated-members.test.ts`. It touches the + closed [`membership-admins`](membership-admins.md) area and is recorded + here because that plan is frozen. **The operator may still adjust this + point** (for instance whether staff and admins should see the row on the + public page itself or only in Manage Members). +- **Sweep cadence.** The spec says the sweep runs "daily, and shortly after + boot". It runs 30 seconds after boot and then hourly, so a held + application reaches admins within an hour of its `visibleAt` rather than up + to a day late. Every step is idempotent (`notifiedAt`, `remindedAt`, the + close), so the extra runs do nothing but look. +- **Commits.** Apply, accept and both closes are one commit each with the + default `<actor>: <METHOD> <path>` message, so neither the offer nor the + note ever reaches a commit; closes add `Closed-By`. The sweep writes at + most two commits per run as `cfp-api`: the closes for age (listing + `project/person` slugs, `Action: project-membership.close`) and the + `notifiedAt`/`remindedAt` bookkeeping, before any mail. An application + from an account old enough records `notifiedAt` in its apply commit. +- **The note never lands.** It is passed straight to the applicant's email; + the logging notifier and the app's own log lines leave it out (the test + checks the record, the full `git log -p` and every app log call). The + offer is likewise kept out of log lines. +- **Limits.** Three open applications counts the person's `applicant` + records; five a day counts submissions in the last 24 hours from an + in-process log plus each record's latest `submittedAt` (a re-application + replaces the earlier one on the record, so the log covers it until a + restart, like the other rate limits). +- **Hidden applications.** A deactivated applicant's application is left out + of the list, counts and notices; its 30-day clock keeps running, so the + sweep still closes it for age, without emailing them. +- **Recipients.** `activeAdminRecipients` reads each admin's private-profile + address at send time and skips one that is missing or marked inactive by a + bounce; no one stands in. An admin reachable only by a linked Slack account + counts toward `hasActiveAdmin` (so Apply shows) but gets no email: the + Slack channel for these notices comes with the agent plans. +- Agent accounts applying get `422 agent_account`, as the members endpoints + do. +- The Accept dialog already shows "Mark filled" per open need; the API + applies `fillRoleIds` from [`needs-on-applications`](needs-on-applications.md), + the next commits on this branch. +- **Not verified here: real email.** New templates go through the existing + Postmark token and stream; that production has what they need is + unverified (Risks above). Send one of each on sandbox before release. +- Browser check done against a local app on a throwaway data repo of + made-up people: a 2-hour-old account applied with an offer and saw + "Application sent ✓" (held: no admin notice, not listed); as the admin I + accepted an older account's application from the Applications screen + (role pre-filled from its need) and saw them in Members, closed another + with a note (no trace of the note in the data repo or the API log), and + that applicant's Join block showed "Following ✓" and "You can apply again + on December 29, 2026"; a project whose only admin is deactivated showed + the no-active-admin message with the `/chat` link and kept Follow. The + accepted applicant was not the held new account, since a held application + is not listed to admins until its hold ends. + ## Follow-ups + +- Tracked as: send one of each new email kind (new application, reminder, + accepted, closed with a note, closed for age, member added, follower + update and need) on sandbox before the release, to confirm Postmark's + sender and stream. From 4313a8e7a01b5f1613e95c95a3c7afac295c7d7b Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:37:51 +0000 Subject: [PATCH 41/78] chore(plans): mark needs-on-applications in-progress Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- plans/needs-on-applications.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plans/needs-on-applications.md b/plans/needs-on-applications.md index 2a349979..9d6cf05e 100644 --- a/plans/needs-on-applications.md +++ b/plans/needs-on-applications.md @@ -1,5 +1,5 @@ --- -status: planned +status: in-progress depends: [membership-applications] specs: - specs/behaviors/help-wanted-roles.md From a0ef925bbea8fc2a4945dfa410be46abc9bd57d9 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:37:59 +0000 Subject: [PATCH 42/78] docs(specs): give the role shape what a need card needs to pick its button help-wanted-roles.md has each card show Apply, Application sent, Member, Sign in to apply or Not taking applications, but the role shape carried only canApply, so /help-wanted and the home rail could not tell an applicant from a member or a project with no active admin. Adds the caller's standing (viewer.state, viewer.appliedForThis) and projectHasActiveAdmin, the state-about-the-caller fields authorization.md allows beside canX flags. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- specs/api/projects-help-wanted.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/specs/api/projects-help-wanted.md b/specs/api/projects-help-wanted.md index dfc918b9..88a9949e 100644 --- a/specs/api/projects-help-wanted.md +++ b/specs/api/projects-help-wanted.md @@ -168,7 +168,14 @@ Cross-project browse of open roles. Used by the `/help-wanted` screen. "canFill": false, "canClose": false }, + "viewer": { // the caller's standing, for the card's button; null when signed out + "state": "follower" | "applicant" | "member" | null, + "appliedForThis": false // an open application of the caller's selects this role + } | null, + "projectHasActiveAdmin": true, "createdAt": "...", "updatedAt": "..." } ``` + +The card's action ([help-wanted-roles.md → Display rules](../behaviors/help-wanted-roles.md#display-rules-across-screens)) follows from these: signed out → "Sign in to apply"; `viewer.state = member` → "Member"; `viewer.appliedForThis` → "Application sent ✓"; `projectHasActiveAdmin = false` → "Not taking applications"; `permissions.canApply` → "Apply". `canApply` is the project's `canApply` for the caller and the role being `open`. From b85d5eadab61dce9f6041ceea21aa5d4a8582415 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:38:39 +0000 Subject: [PATCH 43/78] feat(shared): needs filled by several members, with a details link; retire interest HelpWantedRole trades filledById for filledByIds (zero or more members, settable while the need stays open) and gains an https detailsUrl; help-wanted-roles moves to v3. The help-wanted-interest schema and its sheet contract leave the build; its published v1 and v2 documents stay in contracts/, immutable and declared by nothing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../help-wanted-roles/v3.json | 87 +++++++++++++++++++ packages/shared/src/contracts.ts | 10 +-- .../src/schemas/help-wanted-interest.ts | 19 ---- .../shared/src/schemas/help-wanted-role.ts | 5 +- packages/shared/src/schemas/index.ts | 2 - packages/shared/tests/contracts.test.ts | 1 - packages/shared/tests/schemas.test.ts | 32 ++----- 7 files changed, 102 insertions(+), 54 deletions(-) create mode 100644 contracts/codeforphilly.org/help-wanted-roles/v3.json delete mode 100644 packages/shared/src/schemas/help-wanted-interest.ts diff --git a/contracts/codeforphilly.org/help-wanted-roles/v3.json b/contracts/codeforphilly.org/help-wanted-roles/v3.json new file mode 100644 index 00000000..97e16c24 --- /dev/null +++ b/contracts/codeforphilly.org/help-wanted-roles/v3.json @@ -0,0 +1,87 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://codeforphilly.org/help-wanted-roles/v3", + "title": "Help-wanted role", + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "projectSlug": { + "type": "string", + "minLength": 1 + }, + "postedById": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "title": { + "type": "string", + "minLength": 1, + "maxLength": 120 + }, + "description": { + "type": "string", + "minLength": 1 + }, + "commitmentHoursPerWeek": { + "type": "integer", + "minimum": 0 + }, + "status": { + "default": "open", + "type": "string", + "enum": [ + "open", + "filled", + "closed" + ] + }, + "filledByIds": { + "default": [], + "type": "array", + "items": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "detailsUrl": { + "type": "string", + "format": "uri", + "pattern": "^https:\\/\\/.*" + }, + "filledAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + "closedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + "createdAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + "updatedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + } + }, + "required": [ + "createdAt", + "description", + "id", + "postedById", + "projectSlug", + "title", + "updatedAt" + ] +} diff --git a/packages/shared/src/contracts.ts b/packages/shared/src/contracts.ts index 77cd6348..f87b3128 100644 --- a/packages/shared/src/contracts.ts +++ b/packages/shared/src/contracts.ts @@ -22,7 +22,6 @@ import { EventRsvpSchema, EventSchema, EventSeriesSchema, - HelpWantedInterestExpressionSchema, HelpWantedRoleSchema, PersonEvaluationSchema, PersonSchema, @@ -54,12 +53,9 @@ export const SHEET_CONTRACTS = { 'project-updates': { schema: ProjectUpdateSchema, version: 2, title: 'Project update' }, 'project-buzz': { schema: ProjectBuzzSchema, version: 2, title: 'Project buzz' }, 'blog-posts': { schema: BlogPostSchema, version: 1, title: 'Blog post' }, - 'help-wanted-roles': { schema: HelpWantedRoleSchema, version: 2, title: 'Help-wanted role' }, - 'help-wanted-interest': { - schema: HelpWantedInterestExpressionSchema, - version: 2, - title: 'Help-wanted interest expression', - }, + // help-wanted-interest is retired (applications select needs instead); its + // published contracts stay in contracts/ unchanged, declared by no sheet. + 'help-wanted-roles': { schema: HelpWantedRoleSchema, version: 3, title: 'Help-wanted role' }, tags: { schema: TagSchema, version: 1, title: 'Tag' }, 'tag-assignments': { schema: TagAssignmentSchema, version: 1, title: 'Tag assignment' }, 'slug-history': { schema: SlugHistorySchema, version: 1, title: 'Slug history' }, diff --git a/packages/shared/src/schemas/help-wanted-interest.ts b/packages/shared/src/schemas/help-wanted-interest.ts deleted file mode 100644 index 9bd4473a..00000000 --- a/packages/shared/src/schemas/help-wanted-interest.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { z } from 'zod'; - -import { references } from '../references.js'; - -/** - * Someone's interest in a help-wanted role, keyed on disk by the role's id - * and the person's handle (`help-wanted-interest/${roleId}/${personSlug}`). - * Roles are keyed by id, so `roleId` stays an id; the person is referenced - * by slug (specs/data-model.md → References). - */ -export const HelpWantedInterestExpressionSchema = z.object({ - id: z.string().uuid(), - roleId: z.string().uuid(), - personSlug: z.string().min(1).meta(references('people.slug')), - message: z.string().max(2_000).nullable().optional(), - createdAt: z.string().datetime({ offset: true }), -}); - -export type HelpWantedInterestExpression = z.infer<typeof HelpWantedInterestExpressionSchema>; diff --git a/packages/shared/src/schemas/help-wanted-role.ts b/packages/shared/src/schemas/help-wanted-role.ts index a7f8e773..b7e38997 100644 --- a/packages/shared/src/schemas/help-wanted-role.ts +++ b/packages/shared/src/schemas/help-wanted-role.ts @@ -15,7 +15,10 @@ export const HelpWantedRoleSchema = z.object({ description: z.string().min(1), commitmentHoursPerWeek: z.number().int().min(0).nullable().optional(), status: z.enum(['open', 'filled', 'closed']).default('open'), - filledById: z.string().uuid().nullable().optional(), + /** Members who filled it; may be set while `open` (a need several people fill). Never adds anyone to the project. */ + filledByIds: z.array(z.string().uuid()).default([]), + /** HTTPS link to task-level detail (issues, a board) where the work lives. */ + detailsUrl: z.string().url().startsWith('https://').nullable().optional(), filledAt: z.string().datetime({ offset: true }).nullable().optional(), closedAt: z.string().datetime({ offset: true }).nullable().optional(), createdAt: z.string().datetime({ offset: true }), diff --git a/packages/shared/src/schemas/index.ts b/packages/shared/src/schemas/index.ts index 67373218..9ea32695 100644 --- a/packages/shared/src/schemas/index.ts +++ b/packages/shared/src/schemas/index.ts @@ -38,8 +38,6 @@ export type { TagAssignment } from './tag-assignment.js'; export { HelpWantedRoleSchema } from './help-wanted-role.js'; export type { HelpWantedRole } from './help-wanted-role.js'; -export { HelpWantedInterestExpressionSchema } from './help-wanted-interest.js'; -export type { HelpWantedInterestExpression } from './help-wanted-interest.js'; export { EventSchema, EventAgendaItemSchema, EVENT_STATUSES } from './event.js'; export type { Event, EventAgendaItem, EventStatus } from './event.js'; diff --git a/packages/shared/tests/contracts.test.ts b/packages/shared/tests/contracts.test.ts index 77deaf7a..d3c2422b 100644 --- a/packages/shared/tests/contracts.test.ts +++ b/packages/shared/tests/contracts.test.ts @@ -54,7 +54,6 @@ describe('SHEET_REFERENCES', () => { 'project-updates.projectSlug → projects.slug', 'project-buzz.projectSlug → projects.slug', 'help-wanted-roles.projectSlug → projects.slug', - 'help-wanted-interest.personSlug → people.slug', 'event-rsvps.eventSlug → events.slug', 'event-rsvps.personSlug → people.slug', 'person-evaluations.personSlug → people.slug', diff --git a/packages/shared/tests/schemas.test.ts b/packages/shared/tests/schemas.test.ts index 8c5ea475..795d9e36 100644 --- a/packages/shared/tests/schemas.test.ts +++ b/packages/shared/tests/schemas.test.ts @@ -2,7 +2,6 @@ import { describe, expect, it } from 'vitest'; import { BlogPostSchema, - HelpWantedInterestExpressionSchema, HelpWantedRoleSchema, LegacyPasswordCredentialSchema, PersonSchema, @@ -379,6 +378,14 @@ describe('HelpWantedRoleSchema', () => { expect(result.success).toBe(true); }); + it('fills by several members and takes an https details link', () => { + const base = { id: uuid, projectSlug: 'transit-app', postedById: uuid2, title: 'Dev', description: 'D', createdAt: now, updatedAt: now }; + const r = HelpWantedRoleSchema.parse({ ...base, status: 'open', filledByIds: [uuid, uuid2], detailsUrl: 'https://example.org/issues' }); + expect(r.filledByIds).toEqual([uuid, uuid2]); + expect(HelpWantedRoleSchema.parse(base).filledByIds).toEqual([]); + expect(HelpWantedRoleSchema.safeParse({ ...base, detailsUrl: 'http://example.org' }).success).toBe(false); + }); + it('rejects title exceeding 120 chars', () => { const result = HelpWantedRoleSchema.safeParse({ id: uuid, @@ -394,29 +401,6 @@ describe('HelpWantedRoleSchema', () => { }); }); -describe('HelpWantedInterestExpressionSchema', () => { - it('accepts a valid interest expression', () => { - const result = HelpWantedInterestExpressionSchema.safeParse({ - id: uuid, - roleId: uuid, - personSlug: 'janedoe', - createdAt: now, - }); - expect(result.success).toBe(true); - }); - - it('rejects message exceeding 2000 chars', () => { - const result = HelpWantedInterestExpressionSchema.safeParse({ - id: uuid, - roleId: uuid, - personSlug: 'janedoe', - message: 'x'.repeat(2001), - createdAt: now, - }); - expect(result.success).toBe(false); - }); -}); - describe('SlugHistorySchema', () => { it('accepts a valid slug history entry', () => { const result = SlugHistorySchema.safeParse({ From 748444d770347929746c3b51aa2bf411465e7b9d Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:38:44 +0000 Subject: [PATCH 44/78] chore(api): declare help-wanted-roles v3 and drop the interest sheet config Vendored with `gitsheets contracts adopt`; provenance lands when the data repo adopts from the published URL and drops its interest sheet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../help-wanted-interest/v2.toml | 28 -------- .../help-wanted-roles/v3.toml | 71 +++++++++++++++++++ apps/api/gitsheets/help-wanted-interest.toml | 4 -- apps/api/gitsheets/help-wanted-roles.toml | 2 +- 4 files changed, 72 insertions(+), 33 deletions(-) delete mode 100644 apps/api/gitsheets/contracts/codeforphilly.org/help-wanted-interest/v2.toml create mode 100644 apps/api/gitsheets/contracts/codeforphilly.org/help-wanted-roles/v3.toml delete mode 100644 apps/api/gitsheets/help-wanted-interest.toml diff --git a/apps/api/gitsheets/contracts/codeforphilly.org/help-wanted-interest/v2.toml b/apps/api/gitsheets/contracts/codeforphilly.org/help-wanted-interest/v2.toml deleted file mode 100644 index 8318743b..00000000 --- a/apps/api/gitsheets/contracts/codeforphilly.org/help-wanted-interest/v2.toml +++ /dev/null @@ -1,28 +0,0 @@ -"$id" = "https://codeforphilly.org/help-wanted-interest/v2" -"$schema" = "http://json-schema.org/draft-07/schema#" -required = ["createdAt", "id", "personSlug", "roleId"] -title = "Help-wanted interest expression" -type = "object" - -[properties.createdAt] -format = "date-time" -pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' -type = "string" - -[properties.id] -format = "uuid" -pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" -type = "string" - -[properties.message] -maxLength = 2000 -type = "string" - -[properties.personSlug] -minLength = 1 -type = "string" - -[properties.roleId] -format = "uuid" -pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" -type = "string" diff --git a/apps/api/gitsheets/contracts/codeforphilly.org/help-wanted-roles/v3.toml b/apps/api/gitsheets/contracts/codeforphilly.org/help-wanted-roles/v3.toml new file mode 100644 index 00000000..d874134a --- /dev/null +++ b/apps/api/gitsheets/contracts/codeforphilly.org/help-wanted-roles/v3.toml @@ -0,0 +1,71 @@ +"$id" = "https://codeforphilly.org/help-wanted-roles/v3" +"$schema" = "http://json-schema.org/draft-07/schema#" +required = ["createdAt", "description", "id", "postedById", "projectSlug", "title", "updatedAt"] +title = "Help-wanted role" +type = "object" + +[properties.closedAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.commitmentHoursPerWeek] +minimum = 0 +type = "integer" + +[properties.createdAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.description] +minLength = 1 +type = "string" + +[properties.detailsUrl] +format = "uri" +pattern = '^https:\/\/.*' +type = "string" + +[properties.filledAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.filledByIds] +default = [] +type = "array" + +[properties.filledByIds.items] +format = "uuid" +pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" +type = "string" + +[properties.id] +format = "uuid" +pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" +type = "string" + +[properties.postedById] +format = "uuid" +pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" +type = "string" + +[properties.projectSlug] +minLength = 1 +type = "string" + +[properties.status] +default = "open" +enum = ["open", "filled", "closed"] +type = "string" + +[properties.title] +maxLength = 120 +minLength = 1 +type = "string" + +[properties.updatedAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" diff --git a/apps/api/gitsheets/help-wanted-interest.toml b/apps/api/gitsheets/help-wanted-interest.toml deleted file mode 100644 index 1ed48cc5..00000000 --- a/apps/api/gitsheets/help-wanted-interest.toml +++ /dev/null @@ -1,4 +0,0 @@ -[gitsheet] -root = 'help-wanted-interest' -path = '${{ roleId }}/${{ personSlug }}' -implements = ["codeforphilly.org/help-wanted-interest/v2"] diff --git a/apps/api/gitsheets/help-wanted-roles.toml b/apps/api/gitsheets/help-wanted-roles.toml index 853fb477..aa3fc33f 100644 --- a/apps/api/gitsheets/help-wanted-roles.toml +++ b/apps/api/gitsheets/help-wanted-roles.toml @@ -1,4 +1,4 @@ [gitsheet] root = 'help-wanted-roles' path = '${{ projectSlug }}/${{ id }}' -implements = ["codeforphilly.org/help-wanted-roles/v2"] +implements = ["codeforphilly.org/help-wanted-roles/v3"] From e520f64f099e80dfd19e24226aa185c7d8497142 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:54:26 +0000 Subject: [PATCH 45/78] refactor(api): retire help-wanted interest everywhere it was read or written MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The help-wanted-interest sheet is gone (specs/behaviors/help-wanted-roles.md → Interest expressions, retired): its indices, loader and incremental-reload entries, rename cascade, account-claim re-pointing, person and project purge steps, prune-spam count, moderation footprint, and the interest and fill emails. Account claim now re-points filledByIds. The old slug-references migration no longer touches the retired sheet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../202610150400-slug-references.ts | 6 +- apps/api/scripts/prune-spam.ts | 5 +- apps/api/scripts/scrub-data.ts | 2 +- apps/api/src/notify/email-notifier.ts | 47 +----- apps/api/src/notify/index.ts | 39 +---- apps/api/src/notify/templates.ts | 150 ++---------------- apps/api/src/services/account-claim.ts | 33 +--- apps/api/src/services/moderation.ts | 22 +-- apps/api/src/services/person-purge.ts | 8 - apps/api/src/services/person.write.ts | 3 +- apps/api/src/services/project-purge.ts | 7 - apps/api/src/services/reference-cascade.ts | 6 - apps/api/src/store/memory/incremental.ts | 7 - apps/api/src/store/memory/loader.ts | 3 - apps/api/src/store/memory/state.ts | 35 +--- apps/api/src/store/public.ts | 2 - apps/api/src/store/state-apply.ts | 13 -- apps/api/tests/email-notifier.test.ts | 128 ++++----------- .../tests/migration-slug-references.test.ts | 5 - apps/api/tests/moderation-signals.test.ts | 2 +- apps/api/tests/prune-spam.test.ts | 2 - apps/api/tests/reload-swap.test.ts | 7 - apps/api/tests/rename-cascade.test.ts | 7 +- .../modals/ExpressInterestModal.tsx | 107 ------------- apps/web/tests/ExpressInterestModal.test.tsx | 88 ---------- 25 files changed, 70 insertions(+), 664 deletions(-) delete mode 100644 apps/web/src/components/modals/ExpressInterestModal.tsx delete mode 100644 apps/web/tests/ExpressInterestModal.test.tsx diff --git a/apps/api/scripts/migrations/202610150400-slug-references.ts b/apps/api/scripts/migrations/202610150400-slug-references.ts index 440a4e56..a9c64a27 100644 --- a/apps/api/scripts/migrations/202610150400-slug-references.ts +++ b/apps/api/scripts/migrations/202610150400-slug-references.ts @@ -10,9 +10,11 @@ * project-updates projectId → projectSlug * project-buzz projectId → projectSlug * help-wanted-roles projectId → projectSlug - * help-wanted-interest personId → personSlug * event-rsvps eventId, personId → year, eventSlug, personSlug * + * (help-wanted-interest was in this list when it ran; that sheet has since been + * retired, so the script no longer touches it.) + * * Each slug field comes from the record's on-disk value (writes have always * stored it, since the path renders from it), falling back to resolving the * dropped id through the parent sheet. An RSVP's `year` falls back to its @@ -51,7 +53,6 @@ export const MIGRATED_SHEETS = [ 'project-updates', 'project-buzz', 'help-wanted-roles', - 'help-wanted-interest', 'event-rsvps', ] as const satisfies readonly ContractSheet[]; type MigratedSheet = (typeof MIGRATED_SHEETS)[number]; @@ -62,7 +63,6 @@ const DROPPED_IDS: Record<MigratedSheet, Record<string, ParentSheet>> = { 'project-updates': { projectId: 'projects' }, 'project-buzz': { projectId: 'projects' }, 'help-wanted-roles': { projectId: 'projects' }, - 'help-wanted-interest': { personId: 'people' }, 'event-rsvps': { eventId: 'events', personId: 'people' }, }; diff --git a/apps/api/scripts/prune-spam.ts b/apps/api/scripts/prune-spam.ts index 28d3875e..1c596d95 100644 --- a/apps/api/scripts/prune-spam.ts +++ b/apps/api/scripts/prune-spam.ts @@ -348,7 +348,6 @@ export interface PruneSummary { readonly peopleAfter: number; readonly protectedByMembership: number; readonly membershipsDeleted: number; - readonly helpWantedInterestDeleted: number; readonly eventRsvpsDeleted: number; readonly personTagAssignmentsDeleted: number; readonly projectUpdatesAuthorNulled: number; @@ -487,7 +486,7 @@ export async function pruneSpam(args: CliArgs): Promise<PruneSummary> { } // --- Steps B–C: Cascade-delete every record that references a pruned - // person by slug (memberships, help-wanted interest, RSVPs) — the set + // person by slug (memberships, RSVPs) — the set // comes from the references the schemas declare. Memberships are // normally 0 (members are protected from machine verdicts); the sweep // still runs for human-vote prunes and stale records. @@ -548,7 +547,6 @@ export async function pruneSpam(args: CliArgs): Promise<PruneSummary> { peopleAfter, protectedByMembership, membershipsDeleted: referencesDeleted.get('project-memberships') ?? 0, - helpWantedInterestDeleted: referencesDeleted.get('help-wanted-interest') ?? 0, eventRsvpsDeleted: referencesDeleted.get('event-rsvps') ?? 0, personTagAssignmentsDeleted, projectUpdatesAuthorNulled, @@ -582,7 +580,6 @@ function printSummary(summary: PruneSummary, args: CliArgs): void { lines.push(`peopleAfter: ${summary.peopleAfter}`); lines.push(`protectedByMembership: ${summary.protectedByMembership}`); lines.push(`membershipsDeleted: ${summary.membershipsDeleted}`); - lines.push(`helpWantedInterestDeleted: ${summary.helpWantedInterestDeleted}`); lines.push(`eventRsvpsDeleted: ${summary.eventRsvpsDeleted}`); lines.push(`personTagAssignmentsDeleted: ${summary.personTagAssignmentsDeleted}`); lines.push(`projectUpdatesAuthorNulled: ${summary.projectUpdatesAuthorNulled}`); diff --git a/apps/api/scripts/scrub-data.ts b/apps/api/scripts/scrub-data.ts index 6cd2b6ee..9a681a77 100644 --- a/apps/api/scripts/scrub-data.ts +++ b/apps/api/scripts/scrub-data.ts @@ -138,7 +138,7 @@ export function buildSlugMap(realSlugs: readonly string[], seed: string): Map<st /** * Rewrite every field that references a person by slug (memberships, - * help-wanted interest, RSVPs, evaluations — the references the schemas + * RSVPs, evaluations — the references the schemas * declare, specs/data-model.md → References) to that person's pseudonymized * slug, so the reference still resolves and the record's path follows. */ diff --git a/apps/api/src/notify/email-notifier.ts b/apps/api/src/notify/email-notifier.ts index 8c71a9fd..6723dd24 100644 --- a/apps/api/src/notify/email-notifier.ts +++ b/apps/api/src/notify/email-notifier.ts @@ -3,14 +3,9 @@ * * Renders each notification through the templates module and hands the * result to an `EmailTransport` (Postmark in production — see - * `postmark-transport.ts`). Delivery failures are logged but never thrown — - * per `specs/api/projects-help-wanted.md`, the express-interest endpoint - * returns 202 to the caller regardless of downstream notification outcome, - * and the auth routes fire-and-forget for the same reason. - * - * Slack DM is deliberately out of scope here (tracked at #95); this is - * the email-only first cut. The Notifier interface still accepts - * `maintainerSlackHandle` so the data flow is ready when Slack lands. + * `postmark-transport.ts`). Delivery failures are logged but never thrown: + * every caller fires and forgets, since a transition succeeds whether or not + * mail is delivered. */ import type { FastifyBaseLogger } from 'fastify'; @@ -19,8 +14,6 @@ import type { EventReminderNotification, EventRsvpNotification, EventUpdatedNotification, - HelpWantedFillNotification, - HelpWantedInterestNotification, ApplicationDecisionNotification, MemberAddedNotification, NewApplicationNotification, @@ -37,8 +30,6 @@ import { renderEventUpdatedEmail, } from './event-templates.js'; import { - renderFilledEmail, - renderInterestEmail, renderPasswordResetEmail, renderWelcomeEmail, } from './templates.js'; @@ -83,22 +74,6 @@ export class EmailNotifier implements Notifier { this.#log = opts.logger; } - async notifyHelpWantedInterest( - n: HelpWantedInterestNotification, - ): Promise<{ delivered: boolean }> { - const ctx = { kind: 'help-wanted.interest', projectSlug: n.projectSlug, roleId: n.roleId }; - if (!n.maintainerEmail) { - this.#log.warn(ctx, 'help-wanted interest: no maintainer email; skipped'); - return { delivered: false }; - } - return this.#deliver( - 'help-wanted interest', - ctx, - n.maintainerEmail, - renderInterestEmail(n, this.#siteHost), - ); - } - async notifyMemberAdded(n: MemberAddedNotification): Promise<{ delivered: boolean }> { const ctx = { kind: 'membership.added', project: n.projectSlug }; if (!n.email) { @@ -167,22 +142,6 @@ export class EmailNotifier implements Notifier { ); } - async notifyHelpWantedFilled( - n: HelpWantedFillNotification, - ): Promise<{ delivered: boolean }> { - const ctx = { kind: 'help-wanted.filled', projectTitle: n.projectTitle }; - if (!n.maintainerEmail) { - this.#log.warn(ctx, 'help-wanted fill: no maintainer email; skipped'); - return { delivered: false }; - } - return this.#deliver( - 'help-wanted fill', - ctx, - n.maintainerEmail, - renderFilledEmail(n, this.#siteHost), - ); - } - async notifyEventRsvp(n: EventRsvpNotification): Promise<{ delivered: boolean }> { const ctx = { kind: 'event.rsvp', event: n.event.slug }; if (!n.email) { diff --git a/apps/api/src/notify/index.ts b/apps/api/src/notify/index.ts index cb3e3689..18c61d49 100644 --- a/apps/api/src/notify/index.ts +++ b/apps/api/src/notify/index.ts @@ -1,35 +1,14 @@ /** - * Notification fan-out for help-wanted side-effects. + * Notification fan-out: membership, application, account and event email. * - * v1 ships with email + slack-DM channels; Slack DM is stubbed until the - * Slack integration exists. Failures are logged but never fail the request — - * the spec says express-interest returns 202 to the caller regardless. + * Failures are logged but never fail the request: a transition succeeds + * whether or not mail is delivered (specs/behaviors/project-membership.md). * * The email transport is also stubbed; this module exists so the * surface is in place for write-api to call and for tests to spy on. */ import type { FastifyBaseLogger } from 'fastify'; -export interface HelpWantedInterestNotification { - readonly maintainerEmail: string | null; - readonly maintainerSlackHandle: string | null; - readonly roleTitle: string; - readonly projectTitle: string; - readonly projectSlug: string; - readonly roleId: string; - readonly interestedPersonFullName: string; - readonly interestedPersonSlug: string; - readonly message: string | null; -} - -export interface HelpWantedFillNotification { - readonly maintainerEmail: string | null; - readonly roleTitle: string; - readonly projectTitle: string; - readonly filledByFullName: string | null; - readonly filledBySlug: string | null; -} - /** * Welcome notification — fires once per Person on the GitHub OAuth * `create-fresh` outcome (a brand-new signup with no laddr-account-claim @@ -183,8 +162,6 @@ export interface Notifier { notifyMemberAdded(n: MemberAddedNotification): Promise<{ delivered: boolean }>; notifyProjectUpdate(n: ProjectUpdateNotification): Promise<{ delivered: boolean }>; notifyNewNeed(n: NewNeedNotification): Promise<{ delivered: boolean }>; - notifyHelpWantedInterest(n: HelpWantedInterestNotification): Promise<{ delivered: boolean }>; - notifyHelpWantedFilled(n: HelpWantedFillNotification): Promise<{ delivered: boolean }>; notifyWelcomeOnSignup(n: WelcomeNotification): Promise<{ delivered: boolean }>; notifyPasswordReset(n: PasswordResetNotification): Promise<{ delivered: boolean }>; notifyEventRsvp(n: EventRsvpNotification): Promise<{ delivered: boolean }>; @@ -232,16 +209,6 @@ export class LoggingNotifier implements Notifier { return { delivered: true }; } - async notifyHelpWantedInterest(n: HelpWantedInterestNotification): Promise<{ delivered: boolean }> { - this.#log.info({ kind: 'help-wanted.interest', ...n }, 'help-wanted interest notification'); - return { delivered: true }; - } - - async notifyHelpWantedFilled(n: HelpWantedFillNotification): Promise<{ delivered: boolean }> { - this.#log.info({ kind: 'help-wanted.filled', ...n }, 'help-wanted fill notification'); - return { delivered: true }; - } - async notifyWelcomeOnSignup(n: WelcomeNotification): Promise<{ delivered: boolean }> { this.#log.info({ kind: 'auth.welcome', ...n }, 'welcome notification'); return { delivered: true }; diff --git a/apps/api/src/notify/templates.ts b/apps/api/src/notify/templates.ts index 6533824c..d08a2532 100644 --- a/apps/api/src/notify/templates.ts +++ b/apps/api/src/notify/templates.ts @@ -1,99 +1,33 @@ /** - * Email templates for help-wanted notifications. + * Email templates for account notifications (welcome, password reset). * * Plain-text + HTML versions of each message. Bodies are interpolated * inline; they're short enough that a template engine would be more * overhead than the strings themselves. URLs are absolute (resolved * against the configured siteHost) so links work from email clients. */ -import type { - HelpWantedFillNotification, - HelpWantedInterestNotification, - PasswordResetNotification, - WelcomeNotification, -} from './index.js'; +import type { PasswordResetNotification, WelcomeNotification } from './index.js'; -/** Strip an absolute URL down to scheme + host + path. Useful for log lines. */ -export function buildRoleUrl(siteHost: string, projectSlug: string, roleId: string): string { - // Anchor the role on the project detail page; the front-end opens the - // help-wanted section by the role's id. - return `https://${siteHost}/projects/${projectSlug}#help-wanted-${roleId}`; -} - -/** Escape characters that have HTML meaning. Minimal but correct for our payloads. */ -function escapeHtml(s: string): string { - return s - .replace(/&/g, '&') - .replace(/</g, '<') - .replace(/>/g, '>') - .replace(/"/g, '"') - .replace(/'/g, '''); -} - -export interface InterestTemplate { +export interface WelcomeTemplate { readonly subject: string; readonly text: string; readonly html: string; } -export function renderInterestEmail( - n: HelpWantedInterestNotification, - siteHost: string, -): InterestTemplate { - const url = buildRoleUrl(siteHost, n.projectSlug, n.roleId); - const subject = `Someone's interested in your help-wanted role: ${n.roleTitle}`; - const text = [ - `${n.interestedPersonFullName} (@${n.interestedPersonSlug}) just expressed interest`, - `in your "${n.roleTitle}" role on ${n.projectTitle}.`, - '', - n.message ? `Their message:\n${n.message}\n` : '', - `View the role and reply:`, - ` ${url}`, - '', - `— Code for Philly`, - ] - .filter((line, idx, arr) => !(line === '' && arr[idx - 1] === '')) - .join('\n'); - - const html = `<!DOCTYPE html> -<html lang="en"> -<body style="font-family: system-ui, sans-serif; max-width: 32rem; margin: 0 auto; padding: 1rem; color: #111;"> - <p> - <strong>${escapeHtml(n.interestedPersonFullName)}</strong> - (<a href="https://${siteHost}/members/${encodeURIComponent(n.interestedPersonSlug)}">@${escapeHtml(n.interestedPersonSlug)}</a>) - just expressed interest in your - <a href="${url}">${escapeHtml(n.roleTitle)}</a> role on - <a href="https://${siteHost}/projects/${encodeURIComponent(n.projectSlug)}">${escapeHtml(n.projectTitle)}</a>. - </p> -${ - n.message - ? ` <blockquote style="border-left: 3px solid #ccc; padding: 0.25rem 1rem; margin: 1rem 0; color: #333; white-space: pre-wrap;">${escapeHtml(n.message)}</blockquote>` - : '' -} - <p> - <a href="${url}" style="display: inline-block; padding: 0.5rem 1rem; background: #0366d6; color: #fff; text-decoration: none; border-radius: 4px;">View the role</a> - </p> - <hr style="border: none; border-top: 1px solid #eee; margin: 2rem 0;"> - <p style="color: #666; font-size: 0.875rem;"> - You're receiving this because you're the maintainer of - ${escapeHtml(n.projectTitle)} on Code for Philly. - </p> -</body> -</html>`; - - return { subject, text, html }; -} - -export interface FilledTemplate { +export interface PasswordResetTemplate { readonly subject: string; readonly text: string; readonly html: string; } -export interface WelcomeTemplate { - readonly subject: string; - readonly text: string; - readonly html: string; +/** Escape characters that have HTML meaning. Minimal but correct for our payloads. */ +function escapeHtml(s: string): string { + return s + .replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); } export function renderWelcomeEmail( @@ -143,66 +77,6 @@ export function renderWelcomeEmail( return { subject, text, html }; } -export function renderFilledEmail( - n: HelpWantedFillNotification, - siteHost: string, -): FilledTemplate { - const subject = `Role filled: ${n.roleTitle}`; - const filledBy = n.filledByFullName ?? 'Someone'; - const filledLink = n.filledBySlug - ? `https://${siteHost}/members/${encodeURIComponent(n.filledBySlug)}` - : null; - - const text = [ - `Your "${n.roleTitle}" role on ${n.projectTitle} was just marked as filled.`, - '', - filledBy === 'Someone' - ? 'No specific person was attributed; you can edit the role to record who took it on.' - : `Filled by: ${filledBy}${n.filledBySlug ? ` (@${n.filledBySlug})` : ''}`, - '', - `— Code for Philly`, - ] - .filter((line, idx, arr) => !(line === '' && arr[idx - 1] === '')) - .join('\n'); - - const html = `<!DOCTYPE html> -<html lang="en"> -<body style="font-family: system-ui, sans-serif; max-width: 32rem; margin: 0 auto; padding: 1rem; color: #111;"> - <p> - Your <strong>${escapeHtml(n.roleTitle)}</strong> role on - <strong>${escapeHtml(n.projectTitle)}</strong> was just marked as filled. - </p> - <p> - ${ - filledLink && n.filledBySlug - ? `Filled by: <a href="${filledLink}">${escapeHtml(filledBy)}</a> (@${escapeHtml(n.filledBySlug)})` - : `No specific person was attributed; you can edit the role to record who took it on.` - } - </p> - <hr style="border: none; border-top: 1px solid #eee; margin: 2rem 0;"> - <p style="color: #666; font-size: 0.875rem;"> - You're receiving this because you're the maintainer of - ${escapeHtml(n.projectTitle)} on Code for Philly. - </p> -</body> -</html>`; - - return { subject, text, html }; -} - -export interface PasswordResetTemplate { - readonly subject: string; - readonly text: string; - readonly html: string; -} - -/** - * Render a password-reset email. The `siteHost` is needed to build the - * reset link; the token rides in the URL fragment so it doesn't end up - * in HTTP referer headers when the user clicks through. - * - * Per specs/api/auth.md `POST /api/auth/password-reset/request`. - */ export function renderPasswordResetEmail( n: PasswordResetNotification, siteHost: string, diff --git a/apps/api/src/services/account-claim.ts b/apps/api/src/services/account-claim.ts index 971d5372..ea03056a 100644 --- a/apps/api/src/services/account-claim.ts +++ b/apps/api/src/services/account-claim.ts @@ -17,14 +17,12 @@ */ import { EventRsvpSchema, - HelpWantedInterestExpressionSchema, PersonSchema, PrivateProfileSchema, ProjectMembershipSchema, SlugHistorySchema, type AccountClaimRequest, type EventRsvp, - type HelpWantedInterestExpression, type HelpWantedRole, type Person, type PrivateProfile, @@ -35,7 +33,7 @@ import { } from '@cfp/shared/schemas'; import { uuidv7 } from 'uuidv7'; import type { DualStoreTx } from '../store/store.js'; -import { interestKey, rsvpKey, type InMemoryState } from '../store/memory/state.js'; +import { rsvpKey, type InMemoryState } from '../store/memory/state.js'; import { StateApply } from '../store/state-apply.js'; import type { PrivateStore } from '../store/private/index.js'; import type { @@ -637,8 +635,9 @@ export class AccountClaimService { if (r.postedById === requester.id) { updated = { ...(updated ?? r), postedById: claimed.id }; } - if (r.filledById === requester.id) { - updated = { ...(updated ?? r), filledById: claimed.id }; + if (r.filledByIds.includes(requester.id)) { + const ids = r.filledByIds.map((id) => (id === requester.id ? claimed.id : id)); + updated = { ...(updated ?? r), filledByIds: [...new Set(ids)] }; } if (updated) { await tx.public['help-wanted-roles'].upsert(updated); @@ -646,24 +645,6 @@ export class AccountClaimService { } } - const reInterest: HelpWantedInterestExpression[] = []; - const removedInterest: HelpWantedInterestExpression[] = []; - for (const e of this.#state.helpWantedInterest.values()) { - if (e.personSlug !== requester.slug) continue; - // Dedupe: if the claimed Person already expressed interest in this role, - // drop the requester's row. - const claimedExisting = this.#state.interestByRoleAndPerson.get(interestKey(e.roleId, claimed.slug)); - if (claimedExisting) { - await tx.public['help-wanted-interest'].delete(e); - removedInterest.push(e); - continue; - } - const updated = HelpWantedInterestExpressionSchema.parse({ ...e, personSlug: claimed.slug }); - await tx.public['help-wanted-interest'].delete(e); - await tx.public['help-wanted-interest'].upsert(updated); - reInterest.push(updated); - } - // RSVPs reference the person by slug too: re-point them, dropping any for // an event the claimed Person is already going to. const reRsvps: EventRsvp[] = []; @@ -743,8 +724,6 @@ export class AccountClaimService { reUpdates, reBuzz, reRoles, - reInterest, - removedInterest, reRsvps, removedRsvps, }); @@ -765,8 +744,6 @@ interface MergeApplyInput { readonly reUpdates: ProjectUpdate[]; readonly reBuzz: ProjectBuzz[]; readonly reRoles: HelpWantedRole[]; - readonly reInterest: HelpWantedInterestExpression[]; - readonly removedInterest: HelpWantedInterestExpression[]; readonly reRsvps: EventRsvp[]; readonly removedRsvps: EventRsvp[]; } @@ -802,8 +779,6 @@ export class MergeApply { for (const u of i.reUpdates) stateApply.upsertProjectUpdate(u); for (const b of i.reBuzz) stateApply.upsertProjectBuzz(b); for (const r of i.reRoles) stateApply.upsertHelpWantedRole(r); - for (const e of i.reInterest) stateApply.upsertInterest(e); - for (const e of i.removedInterest) stateApply.removeInterest(e); for (const r of i.reRsvps) stateApply.upsertEventRsvp(r); for (const r of i.removedRsvps) stateApply.removeEventRsvp(r); } diff --git a/apps/api/src/services/moderation.ts b/apps/api/src/services/moderation.ts index 7dc94257..822fa1fd 100644 --- a/apps/api/src/services/moderation.ts +++ b/apps/api/src/services/moderation.ts @@ -106,7 +106,6 @@ export interface FootprintCounts { readonly updates: number; readonly buzz: number; readonly blogPosts: number; - readonly helpWantedInterest: number; readonly tags: number; /** Event RSVPs on record, past and upcoming events alike. */ readonly rsvps: number; @@ -179,7 +178,6 @@ export interface MemberFootprint { readonly updates: Array<{ project: ProjectRef; number: number; title: string; postedAt: string }>; readonly buzz: Array<{ project: ProjectRef; slug: string; title: string; postedAt: string }>; readonly blogPosts: Array<{ slug: string; title: string; postedAt: string }>; - readonly helpWantedInterest: Array<{ project: ProjectRef; role: { title: string }; createdAt: string }>; readonly tags: Array<{ handle: string; type: string }>; /** Event RSVPs, newest RSVP first (specs/api/moderation.md → GET /api/admin/members/:slug). */ readonly rsvps: Array<{ event: EventRef; createdAt: string }>; @@ -195,8 +193,6 @@ interface AuthoredCounts { updates: Map<string, number>; buzz: Map<string, number>; blogPosts: Map<string, number>; - /** Keyed by person slug (interest references people by slug); the rest by person id. */ - interest: Map<string, number>; } export interface MemberListResult { @@ -290,7 +286,7 @@ export function computeSignals(input: { if (input.slugPurgedBefore) negative('slug-purged-before'); if (input.lastSlackSsoAt) signals.push('slack-sso'); const fp = input.footprint; - if (fp.memberships + fp.applications + fp.updates + fp.buzz + fp.blogPosts + fp.helpWantedInterest > 0) { + if (fp.memberships + fp.applications + fp.updates + fp.buzz + fp.blogPosts > 0) { signals.push('has-footprint'); } return { signals, attention }; @@ -584,7 +580,6 @@ export class ModerationService { updates: authored.updates.get(p.id) ?? 0, buzz: authored.buzz.get(p.id) ?? 0, blogPosts: authored.blogPosts.get(p.id) ?? 0, - helpWantedInterest: authored.interest.get(p.slug) ?? 0, tags: this.#state.tagAssignmentsByTaggable.get(p.id)?.size ?? 0, rsvps: this.#state.rsvpsByPerson.get(p.slug)?.size ?? 0, }; @@ -686,15 +681,6 @@ export class ModerationService { .map((bp) => ({ slug: bp.slug, title: bp.title, postedAt: bp.postedAt })) .sort((a, b) => b.postedAt.localeCompare(a.postedAt)); - const helpWantedInterest = [...s.helpWantedInterest.values()] - .filter((i) => i.personSlug === slug) - .flatMap((i) => { - const role = s.helpWantedRoles.get(i.roleId); - const project = role ? projectRef(role.projectSlug) : null; - return role && project ? [{ project, role: { title: role.title }, createdAt: i.createdAt }] : []; - }) - .sort((a, b) => b.createdAt.localeCompare(a.createdAt)); - const tags = [...(s.tagAssignmentsByTaggable.get(id) ?? [])] .map((taId) => s.tagAssignments.get(taId)) .flatMap((ta) => { @@ -713,7 +699,7 @@ export class ModerationService { }) .sort((a, b) => b.createdAt.localeCompare(a.createdAt)); - return { memberships, applications, follows, updates, buzz, blogPosts, helpWantedInterest, tags, rsvps }; + return { memberships, applications, follows, updates, buzz, blogPosts, tags, rsvps }; } #voteView(rec: PersonEvaluation): VoteView { @@ -735,12 +721,10 @@ export class ModerationService { const updates = new Map<string, number>(); const buzz = new Map<string, number>(); const blogPosts = new Map<string, number>(); - const interest = new Map<string, number>(); for (const u of this.#state.projectUpdates.values()) bump(updates, u.authorId); for (const b of this.#state.projectBuzz.values()) bump(buzz, b.postedById); for (const bp of this.#state.blogPosts.values()) bump(blogPosts, bp.authorId); - for (const i of this.#state.helpWantedInterest.values()) bump(interest, i.personSlug); - return { updates, buzz, blogPosts, interest }; + return { updates, buzz, blogPosts }; } } diff --git a/apps/api/src/services/person-purge.ts b/apps/api/src/services/person-purge.ts index 415b6a16..6b234c9a 100644 --- a/apps/api/src/services/person-purge.ts +++ b/apps/api/src/services/person-purge.ts @@ -57,14 +57,6 @@ async function purgePersonRecords( } } - // 3. Cascade-delete help-wanted-interest. - for (const interest of state.helpWantedInterest.values()) { - if (interest.personSlug === existing.slug && !deleted.has(interest.id)) { - await tx.public['help-wanted-interest'].delete(interest); - stateApply.removeInterest(interest); - } - } - // 3b. Cascade-delete event RSVPs (path: year/eventSlug/personSlug). for (const rsvpId of state.rsvpsByPerson.get(existing.slug) ?? new Set<string>()) { const rsvp = state.eventRsvps.get(rsvpId); diff --git a/apps/api/src/services/person.write.ts b/apps/api/src/services/person.write.ts index 542a19d2..4c0f400f 100644 --- a/apps/api/src/services/person.write.ts +++ b/apps/api/src/services/person.write.ts @@ -156,7 +156,7 @@ export class PersonWriteService { stateApply.upsertPerson(updated); if (newSlug !== existing.slug) { - // Memberships, interest, RSVPs and evaluations reference the person by + // Memberships, RSVPs and evaluations reference the person by // slug and live under it: move them in this same commit. await cascadeRename(tx, this.#state, stateApply, { target: 'people', @@ -277,7 +277,6 @@ export class PersonWriteService { * One transaction that hard-deletes: * - the person record * - all project-memberships for the person - * - all help-wanted-interest expressions for the person * - all tag-assignments where taggableType = 'person' + taggableId = personId * - all project-updates authored by the person (DELETE, not null) * - all project-buzz posted by the person (DELETE, not null) diff --git a/apps/api/src/services/project-purge.ts b/apps/api/src/services/project-purge.ts index 60c21ca3..e4c98a85 100644 --- a/apps/api/src/services/project-purge.ts +++ b/apps/api/src/services/project-purge.ts @@ -54,9 +54,6 @@ function touchedByOthers(state: InMemoryState, project: Project, batch: Batch): } for (const roleId of idsIn(state.helpWantedByProject, project.slug)) { if (outsiderId(state.helpWantedRoles.get(roleId)?.postedById)) return true; - for (const id of idsIn(state.interestByRole, roleId)) { - if (outsiderSlug(state.helpWantedInterest.get(id)?.personSlug)) return true; - } } for (const rsvp of state.eventRsvps.values()) { if (rsvp.projectId === project.id && outsiderSlug(rsvp.personSlug)) return true; @@ -114,10 +111,6 @@ export async function purgeProject( if (b) await once(b.id, async () => { await tx.public['project-buzz'].delete(b); stateApply.removeProjectBuzz(b); }); } for (const roleId of idsIn(state.helpWantedByProject, project.slug)) { - for (const id of idsIn(state.interestByRole, roleId)) { - const e = state.helpWantedInterest.get(id); - if (e) await once(e.id, async () => { await tx.public['help-wanted-interest'].delete(e); stateApply.removeInterest(e); }); - } await deleteTagAssignments(tx, state, stateApply, roleId, once); const r = state.helpWantedRoles.get(roleId); if (r) await once(r.id, async () => { await tx.public['help-wanted-roles'].delete(r); stateApply.removeHelpWantedRole(r); }); diff --git a/apps/api/src/services/reference-cascade.ts b/apps/api/src/services/reference-cascade.ts index 7453fe01..303077dc 100644 --- a/apps/api/src/services/reference-cascade.ts +++ b/apps/api/src/services/reference-cascade.ts @@ -14,7 +14,6 @@ import { SHEET_REFERENCES, type ContractSheet, type SheetReference } from '@cfp/ import type { AgentGrant, EventRsvp, - HelpWantedInterestExpression, HelpWantedRole, PersonEvaluation, ProjectBuzz, @@ -68,11 +67,6 @@ const REFERENCING_SHEETS: Partial<Record<ContractSheet, ReferencingSheet<never>> remove: (a, r) => a.removeHelpWantedRole(r), upsert: (a, r) => a.upsertHelpWantedRole(r), }), - 'help-wanted-interest': sheet<HelpWantedInterestExpression>({ - records: (s) => s.helpWantedInterest.values(), - remove: (a, r) => a.removeInterest(r), - upsert: (a, r) => a.upsertInterest(r), - }), 'event-rsvps': sheet<EventRsvp>({ records: (s) => s.eventRsvps.values(), remove: (a, r) => a.removeEventRsvp(r), diff --git a/apps/api/src/store/memory/incremental.ts b/apps/api/src/store/memory/incremental.ts index 008aff08..a0831bc5 100644 --- a/apps/api/src/store/memory/incremental.ts +++ b/apps/api/src/store/memory/incremental.ts @@ -17,7 +17,6 @@ import { indexEvent, indexEventRsvp, indexEventSeries, - indexHelpWantedInterest, indexHelpWantedRole, indexMembership, indexPerson, @@ -34,7 +33,6 @@ import { unindexEvent, unindexEventRsvp, unindexEventSeries, - unindexHelpWantedInterest, unindexHelpWantedRole, unindexMembership, unindexPerson, @@ -102,11 +100,6 @@ const HANDLERS = [ ftsRemove: (fts, r) => fts.removeHelpWanted(r.id), ftsAdd: (fts, r) => fts.upsertHelpWanted(r.id, r.title, r.description), }), - handler({ - sheet: 'help-wanted-interest', - unindex: unindexHelpWantedInterest, - index: indexHelpWantedInterest, - }), handler({ sheet: 'slug-history', unindex: unindexSlugHistory, diff --git a/apps/api/src/store/memory/loader.ts b/apps/api/src/store/memory/loader.ts index 60383aa0..495f8dd4 100644 --- a/apps/api/src/store/memory/loader.ts +++ b/apps/api/src/store/memory/loader.ts @@ -12,7 +12,6 @@ import { indexEvent, indexEventRsvp, indexEventSeries, - indexHelpWantedInterest, indexHelpWantedRole, indexMembership, indexPerson, @@ -48,7 +47,6 @@ export async function loadInMemoryState(publicStore: PublicStore): Promise<InMem // config PR yet — queryAll returns [] in that case, which is fine. const blogPosts = await publicStore['blog-posts'].queryAll(); const roles = await publicStore['help-wanted-roles'].queryAll(); - const interests = await publicStore['help-wanted-interest'].queryAll(); const slugHistoryRecords = await publicStore['slug-history'].queryAll(); // Human spam votes. Absent on data repos without the sheet config → []. const evaluations = await publicStore['person-evaluations'].queryAll(); @@ -69,7 +67,6 @@ export async function loadInMemoryState(publicStore: PublicStore): Promise<InMem for (const b of buzzes) indexProjectBuzz(state, b); for (const bp of blogPosts) indexBlogPost(state, bp); for (const r of roles) indexHelpWantedRole(state, r); - for (const i of interests) indexHelpWantedInterest(state, i); // Slug-history is filtered for expiry inside indexSlugHistory — records // past their 90-day window are skipped (the sheet retains them until a // separate sweeper purges; this is the read-path defense). diff --git a/apps/api/src/store/memory/state.ts b/apps/api/src/store/memory/state.ts index 30348a9b..d53bb28c 100644 --- a/apps/api/src/store/memory/state.ts +++ b/apps/api/src/store/memory/state.ts @@ -13,7 +13,6 @@ import type { Event, EventRsvp, EventSeries, - HelpWantedInterestExpression, HelpWantedRole, Person, PersonEvaluation, @@ -41,7 +40,6 @@ export interface InMemoryState { projectBuzz: Map<string, ProjectBuzz>; blogPosts: Map<string, BlogPost>; helpWantedRoles: Map<string, HelpWantedRole>; - helpWantedInterest: Map<string, HelpWantedInterestExpression>; events: Map<string, Event>; eventRsvps: Map<string, EventRsvp>; eventSeries: Map<string, EventSeries>; @@ -116,10 +114,6 @@ export interface InMemoryState { /** tagId → Set<tagAssignmentId> */ tagAssignmentsByTag: Map<string, Set<string>>; - /** roleId + personSlug → interestId (see {@link interestKey}) */ - interestByRoleAndPerson: Map<string, string>; - /** roleId → Set<interestId> */ - interestByRole: Map<string, Set<string>>; /** * Slug-history index, keyed by `${entityType}:${oldSlug}` → newSlug + expiry. @@ -178,10 +172,6 @@ export function rsvpKey(eventSlug: string, personSlug: string): string { return `${eventSlug}:${personSlug}`; } -/** Compose the role+person interest key. */ -export function interestKey(roleId: string, personSlug: string): string { - return `${roleId}:${personSlug}`; -} /** Compose a project-scoped child key (update number, buzz slug). */ export function projectChildKey(projectSlug: string, child: string | number): string { @@ -231,7 +221,6 @@ export function createEmptyState(): InMemoryState { projectBuzz: new Map(), blogPosts: new Map(), helpWantedRoles: new Map(), - helpWantedInterest: new Map(), events: new Map(), eventRsvps: new Map(), eventSeries: new Map(), @@ -255,8 +244,6 @@ export function createEmptyState(): InMemoryState { helpWantedByProject: new Map(), tagAssignmentsByTaggable: new Map(), tagAssignmentsByTag: new Map(), - interestByRoleAndPerson: new Map(), - interestByRole: new Map(), slugHistory: new Map(), personEvaluations: new Map(), evaluationsByPerson: new Map(), @@ -426,22 +413,15 @@ export function indexBlogPost(state: InMemoryState, post: BlogPost): void { } /** Add or replace a help-wanted role and update secondary indices. */ -export function indexHelpWantedRole(state: InMemoryState, role: HelpWantedRole): void { +export function indexHelpWantedRole(state: InMemoryState, input: HelpWantedRole): void { + // A record written before help-wanted-roles v3 has no filledByIds; read it as none. + const role = Array.isArray(input.filledByIds) ? input : { ...input, filledByIds: [] }; const old = state.helpWantedRoles.get(role.id); if (old) unindexHelpWantedRole(state, old); state.helpWantedRoles.set(role.id, role); addToSet(state.helpWantedByProject, role.projectSlug, role.id); } -/** Add or replace a help-wanted interest expression and update secondary indices. */ -export function indexHelpWantedInterest(state: InMemoryState, expr: HelpWantedInterestExpression): void { - const old = state.helpWantedInterest.get(expr.id); - if (old) unindexHelpWantedInterest(state, old); - state.helpWantedInterest.set(expr.id, expr); - addToSet(state.interestByRole, expr.roleId, expr.id); - state.interestByRoleAndPerson.set(interestKey(expr.roleId, expr.personSlug), expr.id); -} - /** Add or replace one person-evaluation record (one per person + evaluator). */ export function indexPersonEvaluation(state: InMemoryState, record: PersonEvaluation): void { const key = `${record.personSlug}/${record.evaluator}`; @@ -556,15 +536,6 @@ export function unindexHelpWantedRole(state: InMemoryState, role: HelpWantedRole removeFromSet(state.helpWantedByProject, role.projectSlug, role.id); } -export function unindexHelpWantedInterest( - state: InMemoryState, - expr: HelpWantedInterestExpression, -): void { - state.helpWantedInterest.delete(expr.id); - removeFromSet(state.interestByRole, expr.roleId, expr.id); - deleteIfOwned(state.interestByRoleAndPerson, interestKey(expr.roleId, expr.personSlug), expr.id); -} - export function unindexEvent(state: InMemoryState, event: Event): void { state.events.delete(event.id); deleteIfOwned(state.eventIdBySlug, event.slug, event.id); diff --git a/apps/api/src/store/public.ts b/apps/api/src/store/public.ts index 81480cc2..7732d3d1 100644 --- a/apps/api/src/store/public.ts +++ b/apps/api/src/store/public.ts @@ -10,7 +10,6 @@ import { EventRsvpSchema, EventSchema, EventSeriesSchema, - HelpWantedInterestExpressionSchema, HelpWantedRoleSchema, PersonSchema, PersonEvaluationSchema, @@ -37,7 +36,6 @@ export const PUBLIC_SHEET_SCHEMAS = { 'project-buzz': ProjectBuzzSchema, 'blog-posts': BlogPostSchema, 'help-wanted-roles': HelpWantedRoleSchema, - 'help-wanted-interest': HelpWantedInterestExpressionSchema, tags: TagSchema, 'tag-assignments': TagAssignmentSchema, 'slug-history': SlugHistorySchema, diff --git a/apps/api/src/store/state-apply.ts b/apps/api/src/store/state-apply.ts index 2244568a..62aebe8e 100644 --- a/apps/api/src/store/state-apply.ts +++ b/apps/api/src/store/state-apply.ts @@ -13,7 +13,6 @@ import type { Event, EventRsvp, EventSeries, - HelpWantedInterestExpression, HelpWantedRole, Person, PersonEvaluation, @@ -33,7 +32,6 @@ import { indexEvent, indexEventRsvp, indexEventSeries, - indexHelpWantedInterest, indexHelpWantedRole, indexMembership, indexPerson, @@ -48,7 +46,6 @@ import { unindexAgentGrant, unindexEventRsvp, unindexEventSeries, - unindexHelpWantedInterest, unindexHelpWantedRole, unindexMembership, unindexPersonEvaluation, @@ -229,16 +226,6 @@ export class StateApply { return this; } - upsertInterest(e: HelpWantedInterestExpression): this { - this.#ops.push((state) => indexHelpWantedInterest(state, e)); - return this; - } - - removeInterest(e: HelpWantedInterestExpression): this { - this.#ops.push((state) => unindexHelpWantedInterest(state, e)); - return this; - } - upsertBlogPost(post: BlogPost): this { this.#ops.push((state) => { state.blogPosts.set(post.id, post); diff --git a/apps/api/tests/email-notifier.test.ts b/apps/api/tests/email-notifier.test.ts index 1e59f7ae..b2b63aca 100644 --- a/apps/api/tests/email-notifier.test.ts +++ b/apps/api/tests/email-notifier.test.ts @@ -3,7 +3,7 @@ * * Stubs the `EmailTransport` seam with a `vi.fn()` — verifies that the * notifier composes the right payload + handles delivery success/failure - * per the spec (express-interest must return 202 to the caller regardless). + * (a transition succeeds whether or not mail is delivered). * The Postmark adapter behind that seam has its own test * (postmark-transport.test.ts). * @@ -13,16 +13,8 @@ */ import { describe, expect, it, vi } from 'vitest'; import { EmailNotifier } from '../src/notify/email-notifier.js'; -import { - renderFilledEmail, - renderInterestEmail, - renderWelcomeEmail, -} from '../src/notify/templates.js'; -import type { - HelpWantedFillNotification, - HelpWantedInterestNotification, - WelcomeNotification, -} from '../src/notify/index.js'; +import { renderWelcomeEmail } from '../src/notify/templates.js'; +import type { ApplicationDecisionNotification, MemberAddedNotification, WelcomeNotification } from '../src/notify/index.js'; const noopLogger = { info: vi.fn(), @@ -38,24 +30,22 @@ const noopLogger = { // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any; -const baseInterest: HelpWantedInterestNotification = { - maintainerEmail: 'maintainer@example.com', - maintainerSlackHandle: null, - roleTitle: 'Frontend lead', +const baseAdded: MemberAddedNotification = { + email: 'pat@example.org', + fullName: 'Pat Example', projectTitle: 'SquadQuest', projectSlug: 'squadquest', - roleId: '01951a3c-0000-7000-8000-000000000007', - interestedPersonFullName: 'Jane Doe', - interestedPersonSlug: 'jane-doe', - message: 'I love React — let me help!', + addedByName: 'Ada Admin', }; -const baseFill: HelpWantedFillNotification = { - maintainerEmail: 'maintainer@example.com', - roleTitle: 'Frontend lead', +const baseClosed: ApplicationDecisionNotification = { + email: 'pat@example.org', + fullName: 'Pat Example', projectTitle: 'SquadQuest', - filledByFullName: 'Jane Doe', - filledBySlug: 'jane-doe', + projectSlug: 'squadquest', + outcome: 'closed', + note: 'Maybe next season.', + chatChannel: null, }; const baseWelcome: WelcomeNotification = { @@ -73,77 +63,26 @@ function makeNotifier(transport: { send: ReturnType<typeof vi.fn> }): EmailNotif }); } -describe('renderInterestEmail', () => { - it('builds subject + text + html with all fields interpolated', () => { - const tpl = renderInterestEmail(baseInterest, 'codeforphilly.org'); - expect(tpl.subject).toContain('Frontend lead'); - expect(tpl.text).toContain('Jane Doe'); - expect(tpl.text).toContain('@jane-doe'); - expect(tpl.text).toContain('SquadQuest'); - expect(tpl.text).toContain('I love React — let me help!'); - expect(tpl.text).toContain('https://codeforphilly.org/projects/squadquest'); - expect(tpl.html).toContain('<strong>Jane Doe</strong>'); - expect(tpl.html).toContain('href="https://codeforphilly.org/members/jane-doe"'); - }); - - it('omits the message blockquote when no message', () => { - const tpl = renderInterestEmail({ ...baseInterest, message: null }, 'codeforphilly.org'); - expect(tpl.html).not.toContain('blockquote'); - expect(tpl.text).not.toContain('Their message'); - }); - - it('escapes HTML in user-supplied fields', () => { - const tpl = renderInterestEmail( - { ...baseInterest, message: '<script>alert(1)</script>' }, - 'codeforphilly.org', - ); - expect(tpl.html).not.toContain('<script>'); - expect(tpl.html).toContain('<script>'); - }); -}); - -describe('renderFilledEmail', () => { - it('names the filler when filledBy is set', () => { - const tpl = renderFilledEmail(baseFill, 'codeforphilly.org'); - expect(tpl.subject).toContain('Role filled'); - expect(tpl.text).toContain('Jane Doe'); - expect(tpl.html).toContain('href="https://codeforphilly.org/members/jane-doe"'); - }); - - it('omits the link when filledBy is null', () => { - const tpl = renderFilledEmail( - { ...baseFill, filledByFullName: null, filledBySlug: null }, - 'codeforphilly.org', - ); - expect(tpl.text).toContain('No specific person'); - expect(tpl.html).not.toContain('href="https://codeforphilly.org/members/'); - }); -}); - -describe('EmailNotifier.notifyHelpWantedInterest', () => { +describe('EmailNotifier.notifyMemberAdded', () => { it('sends via the transport and returns delivered:true', async () => { const send = vi.fn().mockResolvedValue({ messageId: 'msg-123' }); const notifier = makeNotifier({ send }); - const result = await notifier.notifyHelpWantedInterest(baseInterest); + const result = await notifier.notifyMemberAdded(baseAdded); expect(result).toEqual({ delivered: true }); expect(send).toHaveBeenCalledTimes(1); const arg = send.mock.calls[0]![0]!; - expect(arg.to).toBe('maintainer@example.com'); + expect(arg.to).toBe('pat@example.org'); expect(arg.from).toContain('Code for Philly'); - expect(arg.subject).toContain('Frontend lead'); - expect(arg.text).toContain('Jane Doe'); - expect(arg.html).toContain('<strong>Jane Doe</strong>'); + expect(arg.subject).toContain('SquadQuest'); + expect(arg.text).toContain('Ada Admin'); }); - it('returns delivered:false when maintainerEmail is null (no transport call)', async () => { + it('returns delivered:false when the address is empty (no transport call)', async () => { const send = vi.fn(); const notifier = makeNotifier({ send }); - const result = await notifier.notifyHelpWantedInterest({ - ...baseInterest, - maintainerEmail: null, - }); + const result = await notifier.notifyMemberAdded({ ...baseAdded, email: '' }); expect(result).toEqual({ delivered: false }); expect(send).not.toHaveBeenCalled(); }); @@ -156,7 +95,7 @@ describe('EmailNotifier.notifyHelpWantedInterest', () => { .mockRejectedValue(Object.assign(new Error('Sender signature not found'), { code: 400, statusCode: 422 })); const notifier = makeNotifier({ send }); - const result = await notifier.notifyHelpWantedInterest(baseInterest); + const result = await notifier.notifyMemberAdded(baseAdded); expect(result).toEqual({ delivered: false }); expect(noopLogger.error).toHaveBeenCalled(); }); @@ -165,7 +104,7 @@ describe('EmailNotifier.notifyHelpWantedInterest', () => { const send = vi.fn().mockRejectedValue(new Error('network blip')); const notifier = makeNotifier({ send }); - const result = await notifier.notifyHelpWantedInterest(baseInterest); + const result = await notifier.notifyMemberAdded(baseAdded); expect(result).toEqual({ delivered: false }); }); }); @@ -239,25 +178,26 @@ describe('EmailNotifier.notifyWelcomeOnSignup', () => { }); }); -describe('EmailNotifier.notifyHelpWantedFilled', () => { - it('sends via the transport and returns delivered:true', async () => { +describe('EmailNotifier.notifyApplicationDecision', () => { + it('sends a close with the note, never calling it a rejection', async () => { const send = vi.fn().mockResolvedValue({ messageId: 'msg-456' }); const notifier = makeNotifier({ send }); - const result = await notifier.notifyHelpWantedFilled(baseFill); + const result = await notifier.notifyApplicationDecision(baseClosed); expect(result).toEqual({ delivered: true }); - expect(send).toHaveBeenCalledTimes(1); - expect(send.mock.calls[0]![0]!.subject).toContain('Role filled'); + const arg = send.mock.calls[0]![0]!; + expect(arg.text).toContain("isn't taking this on right now"); + expect(arg.text).toContain('Maybe next season.'); + expect(arg.text).toContain('still following'); + expect(`${arg.subject} ${arg.text}`).not.toMatch(/reject|declin/i); }); - it('returns delivered:false on missing maintainerEmail', async () => { + it('returns delivered:false on a missing address', async () => { const send = vi.fn(); const notifier = makeNotifier({ send }); - const result = await notifier.notifyHelpWantedFilled({ - ...baseFill, - maintainerEmail: null, - }); + const result = await notifier.notifyApplicationDecision({ ...baseClosed, email: '' }); expect(result).toEqual({ delivered: false }); expect(send).not.toHaveBeenCalled(); }); }); + diff --git a/apps/api/tests/migration-slug-references.test.ts b/apps/api/tests/migration-slug-references.test.ts index a917fcde..1e48074a 100644 --- a/apps/api/tests/migration-slug-references.test.ts +++ b/apps/api/tests/migration-slug-references.test.ts @@ -38,7 +38,6 @@ const ID = { update: '01951a3c-0000-7000-8000-000000000006', buzz: '01951a3c-0000-7000-8000-000000000007', role: '01951a3c-0000-7000-8000-000000000008', - interest: '01951a3c-0000-7000-8000-000000000009', rsvp: '01951a3c-0000-7000-8000-00000000000a', }; const IMAGE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a]); @@ -116,9 +115,6 @@ async function seedOldShape(overrides: Record<string, string | Buffer> = {}): Pr id: ID.role, projectId: ID.project, projectSlug: 'proj', postedById: ID.jane, title: 'Dev', description: 'Help', status: 'open', createdAt: NOW, updatedAt: NOW, }), - [`help-wanted-interest/${ID.role}/bob.toml`]: toml({ - id: ID.interest, roleId: ID.role, personId: ID.bob, personSlug: 'bob', createdAt: NOW, - }), // No year / eventSlug on disk: both come from the event, via eventId. 'event-rsvps/2026/hack-night/bob.toml': toml({ id: ID.rsvp, eventId: ID.event, personId: ID.bob, personSlug: 'bob', plan: 'project', @@ -154,7 +150,6 @@ describe('slug-references migration', () => { for (const path of ['project-updates/proj/1.toml', 'project-buzz/proj/press.toml', `help-wanted-roles/proj/${ID.role}.toml`]) { expect(await git('show', `main:${path}`), path).not.toContain('projectId'); } - expect(await git('show', `main:help-wanted-interest/${ID.role}/bob.toml`)).not.toContain('personId'); const rsvp = await git('show', 'main:event-rsvps/2026/hack-night/bob.toml'); expect(rsvp).toContain('year = "2026"'); diff --git a/apps/api/tests/moderation-signals.test.ts b/apps/api/tests/moderation-signals.test.ts index f1d8f5a8..d2865e70 100644 --- a/apps/api/tests/moderation-signals.test.ts +++ b/apps/api/tests/moderation-signals.test.ts @@ -51,7 +51,7 @@ function profile(personId: string, extra: Partial<PrivateProfile> = {}): Private }; } -const NO_FOOTPRINT = { memberships: 0, applications: 0, follows: 0, updates: 0, buzz: 0, blogPosts: 0, helpWantedInterest: 0, tags: 0, rsvps: 0 }; +const NO_FOOTPRINT = { memberships: 0, applications: 0, follows: 0, updates: 0, buzz: 0, blogPosts: 0, tags: 0, rsvps: 0 }; describe('emailMatchesName', () => { it('matches when the local part contains a name token', () => { diff --git a/apps/api/tests/prune-spam.test.ts b/apps/api/tests/prune-spam.test.ts index 20402aa5..8d4f3924 100644 --- a/apps/api/tests/prune-spam.test.ts +++ b/apps/api/tests/prune-spam.test.ts @@ -155,7 +155,6 @@ describe('prune-spam', () => { extra: async (tx) => { await tx.sheet('tag-assignments').upsert({ id: uuid(301), tagId: uuid(400), taggableType: 'person', taggableId: uuid(1), createdAt: NOW }); await tx.sheet('tag-assignments').upsert({ id: uuid(302), tagId: uuid(400), taggableType: 'person', taggableId: uuid(7), createdAt: NOW }); - await tx.sheet('help-wanted-interest').upsert({ id: uuid(501), roleId, personSlug: 'spammer', createdAt: NOW }); await tx.sheet('event-rsvps').upsert({ id: uuid(701), year: '2026', eventSlug: 'hack-night', personSlug: 'spammer', createdAt: NOW, updatedAt: NOW }); await tx.sheet('event-rsvps').upsert({ id: uuid(702), year: '2026', eventSlug: 'hack-night', personSlug: 'clean', createdAt: NOW, updatedAt: NOW }); await tx.sheet('project-updates').upsert({ id: uuid(601), authorId: uuid(1), body: 'hi', number: 1, projectSlug: 'proj', createdAt: NOW, updatedAt: NOW }); @@ -172,7 +171,6 @@ describe('prune-spam', () => { peopleAfter: 5, protectedByMembership: 1, membershipsDeleted: 1, - helpWantedInterestDeleted: 1, eventRsvpsDeleted: 1, personTagAssignmentsDeleted: 1, projectUpdatesAuthorNulled: 1, diff --git a/apps/api/tests/reload-swap.test.ts b/apps/api/tests/reload-swap.test.ts index 797948d6..59a40ef9 100644 --- a/apps/api/tests/reload-swap.test.ts +++ b/apps/api/tests/reload-swap.test.ts @@ -15,7 +15,6 @@ import type { BlogPost, Event, EventRsvp, - HelpWantedInterestExpression, HelpWantedRole, Person, Project, @@ -36,7 +35,6 @@ import { indexEventSeries, indexAgentGrant, indexSpamPurge, - indexHelpWantedInterest, indexPersonEvaluation, indexHelpWantedRole, indexMembership, @@ -127,10 +125,6 @@ function makeRole(n: number, projectSlug: string): HelpWantedRole { return { id: uuid(n), projectSlug, createdAt: NOW, updatedAt: NOW } as unknown as HelpWantedRole; } -function makeInterest(n: number, roleId: string, personSlug: string): HelpWantedInterestExpression { - return { id: uuid(n), roleId, personSlug, createdAt: NOW } as unknown as HelpWantedInterestExpression; -} - function makeEvent(n: number, slug: string, legacyId: number): Event { return { id: uuid(n), slug, legacyId, title: slug, status: 'scheduled', startsAt: NOW, endsAt: NOW, icsSequence: 0, createdAt: NOW, updatedAt: NOW } as unknown as Event; } @@ -172,7 +166,6 @@ function buildState(base: number, slugs: { project: string; buzz: string; oldSlu indexProjectUpdate(state, makeUpdate(base + 7, project.slug, 1)); indexBlogPost(state, makeBlogPost(base + 8, `${slugs.project}-post`, 7)); indexHelpWantedRole(state, role); - indexHelpWantedInterest(state, makeInterest(base + 10, role.id, person.slug)); indexSlugHistory(state, makeSlugHistory(base + 11, project.id, slugs.oldSlug, slugs.project)); const series = { id: uuid(base + 14), slug: `${slugs.project}-series`, title: 'Series', createdAt: NOW, updatedAt: NOW }; indexEventSeries(state, series); diff --git a/apps/api/tests/rename-cascade.test.ts b/apps/api/tests/rename-cascade.test.ts index 1d456607..20d70c23 100644 --- a/apps/api/tests/rename-cascade.test.ts +++ b/apps/api/tests/rename-cascade.test.ts @@ -69,10 +69,6 @@ async function seedReferencingRecords(): Promise<void> { id: '01951a3c-0000-7000-8000-0000000000e4', year: '2026', eventSlug: EVENT_SLUG, personSlug: 'other-person', createdAt: NOW, updatedAt: NOW, }); - await tx.sheet('help-wanted-interest').upsert({ - id: '01951a3c-0000-7000-8000-0000000000e5', roleId: fixtures.helpWantedId, - personSlug: fixtures.personSlug, message: 'Count me in', createdAt: NOW, - }); await tx.sheet('person-evaluations').upsert({ personSlug: fixtures.personSlug, evaluator: 'human-other-person', verdict: 'legit', confidence: 1, flags: [], evaluatedAt: NOW, @@ -139,7 +135,6 @@ function inMemory(state: InMemoryState, sheet: ContractSheet): Rec[] { 'project-updates': state.projectUpdates, 'project-buzz': state.projectBuzz, 'help-wanted-roles': state.helpWantedRoles, - 'help-wanted-interest': state.helpWantedInterest, 'event-rsvps': state.eventRsvps, 'person-evaluations': state.personEvaluations, 'agent-grants': state.agentGrants, @@ -267,7 +262,7 @@ describe('rename cascade', () => { ]); }); - it('a person rename keeps their memberships, interest and RSVP visible through the API', async () => { + it('a person rename keeps their memberships and RSVP visible through the API', async () => { const newSlug = 'jane-renamed'; await rename('people', fixtures.personSlug, newSlug); diff --git a/apps/web/src/components/modals/ExpressInterestModal.tsx b/apps/web/src/components/modals/ExpressInterestModal.tsx deleted file mode 100644 index 529d500f..00000000 --- a/apps/web/src/components/modals/ExpressInterestModal.tsx +++ /dev/null @@ -1,107 +0,0 @@ -import { useState } from 'react'; -import { useQueryClient } from '@tanstack/react-query'; -import { toast } from 'sonner'; -import { - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, -} from '@/components/ui/dialog'; -import { Button } from '@/components/ui/button'; -import { Label } from '@/components/ui/label'; -import { Textarea } from '@/components/ui/textarea'; -import { api, ApiError } from '@/lib/api'; - -interface ExpressInterestModalProps { - open: boolean; - onOpenChange: (open: boolean) => void; - projectSlug: string; - roleId: string; - roleTitle: string; -} - -export function ExpressInterestModal({ - open, - onOpenChange, - projectSlug, - roleId, - roleTitle, -}: ExpressInterestModalProps) { - const queryClient = useQueryClient(); - const [message, setMessage] = useState(''); - const [submitting, setSubmitting] = useState(false); - - const handleSubmit = async (e: React.FormEvent) => { - e.preventDefault(); - setSubmitting(true); - try { - await api.helpWantedRole.expressInterest(projectSlug, roleId, { - message: message.trim() || null, - }); - await queryClient.invalidateQueries({ queryKey: ['project', projectSlug] }); - await queryClient.invalidateQueries({ - queryKey: ['project-help-wanted', projectSlug], - }); - await queryClient.invalidateQueries({ queryKey: ['help-wanted-index'] }); - toast.success('Interest sent — the project maintainer will be notified'); - setMessage(''); - onOpenChange(false); - } catch (err) { - if (err instanceof ApiError) { - if (err.code === 'already_expressed') { - toast.error( - 'You expressed interest in this role recently. Try again in 30 days.', - ); - } else if (err.code === 'role_not_open') { - toast.error('This role is no longer accepting interest.'); - } else { - toast.error(err.message); - } - } else { - toast.error("Couldn't send interest."); - } - } finally { - setSubmitting(false); - } - }; - - return ( - <Dialog open={open} onOpenChange={onOpenChange}> - <DialogContent> - <form onSubmit={handleSubmit}> - <DialogHeader> - <DialogTitle>Express Interest</DialogTitle> - <DialogDescription> - Send a note to the maintainer of <strong>{roleTitle}</strong>. Your name - and contact info are included automatically. - </DialogDescription> - </DialogHeader> - <div className="py-4 space-y-2"> - <Label htmlFor="interest-message">Optional message</Label> - <Textarea - id="interest-message" - value={message} - onChange={(e) => setMessage(e.target.value)} - placeholder="Tell them a bit about your interest, availability, or background…" - rows={5} - maxLength={2000} - /> - <p className="text-xs text-muted-foreground text-right"> - {message.length} / 2000 - </p> - </div> - <DialogFooter> - <Button type="button" variant="outline" onClick={() => onOpenChange(false)}> - Cancel - </Button> - <Button type="submit" disabled={submitting}> - {submitting ? 'Sending…' : 'Send interest'} - </Button> - </DialogFooter> - </form> - </DialogContent> - </Dialog> - ); -} diff --git a/apps/web/tests/ExpressInterestModal.test.tsx b/apps/web/tests/ExpressInterestModal.test.tsx deleted file mode 100644 index 89d62ce0..00000000 --- a/apps/web/tests/ExpressInterestModal.test.tsx +++ /dev/null @@ -1,88 +0,0 @@ -import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'; -import { screen, waitFor } from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; -import { renderScreen, mockOk } from './test-utils.js'; -import { ExpressInterestModal } from '../src/components/modals/ExpressInterestModal.js'; - -describe('ExpressInterestModal', () => { - let lastUrl = ''; - let lastBody: unknown = null; - let respondWithRateCap = false; - - beforeEach(() => { - lastUrl = ''; - lastBody = null; - respondWithRateCap = false; - vi.spyOn(globalThis, 'fetch').mockImplementation(((input: string, init?: RequestInit) => { - lastUrl = input; - lastBody = init?.body ? JSON.parse(String(init.body)) : null; - if (respondWithRateCap) { - return Promise.resolve( - new Response( - JSON.stringify({ - success: false, - error: { code: 'already_expressed', message: 'Already expressed within 30 days' }, - metadata: { timestamp: new Date().toISOString() }, - }), - { status: 409, headers: { 'content-type': 'application/json' } }, - ), - ); - } - return Promise.resolve( - new Response(JSON.stringify(mockOk({ delivered: true })), { - status: 202, - headers: { 'content-type': 'application/json' }, - }), - ); - }) as typeof fetch); - }); - - afterEach(() => { - vi.restoreAllMocks(); - }); - - it('submits with optional message and POSTs the correct endpoint', async () => { - const user = userEvent.setup(); - const onOpenChange = vi.fn(); - renderScreen( - <ExpressInterestModal - open - onOpenChange={onOpenChange} - projectSlug="alpha" - roleId="r-1" - roleTitle="React dev" - />, - ); - - await user.type(screen.getByLabelText(/optional message/i), 'I would love to help'); - await user.click(screen.getByRole('button', { name: /send interest/i })); - - await waitFor(() => { - expect(lastUrl).toBe('/api/projects/alpha/help-wanted/r-1/express-interest'); - }); - expect((lastBody as { message: string }).message).toBe('I would love to help'); - expect(onOpenChange).toHaveBeenCalledWith(false); - }); - - it('handles 30-day rate-cap (already_expressed) by surfacing an error', async () => { - respondWithRateCap = true; - const user = userEvent.setup(); - renderScreen( - <ExpressInterestModal - open - onOpenChange={vi.fn()} - projectSlug="alpha" - roleId="r-1" - roleTitle="React dev" - />, - ); - - await user.click(screen.getByRole('button', { name: /send interest/i })); - - await waitFor(() => { - expect(lastUrl).toBe('/api/projects/alpha/help-wanted/r-1/express-interest'); - }); - // Modal stays open and surfaces the rate-cap message via toast (sonner) — - // we don't render the Toaster here; just assert the fetch was called. - }); -}); From a5a0f26c01eb531ecc9b77b86783e03bc7b58b25 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:54:26 +0000 Subject: [PATCH 46/78] feat(api): needs filled by members, details links, and mark filled on accept MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fill takes filledBySlugs (members only, else 422 not_a_member) and keepOpen; it never adds anyone to the project. Reopen clears the list. - detailsUrl on post and edit, https only. Editing is project-admin or staff. - Each role carries viewer {state, appliedForThis} and projectHasActiveAdmin so a card can pick its button; interestCount is gone. - POST …/express-interest answers 410. - Accept takes fillRoleIds: open needs the application picked, filled in the accept commit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/src/plugins/services.ts | 2 +- apps/api/src/routes/projects-applications.ts | 2 +- apps/api/src/routes/projects-help-wanted.ts | 119 ++--------- apps/api/src/services/help-wanted.ts | 87 +++++--- apps/api/src/services/help-wanted.write.ts | 201 +++++++----------- apps/api/src/services/permissions.ts | 24 +-- apps/api/src/services/project-application.ts | 19 +- .../src/services/serializers/help-wanted.ts | 18 +- apps/api/tests/needs.test.ts | 154 ++++++++++++++ apps/api/tests/write-api.test.ts | 38 +--- 10 files changed, 354 insertions(+), 310 deletions(-) create mode 100644 apps/api/tests/needs.test.ts diff --git a/apps/api/src/plugins/services.ts b/apps/api/src/plugins/services.ts index d5bf713f..b37a5bdc 100644 --- a/apps/api/src/plugins/services.ts +++ b/apps/api/src/plugins/services.ts @@ -146,7 +146,7 @@ async function servicesPlugin(fastify: FastifyInstance): Promise<void> { projectUpdates: new ProjectUpdateService(state), projectBuzz: new ProjectBuzzService(state), blogPosts: new BlogPostService(state), - helpWanted: new HelpWantedService(state, fts), + helpWanted: new HelpWantedService(state, fts, fastify.store.private), events: new EventService(state), eventSeries: new EventSeriesService(state), eventsWrite: new EventWriteService(state), diff --git a/apps/api/src/routes/projects-applications.ts b/apps/api/src/routes/projects-applications.ts index 255e720e..06a751d2 100644 --- a/apps/api/src/routes/projects-applications.ts +++ b/apps/api/src/routes/projects-applications.ts @@ -148,7 +148,7 @@ export async function projectApplicationRoutes(fastify: FastifyInstance): Promis }, }, async (request) => { const { slug, personSlug } = request.params as { slug: string; personSlug: string }; - const body = (request.body ?? {}) as { role?: string | null; isAdmin?: boolean }; + const body = (request.body ?? {}) as { role?: string | null; isAdmin?: boolean; fillRoleIds?: string[] }; const result = await fastify.store.transact( buildTransactionOptions({ request, diff --git a/apps/api/src/routes/projects-help-wanted.ts b/apps/api/src/routes/projects-help-wanted.ts index a07113da..ca673130 100644 --- a/apps/api/src/routes/projects-help-wanted.ts +++ b/apps/api/src/routes/projects-help-wanted.ts @@ -4,20 +4,17 @@ * GET /api/help-wanted (global browse) * POST /api/projects/:slug/help-wanted * PATCH /api/projects/:slug/help-wanted/:roleId - * POST /api/projects/:slug/help-wanted/:roleId/express-interest + * POST /api/projects/:slug/help-wanted/:roleId/express-interest (410: removed) * POST /api/projects/:slug/help-wanted/:roleId/fill * POST /api/projects/:slug/help-wanted/:roleId/close * POST /api/projects/:slug/help-wanted/:roleId/reopen */ import type { FastifyInstance } from 'fastify'; import { ok, paginated } from '../lib/response.js'; -import { ApiNotFoundError, ApiValidationError } from '../lib/errors.js'; +import { ApiNotFoundError, ApiValidationError, GoneError } from '../lib/errors.js'; import { getCallerSession } from '../services/permissions.js'; import { buildTransactionOptions } from '../store/commit-meta.js'; -import { interestKey, projectBySlug } from '../store/memory/state.js'; -import { computeHelpWantedPermissions } from '../services/permissions.js'; -import { serializeHelpWantedRole } from '../services/serializers/help-wanted.js'; -import type { HelpWantedRole, ProjectMembership } from '@cfp/shared/schemas'; +import type { HelpWantedRole } from '@cfp/shared/schemas'; export async function helpWantedRoutes(fastify: FastifyInstance): Promise<void> { // GET /api/projects/:slug/help-wanted @@ -56,7 +53,7 @@ export async function helpWantedRoutes(fastify: FastifyInstance): Promise<void> perPage: q['perPage'] as number | undefined, }; - const result = fastify.services.helpWanted.listForProject(slug, opts, caller); + const result = await fastify.services.helpWanted.listForProject(slug, opts, caller); if ('error' in result) { if (result.error === 'not_found') throw new ApiNotFoundError(`Project '${slug}' not found`); @@ -114,7 +111,7 @@ export async function helpWantedRoutes(fastify: FastifyInstance): Promise<void> perPage: q['perPage'] as number | undefined, }; - const result = fastify.services.helpWanted.globalBrowse(opts, caller); + const result = await fastify.services.helpWanted.globalBrowse(opts, caller); if ('error' in result) { if (result.error === 'invalid_sort') { @@ -145,40 +142,9 @@ export async function helpWantedRoutes(fastify: FastifyInstance): Promise<void> }, ); - function serializeRoleResponse(role: HelpWantedRole, request: Parameters<typeof getCallerSession>[0]) { - const project = projectBySlug(fastify.inMemoryState, role.projectSlug)!; - const memberships = [...(fastify.inMemoryState.membershipsByProject.get(role.projectSlug) ?? [])] - .map((id) => fastify.inMemoryState.projectMemberships.get(id)) - .filter((m): m is ProjectMembership => m !== undefined); - const postedBy = fastify.inMemoryState.people.get(role.postedById) ?? null; - const filledBy = role.filledById - ? (fastify.inMemoryState.people.get(role.filledById) ?? null) - : null; - const tagAssignments = [...(fastify.inMemoryState.tagAssignmentsByTaggable.get(role.id) ?? [])] - .map((id) => fastify.inMemoryState.tagAssignments.get(id)) - .filter((ta): ta is NonNullable<typeof ta> => ta !== undefined); - const caller = getCallerSession(request); - const interestCount = fastify.inMemoryState.interestByRole.get(role.id)?.size ?? 0; - const alreadyExpressed = caller - ? fastify.inMemoryState.interestByRoleAndPerson.has(interestKey(role.id, caller.slug)) - : false; - const permissions = computeHelpWantedPermissions( - caller, - role, - project, - memberships, - alreadyExpressed, - ); - return serializeHelpWantedRole(role, { - project, - postedBy, - filledBy, - tagAssignments, - allTags: fastify.inMemoryState.tags, - interestCount, - permissions, - }); - } + const serializeRoleResponse = (role: HelpWantedRole, request: Parameters<typeof getCallerSession>[0]) => + fastify.services.helpWanted.serializeOne(role, getCallerSession(request)); + // POST /api/projects/:slug/help-wanted fastify.post('/api/projects/:slug/help-wanted', { @@ -215,7 +181,7 @@ export async function helpWantedRoutes(fastify: FastifyInstance): Promise<void> }) .catch((err: unknown) => fastify.log.error({ err }, 'follower email for need failed')); reply.code(201); - return ok(serializeRoleResponse(result.value.role, request)); + return ok(await serializeRoleResponse(result.value.role, request)); }); // PATCH /api/projects/:slug/help-wanted/:roleId @@ -247,54 +213,25 @@ export async function helpWantedRoutes(fastify: FastifyInstance): Promise<void> fastify.services.helpWantedWrite.update(tx, slug, roleId, body, request.session), ); result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); - return ok(serializeRoleResponse(result.value.role, request)); + return ok(await serializeRoleResponse(result.value.role, request)); }); - // POST /api/projects/:slug/help-wanted/:roleId/express-interest + // POST /api/projects/:slug/help-wanted/:roleId/express-interest — removed: + // a person interested in a need applies to the project with it selected + // (specs/api/projects-help-wanted.md). Answers 410 for one release; remove + // this handler in the release after next, so the path 404s. fastify.post('/api/projects/:slug/help-wanted/:roleId/express-interest', { schema: { tags: ['help-wanted'], - summary: 'Express interest in a role', + summary: 'Removed: apply to the project with this need selected', params: { type: 'object', properties: { slug: { type: 'string' }, roleId: { type: 'string' } }, required: ['slug', 'roleId'], }, - body: { type: 'object' }, }, - }, async (request, reply) => { - const { slug, roleId } = request.params as { slug: string; roleId: string }; - const body = (request.body ?? {}) as { message?: string | null }; - const result = await fastify.store.transact( - buildTransactionOptions({ - request, - action: 'help-wanted.express-interest', - subjectType: 'help-wanted-role', - subjectSlug: `${slug}/${roleId}`, - responseCode: 202, - }), - async (tx) => - fastify.services.helpWantedWrite.expressInterest(tx, slug, roleId, body, request.session), - ); - result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); - - // Fire notification AFTER commit. Failures here log but do not fail. - void fastify.notifier - .notifyHelpWantedInterest({ - maintainerEmail: null, - maintainerSlackHandle: result.value.poster?.slackHandle ?? null, - roleTitle: result.value.role.title, - projectTitle: result.value.project.title, - projectSlug: result.value.project.slug, - roleId: result.value.role.id, - interestedPersonFullName: request.session.person!.fullName, - interestedPersonSlug: request.session.person!.slug, - message: result.value.expression.message ?? null, - }) - .catch((err) => request.log.warn({ err }, 'help-wanted interest notification failed')); - - reply.code(202); - return ok({ delivered: true }); + }, async () => { + throw new GoneError('Express interest is gone: apply to the project with this need selected'); }); // POST /api/projects/:slug/help-wanted/:roleId/fill @@ -311,7 +248,7 @@ export async function helpWantedRoutes(fastify: FastifyInstance): Promise<void> }, }, async (request) => { const { slug, roleId } = request.params as { slug: string; roleId: string }; - const body = (request.body ?? {}) as { filledBySlug?: string | null }; + const body = (request.body ?? {}) as { filledBySlugs?: string[]; keepOpen?: boolean }; const result = await fastify.store.transact( buildTransactionOptions({ request, @@ -319,25 +256,13 @@ export async function helpWantedRoutes(fastify: FastifyInstance): Promise<void> subjectType: 'help-wanted-role', subjectSlug: `${slug}/${roleId}`, responseCode: 200, - ...(body.filledBySlug - ? { extraTrailers: { 'Filled-By-Slug': body.filledBySlug } } - : {}), + ...(body.filledBySlugs?.length ? { extraTrailers: { 'Filled-By-Slugs': body.filledBySlugs.join(', ') } } : {}), }), async (tx) => fastify.services.helpWantedWrite.fill(tx, slug, roleId, body, request.session), ); result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); - void fastify.notifier - .notifyHelpWantedFilled({ - maintainerEmail: null, - roleTitle: result.value.role.title, - projectTitle: result.value.project.title, - filledByFullName: result.value.filledBy?.fullName ?? null, - filledBySlug: result.value.filledBy?.slug ?? null, - }) - .catch((err) => request.log.warn({ err }, 'help-wanted filled notification failed')); - - return ok(serializeRoleResponse(result.value.role, request)); + return ok(await serializeRoleResponse(result.value.role, request)); }); // POST /api/projects/:slug/help-wanted/:roleId/close @@ -364,7 +289,7 @@ export async function helpWantedRoutes(fastify: FastifyInstance): Promise<void> async (tx) => fastify.services.helpWantedWrite.close(tx, slug, roleId, request.session), ); result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); - return ok(serializeRoleResponse(result.value.role, request)); + return ok(await serializeRoleResponse(result.value.role, request)); }); // POST /api/projects/:slug/help-wanted/:roleId/reopen @@ -391,7 +316,7 @@ export async function helpWantedRoutes(fastify: FastifyInstance): Promise<void> async (tx) => fastify.services.helpWantedWrite.reopen(tx, slug, roleId, request.session), ); result.value.stateApply.apply(fastify.inMemoryState, fastify.fts); - return ok(serializeRoleResponse(result.value.role, request)); + return ok(await serializeRoleResponse(result.value.role, request)); }); // Silence unused imports — they're used elsewhere when validation failures are diff --git a/apps/api/src/services/help-wanted.ts b/apps/api/src/services/help-wanted.ts index 2a0d430b..76722717 100644 --- a/apps/api/src/services/help-wanted.ts +++ b/apps/api/src/services/help-wanted.ts @@ -2,7 +2,11 @@ * HelpWantedService — read operations. */ import type { HelpWantedRole, Project, ProjectMembership } from '@cfp/shared/schemas'; -import { interestKey, projectBySlug, type InMemoryState } from '../store/memory/state.js'; +import { projectBySlug, type InMemoryState } from '../store/memory/state.js'; +import type { PrivateStore } from '../store/private/interface.js'; +import { isAgentAccount } from '../auth/agent-grant.js'; +import { hasActiveAdmin } from './memberships.js'; +import { reapplyAfter } from './project-application.js'; import type { FtsEngine } from '../store/fts.js'; import type { CallerSession } from './permissions.js'; import { computeHelpWantedPermissions } from './permissions.js'; @@ -50,17 +54,34 @@ function parseSortSpec( export class HelpWantedService { readonly #state: InMemoryState; readonly #fts: FtsEngine; + readonly #privateStore: PrivateStore | undefined; - constructor(state: InMemoryState, fts: FtsEngine) { + constructor(state: InMemoryState, fts: FtsEngine, privateStore?: PrivateStore) { this.#state = state; this.#fts = fts; + this.#privateStore = privateStore; } - listForProject( + /** One role in the response shape for this caller. */ + async serializeOne(role: HelpWantedRole, caller?: CallerSession): Promise<HelpWantedRoleResponse> { + const project = projectBySlug(this.#state, role.projectSlug)!; + return this.#serializeRole(role, project, this.#getMemberships(project.slug), caller, new Map()); + } + + async #activeAdmin(projectSlug: string, cache: Map<string, boolean>): Promise<boolean> { + let v = cache.get(projectSlug); + if (v === undefined) { + v = this.#privateStore ? await hasActiveAdmin(this.#state, this.#privateStore, projectSlug) : false; + cache.set(projectSlug, v); + } + return v; + } + + async listForProject( projectSlug: string, opts: ProjectHelpWantedListOptions, caller?: CallerSession, - ): { items: HelpWantedRoleResponse[]; totalItems: number } | { error: 'not_found' | 'invalid_sort' | 'invalid_filter' } { + ): Promise<{ items: HelpWantedRoleResponse[]; totalItems: number } | { error: 'not_found' | 'invalid_sort' | 'invalid_filter' }> { const sortSpec = parseSortSpec(opts.sort ?? '-createdAt', PROJECT_HELP_ALLOWED_SORT); if (!sortSpec) return { error: 'invalid_sort' }; @@ -99,15 +120,17 @@ export class HelpWantedService { const slice = roles.slice((page - 1) * perPage, page * perPage); const memberships = this.#getMemberships(project.slug); - const items = slice.map((role) => this.#serializeRole(role, project, memberships, caller)); + const cache = new Map<string, boolean>(); + const items: HelpWantedRoleResponse[] = []; + for (const role of slice) items.push(await this.#serializeRole(role, project, memberships, caller, cache)); return { items, totalItems }; } - globalBrowse( + async globalBrowse( opts: GlobalHelpWantedOptions, caller?: CallerSession, - ): { items: HelpWantedRoleResponse[]; totalItems: number; facets: { byTech: Array<{ tag: string; count: number }>; byTopic: Array<{ tag: string; count: number }> } } | { error: 'invalid_sort' | 'invalid_filter' } { + ): Promise<{ items: HelpWantedRoleResponse[]; totalItems: number; facets: { byTech: Array<{ tag: string; count: number }>; byTopic: Array<{ tag: string; count: number }> } } | { error: 'invalid_sort' | 'invalid_filter' }> { const sortSpec = parseSortSpec(opts.sort ?? '-createdAt', GLOBAL_HELP_ALLOWED_SORT); if (!sortSpec) return { error: 'invalid_sort' }; @@ -181,41 +204,46 @@ export class HelpWantedService { const perPage = Math.min(100, Math.max(1, opts.perPage ?? 30)); const slice = roles.slice((page - 1) * perPage, page * perPage); - const items = slice.map((role) => { + const cache = new Map<string, boolean>(); + const items: HelpWantedRoleResponse[] = []; + for (const role of slice) { const project = projectBySlug(this.#state, role.projectSlug)!; - const memberships = this.#getMemberships(role.projectSlug); - return this.#serializeRole(role, project, memberships, caller); - }); + items.push(await this.#serializeRole(role, project, this.#getMemberships(role.projectSlug), caller, cache)); + } return { items, totalItems, facets }; } - #serializeRole( + async #serializeRole( role: HelpWantedRole, project: Project, memberships: ProjectMembership[], - caller?: CallerSession, - ): HelpWantedRoleResponse { + caller: CallerSession | undefined, + activeAdminCache: Map<string, boolean>, + ): Promise<HelpWantedRoleResponse> { const postedBy = this.#state.people.get(role.postedById) ?? null; - const filledBy = role.filledById ? (this.#state.people.get(role.filledById) ?? null) : null; - - const interestCount = this.#state.interestByRole.get(role.id)?.size ?? 0; - - const alreadyExpressedInterest = caller - ? this.#state.interestByRoleAndPerson.has(interestKey(role.id, caller.slug)) - : false; + const filledBy = role.filledByIds + .map((id) => this.#state.people.get(id)) + .filter((p): p is NonNullable<typeof p> => p !== undefined); const tagAssignments = [...(this.#state.tagAssignmentsByTaggable.get(role.id) ?? [])] .map((taId) => this.#state.tagAssignments.get(taId)) .filter((ta): ta is NonNullable<typeof ta> => ta !== undefined); - const permissions = computeHelpWantedPermissions( - caller, - role, - project, - memberships, - alreadyExpressedInterest, - ); + const activeAdmin = await this.#activeAdmin(project.slug, activeAdminCache); + const own = caller ? memberships.find((m) => m.personSlug === caller.slug) : undefined; + const permissions = computeHelpWantedPermissions(caller, role, project, memberships, { + hasActiveAdmin: activeAdmin, + callerIsAgent: caller ? isAgentAccount(this.#state, caller.slug) : false, + reapplyWaitRunning: reapplyAfter(own, new Date()) !== null, + }); + const viewer = caller + ? { + state: own?.state ?? null, + appliedForThis: + own?.state === 'applicant' && own.application?.status === 'open' && own.application.roleIds.includes(role.id), + } + : null; return serializeHelpWantedRole(role, { project, @@ -223,8 +251,9 @@ export class HelpWantedService { filledBy, tagAssignments, allTags: this.#state.tags, - interestCount, permissions, + viewer, + projectHasActiveAdmin: activeAdmin, }); } diff --git a/apps/api/src/services/help-wanted.write.ts b/apps/api/src/services/help-wanted.write.ts index f6d7885d..2fc7a8ce 100644 --- a/apps/api/src/services/help-wanted.write.ts +++ b/apps/api/src/services/help-wanted.write.ts @@ -1,31 +1,27 @@ /** - * Help-wanted role writes: - * - POST /api/projects/:slug/help-wanted (project-admin | staff) - * - PATCH /api/projects/:slug/help-wanted/:roleId (poster | project-admin | staff) - * - POST /api/projects/:slug/help-wanted/:roleId/express-interest (user, rate-cap) - * - POST /api/projects/:slug/help-wanted/:roleId/fill (project-admin | staff) - * - POST /api/projects/:slug/help-wanted/:roleId/close (project-admin | staff) - * - POST /api/projects/:slug/help-wanted/:roleId/reopen (project-admin | staff) + * Help-wanted role (need) writes, all project-admin | staff + * (specs/api/projects-help-wanted.md): + * - POST /api/projects/:slug/help-wanted + * - PATCH /api/projects/:slug/help-wanted/:roleId + * - POST /api/projects/:slug/help-wanted/:roleId/fill + * - POST /api/projects/:slug/help-wanted/:roleId/close + * - POST /api/projects/:slug/help-wanted/:roleId/reopen * - * Side effects per specs/behaviors/help-wanted-roles.md: - * - fill with attribution → adds the person as a project member if not yet - * (Notifier is invoked by the route after commit.) - * - express-interest → 30-day rate cap per (roleId, personSlug); notification - * fan-out happens after commit + * Filling names members only and never adds anyone to the project + * (specs/behaviors/help-wanted-roles.md → Side effects): the ways in are an + * accepted application, whose "mark filled" fills in the same commit, or an + * admin's add. */ import { uuidv7 } from 'uuidv7'; import { - HelpWantedInterestExpressionSchema, HelpWantedRoleSchema, - ProjectMembershipSchema, - type HelpWantedInterestExpression, type HelpWantedRole, type Person, type Project, type ProjectMembership, } from '@cfp/shared/schemas'; import type { DualStoreTx } from '../store/store.js'; -import { interestKey, type InMemoryState } from '../store/memory/state.js'; +import { personBySlug, type InMemoryState } from '../store/memory/state.js'; import { StateApply } from '../store/state-apply.js'; import { ApiNotFoundError, ApiValidationError, ConflictError } from '../lib/errors.js'; import { requireAuth } from '../auth/require.js'; @@ -33,7 +29,36 @@ import type { SessionContext } from '../auth/middleware.js'; import { applyTagsForEntity, type TagAssignmentInput, type TagNamespace } from './tag.write.js'; const MAX_DESCRIPTION = 4_000; -const INTEREST_RATE_CAP_MS = 30 * 24 * 60 * 60 * 1000; + +/** `detailsUrl`: an https URL, or null/absent. */ +function checkDetailsUrl(url: string | null | undefined): void { + if (url === undefined || url === null || url === '') return; + let ok = false; + try { + ok = new URL(url).protocol === 'https:'; + } catch { + ok = false; + } + if (!ok) throw new ApiValidationError('detailsUrl must be an https URL', { detailsUrl: 'invalid' }); +} + +/** + * Fill these needs with `person` (they must already be members), as part of + * another write: accepting an application with "mark filled". Returns the + * updated roles; the caller upserts them. + */ +export function filledWith(roles: readonly HelpWantedRole[], personId: string, now: string): HelpWantedRole[] { + return roles.map((role) => + HelpWantedRoleSchema.parse({ + ...role, + status: 'filled', + filledByIds: [...new Set([...role.filledByIds, personId])], + filledAt: now, + closedAt: null, + updatedAt: now, + }), + ); +} function nowIso(): string { return new Date().toISOString(); @@ -53,12 +78,14 @@ export class HelpWantedWriteService { title: string; description: string; commitmentHoursPerWeek?: number | null; + detailsUrl?: string | null; tags?: { topic?: string[]; tech?: string[]; event?: string[] }; }, session: SessionContext, ): Promise<{ role: HelpWantedRole; stateApply: StateApply }> { const { project, memberships } = this.#projectOrThrow(projectSlug); requireAuth('project-admin | staff', { session, project, memberships }); + checkDetailsUrl(input.detailsUrl); if (!input.title || input.title.length < 1 || input.title.length > 120) { throw new ApiValidationError('title required, 1-120 chars', { title: 'required' }); @@ -90,7 +117,9 @@ export class HelpWantedWriteService { title: input.title, description: input.description, commitmentHoursPerWeek: input.commitmentHoursPerWeek ?? null, + detailsUrl: input.detailsUrl || null, status: 'open', + filledByIds: [], createdAt: now, updatedAt: now, }); @@ -123,20 +152,16 @@ export class HelpWantedWriteService { title?: string; description?: string; commitmentHoursPerWeek?: number | null; + detailsUrl?: string | null; tags?: { topic?: string[]; tech?: string[]; event?: string[] }; }, session: SessionContext, ): Promise<{ role: HelpWantedRole; stateApply: StateApply }> { const { project, memberships } = this.#projectOrThrow(projectSlug); const existing = this.#roleOrThrow(project.slug, roleId); - - // Poster, project maintainer, or staff can edit. Use a two-step check: - // first try maintainer | staff, fall back to a per-poster check. - if (session.person?.id !== existing.postedById) { - requireAuth('project-admin | staff', { session, project, memberships }); - } else { - requireAuth('user', { session }); - } + // A poster who is no longer an admin can no longer edit their role. + requireAuth('project-admin | staff', { session, project, memberships }); + checkDetailsUrl(input.detailsUrl); if (input.title !== undefined && (input.title.length < 1 || input.title.length > 120)) { throw new ApiValidationError('title 1-120 chars', { title: 'invalid' }); @@ -158,6 +183,7 @@ export class HelpWantedWriteService { input.commitmentHoursPerWeek === undefined ? (existing.commitmentHoursPerWeek ?? null) : input.commitmentHoursPerWeek, + detailsUrl: input.detailsUrl === undefined ? (existing.detailsUrl ?? null) : input.detailsUrl || null, updatedAt: nowIso(), }); @@ -185,127 +211,46 @@ export class HelpWantedWriteService { return { role: updated, stateApply }; } - async expressInterest( - tx: DualStoreTx, - projectSlug: string, - roleId: string, - input: { message?: string | null }, - session: SessionContext, - ): Promise<{ - role: HelpWantedRole; - project: Project; - poster: Person | null; - expression: HelpWantedInterestExpression; - stateApply: StateApply; - }> { - requireAuth('user', { session }); - const { project } = this.#projectOrThrow(projectSlug); - const role = this.#roleOrThrow(project.slug, roleId); - - if (role.status !== 'open') { - throw new ConflictError('Role is not open', 'role_not_open'); - } - - // 30-day rate cap per (roleId, personSlug) - const existingId = this.#state.interestByRoleAndPerson.get( - interestKey(role.id, session.person!.slug), - ); - if (existingId) { - const existing = this.#state.helpWantedInterest.get(existingId); - if (existing) { - const elapsed = Date.now() - new Date(existing.createdAt).getTime(); - if (elapsed < INTEREST_RATE_CAP_MS) { - throw new ConflictError( - 'You already expressed interest in this role recently', - 'already_expressed', - ); - } - } - } - - if (input.message !== undefined && input.message !== null && input.message.length > 2_000) { - throw new ApiValidationError('message <= 2000 chars', { message: 'too_long' }); - } - - const now = nowIso(); - const expression: HelpWantedInterestExpression = HelpWantedInterestExpressionSchema.parse({ - id: uuidv7(), - roleId: role.id, - personSlug: session.person!.slug, - message: input.message ?? null, - createdAt: now, - }); - - await tx.public['help-wanted-interest'].upsert(expression); - - const stateApply = new StateApply().upsertInterest(expression); - const poster = this.#state.people.get(role.postedById) ?? null; - - return { role, project, poster, expression, stateApply }; - } - + /** + * fill — names zero or more members in `filledByIds`; unless `keepOpen`, + * the need moves to `filled`. Never creates a membership. + */ async fill( tx: DualStoreTx, projectSlug: string, roleId: string, - input: { filledBySlug?: string | null }, + input: { filledBySlugs?: string[]; keepOpen?: boolean }, session: SessionContext, - ): Promise<{ - role: HelpWantedRole; - project: Project; - filledBy: Person | null; - poster: Person | null; - stateApply: StateApply; - }> { + ): Promise<{ role: HelpWantedRole; project: Project; filledBy: Person[]; stateApply: StateApply }> { const { project, memberships } = this.#projectOrThrow(projectSlug); const role = this.#roleOrThrow(project.slug, roleId); requireAuth('project-admin | staff', { session, project, memberships }); - let filledBy: Person | null = null; - if (input.filledBySlug) { - const personId = this.#state.personIdBySlug.get(input.filledBySlug); - if (!personId) { - throw new ApiNotFoundError(`Person '${input.filledBySlug}' not found`); + const filledBy: Person[] = []; + for (const slug of [...new Set(input.filledBySlugs ?? [])]) { + const person = personBySlug(this.#state, slug); + const isMember = memberships.some((m) => m.personSlug === slug && m.state === 'member'); + if (!person || person.deletedAt || !isMember) { + throw new ApiValidationError( + `'${slug}' is not a member of this project; add them or accept their application first`, + { filledBySlugs: 'not_a_member' }, + 'not_a_member', + ); } - filledBy = this.#state.people.get(personId) ?? null; - if (!filledBy) throw new ApiNotFoundError(`Person '${input.filledBySlug}' not found`); + filledBy.push(person); } const now = nowIso(); + const keepOpen = input.keepOpen === true; const updated: HelpWantedRole = HelpWantedRoleSchema.parse({ ...role, - status: 'filled', - filledAt: now, - filledById: filledBy?.id ?? null, - closedAt: null, + filledByIds: [...new Set([...(keepOpen ? role.filledByIds : []), ...filledBy.map((p) => p.id)])], + ...(keepOpen ? {} : { status: 'filled', filledAt: now, closedAt: null }), updatedAt: now, }); await tx.public['help-wanted-roles'].upsert(updated); - - const stateApply = new StateApply().upsertHelpWantedRole(updated); - - // Membership side-effect - if (filledBy && !memberships.some((m) => m.personSlug === filledBy!.slug)) { - // Replaced by members-only fills in plans/needs-on-applications.md. - const membership: ProjectMembership = ProjectMembershipSchema.parse({ - id: uuidv7(), - projectSlug: project.slug, - personSlug: filledBy.slug, - state: 'member', - role: `Help-wanted: ${role.title}`, - via: 'added', - followedAt: now, - joinedAt: now, - createdAt: now, - updatedAt: now, - }); - await tx.public['project-memberships'].upsert(membership); - stateApply.upsertMembership(membership); - } - - const poster = this.#state.people.get(role.postedById) ?? null; - return { role: updated, project, filledBy, poster, stateApply }; + return { role: updated, project, filledBy, stateApply: new StateApply().upsertHelpWantedRole(updated) }; } async close( @@ -346,7 +291,7 @@ export class HelpWantedWriteService { ...role, status: 'open', filledAt: null, - filledById: null, + filledByIds: [], closedAt: null, updatedAt: nowIso(), }); diff --git a/apps/api/src/services/permissions.ts b/apps/api/src/services/permissions.ts index aea7767d..aca04d74 100644 --- a/apps/api/src/services/permissions.ts +++ b/apps/api/src/services/permissions.ts @@ -66,8 +66,8 @@ export interface BuzzPermissions { export interface HelpWantedPermissions { readonly canEdit: boolean; - readonly canExpressInterest: boolean; - readonly alreadyExpressedInterest: boolean; + /** The caller may apply to the project now, and the role is open. */ + readonly canApply: boolean; readonly canFill: boolean; readonly canClose: boolean; } @@ -224,19 +224,17 @@ export function computeHelpWantedPermissions( caller: CallerSession | undefined, role: HelpWantedRole, project: Project, - memberships: ProjectMembership[], - alreadyExpressedInterest: boolean, + memberships: readonly ProjectMembership[], + ctx: ProjectPermissionContext = {}, ): HelpWantedPermissions { const staff = isStaff(caller); - const maintainer = isProjectAdminOf(caller, project, memberships); - const isPoster = caller !== undefined && caller.id === role.postedById; - const authenticated = caller !== undefined; - + const admin = isProjectAdminOf(caller, project, memberships); + const projectPerms = computeProjectPermissions(caller, project, memberships, ctx); return { - canEdit: isPoster || maintainer || staff, - canExpressInterest: authenticated && role.status === 'open' && !alreadyExpressedInterest, - alreadyExpressedInterest, - canFill: maintainer || staff, - canClose: maintainer || staff, + // A poster who is no longer an admin can no longer edit their role. + canEdit: admin || staff, + canApply: projectPerms.canApply && role.status === 'open', + canFill: admin || staff, + canClose: admin || staff, }; } diff --git a/apps/api/src/services/project-application.ts b/apps/api/src/services/project-application.ts index ca47541c..e79ae265 100644 --- a/apps/api/src/services/project-application.ts +++ b/apps/api/src/services/project-application.ts @@ -28,6 +28,7 @@ import { StateApply } from '../store/state-apply.js'; import type { DualStoreTx } from '../store/store.js'; import { hasActiveAdmin, membershipOf, membershipsOfPerson, membershipsOfProject } from './memberships.js'; import { asFollower, checkRole, refuseAgent } from './project-membership.write.js'; +import { filledWith } from './help-wanted.write.js'; import { serializePersonAvatar, type PersonAvatar } from './serializers/common.js'; const HOUR = 60 * 60 * 1000; @@ -351,7 +352,7 @@ export class ProjectApplicationService { tx: DualStoreTx, projectSlug: string, personSlug: string, - input: { role?: string | null; isAdmin?: boolean }, + input: { role?: string | null; isAdmin?: boolean; fillRoleIds?: string[] }, session: SessionContext, now: Date = new Date(), ): Promise<DecideResult> { @@ -359,6 +360,14 @@ export class ProjectApplicationService { checkRole(input.role); if (input.isAdmin === true) refuseAgent(this.#state, applicant); const app = existing.application!; + // "Mark filled": a subset of the needs this application picked that are still open. + const toFill = [...new Set(input.fillRoleIds ?? [])].map((id) => { + const role = this.#state.helpWantedRoles.get(id); + if (!role || !app.roleIds.includes(id) || role.projectSlug !== project.slug || role.status !== 'open') { + throw new ApiValidationError('fillRoleIds must be open needs this application picked', { fillRoleIds: 'invalid' }); + } + return role; + }); const firstNeed = app.roleIds.length > 0 ? this.#state.helpWantedRoles.get(app.roleIds[0]!) : undefined; const role = input.role === undefined ? (firstNeed?.title ?? null) : input.role; const at = iso(now); @@ -374,7 +383,13 @@ export class ProjectApplicationService { updatedAt: at, }); await tx.public['project-memberships'].upsert(membership); - return { membership, stateApply: new StateApply().upsertMembership(membership), project, applicant }; + const stateApply = new StateApply().upsertMembership(membership); + // The fills ride in the same commit as the accept. + for (const role of filledWith(toFill, applicant.id, at)) { + await tx.public['help-wanted-roles'].upsert(role); + stateApply.upsertHelpWantedRole(role); + } + return { membership, stateApply, project, applicant }; } /** close by an admin ("Close application") — applicant → follower, `closedBy = admin`. */ diff --git a/apps/api/src/services/serializers/help-wanted.ts b/apps/api/src/services/serializers/help-wanted.ts index a06c9cb6..6734cba8 100644 --- a/apps/api/src/services/serializers/help-wanted.ts +++ b/apps/api/src/services/serializers/help-wanted.ts @@ -14,12 +14,15 @@ export interface HelpWantedRoleResponse { readonly descriptionHtml: string; readonly commitmentHoursPerWeek: number | null; readonly status: string; - readonly filledBy: PersonAvatar | null; + readonly detailsUrl: string | null; + readonly filledBy: PersonAvatar[]; readonly filledAt: string | null; readonly closedAt: string | null; readonly tags: { topic: TagItem[]; tech: TagItem[] }; - readonly interestCount: number; readonly permissions: HelpWantedPermissions; + /** The caller's standing on the project, for the card's button; null when signed out. */ + readonly viewer: { readonly state: 'follower' | 'applicant' | 'member' | null; readonly appliedForThis: boolean } | null; + readonly projectHasActiveAdmin: boolean; readonly createdAt: string; readonly updatedAt: string; } @@ -29,11 +32,12 @@ export function serializeHelpWantedRole( opts: { project: Project; postedBy: Person | null; - filledBy: Person | null; + filledBy: Person[]; tagAssignments: TagAssignment[]; allTags: Map<string, Tag>; - interestCount: number; permissions: HelpWantedPermissions; + viewer: HelpWantedRoleResponse['viewer']; + projectHasActiveAdmin: boolean; }, ): HelpWantedRoleResponse { const roleTags = opts.tagAssignments @@ -52,12 +56,14 @@ export function serializeHelpWantedRole( descriptionHtml: renderMarkdown(role.description).html, commitmentHoursPerWeek: role.commitmentHoursPerWeek ?? null, status: role.status, - filledBy: serializePersonAvatar(opts.filledBy), + detailsUrl: role.detailsUrl ?? null, + filledBy: opts.filledBy.map(serializePersonAvatar).filter((a): a is PersonAvatar => a !== null), filledAt: role.filledAt ?? null, closedAt: role.closedAt ?? null, tags: { topic: tagsByNamespace.topic, tech: tagsByNamespace.tech }, - interestCount: opts.interestCount, permissions: opts.permissions, + viewer: opts.viewer, + projectHasActiveAdmin: opts.projectHasActiveAdmin, createdAt: role.createdAt, updatedAt: role.updatedAt, }; diff --git a/apps/api/tests/needs.test.ts b/apps/api/tests/needs.test.ts new file mode 100644 index 00000000..d9d88dbb --- /dev/null +++ b/apps/api/tests/needs.test.ts @@ -0,0 +1,154 @@ +/** + * Needs on applications (plans/needs-on-applications.md): fills by several + * members that never add anyone, "mark filled" on accept in the same commit, + * detailsUrl, the role shape's caller state, and express-interest retired. + * + * Every person here is invented; addresses are example.org. + */ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { + fid, + minutesAgo, + personRecord, + privateProfile, + startAgentTestEnv, + type AgentTestEnv, + type Rec, +} from './helpers/agent-fixtures.js'; + +const P = { ada: 1, ben: 2, cal: 3, dee: 4, eve: 5, poe: 6 }; +const R = { a: fid(300), b: fid(301), c: fid(302), other: fid(303) }; +const T = '2026-05-01T00:00:00.000Z'; +const RECENT = minutesAgo(60); + +const rec = (n: number, person: string, state: string, over: Rec = {}): Rec => ({ + id: fid(100 + n), projectSlug: 'proj', personSlug: person, state, isAdmin: false, muted: false, + followedAt: T, createdAt: T, updatedAt: T, ...(state === 'member' ? { via: 'legacy', joinedAt: T } : {}), ...over, +}); +const role = (id: string, title: string, over: Rec = {}): Rec => ({ + id, projectSlug: 'proj', postedById: fid(P.poe), title, description: `${title} work.`, status: 'open', + filledByIds: [], createdAt: T, updatedAt: T, ...over, +}); + +describe('needs', () => { + let env: AgentTestEnv; + beforeEach(async () => { + env = await startAgentTestEnv({ + records: { + people: Object.entries(P).map(([slug, k]) => personRecord(k, slug)), + projects: [ + { id: fid(50), slug: 'proj', title: 'Proj', stage: 'testing', featured: false, createdAt: T, updatedAt: T }, + { id: fid(51), slug: 'other', title: 'Other', stage: 'testing', featured: false, createdAt: T, updatedAt: T }, + ], + 'project-memberships': [ + rec(1, 'ada', 'member', { isAdmin: true }), + rec(2, 'ben', 'member'), + rec(3, 'cal', 'member'), + rec(4, 'dee', 'applicant', { + application: { status: 'open', roleIds: [R.a, R.c], offer: 'Both, please.', submittedAt: RECENT, visibleAt: RECENT, notifiedAt: RECENT }, + }), + // poe posted the roles while an admin, and no longer is one. + rec(6, 'poe', 'member'), + ], + 'help-wanted-roles': [ + role(R.a, 'Frontend dev'), + role(R.b, 'Mapper'), + role(R.c, 'Old need', { status: 'closed', closedAt: T }), + { ...role(R.other, 'Elsewhere'), projectSlug: 'other' }, + ], + }, + profiles: [privateProfile(fid(P.ada), 'ada@example.org')], + }); + }); + afterEach(async () => { + await env.close(); + }); + + const call = async (who: number | null, method: 'GET' | 'POST' | 'PATCH', url: string, payload?: Rec) => + env.app.inject({ + method, + url, + ...(who !== null ? { cookies: { cfp_session: await env.cookie(who, 'user') } } : {}), + ...(payload !== undefined ? { payload } : {}), + }); + const roleOf = (id: string) => env.app.inMemoryState.helpWantedRoles.get(id)!; + const memberCount = () => [...env.app.inMemoryState.projectMemberships.values()].filter((m) => m.projectSlug === 'proj').length; + const errCode = (res: { json: () => unknown }) => (res.json() as { error: { code: string } }).error.code; + + it('fill with two members records both and sets filled; keepOpen keeps it open; nobody is added', async () => { + const before = memberCount(); + let res = await call(P.ada, 'POST', `/api/projects/proj/help-wanted/${R.b}/fill`, { filledBySlugs: ['ben', 'cal'], keepOpen: true }); + expect(res.statusCode, res.body).toBe(200); + expect(roleOf(R.b)).toMatchObject({ status: 'open', filledByIds: [fid(P.ben), fid(P.cal)] }); + expect(res.json<{ data: { filledBy: Array<{ slug: string }> } }>().data.filledBy.map((p) => p.slug)).toEqual(['ben', 'cal']); + + res = await call(P.ada, 'POST', `/api/projects/proj/help-wanted/${R.a}/fill`, { filledBySlugs: ['ben', 'cal'] }); + expect(res.statusCode, res.body).toBe(200); + expect(roleOf(R.a)).toMatchObject({ status: 'filled', filledByIds: [fid(P.ben), fid(P.cal)] }); + expect(memberCount()).toBe(before); + + res = await call(P.ada, 'POST', `/api/projects/proj/help-wanted/${R.a}/reopen`); + expect(roleOf(R.a)).toMatchObject({ status: 'open', filledByIds: [] }); + }); + + it('filling with a non-member is 422 not_a_member and adds no one', async () => { + const before = memberCount(); + for (const slug of ['eve', 'dee']) { + const res = await call(P.ada, 'POST', `/api/projects/proj/help-wanted/${R.b}/fill`, { filledBySlugs: [slug] }); + expect(res.statusCode).toBe(422); + expect(errCode(res)).toBe('not_a_member'); + } + expect(memberCount()).toBe(before); + expect(roleOf(R.b).status).toBe('open'); + }); + + it('accept with fillRoleIds fills those needs in the accept commit', async () => { + const res = await call(P.ada, 'POST', '/api/projects/proj/applications/dee/accept', { fillRoleIds: [R.a] }); + expect(res.statusCode, res.body).toBe(200); + expect(roleOf(R.a)).toMatchObject({ status: 'filled', filledByIds: [fid(P.dee)] }); + const files = await env.git('show', '--name-only', '--format=', 'HEAD'); + expect(files).toContain('project-memberships/proj/dee.toml'); + expect(files).toContain(`help-wanted-roles/proj/${R.a}.toml`); + }); + + it('accept refuses a fill the application did not pick, or that is not open (422)', async () => { + for (const ids of [[R.b], [R.c], [R.other]]) { + const res = await call(P.ada, 'POST', '/api/projects/proj/applications/dee/accept', { fillRoleIds: ids }); + expect(res.statusCode, JSON.stringify(ids)).toBe(422); + } + expect(env.app.inMemoryState.projectMemberships.get(fid(104))!.state).toBe('applicant'); + }); + + it('express-interest answers 410; no role carries interestCount; detailsUrl is kept', async () => { + expect((await call(P.eve, 'POST', `/api/projects/proj/help-wanted/${R.a}/express-interest`, {})).statusCode).toBe(410); + const posted = await call(P.ada, 'POST', '/api/projects/proj/help-wanted', { + title: 'Data cleanup', description: 'Tidy the stops.', detailsUrl: 'https://example.org/issues?q=data', + }); + expect(posted.statusCode, posted.body).toBe(201); + expect(posted.json<{ data: Rec }>().data['detailsUrl']).toBe('https://example.org/issues?q=data'); + const bad = await call(P.ada, 'POST', '/api/projects/proj/help-wanted', { title: 'X', description: 'Y', detailsUrl: 'http://example.org' }); + expect(bad.statusCode).toBe(422); + for (const url of ['/api/help-wanted', '/api/projects/proj/help-wanted', '/api/projects/proj']) { + expect((await call(P.eve, 'GET', url)).body).not.toContain('interestCount'); + } + }); + + it('a poster who is no longer an admin cannot edit their role', async () => { + expect((await call(P.poe, 'PATCH', `/api/projects/proj/help-wanted/${R.a}`, { title: 'Mine' })).statusCode).toBe(403); + expect((await call(P.ada, 'PATCH', `/api/projects/proj/help-wanted/${R.a}`, { detailsUrl: 'https://example.org/b' })).statusCode).toBe(200); + }); + + it('each role says enough about the caller to pick the card button', async () => { + const card = async (who: number | null) => + (await call(who, 'GET', '/api/help-wanted')).json<{ data: Array<{ id: string; viewer: Rec | null; permissions: Rec; projectHasActiveAdmin: boolean }> }>() + .data.find((r) => r.id === R.a)!; + expect(await card(null)).toMatchObject({ viewer: null, projectHasActiveAdmin: true, permissions: { canApply: false } }); + expect(await card(P.eve)).toMatchObject({ viewer: { state: null, appliedForThis: false }, permissions: { canApply: true } }); + expect(await card(P.dee)).toMatchObject({ viewer: { state: 'applicant', appliedForThis: true }, permissions: { canApply: false } }); + expect(await card(P.ben)).toMatchObject({ viewer: { state: 'member', appliedForThis: false }, permissions: { canApply: false } }); + const elsewhere = (await call(P.eve, 'GET', '/api/help-wanted')).json<{ data: Array<{ id: string; projectHasActiveAdmin: boolean; permissions: Rec }> }>() + .data.find((r) => r.id === R.other)!; + expect(elsewhere).toMatchObject({ projectHasActiveAdmin: false, permissions: { canApply: false } }); + }); +}); diff --git a/apps/api/tests/write-api.test.ts b/apps/api/tests/write-api.test.ts index bb792a90..a2ded4f5 100644 --- a/apps/api/tests/write-api.test.ts +++ b/apps/api/tests/write-api.test.ts @@ -456,29 +456,7 @@ describe('Help-wanted', () => { expect(body.data.some((r) => r.title === 'iOS developer')).toBe(true); }); - it('express-interest enforces the 30-day rate cap', async () => { - const cookie = await userCookie(fixtures.personId); - const first = await app!.inject({ - method: 'POST', - url: `/api/projects/${fixtures.projectSlug}/help-wanted/${fixtures.helpWantedId}/express-interest`, - headers: { cookie, 'content-type': 'application/json' }, - payload: { message: 'interested' }, - }); - expect(first.statusCode).toBe(202); - - const dup = await app!.inject({ - method: 'POST', - url: `/api/projects/${fixtures.projectSlug}/help-wanted/${fixtures.helpWantedId}/express-interest`, - headers: { cookie, 'content-type': 'application/json' }, - payload: { message: 'still interested' }, - }); - expect(dup.statusCode).toBe(409); - expect(dup.json<{ error: { code: string } }>().error.code).toBe('already_expressed'); - }); - - it('fill with attribution creates a membership for filledBy', async () => { - // The fixture's person is already a member; use a different person isn't - // possible without an importer. Assert the no-attribution path here. + it('fill without attribution marks the role filled (fuller cases in needs.test.ts)', async () => { const cookie = await userCookie(fixtures.personId); const res = await app!.inject({ method: 'POST', @@ -487,27 +465,21 @@ describe('Help-wanted', () => { payload: {}, }); expect(res.statusCode).toBe(200); - const body = res.json<{ data: { status: string; filledBy: unknown | null } }>(); + const body = res.json<{ data: { status: string; filledBy: unknown[] } }>(); expect(body.data.status).toBe('filled'); }); - it('cannot express interest on a filled role', async () => { + it('express-interest is retired: 410 gone', async () => { const cookie = await userCookie(fixtures.personId); - await app!.inject({ - method: 'POST', - url: `/api/projects/${fixtures.projectSlug}/help-wanted/${fixtures.helpWantedId}/fill`, - headers: { cookie, 'content-type': 'application/json' }, - payload: {}, - }); const res = await app!.inject({ method: 'POST', url: `/api/projects/${fixtures.projectSlug}/help-wanted/${fixtures.helpWantedId}/express-interest`, headers: { cookie, 'content-type': 'application/json' }, payload: { message: 'hi' }, }); - expect(res.statusCode).toBe(409); - expect(res.json<{ error: { code: string } }>().error.code).toBe('role_not_open'); + expect(res.statusCode).toBe(410); }); + }); // --------------------------------------------------------------------------- From 7fb618b94d06df337becd25150ea0407179eac6b Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:54:26 +0000 Subject: [PATCH 47/78] feat(api): migration from filledById to filledByIds Rewrites help-wanted-roles to the v3 fill shape in one commit, idempotent, and counts help-wanted-interest records so the sheet is dropped only at 0. Run it while the sheet still declares v2, then adopt v3. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/package.json | 3 +- .../202611290100-help-wanted-fills.ts | 157 ++++++++++++++++++ .../tests/migration-help-wanted-fills.test.ts | 86 ++++++++++ 3 files changed, 245 insertions(+), 1 deletion(-) create mode 100644 apps/api/scripts/migrations/202611290100-help-wanted-fills.ts create mode 100644 apps/api/tests/migration-help-wanted-fills.test.ts diff --git a/apps/api/package.json b/apps/api/package.json index 5c198167..fa73636e 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -19,7 +19,8 @@ "script:prune-spam": "tsx scripts/prune-spam.ts", "check:sheet-configs": "tsx scripts/check-sheet-configs.ts", "script:migrate-slug-references": "tsx scripts/migrations/202610150400-slug-references.ts", - "script:migrate-project-admins": "tsx scripts/migrations/202611290000-project-admins.ts" + "script:migrate-project-admins": "tsx scripts/migrations/202611290000-project-admins.ts", + "script:migrate-help-wanted-fills": "tsx scripts/migrations/202611290100-help-wanted-fills.ts" }, "dependencies": { "@aws-sdk/client-s3": "^3.1048.0", diff --git a/apps/api/scripts/migrations/202611290100-help-wanted-fills.ts b/apps/api/scripts/migrations/202611290100-help-wanted-fills.ts new file mode 100644 index 00000000..add78886 --- /dev/null +++ b/apps/api/scripts/migrations/202611290100-help-wanted-fills.ts @@ -0,0 +1,157 @@ +/** + * Migration: needs are filled by several members (plans/needs-on-applications.md, + * specs/data-model.md → HelpWantedRole). + * + * help-wanted-roles filledById → filledByIds ([filledById], or [] when absent) + * + * It also counts `help-wanted-interest` records on the branch, without + * touching them: the retired sheet is dropped from the data repo by hand + * (its config and records), and only once this count is 0 — stop and ask if + * it is not (the plan's risk note). + * + * One tree write, one commit on `--branch`; a second run makes no commit. + * Prints counts only. Like 202611290000-project-admins, run it while the + * sheet still declares v2 (open for extension), then adopt v3. + * + * Usage: + * npm run -w apps/api script:migrate-help-wanted-fills -- \ + * --data-repo=/path/to/codeforphilly-data.git --branch=fixture [--dry-run] + */ +import { resolve } from 'node:path'; + +import { HelpWantedRoleSchema } from '@cfp/shared/schemas'; +import { openRepo } from 'gitsheets'; + +const AUTHOR = { name: 'Code for Philly API', email: 'api@users.noreply.codeforphilly.org' }; + +type Rec = Record<string, unknown>; + +export interface MigrateFillsOptions { + readonly dataRepo: string; + readonly branch: string; + readonly dryRun?: boolean; +} + +export interface MigrateFillsResult { + /** Roles rewritten (0 on a re-run). */ + readonly rolesMigrated: number; + /** Records in the retired help-wanted-interest sheet; it may be dropped only at 0. */ + readonly interestRecords: number; + readonly commitHash: string | null; +} + +interface TxSheet { + query(): AsyncIterable<Rec>; + upsert(record: Rec): Promise<unknown>; +} + +async function readAll(sheet: TxSheet): Promise<Rec[]> { + const out: Rec[] = []; + for await (const r of sheet.query()) out.push(Object.fromEntries(Object.entries(r))); + return out; +} + +/** One role in the v3 shape. Pure; a role already migrated comes back equal. */ +export function migrateRole(record: Rec): Rec { + const next: Rec = { ...record }; + const legacy = record['filledById']; + delete next['filledById']; + const ids = Array.isArray(record['filledByIds']) ? (record['filledByIds'] as unknown[]).filter((v) => typeof v === 'string') : []; + if (typeof legacy === 'string' && legacy !== '' && !ids.includes(legacy)) ids.push(legacy); + next['filledByIds'] = ids; + return next; +} + +export async function migrateHelpWantedFills(opts: MigrateFillsOptions): Promise<MigrateFillsResult> { + const repo = await openRepo({ gitDir: opts.dataRepo }); + const ref = `refs/heads/${opts.branch}`; + if ((await repo.resolveRef(ref)) === null) throw new Error(`branch '${opts.branch}' not found in ${opts.dataRepo}`); + + // Count the retired sheet's records straight from the tree: the sheet may + // already have no config, and this script never opens it for writing. + let interestRecords = 0; + const countUnder = async (dir: string): Promise<void> => { + for (const entry of (await repo.listTree(ref, dir)) ?? []) { + const path = `${dir}/${entry.name}`; + if (entry.type === 'tree') await countUnder(path); + else if (entry.name.endsWith('.toml')) interestRecords += 1; + } + }; + await countUnder('help-wanted-interest'); + + let rolesMigrated = 0; + let wrote = false; + const result = await repo.transact( + { + parent: ref, + branch: ref, + message: + 'migrate: needs are filled by several members\n\n' + + 'help-wanted-roles: filledById becomes filledByIds\n' + + '(codeforphilly-ng plans/needs-on-applications.md).\n', + author: AUTHOR, + trailers: { Action: 'migrate.help-wanted-fills' }, + }, + async (tx) => { + const sheet = tx.sheet('help-wanted-roles') as unknown as TxSheet; + const plan: Rec[] = []; + const problems: string[] = []; + for (const record of await readAll(sheet)) { + const next = migrateRole(record); + const parsed = HelpWantedRoleSchema.safeParse(next); + if (!parsed.success) { + problems.push(`help-wanted-roles/${String(record['projectSlug'])}/${String(record['id'])}: ${parsed.error.message}`); + continue; + } + if (JSON.stringify(next) !== JSON.stringify(record)) plan.push(next); + } + if (problems.length > 0) throw new Error(`${problems.length} role(s) would not be valid; nothing written:\n${problems.join('\n')}`); + rolesMigrated = plan.length; + if (opts.dryRun) return; + for (const next of plan) await sheet.upsert(next); + wrote = plan.length > 0; + }, + ); + return { rolesMigrated, interestRecords, commitHash: wrote ? result.commitHash : null }; +} + +function parseArgs(argv: readonly string[]): MigrateFillsOptions { + const opts: Record<string, string | true> = {}; + for (const a of argv) { + if (!a.startsWith('--')) continue; + const eq = a.indexOf('='); + if (eq === -1) opts[a.slice(2)] = true; + else opts[a.slice(2, eq)] = a.slice(eq + 1); + } + const dataRepo = + typeof opts['data-repo'] === 'string' && opts['data-repo'] !== '' ? opts['data-repo'] : process.env['CFP_DATA_REPO_PATH']; + if (!dataRepo) { + process.stderr.write('missing --data-repo=<path> (or set CFP_DATA_REPO_PATH)\n'); + process.exit(2); + } + const branch = opts['branch']; + if (typeof branch !== 'string' || branch === '') { + process.stderr.write('missing --branch=<name>\n'); + process.exit(2); + } + return { dataRepo: resolve(dataRepo), branch, dryRun: opts['dry-run'] === true }; +} + +async function main(): Promise<void> { + const args = parseArgs(process.argv.slice(2)); + console.log(`[migrate] ${args.dataRepo} ${args.branch}${args.dryRun ? ' (dry run)' : ''}`); + const r = await migrateHelpWantedFills(args); + console.log(` roles migrated ${r.rolesMigrated}`); + console.log(` help-wanted-interest records ${r.interestRecords}${r.interestRecords > 0 ? ' <- stop: do not drop the sheet' : ''}`); + if (args.dryRun) console.log('(dry run: nothing written)'); + else if (r.commitHash) console.log(`commit: ${r.commitHash} on ${args.branch}`); + else console.log('(no changes: already migrated)'); +} + +const isMain = process.argv[1] !== undefined && import.meta.url.endsWith(process.argv[1].replace(/\\/g, '/')); +if (isMain) { + main().catch((err: unknown) => { + console.error(err instanceof Error ? err.message : err); + process.exit(1); + }); +} diff --git a/apps/api/tests/migration-help-wanted-fills.test.ts b/apps/api/tests/migration-help-wanted-fills.test.ts new file mode 100644 index 00000000..3d438825 --- /dev/null +++ b/apps/api/tests/migration-help-wanted-fills.test.ts @@ -0,0 +1,86 @@ +/** + * Migration: needs filled by several members + * (scripts/migrations/202611290100-help-wanted-fills.ts), against old-shape + * fixtures committed as raw TOML. Made-up records only. + */ +import { execFile } from 'node:child_process'; +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { promisify } from 'node:util'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { migrateHelpWantedFills } from '../scripts/migrations/202611290100-help-wanted-fills.js'; +import { createFullDataRepo } from './helpers/test-full-repo.js'; + +const exec = promisify(execFile); +const GITSHEETS_CLI = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', 'node_modules', '.bin', 'gitsheets'); +const NOW = '2026-05-15T18:42:00Z'; +const id = (n: number): string => `01951a3c-0000-7000-8000-${String(n).padStart(12, '0')}`; + +let data: { path: string; cleanup: () => Promise<void> }; +const git = async (...args: string[]) => (await exec('git', ['--git-dir', data.path, ...args])).stdout.trim(); +const toml = (f: Record<string, string | number>) => + `${Object.entries(f).map(([k, v]) => `${k} = ${typeof v === 'string' ? JSON.stringify(v) : String(v)}`).join('\n')}\n`; + +async function seed(files: Record<string, string>): Promise<void> { + const wt = await mkdtemp(join(tmpdir(), 'cfp-migrate-fills-')); + try { + const run = (...args: string[]) => exec('git', args, { cwd: wt }); + await exec('git', ['clone', '--no-local', data.path, wt]); + await run('config', 'user.email', 'test@example.org'); + await run('config', 'user.name', 'cfp test'); + await run('config', 'commit.gpgsign', 'false'); + await run('config', 'core.hooksPath', '/dev/null'); + for (const [rel, content] of Object.entries(files)) { + await mkdir(dirname(join(wt, rel)), { recursive: true }); + await writeFile(join(wt, rel), content); + await run('add', rel); + } + await run('commit', '-m', 'seed'); + await run('push', 'origin', 'main'); + } finally { + await rm(wt, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); + } +} + +const role = (n: number, extra: Record<string, string>) => + toml({ id: id(n), projectSlug: 'proj', postedById: id(1), title: `Need ${n}`, description: 'Help.', createdAt: NOW, updatedAt: NOW, ...extra }); + +beforeEach(async () => { + data = await createFullDataRepo(); + await seed({ + 'people/ada.toml': toml({ id: id(1), slug: 'ada', fullName: 'Ada', accountLevel: 'user', createdAt: NOW, updatedAt: NOW }), + 'projects/proj.toml': toml({ id: id(2), slug: 'proj', title: 'Proj', stage: 'testing', createdAt: NOW, updatedAt: NOW }), + [`help-wanted-roles/proj/${id(10)}.toml`]: role(10, { status: 'filled', filledById: id(1), filledAt: NOW }), + [`help-wanted-roles/proj/${id(11)}.toml`]: role(11, { status: 'open' }), + }); +}); +afterEach(async () => { + await data.cleanup(); +}); + +describe('help-wanted fills migration', () => { + it('turns filledById into filledByIds in one commit and counts interest records; a second run is a no-op', async () => { + const first = await migrateHelpWantedFills({ dataRepo: data.path, branch: 'main' }); + expect(first).toMatchObject({ rolesMigrated: 2, interestRecords: 0 }); + expect(first.commitHash).toBe(await git('rev-parse', 'main')); + const filled = await git('show', `main:help-wanted-roles/proj/${id(10)}.toml`); + expect(filled).toContain(`filledByIds = ["${id(1)}"]`); + expect(filled).not.toContain('filledById ='); + expect(await git('show', `main:help-wanted-roles/proj/${id(11)}.toml`)).toContain("filledByIds = []"); + await exec(GITSHEETS_CLI, ['contracts', 'verify', '--git-dir', data.path, '--ref', 'main']); + + const second = await migrateHelpWantedFills({ dataRepo: data.path, branch: 'main' }); + expect(second).toMatchObject({ rolesMigrated: 0, commitHash: null }); + expect(await git('rev-parse', 'main')).toBe(first.commitHash); + }); + + it('reports interest records left in the retired sheet', async () => { + await seed({ [`help-wanted-interest/${id(10)}/bob.toml`]: toml({ id: id(20), roleId: id(10), personSlug: 'bob', createdAt: NOW }) }); + const r = await migrateHelpWantedFills({ dataRepo: data.path, branch: 'main', dryRun: true }); + expect(r).toMatchObject({ interestRecords: 1, commitHash: null, rolesMigrated: 2 }); + }); +}); From 3763951058f840d157b6c155dc1720d5298cdbf2 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:56:32 +0000 Subject: [PATCH 48/78] style(api): lint fixes in the needs work Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/src/services/help-wanted.write.ts | 4 ++-- apps/api/tests/needs.test.ts | 2 +- apps/api/tests/prune-spam.test.ts | 1 - 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/apps/api/src/services/help-wanted.write.ts b/apps/api/src/services/help-wanted.write.ts index 2fc7a8ce..987fd45e 100644 --- a/apps/api/src/services/help-wanted.write.ts +++ b/apps/api/src/services/help-wanted.write.ts @@ -23,7 +23,7 @@ import { import type { DualStoreTx } from '../store/store.js'; import { personBySlug, type InMemoryState } from '../store/memory/state.js'; import { StateApply } from '../store/state-apply.js'; -import { ApiNotFoundError, ApiValidationError, ConflictError } from '../lib/errors.js'; +import { ApiNotFoundError, ApiValidationError } from '../lib/errors.js'; import { requireAuth } from '../auth/require.js'; import type { SessionContext } from '../auth/middleware.js'; import { applyTagsForEntity, type TagAssignmentInput, type TagNamespace } from './tag.write.js'; @@ -33,7 +33,7 @@ const MAX_DESCRIPTION = 4_000; /** `detailsUrl`: an https URL, or null/absent. */ function checkDetailsUrl(url: string | null | undefined): void { if (url === undefined || url === null || url === '') return; - let ok = false; + let ok: boolean; try { ok = new URL(url).protocol === 'https:'; } catch { diff --git a/apps/api/tests/needs.test.ts b/apps/api/tests/needs.test.ts index d9d88dbb..55d838df 100644 --- a/apps/api/tests/needs.test.ts +++ b/apps/api/tests/needs.test.ts @@ -88,7 +88,7 @@ describe('needs', () => { expect(roleOf(R.a)).toMatchObject({ status: 'filled', filledByIds: [fid(P.ben), fid(P.cal)] }); expect(memberCount()).toBe(before); - res = await call(P.ada, 'POST', `/api/projects/proj/help-wanted/${R.a}/reopen`); + expect((await call(P.ada, 'POST', `/api/projects/proj/help-wanted/${R.a}/reopen`)).statusCode).toBe(200); expect(roleOf(R.a)).toMatchObject({ status: 'open', filledByIds: [] }); }); diff --git a/apps/api/tests/prune-spam.test.ts b/apps/api/tests/prune-spam.test.ts index 8d4f3924..046f21e3 100644 --- a/apps/api/tests/prune-spam.test.ts +++ b/apps/api/tests/prune-spam.test.ts @@ -119,7 +119,6 @@ async function slugsOn(repoPath: string, ref: string, root: string): Promise<str describe('prune-spam', () => { it('applies the aggregation rule, cascades, and commits onto the branch', async () => { - const roleId = uuid(900); const { data, evaluationsPath } = await setup({ people: [ person(1, 'spammer'), From 1526d50314c5cfb03f12a889a702d0601a56e9fe Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:56:32 +0000 Subject: [PATCH 49/78] feat(web): one need card with the apply states, fill picker and details link MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - HelpWantedCard is the need card on the project page, /help-wanted and the home rail. Its action is Sign in to apply, Member, Application sent ✓, Not taking applications, or Apply; Apply opens the project's apply form with the need ticked (the project page hands it to its own form). - Admins and staff get a menu: Edit, Mark filled, Close, Reopen. - Mark filled picks members (none or several) and can keep the need open. - The post form, now also the edit form, takes a details link. - Express interest is gone, with its modal and test; the moderation footprint no longer lists interest. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/web/src/components/HelpWantedCard.tsx | 178 ++++++++++++++---- .../src/components/modals/FillRoleModal.tsx | 95 ++++++---- .../components/modals/PostHelpWantedModal.tsx | 56 ++++-- apps/web/src/lib/api.ts | 32 ++-- apps/web/src/lib/needs.ts | 11 ++ apps/web/src/pages/AdminMembers.tsx | 7 - apps/web/src/screens/ProjectDetail.tsx | 97 +--------- apps/web/tests/AdminMembers.test.tsx | 3 +- apps/web/tests/HelpWantedCard.test.tsx | 144 ++++++++++++++ apps/web/tests/HelpWantedIndex.test.tsx | 11 +- 10 files changed, 415 insertions(+), 219 deletions(-) create mode 100644 apps/web/src/lib/needs.ts create mode 100644 apps/web/tests/HelpWantedCard.test.tsx diff --git a/apps/web/src/components/HelpWantedCard.tsx b/apps/web/src/components/HelpWantedCard.tsx index 32c7f062..0f0bb559 100644 --- a/apps/web/src/components/HelpWantedCard.tsx +++ b/apps/web/src/components/HelpWantedCard.tsx @@ -1,17 +1,47 @@ +/** + * The need card, shared by the project page, /help-wanted and the home rail + * (specs/behaviors/help-wanted-roles.md → Display rules across screens). + * + * Its one action follows from the role's caller state + * (specs/api/projects-help-wanted.md → Role shape): Sign in to apply, Member, + * Application sent ✓, Not taking applications, or Apply. Apply opens the + * project's apply form with this need ticked. Project admins and staff get + * a menu with Edit, Mark filled, Close and Reopen. + */ import { useState } from 'react'; import { Link } from 'react-router'; +import { useQueryClient } from '@tanstack/react-query'; +import { MoreHorizontalIcon } from 'lucide-react'; +import { toast } from 'sonner'; import { Button } from '@/components/ui/button'; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from '@/components/ui/dropdown-menu'; import { TagChip } from '@/components/TagChip'; import { PersonAvatar } from '@/components/PersonAvatar'; import { MarkdownView } from '@/components/MarkdownView'; -import { ExpressInterestModal } from '@/components/modals/ExpressInterestModal'; +import { ApplyDialog } from '@/components/project/ApplyDialog'; +import { FillRoleModal } from '@/components/modals/FillRoleModal'; +import { PostHelpWantedModal } from '@/components/modals/PostHelpWantedModal'; import { useAuth } from '@/hooks/useAuth'; +import { invalidateNeeds } from '@/lib/needs'; import { formatAbsoluteDate, formatRelativeTime } from '@/lib/time'; -import type { HelpWantedRoleResponse } from '@/lib/api'; +import { api, ApiError, type HelpWantedRoleResponse, type ProjectDetail } from '@/lib/api'; -interface HelpWantedCardProps { - role: HelpWantedRoleResponse; - showProjectLink?: boolean; +export type NeedAction = 'sign-in' | 'member' | 'applied' | 'not-taking' | 'apply' | null; + +/** Which one action a card shows, in the order the spec gives. */ +export function needAction(role: HelpWantedRoleResponse, signedIn: boolean): NeedAction { + if (!signedIn || role.viewer === null) return 'sign-in'; + if (role.viewer.state === 'member') return 'member'; + if (role.viewer.appliedForThis) return 'applied'; + if (!role.projectHasActiveAdmin) return 'not-taking'; + if (role.permissions.canApply) return 'apply'; + // An applicant whose open application did not pick this need: nothing to offer here. + return null; } function commitmentLabel(hours: number | null): string { @@ -19,16 +49,57 @@ function commitmentLabel(hours: number | null): string { return `~${hours} hrs/week`; } -export function HelpWantedCard({ role, showProjectLink = true }: HelpWantedCardProps) { +interface HelpWantedCardProps { + role: HelpWantedRoleResponse; + showProjectLink?: boolean; + /** + * Open the apply form with this need ticked. The project page passes its + * own; elsewhere the card loads the project and opens the form itself. + */ + onApply?: (role: HelpWantedRoleResponse) => void; +} + +export function HelpWantedCard({ role, showProjectLink = true, onApply }: HelpWantedCardProps) { const { person } = useAuth(); - const isSignedIn = person !== null; - const [modalOpen, setModalOpen] = useState(false); + const queryClient = useQueryClient(); + const action = needAction(role, person !== null); + const slug = role.project.slug; + const [applyProject, setApplyProject] = useState<ProjectDetail | null>(null); + const [loadingApply, setLoadingApply] = useState(false); + const [fillOpen, setFillOpen] = useState(false); + const [editOpen, setEditOpen] = useState(false); + const { canEdit, canFill, canClose } = role.permissions; + const isOpen = role.status === 'open'; + const hasMenu = canEdit || canFill || canClose; + + const apply = async () => { + if (onApply) { + onApply(role); + return; + } + setLoadingApply(true); + try { + const res = await queryClient.fetchQuery({ queryKey: ['project', slug], queryFn: () => api.projects.get(slug) }); + setApplyProject(res.data); + } catch { + toast.error("Couldn't open the apply form."); + } finally { + setLoadingApply(false); + } + }; + + const transition = (kind: 'close' | 'reopen') => { + if (kind === 'close' && !window.confirm(`Close "${role.title}" without filling?`)) return; + api.helpWantedRole[kind](slug, role.id) + .then(() => invalidateNeeds(queryClient, slug)) + .catch((err: unknown) => toast.error(err instanceof ApiError ? err.message : 'Something went wrong.')); + }; return ( <article className="rounded-lg border border-border bg-card p-4"> {showProjectLink && ( <div className="flex items-center justify-between mb-2"> - <Link to={`/projects/${role.project.slug}`} className="text-sm text-muted-foreground hover:text-primary"> + <Link to={`/projects/${slug}`} className="text-sm text-muted-foreground hover:text-primary"> {role.project.title} </Link> <span className="inline-flex items-center rounded-full bg-yellow-100 text-yellow-900 dark:bg-yellow-900/30 dark:text-yellow-200 px-2 py-0.5 text-xs font-medium"> @@ -37,7 +108,24 @@ export function HelpWantedCard({ role, showProjectLink = true }: HelpWantedCardP </div> )} - <h3 className="text-lg font-semibold mb-2">{role.title}</h3> + <div className="flex items-start justify-between gap-2 mb-2"> + <h3 className="text-lg font-semibold">{role.title}</h3> + {hasMenu && ( + <DropdownMenu> + <DropdownMenuTrigger asChild> + <Button size="icon" variant="ghost" className="h-8 w-8 shrink-0" aria-label={`Manage ${role.title}`}> + <MoreHorizontalIcon className="h-4 w-4" /> + </Button> + </DropdownMenuTrigger> + <DropdownMenuContent align="end"> + {canEdit && <DropdownMenuItem onSelect={() => setEditOpen(true)}>Edit</DropdownMenuItem>} + {canFill && isOpen && <DropdownMenuItem onSelect={() => setFillOpen(true)}>Mark filled</DropdownMenuItem>} + {canClose && isOpen && <DropdownMenuItem onSelect={() => transition('close')}>Close</DropdownMenuItem>} + {canFill && !isOpen && <DropdownMenuItem onSelect={() => transition('reopen')}>Reopen</DropdownMenuItem>} + </DropdownMenuContent> + </DropdownMenu> + )} + </div> <div className="line-clamp-4 mb-3 text-sm"> <MarkdownView html={role.descriptionHtml} /> @@ -53,8 +141,25 @@ export function HelpWantedCard({ role, showProjectLink = true }: HelpWantedCardP {role.tags.topic.map((t) => ( <TagChip key={`topic.${t.slug}`} tag={t} /> ))} + {role.detailsUrl && ( + <a + href={role.detailsUrl} + target="_blank" + rel="noopener noreferrer" + className="text-xs text-primary hover:underline" + aria-label={`Details: ${role.title}`} + > + Details + </a> + )} </div> + {role.filledBy.length > 0 && ( + <p className="mb-3 text-xs text-muted-foreground"> + Filled by {role.filledBy.map((p) => p.fullName).join(', ')} + </p> + )} + <div className="flex items-center justify-between gap-3 pt-3 border-t border-border"> <div className="flex items-center gap-2 text-xs text-muted-foreground"> {role.postedBy && ( @@ -72,35 +177,38 @@ export function HelpWantedCard({ role, showProjectLink = true }: HelpWantedCardP </span> </div> - {isSignedIn ? ( - role.permissions.alreadyExpressedInterest ? ( - <Button size="sm" variant="outline" disabled> - Interest Sent ✓ - </Button> - ) : ( - <Button - size="sm" - disabled={!role.permissions.canExpressInterest} - onClick={() => setModalOpen(true)} - > - Express Interest - </Button> - ) - ) : ( + {action === 'sign-in' && ( <Button asChild size="sm" variant="outline"> - <Link to={`/login?return=${encodeURIComponent(`/projects/${role.project.slug}`)}`}> - Sign in to express interest - </Link> + <Link to={`/login?return=${encodeURIComponent(`/projects/${slug}`)}`}>Sign in to apply</Link> + </Button> + )} + {action === 'member' && <span className="text-sm text-muted-foreground">Member</span>} + {action === 'applied' && ( + <Button size="sm" variant="outline" disabled> + Application sent ✓ + </Button> + )} + {action === 'not-taking' && <span className="text-sm text-muted-foreground">Not taking applications</span>} + {action === 'apply' && ( + <Button size="sm" onClick={() => void apply()} disabled={loadingApply} aria-label={`Apply: ${role.title}`}> + Apply </Button> )} </div> - <ExpressInterestModal - open={modalOpen} - onOpenChange={setModalOpen} - projectSlug={role.project.slug} - roleId={role.id} - roleTitle={role.title} - /> + + {applyProject && ( + <ApplyDialog + project={applyProject} + open + onOpenChange={(o) => !o && setApplyProject(null)} + preselectedRoleId={role.id} + onApplied={() => invalidateNeeds(queryClient, slug)} + /> + )} + {fillOpen && ( + <FillRoleModal open={fillOpen} onOpenChange={setFillOpen} projectSlug={slug} roleId={role.id} roleTitle={role.title} /> + )} + {editOpen && <PostHelpWantedModal open={editOpen} onOpenChange={setEditOpen} projectSlug={slug} role={role} />} </article> ); } diff --git a/apps/web/src/components/modals/FillRoleModal.tsx b/apps/web/src/components/modals/FillRoleModal.tsx index df6bae1e..278fa32a 100644 --- a/apps/web/src/components/modals/FillRoleModal.tsx +++ b/apps/web/src/components/modals/FillRoleModal.tsx @@ -1,5 +1,12 @@ +/** + * Mark a need filled (specs/behaviors/help-wanted-roles.md → Lifecycle): + * pick the project's members who filled it, none or several, and optionally + * keep it open for more. Filling never adds anyone to the project: a + * non-member joins through an application, whose accept can mark the need + * filled in the same step. + */ import { useState } from 'react'; -import { useQueryClient } from '@tanstack/react-query'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; import { toast } from 'sonner'; import { Dialog, @@ -10,9 +17,10 @@ import { DialogTitle, } from '@/components/ui/dialog'; import { Button } from '@/components/ui/button'; -import { Input } from '@/components/ui/input'; +import { Checkbox } from '@/components/ui/checkbox'; import { Label } from '@/components/ui/label'; import { api, ApiError } from '@/lib/api'; +import { invalidateNeeds } from '@/lib/needs'; interface FillRoleModalProps { open: boolean; @@ -22,32 +30,29 @@ interface FillRoleModalProps { roleTitle: string; } -export function FillRoleModal({ - open, - onOpenChange, - projectSlug, - roleId, - roleTitle, -}: FillRoleModalProps) { +export function FillRoleModal({ open, onOpenChange, projectSlug, roleId, roleTitle }: FillRoleModalProps) { const queryClient = useQueryClient(); - const [filledBySlug, setFilledBySlug] = useState(''); + const projectQ = useQuery({ queryKey: ['project', projectSlug], queryFn: () => api.projects.get(projectSlug), enabled: open }); + const members = (projectQ.data?.data.memberships ?? []).filter((m) => m.person.slug !== null && !m.person.deactivated); + const [picked, setPicked] = useState<Set<string>>(new Set()); + const [keepOpen, setKeepOpen] = useState(false); const [submitting, setSubmitting] = useState(false); + const toggle = (slug: string, on: boolean) => + setPicked((s) => { + const next = new Set(s); + if (on) next.add(slug); + else next.delete(slug); + return next; + }); + const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setSubmitting(true); try { - await api.helpWantedRole.fill( - projectSlug, - roleId, - filledBySlug.trim() || null, - ); - await queryClient.invalidateQueries({ queryKey: ['project', projectSlug] }); - await queryClient.invalidateQueries({ - queryKey: ['project-help-wanted', projectSlug], - }); - toast.success(`Marked "${roleTitle}" as filled`); - setFilledBySlug(''); + await api.helpWantedRole.fill(projectSlug, roleId, { filledBySlugs: [...picked], keepOpen }); + await invalidateNeeds(queryClient, projectSlug); + toast.success(keepOpen ? `Recorded who filled "${roleTitle}"` : `Marked "${roleTitle}" as filled`); onOpenChange(false); } catch (err) { toast.error(err instanceof ApiError ? err.message : 'Failed to mark filled'); @@ -61,31 +66,45 @@ export function FillRoleModal({ <DialogContent> <form onSubmit={handleSubmit}> <DialogHeader> - <DialogTitle>Mark role filled</DialogTitle> + <DialogTitle>Mark need filled</DialogTitle> <DialogDescription> - Mark <strong>{roleTitle}</strong> as filled. Optionally specify the - person who filled it — they'll be added as a project member if not - already on the project. + Who filled <strong>{roleTitle}</strong>? Pick from the project's members. Someone not on the + project joins by applying first. </DialogDescription> </DialogHeader> - <div className="py-4 space-y-2"> - <Label htmlFor="filled-by">Filled by (optional)</Label> - <Input - id="filled-by" - value={filledBySlug} - onChange={(e) => setFilledBySlug(e.target.value)} - placeholder="e.g. chris" - /> - <p className="text-xs text-muted-foreground"> - Leave blank to mark filled without attribution. - </p> + <div className="py-4 space-y-4"> + <fieldset className="space-y-2"> + <legend className="text-sm font-medium">Filled by (optional)</legend> + {projectQ.isLoading ? ( + <p className="text-sm text-muted-foreground">Loading members…</p> + ) : members.length === 0 ? ( + <p className="text-sm text-muted-foreground">No members to pick.</p> + ) : ( + <div className="max-h-56 space-y-2 overflow-y-auto"> + {members.map((m) => ( + <div key={m.id} className="flex items-center gap-2"> + <Checkbox + id={`fill-${m.person.slug}`} + checked={picked.has(m.person.slug!)} + onCheckedChange={(v) => toggle(m.person.slug!, v === true)} + /> + <Label htmlFor={`fill-${m.person.slug}`}>{m.person.fullName}</Label> + </div> + ))} + </div> + )} + </fieldset> + <div className="flex items-center gap-2"> + <Checkbox id="fill-keep-open" checked={keepOpen} onCheckedChange={(v) => setKeepOpen(v === true)} /> + <Label htmlFor="fill-keep-open">Keep open for more people</Label> + </div> </div> <DialogFooter> <Button type="button" variant="outline" onClick={() => onOpenChange(false)}> Cancel </Button> - <Button type="submit" disabled={submitting}> - {submitting ? 'Saving…' : 'Mark filled'} + <Button type="submit" disabled={submitting || (keepOpen && picked.size === 0)}> + {submitting ? 'Saving…' : keepOpen ? 'Record' : 'Mark filled'} </Button> </DialogFooter> </form> diff --git a/apps/web/src/components/modals/PostHelpWantedModal.tsx b/apps/web/src/components/modals/PostHelpWantedModal.tsx index 87ee4f4c..4d7d8f31 100644 --- a/apps/web/src/components/modals/PostHelpWantedModal.tsx +++ b/apps/web/src/components/modals/PostHelpWantedModal.tsx @@ -14,30 +14,35 @@ import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { MarkdownEditor } from '@/components/MarkdownEditor'; import { TagPicker } from '@/components/TagPicker'; -import { api, ApiError } from '@/lib/api'; +import { api, ApiError, type HelpWantedRoleResponse } from '@/lib/api'; +import { invalidateNeeds } from '@/lib/needs'; import { useAuth } from '@/hooks/useAuth'; interface PostHelpWantedModalProps { open: boolean; onOpenChange: (open: boolean) => void; projectSlug: string; + /** Edit this role instead of posting a new one. */ + role?: HelpWantedRoleResponse; } export function PostHelpWantedModal({ open, onOpenChange, projectSlug, + role, }: PostHelpWantedModalProps) { const queryClient = useQueryClient(); const { person } = useAuth(); const isStaff = person?.accountLevel === 'staff' || person?.accountLevel === 'administrator'; - const [title, setTitle] = useState(''); - const [description, setDescription] = useState(''); - const [hours, setHours] = useState<string>(''); - const [tagsTopic, setTagsTopic] = useState<string[]>([]); - const [tagsTech, setTagsTech] = useState<string[]>([]); + const [title, setTitle] = useState(role?.title ?? ''); + const [description, setDescription] = useState(role?.description ?? ''); + const [hours, setHours] = useState<string>(role?.commitmentHoursPerWeek != null ? String(role.commitmentHoursPerWeek) : ''); + const [detailsUrl, setDetailsUrl] = useState(role?.detailsUrl ?? ''); + const [tagsTopic, setTagsTopic] = useState<string[]>(role?.tags.topic.map((t) => t.slug) ?? []); + const [tagsTech, setTagsTech] = useState<string[]>(role?.tags.tech.map((t) => t.slug) ?? []); const [submitting, setSubmitting] = useState(false); const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({}); @@ -45,6 +50,7 @@ export function PostHelpWantedModal({ setTitle(''); setDescription(''); setHours(''); + setDetailsUrl(''); setTagsTopic([]); setTagsTech([]); setFieldErrors({}); @@ -55,18 +61,18 @@ export function PostHelpWantedModal({ setSubmitting(true); setFieldErrors({}); try { - await api.projects.postHelpWanted(projectSlug, { + const input = { title: title.trim(), description, commitmentHoursPerWeek: hours ? Number.parseInt(hours, 10) : null, + detailsUrl: detailsUrl.trim() === '' ? null : detailsUrl.trim(), tags: { topic: tagsTopic, tech: tagsTech }, - }); - await queryClient.invalidateQueries({ - queryKey: ['project-help-wanted', projectSlug], - }); - await queryClient.invalidateQueries({ queryKey: ['help-wanted-index'] }); - toast.success('Help-wanted role posted'); - reset(); + }; + if (role) await api.helpWantedRole.update(projectSlug, role.id, input); + else await api.projects.postHelpWanted(projectSlug, input); + await invalidateNeeds(queryClient, projectSlug); + toast.success(role ? 'Need updated' : 'Help-wanted role posted'); + if (!role) reset(); onOpenChange(false); } catch (err) { if (err instanceof ApiError) { @@ -81,11 +87,11 @@ export function PostHelpWantedModal({ }; return ( - <Dialog open={open} onOpenChange={(o) => { if (!o) reset(); onOpenChange(o); }}> + <Dialog open={open} onOpenChange={(o) => { if (!o && !role) reset(); onOpenChange(o); }}> <DialogContent className="max-w-3xl"> <form onSubmit={handleSubmit}> <DialogHeader> - <DialogTitle>Post Help-Wanted Role</DialogTitle> + <DialogTitle>{role ? 'Edit need' : 'Post Help-Wanted Role'}</DialogTitle> <DialogDescription> Describe a concrete, time-boxed way someone can contribute. </DialogDescription> @@ -132,6 +138,22 @@ export function PostHelpWantedModal({ className="w-40" /> </div> + <div className="space-y-1.5"> + <Label htmlFor="hw-details">Details link</Label> + <Input + id="hw-details" + type="url" + value={detailsUrl} + onChange={(e) => setDetailsUrl(e.target.value)} + placeholder="https://github.com/… (an issue list, a doc)" + pattern="https://.*" + aria-invalid={fieldErrors['detailsUrl'] ? 'true' : 'false'} + aria-describedby="hw-details-help" + /> + <p id="hw-details-help" className={fieldErrors['detailsUrl'] ? 'text-xs text-destructive' : 'text-xs text-muted-foreground'}> + {fieldErrors['detailsUrl'] ?? 'Optional. An https link the card shows as "Details".'} + </p> + </div> <TagPicker namespace="topic" label="Topic tags" @@ -152,7 +174,7 @@ export function PostHelpWantedModal({ Cancel </Button> <Button type="submit" disabled={!title.trim() || !description.trim() || submitting}> - {submitting ? 'Posting…' : 'Post role'} + {submitting ? 'Saving…' : role ? 'Save' : 'Post role'} </Button> </DialogFooter> </form> diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index d88859b4..27b3cd76 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -313,8 +313,7 @@ export interface TagResponse { export interface HelpWantedPermissions { readonly canEdit: boolean; - readonly canExpressInterest: boolean; - readonly alreadyExpressedInterest: boolean; + readonly canApply: boolean; readonly canFill: boolean; readonly canClose: boolean; } @@ -328,12 +327,15 @@ export interface HelpWantedRoleResponse { readonly descriptionHtml: string; readonly commitmentHoursPerWeek: number | null; readonly status: string; - readonly filledBy: PersonAvatar | null; + readonly detailsUrl: string | null; + readonly filledBy: PersonAvatar[]; readonly filledAt: string | null; readonly closedAt: string | null; readonly tags: { topic: TagItem[]; tech: TagItem[] }; - readonly interestCount: number; readonly permissions: HelpWantedPermissions; + /** The caller's standing on the project; null when signed out. */ + readonly viewer: { readonly state: MembershipState | null; readonly appliedForThis: boolean } | null; + readonly projectHasActiveAdmin: boolean; readonly createdAt: string; readonly updatedAt: string; } @@ -734,6 +736,8 @@ export interface CreateHelpWantedInput { title: string; description: string; commitmentHoursPerWeek?: number | null; + /** An https link with more about the need (an issue list, a doc). */ + detailsUrl?: string | null; tags?: { tech?: string[]; topic?: string[] }; } @@ -756,10 +760,6 @@ export interface LeaveProjectInput { confirmLastAdmin?: boolean; } -export interface ExpressInterestInput { - message?: string | null; -} - export interface SessionListItem { jti: string; userAgent: string; @@ -889,7 +889,6 @@ export interface MemberRow { readonly updates: number; readonly buzz: number; readonly blogPosts: number; - readonly helpWantedInterest: number; readonly tags: number; /** Event RSVPs on record, past and upcoming events alike. */ readonly rsvps: number; @@ -928,7 +927,6 @@ export interface MemberFootprint { readonly updates: Array<{ project: ProjectRef; number: number; title: string; postedAt: string }>; readonly buzz: Array<{ project: ProjectRef; slug: string; title: string; postedAt: string }>; readonly blogPosts: Array<{ slug: string; title: string; postedAt: string }>; - readonly helpWantedInterest: Array<{ project: ProjectRef; role: { title: string }; createdAt: string }>; readonly tags: Array<{ handle: string; type: string }>; /** Event RSVPs, newest RSVP first. */ readonly rsvps: Array<{ event: { slug: string; title: string; startsAt: string }; createdAt: string }>; @@ -1106,23 +1104,15 @@ export const api = { `/api/projects/${encodeURIComponent(projectSlug)}/help-wanted/${encodeURIComponent(roleId)}`, { method: 'PATCH', body: JSON.stringify(input) }, ), - expressInterest: ( - projectSlug: string, - roleId: string, - input: ExpressInterestInput, - ): Promise<SuccessEnvelope<{ delivered: boolean }>> => - request( - `/api/projects/${encodeURIComponent(projectSlug)}/help-wanted/${encodeURIComponent(roleId)}/express-interest`, - { method: 'POST', body: JSON.stringify(input) }, - ), + /** Members who filled it (none is allowed); keepOpen records them and leaves it open. */ fill: ( projectSlug: string, roleId: string, - filledBySlug?: string | null, + input: { filledBySlugs: string[]; keepOpen?: boolean }, ): Promise<SuccessEnvelope<HelpWantedRoleResponse>> => request( `/api/projects/${encodeURIComponent(projectSlug)}/help-wanted/${encodeURIComponent(roleId)}/fill`, - { method: 'POST', body: JSON.stringify({ filledBySlug: filledBySlug ?? null }) }, + { method: 'POST', body: JSON.stringify(input) }, ), close: ( projectSlug: string, diff --git a/apps/web/src/lib/needs.ts b/apps/web/src/lib/needs.ts new file mode 100644 index 00000000..dee80af1 --- /dev/null +++ b/apps/web/src/lib/needs.ts @@ -0,0 +1,11 @@ +import type { QueryClient } from '@tanstack/react-query'; + +/** Every query a change to a project's needs shows up in. */ +export async function invalidateNeeds(queryClient: QueryClient, projectSlug: string): Promise<void> { + await Promise.all([ + queryClient.invalidateQueries({ queryKey: ['project', projectSlug] }), + queryClient.invalidateQueries({ queryKey: ['project-help-wanted', projectSlug] }), + queryClient.invalidateQueries({ queryKey: ['help-wanted-index'] }), + queryClient.invalidateQueries({ queryKey: ['help-wanted'] }), + ]); +} diff --git a/apps/web/src/pages/AdminMembers.tsx b/apps/web/src/pages/AdminMembers.tsx index c59f700e..885143f6 100644 --- a/apps/web/src/pages/AdminMembers.tsx +++ b/apps/web/src/pages/AdminMembers.tsx @@ -332,7 +332,6 @@ function MemberRowView({ fp.updates ? `${fp.updates} update${fp.updates === 1 ? '' : 's'}` : null, fp.buzz ? `${fp.buzz} buzz` : null, fp.blogPosts ? `${fp.blogPosts} post${fp.blogPosts === 1 ? '' : 's'}` : null, - fp.helpWantedInterest ? `${fp.helpWantedInterest} help-wanted` : null, fp.applications ? `${fp.applications} application${fp.applications === 1 ? '' : 's'}` : null, fp.follows ? `${fp.follows} follow${fp.follows === 1 ? '' : 's'}` : null, fp.rsvps ? `${fp.rsvps} RSVP${fp.rsvps === 1 ? '' : 's'}` : null, @@ -499,12 +498,6 @@ function MemberDetailView({ slug }: { slug: string }) { <li key={bp.slug}><Link to={`/blog/${bp.slug}`} className="hover:underline">{bp.title}</Link>, {formatAbsoluteDate(bp.postedAt)}</li> )), )} - {section( - 'Help-wanted interest', - footprint.helpWantedInterest.map((i, idx) => ( - <li key={idx}>{i.role.title} on {i.project.title}, {formatAbsoluteDate(i.createdAt)}</li> - )), - )} {section( 'Event RSVPs', footprint.rsvps.map((r) => ( diff --git a/apps/web/src/screens/ProjectDetail.tsx b/apps/web/src/screens/ProjectDetail.tsx index 7b17e041..cfb99c4b 100644 --- a/apps/web/src/screens/ProjectDetail.tsx +++ b/apps/web/src/screens/ProjectDetail.tsx @@ -29,12 +29,11 @@ import { PostUpdateModal } from '@/components/modals/PostUpdateModal'; import { PostHelpWantedModal } from '@/components/modals/PostHelpWantedModal'; import { AddMemberModal } from '@/components/modals/AddMemberModal'; import { ManageMembersModal } from '@/components/modals/ManageMembersModal'; -import { ExpressInterestModal } from '@/components/modals/ExpressInterestModal'; -import { FillRoleModal } from '@/components/modals/FillRoleModal'; +import { HelpWantedCard } from '@/components/HelpWantedCard'; import { JoinBlock } from '@/components/project/JoinBlock'; import { ApplyDialog } from '@/components/project/ApplyDialog'; import { useAuth } from '@/hooks/useAuth'; -import { api, ApiError, type HelpWantedRoleResponse } from '@/lib/api'; +import { api, ApiError } from '@/lib/api'; import { formatRelativeTime, formatAbsoluteDate } from '@/lib/time'; /** @@ -59,11 +58,6 @@ interface ProjectDetailProps { anchor?: 'update' | 'buzz'; } -function commitmentLabel(hours: number | null): string { - if (hours === null) return 'Flexible commitment'; - return `~${hours} hrs/week`; -} - function isGithubUrl(url: string): boolean { try { const u = new URL(url); @@ -85,8 +79,6 @@ export function ProjectDetail({ anchor }: ProjectDetailProps = {}) { const [helpWantedModalOpen, setHelpWantedModalOpen] = useState(false); const [addMemberOpen, setAddMemberOpen] = useState(false); const [manageMembersOpen, setManageMembersOpen] = useState(false); - const [interestRole, setInterestRole] = useState<HelpWantedRoleResponse | null>(null); - const [fillRole, setFillRole] = useState<HelpWantedRoleResponse | null>(null); const [stageInfoOpen, setStageInfoOpen] = useState(false); const [memberBusy, setMemberBusy] = useState(false); const [memberError, setMemberError] = useState<string | null>(null); @@ -324,71 +316,7 @@ export function ProjectDetail({ anchor }: ProjectDetailProps = {}) { ) : ( <div className="space-y-3"> {helpWantedRoles.map((role) => ( - <article key={role.id} className="rounded-lg border border-border bg-card p-4"> - <h3 className="font-semibold mb-2">{role.title}</h3> - <div className="line-clamp-4 mb-3 text-sm"> - <MarkdownView html={role.descriptionHtml} /> - </div> - <div className="flex flex-wrap gap-2 mb-3"> - <span className="inline-flex items-center rounded-full bg-muted px-2 py-0.5 text-xs"> - {commitmentLabel(role.commitmentHoursPerWeek)} - </span> - {role.tags.tech.map((t) => <TagChip key={`tech.${t.slug}`} tag={t} />)} - {role.tags.topic.map((t) => <TagChip key={`topic.${t.slug}`} tag={t} />)} - </div> - <div className="flex items-center justify-end gap-2"> - {/* One row per open role, so these names repeat - verbatim unless they carry the role title. */} - {role.permissions.canFill && ( - <Button - size="sm" - variant="outline" - aria-label={`Mark filled: ${role.title}`} - onClick={() => setFillRole(role)} - > - Mark filled - </Button> - )} - {role.permissions.canClose && ( - <Button - size="sm" - variant="ghost" - aria-label={`Close ${role.title}`} - onClick={() => { - if (!window.confirm(`Close "${role.title}" without filling?`)) return; - api.helpWantedRole - .close(slug, role.id) - .then(() => helpWantedQ.refetch()) - .catch(() => undefined); - }} - > - Close - </Button> - )} - {isSignedIn ? ( - role.permissions.alreadyExpressedInterest ? ( - <Button size="sm" variant="outline" disabled> - Interest Sent ✓ - </Button> - ) : ( - <Button - size="sm" - disabled={!role.permissions.canExpressInterest} - onClick={() => setInterestRole(role)} - > - Express Interest - </Button> - ) - ) : ( - <Link - to={`/login?return=${encodeURIComponent(`/projects/${slug}`)}`} - className="text-sm text-primary hover:underline" - > - Sign in to express interest - </Link> - )} - </div> - </article> + <HelpWantedCard key={role.id} role={role} showProjectLink={false} onApply={(r) => openApply(r.id)} /> ))} </div> )} @@ -657,25 +585,6 @@ export function ProjectDetail({ anchor }: ProjectDetailProps = {}) { onOpenChange={setManageMembersOpen} project={project} /> - {interestRole && ( - <ExpressInterestModal - open={!!interestRole} - onOpenChange={(o) => !o && setInterestRole(null)} - projectSlug={slug} - roleId={interestRole.id} - roleTitle={interestRole.title} - /> - )} - {fillRole && ( - <FillRoleModal - open={!!fillRole} - onOpenChange={(o) => !o && setFillRole(null)} - projectSlug={slug} - roleId={fillRole.id} - roleTitle={fillRole.title} - /> - )} - <Dialog open={deleteOpen} onOpenChange={setDeleteOpen}> <DialogContent> <DialogHeader> diff --git a/apps/web/tests/AdminMembers.test.tsx b/apps/web/tests/AdminMembers.test.tsx index d5716ff7..0e00c091 100644 --- a/apps/web/tests/AdminMembers.test.tsx +++ b/apps/web/tests/AdminMembers.test.tsx @@ -18,7 +18,6 @@ const NO_FOOTPRINT: MemberRow['footprint'] = { updates: 0, buzz: 0, blogPosts: 0, - helpWantedInterest: 0, tags: 0, rsvps: 0, }; @@ -54,7 +53,7 @@ function makeRow(over: Partial<MemberRow> = {}): MemberRow { function makeDetail(rsvps: MemberDetail['footprint']['rsvps']): MemberDetail { return { person: { slug: 'quiet-volunteer', fullName: 'Quiet Volunteer', bioHtml: '' } as unknown as MemberDetail['person'], - footprint: { memberships: [], updates: [], buzz: [], blogPosts: [], helpWantedInterest: [], tags: [], rsvps }, + footprint: { memberships: [], updates: [], buzz: [], blogPosts: [], tags: [], rsvps }, votes: [], earlierVotes: [], earlierPurges: [], diff --git a/apps/web/tests/HelpWantedCard.test.tsx b/apps/web/tests/HelpWantedCard.test.tsx new file mode 100644 index 00000000..447a13e8 --- /dev/null +++ b/apps/web/tests/HelpWantedCard.test.tsx @@ -0,0 +1,144 @@ +/** + * The need card's one action per caller state + * (specs/behaviors/help-wanted-roles.md → Display rules across screens), the + * Details link, the admin menu, and Apply opening the form with the need ticked. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { renderScreen, mockOk } from './test-utils.js'; +import { HelpWantedCard, needAction } from '../src/components/HelpWantedCard.js'; +import type { HelpWantedRoleResponse } from '../src/lib/api.js'; + +// Radix checkboxes measure themselves with ResizeObserver, which jsdom lacks. +globalThis.ResizeObserver ??= class { + observe() {} + unobserve() {} + disconnect() {} +} as unknown as typeof ResizeObserver; + +const auth = vi.hoisted(() => ({ person: null as null | { slug: string } })); +vi.mock('../src/hooks/useAuth.js', () => ({ useAuth: () => ({ person: auth.person }) })); + +const ROLE: HelpWantedRoleResponse = { + id: 'r1', + project: { slug: 'sample', title: 'Sample Project' }, + postedBy: null, + title: 'Frontend developer', + description: 'Help us build a React app', + descriptionHtml: '<p>Help us build a React app</p>', + commitmentHoursPerWeek: 4, + status: 'open', + detailsUrl: null, + filledBy: [], + filledAt: null, + closedAt: null, + tags: { topic: [], tech: [] }, + permissions: { canEdit: false, canApply: false, canFill: false, canClose: false }, + viewer: null, + projectHasActiveAdmin: true, + createdAt: '2026-05-01T00:00:00Z', + updatedAt: '2026-05-01T00:00:00Z', +}; +const as = (over: Partial<HelpWantedRoleResponse>): HelpWantedRoleResponse => ({ ...ROLE, ...over }); +const PERMS = ROLE.permissions; + +describe('need card', () => { + beforeEach(() => { + auth.person = { slug: 'me' }; + }); + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('picks one action per caller state, in the spec order', () => { + expect(needAction(ROLE, false)).toBe('sign-in'); + expect(needAction(as({ viewer: { state: 'member', appliedForThis: false } }), true)).toBe('member'); + expect(needAction(as({ viewer: { state: 'applicant', appliedForThis: true } }), true)).toBe('applied'); + expect(needAction(as({ viewer: { state: null, appliedForThis: false }, projectHasActiveAdmin: false }), true)).toBe('not-taking'); + expect(needAction(as({ viewer: { state: 'follower', appliedForThis: false }, permissions: { ...PERMS, canApply: true } }), true)).toBe('apply'); + expect(needAction(as({ viewer: { state: 'applicant', appliedForThis: false } }), true)).toBeNull(); + }); + + const cases: Array<[string, Partial<HelpWantedRoleResponse>, boolean, RegExp]> = [ + ['signed out', {}, false, /sign in to apply/i], + ['a member', { viewer: { state: 'member', appliedForThis: false } }, true, /^member$/i], + ['an applicant for this need', { viewer: { state: 'applicant', appliedForThis: true } }, true, /application sent ✓/i], + ['anyone, with no active admin', { viewer: { state: null, appliedForThis: false }, projectHasActiveAdmin: false }, true, /not taking applications/i], + ['someone who can apply', { viewer: { state: null, appliedForThis: false }, permissions: { ...PERMS, canApply: true } }, true, /^apply$/i], + ]; + for (const [who, over, signedIn, label] of cases) { + it(`shows the right action for ${who}`, () => { + auth.person = signedIn ? { slug: 'me' } : null; + renderScreen(<HelpWantedCard role={as(over)} />); + expect(screen.getByText(label)).toBeInTheDocument(); + const others = [/sign in to apply/i, /^member$/i, /application sent ✓/i, /not taking applications/i, /^apply$/i].filter((l) => l.source !== label.source); + for (const other of others) expect(screen.queryByText(other)).toBeNull(); + }); + } + + it('shows a Details link only when detailsUrl is set, and who filled it', () => { + const { unmount } = renderScreen(<HelpWantedCard role={ROLE} />); + expect(screen.queryByRole('link', { name: /details/i })).toBeNull(); + unmount(); + renderScreen( + <HelpWantedCard + role={as({ detailsUrl: 'https://example.org/issues', filledBy: [{ slug: 'ada', fullName: 'Ada Example', avatarUrl: null }] })} + />, + ); + expect(screen.getByRole('link', { name: /details/i })).toHaveAttribute('href', 'https://example.org/issues'); + expect(screen.getByText(/filled by ada example/i)).toBeInTheDocument(); + }); + + it('gives admins a menu with Edit, Mark filled and Close, and nobody else one', async () => { + const { unmount } = renderScreen(<HelpWantedCard role={ROLE} />); + expect(screen.queryByRole('button', { name: /manage frontend developer/i })).toBeNull(); + unmount(); + renderScreen(<HelpWantedCard role={as({ permissions: { ...PERMS, canEdit: true, canFill: true, canClose: true } })} />); + await userEvent.click(screen.getByRole('button', { name: /manage frontend developer/i })); + expect(await screen.findByRole('menuitem', { name: 'Edit' })).toBeInTheDocument(); + expect(screen.getByRole('menuitem', { name: 'Mark filled' })).toBeInTheDocument(); + expect(screen.getByRole('menuitem', { name: 'Close' })).toBeInTheDocument(); + expect(screen.queryByRole('menuitem', { name: 'Reopen' })).toBeNull(); + }); + + it('Apply off the project page opens the apply form with this need ticked', async () => { + vi.spyOn(globalThis, 'fetch').mockImplementation(((input: string) => + Promise.resolve( + input.startsWith('/api/projects/sample') + ? new Response( + JSON.stringify( + mockOk({ + slug: 'sample', + title: 'Sample Project', + openHelpWantedRoles: [ + { id: 'r1', title: 'Frontend developer', commitmentHoursPerWeek: 4, status: 'open', tags: { topic: [], tech: [] } }, + { id: 'r2', title: 'Mapper', commitmentHoursPerWeek: null, status: 'open', tags: { topic: [], tech: [] } }, + ], + }), + ), + { status: 200, headers: { 'content-type': 'application/json' } }, + ) + : new Response(null, { status: 404 }), + )) as typeof fetch); + renderScreen(<HelpWantedCard role={as({ viewer: { state: null, appliedForThis: false }, permissions: { ...PERMS, canApply: true } })} />); + await userEvent.click(screen.getByRole('button', { name: /apply: frontend developer/i })); + const dialog = await screen.findByRole('dialog'); + expect(dialog).toHaveTextContent(/apply to join sample project/i); + await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Frontend developer' })).toBeChecked()); + expect(screen.getByRole('checkbox', { name: 'Mapper' })).not.toBeChecked(); + }); + + it('on the project page, Apply hands the need to the page', async () => { + const onApply = vi.fn(); + renderScreen( + <HelpWantedCard + role={as({ viewer: { state: null, appliedForThis: false }, permissions: { ...PERMS, canApply: true } })} + showProjectLink={false} + onApply={onApply} + />, + ); + await userEvent.click(screen.getByRole('button', { name: /apply: frontend developer/i })); + expect(onApply).toHaveBeenCalledWith(expect.objectContaining({ id: 'r1' })); + }); +}); diff --git a/apps/web/tests/HelpWantedIndex.test.tsx b/apps/web/tests/HelpWantedIndex.test.tsx index cfd92317..a6e9342d 100644 --- a/apps/web/tests/HelpWantedIndex.test.tsx +++ b/apps/web/tests/HelpWantedIndex.test.tsx @@ -13,18 +13,19 @@ const SAMPLE_ROLE = { descriptionHtml: '<p>Help us build a React app</p>', commitmentHoursPerWeek: 4, status: 'open', - filledBy: null, + detailsUrl: null, + filledBy: [], filledAt: null, closedAt: null, tags: { topic: [], tech: [{ namespace: 'tech', slug: 'react', title: 'React' }] }, - interestCount: 0, permissions: { canEdit: false, - canExpressInterest: false, - alreadyExpressedInterest: false, + canApply: false, canFill: false, canClose: false, }, + viewer: null, + projectHasActiveAdmin: true, createdAt: '2026-05-01T00:00:00Z', updatedAt: '2026-05-01T00:00:00Z', }; @@ -62,7 +63,7 @@ describe('HelpWantedIndex', () => { }); expect(screen.getByText(/~4 hrs\/week/)).toBeInTheDocument(); - expect(screen.getByRole('link', { name: /sign in to express interest/i })).toBeInTheDocument(); + expect(screen.getByRole('link', { name: /sign in to apply/i })).toBeInTheDocument(); }); it('renders commitment radio filter options', async () => { From 92d323d5a1614b5d779382b43991706908926198 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:08:04 +0000 Subject: [PATCH 50/78] chore(plans): mark needs-on-applications done (PR #269) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- plans/needs-on-applications.md | 64 ++++++++++++++++++++++++++++++---- 1 file changed, 57 insertions(+), 7 deletions(-) diff --git a/plans/needs-on-applications.md b/plans/needs-on-applications.md index 9d6cf05e..6e35b655 100644 --- a/plans/needs-on-applications.md +++ b/plans/needs-on-applications.md @@ -1,5 +1,5 @@ --- -status: in-progress +status: done depends: [membership-applications] specs: - specs/behaviors/help-wanted-roles.md @@ -57,12 +57,12 @@ claim) removed; `interestCount` gone. ## Validation - [ ] `help-wanted-roles/v3` adopted and mirrored; the `help-wanted-interest` sheet is absent from `empty`, `fixture`, `legacy-import` and `apps/api/gitsheets/`; grep finds no runtime reference to it -- [ ] `POST …/express-interest` returns `410 gone`; no response carries `interestCount` -- [ ] Tests: fill with two member slugs records both and sets `filled`; `keepOpen` records them and stays `open`; a non-member slug → `422 not_a_member`; fill never creates a membership -- [ ] Tests: accept with `fillRoleIds` fills those needs in the same commit; a role not in the application or not open → `422` -- [ ] Need cards show the right one of Apply / Application sent / Member / Sign in to apply / Not taking applications for each caller state (component tests) -- [ ] Browser: from `/help-wanted`, Apply on a need opens the apply form with it ticked; as admin, accept with "mark filled" and see the need leave the board -- [ ] `npm run type-check && npm run lint && npm test` clean +- [x] `POST …/express-interest` returns `410 gone`; no response carries `interestCount` +- [x] Tests: fill with two member slugs records both and sets `filled`; `keepOpen` records them and stays `open`; a non-member slug → `422 not_a_member`; fill never creates a membership +- [x] Tests: accept with `fillRoleIds` fills those needs in the same commit; a role not in the application or not open → `422` +- [x] Need cards show the right one of Apply / Application sent / Member / Sign in to apply / Not taking applications for each caller state (component tests) +- [x] Browser: from `/help-wanted`, Apply on a need opens the apply form with it ticked; as admin, accept with "mark filled" and see the need leave the board +- [x] `npm run type-check && npm run lint && npm test` clean ## Risks / unknowns @@ -70,4 +70,54 @@ claim) removed; `interestCount` gone. ## Notes +- **This PR (#269) carries four plans**: [membership-admins](membership-admins.md), + [membership-follow](membership-follow.md), + [membership-applications](membership-applications.md) and this one, in + that order, each with its own in-progress and done commits. +- **First criterion left open: the data repo was not touched.** The + contract is written (`contracts/codeforphilly.org/help-wanted-roles/v3.json`, + commit `b85d5ea`) and the API mirror declares it with the interest sheet's + config and v2 contract removed (`748444d`), but adopting v3 and dropping + `help-wanted-interest` from `empty`, `fixture` and `legacy-import` happen + in codeforphilly-data, outside this change. Until then CI's + `check:sheet-configs` step fails on this PR. Order: run + `script:migrate-help-wanted-fills` on each branch while it still declares + v2 (it also counts interest records), drop the interest sheet only where + that count is 0, then adopt v3, then copy `empty`'s `.gitsheets/` back into + `apps/api/gitsheets/` (which also refreshes `contracts/sources.toml`, still + listing the interest contracts here). The rest of that criterion holds: no + runtime code reads or writes the sheet; the only mentions left are the + fills migration's count, a historical note in the old slug-references + migration, and the retired-contract comment in `packages/shared`. +- **Spec addition**: `a0ef925` gives the role shape `viewer {state, + appliedForThis}` and `projectHasActiveAdmin`, so a card picks its button + without loading the project. +- **The old slug-references migration** (`202610150400`) no longer touches + help-wanted-interest, since the sheet has no config now. It ran long ago; + only its sheet list, a comment and its test changed. +- **Card for an applicant whose application did not pick this need**: the + spec's list has no state for it, so the card shows no action (re-applying + is the project page's "View" / close flow). Raise it if a button is wanted. +- **Apply off the project page** loads the project and opens the same apply + form in place, so the card turns to "Application sent ✓" without leaving + the board. +- **Fill emails retired.** The old fill notification went with the + interest feature; the welcome email on accept covers the person joining. +- **Edit** reuses the post form, which now also takes the details link. +- **Browser smoke** (local API with made-up fixtures): from `/help-wanted` + as a non-member, Apply opened the form with the need ticked and the card + became "Application sent ✓"; as the admin, accepting with "Mark filled" + wrote the membership and the role in one commit and the board showed no + open roles. Also checked: a member sees "Member", the admin menu has Edit / + Mark filled / Close, and the fill dialog lists members and marked the need + filled. Several members and keep-open are covered by API tests only. +- Gate: check-contracts, type-check, lint, and tests (API 67 files / 792, + web 36 / 215, shared 5 / 120) clean; `npm run build` clean. + ## Follow-ups + +- codeforphilly-data: migrate, drop `help-wanted-interest`, adopt + `help-wanted-roles/v3` on `empty`, `fixture`, `legacy-import`, then + `published` at release; then refresh `apps/api/gitsheets/` from `empty`. +- Release after next: delete the `express-interest` 410 handler. +- The 90-day stale-need reminder stays deferred (`specs/deferred.md`). From 80f04da0cd6f2c783e1edbb6fb84c7b59a4daa6d Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:26:51 +0000 Subject: [PATCH 51/78] chore(api): sync sheet configs with codeforphilly-data v3 adoption apps/api/gitsheets/ mirrors codeforphilly-data's empty branch after it adopts project-memberships/v3, projects/v3 and help-wanted-roles/v3 and drops help-wanted-interest: sources.toml records the v3 provenance, and the v2 documents no sheet declares any more go. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../help-wanted-roles/v2.toml | 62 -------------- .../project-memberships/v2.toml | 40 ---------- .../codeforphilly.org/projects/v2.toml | 80 ------------------- apps/api/gitsheets/contracts/sources.toml | 12 +++ 4 files changed, 12 insertions(+), 182 deletions(-) delete mode 100644 apps/api/gitsheets/contracts/codeforphilly.org/help-wanted-roles/v2.toml delete mode 100644 apps/api/gitsheets/contracts/codeforphilly.org/project-memberships/v2.toml delete mode 100644 apps/api/gitsheets/contracts/codeforphilly.org/projects/v2.toml diff --git a/apps/api/gitsheets/contracts/codeforphilly.org/help-wanted-roles/v2.toml b/apps/api/gitsheets/contracts/codeforphilly.org/help-wanted-roles/v2.toml deleted file mode 100644 index d59ec563..00000000 --- a/apps/api/gitsheets/contracts/codeforphilly.org/help-wanted-roles/v2.toml +++ /dev/null @@ -1,62 +0,0 @@ -"$id" = "https://codeforphilly.org/help-wanted-roles/v2" -"$schema" = "http://json-schema.org/draft-07/schema#" -required = ["createdAt", "description", "id", "postedById", "projectSlug", "title", "updatedAt"] -title = "Help-wanted role" -type = "object" - -[properties.closedAt] -format = "date-time" -pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' -type = "string" - -[properties.commitmentHoursPerWeek] -minimum = 0 -type = "integer" - -[properties.createdAt] -format = "date-time" -pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' -type = "string" - -[properties.description] -minLength = 1 -type = "string" - -[properties.filledAt] -format = "date-time" -pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' -type = "string" - -[properties.filledById] -format = "uuid" -pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" -type = "string" - -[properties.id] -format = "uuid" -pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" -type = "string" - -[properties.postedById] -format = "uuid" -pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" -type = "string" - -[properties.projectSlug] -minLength = 1 -type = "string" - -[properties.status] -default = "open" -enum = ["open", "filled", "closed"] -type = "string" - -[properties.title] -maxLength = 120 -minLength = 1 -type = "string" - -[properties.updatedAt] -format = "date-time" -pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' -type = "string" diff --git a/apps/api/gitsheets/contracts/codeforphilly.org/project-memberships/v2.toml b/apps/api/gitsheets/contracts/codeforphilly.org/project-memberships/v2.toml deleted file mode 100644 index e603429c..00000000 --- a/apps/api/gitsheets/contracts/codeforphilly.org/project-memberships/v2.toml +++ /dev/null @@ -1,40 +0,0 @@ -"$id" = "https://codeforphilly.org/project-memberships/v2" -"$schema" = "http://json-schema.org/draft-07/schema#" -required = ["createdAt", "id", "joinedAt", "personSlug", "projectSlug", "updatedAt"] -title = "Project membership" -type = "object" - -[properties.createdAt] -format = "date-time" -pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' -type = "string" - -[properties.id] -format = "uuid" -pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" -type = "string" - -[properties.isMaintainer] -default = false -type = "boolean" - -[properties.joinedAt] -format = "date-time" -pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' -type = "string" - -[properties.personSlug] -minLength = 1 -type = "string" - -[properties.projectSlug] -minLength = 1 -type = "string" - -[properties.role] -type = "string" - -[properties.updatedAt] -format = "date-time" -pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' -type = "string" diff --git a/apps/api/gitsheets/contracts/codeforphilly.org/projects/v2.toml b/apps/api/gitsheets/contracts/codeforphilly.org/projects/v2.toml deleted file mode 100644 index b95fdf9e..00000000 --- a/apps/api/gitsheets/contracts/codeforphilly.org/projects/v2.toml +++ /dev/null @@ -1,80 +0,0 @@ -"$id" = "https://codeforphilly.org/projects/v2" -"$schema" = "http://json-schema.org/draft-07/schema#" -required = ["createdAt", "id", "slug", "title", "updatedAt"] -title = "Project" -type = "object" - -[properties.chatChannel] -pattern = "^[a-z0-9][a-z0-9_-]{0,40}$" -type = "string" - -[properties.createdAt] -format = "date-time" -pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' -type = "string" - -[properties.createdById] -format = "uuid" -pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" -type = "string" - -[properties.deletedAt] -format = "date-time" -pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' -type = "string" - -[properties.developersUrl] -format = "uri" -pattern = '^https:\/\/.*' -type = "string" - -[properties.featured] -default = false -type = "boolean" - -[properties.featuredImageKey] -type = "string" - -[properties.id] -format = "uuid" -pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" -type = "string" - -[properties.legacyId] -type = "integer" - -[properties.maintainerId] -format = "uuid" -pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" -type = "string" - -[properties.overview] -type = "string" - -[properties.slug] -pattern = "^[a-z0-9][a-z0-9-_]{1,79}$" -type = "string" - -[properties.stage] -default = "commenting" -enum = ["commenting", "bootstrapping", "prototyping", "testing", "maintaining", "drifting", "hibernating"] -type = "string" - -[properties.summary] -maxLength = 280 -type = "string" - -[properties.title] -maxLength = 200 -minLength = 1 -type = "string" - -[properties.updatedAt] -format = "date-time" -pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' -type = "string" - -[properties.usersUrl] -format = "uri" -pattern = '^https:\/\/.*' -type = "string" diff --git a/apps/api/gitsheets/contracts/sources.toml b/apps/api/gitsheets/contracts/sources.toml index 8c25e2ea..4b46aeb3 100644 --- a/apps/api/gitsheets/contracts/sources.toml +++ b/apps/api/gitsheets/contracts/sources.toml @@ -38,6 +38,10 @@ source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/7fe6b adopted = 2026-10-15T16:36:34.227Z source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/a60d22699d9336509fe88208206069bd2bd04364/contracts/codeforphilly.org/help-wanted-roles/v2.json" +["codeforphilly.org/help-wanted-roles/v3"] +adopted = 2026-11-29T22:24:32.42Z +source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/b85d5eadab61dce9f6041ceea21aa5d4a8582415/contracts/codeforphilly.org/help-wanted-roles/v3.json" + ["codeforphilly.org/people/v1"] adopted = 2026-10-14T03:31:24.46Z source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/7fe6b81a0bbd05b7a4e6896d55e181fdb61cfe42/contracts/codeforphilly.org/people/v1.json" @@ -62,6 +66,10 @@ source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/7fe6b adopted = 2026-10-15T16:36:30.365Z source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/a60d22699d9336509fe88208206069bd2bd04364/contracts/codeforphilly.org/project-memberships/v2.json" +["codeforphilly.org/project-memberships/v3"] +adopted = 2026-11-29T22:24:12.383Z +source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/dec168bf35cda956458360ddf3bfdc825d2a17a2/contracts/codeforphilly.org/project-memberships/v3.json" + ["codeforphilly.org/project-updates/v1"] adopted = 2026-10-14T03:31:31.221Z source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/7fe6b81a0bbd05b7a4e6896d55e181fdb61cfe42/contracts/codeforphilly.org/project-updates/v1.json" @@ -78,6 +86,10 @@ source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/7fe6b adopted = 2026-10-15T17:47:46.895Z source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/38870322de7e4f243a87e02d62b0603bd42498dc/contracts/codeforphilly.org/projects/v2.json" +["codeforphilly.org/projects/v3"] +adopted = 2026-11-29T22:24:13.457Z +source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/dec168bf35cda956458360ddf3bfdc825d2a17a2/contracts/codeforphilly.org/projects/v3.json" + ["codeforphilly.org/revocations/v1"] adopted = 2026-10-14T03:31:32.497Z source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/7fe6b81a0bbd05b7a4e6896d55e181fdb61cfe42/contracts/codeforphilly.org/revocations/v1.json" From bef6cb8462c622b53e73ef4dd7919434ff13819c Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:42:49 +0000 Subject: [PATCH 52/78] test(api): adopt the published v2 contracts before declaring v2 in the deploy-order test The vendored mirror now carries only v3, matching the data repo, so the deploy-order case vendors contracts/codeforphilly.org/<sheet>/v2.json itself before its branch declares v2. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/tests/migration-project-admins.test.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/apps/api/tests/migration-project-admins.test.ts b/apps/api/tests/migration-project-admins.test.ts index a62afb8c..d4cc68fe 100644 --- a/apps/api/tests/migration-project-admins.test.ts +++ b/apps/api/tests/migration-project-admins.test.ts @@ -22,6 +22,8 @@ import { createFullDataRepo } from './helpers/test-full-repo.js'; const exec = promisify(execFile); const GITSHEETS_CLI = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', 'node_modules', '.bin', 'gitsheets'); +/** The published contract documents (immutable), for adopting an older version. */ +const CONTRACTS_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', 'contracts', 'codeforphilly.org'); const NOW = '2026-05-15T18:42:00Z'; const id = (n: number): string => `01951a3c-0000-7000-8000-${String(n).padStart(12, '0')}`; @@ -146,6 +148,15 @@ describe('project-admins migration', () => { }); // Old-shape records fail v3, so adoption must come after the migration. await expect(exec(GITSHEETS_CLI, ['contracts', 'verify', '--git-dir', data.path, '--ref', 'main'])).rejects.toThrow(); + // The vendored mirror carries only v3 now, as the data repo does; vendor + // the published v2 documents so the branch can still declare them. + for (const sheet of ['project-memberships', 'projects']) { + await exec(GITSHEETS_CLI, [ + 'contracts', 'adopt', join(CONTRACTS_DIR, sheet, 'v2.json'), + '--git-dir', data.path, '--commit-to', 'main', '--message', `adopt ${sheet} v2`, + '--author-name', 'cfp test', '--author-email', 'test@example.org', + ]); + } await declare(2); const result = await migrateProjectAdmins({ dataRepo: data.path, branch: 'main' }); expect(result.membershipsMigrated).toBe(4); From 7458cf0637f04638518bbc7b8e749c990f2c564c Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:12:53 +0000 Subject: [PATCH 53/78] chore(plans): mark slack-account-link in-progress Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- plans/slack-account-link.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plans/slack-account-link.md b/plans/slack-account-link.md index 1b8cd7d3..39c5226a 100644 --- a/plans/slack-account-link.md +++ b/plans/slack-account-link.md @@ -1,5 +1,5 @@ --- -status: planned +status: in-progress depends: [] specs: - specs/api/slack-link.md From cb661635f40b40fe0acb576cc11c871fd67dee08 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:14:50 +0000 Subject: [PATCH 54/78] docs(specs): settle the gaps the Slack link and agent feed left open - slack-link: the code is 8 characters shown as two groups of four (the example had 7); the code response carries botDmUrl so the Account row can link the bot's name to a DM, as the screen asks; an account with no private profile is refused (the link lives there); redemption fails closed with no workspace configured; a 409 does not consume the code - auth: /me's slack field, which account.md already reads - conventions: the linking pair counts as credential endpoints - data-model: agent-grants contract is v2 (the new scopes change it) - agent-applications: application.visible is at notifiedAt (when the hold ended for a held one), so the cursor never skips it; events appear once a minute old; next is never null; where decidedBy, decidedVia and closedBy sit; the decide scope without its companions is refused at use (401), and a foreign workspace is not_project_admin - architecture: SLACK_TEAM_ID and SLACK_OPS_BOT_DM_URL Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- specs/api/agent-applications.md | 18 ++++++++++++++---- specs/api/auth.md | 9 ++++++--- specs/api/conventions.md | 2 +- specs/api/slack-link.md | 23 +++++++++++++++-------- specs/architecture.md | 2 ++ specs/data-model.md | 2 +- 6 files changed, 39 insertions(+), 17 deletions(-) diff --git a/specs/api/agent-applications.md b/specs/api/agent-applications.md index ad9d0591..8e89328d 100644 --- a/specs/api/agent-applications.md +++ b/specs/api/agent-applications.md @@ -50,17 +50,23 @@ not a stored log): | Type | When (`at`) | | ---- | ----------- | -| `application.visible` | the application's `visibleAt` arrived (admins were notified) | +| `application.visible` | admins were notified (`notifiedAt`: at once, or when a held application's hold ended) | | `application.reminder` | the 14-day reminder went out (`remindedAt`) | | `application.accepted` | accepted (`decidedAt`), with `decidedBy` and `decidedVia` | | `application.closed` | closed (`closedAt`), with `closedBy` and, for an admin close, `decidedBy` | +- `application` also carries `decidedBy` (`{ slug, fullName }`, or `null`), + `decidedVia` and `closedBy`, as they stand now. - `admins` lists the project's active admins; `slackUserId` is set only for an admin with a verified [Slack link](slack-link.md). No email address, ever. - Applications from deactivated applicants produce no events, and their earlier events drop out of the feed. - Ordered by `at`, then record id. The cursor is stable across restarts - (it encodes the last `at` and id). + (it encodes the last `at` and id). `metadata.next` is the cursor to pass + next time: the last event's, or, when there are none, the position reached, + so it is never `null`. +- An event appears once it is a minute old, so a write whose timestamp was + taken just before it committed cannot land behind a cursor already read. ## POST /api/agent/applications/:projectSlug/:personSlug/decision @@ -81,7 +87,7 @@ Records an accept or a close that a project admin made in Slack. | Field | Required | Notes | | ----- | -------- | ----- | | decision | yes | `accept` \| `close` | -| onBehalfOf | yes | The Slack user who decided. Must resolve through a verified link to a person who is, now, an active project admin of `:projectSlug` ([authorization.md → On behalf of a project admin](../behaviors/authorization.md#on-behalf-of-a-project-admin)). | +| onBehalfOf | yes | The Slack user who decided; `slackTeamId` must be the workspace the site serves. Must resolve through a verified link to a person who is, now, an active project admin of `:projectSlug` ([authorization.md → On behalf of a project admin](../behaviors/authorization.md#on-behalf-of-a-project-admin)). | | role, fillRoleIds | no | As for the site's accept ([projects-applications.md](projects-applications.md)). | | note | no | For `close`: emailed to the applicant, never stored. | @@ -100,8 +106,12 @@ screen. ### Errors +- `401 unauthenticated` — no grant with `projects:applications:decide`, or a + grant that holds it without `projects:applications:read` and `slack:link` + (refused at use as well as at mint) - `403 forbidden` (`error.code = "not_project_admin"`) — the Slack user is not - linked, or the linked person is not an active admin of this project + linked (or names another workspace), or the linked person is not an active + admin of this project - `404 not_found` — no open, visible application from that person - `429 rate_limited` — more than 30 decisions per agent in 24 hours diff --git a/specs/api/auth.md b/specs/api/auth.md index cb69e3b4..b887bb45 100644 --- a/specs/api/auth.md +++ b/specs/api/auth.md @@ -223,7 +223,7 @@ Empty body. The flow is purely redirect-driven. ## GET /api/auth/me -Returns the current Person (full PersonResponse shape — see [api/people.md](people.md)) plus `accountLevel`, `hasGitHubLink`, and `lastLoginMethod`. Used by the SPA on load to bootstrap the auth context and decide whether to render the "Connect GitHub" banner. +Returns the current Person (full PersonResponse shape — see [api/people.md](people.md)) plus `accountLevel`, `hasGitHubLink`, `lastLoginMethod`, and `slack`. Used by the SPA on load to bootstrap the auth context and decide whether to render the "Connect GitHub" banner. ### Response — 200 @@ -234,14 +234,17 @@ Returns the current Person (full PersonResponse shape — see [api/people.md](pe "person": { /* PersonResponse */ }, "accountLevel": "staff", "hasGitHubLink": true, - "lastLoginMethod": "github" + "lastLoginMethod": "github", + "slack": { "linked": true, "linkedAt": "2026-11-20T…" } } } ``` `hasGitHubLink` is `Person.githubUserId !== null`. `lastLoginMethod` is one of `"github" | "legacy_password" | "password_reset"`; the SPA can use it to render UI hints (e.g., "Signed in via password — connect GitHub for faster sign-in next time" inline on `/account`). -If no session, returns 200 with `data.person = null`, `data.accountLevel = "anonymous"`, `hasGitHubLink = false`, `lastLoginMethod = null`. (We deliberately do not 401 here — the frontend calls this on every page load including public pages.) +`slack` is whether the person has a verified [Slack link](slack-link.md) and since when (`{ linked: false, linkedAt: null }` when not); it never carries the Slack user id. + +If no session, returns 200 with `data.person = null`, `data.accountLevel = "anonymous"`, `hasGitHubLink = false`, `lastLoginMethod = null`, `slack = null`. (We deliberately do not 401 here — the frontend calls this on every page load including public pages.) The PersonResponse for self includes `email` (fetched from PrivateProfile) and `newsletter` state. For staff viewing other people, see [api/people.md](people.md) on which private fields are visible. diff --git a/specs/api/conventions.md b/specs/api/conventions.md index 5a4482ce..009c89dc 100644 --- a/specs/api/conventions.md +++ b/specs/api/conventions.md @@ -165,7 +165,7 @@ Only `/api/**` requests are counted. The SPA shell, its assets, and image thumbn - Unauthenticated reads: 300 requests / minute / IP - Authenticated reads: 300 requests / minute / account - Writes: 30 requests / minute / account (30 / minute / IP when anonymous) -- Credential endpoints: 20 requests / minute / IP. These are the routes that accept or mint a credential: `POST /api/auth/login`, `/api/auth/github/start` and `/callback`, `/api/auth/link-github`, `/api/auth/password-reset/*`, and `POST /api/account-claim/by-password`. Session reads such as `GET /api/auth/me` (called on every page load) and `/api/auth/refresh` are ordinary reads. +- Credential endpoints: 20 requests / minute / IP. These are the routes that accept or mint a credential: `POST /api/auth/login`, `/api/auth/github/start` and `/callback`, `/api/auth/link-github`, `/api/auth/password-reset/*`, `POST /api/account-claim/by-password`, and the Slack linking pair `POST /api/account/slack-link/code` and `POST /api/agent/slack-links` ([slack-link.md](slack-link.md)). Session reads such as `GET /api/auth/me` (called on every page load) and `/api/auth/refresh` are ordinary reads. Per-IP caps assume the gateway delivers the real client address in the first `X-Forwarded-For` hop (the NodeBalancer speaks PROXY protocol to Envoy — cfp-live-cluster #203). diff --git a/specs/api/slack-link.md b/specs/api/slack-link.md index 4b0c2449..d3ffb77d 100644 --- a/specs/api/slack-link.md +++ b/specs/api/slack-link.md @@ -25,31 +25,37 @@ No body. Returns a fresh code and invalidates any earlier unredeemed code for the caller. ```json -{ "success": true, "data": { "code": "K7Q-4MZP", "expiresAt": "..." } } +{ "success": true, "data": { "code": "K7QW-4MZP", "expiresAt": "...", "botDmUrl": "https://…" } } ``` -- 8 characters from an unambiguous alphabet (no `0/O`, `1/I/L`), shown with a - hyphen; matched case-insensitively, hyphen optional. +- 8 characters from an unambiguous alphabet (no `0/O`, `1/I/L`), shown as two + groups of four with a hyphen; matched case-insensitively, hyphen optional. +- `botDmUrl` is a link that opens a direct message with the ops bot in Slack, + from configuration (`SLACK_OPS_BOT_DM_URL`), or `null` when none is set; the + Account screen links the bot's name to it. - Lives **10 minutes**, redeemable once. - Held **in memory only**, as a hash; a restart drops pending codes and the member asks for a new one. Codes are never written to either store or a log. - Counts as a credential endpoint for rate limiting ([conventions.md](conventions.md#rate-limiting)); at most 5 codes per account per hour. -- Refused for agent accounts (`422`). +- Refused for agent accounts (`422`, `error.code = "agent_account"`) and for + an account with no private profile (`422`, `error.code = + "no_private_profile"`), since the link is stored there. ## POST /api/agent/slack-links The bot calls this when a member DMs it a code. ```json -{ "code": "K7Q-4MZP", "slackTeamId": "T…", "slackUserId": "U…" } +{ "code": "K7QW-4MZP", "slackTeamId": "T…", "slackUserId": "U…" } ``` On success, in the same request: sets `PrivateProfile.slack = { teamId, userId, linkedAt }` for the person who issued the code and consumes the code. -`slackTeamId` must be the workspace the site serves (configured; mismatch -`422`). +`slackTeamId` must be the workspace the site serves (`SLACK_TEAM_ID`; +mismatch `422`). With no workspace configured every redemption is refused +(`422`): the site fails closed rather than link to an unknown workspace. ```json { "success": true, "data": { "personSlug": "jane", "linkedAt": "..." } } @@ -63,7 +69,8 @@ The bot replies to the member in the DM; the site emails nothing. code; one response for all three - `409 conflict` (`error.code = "slack_user_linked"`) — that Slack user is already linked to a different site account; the member disconnects the other - account first + account first. The code is not consumed, so it still works for its ten + minutes once they have. - `429 rate_limited` — more than 10 failed redemptions per agent per hour (guessing); further calls are refused for an hour diff --git a/specs/architecture.md b/specs/architecture.md index a5fed30f..b2977777 100644 --- a/specs/architecture.md +++ b/specs/architecture.md @@ -181,6 +181,8 @@ Runtime configuration (sealed-secrets in our cluster): | `SAML_PRIVATE_KEY` / `SAML_CERTIFICATE` | Slack SAML IdP cert chain — see [api/saml.md](api/saml.md) | | `SAML_ENTITY_ID` | Optional. Stable SAML IdP entity ID / assertion `Issuer` (default `https://codeforphilly.org/api/saml/slack/metadata`). Deliberately independent of `CFP_SITE_HOST` so cutover doesn't change the identifier Slack has on file — see [api/saml.md#idp-identity-and-hosts](api/saml.md#idp-identity-and-hosts). | | `SLACK_TEAM_HOST` | Slack workspace host (default `codeforphilly.slack.com`). Used by the `/chat` redirect ([api/chat](screens/chat.md)) and the SAML SP entity binding (ACS URL, NameQualifier). Never used for our own IdP entity ID or endpoint URLs. | +| `SLACK_TEAM_ID` | The Slack workspace id (`T…`) the site serves. A [Slack link](api/slack-link.md) or an agent's on-behalf decision naming another workspace is refused; unset, no link can be made. | +| `SLACK_OPS_BOT_DM_URL` | Optional. A link that opens a direct message with the ops bot; the Account screen's Slack row links the bot's name to it. | | `POSTMARK_SERVER_TOKEN` | Optional. When set, mutates the notifier from the no-op `LoggingNotifier` to the live `EmailNotifier` (Postmark transport). | | `POSTMARK_MESSAGE_STREAM` | Optional. Postmark message stream for outbound mail (default `outbound`). | | `CFP_NOTIFICATION_FROM` | Required when `POSTMARK_SERVER_TOKEN` is set; the `From:` address on outbound mail. | diff --git a/specs/data-model.md b/specs/data-model.md index 4ce5cf46..0be806e3 100644 --- a/specs/data-model.md +++ b/specs/data-model.md @@ -206,7 +206,7 @@ is (its hash is private — [private-storage.md](behaviors/private-storage.md)). **Sheet:** `agent-grants` **Path template:** `agent-grants/${personSlug}/${id}.toml` -**Contract:** `codeforphilly.org/agent-grants/v1` +**Contract:** `codeforphilly.org/agent-grants/v2` (v2 adds the Slack and applications scopes) | Field | Type | Notes | | ------- | ------ | ------- | From 842bcb2c91140a1327c52ae85a55d40277404d04 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:14:54 +0000 Subject: [PATCH 55/78] feat(shared): the Slack and applications scopes, and the Slack link on private profiles AGENT_SCOPES gains slack:link, projects:applications:read and projects:applications:decide, with AGENT_SCOPE_REQUIRES naming each scope's companions. agent-grants/v2 is generated and vendored into the API mirror (with gitsheets contracts adopt; provenance lands when the data repo adopts from the published URL). PrivateProfile gains the optional slack { teamId, userId, linkedAt }. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/gitsheets/agent-grants.toml | 2 +- .../codeforphilly.org/agent-grants/v2.toml | 46 +++++++++++++ .../codeforphilly.org/agent-grants/v2.json | 65 +++++++++++++++++++ packages/shared/src/contracts.ts | 3 +- packages/shared/src/schemas/agent-grant.ts | 24 +++++-- packages/shared/src/schemas/index.ts | 4 +- .../shared/src/schemas/private-profile.ts | 12 ++++ 7 files changed, 148 insertions(+), 8 deletions(-) create mode 100644 apps/api/gitsheets/contracts/codeforphilly.org/agent-grants/v2.toml create mode 100644 contracts/codeforphilly.org/agent-grants/v2.json diff --git a/apps/api/gitsheets/agent-grants.toml b/apps/api/gitsheets/agent-grants.toml index aaebbb51..105cdd92 100644 --- a/apps/api/gitsheets/agent-grants.toml +++ b/apps/api/gitsheets/agent-grants.toml @@ -7,4 +7,4 @@ root = "agent-grants" # Public on purpose: which programs may act, with which scopes, granted by # whom, until when. The token and its hash are never here; the hash lives in # the site's private store. The only writer is the site. -implements = ["codeforphilly.org/agent-grants/v1"] +implements = ["codeforphilly.org/agent-grants/v2"] diff --git a/apps/api/gitsheets/contracts/codeforphilly.org/agent-grants/v2.toml b/apps/api/gitsheets/contracts/codeforphilly.org/agent-grants/v2.toml new file mode 100644 index 00000000..32d71cbf --- /dev/null +++ b/apps/api/gitsheets/contracts/codeforphilly.org/agent-grants/v2.toml @@ -0,0 +1,46 @@ +"$id" = "https://codeforphilly.org/agent-grants/v2" +"$schema" = "http://json-schema.org/draft-07/schema#" +required = ["createdAt", "createdBySlug", "expiresAt", "id", "label", "personSlug", "scopes"] +title = "Agent grant" +type = "object" + +[properties.createdAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.createdBySlug] +minLength = 1 +type = "string" + +[properties.expiresAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.id] +format = "uuid" +pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" +type = "string" + +[properties.label] +maxLength = 80 +minLength = 1 +type = "string" + +[properties.personSlug] +minLength = 1 +type = "string" + +[properties.revokedAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.scopes] +minItems = 1 +type = "array" + +[properties.scopes.items] +enum = ["moderation:read", "moderation:vote", "moderation:purge", "slack:link", "projects:applications:read", "projects:applications:decide"] +type = "string" diff --git a/contracts/codeforphilly.org/agent-grants/v2.json b/contracts/codeforphilly.org/agent-grants/v2.json new file mode 100644 index 00000000..42e97f98 --- /dev/null +++ b/contracts/codeforphilly.org/agent-grants/v2.json @@ -0,0 +1,65 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://codeforphilly.org/agent-grants/v2", + "title": "Agent grant", + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "personSlug": { + "type": "string", + "minLength": 1 + }, + "label": { + "type": "string", + "minLength": 1, + "maxLength": 80 + }, + "scopes": { + "minItems": 1, + "type": "array", + "items": { + "type": "string", + "enum": [ + "moderation:read", + "moderation:vote", + "moderation:purge", + "slack:link", + "projects:applications:read", + "projects:applications:decide" + ] + } + }, + "createdAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + "createdBySlug": { + "type": "string", + "minLength": 1 + }, + "expiresAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + "revokedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + } + }, + "required": [ + "createdAt", + "createdBySlug", + "expiresAt", + "id", + "label", + "personSlug", + "scopes" + ] +} diff --git a/packages/shared/src/contracts.ts b/packages/shared/src/contracts.ts index f87b3128..3afdb924 100644 --- a/packages/shared/src/contracts.ts +++ b/packages/shared/src/contracts.ts @@ -66,7 +66,8 @@ export const SHEET_CONTRACTS = { // v1 was hand-authored before contracts were generated; v2 is the first // generated version (it adds the evaluatedAt datetime pattern). 'person-evaluations': { schema: PersonEvaluationSchema, version: 2, title: 'Person evaluation' }, - 'agent-grants': { schema: AgentGrantSchema, version: 1, title: 'Agent grant' }, + // v2 adds the Slack and applications scopes (specs/api/agents.md → Grants). + 'agent-grants': { schema: AgentGrantSchema, version: 2, title: 'Agent grant' }, 'spam-purges': { schema: SpamPurgeSchema, version: 1, title: 'Spam purge' }, } as const satisfies Record<string, SheetContract>; diff --git a/packages/shared/src/schemas/agent-grant.ts b/packages/shared/src/schemas/agent-grant.ts index a9d42a27..a07f8eac 100644 --- a/packages/shared/src/schemas/agent-grant.ts +++ b/packages/shared/src/schemas/agent-grant.ts @@ -4,13 +4,29 @@ import { references } from '../references.js'; /** * The scopes an agent grant may carry — specs/api/agents.md → Grants. There - * are no others; `moderation:purge` is never implied by another scope and a - * grant carrying it must also carry `moderation:read` (enforced where grants - * are minted, not here, so the published contract stays a plain list). + * are no others. `moderation:purge` is never implied by another scope and a + * grant carrying it must also carry `moderation:read`; + * `projects:applications:decide` must also carry `projects:applications:read` + * and `slack:link` ({@link AGENT_SCOPE_REQUIRES}). Those rules are enforced + * where grants are minted and where the scope is used, not here, so the + * published contract stays a plain list. */ -export const AGENT_SCOPES = ['moderation:read', 'moderation:vote', 'moderation:purge'] as const; +export const AGENT_SCOPES = [ + 'moderation:read', + 'moderation:vote', + 'moderation:purge', + 'slack:link', + 'projects:applications:read', + 'projects:applications:decide', +] as const; export type AgentScope = (typeof AGENT_SCOPES)[number]; +/** The companion scopes a scope cannot be granted (or used) without. */ +export const AGENT_SCOPE_REQUIRES: Readonly<Partial<Record<AgentScope, readonly AgentScope[]>>> = { + 'moderation:purge': ['moderation:read'], + 'projects:applications:decide': ['projects:applications:read', 'slack:link'], +}; + /** * A scoped API grant for an agent account (an automated moderator) — the * `agent-grants` sheet, `agent-grants/${personSlug}/${id}`. Public: which diff --git a/packages/shared/src/schemas/index.ts b/packages/shared/src/schemas/index.ts index 9ea32695..d1d00414 100644 --- a/packages/shared/src/schemas/index.ts +++ b/packages/shared/src/schemas/index.ts @@ -55,7 +55,7 @@ export { RevocationSchema } from './revocation.js'; export type { Revocation } from './revocation.js'; export { PrivateProfileSchema } from './private-profile.js'; -export type { PrivateProfile, Newsletter, GitHubFacts, EmailBounce } from './private-profile.js'; +export type { PrivateProfile, Newsletter, GitHubFacts, EmailBounce, SlackLink } from './private-profile.js'; export { LegacyPasswordCredentialSchema } from './legacy-password-credential.js'; export type { LegacyPasswordCredential } from './legacy-password-credential.js'; @@ -79,7 +79,7 @@ export { } from './person-evaluation.js'; export type { PersonEvaluation, EvaluatorKind } from './person-evaluation.js'; -export { AgentGrantSchema, AgentGrantSecretSchema, AGENT_SCOPES } from './agent-grant.js'; +export { AgentGrantSchema, AgentGrantSecretSchema, AGENT_SCOPES, AGENT_SCOPE_REQUIRES } from './agent-grant.js'; export type { AgentGrant, AgentGrantSecret, AgentScope } from './agent-grant.js'; export { diff --git a/packages/shared/src/schemas/private-profile.ts b/packages/shared/src/schemas/private-profile.ts index aaaa6dc8..fbf092ed 100644 --- a/packages/shared/src/schemas/private-profile.ts +++ b/packages/shared/src/schemas/private-profile.ts @@ -35,6 +35,16 @@ const EmailBounceSchema = z.object({ inactive: z.boolean().optional(), }); +/** + * The verified link to a Slack user (specs/api/slack-link.md). Set and + * cleared only by the linking endpoints; the only mapping anything routes on. + */ +const SlackLinkSchema = z.object({ + teamId: z.string().regex(/^[A-Z0-9]{2,32}$/), + userId: z.string().regex(/^[A-Z0-9]{2,32}$/), + linkedAt: z.string().datetime({ offset: true }), +}); + export const PrivateProfileSchema = z.object({ personId: z.string().uuid(), email: z.string().email().toLowerCase(), @@ -44,6 +54,7 @@ export const PrivateProfileSchema = z.object({ /** Set whenever the SAML IdP issues an assertion for this person. */ lastSlackSsoAt: z.string().datetime({ offset: true }).nullable().optional(), emailBounce: EmailBounceSchema.nullable().optional(), + slack: SlackLinkSchema.nullable().optional(), updatedAt: z.string().datetime({ offset: true }), }); @@ -51,3 +62,4 @@ export type PrivateProfile = z.infer<typeof PrivateProfileSchema>; export type Newsletter = z.infer<typeof NewsletterSchema>; export type GitHubFacts = z.infer<typeof GitHubFactsSchema>; export type EmailBounce = z.infer<typeof EmailBounceSchema>; +export type SlackLink = z.infer<typeof SlackLinkSchema>; From c352bace6d5ae9fe862c301355ac1427e0e18b78 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:19:19 +0000 Subject: [PATCH 56/78] feat(api): index Slack links on private profiles and keep them through profile rewrites MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit bySlackUserId (teamId:userId → personId) is rebuilt with the other private indices, so a link, a disconnect or a purge is reflected at once. The profile rewrites on a GitHub email change, an account claim, a claim merge and a staff email edit rebuilt the profile field by field and would have dropped the link; they carry it now. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/src/services/account-claim.ts | 3 +++ apps/api/src/services/github-account.ts | 2 ++ apps/api/src/services/person.write.ts | 1 + apps/api/src/store/private/base.ts | 14 ++++++++++++++ apps/api/src/store/private/interface.ts | 4 ++++ 5 files changed, 24 insertions(+) diff --git a/apps/api/src/services/account-claim.ts b/apps/api/src/services/account-claim.ts index ea03056a..d3c501c0 100644 --- a/apps/api/src/services/account-claim.ts +++ b/apps/api/src/services/account-claim.ts @@ -560,6 +560,7 @@ export class AccountClaimService { email: primaryEmail.toLowerCase(), emailRefreshedAt: now, newsletter: currentProfile?.newsletter ?? null, + slack: currentProfile?.slack ?? null, updatedAt: now, }); tx.private.putProfile(profile); @@ -704,6 +705,8 @@ export class AccountClaimService { email: requesterProfile.email, emailRefreshedAt: now, newsletter: claimedProfile?.newsletter ?? requesterProfile.newsletter ?? null, + // Same human: a Slack link made from either account survives the merge. + slack: requesterProfile.slack ?? claimedProfile?.slack ?? null, updatedAt: now, }); tx.private.putProfile(merged); diff --git a/apps/api/src/services/github-account.ts b/apps/api/src/services/github-account.ts index 4c2f48f6..e51c1df5 100644 --- a/apps/api/src/services/github-account.ts +++ b/apps/api/src/services/github-account.ts @@ -165,6 +165,8 @@ export class GitHubAccountService { newsletter: currentProfile?.newsletter ?? null, lastSlackSsoAt: currentProfile?.lastSlackSsoAt ?? null, emailBounce: currentProfile?.emailBounce ?? null, + // The Slack link is the person's, not the address's (slack-link.md). + slack: currentProfile?.slack ?? null, github: identity.user ? githubFactsFrom(identity.user, 'ok', now) : (currentProfile?.github ?? null), updatedAt: now, }); diff --git a/apps/api/src/services/person.write.ts b/apps/api/src/services/person.write.ts index 4c0f400f..9c103085 100644 --- a/apps/api/src/services/person.write.ts +++ b/apps/api/src/services/person.write.ts @@ -173,6 +173,7 @@ export class PersonWriteService { email: input.email.toLowerCase(), emailRefreshedAt: now, newsletter: existingProfile?.newsletter ?? null, + slack: existingProfile?.slack ?? null, updatedAt: now, }); tx.private.putProfile(profile); diff --git a/apps/api/src/store/private/base.ts b/apps/api/src/store/private/base.ts index d91fc484..a165949e 100644 --- a/apps/api/src/store/private/base.ts +++ b/apps/api/src/store/private/base.ts @@ -14,6 +14,11 @@ import type { } from '@cfp/shared/schemas'; import type { PrivateIndices, PrivateStore, PrivateStoreTx } from './interface.js'; +/** The `bySlackUserId` key: one site account per Slack user within a workspace. */ +export function slackKey(teamId: string, userId: string): string { + return `${teamId}:${userId}`; +} + /** * Shared in-memory state and logic for both PrivateStore backends. * @@ -34,6 +39,7 @@ export abstract class BasePrivateStore implements PrivateStore { byEmail: new Map(), byUnsubscribeToken: new Map(), legacyPasswordByPersonId: this.legacyPasswords, + bySlackUserId: new Map(), }; /** Fetch the raw bytes of a .jsonl file by key. Return null if absent. */ @@ -84,6 +90,7 @@ export abstract class BasePrivateStore implements PrivateStore { private rebuildIndices(): void { this.indices.byEmail.clear(); this.indices.byUnsubscribeToken.clear(); + this.indices.bySlackUserId.clear(); this.grantIdByHash.clear(); for (const secret of this.grantSecrets.values()) this.grantIdByHash.set(secret.tokenHash, secret.grantId); @@ -93,6 +100,9 @@ export abstract class BasePrivateStore implements PrivateStore { if (token) { this.indices.byUnsubscribeToken.set(token, profile.personId); } + if (profile.slack) { + this.indices.bySlackUserId.set(slackKey(profile.slack.teamId, profile.slack.userId), profile.personId); + } } } @@ -117,6 +127,10 @@ export abstract class BasePrivateStore implements PrivateStore { return this.indices.byEmail.get(email.toLowerCase()) ?? null; } + findPersonIdBySlackUser(teamId: string, userId: string): string | null { + return this.indices.bySlackUserId.get(slackKey(teamId, userId)) ?? null; + } + async *listAllProfiles(): AsyncIterable<PrivateProfile> { for (const profile of this.profiles.values()) { yield profile; diff --git a/apps/api/src/store/private/interface.ts b/apps/api/src/store/private/interface.ts index a71acd3d..1bc4b7f3 100644 --- a/apps/api/src/store/private/interface.ts +++ b/apps/api/src/store/private/interface.ts @@ -14,6 +14,8 @@ export interface PrivateIndices { readonly byUnsubscribeToken: Map<string, string>; /** personId → LegacyPasswordCredential */ readonly legacyPasswordByPersonId: Map<string, LegacyPasswordCredential>; + /** `${teamId}:${userId}` → personId, from `slack` on profiles (specs/data-model.md). */ + readonly bySlackUserId: Map<string, string>; } /** @@ -57,6 +59,8 @@ export interface PrivateStore { putProfile(profile: PrivateProfile): Promise<void>; deleteProfile(personId: string): Promise<void>; findPersonIdByEmail(email: string): Promise<string | null>; + /** The person whose verified Slack link is this workspace's user, or null. */ + findPersonIdBySlackUser(teamId: string, userId: string): string | null; listAllProfiles(): AsyncIterable<PrivateProfile>; // --- Legacy passwords --- From 0e0df5fec72a5feef24a1999210628f9ef29b8b3 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:19:19 +0000 Subject: [PATCH 57/78] feat(api): Slack linking codes, the agent's redemption, and me.slack POST /api/account/slack-link/code issues an 8-character code (two groups of four, no 0/O/1/I/L), hashed in memory for ten minutes, one live code per person, five per hour. POST /api/agent/slack-links (slack:link) redeems it for the Slack user who sent it: unknown, expired, used and orphaned codes answer one 404 code_invalid, ten failures lock the agent out for an hour, another workspace (or none configured) is 422, and a Slack user linked elsewhere is 409 without spending the code. DELETE /api/account/slack-link clears it. /api/auth/me reports { linked, linkedAt }, never the user id. Minting enforces every scope's companions; /api/agent/* routes check scope and companions before the body (401). Both linking paths count as credential endpoints. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/src/app.ts | 2 + apps/api/src/auth/caller.ts | 24 +- apps/api/src/env.ts | 10 + apps/api/src/lib/errors.ts | 6 +- apps/api/src/plugins/rate-limit.ts | 3 + apps/api/src/plugins/services.ts | 6 + apps/api/src/routes/auth.ts | 4 + apps/api/src/routes/slack-link.ts | 68 +++++ apps/api/src/services/agents.ts | 17 +- apps/api/src/services/slack-link.ts | 222 ++++++++++++++++ apps/api/tests/helpers/agent-fixtures.ts | 6 +- apps/api/tests/slack-link.test.ts | 323 +++++++++++++++++++++++ 12 files changed, 681 insertions(+), 10 deletions(-) create mode 100644 apps/api/src/routes/slack-link.ts create mode 100644 apps/api/src/services/slack-link.ts create mode 100644 apps/api/tests/slack-link.test.ts diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 32e9a89c..5f44cbc6 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -68,6 +68,7 @@ import { attachmentRoutes } from './routes/attachments.js'; import { chatRoutes } from './routes/chat.js'; import { moderationRoutes } from './routes/moderation.js'; import { agentRoutes } from './routes/agents.js'; +import { slackLinkRoutes } from './routes/slack-link.js'; import { webhookRoutes } from './routes/webhooks.js'; import { samlRoutes } from './routes/saml.js'; import { internalRoutes } from './routes/internal.js'; @@ -223,6 +224,7 @@ export async function buildApp(opts: BuildAppOptions = {}): Promise<FastifyInsta await fastify.register(chatRoutes); await fastify.register(moderationRoutes); await fastify.register(agentRoutes); + await fastify.register(slackLinkRoutes); await fastify.register(webhookRoutes); await fastify.register(samlRoutes); await fastify.register(internalRoutes); diff --git a/apps/api/src/auth/caller.ts b/apps/api/src/auth/caller.ts index fa4b3c1f..512e5783 100644 --- a/apps/api/src/auth/caller.ts +++ b/apps/api/src/auth/caller.ts @@ -5,10 +5,10 @@ * Anyone who doesn't qualify gets `404 not_found`, like the rest of * `/api/admin`: the endpoints' existence is not a signal. */ -import type { AgentScope } from '@cfp/shared/schemas'; +import { AGENT_SCOPE_REQUIRES, type AgentScope } from '@cfp/shared/schemas'; import type { FastifyRequest } from 'fastify'; -import { ApiNotFoundError } from '../lib/errors.js'; +import { ApiNotFoundError, UnauthenticatedError } from '../lib/errors.js'; import { agentSessionContext, type AgentPrincipal } from './agent-grant.js'; import type { SessionContext } from './middleware.js'; @@ -57,3 +57,23 @@ export function administratorCaller(request: FastifyRequest): SessionContext { } throw new ApiNotFoundError('Not found'); } + +/** + * The agent on an `/api/agent/*` route: a grant carrying `scope` and every + * companion that scope requires (specs/api/agents.md → Grants). A grant + * minted before a companion rule, or a record written by hand, that lacks + * one is refused here too: the check fails closed at use, not only at mint. + * Anyone else, signed-in people and staff included, is anonymous to these + * routes → `401`. + */ +export function agentScopeCaller( + request: FastifyRequest, + scope: AgentScope, +): Extract<ModerationCaller, { kind: 'agent' }> { + const agent = request.agent; + const needed = [scope, ...(AGENT_SCOPE_REQUIRES[scope] ?? [])]; + if (agent && needed.every((s) => agent.scopes.has(s))) { + return { kind: 'agent', session: agentSessionContext(agent), agent }; + } + throw new UnauthenticatedError('An agent grant with this scope is required'); +} diff --git a/apps/api/src/env.ts b/apps/api/src/env.ts index c9f1a2ee..79d0cdf3 100644 --- a/apps/api/src/env.ts +++ b/apps/api/src/env.ts @@ -117,6 +117,14 @@ export const EnvSchema = z.object({ * See specs/api/webhooks.md. */ POSTMARK_WEBHOOK_SECRET: z.string().min(16).optional(), + /** + * The Slack workspace id (`T…`) the site serves. A Slack link or an + * agent's on-behalf decision naming another workspace is refused; unset, + * no link can be made (specs/api/slack-link.md). + */ + SLACK_TEAM_ID: z.string().regex(/^T[A-Z0-9]+$/).optional(), + /** Optional link that opens a DM with the ops bot, for the Account screen. */ + SLACK_OPS_BOT_DM_URL: z.url().optional(), }); export type Env = z.infer<typeof EnvSchema>; @@ -159,6 +167,8 @@ export const envJsonSchema = { POSTMARK_SERVER_TOKEN: { type: 'string' }, POSTMARK_MESSAGE_STREAM: { type: 'string', default: 'outbound' }, POSTMARK_WEBHOOK_SECRET: { type: 'string', minLength: 16 }, + SLACK_TEAM_ID: { type: 'string', pattern: '^T[A-Z0-9]+$' }, + SLACK_OPS_BOT_DM_URL: { type: 'string', pattern: '^https://' }, CFP_NOTIFICATION_FROM: { type: 'string', default: 'Code for Philly <notifications@codeforphilly.org>', diff --git a/apps/api/src/lib/errors.ts b/apps/api/src/lib/errors.ts index aeb15ef1..c41a951e 100644 --- a/apps/api/src/lib/errors.ts +++ b/apps/api/src/lib/errors.ts @@ -68,9 +68,11 @@ export class ForbiddenError extends Error { /** Thrown when a resource is not found (404). */ export class ApiNotFoundError extends Error { - constructor(message = 'Not found') { + readonly code: string; + constructor(message = 'Not found', code = 'not_found') { super(message); this.name = 'ApiNotFoundError'; + this.code = code; } } @@ -144,7 +146,7 @@ export function mapError( } if (err instanceof ApiNotFoundError) { - void reply.code(404).send(errorResponse('not_found', err.message, traceId)); + void reply.code(404).send(errorResponse(err.code, err.message, traceId)); return; } diff --git a/apps/api/src/plugins/rate-limit.ts b/apps/api/src/plugins/rate-limit.ts index a2399479..c0ca370e 100644 --- a/apps/api/src/plugins/rate-limit.ts +++ b/apps/api/src/plugins/rate-limit.ts @@ -89,6 +89,9 @@ const CREDENTIAL_PATHS = [ '/api/auth/link-github', '/api/auth/password-reset/', '/api/account-claim/by-password', + // The Slack linking pair mints and accepts a one-time code (slack-link.md). + '/api/account/slack-link/code', + '/api/agent/slack-links', ]; function pathOf(url: string): string { diff --git a/apps/api/src/plugins/services.ts b/apps/api/src/plugins/services.ts index b37a5bdc..b10a457c 100644 --- a/apps/api/src/plugins/services.ts +++ b/apps/api/src/plugins/services.ts @@ -43,6 +43,7 @@ import { ServerClient } from 'postmark'; import { FollowerMailer } from '../services/follower-mail.js'; import { ProjectApplicationService } from '../services/project-application.js'; import { ApplicationNotices } from '../services/application-notices.js'; +import { SlackLinkService } from '../services/slack-link.js'; declare module 'fastify' { interface FastifyInstance { @@ -74,6 +75,7 @@ declare module 'fastify' { agents: AgentService; agentPurge: AgentPurgeService; spamPurges: SpamPurgeLogService; + slackLinks: SlackLinkService; }; /** Shared in-memory state — write routes call StateApply.apply against this. */ inMemoryState: InMemoryState; @@ -198,6 +200,10 @@ async function servicesPlugin(fastify: FastifyInstance): Promise<void> { webUrl: dataRepoWebUrl(fastify.config.CFP_DATA_REMOTE), branch: fastify.config.CFP_DATA_BRANCH ?? 'published', }), + slackLinks: new SlackLinkService(state, fastify.store.private, { + teamId: fastify.config.SLACK_TEAM_ID, + botDmUrl: fastify.config.SLACK_OPS_BOT_DM_URL, + }), }); } diff --git a/apps/api/src/routes/auth.ts b/apps/api/src/routes/auth.ts index 6db22abd..6c95e103 100644 --- a/apps/api/src/routes/auth.ts +++ b/apps/api/src/routes/auth.ts @@ -14,6 +14,7 @@ import { createHash, randomBytes } from 'node:crypto'; import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; import { errors as JoseErrors } from 'jose'; import { ok } from '../lib/response.js'; +import { slackStatus } from '../services/slack-link.js'; import { UnauthenticatedError, ConflictError, ApiNotFoundError } from '../lib/errors.js'; import { REFRESH_TTL_SECONDS, verifyRefresh, issueSession } from '../auth/jwt.js'; import { @@ -300,6 +301,9 @@ export async function authRoutes(fastify: FastifyInstance): Promise<void> { // Undefined when the session predates the loginMethod claim or when // anonymous. Returned as null for the SPA to treat uniformly. lastLoginMethod: session.loginMethod ?? null, + // Whether the person has a verified Slack link, never its user id + // (specs/api/slack-link.md). + slack: person ? slackStatus(await fastify.store.private.getProfile(person.id)) : null, }); }, ); diff --git a/apps/api/src/routes/slack-link.ts b/apps/api/src/routes/slack-link.ts new file mode 100644 index 00000000..af6c40ed --- /dev/null +++ b/apps/api/src/routes/slack-link.ts @@ -0,0 +1,68 @@ +/** + * Slack account link routes — specs/api/slack-link.md. + * + * POST /api/account/slack-link/code — user (self): a one-time linking code + * DELETE /api/account/slack-link — user (self): remove the link + * POST /api/agent/slack-links — agent:slack:link: redeem a code + * + * None of these writes a public commit: the link lives on the private + * profile. The code and the Slack ids travel in request and response bodies, + * which are never logged. + */ +import type { FastifyInstance } from 'fastify'; + +import { agentScopeCaller } from '../auth/caller.js'; +import { requireSignedIn } from '../auth/require.js'; +import { ok } from '../lib/response.js'; + +export async function slackLinkRoutes(fastify: FastifyInstance): Promise<void> { + const links = () => fastify.services.slackLinks; + + fastify.post( + '/api/account/slack-link/code', + { schema: { tags: ['slack-link'], summary: 'Issue a one-time Slack linking code for the caller' } }, + async (request) => { + const session = requireSignedIn(request.session); + return ok(await links().issue(session.person!)); + }, + ); + + fastify.delete( + '/api/account/slack-link', + { schema: { tags: ['slack-link'], summary: "Remove the caller's Slack link" } }, + async (request, reply) => { + const session = requireSignedIn(request.session); + await links().unlink(session.person!); + return reply.code(204).send(); + }, + ); + + fastify.post( + '/api/agent/slack-links', + { + // Scope before body: a caller without the grant learns nothing from validation. + preValidation: async (request) => { + agentScopeCaller(request, 'slack:link'); + }, + schema: { + tags: ['slack-link'], + summary: 'Redeem a linking code for the Slack user who sent it (agent:slack:link)', + body: { + type: 'object', + properties: { + code: { type: 'string', maxLength: 32 }, + slackTeamId: { type: 'string', maxLength: 32 }, + slackUserId: { type: 'string', maxLength: 32 }, + }, + required: ['code', 'slackTeamId', 'slackUserId'], + additionalProperties: false, + }, + }, + }, + async (request) => { + const caller = agentScopeCaller(request, 'slack:link'); + const body = request.body as { code: string; slackTeamId: string; slackUserId: string }; + return ok(await links().redeem(caller.agent.person, body)); + }, + ); +} diff --git a/apps/api/src/services/agents.ts b/apps/api/src/services/agents.ts index a7d9d2b0..8bc09c90 100644 --- a/apps/api/src/services/agents.ts +++ b/apps/api/src/services/agents.ts @@ -10,6 +10,7 @@ import { uuidv7 } from 'uuidv7'; import { AGENT_SCOPES, + AGENT_SCOPE_REQUIRES, AgentGrantSchema, PersonSchema, agentEvaluatorFor, @@ -80,8 +81,10 @@ function nowIso(): string { } /** - * Validate a grant request: known scopes, at least one, `moderation:purge` - * only with `moderation:read`, `expiresInDays` 1–180 (default 90). + * Validate a grant request: known scopes, at least one, each with its + * companions (`moderation:purge` with `moderation:read`; + * `projects:applications:decide` with `projects:applications:read` and + * `slack:link`), `expiresInDays` 1–180 (default 90). */ export function validateGrantInput(input: GrantInput): { label: string; scopes: AgentScope[]; days: number } { const fields: Record<string, string> = {}; @@ -91,8 +94,14 @@ export function validateGrantInput(input: GrantInput): { label: string; scopes: const scopes = [...new Set(input.scopes)]; if (scopes.length === 0) fields['scopes'] = 'at least one scope'; else if (scopes.some((s) => !known.has(s))) fields['scopes'] = `unknown scope; allowed: ${AGENT_SCOPES.join(', ')}`; - else if (scopes.includes('moderation:purge') && !scopes.includes('moderation:read')) { - fields['scopes'] = 'moderation:purge requires moderation:read'; + else { + for (const scope of scopes as AgentScope[]) { + const missing = (AGENT_SCOPE_REQUIRES[scope] ?? []).filter((s) => !scopes.includes(s)); + if (missing.length > 0) { + fields['scopes'] = `${scope} requires ${(AGENT_SCOPE_REQUIRES[scope] ?? []).join(' and ')}`; + break; + } + } } const days = input.expiresInDays ?? GRANT_DEFAULT_DAYS; if (!Number.isInteger(days) || days < 1 || days > GRANT_MAX_DAYS) fields['expiresInDays'] = `1–${GRANT_MAX_DAYS}`; diff --git a/apps/api/src/services/slack-link.ts b/apps/api/src/services/slack-link.ts new file mode 100644 index 00000000..b62e5bbf --- /dev/null +++ b/apps/api/src/services/slack-link.ts @@ -0,0 +1,222 @@ +/** + * The Slack account link — specs/api/slack-link.md. + * + * A signed-in member asks for a one-time code; the ops bot redeems it with + * the Slack user who sent it in a DM. Both sides are proven: the site knew + * who was signed in when it issued the code, and Slack knows who sent it. + * + * Codes are held in memory only, as SHA-256 hashes, for ten minutes, and are + * redeemable once. They are never written to either store, a commit or a log + * line; a restart drops them. The link itself is `PrivateProfile.slack`. + * + * Every way a code can fail (unknown, expired, used, or its issuer gone) + * answers the same `404 code_invalid`, so the endpoint tells a guesser + * nothing about which accounts or Slack users exist. Ten such failures in an + * hour lock an agent out for an hour. + */ +import { createHash, randomInt } from 'node:crypto'; + +import type { Person, PrivateProfile } from '@cfp/shared/schemas'; + +import { isAgentAccount } from '../auth/agent-grant.js'; +import { ApiNotFoundError, ApiValidationError, ConflictError, RateLimitedError } from '../lib/errors.js'; +import type { InMemoryState } from '../store/memory/state.js'; +import type { PrivateStore } from '../store/private/interface.js'; + +const MINUTE = 60 * 1000; +const HOUR = 60 * MINUTE; + +export const CODE_TTL_MS = 10 * MINUTE; +export const CODES_PER_HOUR = 5; +export const FAILED_REDEMPTIONS_PER_HOUR = 10; +export const REDEMPTION_LOCKOUT_MS = HOUR; + +/** No 0/O, no 1/I/L. */ +export const CODE_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789'; +export const CODE_LENGTH = 8; + +const SLACK_ID = /^[A-Z0-9]{2,32}$/; + +/** A fresh code, shown as two groups of four: `K7QW-4MZP`. */ +export function generateCode(): string { + let raw = ''; + for (let i = 0; i < CODE_LENGTH; i++) raw += CODE_ALPHABET[randomInt(CODE_ALPHABET.length)]; + return `${raw.slice(0, 4)}-${raw.slice(4)}`; +} + +/** The canonical form of a typed code (upper case, no hyphen or spaces), or null if it cannot be one. */ +export function normalizeCode(input: unknown): string | null { + if (typeof input !== 'string') return null; + const s = input.replace(/[\s-]/g, '').toUpperCase(); + if (s.length !== CODE_LENGTH) return null; + for (const ch of s) if (!CODE_ALPHABET.includes(ch)) return null; + return s; +} + +function hashCode(canonical: string): string { + return createHash('sha256').update(canonical, 'utf8').digest('hex'); +} + +/** What `GET /api/auth/me` reports to the person themselves: never the Slack user id. */ +export function slackStatus(profile: PrivateProfile | null): { linked: boolean; linkedAt: string | null } { + return profile?.slack ? { linked: true, linkedAt: profile.slack.linkedAt } : { linked: false, linkedAt: null }; +} + +interface PendingCode { + readonly personId: string; + readonly expiresAt: number; +} + +export interface SlackLinkConfig { + /** The workspace the site serves; unset, every redemption is refused. */ + readonly teamId?: string | undefined; + readonly botDmUrl?: string | undefined; +} + +export class SlackLinkService { + readonly #state: InMemoryState; + readonly #privateStore: PrivateStore; + readonly #config: SlackLinkConfig; + /** sha256(code) → who issued it, until when. */ + readonly #codes = new Map<string, PendingCode>(); + /** personId → the hash of their one live code. */ + readonly #latest = new Map<string, string>(); + /** personId → when they asked for codes in the last hour. */ + readonly #issued = new Map<string, number[]>(); + /** agent slug → failed redemptions in the last hour. */ + readonly #failures = new Map<string, number[]>(); + /** agent slug → refused until. */ + readonly #lockedUntil = new Map<string, number>(); + /** Redemptions run one at a time, so two cannot link one Slack user to two accounts. */ + #queue: Promise<unknown> = Promise.resolve(); + + constructor(state: InMemoryState, privateStore: PrivateStore, config: SlackLinkConfig) { + this.#state = state; + this.#privateStore = privateStore; + this.#config = config; + } + + /** POST /api/account/slack-link/code — a fresh code; any earlier one for the person is void. */ + async issue(person: Person, now: Date = new Date()): Promise<{ code: string; expiresAt: string; botDmUrl: string | null }> { + if (isAgentAccount(this.#state, person.slug)) { + throw new ApiValidationError('An agent account cannot link a Slack user', { person: 'agent_account' }, 'agent_account'); + } + if (!(await this.#privateStore.getProfile(person.id))) { + throw new ApiValidationError( + 'This account has no private profile to hold a Slack link', + { person: 'no_private_profile' }, + 'no_private_profile', + ); + } + const t = now.getTime(); + this.#sweep(t); + const recent = (this.#issued.get(person.id) ?? []).filter((at) => t - at < HOUR); + if (recent.length >= CODES_PER_HOUR) { + throw new RateLimitedError(Math.max(1, Math.ceil((recent[0]! + HOUR - t) / 1000))); + } + recent.push(t); + this.#issued.set(person.id, recent); + + this.#void(person.id); + let code: string; + let hash: string; + do { + code = generateCode(); + hash = hashCode(normalizeCode(code)!); + } while (this.#codes.has(hash)); + const expiresAt = t + CODE_TTL_MS; + this.#codes.set(hash, { personId: person.id, expiresAt }); + this.#latest.set(person.id, hash); + return { code, expiresAt: new Date(expiresAt).toISOString(), botDmUrl: this.#config.botDmUrl ?? null }; + } + + /** POST /api/agent/slack-links — link the code's issuer to the Slack user who sent it. */ + redeem( + agent: Person, + input: { code?: unknown; slackTeamId?: unknown; slackUserId?: unknown }, + now: Date = new Date(), + ): Promise<{ personSlug: string; linkedAt: string }> { + const run = this.#queue.then(() => this.#redeem(agent, input, now)); + this.#queue = run.catch(() => undefined); + return run; + } + + async #redeem( + agent: Person, + input: { code?: unknown; slackTeamId?: unknown; slackUserId?: unknown }, + now: Date, + ): Promise<{ personSlug: string; linkedAt: string }> { + const t = now.getTime(); + const locked = this.#lockedUntil.get(agent.slug); + if (locked !== undefined) { + if (locked > t) throw new RateLimitedError(Math.max(1, Math.ceil((locked - t) / 1000))); + this.#lockedUntil.delete(agent.slug); + this.#failures.delete(agent.slug); + } + + const teamId = this.#config.teamId; + if (!teamId || input.slackTeamId !== teamId) { + throw new ApiValidationError('slackTeamId is not the workspace this site serves', { slackTeamId: 'wrong_workspace' }); + } + if (typeof input.slackUserId !== 'string' || !SLACK_ID.test(input.slackUserId)) { + throw new ApiValidationError('slackUserId must be a Slack user id', { slackUserId: 'invalid' }); + } + const userId = input.slackUserId; + + this.#sweep(t); + const canonical = normalizeCode(input.code); + const hash = canonical ? hashCode(canonical) : null; + const pending = hash ? this.#codes.get(hash) : undefined; + const person = pending ? this.#state.people.get(pending.personId) : undefined; + const profile = person ? await this.#privateStore.getProfile(person.id) : null; + if (!hash || !pending || pending.expiresAt <= t || !person || !profile) { + if (hash && pending) this.#void(pending.personId); + this.#fail(agent.slug, t); + throw new ApiNotFoundError('That code is not valid', 'code_invalid'); + } + + const holder = this.#privateStore.findPersonIdBySlackUser(teamId, userId); + if (holder !== null && holder !== person.id) { + // The code is not consumed: it works once the other account disconnects. + throw new ConflictError('That Slack user is linked to a different account', 'slack_user_linked'); + } + + this.#void(person.id); + const linkedAt = now.toISOString(); + // A new link replaces any old one on this account (one Slack user per account). + await this.#privateStore.putProfile({ ...profile, slack: { teamId, userId, linkedAt }, updatedAt: linkedAt }); + return { personSlug: person.slug, linkedAt }; + } + + /** DELETE /api/account/slack-link — clear the caller's link; nothing to do if there is none. */ + async unlink(person: Person, now: Date = new Date()): Promise<void> { + const profile = await this.#privateStore.getProfile(person.id); + if (!profile?.slack) return; + await this.#privateStore.putProfile({ ...profile, slack: null, updatedAt: now.toISOString() }); + } + + /** Drop a person's live code. */ + #void(personId: string): void { + const hash = this.#latest.get(personId); + if (hash) this.#codes.delete(hash); + this.#latest.delete(personId); + } + + #fail(agentSlug: string, t: number): void { + const recent = (this.#failures.get(agentSlug) ?? []).filter((at) => t - at < HOUR); + recent.push(t); + this.#failures.set(agentSlug, recent); + if (recent.length >= FAILED_REDEMPTIONS_PER_HOUR) this.#lockedUntil.set(agentSlug, t + REDEMPTION_LOCKOUT_MS); + } + + /** Forget expired codes and stale counters. */ + #sweep(t: number): void { + for (const [hash, c] of this.#codes) { + if (c.expiresAt <= t) { + this.#codes.delete(hash); + if (this.#latest.get(c.personId) === hash) this.#latest.delete(c.personId); + } + } + for (const [id, times] of this.#issued) if (times.every((at) => t - at >= HOUR)) this.#issued.delete(id); + } +} diff --git a/apps/api/tests/helpers/agent-fixtures.ts b/apps/api/tests/helpers/agent-fixtures.ts index 45465ee5..6c4f8f93 100644 --- a/apps/api/tests/helpers/agent-fixtures.ts +++ b/apps/api/tests/helpers/agent-fixtures.ts @@ -8,7 +8,7 @@ import { execFile } from 'node:child_process'; import { promisify } from 'node:util'; -import type { FastifyInstance } from 'fastify'; +import type { FastifyInstance, FastifyServerOptions } from 'fastify'; import { openRepo } from 'gitsheets'; import { expect } from 'vitest'; @@ -59,6 +59,8 @@ export async function startAgentTestEnv(opts: { records: Record<string, Rec[]>; profiles?: Rec[]; env?: Record<string, string>; + /** A logger for the app (default: none), e.g. one writing to a capture stream. */ + logger?: FastifyServerOptions['logger']; /** More seeding in the same commit (attachments, raw files). */ extra?: (tx: Parameters<Parameters<Awaited<ReturnType<typeof openRepo>>['transact']>[1]>[0]) => Promise<void>; }): Promise<AgentTestEnv> { @@ -80,7 +82,7 @@ export async function startAgentTestEnv(opts: { ); } const app = await buildApp({ - serverOptions: { logger: false }, + serverOptions: { logger: opts.logger ?? false }, overrideEnv: { CFP_DATA_REPO_PATH: dataRepo.path, STORAGE_BACKEND: 'filesystem', diff --git a/apps/api/tests/slack-link.test.ts b/apps/api/tests/slack-link.test.ts new file mode 100644 index 00000000..c022c2ec --- /dev/null +++ b/apps/api/tests/slack-link.test.ts @@ -0,0 +1,323 @@ +/** + * Linking a site account to a Slack user (plans/slack-account-link.md, + * specs/api/slack-link.md): one-time codes, the agent's redemption, the + * refusals that must not reveal anything, disconnect, purge, the companion + * rule at mint, and that no code or Slack id reaches the public store, a + * commit or a log line. + * + * Every person, workspace and Slack id here is invented. + */ +import { readFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { Writable } from 'node:stream'; + +import { afterEach, describe, expect, it } from 'vitest'; + +import { + bearer, + createAgent, + fid, + personRecord, + privateProfile, + startAgentTestEnv, + type AgentTestEnv, +} from './helpers/agent-fixtures.js'; +import { CODE_ALPHABET, normalizeCode } from '../src/services/slack-link.js'; + +const TEAM = 'TEXAMPLE01'; +const P = { ada: 1, ben: 2, root: 3, sam: 4, noprof: 5 }; +const U_ADA = 'UADA000001'; +const U_OTHER = 'UOTHER0002'; + +function records() { + return { + people: [ + personRecord(P.ada, 'ada'), + personRecord(P.ben, 'ben'), + personRecord(P.root, 'root', { accountLevel: 'administrator' }), + personRecord(P.sam, 'sam', { accountLevel: 'staff' }), + personRecord(P.noprof, 'noprof'), + ], + }; +} +const PROFILES = [P.ada, P.ben, P.root, P.sam].map((k) => privateProfile(fid(k), `p${k}@example.org`)); + +describe('slack account link', () => { + let env: AgentTestEnv; + let logs: string[]; + + const start = async (extraEnv: Record<string, string> = { SLACK_TEAM_ID: TEAM }) => { + logs = []; + const stream = new Writable({ + write(chunk: Buffer, _enc, cb) { + logs.push(chunk.toString('utf8')); + cb(); + }, + }); + env = await startAgentTestEnv({ + records: records(), + profiles: PROFILES, + env: { ...extraEnv, SLACK_OPS_BOT_DM_URL: 'https://example.slack.com/app_redirect?channel=UBOT' }, + logger: { level: 'trace', stream }, + }); + }; + afterEach(async () => { + await env?.close(); + }); + + const as = async (n: number, level: 'user' | 'staff' | 'administrator' = 'user') => ({ + cookies: { cfp_session: await env.cookie(n, level) }, + }); + const issue = async (n: number) => env.app.inject({ method: 'POST', url: '/api/account/slack-link/code', ...(await as(n)) }); + const codeFor = async (n: number) => { + const res = await issue(n); + expect(res.statusCode, res.body).toBe(200); + return res.json<{ data: { code: string; expiresAt: string; botDmUrl: string | null } }>().data; + }; + const redeem = (token: string, payload: Record<string, unknown>) => + env.app.inject({ method: 'POST', url: '/api/agent/slack-links', ...bearer(token), payload }); + const me = async (n: number) => + (await env.app.inject({ method: 'GET', url: '/api/auth/me', ...(await as(n)) })).json<{ + data: { slack: { linked: boolean; linkedAt: string | null } | null }; + }>().data; + const agentWith = async (scopes: string[], slug = 'example-bot') => + (await createAgent(env, (await as(P.root, 'administrator')).cookies.cfp_session, { slug, scopes })).token; + const err = (res: { json: () => unknown }) => { + const { code, message } = (res.json() as { error: { code: string; message: string } }).error; + return { code, message }; + }; + + describe('issuing a code', () => { + it('returns an 8-character code from the unambiguous alphabet, ten minutes, and the bot DM link', async () => { + await start(); + const before = Date.now(); + const data = await codeFor(P.ada); + expect(data.code).toMatch(/^[A-Z2-9]{4}-[A-Z2-9]{4}$/); + for (const ch of data.code.replace('-', '')) expect(CODE_ALPHABET).toContain(ch); + expect(data.code).not.toMatch(/[01OIL]/); + const ttl = Date.parse(data.expiresAt) - before; + expect(ttl).toBeGreaterThan(9.9 * 60_000); + expect(ttl).toBeLessThanOrEqual(10 * 60_000 + 1000); + expect(data.botDmUrl).toBe('https://example.slack.com/app_redirect?channel=UBOT'); + }); + + it('matches case-insensitively with the hyphen optional', () => { + expect(normalizeCode('k7qw-4mzp')).toBe('K7QW4MZP'); + expect(normalizeCode('K7QW4MZP')).toBe('K7QW4MZP'); + expect(normalizeCode('K7QW-4MZ0')).toBeNull(); + expect(normalizeCode('K7Q-4MZP')).toBeNull(); + }); + + it('allows five codes per account per hour', async () => { + await start(); + for (let i = 0; i < 5; i++) expect((await issue(P.ada)).statusCode).toBe(200); + const sixth = await issue(P.ada); + expect(sixth.statusCode).toBe(429); + expect(sixth.headers['retry-after']).toBeDefined(); + // Another account is unaffected. + expect((await issue(P.ben)).statusCode).toBe(200); + }); + + it('is refused to anonymous callers, agent grants and accounts with no private profile', async () => { + await start(); + expect((await env.app.inject({ method: 'POST', url: '/api/account/slack-link/code' })).statusCode).toBe(401); + const token = await agentWith(['slack:link']); + const asAgent = await env.app.inject({ method: 'POST', url: '/api/account/slack-link/code', ...bearer(token) }); + expect(asAgent.statusCode).toBe(401); + const noProfile = await issue(P.noprof); + expect(noProfile.statusCode).toBe(422); + expect(err(noProfile).code).toBe('no_private_profile'); + }); + + it('refuses an agent account (422 agent_account)', async () => { + await start(); + await agentWith(['slack:link']); + const agent = env.app.inMemoryState.people.get(env.app.inMemoryState.personIdBySlug.get('example-bot')!)!; + await expect(env.app.services.slackLinks.issue(agent)).rejects.toMatchObject({ code: 'agent_account' }); + }); + }); + + describe('redeeming a code', () => { + it('links the issuer once; reused, unknown and expired codes all answer the same 404 code_invalid', async () => { + await start(); + const token = await agentWith(['slack:link']); + expect((await me(P.ada)).slack).toEqual({ linked: false, linkedAt: null }); + + const { code } = await codeFor(P.ada); + const ok = await redeem(token, { code: code.toLowerCase().replace('-', ''), slackTeamId: TEAM, slackUserId: U_ADA }); + expect(ok.statusCode, ok.body).toBe(200); + const data = ok.json<{ data: { personSlug: string; linkedAt: string } }>().data; + expect(data.personSlug).toBe('ada'); + expect(await me(P.ada)).toMatchObject({ slack: { linked: true, linkedAt: data.linkedAt } }); + expect(JSON.stringify(await me(P.ada))).not.toContain(U_ADA); + expect(env.app.store.private.findPersonIdBySlackUser(TEAM, U_ADA)).toBe(fid(P.ada)); + + const reused = await redeem(token, { code, slackTeamId: TEAM, slackUserId: U_ADA }); + const unknown = await redeem(token, { code: 'ABCD-EFGH', slackTeamId: TEAM, slackUserId: U_ADA }); + const garbage = await redeem(token, { code: 'not a code', slackTeamId: TEAM, slackUserId: U_ADA }); + + const svc = env.app.services.slackLinks; + const ben = env.app.inMemoryState.people.get(fid(P.ben))!; + const agent = env.app.inMemoryState.people.get(env.app.inMemoryState.personIdBySlug.get('example-bot')!)!; + const old = await svc.issue(ben, new Date(Date.now() - 11 * 60_000)); + const expired = await svc.redeem(agent, { code: old.code, slackTeamId: TEAM, slackUserId: U_OTHER }).catch((e: unknown) => e); + + for (const res of [reused, unknown, garbage]) { + expect(res.statusCode).toBe(404); + expect(err(res)).toEqual(err(reused)); + } + expect(err(reused).code).toBe('code_invalid'); + expect(expired).toMatchObject({ code: 'code_invalid', message: err(reused).message }); + expect((await me(P.ben)).slack?.linked).toBe(false); + }); + + it('a new code voids the earlier one', async () => { + await start(); + const token = await agentWith(['slack:link']); + const first = await codeFor(P.ada); + const second = await codeFor(P.ada); + expect((await redeem(token, { code: first.code, slackTeamId: TEAM, slackUserId: U_ADA })).statusCode).toBe(404); + expect((await redeem(token, { code: second.code, slackTeamId: TEAM, slackUserId: U_ADA })).statusCode).toBe(200); + }); + + it('a Slack user linked to one account cannot be linked to another; disconnect frees it and the code still works', async () => { + await start(); + const token = await agentWith(['slack:link']); + const a = await codeFor(P.ada); + expect((await redeem(token, { code: a.code, slackTeamId: TEAM, slackUserId: U_ADA })).statusCode).toBe(200); + + const b = await codeFor(P.ben); + const conflict = await redeem(token, { code: b.code, slackTeamId: TEAM, slackUserId: U_ADA }); + expect(conflict.statusCode).toBe(409); + expect(err(conflict).code).toBe('slack_user_linked'); + + const del = await env.app.inject({ method: 'DELETE', url: '/api/account/slack-link', ...(await as(P.ada)) }); + expect(del.statusCode).toBe(204); + expect((await me(P.ada)).slack).toEqual({ linked: false, linkedAt: null }); + expect(env.app.store.private.findPersonIdBySlackUser(TEAM, U_ADA)).toBeNull(); + // Disconnecting again is not an error. + expect((await env.app.inject({ method: 'DELETE', url: '/api/account/slack-link', ...(await as(P.ada)) })).statusCode).toBe(204); + + const retry = await redeem(token, { code: b.code, slackTeamId: TEAM, slackUserId: U_ADA }); + expect(retry.statusCode, retry.body).toBe(200); + expect(env.app.store.private.findPersonIdBySlackUser(TEAM, U_ADA)).toBe(fid(P.ben)); + }); + + it('a new link replaces the old one on the same account', async () => { + await start(); + const token = await agentWith(['slack:link']); + expect((await redeem(token, { code: (await codeFor(P.ada)).code, slackTeamId: TEAM, slackUserId: U_ADA })).statusCode).toBe(200); + expect((await redeem(token, { code: (await codeFor(P.ada)).code, slackTeamId: TEAM, slackUserId: U_OTHER })).statusCode).toBe(200); + expect(env.app.store.private.findPersonIdBySlackUser(TEAM, U_ADA)).toBeNull(); + expect(env.app.store.private.findPersonIdBySlackUser(TEAM, U_OTHER)).toBe(fid(P.ada)); + }); + + it('refuses another workspace (422), and every redemption when no workspace is configured', async () => { + await start(); + const token = await agentWith(['slack:link']); + const { code } = await codeFor(P.ada); + const wrong = await redeem(token, { code, slackTeamId: 'TOTHER0001', slackUserId: U_ADA }); + expect(wrong.statusCode).toBe(422); + // The code was not spent on the wrong workspace. + expect((await redeem(token, { code, slackTeamId: TEAM, slackUserId: U_ADA })).statusCode).toBe(200); + await env.close(); + + await start({}); + const token2 = await agentWith(['slack:link']); + const c2 = await codeFor(P.ada); + expect((await redeem(token2, { code: c2.code, slackTeamId: TEAM, slackUserId: U_ADA })).statusCode).toBe(422); + }); + + it('needs a grant with slack:link: other grants, staff and anonymous callers get 401', async () => { + await start(); + const { code } = await codeFor(P.ada); + const payload = { code, slackTeamId: TEAM, slackUserId: U_ADA }; + const modOnly = await agentWith(['moderation:read'], 'mod-bot'); + expect((await redeem(modOnly, payload)).statusCode).toBe(401); + const asStaff = await env.app.inject({ method: 'POST', url: '/api/agent/slack-links', ...(await as(P.sam, 'staff')), payload }); + expect(asStaff.statusCode).toBe(401); + expect((await env.app.inject({ method: 'POST', url: '/api/agent/slack-links', payload })).statusCode).toBe(401); + // A bad body from a caller without the scope still gets 401, not a validation hint. + expect((await redeem(modOnly, { nope: true })).statusCode).toBe(401); + expect((await me(P.ada)).slack?.linked).toBe(false); + }); + + it('locks an agent out for an hour after ten failed redemptions, even for a valid code', async () => { + await start(); + const token = await agentWith(['slack:link']); + const { code } = await codeFor(P.ada); + for (let i = 0; i < 10; i++) { + const res = await redeem(token, { code: `ZZZZ-ZZZ${'ABCDEFGHJK'[i]}`, slackTeamId: TEAM, slackUserId: U_ADA }); + expect(res.statusCode).toBe(404); + } + const eleventh = await redeem(token, { code, slackTeamId: TEAM, slackUserId: U_ADA }); + expect(eleventh.statusCode).toBe(429); + expect(Number(eleventh.headers['retry-after'])).toBeGreaterThan(3500); + expect((await me(P.ada)).slack?.linked).toBe(false); + + // An hour later the lock lifts. + const svc = env.app.services.slackLinks; + const agent = env.app.inMemoryState.people.get(env.app.inMemoryState.personIdBySlug.get('example-bot')!)!; + const later = new Date(Date.now() + 61 * 60_000); + const ada = env.app.inMemoryState.people.get(fid(P.ada))!; + const fresh = await svc.issue(ada, later); + await expect(svc.redeem(agent, { code: fresh.code, slackTeamId: TEAM, slackUserId: U_ADA }, later)).resolves.toMatchObject({ + personSlug: 'ada', + }); + }); + }); + + it('purging the person removes the link', async () => { + await start(); + const token = await agentWith(['slack:link']); + expect((await redeem(token, { code: (await codeFor(P.ben)).code, slackTeamId: TEAM, slackUserId: U_OTHER })).statusCode).toBe(200); + const purge = await env.app.inject({ method: 'POST', url: '/api/people/ben/purge', ...(await as(P.root, 'administrator')) }); + expect(purge.statusCode, purge.body).toBe(204); + expect(env.app.store.private.findPersonIdBySlackUser(TEAM, U_OTHER)).toBeNull(); + const raw = await readFile(join(env.privatePath, 'profiles.jsonl'), 'utf8'); + expect(raw).not.toContain(U_OTHER); + }); + + it('no code or Slack id reaches the public store, a commit or a log line; the link sits on the private profile only', async () => { + await start(); + const token = await agentWith(['slack:link']); + const { code } = await codeFor(P.ada); + expect((await redeem(token, { code, slackTeamId: TEAM, slackUserId: U_ADA })).statusCode).toBe(200); + await redeem(token, { code, slackTeamId: TEAM, slackUserId: U_ADA }); // a failure is logged too + await me(P.ada); + + const history = await env.git('log', '--all', '-p', '--format=%H%n%B'); + const canonical = code.replace('-', ''); + for (const secret of [code, canonical, U_ADA]) { + expect(history).not.toContain(secret); + expect(logs.join('')).not.toContain(secret); + } + expect(logs.length).toBeGreaterThan(0); + const raw = await readFile(join(env.privatePath, 'profiles.jsonl'), 'utf8'); + expect(raw).toContain(U_ADA); + expect(raw).not.toContain(canonical); + }); + + it('minting projects:applications:decide needs projects:applications:read and slack:link', async () => { + await start(); + const adminCookie = (await as(P.root, 'administrator')).cookies.cfp_session; + const mint = (scopes: string[], slug: string) => + env.app.inject({ + method: 'POST', + url: '/api/admin/agents', + cookies: { cfp_session: adminCookie }, + payload: { slug, fullName: `Example ${slug}`, bio: 'An AI ops bot run by the test suite.', grant: { label: 'test', scopes } }, + }); + for (const [i, scopes] of [ + ['projects:applications:decide'], + ['projects:applications:decide', 'projects:applications:read'], + ['projects:applications:decide', 'slack:link'], + ].entries()) { + const res = await mint(scopes, `bad-bot-${i}`); + expect(res.statusCode, res.body).toBe(422); + expect(res.body).toContain('projects:applications:decide requires'); + } + const good = await mint(['projects:applications:decide', 'projects:applications:read', 'slack:link'], 'good-bot'); + expect(good.statusCode, good.body).toBe(201); + }); +}); From b02dc3112a378f1f27bd5f62a28982084e745411 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:21:10 +0000 Subject: [PATCH 58/78] feat(web): the Account screen's Slack row, and the new scopes on the mint form MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Connect Slack asks for a code and shows it with the instruction to DM it to the ops bot within ten minutes (the bot's name links to botDmUrl when configured); the row polls /api/auth/me while the code is live and turns "Connected to Slack ✓ since …" when the bot confirms. Disconnect asks first. The row never shows a Slack user id. The agents panel's mint form offers the three new scopes and warns when decide lacks its companions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/web/src/components/account/SlackRow.tsx | 131 ++++++++++++++++++ apps/web/src/components/admin/AgentsPanel.tsx | 12 ++ apps/web/src/hooks/useAuth.tsx | 17 ++- apps/web/src/lib/api.ts | 21 ++- apps/web/src/screens/Account.tsx | 10 +- apps/web/tests/Account.test.tsx | 60 ++++++++ 6 files changed, 241 insertions(+), 10 deletions(-) create mode 100644 apps/web/src/components/account/SlackRow.tsx diff --git a/apps/web/src/components/account/SlackRow.tsx b/apps/web/src/components/account/SlackRow.tsx new file mode 100644 index 00000000..3a2d6f25 --- /dev/null +++ b/apps/web/src/components/account/SlackRow.tsx @@ -0,0 +1,131 @@ +/** + * The Account screen's Slack row — specs/screens/account.md → Card 1, and + * specs/api/slack-link.md. + * + * Not linked: "Connect Slack" asks for a one-time code and shows it with the + * instruction to DM it to the ops bot within ten minutes; while the code is + * live the row polls `GET /api/auth/me` and turns linked when the bot + * confirms it. Linked: "Connected to Slack ✓ since …" with Disconnect. + * The row never shows the Slack user id (the API never sends it here). + */ +import { useEffect, useState } from 'react'; +import { toast } from 'sonner'; + +import { Button } from '@/components/ui/button'; +import { fetchMeOnce, type SlackLinkStatus } from '@/hooks/useAuth'; +import { api, ApiError, type SlackLinkCode } from '@/lib/api'; +import { formatAbsoluteDate } from '@/lib/time'; + +const POLL_MS = 3000; + +export function SlackRow({ initial }: { initial: SlackLinkStatus | null }) { + const [status, setStatus] = useState<SlackLinkStatus>(initial ?? { linked: false, linkedAt: null }); + const [pending, setPending] = useState<SlackLinkCode | null>(null); + const [busy, setBusy] = useState(false); + + // Poll while a code is live; stop when linked or when it expires. + useEffect(() => { + if (!pending) return; + let cancelled = false; + const tick = async () => { + if (Date.parse(pending.expiresAt) <= Date.now()) { + if (!cancelled) setPending(null); + return; + } + const snap = await fetchMeOnce(); + if (cancelled) return; + if (snap.slack?.linked) { + setStatus(snap.slack); + setPending(null); + toast.success('Slack connected.'); + } + }; + const id = window.setInterval(() => void tick(), POLL_MS); + return () => { + cancelled = true; + window.clearInterval(id); + }; + }, [pending]); + + const connect = async () => { + setBusy(true); + try { + const res = await api.slackLink.issueCode(); + setPending(res.data); + } catch (err) { + toast.error( + err instanceof ApiError && err.status === 429 + ? 'Too many codes in the last hour. Try again later.' + : err instanceof ApiError + ? err.message + : 'Could not get a code', + ); + } finally { + setBusy(false); + } + }; + + const disconnect = async () => { + if (!window.confirm('Disconnect your Slack account? The ops bot will stop reaching you in Slack.')) return; + setBusy(true); + try { + await api.slackLink.disconnect(); + setStatus({ linked: false, linkedAt: null }); + toast.success('Slack disconnected.'); + } catch (err) { + toast.error(err instanceof ApiError ? err.message : 'Could not disconnect'); + } finally { + setBusy(false); + } + }; + + const bot = pending?.botDmUrl ? ( + <a href={pending.botDmUrl} target="_blank" rel="noopener noreferrer" className="text-primary underline"> + the ops bot<span className="sr-only"> (opens Slack in a new tab)</span> + </a> + ) : ( + 'the ops bot' + ); + + return ( + <div className="border-t border-border pt-3 space-y-2"> + <div className="flex items-center justify-between gap-3"> + <div> + <div className="font-medium">Slack</div> + <div className="text-xs text-muted-foreground"> + {status.linked + ? `Connected to Slack ✓${status.linkedAt ? ` since ${formatAbsoluteDate(status.linkedAt)}` : ''}` + : 'Not linked to a Slack account'} + </div> + </div> + {status.linked ? ( + <Button size="sm" variant="outline" onClick={() => void disconnect()} disabled={busy}> + Disconnect + </Button> + ) : ( + !pending && ( + <Button size="sm" onClick={() => void connect()} disabled={busy}> + Connect Slack + </Button> + ) + )} + </div> + {status.linked && ( + <p className="text-xs text-muted-foreground"> + Lets the ops bot send you project notices in Slack and act on your replies, such as accepting an + application you answer there. + </p> + )} + {!status.linked && pending && ( + <div className="rounded-md border border-border bg-muted/40 p-3 space-y-1" aria-live="polite"> + <div className="font-mono text-lg tracking-widest" data-testid="slack-link-code"> + {pending.code} + </div> + <p className="text-xs text-muted-foreground"> + Send this code in a direct message to {bot} in the Code for Philly Slack within 10 minutes. + </p> + </div> + )} + </div> + ); +} diff --git a/apps/web/src/components/admin/AgentsPanel.tsx b/apps/web/src/components/admin/AgentsPanel.tsx index 99029862..9bd4117d 100644 --- a/apps/web/src/components/admin/AgentsPanel.tsx +++ b/apps/web/src/components/admin/AgentsPanel.tsx @@ -216,6 +216,9 @@ const SCOPE_LABEL: Record<AgentScope, string> = { 'moderation:read': 'read roster', 'moderation:vote': 'staged votes', 'moderation:purge': 'purge', + 'slack:link': 'link members’ Slack accounts', + 'projects:applications:read': 'read application events', + 'projects:applications:decide': 'record an admin’s accept or close', }; /** Mint form + the purge second confirm + the token-once dialog. */ @@ -236,6 +239,9 @@ function MintGrantDialog({ 'moderation:read': true, 'moderation:vote': true, 'moderation:purge': false, + 'slack:link': false, + 'projects:applications:read': false, + 'projects:applications:decide': false, }); const [confirmPurge, setConfirmPurge] = useState(false); const mint = useMutation({ @@ -301,6 +307,12 @@ function MintGrantDialog({ {scopes['moderation:purge'] && !scopes['moderation:read'] && ( <p className="text-xs text-destructive">The purge scope needs moderation:read too.</p> )} + {scopes['projects:applications:decide'] && + !(scopes['projects:applications:read'] && scopes['slack:link']) && ( + <p className="text-xs text-destructive"> + The decide scope needs projects:applications:read and slack:link too. + </p> + )} </fieldset> <div className="space-y-1"> <Label htmlFor="grant-days">Expires in (days, 1–180)</Label> diff --git a/apps/web/src/hooks/useAuth.tsx b/apps/web/src/hooks/useAuth.tsx index 448dd07c..c3f2d01e 100644 --- a/apps/web/src/hooks/useAuth.tsx +++ b/apps/web/src/hooks/useAuth.tsx @@ -23,6 +23,12 @@ export interface AuthPerson { deletedAt?: string | null; } +/** `me.slack`: whether the person has a verified Slack link (never its user id). */ +export interface SlackLinkStatus { + linked: boolean; + linkedAt: string | null; +} + export interface AuthState { /** null = anonymous or not yet loaded */ person: AuthPerson | null; @@ -32,6 +38,8 @@ export interface AuthState { hasGitHubLink: boolean; /** How the current session was minted. null for anonymous or pre-loginMethod sessions. */ lastLoginMethod: LoginMethod | null; + /** The Slack link (specs/api/slack-link.md). null when anonymous. */ + slack: SlackLinkStatus | null; /** Reload auth state from the server */ reload: () => Promise<void>; /** Sign out: calls POST /api/auth/logout then clears state */ @@ -46,22 +54,25 @@ interface MeEnvelope { accountLevel?: AccountLevel; hasGitHubLink?: boolean; lastLoginMethod?: LoginMethod | null; + slack?: SlackLinkStatus | null; }; } -interface MeSnapshot { +export interface MeSnapshot { person: AuthPerson | null; hasGitHubLink: boolean; lastLoginMethod: LoginMethod | null; + slack: SlackLinkStatus | null; } const ANON_SNAPSHOT: MeSnapshot = { person: null, hasGitHubLink: false, lastLoginMethod: null, + slack: null, }; -async function fetchMeOnce(): Promise<MeSnapshot> { +export async function fetchMeOnce(): Promise<MeSnapshot> { try { const res = await fetch('/api/auth/me', { credentials: 'include' }); if (!res.ok) { @@ -73,6 +84,7 @@ async function fetchMeOnce(): Promise<MeSnapshot> { person: json.data?.person ?? null, hasGitHubLink: json.data?.hasGitHubLink ?? false, lastLoginMethod: json.data?.lastLoginMethod ?? null, + slack: json.data?.slack ?? null, }; } catch { // Network error — treat as anonymous, don't throw @@ -149,6 +161,7 @@ export function AuthProvider({ children }: { children: ReactNode }) { loading, hasGitHubLink: snapshot.hasGitHubLink, lastLoginMethod: snapshot.lastLoginMethod, + slack: snapshot.slack, reload, signOut, }} diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index 27b3cd76..d2c9193d 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -943,7 +943,20 @@ export interface MemberDetail { // --- Agents and the spam-purge log (specs/api/agents.md) ------------------- -export type AgentScope = 'moderation:read' | 'moderation:vote' | 'moderation:purge'; +export type AgentScope = + | 'moderation:read' + | 'moderation:vote' + | 'moderation:purge' + | 'slack:link' + | 'projects:applications:read' + | 'projects:applications:decide'; + +/** POST /api/account/slack-link/code — specs/api/slack-link.md. */ +export interface SlackLinkCode { + code: string; + expiresAt: string; + botDmUrl: string | null; +} export interface AgentGrantView { readonly id: string; @@ -1283,6 +1296,12 @@ export const api = { revokeSession: (jti: string): Promise<void> => request(`/api/auth/sessions/${encodeURIComponent(jti)}/revoke`, { method: 'POST' }), }, + slackLink: { + /** A one-time code to DM to the ops bot; any earlier one is void. */ + issueCode: (): Promise<SuccessEnvelope<SlackLinkCode>> => + request(`/api/account/slack-link/code`, { method: 'POST' }), + disconnect: (): Promise<void> => request(`/api/account/slack-link`, { method: 'DELETE' }), + }, accountClaim: { candidates: (): Promise<SuccessEnvelope<AccountClaimCandidatesPayload>> => request(`/api/account-claim/candidates`), diff --git a/apps/web/src/screens/Account.tsx b/apps/web/src/screens/Account.tsx index 1eb39dc0..4b23f430 100644 --- a/apps/web/src/screens/Account.tsx +++ b/apps/web/src/screens/Account.tsx @@ -6,6 +6,7 @@ import { Button } from '@/components/ui/button'; import { Checkbox } from '@/components/ui/checkbox'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Breadcrumbs } from '@/components/Breadcrumbs'; +import { SlackRow } from '@/components/account/SlackRow'; import { Dialog, DialogContent, @@ -46,7 +47,7 @@ const LINK_GITHUB_ERROR_MESSAGES: Record<string, string> = { }; export function Account() { - const { person, loading, signOut, reload, hasGitHubLink } = useAuth(); + const { person, loading, signOut, reload, hasGitHubLink, slack } = useAuth(); const navigate = useNavigate(); const queryClient = useQueryClient(); const [searchParams, setSearchParams] = useSearchParams(); @@ -200,12 +201,7 @@ export function Account() { </form> )} </div> - <div className="border-t border-border pt-3"> - <div className="font-medium">Slack</div> - <Button size="sm" variant="outline" disabled className="mt-1"> - Connect Slack (coming soon) - </Button> - </div> + <SlackRow initial={slack} /> <p className="text-xs text-muted-foreground border-t border-border pt-3"> Profile fields like name, bio, slug, and tags live on the{' '} <Link diff --git a/apps/web/tests/Account.test.tsx b/apps/web/tests/Account.test.tsx index be6d5105..c35c0287 100644 --- a/apps/web/tests/Account.test.tsx +++ b/apps/web/tests/Account.test.tsx @@ -157,3 +157,63 @@ describe('Account — accessibility structure', () => { }); }); }); + +describe('Account — Slack row', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + const CODE = { code: 'K7QW-4MZP', expiresAt: new Date(Date.now() + 10 * 60_000).toISOString(), botDmUrl: 'https://example.slack.com/app_redirect?channel=UBOT' }; + + /** /api/auth/me reports not linked until the code has been issued `pollsUntilLinked` polls ago. */ + function mockSlack(pollsUntilLinked: number | null) { + let issued = false; + let polls = 0; + const json = (body: unknown, status = 200) => + Promise.resolve(new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })); + const calls: string[] = []; + vi.spyOn(globalThis, 'fetch').mockImplementation(((input: string, init?: RequestInit) => { + calls.push(`${init?.method ?? 'GET'} ${input}`); + if (input.startsWith('/api/auth/me')) { + if (issued) polls += 1; + const linked = issued && pollsUntilLinked !== null && polls > pollsUntilLinked; + return json(mockOk({ ...githubPerson, slack: linked ? { linked: true, linkedAt: '2026-11-20T12:00:00Z' } : { linked: false, linkedAt: null } })); + } + if (input.startsWith('/api/account/slack-link/code')) { + issued = true; + return json(mockOk(CODE)); + } + if (input.startsWith('/api/account/slack-link')) return Promise.resolve(new Response(null, { status: 204 })); + if (input.startsWith('/api/auth/sessions')) return json(mockOk([])); + return Promise.resolve(new Response(null, { status: 404 })); + }) as typeof fetch); + return calls; + } + + it('Connect Slack shows the code and the DM instruction, then turns connected when the bot confirms', async () => { + const calls = mockSlack(0); + render(); + const button = await screen.findByRole('button', { name: 'Connect Slack' }); + button.click(); + expect(await screen.findByTestId('slack-link-code')).toHaveTextContent('K7QW-4MZP'); + expect(screen.getByText(/within 10 minutes/i)).toBeInTheDocument(); + expect(screen.getByRole('link', { name: /the ops bot/i })).toHaveAttribute('href', CODE.botDmUrl); + await waitFor(() => expect(screen.getByText(/connected to slack ✓ since/i)).toBeInTheDocument(), { timeout: 5000 }); + expect(screen.queryByTestId('slack-link-code')).not.toBeInTheDocument(); + expect(calls).toContain('POST /api/account/slack-link/code'); + }); + + it('a linked account shows Connected with Disconnect, and never a Slack user id', async () => { + vi.spyOn(globalThis, 'fetch').mockImplementation(((input: string) => { + const body = input.startsWith('/api/auth/me') + ? mockOk({ ...githubPerson, slack: { linked: true, linkedAt: '2026-11-20T12:00:00Z' } }) + : mockOk([]); + return Promise.resolve(new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } })); + }) as typeof fetch); + render(); + expect(await screen.findByText(/connected to slack ✓ since/i)).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Disconnect' })).toBeInTheDocument(); + expect(screen.getByText(/act on your replies/i)).toBeInTheDocument(); + expect(document.body.textContent).not.toMatch(/\bU[A-Z0-9]{6,}\b/); + }); +}); From 9f8f68bb56682a0939a7deac68f08fafff6b2db9 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:21:19 +0000 Subject: [PATCH 59/78] docs(ops): SLACK_TEAM_ID and SLACK_OPS_BOT_DM_URL Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .env.example | 8 ++++++++ docs/operations/deploy.md | 2 ++ 2 files changed, 10 insertions(+) diff --git a/.env.example b/.env.example index a9e71502..72715d83 100644 --- a/.env.example +++ b/.env.example @@ -80,6 +80,14 @@ CFP_JWT_SIGNING_KEY=change-me-to-a-random-string-at-least-32-chars # /chat + /launch redirects. Never used for our own entity ID or endpoints. # SLACK_TEAM_HOST=codeforphilly.slack.com +# Slack workspace id (T…) the site serves. Slack account links and an agent's +# on-behalf decisions naming another workspace are refused; unset, no link can +# be made. See specs/api/slack-link.md. +# SLACK_TEAM_ID=TEXAMPLE01 + +# Optional: a link that opens a DM with the ops bot, shown on /account. +# SLACK_OPS_BOT_DM_URL=https://codeforphilly.slack.com/app_redirect?channel=U... + # --------------------------------------------------------------------------- # Static SPA serving (production only) # --------------------------------------------------------------------------- diff --git a/docs/operations/deploy.md b/docs/operations/deploy.md index 97d90d32..bf3f4219 100644 --- a/docs/operations/deploy.md +++ b/docs/operations/deploy.md @@ -287,6 +287,8 @@ comments. Production pod gets these mounted: | `CFP_JWT_SIGNING_KEY` | **Secret** (`codeforphilly-secrets`) | HS256 key (`openssl rand -base64 64`) | | `SAML_PRIVATE_KEY` / `SAML_CERTIFICATE` | **Secret** (`codeforphilly-saml`, prod) | Slack IdP key pair, carried over verbatim from laddr's `saml2` secret so Slack keeps trusting the same cert. Mounted via an extra `envFrom` patch in the live cluster repo; marked `optional` so a sandbox without it still boots. | | `SLACK_TEAM_HOST` | ConfigMap | Slack workspace host (default `codeforphilly.slack.com`). ACS URL, NameID `NameQualifier`, `/chat` + `/launch` redirect target. Never our own IdP identity. | +| `SLACK_TEAM_ID` | ConfigMap | The workspace id (`T…`) of the Code for Philly Slack. Required for [Slack account links](../../specs/api/slack-link.md) and agent decisions on an admin's behalf; unset, every link redemption is refused (fails closed). Not a secret. | +| `SLACK_OPS_BOT_DM_URL` | ConfigMap | Optional. A link that opens a DM with the ops bot (e.g. `https://codeforphilly.slack.com/app_redirect?channel=<bot user id>`); the Account screen's Slack row links the bot's name to it. | | `GIT_SSH_COMMAND` | ConfigMap | Wires `ssh` to the mounted deploy key | | `GIT_AUTHOR_NAME` / `GIT_AUTHOR_EMAIL` | ConfigMap | Committer identity for API-authored data commits | From b071b2192bb3956da2375912a22fab6ab3fbfe76 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:38:20 +0000 Subject: [PATCH 60/78] chore(plans): mark slack-account-link done (PR #TBD) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- plans/slack-account-link.md | 60 ++++++++++++++++++++++++++++++++----- 1 file changed, 52 insertions(+), 8 deletions(-) diff --git a/plans/slack-account-link.md b/plans/slack-account-link.md index 39c5226a..c4a645a0 100644 --- a/plans/slack-account-link.md +++ b/plans/slack-account-link.md @@ -1,5 +1,5 @@ --- -status: in-progress +status: done depends: [] specs: - specs/api/slack-link.md @@ -51,15 +51,15 @@ Account screen's Slack row; purge removes the link. ## Validation -- [ ] Tests: a code redeems once for the person who issued it; expired, reused and unknown codes all return the same `404 code_invalid`; issuing a new code voids the old one -- [ ] Tests: a Slack user linked to account A cannot be linked to B (`409 slack_user_linked`); disconnect clears it; wrong `slackTeamId` → `422` -- [ ] Tests: a grant without `slack:link` gets `401`/`403` on the agent route; 11 failed redemptions in an hour are refused -- [ ] No code or Slack id appears in either data store's public side, any commit, or request logs (log redaction test) -- [ ] Minting `projects:applications:decide` without `projects:applications:read` and `slack:link` returns `422` +- [x] Tests: a code redeems once for the person who issued it; expired, reused and unknown codes all return the same `404 code_invalid`; issuing a new code voids the old one +- [x] Tests: a Slack user linked to account A cannot be linked to B (`409 slack_user_linked`); disconnect clears it; wrong `slackTeamId` → `422` +- [x] Tests: a grant without `slack:link` gets `401`/`403` on the agent route; 11 failed redemptions in an hour are refused +- [x] No code or Slack id appears in either data store's public side, any commit, or request logs (log redaction test) +- [x] Minting `projects:applications:decide` without `projects:applications:read` and `slack:link` returns `422` - [ ] `agent-grants/v2` adopted and mirrored; CI passes -- [ ] Browser: Account → Connect Slack shows a code; redeeming it with a test grant via the API turns the row to "Connected" +- [x] Browser: Account → Connect Slack shows a code; redeeming it with a test grant via the API turns the row to "Connected" - [ ] End to end with the ops bot in the real workspace (awaits the bot PR) -- [ ] `npm run type-check && npm run lint && npm test` clean +- [x] `npm run type-check && npm run lint && npm test` clean ## Risks / unknowns @@ -68,4 +68,48 @@ Account screen's Slack row; purge removes the link. ## Notes +- **Two criteria open.** `agent-grants/v2` is generated, published in + `contracts/` and mirrored into `apps/api/gitsheets/` (vendored with + `gitsheets contracts adopt`; the sheet config declares v2), but adopting + it on the data repo's branches is codeforphilly-data work, so CI's + `check:sheet-configs` will report drift until then (as for the v3 + contracts in this branch's base). The end-to-end check waits on the bot's + DM handler; its `awaits:` entry stays because that PR is still to come. +- **Spec fixes** (`docs(specs): settle the gaps…`): the code is 8 characters + shown as two groups of four (the example had 7); the code response carries + `botDmUrl` (`SLACK_OPS_BOT_DM_URL`) so the row can link the bot's name; an + account with no private profile is refused (`422 no_private_profile`); + redemption fails closed with no `SLACK_TEAM_ID`; a 409 does not spend the + code; `/me`'s `slack` in auth.md; both linking paths are credential + endpoints; agent-grants contract v2 in data-model. +- **Lockout is per agent account** (the spec says per agent; the plan's + Approach said per grant): ten `code_invalid` answers in an hour lock that + agent out for an hour, even for a valid code. A wrong workspace or a 409 + does not count as a failure. +- **`/api/agent/*` checks the scope before the body** (a `preValidation` + hook), and the scope's companions at use as well as at mint, so a grant + record written by hand without them is refused (`401`). +- **Profile rewrites keep the link.** Four places rebuilt the private profile + field by field (GitHub email change, claim, claim merge, staff email edit) + and would have dropped `slack`; they carry it. A claim merge keeps a link + made from either account. Not guarded: a lost update if a GitHub sign-in + rewrites the profile in the same instant as a redemption (both + read-then-write the private profile). +- Redemptions run one at a time in-process, so two cannot link one Slack + user to two accounts. Codes are swept on read; a restart drops them. +- Browser check on a local app with made-up fixtures: signed in as a test + member by legacy password, Account → Connect Slack showed a code and the + DM instruction with the bot link; redeeming it with a test grant via the + API turned the row to "Connected to Slack ✓ since …" with Disconnect, on + its next poll. Neither data repo history nor the API log held the code or + the Slack id; the private profiles file held the id. +- Gate at this commit's tree: check-contracts, type-check, lint, tests + (API 68 files / 807, web 36 / 218, shared 5 / 120) clean. + ## Follow-ups + +- codeforphilly-data: adopt `agent-grants/v2` on `empty`, `fixture`, + `legacy-import`, then `published` at release (no migration: v2 only widens + the scope enum). +- Deploy: set `SLACK_TEAM_ID` (and optionally `SLACK_OPS_BOT_DM_URL`) in the + ConfigMap; without it no link can be made. From def6c539c5ff7142746b316297cad17105143b12 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:38:20 +0000 Subject: [PATCH 61/78] chore(plans): mark agent-application-feed in-progress Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- plans/agent-application-feed.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plans/agent-application-feed.md b/plans/agent-application-feed.md index 70cd3939..75cb1682 100644 --- a/plans/agent-application-feed.md +++ b/plans/agent-application-feed.md @@ -1,5 +1,5 @@ --- -status: planned +status: in-progress depends: [membership-applications, slack-account-link] specs: - specs/api/agent-applications.md From 81a4167f6fafcf6cc61ee1056d9fee932af0535f Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:39:47 +0000 Subject: [PATCH 62/78] feat(api): GET /api/agent/events, the application feed for agents projects:applications:read. Events are derived from the membership records on each read: application.visible at notifiedAt, .reminder at remindedAt, .accepted at decidedAt, .closed at closedAt. A held application, one withdrawn before admins could see it, and every event of a deactivated applicant or deleted project are left out. Each event names the project, the applicant's facts, the application (offer, needs, decidedBy, decidedVia, closedBy) and the active admins, with a Slack user id only for a verified link in this workspace; no email anywhere. Ordered by (at, record id, type) with a base64url cursor that survives a restart; 7-day default window; events show once a minute old, and the sweep stamps its notice bookkeeping when it commits rather than when it started, so nothing lands behind a cursor. hasSlackLink reads the typed field now. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/src/app.ts | 2 + apps/api/src/plugins/services.ts | 3 + apps/api/src/routes/agent-applications.ts | 41 +++ apps/api/src/services/agent-feed.ts | 232 +++++++++++++++ apps/api/src/services/application-notices.ts | 5 +- apps/api/src/services/memberships.ts | 8 +- apps/api/tests/agent-feed.test.ts | 288 +++++++++++++++++++ 7 files changed, 572 insertions(+), 7 deletions(-) create mode 100644 apps/api/src/routes/agent-applications.ts create mode 100644 apps/api/src/services/agent-feed.ts create mode 100644 apps/api/tests/agent-feed.test.ts diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 5f44cbc6..e3b28c21 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -69,6 +69,7 @@ import { chatRoutes } from './routes/chat.js'; import { moderationRoutes } from './routes/moderation.js'; import { agentRoutes } from './routes/agents.js'; import { slackLinkRoutes } from './routes/slack-link.js'; +import { agentApplicationRoutes } from './routes/agent-applications.js'; import { webhookRoutes } from './routes/webhooks.js'; import { samlRoutes } from './routes/saml.js'; import { internalRoutes } from './routes/internal.js'; @@ -225,6 +226,7 @@ export async function buildApp(opts: BuildAppOptions = {}): Promise<FastifyInsta await fastify.register(moderationRoutes); await fastify.register(agentRoutes); await fastify.register(slackLinkRoutes); + await fastify.register(agentApplicationRoutes); await fastify.register(webhookRoutes); await fastify.register(samlRoutes); await fastify.register(internalRoutes); diff --git a/apps/api/src/plugins/services.ts b/apps/api/src/plugins/services.ts index b10a457c..12c02ce7 100644 --- a/apps/api/src/plugins/services.ts +++ b/apps/api/src/plugins/services.ts @@ -44,6 +44,7 @@ import { FollowerMailer } from '../services/follower-mail.js'; import { ProjectApplicationService } from '../services/project-application.js'; import { ApplicationNotices } from '../services/application-notices.js'; import { SlackLinkService } from '../services/slack-link.js'; +import { AgentFeedService } from '../services/agent-feed.js'; declare module 'fastify' { interface FastifyInstance { @@ -76,6 +77,7 @@ declare module 'fastify' { agentPurge: AgentPurgeService; spamPurges: SpamPurgeLogService; slackLinks: SlackLinkService; + agentFeed: AgentFeedService; }; /** Shared in-memory state — write routes call StateApply.apply against this. */ inMemoryState: InMemoryState; @@ -204,6 +206,7 @@ async function servicesPlugin(fastify: FastifyInstance): Promise<void> { teamId: fastify.config.SLACK_TEAM_ID, botDmUrl: fastify.config.SLACK_OPS_BOT_DM_URL, }), + agentFeed: new AgentFeedService(state, fastify.store.private, { teamId: fastify.config.SLACK_TEAM_ID }), }); } diff --git a/apps/api/src/routes/agent-applications.ts b/apps/api/src/routes/agent-applications.ts new file mode 100644 index 00000000..ad09aa31 --- /dev/null +++ b/apps/api/src/routes/agent-applications.ts @@ -0,0 +1,41 @@ +/** + * Agent applications routes — specs/api/agent-applications.md. + * + * GET /api/agent/events — agent:projects:applications:read + * + * The scope is checked before the query or body is validated, so a caller + * without it learns nothing from a validation error. Signed-in people and + * staff are anonymous here (401), like any caller without the grant. + */ +import type { FastifyInstance } from 'fastify'; + +import { agentScopeCaller } from '../auth/caller.js'; + +export async function agentApplicationRoutes(fastify: FastifyInstance): Promise<void> { + fastify.get( + '/api/agent/events', + { + preValidation: async (request) => { + agentScopeCaller(request, 'projects:applications:read'); + }, + schema: { + tags: ['agent-applications'], + summary: 'Application events after a cursor (agent:projects:applications:read)', + querystring: { + type: 'object', + properties: { + after: { type: 'string', maxLength: 512 }, + limit: { type: 'integer', minimum: 1, maximum: 200 }, + }, + additionalProperties: false, + }, + }, + }, + async (request) => { + agentScopeCaller(request, 'projects:applications:read'); + const q = request.query as { after?: string; limit?: number }; + const { data, next } = await fastify.services.agentFeed.events(q); + return { success: true, data, metadata: { timestamp: new Date().toISOString(), next } }; + }, + ); +} diff --git a/apps/api/src/services/agent-feed.ts b/apps/api/src/services/agent-feed.ts new file mode 100644 index 00000000..a33ea7d7 --- /dev/null +++ b/apps/api/src/services/agent-feed.ts @@ -0,0 +1,232 @@ +/** + * The application event feed for agents — specs/api/agent-applications.md → + * GET /api/agent/events. + * + * A view, not a stored log: events are derived from the membership records' + * `application` timestamps on every read. + * + * | type | at | + * | ---------------------- | ------------ | + * | application.visible | notifiedAt | + * | application.reminder | remindedAt | + * | application.accepted | decidedAt | + * | application.closed | closedAt | + * + * Hidden records never appear: an application whose hold has not ended (or + * that was closed before admins could see it), and every event of a + * deactivated or missing applicant or a deleted project. No email address + * is in any event; an admin's Slack user id is there only when they have a + * verified link in the workspace the site serves. + * + * Ordered by `(at, record id, type)`. The cursor is that triple, base64url + * JSON, so it survives restarts. An event appears once it is + * {@link FEED_SETTLE_MS} old, so a write whose timestamp was taken just + * before it committed cannot land behind a cursor already handed out. + */ +import type { Person, ProjectMembership } from '@cfp/shared/schemas'; + +import { ApiValidationError } from '../lib/errors.js'; +import { personBySlug, projectBySlug, type InMemoryState } from '../store/memory/state.js'; +import type { PrivateStore } from '../store/private/interface.js'; +import { adminPeople } from './memberships.js'; +import { applicantFacts } from './project-application.js'; + +const DAY = 24 * 60 * 60 * 1000; +export const FEED_DEFAULT_WINDOW_MS = 7 * DAY; +export const FEED_SETTLE_MS = 60 * 1000; +export const FEED_DEFAULT_LIMIT = 100; +export const FEED_MAX_LIMIT = 200; + +export const FEED_EVENT_TYPES = [ + 'application.visible', + 'application.reminder', + 'application.accepted', + 'application.closed', +] as const; +export type FeedEventType = (typeof FEED_EVENT_TYPES)[number]; + +interface Position { + readonly at: number; + readonly id: string; + /** Index into FEED_EVENT_TYPES; -1 sorts before every event at (at, id). */ + readonly t: number; +} + +export function encodeCursor(p: Position): string { + return Buffer.from(JSON.stringify([p.at, p.id, p.t]), 'utf8').toString('base64url'); +} + +export function decodeCursor(cursor: string): Position { + try { + const v: unknown = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')); + if ( + Array.isArray(v) && + v.length === 3 && + Number.isFinite(v[0]) && + typeof v[1] === 'string' && + Number.isInteger(v[2]) && + v[2] >= -1 && + v[2] < FEED_EVENT_TYPES.length + ) { + return { at: v[0] as number, id: v[1], t: v[2] as number }; + } + } catch { + // fall through + } + throw new ApiValidationError('after is not a cursor from this feed', { after: 'invalid' }); +} + +function compare(a: Position, b: Position): number { + if (a.at !== b.at) return a.at - b.at; + if (a.id !== b.id) return a.id < b.id ? -1 : 1; + return a.t - b.t; +} + +interface PersonRef { + readonly slug: string; + readonly fullName: string; +} + +export interface FeedEvent { + readonly cursor: string; + readonly type: FeedEventType; + readonly at: string; + readonly project: { readonly slug: string; readonly title: string; readonly chatChannel: string | null }; + readonly applicant: PersonRef & { + readonly accountCreatedAt: string; + readonly hasGitHubLink: boolean; + readonly memberOf: Array<{ slug: string; title: string }>; + }; + readonly application: { + readonly status: 'open' | 'accepted' | 'closed'; + readonly roles: Array<{ id: string; title: string }>; + readonly offer: string | null; + readonly submittedAt: string; + readonly decidedBy: PersonRef | null; + readonly decidedVia: 'site' | 'agent' | null; + readonly closedBy: 'admin' | 'applicant' | 'site' | null; + }; + readonly admins: Array<PersonRef & { readonly slackUserId: string | null }>; +} + +/** The raw events one record yields, before visibility and window filters. */ +function eventsOf(m: ProjectMembership): Array<Position & { type: FeedEventType }> { + const app = m.application; + if (!app) return []; + const out: Array<Position & { type: FeedEventType }> = []; + const push = (type: FeedEventType, iso: string | null | undefined) => { + if (!iso) return; + const at = Date.parse(iso); + if (Number.isFinite(at)) out.push({ at, id: m.id, t: FEED_EVENT_TYPES.indexOf(type), type }); + }; + const visibleAt = Date.parse(app.visibleAt); + push('application.visible', app.notifiedAt); + push('application.reminder', app.remindedAt); + if (app.status === 'accepted') push('application.accepted', app.decidedAt); + // Closed before admins could see it (the applicant withdrew during the hold): never shown. + if (app.status === 'closed' && app.closedAt && Date.parse(app.closedAt) >= visibleAt) { + push('application.closed', app.closedAt); + } + return out; +} + +export class AgentFeedService { + readonly #state: InMemoryState; + readonly #privateStore: PrivateStore; + readonly #teamId: string | undefined; + + constructor(state: InMemoryState, privateStore: PrivateStore, opts: { teamId?: string | undefined }) { + this.#state = state; + this.#privateStore = privateStore; + this.#teamId = opts.teamId; + } + + async events( + query: { after?: string | undefined; limit?: number | undefined }, + now: Date = new Date(), + ): Promise<{ data: FeedEvent[]; next: string }> { + const limit = query.limit ?? FEED_DEFAULT_LIMIT; + if (!Number.isInteger(limit) || limit < 1 || limit > FEED_MAX_LIMIT) { + throw new ApiValidationError(`limit is 1–${FEED_MAX_LIMIT}`, { limit: 'out_of_range' }); + } + const after: Position | null = query.after ? decodeCursor(query.after) : null; + const t = now.getTime(); + const horizon = t - FEED_SETTLE_MS; + const floor = t - FEED_DEFAULT_WINDOW_MS; + + const s = this.#state; + const raw: Array<Position & { type: FeedEventType; m: ProjectMembership }> = []; + for (const m of s.projectMemberships.values()) { + const app = m.application; + // Held (hold not over) → nothing, whatever else is on the record. + if (!app || Date.parse(app.visibleAt) > t) continue; + const applicant = personBySlug(s, m.personSlug); + if (!applicant || applicant.deletedAt) continue; + const project = projectBySlug(s, m.projectSlug); + if (!project || project.deletedAt) continue; + for (const e of eventsOf(m)) { + if (e.at > horizon) continue; + if (after ? compare(e, after) <= 0 : e.at < floor) continue; + raw.push({ ...e, m }); + } + } + raw.sort(compare); + const page = raw.slice(0, limit); + + const data: FeedEvent[] = []; + for (const e of page) data.push(await this.#serialize(e, e.type, e.m)); + const last = page[page.length - 1]; + const next = last + ? encodeCursor(last) + : (query.after ?? encodeCursor({ at: Math.max(horizon, floor), id: '', t: -1 })); + return { data, next }; + } + + async #serialize(pos: Position, type: FeedEventType, m: ProjectMembership): Promise<FeedEvent> { + const s = this.#state; + const project = projectBySlug(s, m.projectSlug)!; + const applicant = personBySlug(s, m.personSlug)!; + const app = m.application!; + const facts = applicantFacts(s, applicant, project.slug); + const decider = app.decidedById ? s.people.get(app.decidedById) : undefined; + return { + cursor: encodeCursor(pos), + type, + at: new Date(pos.at).toISOString(), + project: { slug: project.slug, title: project.title, chatChannel: project.chatChannel ?? null }, + applicant: { + slug: applicant.slug, + fullName: applicant.fullName, + accountCreatedAt: facts.accountCreatedAt, + hasGitHubLink: facts.hasGitHubLink, + memberOf: facts.memberOf, + }, + application: { + status: app.status, + roles: app.roleIds.map((id) => ({ id, title: s.helpWantedRoles.get(id)?.title ?? 'Removed need' })), + offer: app.offer ?? null, + submittedAt: app.submittedAt, + decidedBy: decider && !decider.deletedAt ? ref(decider) : null, + decidedVia: app.decidedVia ?? null, + closedBy: app.closedBy ?? null, + }, + admins: await this.#admins(project.slug), + }; + } + + /** The project's active admins, each with a Slack user id only when verified-linked in this workspace. */ + async #admins(projectSlug: string): Promise<FeedEvent['admins']> { + const out: Array<PersonRef & { slackUserId: string | null }> = []; + for (const person of adminPeople(this.#state, projectSlug)) { + if (person.deletedAt) continue; + const slack = (await this.#privateStore.getProfile(person.id))?.slack; + const linked = slack && this.#teamId !== undefined && slack.teamId === this.#teamId; + out.push({ ...ref(person), slackUserId: linked ? slack.userId : null }); + } + return out; + } +} + +function ref(p: Person): PersonRef { + return { slug: p.slug, fullName: p.fullName }; +} diff --git a/apps/api/src/services/application-notices.ts b/apps/api/src/services/application-notices.ts index 1d8707be..32b2800e 100644 --- a/apps/api/src/services/application-notices.ts +++ b/apps/api/src/services/application-notices.ts @@ -195,7 +195,10 @@ export class ApplicationSweepService { else if (!app.remindedAt && t >= visibleAt + REMINDER_AFTER_MS) due.push({ m, reminder: true }); } if (due.length > 0) { - const at = now.toISOString(); + // Taken now, not at the start of the run: the closes and their emails + // above may have taken a while, and the agent feed orders events by + // these stamps (agent-applications.md → GET /api/agent/events). + const at = new Date(Math.max(now.getTime(), Date.now())).toISOString(); const marked = due.map(({ m, reminder }) => ({ reminder, m: { ...m, application: { ...m.application!, ...(reminder ? { remindedAt: at } : { notifiedAt: at }) } }, diff --git a/apps/api/src/services/memberships.ts b/apps/api/src/services/memberships.ts index 5559a104..4bf18b2a 100644 --- a/apps/api/src/services/memberships.ts +++ b/apps/api/src/services/memberships.ts @@ -105,13 +105,9 @@ export function hasDeliverableEmail(profile: PrivateProfile | null | undefined): return Boolean(profile?.email) && profile?.emailBounce?.inactive !== true; } -/** - * A verified Slack link on the profile (specs/api/slack-link.md). The field - * arrives with the Slack-linking plan; until then no profile carries it. - */ +/** A verified Slack link on the profile (specs/api/slack-link.md). */ export function hasSlackLink(profile: PrivateProfile | null | undefined): boolean { - const slack = (profile as { slack?: unknown } | null | undefined)?.slack; - return slack !== undefined && slack !== null; + return Boolean(profile?.slack); } /** diff --git a/apps/api/tests/agent-feed.test.ts b/apps/api/tests/agent-feed.test.ts new file mode 100644 index 00000000..6f331657 --- /dev/null +++ b/apps/api/tests/agent-feed.test.ts @@ -0,0 +1,288 @@ +/** + * The application event feed for agents (plans/agent-application-feed.md, + * specs/api/agent-applications.md → GET /api/agent/events): the four event + * types at the right `at`, the 7-day window, paging that returns every event + * once across pages and a restart, hidden records left out, admins' Slack + * ids only when linked, no email anywhere, and the scope. + * + * Every person, workspace and Slack id here is invented; addresses are example.org. + */ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { buildApp } from '../src/app.js'; +import { FEED_SETTLE_MS } from '../src/services/agent-feed.js'; +import { + JWT_KEY, + bearer, + createAgent, + daysAgo, + fid, + minutesAgo, + personRecord, + privateProfile, + startAgentTestEnv, + type AgentTestEnv, + type Rec, +} from './helpers/agent-fixtures.js'; + +const TEAM = 'TEXAMPLE01'; +const P = { + ada: 1, bounce: 2, olly: 3, ben: 4, root: 5, sam: 6, + dee: 10, old: 11, acc: 12, clo: 13, nina: 14, wd: 15, hal: 16, fresh: 17, far: 18, gina: 19, +}; +const T = '2026-05-01T00:00:00.000Z'; +const ROLE = fid(300); + +let n = 1000; +const rec = (project: string, person: string, state: 'follower' | 'applicant' | 'member', over: Rec = {}): Rec => ({ + id: fid(n++), + projectSlug: project, + personSlug: person, + state, + isAdmin: false, + muted: false, + followedAt: T, + createdAt: T, + updatedAt: T, + ...(state === 'member' ? { via: 'legacy', joinedAt: T } : {}), + ...over, +}); +const app = (over: Rec): Rec => ({ application: { status: 'open', roleIds: [], offer: 'Happy to help.', ...over } }); + +// Times, fixed per run. +const at = { + deeVisible: minutesAgo(180), + oldVisible: daysAgo(15), + oldReminded: daysAgo(1), + accNotified: minutesAgo(300), + accDecided: minutesAgo(120), + cloNotified: minutesAgo(240), + cloClosed: minutesAgo(60), + ninaVisible: new Date(Date.now() + 6 * 3600_000).toISOString(), + wdVisible: minutesAgo(30), + wdClosed: minutesAgo(90), + freshNotified: new Date(Date.now() - 10_000).toISOString(), + ginaVisible: minutesAgo(200), +}; + +function records(): Record<string, Rec[]> { + n = 1000; + return { + people: [ + ...Object.entries(P).map(([slug, k]) => + personRecord(k, slug, { + ...(slug === 'olly' || slug === 'hal' ? { deletedAt: daysAgo(2) } : {}), + ...(slug === 'root' ? { accountLevel: 'administrator' } : {}), + ...(slug === 'sam' ? { accountLevel: 'staff' } : {}), + ...(slug === 'nina' ? { createdAt: minutesAgo(60) } : {}), + ...(slug === 'dee' ? { githubUserId: 4242, githubLogin: 'dee-gh' } : {}), + }), + ), + ], + projects: [ + { id: fid(50), slug: 'proj', title: 'Project Proj', stage: 'testing', featured: false, chatChannel: 'proj-chat', createdAt: T, updatedAt: T }, + { id: fid(51), slug: 'side', title: 'Side', stage: 'testing', featured: false, createdAt: T, updatedAt: T }, + ], + 'help-wanted-roles': [ + { id: ROLE, projectSlug: 'proj', postedById: fid(P.ada), title: 'Frontend dev', description: 'React.', status: 'open', createdAt: T, updatedAt: T }, + ], + 'project-memberships': [ + rec('proj', 'ada', 'member', { isAdmin: true }), + rec('proj', 'bounce', 'member', { isAdmin: true }), + rec('proj', 'olly', 'member', { isAdmin: true }), + rec('proj', 'ben', 'member'), + rec('side', 'dee', 'member'), + rec('proj', 'dee', 'applicant', app({ roleIds: [ROLE], submittedAt: at.deeVisible, visibleAt: at.deeVisible, notifiedAt: at.deeVisible })), + rec('proj', 'old', 'applicant', app({ submittedAt: at.oldVisible, visibleAt: at.oldVisible, notifiedAt: at.oldVisible, remindedAt: at.oldReminded })), + rec('proj', 'acc', 'member', { + via: 'application', joinedAt: at.accDecided, + ...app({ status: 'accepted', submittedAt: at.accNotified, visibleAt: at.accNotified, notifiedAt: at.accNotified, decidedById: fid(P.ada), decidedAt: at.accDecided, decidedVia: 'site' }), + }), + rec('proj', 'clo', 'follower', app({ + status: 'closed', submittedAt: at.cloNotified, visibleAt: at.cloNotified, notifiedAt: at.cloNotified, + closedBy: 'admin', closedAt: at.cloClosed, decidedById: fid(P.ada), decidedAt: at.cloClosed, decidedVia: 'site', + })), + // Held: a new account; admins have not been told. + rec('proj', 'nina', 'applicant', app({ submittedAt: minutesAgo(30), visibleAt: at.ninaVisible, notifiedAt: null })), + // Withdrawn during the hold, before admins could see it. + rec('proj', 'wd', 'follower', app({ status: 'closed', submittedAt: minutesAgo(120), visibleAt: at.wdVisible, closedBy: 'applicant', closedAt: at.wdClosed })), + // Deactivated applicant. + rec('proj', 'hal', 'applicant', app({ submittedAt: at.deeVisible, visibleAt: at.deeVisible, notifiedAt: at.deeVisible })), + // Too new to have settled. + rec('proj', 'fresh', 'applicant', app({ submittedAt: at.freshNotified, visibleAt: at.freshNotified, notifiedAt: at.freshNotified })), + // Outside the default window entirely. + rec('proj', 'far', 'applicant', app({ submittedAt: daysAgo(10), visibleAt: daysAgo(10), notifiedAt: daysAgo(10) })), + // Visible but the sweep has not notified yet. + rec('proj', 'gina', 'applicant', app({ submittedAt: at.ginaVisible, visibleAt: at.ginaVisible, notifiedAt: null })), + ], + }; +} + +const PROFILES = Object.entries(P).map(([slug, k]) => + privateProfile(fid(k), `${slug}@example.org`, { + ...(slug === 'ada' ? { slack: { teamId: TEAM, userId: 'UADA000001', linkedAt: T } } : {}), + ...(slug === 'olly' ? { slack: { teamId: TEAM, userId: 'UOLLY00001', linkedAt: T } } : {}), + // A link in some other workspace never counts. + ...(slug === 'bounce' ? { slack: { teamId: 'TOTHER0001', userId: 'UBOUNCE001', linkedAt: T } } : {}), + }), +); + +interface Ev { + cursor: string; + type: string; + at: string; + applicant: { slug: string }; + application: { status: string; decidedBy: { slug: string } | null; decidedVia: string | null; closedBy: string | null; roles: Array<{ title: string }> }; + admins: Array<{ slug: string; slackUserId: string | null }>; + project: { slug: string; chatChannel: string | null }; +} + +describe('agent application feed', () => { + let env: AgentTestEnv; + let token: string; + + beforeEach(async () => { + env = await startAgentTestEnv({ records: records(), profiles: PROFILES, env: { SLACK_TEAM_ID: TEAM } }); + token = (await createAgent(env, await env.cookie(P.root, 'administrator'), { slug: 'example-bot', scopes: ['projects:applications:read'] })).token; + }); + afterEach(async () => { + await env.close(); + }); + + const feed = async (query = '', tok = token) => { + const res = await env.app.inject({ method: 'GET', url: `/api/agent/events${query}`, ...bearer(tok) }); + expect(res.statusCode, res.body).toBe(200); + return res.json<{ data: Ev[]; metadata: { next: string } }>(); + }; + const key = (e: Ev) => `${e.type} ${e.applicant.slug}`; + + it('yields each event type once at the right at, in order, from the last 7 days', async () => { + const { data, metadata } = await feed(); + expect(data.map(key)).toEqual([ + 'application.reminder old', + 'application.visible acc', + 'application.visible clo', + 'application.visible dee', + 'application.accepted acc', + 'application.closed clo', + ]); + const byKey = new Map(data.map((e) => [key(e), e])); + expect(byKey.get('application.visible dee')!.at).toBe(at.deeVisible); + expect(byKey.get('application.reminder old')!.at).toBe(at.oldReminded); + expect(byKey.get('application.accepted acc')!.at).toBe(at.accDecided); + expect(byKey.get('application.closed clo')!.at).toBe(at.cloClosed); + expect(byKey.get('application.accepted acc')!.application).toMatchObject({ status: 'accepted', decidedBy: { slug: 'ada' }, decidedVia: 'site' }); + expect(byKey.get('application.closed clo')!.application).toMatchObject({ status: 'closed', closedBy: 'admin', decidedBy: { slug: 'ada' } }); + expect(byKey.get('application.visible dee')!.application.roles).toEqual([{ id: ROLE, title: 'Frontend dev' }]); + expect(byKey.get('application.visible dee')!).toMatchObject({ + project: { slug: 'proj', title: 'Project Proj', chatChannel: 'proj-chat' }, + applicant: { slug: 'dee', fullName: 'Test dee', hasGitHubLink: true, memberOf: [{ slug: 'side', title: 'Side' }] }, + }); + expect(metadata.next).toBe(data[data.length - 1]!.cursor); + }); + + it("lists the project's active admins with a Slack id only for a verified link in this workspace, and no email anywhere", async () => { + const res = await env.app.inject({ method: 'GET', url: '/api/agent/events', ...bearer(token) }); + const { data } = res.json<{ data: Ev[] }>(); + for (const e of data) { + expect(e.admins).toEqual([ + { slug: 'ada', fullName: 'Test ada', slackUserId: 'UADA000001' }, + { slug: 'bounce', fullName: 'Test bounce', slackUserId: null }, + ]); + } + // Schema test on the whole response: no key named like an email, no address. + const keys: string[] = []; + const walk = (v: unknown) => { + if (Array.isArray(v)) v.forEach(walk); + else if (v && typeof v === 'object') { + for (const [k, x] of Object.entries(v)) { + keys.push(k); + walk(x); + } + } + }; + walk(res.json()); + expect(keys.filter((k) => /mail/i.test(k))).toEqual([]); + expect(res.body).not.toMatch(/@/); + expect(res.body).not.toContain('UOLLY00001'); + expect(res.body).not.toContain('UBOUNCE001'); + }); + + it('pages with next: every event exactly once across pages and across a restart', async () => { + const all = (await feed()).data.map((e) => e.cursor); + const first = await feed('?limit=2'); + expect(first.data).toHaveLength(2); + + // A restart: a second app on the same stores reads on from the cursor. + const second = await buildApp({ + serverOptions: { logger: false }, + overrideEnv: { + CFP_DATA_REPO_PATH: env.dataPath, + STORAGE_BACKEND: 'filesystem', + CFP_PRIVATE_STORAGE_PATH: env.privatePath, + CFP_JWT_SIGNING_KEY: JWT_KEY, + NODE_ENV: 'test', + SLACK_TEAM_ID: TEAM, + }, + }); + await second.ready(); + try { + const seen = first.data.map((e) => e.cursor); + let next = first.metadata.next; + for (let i = 0; i < 10; i++) { + const res = await second.inject({ method: 'GET', url: `/api/agent/events?limit=2&after=${next}`, ...bearer(token) }); + expect(res.statusCode, res.body).toBe(200); + const page = res.json<{ data: Ev[]; metadata: { next: string } }>(); + if (page.data.length === 0) { + expect(page.metadata.next).toBe(next); + break; + } + seen.push(...page.data.map((e) => e.cursor)); + next = page.metadata.next; + } + expect(seen).toEqual(all); + } finally { + await second.close(); + } + }); + + it('a held application yields nothing until admins are notified; a deactivated applicant’s events vanish', async () => { + const svc = env.app.services.agentFeed; + expect((await feed()).data.some((e) => ['nina', 'wd', 'hal', 'gina', 'far'].includes(e.applicant.slug))).toBe(false); + + // The hold ends and the sweep notifies admins; once settled, the event appears at notifiedAt. + const later = new Date(Date.parse(at.ninaVisible) + 60_000); + await env.app.applicationSweep.sweep(later); + const afterSweep = await svc.events({}, new Date(Math.max(later.getTime(), Date.now()) + FEED_SETTLE_MS + 1000)); + const nina = afterSweep.data.find((e) => e.applicant.slug === 'nina'); + expect(nina?.type).toBe('application.visible'); + expect(afterSweep.data.find((e) => e.applicant.slug === 'gina')?.type).toBe('application.visible'); + expect(afterSweep.data.some((e) => e.applicant.slug === 'wd')).toBe(false); + + // dee is deactivated: every one of their events drops out. + const s = env.app.inMemoryState; + s.people.set(fid(P.dee), { ...s.people.get(fid(P.dee))!, deletedAt: new Date().toISOString() }); + expect((await feed()).data.some((e) => e.applicant.slug === 'dee')).toBe(false); + }); + + it('holds back events younger than a minute, and an empty page still gives a cursor to read on from', async () => { + const svc = env.app.services.agentFeed; + const now = await svc.events({}); + expect(now.data.some((e) => e.applicant.slug === 'fresh')).toBe(false); + const soon = await svc.events({ after: now.next }, new Date(Date.now() + FEED_SETTLE_MS + 1000)); + expect(soon.data.map((e) => e.applicant.slug)).toEqual(['fresh']); + + const empty = await svc.events({ after: soon.next }, new Date(Date.now() + FEED_SETTLE_MS + 2000)); + expect(empty.data).toEqual([]); + expect(empty.next).toBe(soon.next); + }); + + it('refuses a grant without the scope, staff and anonymous callers (401), and a bad cursor (422)', async () => { + const linkOnly = (await createAgent(env, await env.cookie(P.root, 'administrator'), { slug: 'link-bot', scopes: ['slack:link'] })).token; + expect((await env.app.inject({ method: 'GET', url: '/api/agent/events', ...bearer(linkOnly) })).statusCode).toBe(401); + expect((await env.app.inject({ method: 'GET', url: '/api/agent/events', cookies: { cfp_session: await env.cookie(P.sam, 'staff') } })).statusCode).toBe(401); + expect((await env.app.inject({ method: 'GET', url: '/api/agent/events' })).statusCode).toBe(401); + const bad = await env.app.inject({ method: 'GET', url: '/api/agent/events?after=nonsense', ...bearer(token) }); + expect(bad.statusCode).toBe(422); + }); +}); From e57769d6b969596be152cac635626c9e1851876a Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:51:53 +0000 Subject: [PATCH 63/78] chore(plans): mark agent-application-feed done (PR #TBD) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- plans/agent-application-feed.md | 40 ++++++++++++++++++++++++++++----- 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/plans/agent-application-feed.md b/plans/agent-application-feed.md index 75cb1682..03dea72e 100644 --- a/plans/agent-application-feed.md +++ b/plans/agent-application-feed.md @@ -1,5 +1,5 @@ --- -status: in-progress +status: done depends: [membership-applications, slack-account-link] specs: - specs/api/agent-applications.md @@ -38,12 +38,12 @@ over the `openApplications` index plus recently decided records; sort by ## Validation -- [ ] Tests: each event type appears once at the right `at`; paging with `next` returns every event exactly once across pages and across a restart -- [ ] Tests: a held application yields nothing until notified; a deactivated applicant's events vanish -- [ ] Tests: `admins[].slackUserId` is set only for linked, active admins; no field anywhere carries an email (schema test on the response) -- [ ] A grant without the scope is refused +- [x] Tests: each event type appears once at the right `at`; paging with `next` returns every event exactly once across pages and across a restart +- [x] Tests: a held application yields nothing until notified; a deactivated applicant's events vanish +- [x] Tests: `admins[].slackUserId` is set only for linked, active admins; no field anywhere carries an email (schema test on the response) +- [x] A grant without the scope is refused - [ ] End to end: an application on sandbox produces an AI-marked DM to its linked admin (awaits the bot PR and `mpim:write`) -- [ ] `npm run type-check && npm run lint && npm test` clean +- [x] `npm run type-check && npm run lint && npm test` clean ## Risks / unknowns @@ -51,4 +51,32 @@ over the `openApplications` index plus recently decided records; sort by ## Notes +- **End-to-end criterion open; both `awaits:` entries stay.** The bot's + heartbeat stream and the `mpim:write` install are still to come. +- **`application.visible` is at `notifiedAt`, not `visibleAt`** (spec fixed + in `docs(specs): settle the gaps…`, which this plan's Approach predates). + For a held application the sweep sets `notifiedAt` after `visibleAt`, so + an event at `visibleAt` could land behind a cursor already read. +- **A one-minute settle window.** An event shows once it is a minute old; + and the sweep now stamps its notice bookkeeping when it commits, not when + the run started (closes and their emails come first). Together they keep + a late-committed stamp from landing behind a handed-out cursor. Spec says so. +- **Cursor** is base64url JSON `[at ms, record id, type index]`; comparison + is numeric on `at`, so mixed timestamp spellings in records sort right. + `metadata.next` is never null: with no events it is the `after` passed, or + the settle horizon. +- **Hidden** also covers an application the applicant withdrew during its + hold (closed before `visibleAt`): no event at all. A visible application + the sweep has not yet notified has no `visible` event until it does. +- `application` carries `decidedBy`/`decidedVia`/`closedBy` as they stand + now (spec addition); `status` is the current one, so a `visible` event read + late may show `accepted`. +- The feed scans every membership on each read; fine at this scale. +- Smoke on a local app with made-up fixtures: the test grant read two + `application.visible` events with admins and no `@` anywhere in the body. +- Gate at this commit's tree: check-contracts, type-check, lint, tests + (API 69 files / 813, web 36 / 217, shared 5 / 120) clean. + ## Follow-ups + +None on the site side. From 7a2bc96863af250963b79ff527dd3c6656926065 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:51:53 +0000 Subject: [PATCH 64/78] chore(plans): mark agent-decide-on-behalf in-progress Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- plans/agent-decide-on-behalf.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plans/agent-decide-on-behalf.md b/plans/agent-decide-on-behalf.md index 6e28ba7e..16e4d2fd 100644 --- a/plans/agent-decide-on-behalf.md +++ b/plans/agent-decide-on-behalf.md @@ -1,5 +1,5 @@ --- -status: planned +status: in-progress depends: [agent-application-feed, needs-on-applications] specs: - specs/api/agent-applications.md From d9e7d3eeceb12ffecb67b6439f2cb0f7d52a1ce1 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:53:14 +0000 Subject: [PATCH 65/78] feat(api): the confirmation email to an admin an agent decided for MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "The ops bot recorded that you accepted …", naming the agent, how to undo it, and a link to the Applications screen. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/src/notify/email-notifier.ts | 11 ++++++++ apps/api/src/notify/index.ts | 23 ++++++++++++++++ apps/api/src/notify/membership-templates.ts | 29 +++++++++++++++++++++ apps/api/tests/membership-templates.test.ts | 17 ++++++++++++ 4 files changed, 80 insertions(+) diff --git a/apps/api/src/notify/email-notifier.ts b/apps/api/src/notify/email-notifier.ts index 6723dd24..db7d6a9b 100644 --- a/apps/api/src/notify/email-notifier.ts +++ b/apps/api/src/notify/email-notifier.ts @@ -14,6 +14,7 @@ import type { EventReminderNotification, EventRsvpNotification, EventUpdatedNotification, + AgentDecisionConfirmation, ApplicationDecisionNotification, MemberAddedNotification, NewApplicationNotification, @@ -34,6 +35,7 @@ import { renderWelcomeEmail, } from './templates.js'; import { + renderAgentDecisionConfirmationEmail, renderApplicationDecisionEmail, renderMemberAddedEmail, renderNewApplicationEmail, @@ -92,6 +94,15 @@ export class EmailNotifier implements Notifier { return this.#deliver('application notice', ctx, n.email, renderNewApplicationEmail(n, this.#siteHost)); } + async notifyAgentDecisionConfirmation(n: AgentDecisionConfirmation): Promise<{ delivered: boolean }> { + const ctx = { kind: `application.agent-${n.decision}`, project: n.projectSlug }; + if (!n.email) { + this.#log.warn(ctx, 'agent decision confirmation: no email address; skipped'); + return { delivered: false }; + } + return this.#deliver('agent decision confirmation', ctx, n.email, renderAgentDecisionConfirmationEmail(n, this.#siteHost)); + } + async notifyApplicationDecision(n: ApplicationDecisionNotification): Promise<{ delivered: boolean }> { const ctx = { kind: `application.${n.outcome}`, project: n.projectSlug }; if (!n.email) { diff --git a/apps/api/src/notify/index.ts b/apps/api/src/notify/index.ts index 18c61d49..0271417d 100644 --- a/apps/api/src/notify/index.ts +++ b/apps/api/src/notify/index.ts @@ -156,7 +156,25 @@ export interface ApplicationDecisionNotification { readonly chatChannel: string | null; } +/** + * To a project admin: an agent recorded a decision in their name + * (specs/behaviors/authorization.md → On behalf of a project admin), so a + * decision they did not make surfaces at once. + */ +export interface AgentDecisionConfirmation { + readonly email: string; + /** The admin's name. */ + readonly fullName: string; + readonly projectTitle: string; + readonly projectSlug: string; + readonly applicantName: string; + readonly decision: 'accepted' | 'closed'; + /** The agent account's name, e.g. "Example Ops Bot". */ + readonly agentName: string; +} + export interface Notifier { + notifyAgentDecisionConfirmation(n: AgentDecisionConfirmation): Promise<{ delivered: boolean }>; notifyNewApplication(n: NewApplicationNotification): Promise<{ delivered: boolean }>; notifyApplicationDecision(n: ApplicationDecisionNotification): Promise<{ delivered: boolean }>; notifyMemberAdded(n: MemberAddedNotification): Promise<{ delivered: boolean }>; @@ -193,6 +211,11 @@ export class LoggingNotifier implements Notifier { return { delivered: true }; } + async notifyAgentDecisionConfirmation(n: AgentDecisionConfirmation): Promise<{ delivered: boolean }> { + this.#log.info({ kind: `application.agent-${n.decision}`, project: n.projectSlug }, 'agent decision confirmation'); + return { delivered: true }; + } + async notifyApplicationDecision(n: ApplicationDecisionNotification): Promise<{ delivered: boolean }> { // Never the note: it is emailed and stored nowhere, logs included. this.#log.info({ kind: `application.${n.outcome}`, project: n.projectSlug }, 'application decision notification'); diff --git a/apps/api/src/notify/membership-templates.ts b/apps/api/src/notify/membership-templates.ts index 2ff93a44..3470c0d0 100644 --- a/apps/api/src/notify/membership-templates.ts +++ b/apps/api/src/notify/membership-templates.ts @@ -7,6 +7,7 @@ * never turned into a link by us. */ import type { + AgentDecisionConfirmation, ApplicationDecisionNotification, MemberAddedNotification, NewApplicationNotification, @@ -197,3 +198,31 @@ export function renderApplicationDecisionEmail(n: ApplicationDecisionNotificatio footer, ); } + +/** + * To the project admin an agent named: "The ops bot recorded that you + * accepted …", with a link to the Applications screen, so a decision they + * did not make surfaces at once (authorization.md → On behalf of a project admin). + */ +export function renderAgentDecisionConfirmationEmail(n: AgentDecisionConfirmation, siteHost: string): MembershipEmail { + const verb = n.decision === 'accepted' ? 'accepted' : 'closed'; + const what = + n.decision === 'accepted' + ? `accepted ${n.applicantName}'s application to ${n.projectTitle}; they are now a member` + : `closed ${n.applicantName}'s application to ${n.projectTitle}; they are still following the project`; + return renderBlocks( + `The ops bot recorded that you ${verb} an application to ${n.projectTitle}`, + [ + { p: `Hi ${n.fullName}, the ops bot (${n.agentName}) recorded in your name that you ${what}.` }, + { + p: + "If you didn't say so, tell the organizers. " + + (n.decision === 'accepted' + ? 'You can undo it by removing the member from the project.' + : 'You can undo it by adding the person to the project directly.'), + }, + { link: `${projectUrl(siteHost, n.projectSlug)}/applications`, label: 'Open the Applications screen' }, + ], + `You're receiving this because you are an admin of ${n.projectTitle} and your Slack account is linked to Code for Philly.`, + ); +} diff --git a/apps/api/tests/membership-templates.test.ts b/apps/api/tests/membership-templates.test.ts index 986befb4..8cdc8070 100644 --- a/apps/api/tests/membership-templates.test.ts +++ b/apps/api/tests/membership-templates.test.ts @@ -6,6 +6,7 @@ import { describe, expect, it } from 'vitest'; import { + renderAgentDecisionConfirmationEmail, renderMemberAddedEmail, renderNewNeedEmail, renderProjectUpdateEmail, @@ -41,4 +42,20 @@ describe('membership email templates', () => { expect(e.html).toContain('<script>'); expect(e.html).not.toContain('href="https://spam.example"'); }); + + it('the agent decision confirmation tells the admin what was recorded in their name, and how to undo it', () => { + const accepted = renderAgentDecisionConfirmationEmail( + { ...base, applicantName: 'Cam Applicant', decision: 'accepted', agentName: 'Example Bot' }, + HOST, + ); + expect(accepted.subject).toBe('The ops bot recorded that you accepted an application to Proj'); + expect(accepted.text).toContain("recorded in your name that you accepted Cam Applicant's application to Proj"); + expect(accepted.text).toContain('removing the member'); + expect(accepted.text).toContain('https://example.org/projects/proj/applications'); + const closed = renderAgentDecisionConfirmationEmail( + { ...base, applicantName: 'Cam Applicant', decision: 'closed', agentName: 'Example Bot' }, + HOST, + ); + expect(closed.text).toContain('adding the person to the project directly'); + }); }); From 264d60fc0ad28e37c052a07c544dc82cd38f54ee Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:53:14 +0000 Subject: [PATCH 66/78] feat(api): an agent records a project admin's accept or close POST /api/agent/applications/:projectSlug/:personSlug/decision under projects:applications:decide, which must hold its two companions at use (401 otherwise). onBehalfOf must name a Slack user in the configured workspace with a verified link to a person who is not deactivated, not an agent, and is a project-admin of this project right now, checked with the site's project-admin marker alone so staff powers do not carry over (403 not_project_admin otherwise). Checked before the lock to name the admin in the commit and again under it, with the 30-per-24-hours cap per agent across its grants (records plus an in-process log). The effect is the site's accept or close run as that admin, with decidedVia = agent and agentGrantId; the commit is the agent's with Actor-Kind, Grant-Id and On-Behalf-Of. Unknown body fields (isAdmin above all) are refused, not dropped. The applicant gets the usual email and the admin a confirmation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/src/plugins/services.ts | 8 +- apps/api/src/routes/agent-applications.ts | 95 ++++- apps/api/src/services/agent-decision.ts | 185 +++++++++ apps/api/src/services/application-notices.ts | 34 ++ apps/api/src/services/project-application.ts | 23 +- apps/api/tests/agent-decision.test.ts | 413 +++++++++++++++++++ 6 files changed, 753 insertions(+), 5 deletions(-) create mode 100644 apps/api/src/services/agent-decision.ts create mode 100644 apps/api/tests/agent-decision.test.ts diff --git a/apps/api/src/plugins/services.ts b/apps/api/src/plugins/services.ts index 12c02ce7..abce77f1 100644 --- a/apps/api/src/plugins/services.ts +++ b/apps/api/src/plugins/services.ts @@ -45,6 +45,7 @@ import { ProjectApplicationService } from '../services/project-application.js'; import { ApplicationNotices } from '../services/application-notices.js'; import { SlackLinkService } from '../services/slack-link.js'; import { AgentFeedService } from '../services/agent-feed.js'; +import { AgentDecisionService } from '../services/agent-decision.js'; declare module 'fastify' { interface FastifyInstance { @@ -78,6 +79,7 @@ declare module 'fastify' { spamPurges: SpamPurgeLogService; slackLinks: SlackLinkService; agentFeed: AgentFeedService; + agentDecisions: AgentDecisionService; }; /** Shared in-memory state — write routes call StateApply.apply against this. */ inMemoryState: InMemoryState; @@ -143,6 +145,7 @@ async function servicesPlugin(fastify: FastifyInstance): Promise<void> { ); const githubAccount = new GitHubAccountService(state); + const applications = new ProjectApplicationService(state, fastify.store.private); fastify.decorate('services', { projects: new ProjectService(state, fts, fastify.store.private), people: new PersonService(state, fts, fastify.store.private), @@ -157,7 +160,7 @@ async function servicesPlugin(fastify: FastifyInstance): Promise<void> { eventSeriesWrite: new EventSeriesWriteService(state), projectsWrite: new ProjectWriteService(state), projectMembershipsWrite: new ProjectMembershipWriteService(state), - applications: new ProjectApplicationService(state, fastify.store.private), + applications, projectUpdatesWrite: new ProjectUpdateWriteService(state), projectBuzzWrite: new ProjectBuzzWriteService(state), helpWantedWrite: new HelpWantedWriteService(state), @@ -207,6 +210,9 @@ async function servicesPlugin(fastify: FastifyInstance): Promise<void> { botDmUrl: fastify.config.SLACK_OPS_BOT_DM_URL, }), agentFeed: new AgentFeedService(state, fastify.store.private, { teamId: fastify.config.SLACK_TEAM_ID }), + agentDecisions: new AgentDecisionService(state, fastify.store.private, applications, { + teamId: fastify.config.SLACK_TEAM_ID, + }), }); } diff --git a/apps/api/src/routes/agent-applications.ts b/apps/api/src/routes/agent-applications.ts index ad09aa31..1f064278 100644 --- a/apps/api/src/routes/agent-applications.ts +++ b/apps/api/src/routes/agent-applications.ts @@ -1,7 +1,9 @@ /** * Agent applications routes — specs/api/agent-applications.md. * - * GET /api/agent/events — agent:projects:applications:read + * GET /api/agent/events — agent:projects:applications:read + * POST /api/agent/applications/:projectSlug/:personSlug/decision + * — agent:projects:applications:decide (with its two companions) * * The scope is checked before the query or body is validated, so a caller * without it learns nothing from a validation error. Signed-in people and @@ -10,6 +12,12 @@ import type { FastifyInstance } from 'fastify'; import { agentScopeCaller } from '../auth/caller.js'; +import { ApiValidationError } from '../lib/errors.js'; +import { ok } from '../lib/response.js'; +import type { AgentDecisionInput } from '../services/agent-decision.js'; +import { buildTransactionOptions } from '../store/commit-meta.js'; + +const DECISION_FIELDS = new Set(['decision', 'onBehalfOf', 'role', 'fillRoleIds', 'note']); export async function agentApplicationRoutes(fastify: FastifyInstance): Promise<void> { fastify.get( @@ -38,4 +46,89 @@ export async function agentApplicationRoutes(fastify: FastifyInstance): Promise< return { success: true, data, metadata: { timestamp: new Date().toISOString(), next } }; }, ); + + fastify.post( + '/api/agent/applications/:projectSlug/:personSlug/decision', + { + preValidation: async (request) => { + agentScopeCaller(request, 'projects:applications:decide'); + // Refuse, rather than silently drop, anything the grant may not ask for + // (isAdmin above all): the schema's additionalProperties would strip it. + const body = request.body; + if (body && typeof body === 'object' && !Array.isArray(body)) { + const extra = Object.keys(body).filter((k) => !DECISION_FIELDS.has(k)); + if (extra.length > 0) { + throw new ApiValidationError('Unknown fields', Object.fromEntries(extra.map((k) => [k, 'not allowed']))); + } + } + }, + schema: { + tags: ['agent-applications'], + summary: "Record a project admin's accept or close of an open application (agent:projects:applications:decide)", + params: { + type: 'object', + properties: { projectSlug: { type: 'string' }, personSlug: { type: 'string' } }, + required: ['projectSlug', 'personSlug'], + }, + body: { + type: 'object', + properties: { + decision: { type: 'string', enum: ['accept', 'close'] }, + onBehalfOf: { + type: 'object', + properties: { + slackTeamId: { type: 'string', maxLength: 32 }, + slackUserId: { type: 'string', maxLength: 32 }, + }, + required: ['slackTeamId', 'slackUserId'], + additionalProperties: false, + }, + role: { type: ['string', 'null'] }, + fillRoleIds: { type: 'array', items: { type: 'string' } }, + note: { type: ['string', 'null'] }, + }, + required: ['decision', 'onBehalfOf'], + // No isAdmin, no anything else: the grant accepts or closes, nothing more. + additionalProperties: false, + }, + }, + }, + async (request) => { + const caller = agentScopeCaller(request, 'projects:applications:decide'); + const { projectSlug, personSlug } = request.params as { projectSlug: string; personSlug: string }; + const svc = fastify.services.agentDecisions; + const input = svc.validate(request.body as Partial<AgentDecisionInput>); + // Refuse early (before taking the lock), and name the admin for the commit; + // decide() checks both again under the lock. + svc.checkCap(caller.agent.person.slug, new Date()); + const { admin } = svc.resolveAdmin(projectSlug, input.onBehalfOf); + + const accept = input.decision === 'accept'; + const result = await fastify.store.transact( + buildTransactionOptions({ + request, + session: caller.session, + action: accept ? 'project-membership.accept' : 'project-membership.close', + subjectType: 'project-membership', + subjectSlug: `${projectSlug}/${personSlug}`, + responseCode: 200, + extraTrailers: { 'On-Behalf-Of': admin.slug, ...(accept ? {} : { 'Closed-By': 'admin' }) }, + }), + async (tx) => svc.decide(tx, caller.agent, projectSlug, personSlug, input, admin.id), + (value) => value.stateApply.apply(fastify.inMemoryState, fastify.fts), + ); + const { membership: m, note, project, applicant } = result.value; + svc.noteDecision(caller.agent.person.slug, m.id, new Date(m.application!.decidedAt!)); + + // The applicant hears exactly as for a site decision; the admin gets a confirmation. + void fastify.applicationNotices + .toApplicant(m, accept ? 'accepted' : 'closed', note) + .catch((err: unknown) => fastify.log.error({ err }, 'application decision email failed')); + void fastify.applicationNotices + .confirmAgentDecision(admin, project, applicant, accept ? 'accepted' : 'closed', caller.agent.person) + .catch((err: unknown) => fastify.log.error({ err }, 'agent decision confirmation failed')); + + return ok({ state: m.state, decidedBy: { slug: admin.slug } }); + }, + ); } diff --git a/apps/api/src/services/agent-decision.ts b/apps/api/src/services/agent-decision.ts new file mode 100644 index 00000000..2e32d7c5 --- /dev/null +++ b/apps/api/src/services/agent-decision.ts @@ -0,0 +1,185 @@ +/** + * An agent records a project admin's accept or close — specs/api/agent-applications.md → + * POST /api/agent/applications/:projectSlug/:personSlug/decision, and + * specs/behaviors/authorization.md → On behalf of a project admin. + * + * The one place a grant acts for a person, so every check fails closed: + * + * - the grant holds `projects:applications:decide` and both companions + * (checked by the route, {@link agentScopeCaller}); + * - the named Slack user is in the workspace the site serves and resolves + * through a verified link (`PrivateProfile.slack`) to a person who exists, + * is not deactivated, is not an agent account, and is — right now — a + * `member` with `isAdmin` on this project. Staff powers do not carry over: + * the check is the site's `project-admin` marker alone; + * - at most {@link AGENT_DECISIONS_PER_DAY} decisions per agent in any + * rolling 24 hours; + * - the application is open and visible (else 404), so a replay of a decided + * application changes nothing. + * + * The effects are the site's accept and close, run as the named admin (for + * `decidedById` and the authorization check) with `decidedVia = agent` and + * `agentGrantId`; the route commits as the agent with `Actor-Kind: agent`, + * `Grant-Id` and `On-Behalf-Of: <admin slug>`, and emails the admin a + * confirmation. + */ +import type { Person, Project } from '@cfp/shared/schemas'; + +import { grantsOf, isAgentAccount, type AgentPrincipal } from '../auth/agent-grant.js'; +import type { SessionContext } from '../auth/middleware.js'; +import { requireAuth } from '../auth/require.js'; +import { ApiNotFoundError, ApiValidationError, ForbiddenError, RateLimitedError } from '../lib/errors.js'; +import { projectBySlug, type InMemoryState } from '../store/memory/state.js'; +import type { PrivateStore } from '../store/private/interface.js'; +import type { DualStoreTx } from '../store/store.js'; +import { membershipsOfProject } from './memberships.js'; +import { NOTE_MAX, type DecideResult, type ProjectApplicationService } from './project-application.js'; + +const DAY = 24 * 60 * 60 * 1000; +export const AGENT_DECISIONS_PER_DAY = 30; + +export interface AgentDecisionInput { + readonly decision: 'accept' | 'close'; + readonly onBehalfOf: { readonly slackTeamId: string; readonly slackUserId: string }; + readonly role?: string | null; + readonly fillRoleIds?: string[]; + readonly note?: string | null; +} + +export type AgentDecisionResult = DecideResult & { readonly admin: Person; readonly note: string | null }; + +const NOT_ADMIN = 'The named Slack user is not a linked, active admin of this project'; + +export class AgentDecisionService { + readonly #state: InMemoryState; + readonly #privateStore: PrivateStore; + readonly #applications: ProjectApplicationService; + readonly #teamId: string | undefined; + /** agent slug → decisions recorded in this process (membership id and when), for the cap. */ + readonly #log = new Map<string, Array<{ id: string; at: number }>>(); + + constructor( + state: InMemoryState, + privateStore: PrivateStore, + applications: ProjectApplicationService, + opts: { teamId?: string | undefined }, + ) { + this.#state = state; + this.#privateStore = privateStore; + this.#applications = applications; + this.#teamId = opts.teamId; + } + + /** Shape checks that need no state. */ + validate(input: Partial<AgentDecisionInput>): AgentDecisionInput { + const fields: Record<string, string> = {}; + if (input.decision !== 'accept' && input.decision !== 'close') fields['decision'] = 'accept or close'; + const ob = input.onBehalfOf; + if (!ob || typeof ob.slackTeamId !== 'string' || typeof ob.slackUserId !== 'string') { + fields['onBehalfOf'] = '{ slackTeamId, slackUserId }'; + } + if (input.decision === 'close' && (input.role !== undefined || input.fillRoleIds !== undefined)) { + fields['role'] = 'role and fillRoleIds are for accept'; + } + if (input.decision === 'accept' && input.note != null) fields['note'] = 'note is for close'; + if (typeof input.note === 'string' && input.note.length > NOTE_MAX) fields['note'] = `at most ${NOTE_MAX} characters`; + if (Object.keys(fields).length > 0) throw new ApiValidationError('Invalid decision', fields); + return input as AgentDecisionInput; + } + + /** + * The project admin the request names, or `403 not_project_admin`. Called + * once before the write (to name them in the commit) and again under the + * write lock, where it must resolve to the same person. + */ + resolveAdmin(projectSlug: string, onBehalfOf: AgentDecisionInput['onBehalfOf']): { admin: Person; project: Project } { + const project = projectBySlug(this.#state, projectSlug); + if (!project || project.deletedAt) throw new ApiNotFoundError(`Project '${projectSlug}' not found`); + const refuse = (): never => { + throw new ForbiddenError(NOT_ADMIN, 'not_project_admin'); + }; + + const teamId = this.#teamId; + if (!teamId || onBehalfOf.slackTeamId !== teamId) return refuse(); + const personId = this.#privateStore.findPersonIdBySlackUser(teamId, onBehalfOf.slackUserId); + if (!personId) return refuse(); + const admin = this.#state.people.get(personId); + if (!admin || admin.deletedAt || isAgentAccount(this.#state, admin.slug)) return refuse(); + + // `project-admin` alone, as a plain user: staff and administrator powers do not carry over. + const asAdmin: SessionContext = { person: admin, accountLevel: 'user', personId: admin.id }; + try { + requireAuth('project-admin', { session: asAdmin, project, memberships: membershipsOfProject(this.#state, project.slug) }); + } catch { + return refuse(); + } + return { admin, project }; + } + + /** Decision times in the last 24 hours for every grant of this agent: the records and this process's log. */ + recentDecisions(agentSlug: string, now: number): number[] { + const grants = new Set(grantsOf(this.#state, agentSlug).map((g) => g.id)); + const seen = new Set<string>(); + const times: number[] = []; + const add = (id: string, at: number) => { + const key = `${id}@${at}`; + if (!Number.isFinite(at) || now - at >= DAY || seen.has(key)) return; + seen.add(key); + times.push(at); + }; + for (const m of this.#state.projectMemberships.values()) { + const app = m.application; + if (app?.decidedVia === 'agent' && app.agentGrantId && grants.has(app.agentGrantId) && app.decidedAt) { + add(m.id, Date.parse(app.decidedAt)); + } + } + const log = (this.#log.get(agentSlug) ?? []).filter((e) => now - e.at < DAY); + this.#log.set(agentSlug, log); + for (const e of log) add(e.id, e.at); + return times.sort((a, b) => a - b); + } + + /** Throws 429 when the agent has reached its daily cap. */ + checkCap(agentSlug: string, now: Date): void { + const recent = this.recentDecisions(agentSlug, now.getTime()); + if (recent.length >= AGENT_DECISIONS_PER_DAY) { + const frees = recent[recent.length - AGENT_DECISIONS_PER_DAY]! + DAY; + throw new RateLimitedError(Math.max(1, Math.ceil((frees - now.getTime()) / 1000))); + } + } + + /** + * Run under the write lock: cap, admin (must still be `expectedAdminId`), + * then the site's accept or close as that admin, marked as the agent's. + */ + async decide( + tx: DualStoreTx, + agent: AgentPrincipal, + projectSlug: string, + personSlug: string, + input: AgentDecisionInput, + expectedAdminId: string, + now: Date = new Date(), + ): Promise<AgentDecisionResult> { + this.checkCap(agent.person.slug, now); + const { admin } = this.resolveAdmin(projectSlug, input.onBehalfOf); + if (admin.id !== expectedAdminId) throw new ForbiddenError(NOT_ADMIN, 'not_project_admin'); + const asAdmin: SessionContext = { person: admin, accountLevel: 'user', personId: admin.id }; + const via = { agentGrantId: agent.grant.id }; + if (input.decision === 'accept') { + const fill = input.fillRoleIds !== undefined ? { fillRoleIds: input.fillRoleIds } : {}; + const role = input.role !== undefined ? { role: input.role } : {}; + const result = await this.#applications.accept(tx, projectSlug, personSlug, { ...role, ...fill }, asAdmin, now, via); + return { ...result, admin, note: null }; + } + const result = await this.#applications.close(tx, projectSlug, personSlug, { note: input.note ?? null }, asAdmin, now, via); + return { ...result, admin }; + } + + /** Count a decision toward the cap once its commit has landed. */ + noteDecision(agentSlug: string, membershipId: string, at: Date): void { + const log = this.#log.get(agentSlug) ?? []; + log.push({ id: membershipId, at: at.getTime() }); + this.#log.set(agentSlug, log); + } +} diff --git a/apps/api/src/services/application-notices.ts b/apps/api/src/services/application-notices.ts index 32b2800e..0974a0f1 100644 --- a/apps/api/src/services/application-notices.ts +++ b/apps/api/src/services/application-notices.ts @@ -96,6 +96,40 @@ export class ApplicationNotices { return attempted; } + /** + * Tell the admin an agent named that it recorded a decision in their name + * (authorization.md → On behalf of a project admin). Skipped, never + * redirected, when they have no deliverable address. + */ + async confirmAgentDecision( + admin: Person, + project: { slug: string; title: string }, + applicant: Person, + decision: 'accepted' | 'closed', + agent: Person, + ): Promise<boolean> { + const profile = await this.#d.privateStore.getProfile(admin.id); + if (!profile || !hasDeliverableEmail(profile)) { + this.#d.log.info({ project: project.slug, decision }, 'agent decision confirmation: no deliverable address; skipped'); + return false; + } + try { + await this.#d.notifier.notifyAgentDecisionConfirmation({ + email: profile.email, + fullName: admin.fullName, + projectTitle: project.title, + projectSlug: project.slug, + applicantName: applicant.fullName, + decision, + agentName: agent.fullName, + }); + return true; + } catch (err) { + this.#d.log.error({ err, project: project.slug, decision }, 'agent decision confirmation: send threw'); + return false; + } + } + /** Tell the applicant the outcome. The note goes only into this email. */ async toApplicant( m: ProjectMembership, diff --git a/apps/api/src/services/project-application.ts b/apps/api/src/services/project-application.ts index e79ae265..2ef28d97 100644 --- a/apps/api/src/services/project-application.ts +++ b/apps/api/src/services/project-application.ts @@ -146,6 +146,20 @@ export interface ApplyInput { readonly offer?: string | null; } +/** + * How a decision was made: on the site by the session's person, or by an + * agent on that person's behalf (`decidedVia = agent`, `agentGrantId`) — + * specs/api/agent-applications.md. The session is always the deciding + * admin; the agent is the commit author, set by the caller. + */ +export interface DecisionVia { + readonly agentGrantId: string; +} + +function viaFields(via: DecisionVia | undefined): { decidedVia: 'site' | 'agent'; agentGrantId?: string } { + return via ? { decidedVia: 'agent', agentGrantId: via.agentGrantId } : { decidedVia: 'site' }; +} + export interface DecideResult { readonly membership: ProjectMembership; readonly stateApply: StateApply; @@ -355,6 +369,7 @@ export class ProjectApplicationService { input: { role?: string | null; isAdmin?: boolean; fillRoleIds?: string[] }, session: SessionContext, now: Date = new Date(), + via?: DecisionVia, ): Promise<DecideResult> { const { project, applicant, existing } = this.#openApplicationOrThrow(projectSlug, personSlug, session, now); checkRole(input.role); @@ -379,7 +394,7 @@ export class ProjectApplicationService { role: role === null ? null : role.slice(0, 80), via: 'application', joinedAt: at, - application: { ...app, status: 'accepted', decidedById: session.person!.id, decidedAt: at, decidedVia: 'site' }, + application: { ...app, status: 'accepted', decidedById: session.person!.id, decidedAt: at, ...viaFields(via) }, updatedAt: at, }); await tx.public['project-memberships'].upsert(membership); @@ -400,13 +415,14 @@ export class ProjectApplicationService { input: { note?: string | null }, session: SessionContext, now: Date = new Date(), + via?: DecisionVia, ): Promise<DecideResult & { note: string | null }> { const { project, applicant, existing } = this.#openApplicationOrThrow(projectSlug, personSlug, session, now); const note = typeof input.note === 'string' && input.note.trim() !== '' ? input.note : null; if (note !== null && note.length > NOTE_MAX) { throw new ApiValidationError(`note is at most ${NOTE_MAX} characters`, { note: 'too_long' }); } - const membership = this.#closed(existing, 'admin', now, session.person!.id); + const membership = this.#closed(existing, 'admin', now, session.person!.id, via); await tx.public['project-memberships'].upsert(membership); return { membership, stateApply: new StateApply().upsertMembership(membership), project, applicant, note }; } @@ -421,6 +437,7 @@ export class ProjectApplicationService { closedBy: 'admin' | 'applicant' | 'site', now: Date, decidedById: string | null, + via?: DecisionVia, ): ProjectMembership { const at = iso(now); return asFollower(m, at, { @@ -429,7 +446,7 @@ export class ProjectApplicationService { status: 'closed', closedBy, closedAt: at, - ...(decidedById ? { decidedById, decidedAt: at, decidedVia: 'site' as const } : {}), + ...(decidedById ? { decidedById, decidedAt: at, ...viaFields(via) } : {}), }, }); } diff --git a/apps/api/tests/agent-decision.test.ts b/apps/api/tests/agent-decision.test.ts new file mode 100644 index 00000000..983b3613 --- /dev/null +++ b/apps/api/tests/agent-decision.test.ts @@ -0,0 +1,413 @@ +/** + * An agent records a project admin's accept or close from Slack + * (plans/agent-decide-on-behalf.md, specs/api/agent-applications.md → + * POST …/decision, specs/behaviors/authorization.md → On behalf of a + * project admin). The happy paths, the commit and record, the confirmation + * email, and every refusal: unlinked, other workspace, linked to a + * non-admin, staff who is not an admin, deactivated, demoted, wrong + * project, missing scope or companions, the daily cap, replay, and every + * other route the grant must not reach. + * + * Every person, workspace and Slack id here is invented; addresses are example.org. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { ProjectMembership } from '@cfp/shared/schemas'; + +import { AGENT_DECISIONS_PER_DAY } from '../src/services/agent-decision.js'; +import { StateApply } from '../src/store/state-apply.js'; +import { + bearer, + createAgent, + daysAgo, + fid, + minutesAgo, + mintGrant, + personRecord, + privateProfile, + startAgentTestEnv, + type AgentTestEnv, + type Rec, +} from './helpers/agent-fixtures.js'; + +const TEAM = 'TEXAMPLE01'; +const P = { + ada: 1, olly: 2, dana: 3, sam: 4, ben: 5, ivy: 6, root: 7, una: 8, + cara: 10, dev: 11, eli: 12, fay: 13, gus: 14, hana: 15, +}; +const U = { ada: 'UADA000001', olly: 'UOLLY00001', dana: 'UDANA00001', sam: 'USAM000001', ivy: 'UIVY000001', ben: 'UBEN000001' }; +const ROLE = fid(300); +const T = '2026-05-01T00:00:00.000Z'; +const RECENT = minutesAgo(90); +const NOTE = 'We are full on frontend this season, thank you.'; + +let n = 1000; +const rec = (project: string, person: string, state: 'follower' | 'applicant' | 'member', over: Rec = {}): Rec => ({ + id: fid(n++), + projectSlug: project, + personSlug: person, + state, + isAdmin: false, + muted: false, + followedAt: T, + createdAt: T, + updatedAt: T, + ...(state === 'member' ? { via: 'legacy', joinedAt: T } : {}), + ...over, +}); +const openApp = (over: Rec = {}): Rec => ({ + application: { status: 'open', roleIds: [], offer: 'Glad to help.', submittedAt: RECENT, visibleAt: RECENT, notifiedAt: RECENT, ...over }, +}); +const project = (k: number, slug: string): Rec => ({ + id: fid(50 + k), slug, title: `Project ${slug}`, stage: 'testing', featured: false, chatChannel: slug, createdAt: T, updatedAt: T, +}); + +function records(): Record<string, Rec[]> { + n = 1000; + return { + people: Object.entries(P).map(([slug, k]) => + personRecord(k, slug, { + ...(slug === 'olly' ? { deletedAt: daysAgo(1) } : {}), + ...(slug === 'sam' ? { accountLevel: 'staff' } : {}), + ...(slug === 'root' ? { accountLevel: 'administrator' } : {}), + ...(slug === 'una' ? { accountLevel: 'staff' } : {}), + }), + ), + projects: [project(0, 'proj'), project(1, 'side')], + 'help-wanted-roles': [ + { id: ROLE, projectSlug: 'proj', postedById: fid(P.ada), title: 'Frontend dev', description: 'React.', status: 'open', createdAt: T, updatedAt: T }, + ], + 'project-memberships': [ + rec('proj', 'ada', 'member', { isAdmin: true, role: 'Founder' }), + rec('proj', 'olly', 'member', { isAdmin: true }), // deactivated admin + rec('proj', 'dana', 'member'), // a member, not (or no longer) an admin + rec('proj', 'ben', 'member'), + rec('proj', 'una', 'member', { isAdmin: true }), // staff who is an admin here: counts as an admin + rec('side', 'ivy', 'member', { isAdmin: true }), // admin of another project only + rec('proj', 'cara', 'applicant', openApp({ roleIds: [ROLE] })), + rec('proj', 'dev', 'applicant', openApp()), + rec('proj', 'eli', 'applicant', openApp()), + rec('proj', 'fay', 'applicant', openApp({ visibleAt: new Date(Date.now() + 6 * 3600_000).toISOString(), notifiedAt: null })), + rec('proj', 'gus', 'member', { + via: 'application', joinedAt: minutesAgo(30), + ...openApp({ status: 'accepted', decidedById: fid(P.ada), decidedAt: minutesAgo(30), decidedVia: 'site' }), + }), + rec('proj', 'hana', 'applicant', openApp()), + ], + }; +} + +const slack = (userId: string, teamId = TEAM): Rec => ({ slack: { teamId, userId, linkedAt: T } }); +const PROFILES = Object.entries(P).map(([slug, k]) => + privateProfile(fid(k), `${slug}@example.org`, { + ...(slug === 'ada' ? slack(U.ada) : {}), + ...(slug === 'olly' ? slack(U.olly) : {}), + ...(slug === 'dana' ? slack(U.dana) : {}), + ...(slug === 'sam' ? slack(U.sam) : {}), + ...(slug === 'ivy' ? slack(U.ivy) : {}), + ...(slug === 'una' ? slack('UUNA000001') : {}), + // ben's link is in some other workspace. + ...(slug === 'ben' ? slack(U.ben, 'TOTHER0001') : {}), + }), +); + +const ALL = ['slack:link', 'projects:applications:read', 'projects:applications:decide']; + +describe('agent decisions on a project admin’s behalf', () => { + let env: AgentTestEnv; + let agent: { token: string; grantId: string; personId: string }; + let adminCookie: string; + + beforeEach(async () => { + env = await startAgentTestEnv({ records: records(), profiles: PROFILES, env: { SLACK_TEAM_ID: TEAM } }); + adminCookie = await env.cookie(P.root, 'administrator'); + agent = await createAgent(env, adminCookie, { slug: 'example-bot', scopes: ALL }); + }); + afterEach(async () => { + vi.restoreAllMocks(); + await env.close(); + }); + + const decide = (person: string, body: Rec, token = agent.token, projectSlug = 'proj') => + env.app.inject({ + method: 'POST', + url: `/api/agent/applications/${projectSlug}/${person}/decision`, + ...bearer(token), + payload: body, + }); + const by = (userId: string, teamId = TEAM) => ({ slackTeamId: teamId, slackUserId: userId }); + const record = (person: string, projectSlug = 'proj'): ProjectMembership | undefined => { + const s = env.app.inMemoryState; + for (const id of s.membershipsByPerson.get(person) ?? []) { + const m = s.projectMemberships.get(id); + if (m?.projectSlug === projectSlug) return m; + } + return undefined; + }; + const head = async () => (await env.git('rev-parse', 'HEAD')).trim(); + const lastCommit = async () => env.git('log', '-1', '--format=%an <%ae>%n%B'); + const spies = () => ({ + applicant: vi.spyOn(env.app.notifier, 'notifyApplicationDecision'), + confirm: vi.spyOn(env.app.notifier, 'notifyAgentDecisionConfirmation'), + }); + const settle = () => new Promise((r) => setTimeout(r, 20)); + const errCode = (res: { json: () => unknown }) => (res.json() as { error: { code: string } }).error.code; + + it('accepts for a linked active admin: the record names the admin and the grant, the commit is the agent’s', async () => { + const mail = spies(); + const res = await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada), fillRoleIds: [ROLE] }); + expect(res.statusCode, res.body).toBe(200); + expect(res.json<{ data: unknown }>().data).toEqual({ state: 'member', decidedBy: { slug: 'ada' } }); + + const m = record('cara')!; + expect(m).toMatchObject({ state: 'member', via: 'application', role: 'Frontend dev' }); + expect(m.application).toMatchObject({ + status: 'accepted', decidedById: fid(P.ada), decidedVia: 'agent', agentGrantId: agent.grantId, + }); + expect(env.app.inMemoryState.helpWantedRoles.get(ROLE)).toMatchObject({ status: 'filled' }); + + const commit = await lastCommit(); + expect(commit).toMatch(/^Example example-bot <example-bot@users\.noreply\.codeforphilly\.org>/); + expect(commit).toMatch(/^Action: project-membership\.accept$/m); + expect(commit).toMatch(/^Actor-Kind: agent$/m); + expect(commit).toMatch(new RegExp(`^Grant-Id: ${agent.grantId}$`, 'm')); + expect(commit).toMatch(/^On-Behalf-Of: ada$/m); + expect(commit).not.toContain(U.ada); + + await settle(); + expect(mail.applicant).toHaveBeenCalledTimes(1); + expect(mail.applicant.mock.calls[0]![0]).toMatchObject({ email: 'cara@example.org', outcome: 'accepted' }); + expect(mail.confirm).toHaveBeenCalledTimes(1); + expect(mail.confirm.mock.calls[0]![0]).toMatchObject({ + email: 'ada@example.org', decision: 'accepted', applicantName: 'Test cara', projectSlug: 'proj', agentName: 'Example example-bot', + }); + }); + + it('closes for a linked active admin; the note goes to the applicant only, never to the record or a commit', async () => { + const mail = spies(); + const res = await decide('dev', { decision: 'close', onBehalfOf: by(U.ada), note: NOTE }); + expect(res.statusCode, res.body).toBe(200); + expect(res.json<{ data: unknown }>().data).toEqual({ state: 'follower', decidedBy: { slug: 'ada' } }); + expect(record('dev')!.application).toMatchObject({ + status: 'closed', closedBy: 'admin', decidedById: fid(P.ada), decidedVia: 'agent', agentGrantId: agent.grantId, + }); + const commit = await lastCommit(); + expect(commit).toMatch(/^Action: project-membership\.close$/m); + expect(commit).toMatch(/^Closed-By: admin$/m); + expect(commit).toMatch(/^On-Behalf-Of: ada$/m); + expect(await env.git('log', '--all', '-p')).not.toContain(NOTE); + await settle(); + expect(mail.applicant.mock.calls[0]![0]).toMatchObject({ email: 'dev@example.org', outcome: 'closed', note: NOTE }); + expect(mail.confirm).toHaveBeenCalledTimes(1); + expect(mail.confirm.mock.calls[0]![0]).toMatchObject({ email: 'ada@example.org', decision: 'closed' }); + }); + + it('a staff member who is also an admin of the project counts as an admin', async () => { + const res = await decide('eli', { decision: 'accept', onBehalfOf: by('UUNA000001') }); + expect(res.statusCode, res.body).toBe(200); + expect(record('eli')!.application!.decidedById).toBe(fid(P.una)); + }); + + describe('refuses with 403 not_project_admin, writing and sending nothing', () => { + const cases: Array<[string, () => Rec]> = [ + ['an unlinked Slack user', () => by('UNOBODY001')], + ['a Slack id linked in another workspace', () => by(U.ben, 'TOTHER0001')], + ['an admin’s Slack id named in another workspace', () => by(U.ada, 'TOTHER0001')], + ['a Slack user linked to an account that is not an admin', () => by(U.dana)], + ['linked staff who is not an admin of the project', () => by(U.sam)], + ['a deactivated admin', () => by(U.olly)], + ['an admin of a different project', () => by(U.ivy)], + ]; + for (const [label, who] of cases) { + it(label, async () => { + const mail = spies(); + const before = await head(); + for (const decision of ['accept', 'close']) { + const res = await decide('cara', { decision, onBehalfOf: who() }); + expect(res.statusCode, res.body).toBe(403); + expect(errCode(res)).toBe('not_project_admin'); + } + expect(await head()).toBe(before); + expect(record('cara')!.state).toBe('applicant'); + await settle(); + expect(mail.applicant).not.toHaveBeenCalled(); + expect(mail.confirm).not.toHaveBeenCalled(); + }); + } + + it('an admin demoted since: refused at once', async () => { + expect((await decide('cara', { decision: 'close', onBehalfOf: by(U.ada) })).statusCode).toBe(200); + const demote = await env.app.inject({ + method: 'PATCH', + url: '/api/projects/proj/members/ada', + cookies: { cfp_session: adminCookie }, + payload: { isAdmin: false, confirmLastAdmin: true }, + }); + expect(demote.statusCode, demote.body).toBe(200); + const res = await decide('dev', { decision: 'accept', onBehalfOf: by(U.ada) }); + expect(res.statusCode).toBe(403); + expect(record('dev')!.state).toBe('applicant'); + }); + + it('an admin who disconnected Slack: refused', async () => { + const del = await env.app.inject({ method: 'DELETE', url: '/api/account/slack-link', cookies: { cfp_session: await env.cookie(P.ada, 'user') } }); + expect(del.statusCode).toBe(204); + expect((await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(403); + }); + + it('no workspace configured: refused for everyone', async () => { + await env.close(); + env = await startAgentTestEnv({ records: records(), profiles: PROFILES }); + agent = await createAgent(env, await env.cookie(P.root, 'administrator'), { slug: 'example-bot', scopes: ALL }); + expect((await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(403); + }); + }); + + describe('scope', () => { + it('a grant without the decide scope, staff and anonymous callers get 401', async () => { + const readLink = await mintGrant(env, adminCookie, 'example-bot', ['slack:link', 'projects:applications:read']); + expect((await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada) }, readLink.token)).statusCode).toBe(401); + const asStaff = await env.app.inject({ + method: 'POST', url: '/api/agent/applications/proj/cara/decision', + cookies: { cfp_session: await env.cookie(P.sam, 'staff') }, + payload: { decision: 'accept', onBehalfOf: by(U.ada) }, + }); + expect(asStaff.statusCode).toBe(401); + const asAdminOfProject = await env.app.inject({ + method: 'POST', url: '/api/agent/applications/proj/cara/decision', + cookies: { cfp_session: await env.cookie(P.ada, 'user') }, + payload: { decision: 'accept', onBehalfOf: by(U.ada) }, + }); + expect(asAdminOfProject.statusCode).toBe(401); + const anon = await env.app.inject({ method: 'POST', url: '/api/agent/applications/proj/cara/decision', payload: { decision: 'accept', onBehalfOf: by(U.ada) } }); + expect(anon.statusCode).toBe(401); + expect(record('cara')!.state).toBe('applicant'); + }); + + it('a grant holding decide without its companions is refused at use (401)', async () => { + for (const scopes of [ + ['projects:applications:decide'], + ['projects:applications:decide', 'slack:link'], + ['projects:applications:decide', 'projects:applications:read'], + ]) { + // As if a grant record had been written by hand: mint rejects these. + const g = env.app.inMemoryState.agentGrants.get(agent.grantId)!; + env.app.inMemoryState.agentGrants.set(agent.grantId, { ...g, scopes: scopes as typeof g.scopes }); + const res = await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada) }); + expect(res.statusCode, scopes.join(',')).toBe(401); + } + expect(record('cara')!.state).toBe('applicant'); + }); + + it('a revoked grant is refused', async () => { + const revoke = await env.app.inject({ + method: 'POST', url: `/api/admin/agents/example-bot/grants/${agent.grantId}/revoke`, cookies: { cfp_session: adminCookie }, payload: {}, + }); + expect(revoke.statusCode, revoke.body).toBe(200); + expect((await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(401); + }); + }); + + describe('what it reaches', () => { + it('only open, visible applications: a held one, a decided one and a replay are 404', async () => { + expect((await decide('fay', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(404); + expect((await decide('gus', { decision: 'close', onBehalfOf: by(U.ada) })).statusCode).toBe(404); + expect((await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(200); + const before = await head(); + expect((await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(404); + expect((await decide('cara', { decision: 'close', onBehalfOf: by(U.ada) })).statusCode).toBe(404); + expect(await head()).toBe(before); + expect((await decide('nobody', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(404); + }); + + it('never adds, removes or promotes members, or touches needs or the project, through any route', async () => { + const before = await head(); + const tries: Array<[string, string, Rec | undefined]> = [ + ['POST', '/api/projects/proj/members', { personSlug: 'hana', isAdmin: true }], + ['PATCH', '/api/projects/proj/members/ben', { isAdmin: true }], + ['DELETE', '/api/projects/proj/members/ben', undefined], + ['POST', '/api/projects/proj/applications/hana/accept', {}], + ['POST', '/api/projects/proj/applications/hana/close', {}], + ['POST', '/api/projects/proj/help-wanted', { title: 'Spam', description: 'x' }], + ['PATCH', `/api/projects/proj/help-wanted/${ROLE}`, { title: 'Changed' }], + ['POST', `/api/projects/proj/help-wanted/${ROLE}/close`, {}], + ['PATCH', '/api/projects/proj', { title: 'Changed' }], + ['DELETE', '/api/projects/proj', undefined], + ['POST', '/api/projects/proj/follow', {}], + ['POST', '/api/projects/proj/applications', { offer: 'hi' }], + ]; + for (const [method, url, payload] of tries) { + const res = await env.app.inject({ method: method as 'POST', url, ...bearer(agent.token), ...(payload ? { payload } : {}) }); + expect([401, 403, 404], `${method} ${url} → ${res.statusCode}`).toContain(res.statusCode); + } + // The decision endpoint itself takes no isAdmin or anything else. + const promote = await decide('hana', { decision: 'accept', onBehalfOf: by(U.ada), isAdmin: true }); + expect(promote.statusCode).toBe(422); + expect(await head()).toBe(before); + expect(record('hana')!.state).toBe('applicant'); + }); + + it('git log --grep On-Behalf-Of lists exactly the agent’s decisions', async () => { + // A site decision by the admin herself carries no On-Behalf-Of. + const site = await env.app.inject({ + method: 'POST', url: '/api/projects/proj/applications/hana/accept', cookies: { cfp_session: await env.cookie(P.ada, 'user') }, payload: {}, + }); + expect(site.statusCode, site.body).toBe(200); + expect((await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(200); + expect((await decide('dev', { decision: 'close', onBehalfOf: by('UUNA000001') })).statusCode).toBe(200); + const listed = (await env.git('log', '--grep=^On-Behalf-Of: ', '--format=%ae %(trailers:key=On-Behalf-Of,valueonly,separator=)')) + .trim() + .split('\n'); + expect(listed).toEqual([ + 'example-bot@users.noreply.codeforphilly.org una', + 'example-bot@users.noreply.codeforphilly.org ada', + ]); + }); + }); + + describe('the daily cap', () => { + /** Commit `count` agent decisions to the data repo, `ageMs` ago, for `grantId`. */ + const seedDecisions = async (count: number, grantId: string, ageMs: number) => { + const at = new Date(Date.now() - ageMs).toISOString(); + const ms: ProjectMembership[] = []; + for (let i = 0; i < count; i++) { + ms.push({ + id: fid(5000 + ageMs / 1000 + i), projectSlug: 'side', personSlug: `seed-${ageMs / 1000}-${i}`, state: 'member', isAdmin: false, muted: false, + via: 'application', followedAt: T, joinedAt: at, createdAt: T, updatedAt: at, + application: { status: 'accepted', roleIds: [], offer: 'x', submittedAt: T, visibleAt: T, decidedById: fid(P.ivy), decidedAt: at, decidedVia: 'agent', agentGrantId: grantId }, + } as ProjectMembership); + } + await env.app.store.transact({ message: 'seed agent decisions', author: { name: 'cfp test', email: 'test@example.org' } }, async (tx) => { + for (const m of ms) await tx.public['project-memberships'].upsert(m); + }); + const apply = new StateApply(); + for (const m of ms) apply.upsertMembership(m); + apply.apply(env.app.inMemoryState, env.app.fts); + }; + + it(`the ${AGENT_DECISIONS_PER_DAY + 1}st decision in 24 hours is 429, counted across the agent’s grants`, async () => { + const second = await mintGrant(env, adminCookie, 'example-bot', ALL); + await seedDecisions(AGENT_DECISIONS_PER_DAY - 2, agent.grantId, 3600_000); + await seedDecisions(5, agent.grantId, 25 * 3600_000); // older than a day: not counted + expect((await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(200); // 29 + expect((await decide('dev', { decision: 'accept', onBehalfOf: by(U.ada) }, second.token)).statusCode).toBe(200); // 30 + const before = await head(); + const over = await decide('eli', { decision: 'close', onBehalfOf: by(U.ada) }); + expect(over.statusCode).toBe(429); + expect(Number(over.headers['retry-after'])).toBeGreaterThan(0); + const viaSecond = await decide('eli', { decision: 'close', onBehalfOf: by(U.ada) }, second.token); + expect(viaSecond.statusCode).toBe(429); + expect(await head()).toBe(before); + expect(record('eli')!.state).toBe('applicant'); + }); + + it('a decision whose record is later replaced still counts (the in-process log)', async () => { + await seedDecisions(AGENT_DECISIONS_PER_DAY - 1, agent.grantId, 3600_000); + expect((await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(200); + // The member is removed: the record (and its application) is gone. + const remove = await env.app.inject({ method: 'DELETE', url: '/api/projects/proj/members/cara', cookies: { cfp_session: adminCookie } }); + expect(remove.statusCode, remove.body).toBe(204); + expect((await decide('dev', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(429); + }); + }); +}); From 793a6dae77d6522bee7d479988c5b52435b3bc75 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:53:14 +0000 Subject: [PATCH 67/78] test(web): "via the ops bot" on an agent-recorded decision Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/web/tests/ProjectApplications.test.tsx | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/apps/web/tests/ProjectApplications.test.tsx b/apps/web/tests/ProjectApplications.test.tsx index 38244685..3b83a88a 100644 --- a/apps/web/tests/ProjectApplications.test.tsx +++ b/apps/web/tests/ProjectApplications.test.tsx @@ -29,7 +29,7 @@ const ITEM = { }, }; -function mockApi(listStatus = 200) { +function mockApi(listStatus = 200, item: unknown = ITEM) { return vi.spyOn(globalThis, 'fetch').mockImplementation(((input: string, init?: RequestInit) => { if (input.startsWith('/api/auth/me')) { return Promise.resolve(json(200, mockOk({ person: { id: 'u1', slug: 'ada', fullName: 'Ada', accountLevel: 'user', avatarUrl: null }, accountLevel: 'user' }))); @@ -37,7 +37,7 @@ function mockApi(listStatus = 200) { if (input.includes('/applications/pat/')) return Promise.resolve(json(200, mockOk({}))); if (input.includes('/api/projects/proj/applications')) { if (listStatus !== 200) return Promise.resolve(json(listStatus, { success: false, error: { code: 'forbidden', message: 'no' } })); - return Promise.resolve(json(200, { success: true, data: [ITEM], metadata: { page: 1, perPage: 20, totalItems: 1, totalPages: 1, counts: { open: 1, accepted: 0, closed: 0 } } })); + return Promise.resolve(json(200, { success: true, data: [item], metadata: { page: 1, perPage: 20, totalItems: 1, totalPages: 1, counts: { open: 1, accepted: 0, closed: 0 } } })); } if (input.startsWith('/api/projects/proj')) return Promise.resolve(json(200, mockOk({ slug: 'proj', title: 'Proj' }))); void init; @@ -101,4 +101,20 @@ describe('ProjectApplications', () => { render(); expect(await screen.findByText(/only this project's admins and site staff/i)).toBeInTheDocument(); }); + + it('an agent-recorded decision says "via the ops bot", naming the admin who decided', async () => { + mockApi(200, { + ...ITEM, + state: 'member', + application: { + ...ITEM.application, + status: 'accepted', + decidedBy: { slug: 'ada', fullName: 'Ada Admin', avatarUrl: null }, + decidedAt: '2026-11-21T00:00:00Z', + decidedVia: 'agent', + }, + }); + render(); + expect(await screen.findByText(/Accepted by Ada Admin, .* via the ops bot/)).toBeInTheDocument(); + }); }); From b7368893a75c56ac5873ff27837673748c6e3831 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:04:27 +0000 Subject: [PATCH 68/78] chore(plans): mark agent-decide-on-behalf done (PR #TBD) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- plans/agent-decide-on-behalf.md | 61 +++++++++++++++++++++++++++++---- 1 file changed, 54 insertions(+), 7 deletions(-) diff --git a/plans/agent-decide-on-behalf.md b/plans/agent-decide-on-behalf.md index 16e4d2fd..5ff5ccf3 100644 --- a/plans/agent-decide-on-behalf.md +++ b/plans/agent-decide-on-behalf.md @@ -1,5 +1,5 @@ --- -status: in-progress +status: done depends: [agent-application-feed, needs-on-applications] specs: - specs/api/agent-applications.md @@ -46,13 +46,13 @@ override disabled. ## Validation -- [ ] Tests: a linked active admin's accept and close succeed; commit author is the agent with `Actor-Kind: agent`, `Grant-Id` and `On-Behalf-Of: <admin slug>`; the record has `decidedById` = admin, `decidedVia = agent`, `agentGrantId` -- [ ] Tests: unlinked Slack user, linked non-admin, linked staff who is not a project admin, and a deactivated admin all get `403 not_project_admin` -- [ ] Tests: the grant cannot add, remove, promote or touch needs through any route -- [ ] Tests: the named admin gets one confirmation email per decision; the 31st decision in 24 hours → `429` -- [ ] `git log --grep='^On-Behalf-Of: '` on the test repo lists exactly the agent's decisions +- [x] Tests: a linked active admin's accept and close succeed; commit author is the agent with `Actor-Kind: agent`, `Grant-Id` and `On-Behalf-Of: <admin slug>`; the record has `decidedById` = admin, `decidedVia = agent`, `agentGrantId` +- [x] Tests: unlinked Slack user, linked non-admin, linked staff who is not a project admin, and a deactivated admin all get `403 not_project_admin` +- [x] Tests: the grant cannot add, remove, promote or touch needs through any route +- [x] Tests: the named admin gets one confirmation email per decision; the 31st decision in 24 hours → `429` +- [x] `git log --grep='^On-Behalf-Of: '` on the test repo lists exactly the agent's decisions - [ ] End to end: an admin answers in a Slack DM and the application moves on the site (awaits the bot PR) -- [ ] `npm run type-check && npm run lint && npm test` clean +- [x] `npm run type-check && npm run lint && npm test` clean ## Risks / unknowns @@ -60,4 +60,51 @@ override disabled. ## Notes +- **End-to-end criterion open; its `awaits:` entry stays** until the bot's + DM reply handling lands. +- **Fail-closed order.** The route checks the scope and both companions + before the body (401; a hand-written grant record without them is refused + too), refuses unknown body fields with 422 rather than letting the schema + strip them (so `isAdmin` can never ride along), checks the cap, and + resolves the admin; under the write lock it checks the cap again and + re-resolves the admin, who must be the same person the commit names. +- **Who counts as the admin.** The Slack user must be in `SLACK_TEAM_ID` + (unset → everyone is refused), resolve through `bySlackUserId` to a person + who exists, is not deactivated, is not an agent account, and passes the + site's `project-admin` marker evaluated as a plain `user`: staff and + administrator levels add nothing, while a staff member who is a project + admin counts (tested). Refusals tested: unlinked id, link in another + workspace, an admin's id named under another workspace, linked non-admin, + linked staff not an admin here, deactivated admin, admin of another + project, admin demoted since, admin who disconnected, no workspace + configured, missing scope, decide without either companion, revoked grant. + Each writes no commit and sends no email. +- **Replay** of a decided application, a held one, or an unknown person is + `404` with no commit. +- **The cap** counts the agent's decisions in 24 hours across all its + grants, from records (`decidedVia = agent`, `agentGrantId` of any of its + grants) plus an in-process log, so removing a member it accepted does not + free a slot (tested). The log resets on restart; records still count. +- **Service reuse.** `accept`/`close` take an optional `{ agentGrantId }`; + the session passed is the admin's (for `decidedById` and the marker + check), the commit session is the agent's. Applicant email is as for a + site decision; the admin's confirmation is a new template. +- "via the ops bot" on the Applications screen already existed on this + branch; a web test now covers it. +- Smoke on a local app with made-up fixtures: linked a test admin through + the code flow, then the test grant accepted one application and closed + another (with a note) for her. Commits were authored by the agent with + `Actor-Kind: agent`, `On-Behalf-Of: ada` (and `Closed-By: admin`); the + note appeared nowhere in the data repo; an unlinked Slack id got `403 + not_project_admin`; the Applications screen showed "Accepted by … via the + ops bot" and "Closed by … via the ops bot". Email went to the logging + notifier (no Postmark locally). +- Gate at this commit's tree: check-contracts, type-check, lint, tests + (API 70 files / 835, web 36 / 218, shared 5 / 120) and `npm run build` + clean. `check:sheet-configs` not run (needs the data repo; known v3/v2 + drift until codeforphilly-data adopts). + ## Follow-ups + +- Send one agent-decision confirmation email on sandbox before release, with + the other new templates, to confirm Postmark's sender and stream. From d38155c7ddb4e5bb07f9ba44eebf3e4a192c437e Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:05:48 +0000 Subject: [PATCH 69/78] chore(plans): record PR #270 on the Slack-chain plans The three closeout commits were made before the pull request existed. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- plans/agent-application-feed.md | 1 + plans/agent-decide-on-behalf.md | 1 + plans/slack-account-link.md | 1 + 3 files changed, 3 insertions(+) diff --git a/plans/agent-application-feed.md b/plans/agent-application-feed.md index 03dea72e..102daa5f 100644 --- a/plans/agent-application-feed.md +++ b/plans/agent-application-feed.md @@ -7,6 +7,7 @@ specs: awaits: - "CodeForPhilly/grittybot — heartbeat stream that reads GET /api/agent/events and DMs admins, marked as AI (bot repo, by PR)" - "GrittyBot Slack app gains mpim:write (group DMs), merged in the bot repo and installed by a workspace admin" +pr: 270 --- # Plan: Application event feed for agents diff --git a/plans/agent-decide-on-behalf.md b/plans/agent-decide-on-behalf.md index 5ff5ccf3..c4f3edf7 100644 --- a/plans/agent-decide-on-behalf.md +++ b/plans/agent-decide-on-behalf.md @@ -9,6 +9,7 @@ specs: - specs/screens/project-applications.md awaits: - "CodeForPhilly/grittybot — DM reply/button handling that records an admin's accept or close via the decision endpoint (bot repo, by PR)" +pr: 270 --- # Plan: Agent records an admin's decision from Slack diff --git a/plans/slack-account-link.md b/plans/slack-account-link.md index c4a645a0..095b116b 100644 --- a/plans/slack-account-link.md +++ b/plans/slack-account-link.md @@ -10,6 +10,7 @@ specs: - specs/screens/account.md awaits: - "CodeForPhilly/grittybot — DM handler that takes a linking code and calls POST /api/agent/slack-links (bot repo, by PR)" +pr: 270 --- # Plan: Link a site account to a Slack user From 72dcd22c0208a4dfcb806463cdaf10b10a37b8f2 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:57:24 +0000 Subject: [PATCH 70/78] chore(plans): reopen slack-account-link for automatic linking Operator-approved on PR #270: the site links an account to a Slack user by itself when the user found by its email has the handle the site asserted at sign-in. Scope, approach and validation amended; the earlier closeout's ticks stand. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- plans/slack-account-link.md | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/plans/slack-account-link.md b/plans/slack-account-link.md index 095b116b..aa87ea3e 100644 --- a/plans/slack-account-link.md +++ b/plans/slack-account-link.md @@ -1,8 +1,11 @@ --- -status: done +status: in-progress depends: [] specs: - specs/api/slack-link.md + - specs/api/saml.md + - specs/api/auth.md + - specs/architecture.md - specs/api/agents.md - specs/data-model.md - specs/behaviors/private-storage.md @@ -28,7 +31,20 @@ use, rate limited); `DELETE /api/account/slack-link`; `POST read and decide endpoints themselves land in later plans); `me.slack`; the Account screen's Slack row; purge removes the link. -**Out:** the bot's side (awaited); anything that uses the link. +**Reopened (operator-approved, PR #270): automatic linking.** Every Slack +account in the workspace is created through the site's SAML sign-in, and +for most members Slack's handle equals the `slackSamlNameId` the site +asserted. The site gets its own read-only Slack token and links an account +by itself when two independent facts agree: the Slack user that +`users.lookupByEmail` finds for the account's private-profile email has a +handle exactly equal to `slackSamlNameId`, and is a full, active, human +member of the configured workspace. Links record how they were made +(`via: auto | code`) and when last verified; automatic links are +re-verified with age and before an on-behalf decision; a member who +disconnects is not silently re-linked. The code stays as the fallback. + +**Out:** the bot's side (awaited); anything that uses the link; +punctuation-normalised handle matching. ## Implements @@ -49,6 +65,12 @@ Account screen's Slack row; purge removes the link. 4. `AGENT_SCOPES` gains the three scopes; mint enforces the companion rules; `agent-grants/v2` contract adopted and mirrored. 5. Web: Slack row with code display and polling of `/api/auth/me`. +6. (Reopened) A `SlackDirectory` interface with a fetch client for + `users.lookupByEmail` and a fake for tests; an auto-link service with a + site-wide call budget, Retry-After backoff, per-person result cache and + in-flight dedupe; triggers at Slack SAML sign-in (delayed), on `/me`, and + when the feed needs an admin's id; re-verification of automatic links + before use and before decisions; the opt-out on disconnect. ## Validation @@ -60,6 +82,9 @@ Account screen's Slack row; purge removes the link. - [ ] `agent-grants/v2` adopted and mirrored; CI passes - [x] Browser: Account → Connect Slack shows a code; redeeming it with a test grant via the API turns the row to "Connected" - [ ] End to end with the ops bot in the real workspace (awaits the bot PR) +- [ ] Tests (automatic): both matches link (`via: auto`); an email match with a different handle, a handle match with a different email, a guest, a bot, a deleted user and another workspace do not; no token → no attempt +- [ ] Tests (automatic): a Slack error or rate limit fails closed without failing the request that triggered it; a member who disconnected is not re-linked automatically and can reconnect by code +- [ ] Tests (automatic): a re-check that no longer matches removes the link and the on-behalf decision is refused `not_project_admin`; the email never appears in logs or responses - [x] `npm run type-check && npm run lint && npm test` clean ## Risks / unknowns From 5e0981d79d697252bf9fe59a50f3d2dd40ba19bb Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:58:13 +0000 Subject: [PATCH 71/78] docs(specs): link Slack accounts automatically when email and handle agree Operator-approved design on PR #270. With its own read-only token (SLACK_BOT_TOKEN: users:read, users:read.email) the site links an account when users.lookupByEmail for the private-profile email returns a full, active, human member of SLACK_TEAM_ID whose handle exactly equals slackSamlNameId. It runs one person at a time: about a minute after Slack SAML sign-in, on /me (waiting at most 1.5 s), and for up to 5 admins per feed request; at most 20 Slack calls a minute, honouring Retry-After; no-match cached 24 h, errors 15 min. Automatic links are re-verified when used past 24 h, always before an on-behalf decision (a mismatch removes the link; either failure refuses not_project_admin); the feed stops carrying an id unverified for 7 days. Links record via (auto | code) and verifiedAt; disconnecting records an opt-out the automatic path honours and a code link clears. The code stays as the fallback. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- specs/api/agent-applications.md | 13 +++- specs/api/auth.md | 4 +- specs/api/saml.md | 2 +- specs/api/slack-link.md | 119 +++++++++++++++++++++++++---- specs/architecture.md | 1 + specs/behaviors/private-storage.md | 5 +- specs/data-model.md | 3 +- specs/screens/account.md | 3 +- 8 files changed, 125 insertions(+), 25 deletions(-) diff --git a/specs/api/agent-applications.md b/specs/api/agent-applications.md index 8e89328d..1ab9507b 100644 --- a/specs/api/agent-applications.md +++ b/specs/api/agent-applications.md @@ -58,7 +58,11 @@ not a stored log): - `application` also carries `decidedBy` (`{ slug, fullName }`, or `null`), `decidedVia` and `closedBy`, as they stand now. - `admins` lists the project's active admins; `slackUserId` is set only for an - admin with a verified [Slack link](slack-link.md). No email address, ever. + admin with a verified [Slack link](slack-link.md) (an automatic link + unverified for more than 7 days does not count). Building the feed may + link or re-verify a few admins automatically + ([slack-link.md → When it runs](slack-link.md#when-it-runs)). No email + address, ever. - Applications from deactivated applicants produce no events, and their earlier events drop out of the feed. - Ordered by `at`, then record id. The cursor is stable across restarts @@ -87,7 +91,7 @@ Records an accept or a close that a project admin made in Slack. | Field | Required | Notes | | ----- | -------- | ----- | | decision | yes | `accept` \| `close` | -| onBehalfOf | yes | The Slack user who decided; `slackTeamId` must be the workspace the site serves. Must resolve through a verified link to a person who is, now, an active project admin of `:projectSlug` ([authorization.md → On behalf of a project admin](../behaviors/authorization.md#on-behalf-of-a-project-admin)). | +| onBehalfOf | yes | The Slack user who decided; `slackTeamId` must be the workspace the site serves. An automatic link more than 24 hours past its `verifiedAt` is re-verified first ([slack-link.md → Re-verification](slack-link.md#re-verification)). Must resolve through a verified link to a person who is, now, an active project admin of `:projectSlug` ([authorization.md → On behalf of a project admin](../behaviors/authorization.md#on-behalf-of-a-project-admin)). | | role, fillRoleIds | no | As for the site's accept ([projects-applications.md](projects-applications.md)). | | note | no | For `close`: emailed to the applicant, never stored. | @@ -110,8 +114,9 @@ screen. grant that holds it without `projects:applications:read` and `slack:link` (refused at use as well as at mint) - `403 forbidden` (`error.code = "not_project_admin"`) — the Slack user is not - linked (or names another workspace), or the linked person is not an active - admin of this project + linked (or names another workspace), the linked person is not an active + admin of this project, or an automatic link failed or could not get its + re-verification - `404 not_found` — no open, visible application from that person - `429 rate_limited` — more than 30 decisions per agent in 24 hours diff --git a/specs/api/auth.md b/specs/api/auth.md index b887bb45..b654c4fe 100644 --- a/specs/api/auth.md +++ b/specs/api/auth.md @@ -235,14 +235,14 @@ Returns the current Person (full PersonResponse shape — see [api/people.md](pe "accountLevel": "staff", "hasGitHubLink": true, "lastLoginMethod": "github", - "slack": { "linked": true, "linkedAt": "2026-11-20T…" } + "slack": { "linked": true, "linkedAt": "2026-11-20T…", "via": "auto" } } } ``` `hasGitHubLink` is `Person.githubUserId !== null`. `lastLoginMethod` is one of `"github" | "legacy_password" | "password_reset"`; the SPA can use it to render UI hints (e.g., "Signed in via password — connect GitHub for faster sign-in next time" inline on `/account`). -`slack` is whether the person has a verified [Slack link](slack-link.md) and since when (`{ linked: false, linkedAt: null }` when not); it never carries the Slack user id. +`slack` is whether the person has a verified [Slack link](slack-link.md), since when, and how it was made (`via`: `auto` or `code`; `{ linked: false, linkedAt: null, via: null }` when not); it never carries the Slack user id. For a signed-in person with no link, `/me` may first try the [automatic link](slack-link.md#when-it-runs), waiting at most 1.5 seconds. If no session, returns 200 with `data.person = null`, `data.accountLevel = "anonymous"`, `hasGitHubLink = false`, `lastLoginMethod = null`, `slack = null`. (We deliberately do not 401 here — the frontend calls this on every page load including public pages.) diff --git a/specs/api/saml.md b/specs/api/saml.md index 24dc3947..f22366af 100644 --- a/specs/api/saml.md +++ b/specs/api/saml.md @@ -122,7 +122,7 @@ Rules: - `SAMLResponse` (base64-encoded signed XML) - `RelayState` — the channel/redir path so Slack lands the user in the right place -6. **Slack SSO stamp.** Set `PrivateProfile.lastSlackSsoAt = now` for the person (best-effort; a private-store failure never fails the assertion). Surfaced on the staff roster ([api/moderation.md](moderation.md)). +6. **Slack SSO stamp.** Set `PrivateProfile.lastSlackSsoAt = now` for the person (best-effort; a private-store failure never fails the assertion). Surfaced on the staff roster ([api/moderation.md](moderation.md)). The same moment schedules the person's [automatic Slack link](slack-link.md#when-it-runs) check, about a minute later and never in the assertion's path. The destination URL inside the Response includes the `redir` so Slack's POST endpoint sees it. diff --git a/specs/api/slack-link.md b/specs/api/slack-link.md index d3ffb77d..18179b0f 100644 --- a/specs/api/slack-link.md +++ b/specs/api/slack-link.md @@ -2,14 +2,98 @@ A verified link between a site account and a Slack user, so the ops bot can reach project admins in Slack and, when allowed, act on what they say there -([agent-applications.md](agent-applications.md)). Both sides are proven: the -site knows who is signed in when it issues a code, and Slack knows who sent -the code to the bot. - -The site is already the SAML sign-in for the Slack workspace -([saml.md](saml.md)), but it does not learn the Slack user id from that, and -the self-typed `Person.slackHandle` proves nothing. This link is the only -mapping anything routes on. +([agent-applications.md](agent-applications.md)). A link is made one of two +ways, and the link records which (`via`): + +- **Automatically** (`via = auto`), by the site alone, when two independent + facts agree: the Slack user Slack finds for the account's email has the + handle the site asserted for this person at Slack sign-in. See + [Automatic link](#automatic-link). +- **By code** (`via = code`), the fallback for anyone the automatic path + cannot link: the site knows who is signed in when it issues a code, and + Slack knows who sent the code to the bot. + +The site is the SAML sign-in for the Slack workspace ([saml.md](saml.md)), +but the assertion does not tell it the Slack user id, and the self-typed +`Person.slackHandle` proves nothing. This link is the only mapping anything +routes on; an agent never asserts one. + +## Automatic link + +Every Slack account in the workspace is created through the site's SAML +sign-in, and Slack keeps the NameID the site asserted (`slackSamlNameId`) as +the account's handle (`user.name`). Neither the handle nor the email alone is +trusted (a member may be able to change either in Slack); both must agree. + +The site links a person to a Slack user when **all** hold: + +1. `SLACK_BOT_TOKEN` and `SLACK_TEAM_ID` are configured. The token is the + site's own, read-only, with the scopes `users:read` and `users:read.email`. + Without both, the automatic path is off and nothing else changes. +2. `users.lookupByEmail` for the person's private-profile email returns a + user whose `name` **exactly** equals the person's `slackSamlNameId` (no + case folding, no punctuation normalising). +3. That user's `team_id` is `SLACK_TEAM_ID`, and it is not `deleted`, not a + bot (`is_bot`, or Slackbot), and not a guest (`is_restricted`, + `is_ultra_restricted`). +4. The person exists, is not deactivated, is not an agent account, has a + private profile, has no link already, and has not opted out (below). +5. No other account is linked to that Slack user. (If one is, nothing + happens; the code path's `409` still applies there.) + +The link is stored as for a code link, with `via = auto` and `verifiedAt`. +A failed match, a Slack error or a rate limit changes nothing and never fails +the request that triggered the attempt. + +### When it runs + +The site has no list of members to sweep and never fans out across all of +them; it checks one person at a time, when it has a reason to: + +- **At Slack SAML sign-in**, about a minute after the assertion is issued + (a first sign-in creates the Slack account only once Slack consumes the + assertion). This clears that person's cached "no match". +- **On `GET /api/auth/me`** for a signed-in person with no link and no + opt-out, when no result for them is cached. `/me` waits at most 1.5 + seconds for it; a slower lookup finishes in the background and shows on + the next load. +- **When the agent feed needs an admin's Slack id** and the admin has no + link (or an automatic link due for re-verification), for at most 5 admins + per feed request; the rest wait for a later request. + +Limits and caching, all in memory (a restart forgets them): + +- At most 20 Slack calls a minute across the site, below `users.lookupByEmail`'s + rate tier; a `429` from Slack stops all calls for its `Retry-After`. + Calls over budget are skipped, not queued. +- A "no match" for a person is cached for 24 hours; a Slack error for 15 + minutes. One attempt per person runs at a time. + +### Re-verification + +An automatic link is re-checked (the same lookup and the same five +conditions, for the same Slack user) when it is used and its `verifiedAt` is +more than **24 hours** old: + +- **Before an on-behalf decision** ([agent-applications.md](agent-applications.md)), + always, before the write. If it no longer matches, the link is removed and + the decision is refused `403 not_project_admin`; if Slack cannot be + asked (no token, an error, a rate limit), the decision is refused the same + way and the link is kept. +- **When the feed or `/me` uses it**, within the budget above. A re-check + that no longer matches removes the link. If a re-check cannot run, the + link is still used until it is **7 days** past `verifiedAt`; after that + the feed carries `slackUserId: null` for that admin until a re-check + succeeds. + +Code links are not re-verified: the member proved them by DM. + +### Opt-out + +Disconnecting (`DELETE /api/account/slack-link`) records +`slackAutoLinkOptOutAt` on the private profile, and the automatic path never +links that person again. Redeeming a code clears the opt-out: reconnecting is +always on purpose. ## Endpoints @@ -21,7 +105,7 @@ mapping anything routes on. ## POST /api/account/slack-link/code -No body. Returns a fresh code and invalidates any earlier unredeemed code for +The fallback for a member the automatic path cannot link. No body. Returns a fresh code and invalidates any earlier unredeemed code for the caller. ```json @@ -52,7 +136,8 @@ The bot calls this when a member DMs it a code. ``` On success, in the same request: sets `PrivateProfile.slack = { teamId, -userId, linkedAt }` for the person who issued the code and consumes the code. +userId, linkedAt, via: "code", verifiedAt }` for the person who issued the +code, clears any `slackAutoLinkOptOutAt`, and consumes the code. `slackTeamId` must be the workspace the site serves (`SLACK_TEAM_ID`; mismatch `422`). With no workspace configured every redemption is refused (`422`): the site fails closed rather than link to an unknown workspace. @@ -76,11 +161,13 @@ The bot replies to the member in the DM; the site emails nothing. ## DELETE /api/account/slack-link -Clears `PrivateProfile.slack`. `204`. No error if there was none. +Clears `PrivateProfile.slack` and records `slackAutoLinkOptOutAt`, so the +automatic path does not link the account again ([Opt-out](#opt-out)). `204`. +No error if there was no link (the opt-out is recorded either way). ## Notes -- **Private only.** The link lives on the private profile +- **Private only.** The link and the opt-out live on the private profile ([private-storage.md](../behaviors/private-storage.md)), changes no public record, and makes no public commit. The Slack user id is returned only to agents holding `projects:applications:read`, for the admins of an @@ -89,5 +176,9 @@ Clears `PrivateProfile.slack`. `204`. No error if there was none. user per account (a new link replaces the old). - **Purge** removes it with the private profile. **Deactivation** leaves it in place but the deactivated person is never resolved as an admin. -- `GET /api/auth/me` reports `slack: { linked, linkedAt }` to the person - themselves. +- `GET /api/auth/me` reports `slack: { linked, linkedAt, via }` to the + person themselves. +- **No email leaves the site toward anyone but Slack.** The automatic path + sends the person's email to Slack's API (which already holds it for that + member) and to nothing else; neither the email nor the Slack user id is + logged, and no response says whether a lookup found anyone. diff --git a/specs/architecture.md b/specs/architecture.md index b2977777..92e3644f 100644 --- a/specs/architecture.md +++ b/specs/architecture.md @@ -182,6 +182,7 @@ Runtime configuration (sealed-secrets in our cluster): | `SAML_ENTITY_ID` | Optional. Stable SAML IdP entity ID / assertion `Issuer` (default `https://codeforphilly.org/api/saml/slack/metadata`). Deliberately independent of `CFP_SITE_HOST` so cutover doesn't change the identifier Slack has on file — see [api/saml.md#idp-identity-and-hosts](api/saml.md#idp-identity-and-hosts). | | `SLACK_TEAM_HOST` | Slack workspace host (default `codeforphilly.slack.com`). Used by the `/chat` redirect ([api/chat](screens/chat.md)) and the SAML SP entity binding (ACS URL, NameQualifier). Never used for our own IdP entity ID or endpoint URLs. | | `SLACK_TEAM_ID` | The Slack workspace id (`T…`) the site serves. A [Slack link](api/slack-link.md) or an agent's on-behalf decision naming another workspace is refused; unset, no link can be made. | +| `SLACK_BOT_TOKEN` | Optional secret. The site's own read-only Slack token (scopes `users:read`, `users:read.email`), used only for the [automatic Slack link](api/slack-link.md#automatic-link). Unset, the automatic link is off and code links still work. | | `SLACK_OPS_BOT_DM_URL` | Optional. A link that opens a direct message with the ops bot; the Account screen's Slack row links the bot's name to it. | | `POSTMARK_SERVER_TOKEN` | Optional. When set, mutates the notifier from the no-op `LoggingNotifier` to the live `EmailNotifier` (Postmark transport). | | `POSTMARK_MESSAGE_STREAM` | Optional. Postmark message stream for outbound mail (default `outbound`). | diff --git a/specs/behaviors/private-storage.md b/specs/behaviors/private-storage.md index 8287da4d..d838c412 100644 --- a/specs/behaviors/private-storage.md +++ b/specs/behaviors/private-storage.md @@ -75,7 +75,7 @@ the agent account deletes its lines with the rest of its private data. "status": "ok", "checkedAt": "2026-09-18T20:00:00Z" }, "lastSlackSsoAt": "2026-09-18T01:12:00Z", - "slack": { "teamId": "T…", "userId": "U…", "linkedAt": "2026-11-20T…" }, + "slack": { "teamId": "T…", "userId": "U…", "linkedAt": "2026-11-20T…", "via": "auto", "verifiedAt": "2026-11-20T…" }, "emailBounce": { "type": "HardBounce", "bouncedAt": "2026-09-10T...", "description": "…", "inactive": true }, "updatedAt": "2026-05-15T18:42:00Z" } @@ -83,7 +83,8 @@ the agent account deletes its lines with the rest of its private data. `slack` is optional: the verified link to a Slack user, set and cleared only by [api/slack-link.md](../api/slack-link.md); it is what an agent's Slack user id -resolves through. The other three trailing fields are optional and exist for +resolves through. `slackAutoLinkOptOutAt` (optional) records that the member +disconnected, so the automatic link leaves them alone. The other three trailing fields are optional and exist for staff moderation ([api/moderation.md](../api/moderation.md)): - `github` — what GitHub said about the linked account, captured at every GitHub diff --git a/specs/data-model.md b/specs/data-model.md index 0be806e3..4d8c0c4f 100644 --- a/specs/data-model.md +++ b/specs/data-model.md @@ -120,7 +120,8 @@ The sensitive complement to a Person. Stored in the **private store** (S3-compat | email | string | the user's most-recent GitHub-verified primary email. Refreshed on every OAuth login. Lowercased for canonical form. | | emailRefreshedAt | iso8601 | when `email` was last refreshed from GitHub | | newsletter | object nullable | newsletter subscription state (see below) | -| slack | object nullable | the verified link to a Slack user: `{ teamId, userId, linkedAt }`. Set and cleared only by [api/slack-link.md](api/slack-link.md). | +| slack | object nullable | the verified link to a Slack user: `{ teamId, userId, linkedAt, via, verifiedAt }`, `via` = `auto` \| `code` (absent means `code`), `verifiedAt` when an automatic link last re-checked. Set and cleared only by [api/slack-link.md](api/slack-link.md). | +| slackAutoLinkOptOutAt | iso8601 nullable | the member disconnected Slack; the automatic link never re-links them. Cleared by a code link. | | updatedAt | iso8601 | | The `newsletter` sub-object: diff --git a/specs/screens/account.md b/specs/screens/account.md index eb844e65..f43d8ec4 100644 --- a/specs/screens/account.md +++ b/specs/screens/account.md @@ -31,7 +31,8 @@ The card's contents depend on `me.hasGitHubLink`: - Refresh timestamp ("Last updated when you signed in on {date}") - **Slack** — the verified link to a Slack user ([api/slack-link.md](../api/slack-link.md)), from `me.slack`: - Not linked: "Connect Slack" button. It shows a one-time code and the instruction "Send this code in a direct message to the ops bot in the Code for Philly Slack within 10 minutes," with the bot's name linked to a DM with it. The row polls `GET /api/auth/me` while the code is live and turns linked when the bot confirms it. - - Linked: "Connected to Slack ✓ since {linkedAt}" with "Disconnect". Under it: "Lets the ops bot send you project notices in Slack and act on your replies, such as accepting an application you answer there." + - Linked: "Connected to Slack ✓ since {linkedAt}", followed by "(matched automatically)" when `via = auto` or "(by code)" when `via = code`, with "Disconnect". Under it: "Lets the ops bot send you project notices in Slack and act on your replies, such as accepting an application you answer there." + - Disconnect's confirm says the site will not reconnect the account by itself; "Connect Slack" (the code) reconnects it. - The row never shows the Slack user id. **State B — GitHub not yet linked** (`me.hasGitHubLink === false`) From 28a2b5b2ff18fc64c2640241212bb953cc841777 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:04:56 +0000 Subject: [PATCH 72/78] feat(shared): how a Slack link was made, when it was verified, and the opt-out PrivateProfile.slack gains via (auto | code; absent means code) and verifiedAt; the profile gains slackAutoLinkOptOutAt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- packages/shared/src/schemas/private-profile.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/shared/src/schemas/private-profile.ts b/packages/shared/src/schemas/private-profile.ts index fbf092ed..43102bcc 100644 --- a/packages/shared/src/schemas/private-profile.ts +++ b/packages/shared/src/schemas/private-profile.ts @@ -43,6 +43,10 @@ const SlackLinkSchema = z.object({ teamId: z.string().regex(/^[A-Z0-9]{2,32}$/), userId: z.string().regex(/^[A-Z0-9]{2,32}$/), linkedAt: z.string().datetime({ offset: true }), + /** How it was made: the site matched email and handle, or the member sent a code. Absent → `code`. */ + via: z.enum(['auto', 'code']).optional(), + /** When an automatic link was last re-checked against Slack (and when a code link was made). */ + verifiedAt: z.string().datetime({ offset: true }).optional(), }); export const PrivateProfileSchema = z.object({ @@ -55,6 +59,8 @@ export const PrivateProfileSchema = z.object({ lastSlackSsoAt: z.string().datetime({ offset: true }).nullable().optional(), emailBounce: EmailBounceSchema.nullable().optional(), slack: SlackLinkSchema.nullable().optional(), + /** The member disconnected Slack: the automatic link never re-links them. Cleared by a code link. */ + slackAutoLinkOptOutAt: z.string().datetime({ offset: true }).nullable().optional(), updatedAt: z.string().datetime({ offset: true }), }); From a680ff49276052b036a3b508abb96941ebccbe65 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:04:56 +0000 Subject: [PATCH 73/78] feat(api): a Slack directory client for users.lookupByEmail Behind an interface so tests use a fake. 429 and ratelimited become SlackRateLimitedError with Retry-After; users_not_found is null; anything else is SlackApiError carrying Slack's error string, never the email. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/src/slack/directory.ts | 89 +++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 apps/api/src/slack/directory.ts diff --git a/apps/api/src/slack/directory.ts b/apps/api/src/slack/directory.ts new file mode 100644 index 00000000..8ddf4726 --- /dev/null +++ b/apps/api/src/slack/directory.ts @@ -0,0 +1,89 @@ +/** + * The one Slack API call the site makes: `users.lookupByEmail`, with the + * site's own read-only token (scopes `users:read`, `users:read.email`) — + * specs/api/slack-link.md → Automatic link. + * + * Behind an interface so tests use a fake and never touch the network. + * The email is sent to Slack only; it is never logged here or by callers. + */ + +/** The fields of a Slack user the automatic link looks at. */ +export interface SlackDirectoryUser { + readonly id: string; + /** The handle; Slack keeps the SAML NameID the site asserted at first sign-in. */ + readonly name: string; + readonly team_id?: string; + readonly deleted?: boolean; + readonly is_bot?: boolean; + readonly is_restricted?: boolean; + readonly is_ultra_restricted?: boolean; +} + +/** Slack said 429: stop calling for `retryAfterSeconds`. */ +export class SlackRateLimitedError extends Error { + readonly retryAfterSeconds: number; + constructor(retryAfterSeconds: number) { + super('Slack rate limited'); + this.name = 'SlackRateLimitedError'; + this.retryAfterSeconds = retryAfterSeconds; + } +} + +/** Any other failure: a network error, a non-OK status, or `ok: false` with an error other than not-found. */ +export class SlackApiError extends Error { + /** Slack's `error` string or the HTTP status; never the request's arguments. */ + readonly slackError: string; + constructor(slackError: string) { + super(`Slack API error: ${slackError}`); + this.name = 'SlackApiError'; + this.slackError = slackError; + } +} + +export interface SlackDirectory { + /** The user with this email, or null when Slack has none. Throws the errors above. */ + lookupUserByEmail(email: string): Promise<SlackDirectoryUser | null>; +} + +/** The real client, over `fetch`. */ +export class FetchSlackDirectory implements SlackDirectory { + readonly #token: string; + readonly #fetch: typeof fetch; + + constructor(token: string, fetchImpl: typeof fetch = fetch) { + this.#token = token; + this.#fetch = fetchImpl; + } + + async lookupUserByEmail(email: string): Promise<SlackDirectoryUser | null> { + let res: Response; + try { + res = await this.#fetch('https://slack.com/api/users.lookupByEmail', { + method: 'POST', + headers: { + authorization: `Bearer ${this.#token}`, + 'content-type': 'application/x-www-form-urlencoded', + }, + body: new URLSearchParams({ email }).toString(), + signal: AbortSignal.timeout(5000), + }); + } catch (err) { + throw new SlackApiError(err instanceof Error && err.name === 'TimeoutError' ? 'timeout' : 'network'); + } + if (res.status === 429) { + const retry = Number(res.headers.get('retry-after')); + throw new SlackRateLimitedError(Number.isFinite(retry) && retry > 0 ? retry : 60); + } + if (!res.ok) throw new SlackApiError(`http_${res.status}`); + let body: { ok?: boolean; error?: string; user?: SlackDirectoryUser }; + try { + body = (await res.json()) as typeof body; + } catch { + throw new SlackApiError('invalid_json'); + } + if (body.ok && body.user) return body.user; + if (body.error === 'users_not_found') return null; + if (body.error === 'ratelimited') throw new SlackRateLimitedError(60); + throw new SlackApiError(typeof body.error === 'string' ? body.error : 'unknown'); + } +} From c4b9da367e0803b0e418c4a801245cff9115b9e1 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:04:56 +0000 Subject: [PATCH 74/78] feat(api): link Slack accounts automatically when email and handle agree With SLACK_BOT_TOKEN and SLACK_TEAM_ID, the site links a person when the Slack user found for their private-profile email has a handle exactly equal to slackSamlNameId and is a full, active, human member of the workspace. Runs about a minute after Slack SAML sign-in, on /me (waiting at most 1.5 s), and for up to 5 admins per feed request; 20 Slack calls a minute site-wide, Retry-After honoured, no-match cached 24 h and errors 15 min, one attempt per person at a time; never throws to its caller. Automatic links past 24 h are re-checked when used and always before an on-behalf decision: a mismatch removes the link, and the decision is refused not_project_admin if the link is removed or could not be re-checked (resolved again under the write lock). The feed drops an automatic link unverified for 7 days. Code links record via=code and clear the opt-out; disconnecting records it. Profile rewrites carry the opt-out. me.slack reports via. The email is never logged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/api/src/env.ts | 7 + apps/api/src/plugins/services.ts | 14 +- apps/api/src/routes/agent-applications.ts | 5 +- apps/api/src/routes/auth.ts | 17 +- apps/api/src/routes/saml.ts | 2 + apps/api/src/services/account-claim.ts | 2 + apps/api/src/services/agent-decision.ts | 28 +- apps/api/src/services/agent-feed.ts | 31 ++- apps/api/src/services/github-account.ts | 1 + apps/api/src/services/person.write.ts | 1 + apps/api/src/services/slack-auto-link.ts | 321 +++++++++++++++++++++ apps/api/src/services/slack-link.ts | 27 +- apps/api/src/store/private/base.ts | 4 + apps/api/src/store/private/interface.ts | 2 + apps/api/tests/slack-auto-link.test.ts | 325 ++++++++++++++++++++++ apps/api/tests/slack-link.test.ts | 4 +- 16 files changed, 771 insertions(+), 20 deletions(-) create mode 100644 apps/api/src/services/slack-auto-link.ts create mode 100644 apps/api/tests/slack-auto-link.test.ts diff --git a/apps/api/src/env.ts b/apps/api/src/env.ts index 79d0cdf3..f05b09ae 100644 --- a/apps/api/src/env.ts +++ b/apps/api/src/env.ts @@ -123,6 +123,12 @@ export const EnvSchema = z.object({ * no link can be made (specs/api/slack-link.md). */ SLACK_TEAM_ID: z.string().regex(/^T[A-Z0-9]+$/).optional(), + /** + * The site's own read-only Slack token (scopes users:read, + * users:read.email), used only for the automatic Slack link + * (specs/api/slack-link.md → Automatic link). Unset → automatic linking is off. + */ + SLACK_BOT_TOKEN: z.string().startsWith('xoxb-').optional(), /** Optional link that opens a DM with the ops bot, for the Account screen. */ SLACK_OPS_BOT_DM_URL: z.url().optional(), }); @@ -168,6 +174,7 @@ export const envJsonSchema = { POSTMARK_MESSAGE_STREAM: { type: 'string', default: 'outbound' }, POSTMARK_WEBHOOK_SECRET: { type: 'string', minLength: 16 }, SLACK_TEAM_ID: { type: 'string', pattern: '^T[A-Z0-9]+$' }, + SLACK_BOT_TOKEN: { type: 'string', pattern: '^xoxb-' }, SLACK_OPS_BOT_DM_URL: { type: 'string', pattern: '^https://' }, CFP_NOTIFICATION_FROM: { type: 'string', diff --git a/apps/api/src/plugins/services.ts b/apps/api/src/plugins/services.ts index abce77f1..80e1324a 100644 --- a/apps/api/src/plugins/services.ts +++ b/apps/api/src/plugins/services.ts @@ -46,6 +46,8 @@ import { ApplicationNotices } from '../services/application-notices.js'; import { SlackLinkService } from '../services/slack-link.js'; import { AgentFeedService } from '../services/agent-feed.js'; import { AgentDecisionService } from '../services/agent-decision.js'; +import { SlackAutoLinkService } from '../services/slack-auto-link.js'; +import { FetchSlackDirectory } from '../slack/directory.js'; declare module 'fastify' { interface FastifyInstance { @@ -80,6 +82,7 @@ declare module 'fastify' { slackLinks: SlackLinkService; agentFeed: AgentFeedService; agentDecisions: AgentDecisionService; + slackAutoLink: SlackAutoLinkService; }; /** Shared in-memory state — write routes call StateApply.apply against this. */ inMemoryState: InMemoryState; @@ -146,6 +149,13 @@ async function servicesPlugin(fastify: FastifyInstance): Promise<void> { const githubAccount = new GitHubAccountService(state); const applications = new ProjectApplicationService(state, fastify.store.private); + // The automatic Slack link (slack-link.md → Automatic link): off without the site's own token. + const slackAutoLink = new SlackAutoLinkService(state, fastify.store.private, { + teamId: fastify.config.SLACK_TEAM_ID, + directory: fastify.config.SLACK_BOT_TOKEN ? new FetchSlackDirectory(fastify.config.SLACK_BOT_TOKEN) : null, + log: fastify.log, + }); + fastify.addHook('onClose', async () => slackAutoLink.close()); fastify.decorate('services', { projects: new ProjectService(state, fts, fastify.store.private), people: new PersonService(state, fts, fastify.store.private), @@ -209,10 +219,12 @@ async function servicesPlugin(fastify: FastifyInstance): Promise<void> { teamId: fastify.config.SLACK_TEAM_ID, botDmUrl: fastify.config.SLACK_OPS_BOT_DM_URL, }), - agentFeed: new AgentFeedService(state, fastify.store.private, { teamId: fastify.config.SLACK_TEAM_ID }), + agentFeed: new AgentFeedService(state, fastify.store.private, { teamId: fastify.config.SLACK_TEAM_ID, autoLink: slackAutoLink }), agentDecisions: new AgentDecisionService(state, fastify.store.private, applications, { teamId: fastify.config.SLACK_TEAM_ID, + autoLink: slackAutoLink, }), + slackAutoLink, }); } diff --git a/apps/api/src/routes/agent-applications.ts b/apps/api/src/routes/agent-applications.ts index 1f064278..97644788 100644 --- a/apps/api/src/routes/agent-applications.ts +++ b/apps/api/src/routes/agent-applications.ts @@ -101,7 +101,10 @@ export async function agentApplicationRoutes(fastify: FastifyInstance): Promise< // Refuse early (before taking the lock), and name the admin for the commit; // decide() checks both again under the lock. svc.checkCap(caller.agent.person.slug, new Date()); - const { admin } = svc.resolveAdmin(projectSlug, input.onBehalfOf); + const { admin } = svc.resolveAdmin(projectSlug, input.onBehalfOf, { requireFresh: false }); + // An automatic link past its age is re-checked against Slack before the write + // (slack-link.md → Re-verification); decide() refuses one that is still stale. + await svc.refreshLink(admin); const accept = input.decision === 'accept'; const result = await fastify.store.transact( diff --git a/apps/api/src/routes/auth.ts b/apps/api/src/routes/auth.ts index 6c95e103..4956d8a8 100644 --- a/apps/api/src/routes/auth.ts +++ b/apps/api/src/routes/auth.ts @@ -32,7 +32,7 @@ import { verifyLegacyPassword, } from '../auth/legacy-password.js'; import type { SessionMeta } from '../auth/session-metadata.js'; -import type { LegacyPasswordCredential, PasswordToken } from '@cfp/shared/schemas'; +import type { LegacyPasswordCredential, PasswordToken, Person } from '@cfp/shared/schemas'; import { generateCsrfState, generatePkceVerifier, @@ -101,6 +101,19 @@ async function persistSessionMetadata( await fastify.sessionMetadata.add(meta, fastify.store.private); } +/** + * `me.slack`: may first try the automatic Slack link, waiting at most + * ME_WAIT_MS; a Slack failure never fails `/me` (slack-link.md → When it runs). + */ +async function selfSlackStatus(fastify: FastifyInstance, person: Person) { + try { + await fastify.services.slackAutoLink.refreshForSelf(person); + } catch { + // never fails /me + } + return slackStatus(await fastify.store.private.getProfile(person.id)); +} + export async function authRoutes(fastify: FastifyInstance): Promise<void> { // --------------------------------------------------------------------------- @@ -303,7 +316,7 @@ export async function authRoutes(fastify: FastifyInstance): Promise<void> { lastLoginMethod: session.loginMethod ?? null, // Whether the person has a verified Slack link, never its user id // (specs/api/slack-link.md). - slack: person ? slackStatus(await fastify.store.private.getProfile(person.id)) : null, + slack: person ? await selfSlackStatus(fastify, person) : null, }); }, ); diff --git a/apps/api/src/routes/saml.ts b/apps/api/src/routes/saml.ts index 801b1cb1..46060bc0 100644 --- a/apps/api/src/routes/saml.ts +++ b/apps/api/src/routes/saml.ts @@ -401,6 +401,8 @@ async function stampSlackSso(fastify: FastifyInstance, personId: string): Promis if (!profile) return; const now = new Date().toISOString(); await fastify.store.private.putProfile({ ...profile, lastSlackSsoAt: now, updatedAt: now }); + // The person is entering Slack: check the automatic link about a minute from now. + fastify.services.slackAutoLink.scheduleAfterSignIn(personId); } catch (err) { fastify.log.warn({ err, personId }, 'could not stamp lastSlackSsoAt'); } diff --git a/apps/api/src/services/account-claim.ts b/apps/api/src/services/account-claim.ts index d3c501c0..bfa7ee3d 100644 --- a/apps/api/src/services/account-claim.ts +++ b/apps/api/src/services/account-claim.ts @@ -561,6 +561,7 @@ export class AccountClaimService { emailRefreshedAt: now, newsletter: currentProfile?.newsletter ?? null, slack: currentProfile?.slack ?? null, + slackAutoLinkOptOutAt: currentProfile?.slackAutoLinkOptOutAt ?? null, updatedAt: now, }); tx.private.putProfile(profile); @@ -707,6 +708,7 @@ export class AccountClaimService { newsletter: claimedProfile?.newsletter ?? requesterProfile.newsletter ?? null, // Same human: a Slack link made from either account survives the merge. slack: requesterProfile.slack ?? claimedProfile?.slack ?? null, + slackAutoLinkOptOutAt: requesterProfile.slackAutoLinkOptOutAt ?? claimedProfile?.slackAutoLinkOptOutAt ?? null, updatedAt: now, }); tx.private.putProfile(merged); diff --git a/apps/api/src/services/agent-decision.ts b/apps/api/src/services/agent-decision.ts index 2e32d7c5..1d2e2c20 100644 --- a/apps/api/src/services/agent-decision.ts +++ b/apps/api/src/services/agent-decision.ts @@ -34,6 +34,7 @@ import type { PrivateStore } from '../store/private/interface.js'; import type { DualStoreTx } from '../store/store.js'; import { membershipsOfProject } from './memberships.js'; import { NOTE_MAX, type DecideResult, type ProjectApplicationService } from './project-application.js'; +import { linkAge, REVERIFY_AFTER_MS, type SlackAutoLinkService } from './slack-auto-link.js'; const DAY = 24 * 60 * 60 * 1000; export const AGENT_DECISIONS_PER_DAY = 30; @@ -55,6 +56,7 @@ export class AgentDecisionService { readonly #privateStore: PrivateStore; readonly #applications: ProjectApplicationService; readonly #teamId: string | undefined; + readonly #autoLink: SlackAutoLinkService | undefined; /** agent slug → decisions recorded in this process (membership id and when), for the cap. */ readonly #log = new Map<string, Array<{ id: string; at: number }>>(); @@ -62,12 +64,22 @@ export class AgentDecisionService { state: InMemoryState, privateStore: PrivateStore, applications: ProjectApplicationService, - opts: { teamId?: string | undefined }, + opts: { teamId?: string | undefined; autoLink?: SlackAutoLinkService }, ) { this.#state = state; this.#privateStore = privateStore; this.#applications = applications; this.#teamId = opts.teamId; + this.#autoLink = opts.autoLink; + } + + /** + * Re-verify the admin's automatic link if it is due (slack-link.md → + * Re-verification). A mismatch removes the link; either failure leaves it + * stale, and {@link resolveAdmin} then refuses `not_project_admin`. + */ + async refreshLink(admin: Person, now: Date = new Date()): Promise<void> { + if (this.#autoLink) await this.#autoLink.freshForDecision(admin, now); } /** Shape checks that need no state. */ @@ -92,7 +104,11 @@ export class AgentDecisionService { * once before the write (to name them in the commit) and again under the * write lock, where it must resolve to the same person. */ - resolveAdmin(projectSlug: string, onBehalfOf: AgentDecisionInput['onBehalfOf']): { admin: Person; project: Project } { + resolveAdmin( + projectSlug: string, + onBehalfOf: AgentDecisionInput['onBehalfOf'], + opts: { requireFresh: boolean; now?: Date } = { requireFresh: true }, + ): { admin: Person; project: Project } { const project = projectBySlug(this.#state, projectSlug); if (!project || project.deletedAt) throw new ApiNotFoundError(`Project '${projectSlug}' not found`); const refuse = (): never => { @@ -105,6 +121,12 @@ export class AgentDecisionService { if (!personId) return refuse(); const admin = this.#state.people.get(personId); if (!admin || admin.deletedAt || isAgentAccount(this.#state, admin.slug)) return refuse(); + if (opts.requireFresh) { + // An automatic link must have been verified within the last day (code links stand). + const link = this.#privateStore.peekProfile(admin.id)?.slack; + if (!link || link.userId !== onBehalfOf.slackUserId) return refuse(); + if (link.via === 'auto' && linkAge(link, (opts.now ?? new Date()).getTime()) > REVERIFY_AFTER_MS) return refuse(); + } // `project-admin` alone, as a plain user: staff and administrator powers do not carry over. const asAdmin: SessionContext = { person: admin, accountLevel: 'user', personId: admin.id }; @@ -162,7 +184,7 @@ export class AgentDecisionService { now: Date = new Date(), ): Promise<AgentDecisionResult> { this.checkCap(agent.person.slug, now); - const { admin } = this.resolveAdmin(projectSlug, input.onBehalfOf); + const { admin } = this.resolveAdmin(projectSlug, input.onBehalfOf, { requireFresh: true, now }); if (admin.id !== expectedAdminId) throw new ForbiddenError(NOT_ADMIN, 'not_project_admin'); const asAdmin: SessionContext = { person: admin, accountLevel: 'user', personId: admin.id }; const via = { agentGrantId: agent.grant.id }; diff --git a/apps/api/src/services/agent-feed.ts b/apps/api/src/services/agent-feed.ts index a33ea7d7..2d5b784c 100644 --- a/apps/api/src/services/agent-feed.ts +++ b/apps/api/src/services/agent-feed.ts @@ -30,6 +30,7 @@ import { personBySlug, projectBySlug, type InMemoryState } from '../store/memory import type { PrivateStore } from '../store/private/interface.js'; import { adminPeople } from './memberships.js'; import { applicantFacts } from './project-application.js'; +import { FEED_ATTEMPTS_PER_REQUEST, type AutoLinkBudget, type SlackAutoLinkService } from './slack-auto-link.js'; const DAY = 24 * 60 * 60 * 1000; export const FEED_DEFAULT_WINDOW_MS = 7 * DAY; @@ -134,11 +135,17 @@ export class AgentFeedService { readonly #state: InMemoryState; readonly #privateStore: PrivateStore; readonly #teamId: string | undefined; + readonly #autoLink: SlackAutoLinkService | undefined; - constructor(state: InMemoryState, privateStore: PrivateStore, opts: { teamId?: string | undefined }) { + constructor( + state: InMemoryState, + privateStore: PrivateStore, + opts: { teamId?: string | undefined; autoLink?: SlackAutoLinkService }, + ) { this.#state = state; this.#privateStore = privateStore; this.#teamId = opts.teamId; + this.#autoLink = opts.autoLink; } async events( @@ -173,8 +180,18 @@ export class AgentFeedService { raw.sort(compare); const page = raw.slice(0, limit); + // Up to a few automatic links or re-checks per request; never a fan-out. + const budget: AutoLinkBudget = { left: FEED_ATTEMPTS_PER_REQUEST }; + const admins = new Map<string, FeedEvent['admins']>(); const data: FeedEvent[] = []; - for (const e of page) data.push(await this.#serialize(e, e.type, e.m)); + for (const e of page) { + let list = admins.get(e.m.projectSlug); + if (!list) { + list = await this.#admins(e.m.projectSlug, budget, now); + admins.set(e.m.projectSlug, list); + } + data.push(this.#serialize(e, e.type, e.m, list)); + } const last = page[page.length - 1]; const next = last ? encodeCursor(last) @@ -182,7 +199,7 @@ export class AgentFeedService { return { data, next }; } - async #serialize(pos: Position, type: FeedEventType, m: ProjectMembership): Promise<FeedEvent> { + #serialize(pos: Position, type: FeedEventType, m: ProjectMembership, admins: FeedEvent['admins']): FeedEvent { const s = this.#state; const project = projectBySlug(s, m.projectSlug)!; const applicant = personBySlug(s, m.personSlug)!; @@ -210,15 +227,19 @@ export class AgentFeedService { decidedVia: app.decidedVia ?? null, closedBy: app.closedBy ?? null, }, - admins: await this.#admins(project.slug), + admins, }; } /** The project's active admins, each with a Slack user id only when verified-linked in this workspace. */ - async #admins(projectSlug: string): Promise<FeedEvent['admins']> { + async #admins(projectSlug: string, budget: AutoLinkBudget, now: Date): Promise<FeedEvent['admins']> { const out: Array<PersonRef & { slackUserId: string | null }> = []; for (const person of adminPeople(this.#state, projectSlug)) { if (person.deletedAt) continue; + if (this.#autoLink) { + out.push({ ...ref(person), slackUserId: await this.#autoLink.slackIdForFeed(person, budget, now) }); + continue; + } const slack = (await this.#privateStore.getProfile(person.id))?.slack; const linked = slack && this.#teamId !== undefined && slack.teamId === this.#teamId; out.push({ ...ref(person), slackUserId: linked ? slack.userId : null }); diff --git a/apps/api/src/services/github-account.ts b/apps/api/src/services/github-account.ts index e51c1df5..fb09436f 100644 --- a/apps/api/src/services/github-account.ts +++ b/apps/api/src/services/github-account.ts @@ -167,6 +167,7 @@ export class GitHubAccountService { emailBounce: currentProfile?.emailBounce ?? null, // The Slack link is the person's, not the address's (slack-link.md). slack: currentProfile?.slack ?? null, + slackAutoLinkOptOutAt: currentProfile?.slackAutoLinkOptOutAt ?? null, github: identity.user ? githubFactsFrom(identity.user, 'ok', now) : (currentProfile?.github ?? null), updatedAt: now, }); diff --git a/apps/api/src/services/person.write.ts b/apps/api/src/services/person.write.ts index 9c103085..fbeaf810 100644 --- a/apps/api/src/services/person.write.ts +++ b/apps/api/src/services/person.write.ts @@ -174,6 +174,7 @@ export class PersonWriteService { emailRefreshedAt: now, newsletter: existingProfile?.newsletter ?? null, slack: existingProfile?.slack ?? null, + slackAutoLinkOptOutAt: existingProfile?.slackAutoLinkOptOutAt ?? null, updatedAt: now, }); tx.private.putProfile(profile); diff --git a/apps/api/src/services/slack-auto-link.ts b/apps/api/src/services/slack-auto-link.ts new file mode 100644 index 00000000..18197196 --- /dev/null +++ b/apps/api/src/services/slack-auto-link.ts @@ -0,0 +1,321 @@ +/** + * The automatic Slack link — specs/api/slack-link.md → Automatic link. + * + * The site links a person to a Slack user by itself when two independent + * facts agree: the user Slack finds for the person's private-profile email + * (`users.lookupByEmail`) has a handle exactly equal to the person's + * `slackSamlNameId`, and is a full, active, human member of the configured + * workspace. An agent never asserts a link. + * + * One person at a time, only when there is a reason (Slack SAML sign-in, + * `/me`, the agent feed needing an admin's id); never a sweep. Calls are + * budgeted site-wide and honour Slack's Retry-After; results are cached + * per person. Nothing here throws to its caller: a failed lookup leaves + * things as they were and never fails the request that triggered it. + * + * The email goes to Slack and nowhere else: never into a log line, an error + * or a response. Log lines carry the person id and Slack's error string only. + */ +import type { FastifyBaseLogger } from 'fastify'; +import type { Person, PrivateProfile, SlackLink } from '@cfp/shared/schemas'; + +import { isAgentAccount } from '../auth/agent-grant.js'; +import type { InMemoryState } from '../store/memory/state.js'; +import type { PrivateStore } from '../store/private/interface.js'; +import { SlackRateLimitedError, type SlackDirectory, type SlackDirectoryUser } from '../slack/directory.js'; + +const MINUTE = 60 * 1000; +const HOUR = 60 * MINUTE; +const DAY = 24 * HOUR; + +export const AUTO_LINK_CALLS_PER_MINUTE = 20; +export const NO_MATCH_TTL_MS = DAY; +export const ERROR_TTL_MS = 15 * MINUTE; +/** An automatic link older than this is re-checked when used, and always before a decision. */ +export const REVERIFY_AFTER_MS = DAY; +/** An automatic link unverified this long is not used by the feed until a re-check succeeds. */ +export const STALE_MAX_MS = 7 * DAY; +export const SIGN_IN_DELAY_MS = MINUTE; +export const ME_WAIT_MS = 1500; +export const FEED_ATTEMPTS_PER_REQUEST = 5; + +export type AutoLinkOutcome = + | 'off' // no token or workspace configured + | 'skipped' // not eligible, cached, or over budget: Slack was not asked + | 'linked' + | 'no_match' + | 'verified' + | 'removed' + | 'error'; // Slack failed or rate limited + +/** How many Slack calls one request may still make. */ +export interface AutoLinkBudget { + left: number; +} + +export function linkAge(link: SlackLink, now: number): number { + return now - Date.parse(link.verifiedAt ?? link.linkedAt); +} + +export class SlackAutoLinkService { + readonly #state: InMemoryState; + readonly #privateStore: PrivateStore; + readonly #teamId: string | undefined; + readonly #log: FastifyBaseLogger; + #directory: SlackDirectory | null; + /** Call times in the last minute, site-wide. */ + #calls: number[] = []; + #backoffUntil = 0; + /** personId → a cached negative result. */ + readonly #results = new Map<string, { kind: 'no_match' | 'error'; at: number }>(); + readonly #inflight = new Map<string, Promise<AutoLinkOutcome>>(); + readonly #timers = new Set<NodeJS.Timeout>(); + + constructor( + state: InMemoryState, + privateStore: PrivateStore, + opts: { teamId?: string | undefined; directory: SlackDirectory | null; log: FastifyBaseLogger }, + ) { + this.#state = state; + this.#privateStore = privateStore; + this.#teamId = opts.teamId; + this.#directory = opts.directory; + this.#log = opts.log; + } + + /** Swap the directory (tests use a fake; null turns the automatic link off). */ + useDirectory(directory: SlackDirectory | null): void { + this.#directory = directory; + this.#results.clear(); + this.#calls = []; + this.#backoffUntil = 0; + } + + get enabled(): boolean { + return this.#directory !== null && this.#teamId !== undefined; + } + + /** Cancel scheduled sign-in checks (app shutdown). */ + close(): void { + for (const t of this.#timers) clearTimeout(t); + this.#timers.clear(); + } + + /** Try to link a person who has no link. Never throws. */ + attempt(person: Person, opts: { budget?: AutoLinkBudget; now?: Date } = {}): Promise<AutoLinkOutcome> { + return this.#once(person.id, () => this.#attempt(person, opts.budget, opts.now ?? new Date())); + } + + /** Re-check an automatic link against Slack. Never throws. */ + reverify(person: Person, opts: { budget?: AutoLinkBudget; now?: Date } = {}): Promise<AutoLinkOutcome> { + return this.#once(person.id, () => this.#reverify(person, opts.budget, opts.now ?? new Date())); + } + + /** + * For `/me`: try the automatic link when the person has none, waiting at + * most `waitMs`; re-check a due automatic link in the background. + */ + async refreshForSelf(person: Person, waitMs = ME_WAIT_MS): Promise<void> { + if (!this.enabled) return; + const profile = await this.#privateStore.getProfile(person.id); + if (!profile) return; + if (profile.slack) { + if (profile.slack.via === 'auto' && linkAge(profile.slack, Date.now()) > REVERIFY_AFTER_MS) { + void this.reverify(person); + } + return; + } + if (profile.slackAutoLinkOptOutAt || this.#cached(person.id, Date.now())) return; + let timer: NodeJS.Timeout | undefined; + await Promise.race([ + this.attempt(person), + new Promise<void>((resolve) => { + timer = setTimeout(resolve, waitMs); + }), + ]); + if (timer) clearTimeout(timer); + } + + /** + * The Slack user id the feed may carry for an admin, or null: links (or + * re-checks) within the request's budget, and drops an automatic link + * unverified for {@link STALE_MAX_MS}. + */ + async slackIdForFeed(person: Person, budget: AutoLinkBudget, now: Date = new Date()): Promise<string | null> { + let profile = await this.#privateStore.getProfile(person.id); + if (!profile) return null; + if (!profile.slack && this.enabled) { + if ((await this.attempt(person, { budget, now })) === 'linked') profile = await this.#privateStore.getProfile(person.id); + } else if (profile.slack?.via === 'auto' && linkAge(profile.slack, now.getTime()) > REVERIFY_AFTER_MS) { + await this.reverify(person, { budget, now }); + profile = await this.#privateStore.getProfile(person.id); + } + const link = profile?.slack; + if (!link || this.#teamId === undefined || link.teamId !== this.#teamId) return null; + if (link.via === 'auto' && linkAge(link, now.getTime()) > STALE_MAX_MS) return null; + return link.userId; + } + + /** + * Before an on-behalf decision: a code link stands; an automatic link must + * have been verified within {@link REVERIFY_AFTER_MS}, re-checking it now + * if not. False when it no longer matches (it is removed) or cannot be checked. + */ + async freshForDecision(person: Person, now: Date = new Date()): Promise<boolean> { + const link = (await this.#privateStore.getProfile(person.id))?.slack; + if (!link) return false; + if (link.via !== 'auto' || linkAge(link, now.getTime()) <= REVERIFY_AFTER_MS) return true; + return (await this.reverify(person, { now })) === 'verified'; + } + + /** + * At Slack SAML sign-in: forget any cached result and check about a minute + * later (a first sign-in creates the Slack account only once Slack has + * consumed the assertion). + */ + scheduleAfterSignIn(personId: string, delayMs = SIGN_IN_DELAY_MS): void { + if (!this.enabled) return; + this.#results.delete(personId); + const timer = setTimeout(() => { + this.#timers.delete(timer); + const person = this.#state.people.get(personId); + if (person) void this.attempt(person); + }, delayMs); + timer.unref(); + this.#timers.add(timer); + } + + // --------------------------------------------------------------------------- + + #once(personId: string, run: () => Promise<AutoLinkOutcome>): Promise<AutoLinkOutcome> { + const running = this.#inflight.get(personId); + if (running) return running; + const p = run() + .catch((err: unknown) => { + this.#log.error({ err: err instanceof Error ? err.name : 'error', personId }, 'slack auto-link: unexpected failure'); + return 'error' as const; + }) + .finally(() => this.#inflight.delete(personId)); + this.#inflight.set(personId, p); + return p; + } + + #cached(personId: string, t: number): boolean { + const r = this.#results.get(personId); + if (!r) return false; + if (t - r.at < (r.kind === 'no_match' ? NO_MATCH_TTL_MS : ERROR_TTL_MS)) return true; + this.#results.delete(personId); + return false; + } + + /** Who may be linked automatically at all. */ + #eligible(person: Person, profile: PrivateProfile | null): profile is PrivateProfile { + return ( + profile !== null && + !person.deletedAt && + typeof person.slackSamlNameId === 'string' && + person.slackSamlNameId.length > 0 && + !isAgentAccount(this.#state, person.slug) + ); + } + + /** Both facts agree, and the user is a full, active, human member of this workspace. */ + #matches(person: Person, user: SlackDirectoryUser | null): user is SlackDirectoryUser { + return ( + user !== null && + user.name === person.slackSamlNameId && + user.team_id === this.#teamId && + user.deleted !== true && + user.is_bot !== true && + user.id !== 'USLACKBOT' && + user.is_restricted !== true && + user.is_ultra_restricted !== true + ); + } + + /** Take one call from the site-wide budget (and the request's, if given). */ + #take(t: number, budget: AutoLinkBudget | undefined): boolean { + if (t < this.#backoffUntil) return false; + if (budget && budget.left <= 0) return false; + this.#calls = this.#calls.filter((at) => t - at < MINUTE); + if (this.#calls.length >= AUTO_LINK_CALLS_PER_MINUTE) return false; + this.#calls.push(t); + if (budget) budget.left -= 1; + return true; + } + + /** Ask Slack; null on not found, 'error' on failure (cached for the person). */ + async #lookup(personId: string, email: string, t: number): Promise<SlackDirectoryUser | null | 'error'> { + try { + return await this.#directory!.lookupUserByEmail(email); + } catch (err) { + if (err instanceof SlackRateLimitedError) { + this.#backoffUntil = Date.now() + err.retryAfterSeconds * 1000; + this.#log.warn({ retryAfter: err.retryAfterSeconds }, 'slack auto-link: rate limited by Slack'); + } else { + const slackError = (err as { slackError?: unknown }).slackError; + this.#log.warn({ personId, slackError: typeof slackError === 'string' ? slackError : 'unknown' }, 'slack auto-link: lookup failed'); + } + this.#results.set(personId, { kind: 'error', at: t }); + return 'error'; + } + } + + async #attempt(person: Person, budget: AutoLinkBudget | undefined, now: Date): Promise<AutoLinkOutcome> { + if (!this.enabled) return 'off'; + const t = now.getTime(); + const profile = await this.#privateStore.getProfile(person.id); + if (!this.#eligible(person, profile) || profile.slack || profile.slackAutoLinkOptOutAt) return 'skipped'; + if (this.#cached(person.id, t) || !this.#take(t, budget)) return 'skipped'; + + const user = await this.#lookup(person.id, profile.email, t); + if (user === 'error') return 'error'; + const teamId = this.#teamId!; + if (!this.#matches(person, user)) { + this.#results.set(person.id, { kind: 'no_match', at: t }); + return 'no_match'; + } + const holder = this.#privateStore.findPersonIdBySlackUser(teamId, user.id); + if (holder !== null && holder !== person.id) { + this.#results.set(person.id, { kind: 'no_match', at: t }); + return 'no_match'; + } + // Re-read: the profile may have changed while Slack answered. + const fresh = await this.#privateStore.getProfile(person.id); + if (!fresh || fresh.slack || fresh.slackAutoLinkOptOutAt || fresh.email !== profile.email) return 'skipped'; + const at = new Date().toISOString(); + await this.#privateStore.putProfile({ + ...fresh, + slack: { teamId, userId: user.id, linkedAt: at, via: 'auto', verifiedAt: at }, + updatedAt: at, + }); + this.#results.delete(person.id); + this.#log.info({ personId: person.id }, 'slack auto-link: linked'); + return 'linked'; + } + + async #reverify(person: Person, budget: AutoLinkBudget | undefined, now: Date): Promise<AutoLinkOutcome> { + const profile = await this.#privateStore.getProfile(person.id); + const link = profile?.slack; + if (!profile || !link || link.via !== 'auto') return 'skipped'; + if (!this.enabled || !this.#take(now.getTime(), budget)) return 'error'; + + const user = await this.#lookup(person.id, profile.email, now.getTime()); + if (user === 'error') return 'error'; + const still = + this.#eligible(person, profile) && this.#matches(person, user) && user.id === link.userId && link.teamId === this.#teamId; + const fresh = await this.#privateStore.getProfile(person.id); + const same = fresh?.slack && fresh.slack.userId === link.userId && fresh.slack.teamId === link.teamId && fresh.slack.via === 'auto'; + if (!fresh || !same) return 'skipped'; + const at = new Date().toISOString(); + if (still) { + await this.#privateStore.putProfile({ ...fresh, slack: { ...fresh.slack!, verifiedAt: at }, updatedAt: at }); + return 'verified'; + } + // No longer both facts: the link goes. Not an opt-out; a later match may link again. + await this.#privateStore.putProfile({ ...fresh, slack: null, updatedAt: at }); + this.#results.set(person.id, { kind: 'no_match', at: now.getTime() }); + this.#log.info({ personId: person.id }, 'slack auto-link: re-check no longer matches; link removed'); + return 'removed'; + } +} diff --git a/apps/api/src/services/slack-link.ts b/apps/api/src/services/slack-link.ts index b62e5bbf..7ed8b321 100644 --- a/apps/api/src/services/slack-link.ts +++ b/apps/api/src/services/slack-link.ts @@ -58,8 +58,12 @@ function hashCode(canonical: string): string { } /** What `GET /api/auth/me` reports to the person themselves: never the Slack user id. */ -export function slackStatus(profile: PrivateProfile | null): { linked: boolean; linkedAt: string | null } { - return profile?.slack ? { linked: true, linkedAt: profile.slack.linkedAt } : { linked: false, linkedAt: null }; +export function slackStatus( + profile: PrivateProfile | null, +): { linked: boolean; linkedAt: string | null; via: 'auto' | 'code' | null } { + return profile?.slack + ? { linked: true, linkedAt: profile.slack.linkedAt, via: profile.slack.via ?? 'code' } + : { linked: false, linkedAt: null, via: null }; } interface PendingCode { @@ -184,15 +188,26 @@ export class SlackLinkService { this.#void(person.id); const linkedAt = now.toISOString(); // A new link replaces any old one on this account (one Slack user per account). - await this.#privateStore.putProfile({ ...profile, slack: { teamId, userId, linkedAt }, updatedAt: linkedAt }); + // Reconnecting by code is on purpose: it clears any opt-out of the automatic link. + await this.#privateStore.putProfile({ + ...profile, + slack: { teamId, userId, linkedAt, via: 'code', verifiedAt: linkedAt }, + slackAutoLinkOptOutAt: null, + updatedAt: linkedAt, + }); return { personSlug: person.slug, linkedAt }; } - /** DELETE /api/account/slack-link — clear the caller's link; nothing to do if there is none. */ + /** + * DELETE /api/account/slack-link — clear the caller's link and record the + * opt-out, so the automatic link never re-links them (slack-link.md → Opt-out). + */ async unlink(person: Person, now: Date = new Date()): Promise<void> { const profile = await this.#privateStore.getProfile(person.id); - if (!profile?.slack) return; - await this.#privateStore.putProfile({ ...profile, slack: null, updatedAt: now.toISOString() }); + if (!profile) return; + if (!profile.slack && profile.slackAutoLinkOptOutAt) return; + const at = now.toISOString(); + await this.#privateStore.putProfile({ ...profile, slack: null, slackAutoLinkOptOutAt: at, updatedAt: at }); } /** Drop a person's live code. */ diff --git a/apps/api/src/store/private/base.ts b/apps/api/src/store/private/base.ts index a165949e..6c8df5be 100644 --- a/apps/api/src/store/private/base.ts +++ b/apps/api/src/store/private/base.ts @@ -110,6 +110,10 @@ export abstract class BasePrivateStore implements PrivateStore { return this.profiles.get(personId) ?? null; } + peekProfile(personId: string): PrivateProfile | null { + return this.profiles.get(personId) ?? null; + } + async putProfile(profile: PrivateProfile): Promise<void> { const parsed = PrivateProfileSchema.parse(profile); this.profiles.set(parsed.personId, parsed); diff --git a/apps/api/src/store/private/interface.ts b/apps/api/src/store/private/interface.ts index 1bc4b7f3..368df94e 100644 --- a/apps/api/src/store/private/interface.ts +++ b/apps/api/src/store/private/interface.ts @@ -56,6 +56,8 @@ export interface PrivateStore { // --- Profiles --- getProfile(personId: string): Promise<PrivateProfile | null>; + /** The in-memory profile, synchronously (for checks that run under the write lock). */ + peekProfile(personId: string): PrivateProfile | null; putProfile(profile: PrivateProfile): Promise<void>; deleteProfile(personId: string): Promise<void>; findPersonIdByEmail(email: string): Promise<string | null>; diff --git a/apps/api/tests/slack-auto-link.test.ts b/apps/api/tests/slack-auto-link.test.ts new file mode 100644 index 00000000..1d756f3e --- /dev/null +++ b/apps/api/tests/slack-auto-link.test.ts @@ -0,0 +1,325 @@ +/** + * The automatic Slack link (plans/slack-account-link.md, reopened; + * specs/api/slack-link.md → Automatic link): email and handle must both + * agree, guests, bots, deleted users and other workspaces never link, no + * token means no attempt, Slack failures fail closed without failing the + * request, the opt-out holds, re-verification removes a stale link and + * refuses a decision, and the email never reaches a log or a response. + * A fake directory stands in for Slack; nothing here touches the network. + * + * Every person, workspace and Slack id here is invented; addresses are example.org. + */ +import { Writable } from 'node:stream'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { + FetchSlackDirectory, + SlackApiError, + SlackRateLimitedError, + type SlackDirectory, + type SlackDirectoryUser, +} from '../src/slack/directory.js'; +import { FEED_ATTEMPTS_PER_REQUEST } from '../src/services/slack-auto-link.js'; +import { + bearer, + createAgent, + daysAgo, + fid, + minutesAgo, + personRecord, + privateProfile, + startAgentTestEnv, + type AgentTestEnv, + type Rec, +} from './helpers/agent-fixtures.js'; + +const TEAM = 'TEXAMPLE01'; +const P = { + ada: 1, ben: 2, cal: 3, gina: 4, bot: 5, dee: 6, wes: 7, olly: 8, root: 9, cara: 10, + a1: 21, a2: 22, a3: 23, a4: 24, a5: 25, a6: 26, a7: 27, +}; +const T = '2026-05-01T00:00:00.000Z'; +const email = (slug: string) => `${slug}@example.org`; +const user = (id: string, name: string, over: Partial<SlackDirectoryUser> = {}): SlackDirectoryUser => ({ + id, name, team_id: TEAM, deleted: false, is_bot: false, is_restricted: false, is_ultra_restricted: false, ...over, +}); + +class FakeDirectory implements SlackDirectory { + readonly users = new Map<string, SlackDirectoryUser>(); + calls = 0; + mode: 'ok' | 'error' | 'ratelimit' = 'ok'; + async lookupUserByEmail(address: string): Promise<SlackDirectoryUser | null> { + this.calls += 1; + if (this.mode === 'error') throw new SlackApiError('internal_error'); + if (this.mode === 'ratelimit') throw new SlackRateLimitedError(30); + return this.users.get(address) ?? null; + } +} + +function fixtureDirectory(): FakeDirectory { + const d = new FakeDirectory(); + d.users.set(email('ada'), user('UADA000001', 'ada')); + d.users.set(email('ben'), user('UBEN000001', 'benny')); // email matches, handle differs + d.users.set('someone-else@example.org', user('UCAL000001', 'cal')); // handle matches, not cal's email + d.users.set(email('gina'), user('UGINA00001', 'gina', { is_restricted: true })); + d.users.set(email('bot'), user('UBOT000001', 'bot', { is_bot: true })); + d.users.set(email('dee'), user('UDEE000001', 'dee', { deleted: true })); + d.users.set(email('wes'), user('UWES000001', 'wes', { team_id: 'TOTHER0001' })); + d.users.set(email('olly'), user('UOLLY00001', 'olly')); + for (let i = 1; i <= 7; i++) d.users.set(email(`a${i}`), user(`UA${i}00000${i}`, `a${i}`)); + return d; +} + +let n = 1000; +const rec = (project: string, person: string, state: 'applicant' | 'member', over: Rec = {}): Rec => ({ + id: fid(n++), projectSlug: project, personSlug: person, state, isAdmin: false, muted: false, followedAt: T, createdAt: T, updatedAt: T, + ...(state === 'member' ? { via: 'legacy', joinedAt: T } : {}), ...over, +}); +const RECENT = minutesAgo(90); +const openApp = (): Rec => ({ application: { status: 'open', roleIds: [], offer: 'Glad to help.', submittedAt: RECENT, visibleAt: RECENT, notifiedAt: RECENT } }); + +function records(): Record<string, Rec[]> { + n = 1000; + return { + people: Object.entries(P).map(([slug, k]) => + personRecord(k, slug, { slackSamlNameId: slug, ...(slug === 'root' ? { accountLevel: 'administrator' } : {}) }), + ), + projects: [ + { id: fid(50), slug: 'proj', title: 'Project Proj', stage: 'testing', featured: false, createdAt: T, updatedAt: T }, + { id: fid(51), slug: 'many', title: 'Many admins', stage: 'testing', featured: false, createdAt: T, updatedAt: T }, + ], + 'project-memberships': [ + rec('proj', 'ada', 'member', { isAdmin: true }), + rec('proj', 'cara', 'applicant', openApp()), + ...[1, 2, 3, 4, 5, 6, 7].map((i) => rec('many', `a${i}`, 'member', { isAdmin: true })), + rec('many', 'ben', 'applicant', openApp()), + ], + }; +} +const PROFILES = Object.entries(P).map(([slug, k]) => + privateProfile(fid(k), email(slug), slug === 'olly' ? { slackAutoLinkOptOutAt: T } : {}), +); + +describe('automatic Slack link', () => { + let env: AgentTestEnv; + let dir: FakeDirectory; + let logs: string[]; + const bodies: string[] = []; + + beforeEach(async () => { + logs = []; + const stream = new Writable({ + write(chunk: Buffer, _e, cb) { + logs.push(chunk.toString('utf8')); + cb(); + }, + }); + env = await startAgentTestEnv({ records: records(), profiles: PROFILES, env: { SLACK_TEAM_ID: TEAM }, logger: { level: 'trace', stream } }); + dir = fixtureDirectory(); + env.app.services.slackAutoLink.useDirectory(dir); + }); + afterEach(async () => { + // The email never reaches a log line or a response, whatever the test did. + const all = logs.join('') + bodies.join(''); + for (const slug of Object.keys(P)) expect(all).not.toContain(email(slug)); + bodies.length = 0; + await env.close(); + }); + + const me = async (k: number) => { + const res = await env.app.inject({ method: 'GET', url: '/api/auth/me', cookies: { cfp_session: await env.cookie(k, 'user') } }); + expect(res.statusCode).toBe(200); + bodies.push(res.body); + return res.json<{ data: { slack: { linked: boolean; via: string | null } } }>().data.slack; + }; + const profile = (k: number) => env.app.store.private.peekProfile(fid(k)); + + it('links when the email lookup finds a user whose handle equals slackSamlNameId', async () => { + expect(await me(P.ada)).toMatchObject({ linked: true, via: 'auto' }); + expect(profile(P.ada)?.slack).toMatchObject({ teamId: TEAM, userId: 'UADA000001', via: 'auto' }); + expect(profile(P.ada)?.slack?.verifiedAt).toBeDefined(); + expect(env.app.store.private.findPersonIdBySlackUser(TEAM, 'UADA000001')).toBe(fid(P.ada)); + expect(bodies.join('')).not.toContain('UADA000001'); + }); + + it('does not link on one fact alone, nor a guest, a bot, a deleted user or another workspace', async () => { + for (const k of [P.ben, P.cal, P.gina, P.bot, P.dee, P.wes]) { + expect(await me(k)).toMatchObject({ linked: false }); + expect(profile(k)?.slack ?? null).toBeNull(); + } + expect(dir.calls).toBe(6); + // A no-match is cached: asking again does not call Slack. + await me(P.ben); + expect(dir.calls).toBe(6); + }); + + it('with no token configured, never asks Slack', async () => { + env.app.services.slackAutoLink.useDirectory(null); + expect(await me(P.ada)).toMatchObject({ linked: false }); + expect(dir.calls).toBe(0); + }); + + it('a Slack error or a rate limit fails closed without failing the request', async () => { + dir.mode = 'error'; + expect(await me(P.ada)).toMatchObject({ linked: false }); + expect(dir.calls).toBe(1); + await me(P.ada); // the error is cached for a while + expect(dir.calls).toBe(1); + + dir.mode = 'ratelimit'; + expect(await me(P.a1)).toMatchObject({ linked: false }); + expect(dir.calls).toBe(2); + // Backing off: nobody else's lookup goes out until Retry-After passes. + dir.mode = 'ok'; + expect(await me(P.a2)).toMatchObject({ linked: false }); + expect(dir.calls).toBe(2); + }); + + it('respects the opt-out: a disconnected member is not re-linked, and can reconnect by code', async () => { + expect(await me(P.olly)).toMatchObject({ linked: false }); + expect(dir.calls).toBe(0); + + expect(await me(P.ada)).toMatchObject({ linked: true, via: 'auto' }); + const del = await env.app.inject({ method: 'DELETE', url: '/api/account/slack-link', cookies: { cfp_session: await env.cookie(P.ada, 'user') } }); + expect(del.statusCode).toBe(204); + expect(profile(P.ada)?.slackAutoLinkOptOutAt).toBeTruthy(); + const calls = dir.calls; + expect(await me(P.ada)).toMatchObject({ linked: false }); + expect(dir.calls).toBe(calls); + // The SAML sign-in trigger honours it too. + env.app.services.slackAutoLink.scheduleAfterSignIn(fid(P.ada), 5); + await new Promise((r) => setTimeout(r, 50)); + expect(profile(P.ada)?.slack ?? null).toBeNull(); + + // Reconnecting on purpose, by code, clears the opt-out. + const agent = await createAgent(env, await env.cookie(P.root, 'administrator'), { slug: 'example-bot', scopes: ['slack:link'] }); + const code = (await env.app.inject({ method: 'POST', url: '/api/account/slack-link/code', cookies: { cfp_session: await env.cookie(P.ada, 'user') } })).json<{ data: { code: string } }>().data.code; + const redeem = await env.app.inject({ method: 'POST', url: '/api/agent/slack-links', ...bearer(agent.token), payload: { code, slackTeamId: TEAM, slackUserId: 'UADA000001' } }); + expect(redeem.statusCode, redeem.body).toBe(200); + expect(profile(P.ada)?.slack).toMatchObject({ via: 'code' }); + expect(profile(P.ada)?.slackAutoLinkOptOutAt ?? null).toBeNull(); + expect(await me(P.ada)).toMatchObject({ linked: true, via: 'code' }); + }); + + it('a Slack SAML sign-in schedules a check that links', async () => { + env.app.services.slackAutoLink.scheduleAfterSignIn(fid(P.ada), 5); + await new Promise((r) => setTimeout(r, 50)); + expect(profile(P.ada)?.slack).toMatchObject({ userId: 'UADA000001', via: 'auto' }); + }); + + describe('the feed', () => { + let token: string; + beforeEach(async () => { + token = (await createAgent(env, await env.cookie(P.root, 'administrator'), { slug: 'feed-bot', scopes: ['projects:applications:read'] })).token; + }); + const feed = async () => { + const res = await env.app.inject({ method: 'GET', url: '/api/agent/events', ...bearer(token) }); + expect(res.statusCode).toBe(200); + bodies.push(res.body); + return res.json<{ data: Array<{ project: { slug: string }; admins: Array<{ slug: string; slackUserId: string | null }> }> }>().data; + }; + + it('links admins it needs, at most a few per request', async () => { + const first = await feed(); + expect(first.find((e) => e.project.slug === 'proj')!.admins).toEqual([{ slug: 'ada', fullName: 'Test ada', slackUserId: 'UADA000001' }]); + const many = first.find((e) => e.project.slug === 'many')!.admins; + expect(dir.calls).toBe(FEED_ATTEMPTS_PER_REQUEST); + expect(many.filter((a) => a.slackUserId !== null)).toHaveLength(FEED_ATTEMPTS_PER_REQUEST - 1); + // The next request picks up the rest. + const second = await feed(); + expect(second.find((e) => e.project.slug === 'many')!.admins.every((a) => a.slackUserId !== null)).toBe(true); + }); + + it('stops carrying an automatic link unverified for 7 days when Slack cannot re-check it', async () => { + await me(P.ada); + const p = profile(P.ada)!; + await env.app.store.private.putProfile({ ...p, slack: { ...p.slack!, verifiedAt: daysAgo(8) } }); + dir.mode = 'error'; + expect((await feed()).find((e) => e.project.slug === 'proj')!.admins[0]!.slackUserId).toBeNull(); + expect(profile(P.ada)?.slack).toBeTruthy(); // kept, just not used + }); + }); + + describe('re-verification before an on-behalf decision', () => { + let token: string; + beforeEach(async () => { + token = (await createAgent(env, await env.cookie(P.root, 'administrator'), { + slug: 'decide-bot', scopes: ['slack:link', 'projects:applications:read', 'projects:applications:decide'], + })).token; + expect(await me(P.ada)).toMatchObject({ linked: true, via: 'auto' }); + }); + const age = async (days: number) => { + const p = profile(P.ada)!; + await env.app.store.private.putProfile({ ...p, slack: { ...p.slack!, verifiedAt: daysAgo(days) } }); + }; + const decide = async () => { + const res = await env.app.inject({ + method: 'POST', url: '/api/agent/applications/proj/cara/decision', ...bearer(token), + payload: { decision: 'accept', onBehalfOf: { slackTeamId: TEAM, slackUserId: 'UADA000001' } }, + }); + bodies.push(res.body); + return res; + }; + + it('a fresh automatic link decides without asking Slack', async () => { + const calls = dir.calls; + expect((await decide()).statusCode).toBe(200); + expect(dir.calls).toBe(calls); + }); + + it('an old link that still matches is re-verified, then decides', async () => { + await age(2); + const res = await decide(); + expect(res.statusCode, res.body).toBe(200); + expect(Date.parse(profile(P.ada)!.slack!.verifiedAt!)).toBeGreaterThan(Date.now() - 60_000); + }); + + it('an old link that no longer matches is removed and the decision refused not_project_admin', async () => { + await age(2); + dir.users.set(email('ada'), user('UADA000001', 'ada-renamed')); + const res = await decide(); + expect(res.statusCode).toBe(403); + expect(res.json<{ error: { code: string } }>().error.code).toBe('not_project_admin'); + expect(profile(P.ada)?.slack ?? null).toBeNull(); + expect(env.app.store.private.findPersonIdBySlackUser(TEAM, 'UADA000001')).toBeNull(); + }); + + it('an old link Slack cannot re-check is refused, and kept', async () => { + await age(2); + dir.mode = 'error'; + const res = await decide(); + expect(res.statusCode).toBe(403); + expect(res.json<{ error: { code: string } }>().error.code).toBe('not_project_admin'); + expect(profile(P.ada)?.slack).toBeTruthy(); + }); + }); +}); + +describe('FetchSlackDirectory', () => { + const respond = (status: number, body: unknown, headers: Record<string, string> = {}) => + (async () => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', ...headers } })) as unknown as typeof fetch; + + it('posts the email with the token and returns the user', async () => { + let seen: { url: string; init: RequestInit } | null = null; + const fake = (async (url: string, init: RequestInit) => { + seen = { url, init }; + return new Response(JSON.stringify({ ok: true, user: { id: 'UX', name: 'x' } }), { status: 200 }); + }) as unknown as typeof fetch; + const d = new FetchSlackDirectory('xoxb-test', fake); + expect(await d.lookupUserByEmail('x@example.org')).toEqual({ id: 'UX', name: 'x' }); + expect(seen!.url).toBe('https://slack.com/api/users.lookupByEmail'); + expect((seen!.init.headers as Record<string, string>).authorization).toBe('Bearer xoxb-test'); + expect(String(seen!.init.body)).toBe('email=x%40example.org'); + }); + + it('maps users_not_found to null, 429 and ratelimited to SlackRateLimitedError, anything else to SlackApiError', async () => { + expect(await new FetchSlackDirectory('xoxb-t', respond(200, { ok: false, error: 'users_not_found' })).lookupUserByEmail('a@example.org')).toBeNull(); + await expect(new FetchSlackDirectory('xoxb-t', respond(429, {}, { 'retry-after': '12' })).lookupUserByEmail('a@example.org')).rejects.toMatchObject({ retryAfterSeconds: 12 }); + await expect(new FetchSlackDirectory('xoxb-t', respond(200, { ok: false, error: 'ratelimited' })).lookupUserByEmail('a@example.org')).rejects.toBeInstanceOf(SlackRateLimitedError); + const err = await new FetchSlackDirectory('xoxb-t', respond(200, { ok: false, error: 'invalid_auth' })).lookupUserByEmail('a@example.org').catch((e: unknown) => e); + expect(err).toBeInstanceOf(SlackApiError); + expect(String((err as Error).message)).not.toContain('a@example.org'); + await expect(new FetchSlackDirectory('xoxb-t', respond(500, {})).lookupUserByEmail('a@example.org')).rejects.toBeInstanceOf(SlackApiError); + }); +}); diff --git a/apps/api/tests/slack-link.test.ts b/apps/api/tests/slack-link.test.ts index c022c2ec..073a349c 100644 --- a/apps/api/tests/slack-link.test.ts +++ b/apps/api/tests/slack-link.test.ts @@ -141,7 +141,7 @@ describe('slack account link', () => { it('links the issuer once; reused, unknown and expired codes all answer the same 404 code_invalid', async () => { await start(); const token = await agentWith(['slack:link']); - expect((await me(P.ada)).slack).toEqual({ linked: false, linkedAt: null }); + expect((await me(P.ada)).slack).toEqual({ linked: false, linkedAt: null, via: null }); const { code } = await codeFor(P.ada); const ok = await redeem(token, { code: code.toLowerCase().replace('-', ''), slackTeamId: TEAM, slackUserId: U_ADA }); @@ -193,7 +193,7 @@ describe('slack account link', () => { const del = await env.app.inject({ method: 'DELETE', url: '/api/account/slack-link', ...(await as(P.ada)) }); expect(del.statusCode).toBe(204); - expect((await me(P.ada)).slack).toEqual({ linked: false, linkedAt: null }); + expect((await me(P.ada)).slack).toEqual({ linked: false, linkedAt: null, via: null }); expect(env.app.store.private.findPersonIdBySlackUser(TEAM, U_ADA)).toBeNull(); // Disconnecting again is not an error. expect((await env.app.inject({ method: 'DELETE', url: '/api/account/slack-link', ...(await as(P.ada)) })).statusCode).toBe(204); From fb6977d861e831a025cfaa3d3b9f596278f3f86b Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:04:56 +0000 Subject: [PATCH 75/78] feat(web): the Slack row says whether the link was matched automatically or made by code Disconnect's confirm says the site will not reconnect by itself. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/web/src/components/account/SlackRow.tsx | 17 +++++++++++++---- apps/web/src/hooks/useAuth.tsx | 2 ++ apps/web/tests/Account.test.tsx | 8 ++++---- 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/apps/web/src/components/account/SlackRow.tsx b/apps/web/src/components/account/SlackRow.tsx index 3a2d6f25..5cd311a1 100644 --- a/apps/web/src/components/account/SlackRow.tsx +++ b/apps/web/src/components/account/SlackRow.tsx @@ -5,7 +5,9 @@ * Not linked: "Connect Slack" asks for a one-time code and shows it with the * instruction to DM it to the ops bot within ten minutes; while the code is * live the row polls `GET /api/auth/me` and turns linked when the bot - * confirms it. Linked: "Connected to Slack ✓ since …" with Disconnect. + * confirms it. Linked: "Connected to Slack ✓ since …", saying whether the + * site matched it automatically or it was made by code, with Disconnect + * (after which the site does not reconnect it by itself). * The row never shows the Slack user id (the API never sends it here). */ import { useEffect, useState } from 'react'; @@ -66,11 +68,16 @@ export function SlackRow({ initial }: { initial: SlackLinkStatus | null }) { }; const disconnect = async () => { - if (!window.confirm('Disconnect your Slack account? The ops bot will stop reaching you in Slack.')) return; + if ( + !window.confirm( + 'Disconnect your Slack account? The ops bot will stop reaching you in Slack, and the site will not reconnect it by itself. You can reconnect with Connect Slack.', + ) + ) + return; setBusy(true); try { await api.slackLink.disconnect(); - setStatus({ linked: false, linkedAt: null }); + setStatus({ linked: false, linkedAt: null, via: null }); toast.success('Slack disconnected.'); } catch (err) { toast.error(err instanceof ApiError ? err.message : 'Could not disconnect'); @@ -94,7 +101,9 @@ export function SlackRow({ initial }: { initial: SlackLinkStatus | null }) { <div className="font-medium">Slack</div> <div className="text-xs text-muted-foreground"> {status.linked - ? `Connected to Slack ✓${status.linkedAt ? ` since ${formatAbsoluteDate(status.linkedAt)}` : ''}` + ? `Connected to Slack ✓${status.linkedAt ? ` since ${formatAbsoluteDate(status.linkedAt)}` : ''}${ + status.via === 'auto' ? ' (matched automatically)' : status.via === 'code' ? ' (by code)' : '' + }` : 'Not linked to a Slack account'} </div> </div> diff --git a/apps/web/src/hooks/useAuth.tsx b/apps/web/src/hooks/useAuth.tsx index c3f2d01e..1a548fd6 100644 --- a/apps/web/src/hooks/useAuth.tsx +++ b/apps/web/src/hooks/useAuth.tsx @@ -27,6 +27,8 @@ export interface AuthPerson { export interface SlackLinkStatus { linked: boolean; linkedAt: string | null; + /** How the link was made: matched automatically, or by a code sent to the bot. */ + via?: 'auto' | 'code' | null; } export interface AuthState { diff --git a/apps/web/tests/Account.test.tsx b/apps/web/tests/Account.test.tsx index c35c0287..205cee73 100644 --- a/apps/web/tests/Account.test.tsx +++ b/apps/web/tests/Account.test.tsx @@ -177,7 +177,7 @@ describe('Account — Slack row', () => { if (input.startsWith('/api/auth/me')) { if (issued) polls += 1; const linked = issued && pollsUntilLinked !== null && polls > pollsUntilLinked; - return json(mockOk({ ...githubPerson, slack: linked ? { linked: true, linkedAt: '2026-11-20T12:00:00Z' } : { linked: false, linkedAt: null } })); + return json(mockOk({ ...githubPerson, slack: linked ? { linked: true, linkedAt: '2026-11-20T12:00:00Z', via: 'code' } : { linked: false, linkedAt: null, via: null } })); } if (input.startsWith('/api/account/slack-link/code')) { issued = true; @@ -198,7 +198,7 @@ describe('Account — Slack row', () => { expect(await screen.findByTestId('slack-link-code')).toHaveTextContent('K7QW-4MZP'); expect(screen.getByText(/within 10 minutes/i)).toBeInTheDocument(); expect(screen.getByRole('link', { name: /the ops bot/i })).toHaveAttribute('href', CODE.botDmUrl); - await waitFor(() => expect(screen.getByText(/connected to slack ✓ since/i)).toBeInTheDocument(), { timeout: 5000 }); + await waitFor(() => expect(screen.getByText(/connected to slack ✓ since .* \(by code\)/i)).toBeInTheDocument(), { timeout: 5000 }); expect(screen.queryByTestId('slack-link-code')).not.toBeInTheDocument(); expect(calls).toContain('POST /api/account/slack-link/code'); }); @@ -206,12 +206,12 @@ describe('Account — Slack row', () => { it('a linked account shows Connected with Disconnect, and never a Slack user id', async () => { vi.spyOn(globalThis, 'fetch').mockImplementation(((input: string) => { const body = input.startsWith('/api/auth/me') - ? mockOk({ ...githubPerson, slack: { linked: true, linkedAt: '2026-11-20T12:00:00Z' } }) + ? mockOk({ ...githubPerson, slack: { linked: true, linkedAt: '2026-11-20T12:00:00Z', via: 'auto' } }) : mockOk([]); return Promise.resolve(new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } })); }) as typeof fetch); render(); - expect(await screen.findByText(/connected to slack ✓ since/i)).toBeInTheDocument(); + expect(await screen.findByText(/connected to slack ✓ since .* \(matched automatically\)/i)).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Disconnect' })).toBeInTheDocument(); expect(screen.getByText(/act on your replies/i)).toBeInTheDocument(); expect(document.body.textContent).not.toMatch(/\bU[A-Z0-9]{6,}\b/); From 7c04803a183ac42a7ac73cdf10537691a9bf8f11 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:04:56 +0000 Subject: [PATCH 76/78] docs(ops): SLACK_BOT_TOKEN, the site's read-only Slack token Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .env.example | 4 ++++ docs/operations/deploy.md | 1 + docs/operations/secrets.md | 18 ++++++++++++++++++ 3 files changed, 23 insertions(+) diff --git a/.env.example b/.env.example index 72715d83..30576762 100644 --- a/.env.example +++ b/.env.example @@ -85,6 +85,10 @@ CFP_JWT_SIGNING_KEY=change-me-to-a-random-string-at-least-32-chars # be made. See specs/api/slack-link.md. # SLACK_TEAM_ID=TEXAMPLE01 +# Optional: the site's own read-only Slack token (scopes users:read, +# users:read.email) for the automatic Slack link. Unset → link by code only. +# SLACK_BOT_TOKEN=xoxb-... + # Optional: a link that opens a DM with the ops bot, shown on /account. # SLACK_OPS_BOT_DM_URL=https://codeforphilly.slack.com/app_redirect?channel=U... diff --git a/docs/operations/deploy.md b/docs/operations/deploy.md index bf3f4219..4530e476 100644 --- a/docs/operations/deploy.md +++ b/docs/operations/deploy.md @@ -288,6 +288,7 @@ comments. Production pod gets these mounted: | `SAML_PRIVATE_KEY` / `SAML_CERTIFICATE` | **Secret** (`codeforphilly-saml`, prod) | Slack IdP key pair, carried over verbatim from laddr's `saml2` secret so Slack keeps trusting the same cert. Mounted via an extra `envFrom` patch in the live cluster repo; marked `optional` so a sandbox without it still boots. | | `SLACK_TEAM_HOST` | ConfigMap | Slack workspace host (default `codeforphilly.slack.com`). ACS URL, NameID `NameQualifier`, `/chat` + `/launch` redirect target. Never our own IdP identity. | | `SLACK_TEAM_ID` | ConfigMap | The workspace id (`T…`) of the Code for Philly Slack. Required for [Slack account links](../../specs/api/slack-link.md) and agent decisions on an admin's behalf; unset, every link redemption is refused (fails closed). Not a secret. | +| `SLACK_BOT_TOKEN` | **Secret** (`codeforphilly-secrets`) | Optional. The site's own read-only Slack token (scopes `users:read`, `users:read.email`) for the [automatic Slack link](../../specs/api/slack-link.md#automatic-link). Unset, members link by code only. See [secrets.md](secrets.md#slack_bot_token). | | `SLACK_OPS_BOT_DM_URL` | ConfigMap | Optional. A link that opens a DM with the ops bot (e.g. `https://codeforphilly.slack.com/app_redirect?channel=<bot user id>`); the Account screen's Slack row links the bot's name to it. | | `GIT_SSH_COMMAND` | ConfigMap | Wires `ssh` to the mounted deploy key | | `GIT_AUTHOR_NAME` / `GIT_AUTHOR_EMAIL` | ConfigMap | Committer identity for API-authored data commits | diff --git a/docs/operations/secrets.md b/docs/operations/secrets.md index a614b099..ae610bdc 100644 --- a/docs/operations/secrets.md +++ b/docs/operations/secrets.md @@ -191,6 +191,24 @@ for local dev but means real users get no outbound mail in production. merge → `kubectl rollout restart` → delete the old token in Postmark. - **Cadence:** every 12 months, plus immediately on suspected leak. +### `SLACK_BOT_TOKEN` + +The site's own read-only Slack bot token (`xoxb-…`), used only for the +[automatic Slack link](../../specs/api/slack-link.md#automatic-link): it +calls `users.lookupByEmail` for one member at a time. Optional: unset, the +automatic link is off and members link by code. Needs `SLACK_TEAM_ID` too. + +- **Generate:** a Slack app in the Code for Philly workspace, owned by the + site (not the ops bot's app), with bot scopes **`users:read`** and + **`users:read.email`** and nothing else; a workspace admin installs it and + copies the Bot User OAuth Token. +- **Rotation impact:** none; the next lookup uses the new token. While it is + missing or invalid, lookups fail closed (no links made, decisions on stale + automatic links refused). +- **Rotation procedure:** reinstall or regenerate in the app's OAuth page → + `--merge-into` → merge → `kubectl rollout restart`. +- **Cadence:** on suspected leak, or when an admin who installed it leaves. + ### Data-repo deploy key SSH ed25519 private key with **write** access to the `codeforphilly-data` From b8ee18d69a3900918f94dbf96be5554860f9d3ec Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:15:46 +0000 Subject: [PATCH 77/78] chore(plans): mark slack-account-link done again, with the automatic link (PR #270) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- plans/slack-account-link.md | 53 ++++++++++++++++++++++++++++++++++--- 1 file changed, 49 insertions(+), 4 deletions(-) diff --git a/plans/slack-account-link.md b/plans/slack-account-link.md index aa87ea3e..f1e1eb1c 100644 --- a/plans/slack-account-link.md +++ b/plans/slack-account-link.md @@ -1,5 +1,5 @@ --- -status: in-progress +status: done depends: [] specs: - specs/api/slack-link.md @@ -82,9 +82,9 @@ punctuation-normalised handle matching. - [ ] `agent-grants/v2` adopted and mirrored; CI passes - [x] Browser: Account → Connect Slack shows a code; redeeming it with a test grant via the API turns the row to "Connected" - [ ] End to end with the ops bot in the real workspace (awaits the bot PR) -- [ ] Tests (automatic): both matches link (`via: auto`); an email match with a different handle, a handle match with a different email, a guest, a bot, a deleted user and another workspace do not; no token → no attempt -- [ ] Tests (automatic): a Slack error or rate limit fails closed without failing the request that triggered it; a member who disconnected is not re-linked automatically and can reconnect by code -- [ ] Tests (automatic): a re-check that no longer matches removes the link and the on-behalf decision is refused `not_project_admin`; the email never appears in logs or responses +- [x] Tests (automatic): both matches link (`via: auto`); an email match with a different handle, a handle match with a different email, a guest, a bot, a deleted user and another workspace do not; no token → no attempt +- [x] Tests (automatic): a Slack error or rate limit fails closed without failing the request that triggered it; a member who disconnected is not re-linked automatically and can reconnect by code +- [x] Tests (automatic): a re-check that no longer matches removes the link and the on-behalf decision is refused `not_project_admin`; the email never appears in logs or responses - [x] `npm run type-check && npm run lint && npm test` clean ## Risks / unknowns @@ -94,6 +94,47 @@ punctuation-normalised handle matching. ## Notes +- **Reopened and closed again on PR #270 for the automatic link** + (operator-approved). Spec in `docs(specs): link Slack accounts + automatically…`; the earlier Notes below still describe the code path. +- **When it runs, and why.** At Slack SAML sign-in (the moment the site knows + the person is entering Slack; delayed a minute because a first sign-in + creates the Slack account only after Slack consumes the assertion, and it + clears a cached no-match); on `/me` (what the Account screen reads; waits + at most 1.5 s so a slow Slack never slows page loads, and only when + nothing is cached, so it is not a lookup per page view); when the feed + needs an admin's Slack id (the one consumer that needs it; at most 5 per + request). No sweep: the site never fans out across members. +- **Budget and cache** (in memory, reset on restart): 20 Slack calls a + minute site-wide, under `users.lookupByEmail`'s rate tier; a Slack 429 + stops all calls for its Retry-After; over-budget calls are skipped, not + queued. No-match cached 24 h, errors 15 min; one lookup per person at a time. +- **Re-verification ages.** An automatic link is re-checked when used past + 24 h, and always before an on-behalf decision (mismatch → link removed and + `403 not_project_admin`; Slack unavailable → refused the same way, link + kept; the decision service re-checks freshness under the write lock). The + feed keeps using a link it could not re-check for up to 7 days, then + carries `slackUserId: null` until a re-check succeeds. Code links are not + re-checked. +- **Exact matching only.** No case folding or punctuation normalising (the + coordinator measured 298 members who would match only if dots and + underscores were ignored). Widening that is a possible later change and + would need its own spec decision. +- **Opt-out.** Disconnect records `slackAutoLinkOptOutAt` even when there was + no link; a code link clears it. A re-check mismatch removes the link but + does not record an opt-out. +- **Not verified against real Slack.** Every test uses a fake directory; the + fetch client is tested against a fake `fetch`. Untested in the real + workspace: field values (`team_id` on an Enterprise Grid install, handle + spelling), the real rate tier, and whether members can change their + handle or email. +- The profile rewrites (GitHub email change, claim, claim merge, staff email + edit) carry the opt-out as well as the link. An email change does not drop + an automatic link at once; its next re-check uses the new email and + removes it if it no longer matches. +- Gate at this commit's tree: check-contracts, type-check, lint, tests + (API 71 files / 849, web 36 / 218, shared 5 / 120) and `npm run build` clean. + - **Two criteria open.** `agent-grants/v2` is generated, published in `contracts/` and mirrored into `apps/api/gitsheets/` (vendored with `gitsheets contracts adopt`; the sheet config declares v2), but adopting @@ -134,6 +175,10 @@ punctuation-normalised handle matching. ## Follow-ups +- Deploy: create the site's own Slack app with `users:read` and + `users:read.email`, install it, and set `SLACK_BOT_TOKEN` in the sealed + Secret; spot-check one automatic link on sandbox. + - codeforphilly-data: adopt `agent-grants/v2` on `empty`, `fixture`, `legacy-import`, then `published` at release (no migration: v2 only widens the scope enum). From a18bba4a509e2fd3c6b899ec084bd831f9d4c3a9 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:52:57 +0000 Subject: [PATCH 78/78] chore(api): sync sheet configs with codeforphilly-data agent-grants v2 adoption apps/api/gitsheets/ mirrors codeforphilly-data's empty branch after it adopts agent-grants/v2: sources.toml records the v2 provenance, and the v1 document no sheet declares any more goes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../codeforphilly.org/agent-grants/v1.toml | 46 ------------------- apps/api/gitsheets/contracts/sources.toml | 4 ++ 2 files changed, 4 insertions(+), 46 deletions(-) delete mode 100644 apps/api/gitsheets/contracts/codeforphilly.org/agent-grants/v1.toml diff --git a/apps/api/gitsheets/contracts/codeforphilly.org/agent-grants/v1.toml b/apps/api/gitsheets/contracts/codeforphilly.org/agent-grants/v1.toml deleted file mode 100644 index 6cc58e3d..00000000 --- a/apps/api/gitsheets/contracts/codeforphilly.org/agent-grants/v1.toml +++ /dev/null @@ -1,46 +0,0 @@ -"$id" = "https://codeforphilly.org/agent-grants/v1" -"$schema" = "http://json-schema.org/draft-07/schema#" -required = ["createdAt", "createdBySlug", "expiresAt", "id", "label", "personSlug", "scopes"] -title = "Agent grant" -type = "object" - -[properties.createdAt] -format = "date-time" -pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' -type = "string" - -[properties.createdBySlug] -minLength = 1 -type = "string" - -[properties.expiresAt] -format = "date-time" -pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' -type = "string" - -[properties.id] -format = "uuid" -pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" -type = "string" - -[properties.label] -maxLength = 80 -minLength = 1 -type = "string" - -[properties.personSlug] -minLength = 1 -type = "string" - -[properties.revokedAt] -format = "date-time" -pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' -type = "string" - -[properties.scopes] -minItems = 1 -type = "array" - -[properties.scopes.items] -enum = ["moderation:read", "moderation:vote", "moderation:purge"] -type = "string" diff --git a/apps/api/gitsheets/contracts/sources.toml b/apps/api/gitsheets/contracts/sources.toml index 4b46aeb3..cbf60435 100644 --- a/apps/api/gitsheets/contracts/sources.toml +++ b/apps/api/gitsheets/contracts/sources.toml @@ -2,6 +2,10 @@ adopted = 2026-11-12T19:53:17.251Z source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/71bf951824e93b7537025fcc1cd479cd88fb1331/contracts/codeforphilly.org/agent-grants/v1.json" +["codeforphilly.org/agent-grants/v2"] +adopted = 2026-11-30T00:52:16.731Z +source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/842bcb2c91140a1327c52ae85a55d40277404d04/contracts/codeforphilly.org/agent-grants/v2.json" + ["codeforphilly.org/blog-posts/v1"] adopted = 2026-10-14T03:31:18.13Z source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/7fe6b81a0bbd05b7a4e6896d55e181fdb61cfe42/contracts/codeforphilly.org/blog-posts/v1.json"