Request Service
70
API Endpoints
3
Service Deps
3
Infrastructure
3
DB Schemas
API Endpoints
/requestsGet all help requests with optional filters.
/requests/curated (v9.18 + ADR-048 Feed Ranking v2, amended by ADR-082)Get curated feed scored on **six** signals: skill match, trust DISTANCE (caller-relative degrees),
/requests/community/:communityId/pulse (Sprint 89 / ADR-068)The community's weekly help-loop **pulse** for the warm community Home hero ("This week in the
/requests/community/:communityId/open-asks (Sprint 100 / F2)The **reachable, read-only** list behind the pulse "N open asks across the community" row. Returns
/requests/curated?view=home — `offeredAwaiting` (Sprint 100 / G1)The home-feed response now carries `offeredAwaiting`: the count of open asks the member has **offered
/requests/offered-awaiting (Sprint 107 / BUG-023)Canonical read endpoint for the same offered-awaiting predicate. Returns up to 50 distinct open,
/requests/retention-policy (Sprint 90 / ADR-069)Backs the `/about/memory` transparency page. Returns the **resolved retention windows**
/requests/:id (Sprint 101 — canonical viewer-aware detail)Get specific request details. **Sprint 101** makes this the canonical action surface: the response
/requests (v9.0 Polymorphic + ADR-022 Visibility)Create new polymorphic help request (supports 5 types) with visibility scope.
/requests/:idUpdate help request (requester only).
/requests/:idCancel help request (requester only). The caller is the JWT user; no body. A body `user_id` is
/requests/:id/privacyUpdate privacy settings for a request (Social Karma v2.0).
/requests/:id/admin-triageOverride request urgency and/or add a community-scoped admin note (Sprint 25).
/requests/:id/boostBoost a request for 48 hours, adding a +0.3 feed score bonus via the request-service feed ranker (Sprint 36). Admin or moderator.
/requests/:id/boostRemove an active boost from a request (Sprint 36). Admin or moderator.
/requests/:id/propose-matchAdmin proposes a specific community member as a helper (Sprint 36). Creates a real `requests.matches` row with `status='proposed'`.
/requests/:id/urgentToggle request urgency between `urgent` and `medium` (Sprint 36). Admin only.
/offersGet the help offers the caller may read (their own, or their live communities' offers), with optional filters.
/offers/:idGet one offer the caller may read (their own, or a live community's); otherwise 404.
/offersCreate new help offer. The offerer is the JWT caller; a body `offerer_id` is ignored (BUG-061).
/offers/:idEdit an offer's `title` and `description` (offerer only; a body `status` is refused with `400 STATUS_NOT_EDITABLE`, Sprint 137, BUG-089).
/offers/:idWithdraw an offer (offerer only; foreign or missing id → `404 Offer not found`), setting `status = 'withdrawn'` and publishing `offer_withdrawn`.
/offers/:id/privacyUpdate privacy settings for an offer (Social Karma v2.0).
/matchesThe **caller's** matches: always restricted to matches where the JWT caller is the requester, the
/matches/:idMatch details (including requester/helper email) **for a participant only** (requester or
/matchesCreate a member's offer to help (a proposed match). The responder is the **verified JWT identity**
/matches/:id/acceptAccepts a proposed match (Sprint 135, BUG-075). Participant authorization is unchanged (JWT identity, ADR-064).
/matches/:id/rejectRejects or withdraws a proposed match; both participants may (Sprint 62). Sprint 135 (BUG-075, BUG-078): the request lock
/matches/:id/completeTwo-phase match completion. Each party calls this independently; the match
/matches/:idCancels an exchange in progress (Sprint 134 BUG-074).
/requests/:id/offersList pending provider offers on a specific help request. Requester only.
/requests/offers/:id/acceptAccept a pending provider offer. Creates a match between the requester and the provider.
/requests/offers/:id/declineDecline a pending provider offer.
/providers/offersSubmit a provider offer on an open help request.
/providers/offersList offers submitted by the authenticated provider.
/providers/offers/:id/withdrawWithdraw a pending provider offer.
/requests/:id/dibs-candidateReturns the top-scored dibs candidate for any request. Accepts optional `?type=` query param — `type=service` uses provider-profile candidates; any other value (or missing) uses mutual-aid candidates
/requests/:id/dibsSend dibs to a specific provider or community member. Valid for all request types (scheduled and ASAP).
/requests/dibs/:id/acceptProvider accepts dibs. Creates a `requests.matches` record directly and derives the request status (`matched`).
/requests/dibs/:id/declineProvider declines dibs. Derives the request status (`open` for public broadcast unless something else holds it; a
/requests/dibs/pending-for-providerReturns the authenticated provider's pending dibs records (status = `pending`).
/requests/dibs/:id/expireTEST-ONLY: Force-expire a dibs record regardless of `expires_at`. Sets status to `expired` (guarded on `pending`, as decline)
/requests/feedRanked personalized feed for the authenticated user. Items are sorted by the ranker's score
/requests/feed/preferencesReturn the caller's feed preferences; returns sensible defaults when no row exists.
/requests/feed/preferencesUpsert the caller's feed preferences (round-trips with GET).
/requests/feed/dismiss/:itemIdDismiss a feed item (writes `feed.dismissed_items`); the item is excluded from the next
/requests/feed/community-healthCommunity health hero metrics for the `CommunityHealthHero` component. Requires `community_id`
/providersList all provider profiles. Optional query param: `service_type`. **Public** (no auth required).
/providers/myGet the authenticated user's own provider profiles. Auth required.
/providers/:idGet a single provider profile by ID, including ride details if applicable.
/providersCreate a provider profile for the authenticated user.
/providers/:idUpdate a provider profile. Owner only.
/providers/:idDelete a provider profile. Owner only.
/collectivesList all provider collectives. Optional query param: service_type.
/collectives/myGet collectives the authenticated user belongs to (via their provider profiles). Auth required.
/collectives/:idGet a collective with members and communities served.
/collectivesCreate a new provider collective.
/collectives/:idUpdate a collective. Collective admin only.
/collectives/:idDelete a collective. Collective admin only.
/collectives/:id/membersJoin a collective as a member.
/collectives/:id/members/:providerIdRemove a member from a collective. Collective admin only.
/collectives/:id/communitiesLink a collective to a community.
/collectives/:id/communities/:communityIdUnlink a collective from a community. Auth: collective admin OR community admin (Sprint 26).
/collectives/:id/statsReturns aggregate performance stats for a collective: `total_requests_matched`, `fulfillment_rate`, `avg_completion_hours` (null if no completed matches), `communities_served_count`, `available_membe
/providers/:providerId/availabilityToggle a provider's availability status. Body: `{ is_available: boolean }`. Auth: owner only (provider_profiles.user_id must match JWT userId). Returns `{ id, is_available }`. (Sprint 26)
/requests/providers/:providerId/rate-cardsList active rate cards for a provider (public). Owner can pass `?include_inactive=true` to include deactivated cards.
/requests/providers/:providerId/rate-cardsCreate a new rate card for a provider. Auth: owner only. Body: `{ label, pricing_model, rate_amount?, rate_unit?, currency?, notes? }`.
/requests/providers/:providerId/rate-cards/:cardIdUpdate an existing rate card. Auth: owner only.
/requests/providers/:providerId/rate-cards/:cardIdSoft-delete a rate card — sets `is_active = false`. Auth: owner only. Card remains in database for historical reference.
/healthService health check.
Infrastructure
Service Dependencies
Publishes Events
Full Documentation
Request Service - Complete Context Documentation
Last Updated: 2026-06-30 Version: v10.12.0 Port: 3003 Status: Production (Polymorphic Request System + Curated Feed)
Recent Changes
-
2026-11-12 (Sprint 141, BUG-073 fixed on branch, ADR-105):
/admin/schemas(all 9 routes, the global request-type catalogrequests.ui_schemas) now admits a live platform admin only.- The mount is
platformAdminAuth = [verifyToken, requirePlatformAdmin](src/middleware/adminAuth.ts).requirePlatformAdminreadsisLivePlatformAdmin(src/db/liveRole.ts:SELECT 1 FROM auth.platform_admins WHERE user_id = $1 LIMIT 1; no user → false, no query). - A community admin, including any community's creator, gets 403
{ success: false, message: 'Platform admin access required', error: 'PLATFORM_ADMIN_REQUIRED' }. - The admin-actions mount (boost, propose-match, urgent) keeps the any-community prefilter, renamed
requireAnyCommunityAdmin/communityAdminAuth, with unchanged behavior andadminChainPathscoverage. - The old
requireAdmin/adminAuthexports are gone. - Tests:
tests/regression/sprint-141-platform-admin-gate.test.ts(all 9 routes derived from the router, both roles, exact SQL), the updated PR K suite, and the root PR K integration suite (both role directions, real schema).
- The mount is
-
2026-11-10 (Sprint 140, BUG-099 fixed on branch):
GET /offers?status=alllists every readable status. The offers page's "All" option used to send no status, which the route defaulted toactive. The page now sendsall. The route binds NULL for exactlyallbehind($1::text IS NULL OR o.status = $1), so the bind positions ($1status,$2viewer, optional filters from$3) do not move. The audience and the Sprint 139 expiry OR stay mandatory, and an omitted status is stillactive. The Sprint 138/139 SQL-pinning regressions now expect the null-aware predicate. Tests:tests/regression/sprint-140-offer-status-all.test.ts, roottests/integration/sprint-140-offer-status-all.integration.test.ts. -
2026-11-09 (Sprint 139, BUG-097):
GET /offersscopes expiry by status and ownership:AND (o.status <> 'active' OR o.offerer_id = $2 OR (o.expired IS NOT TRUE AND (o.expires_at IS NULL OR o.expires_at > NOW()))), inside the unchanged readable boundary. An owner sees their own expired offer; matched / withdrawn history keeps expired rows; other members still never see an expired active offer. List items gainexpires_atandexpired. Holds still refuse an expired offer. Tests:tests/regression/sprint-139-offer-visibility.test.ts(SQL/params), the rewritten Sprint 138 C case (whole WHERE grouping, mutation-proven), and roottests/integration/sprint-139-offer-visibility.integration.test.ts(real SQL). -
2026-11-09 (Sprint 139, BUG-082):
src/database/db.tslogs a successful query with the sharedcreateLogger('request-service')at debug (Executed query,{ text, duration, rows }, never params) instead of an unconditionalconsole.log. Silent at the defaultinfo;LOG_LEVEL=debugopts in. Errors andwithTransactionare unchanged. Policy: ADR-015 (amended). Test:tests/regression/sprint-139-query-logging.test.ts. -
2026-11-06 (Sprint 138, BUG-093..096): a standing offer is reusable. BUG-093: the final done mark in
PUT /matches/:id/complete(both participants done) callsreleaseOfferafter the request is reconciled (lock order match, request, offer, as cancel), freeing the offer the match used unless another proposed or matched exchange still uses it; a first mark frees nothing and a withdrawn offer stays withdrawn. The release rule in all four copies (releaseOffer,closeProposals, cleanup D1 and D2) is now: an offer is held only by aproposedormatchedmatch, so a completed match no longer holds it (retroactive: the first deployed cleanup sweep frees offers stuck behind past completions). BUG-094: every release setsexpired = TRUEin the same statement when the offer'sexpires_athas passed (no listing readexpiredbefore; the effect was onPOST /matches' fast path and the hard-delete clock). BUG-096:GET /offershides expired offers (flagged, orexpires_atpassed) for every status filter;GET /offers/:idis unchanged. BUG-095: partial indexidx_matches_offer_idonrequests.matches(offer_id) WHERE offer_id IS NOT NULL(migration20261106-matches-offer-id-index.sql) backs the release guards. A freed offer past its expiry follows the existing 7-day hard-delete clock; its completed matches keep their rows withoffer_id = NULL(FKON DELETE SET NULL). No event or dependency change. -
2026-11-04 (Sprint 137, BUG-090):
POST /providers/offerskeeps its provider-profile and reachability fast paths, then locks and re-checks the request withlockRequestForCommitmentbefore checking duplicates and inserting on the same transaction client. An ask that closed or expired since the fast path returns409 REQUEST_NOT_OPENwithout an insert; duplicates keep409 DUPLICATE_OFFER. The requester lookup andoffer_submittedrun after commit. No migration, event or dependency change. -
2026-11-04 (Sprint 137, BUG-089):
PUT /offers/:idrefuses a body status with400 STATUS_NOT_EDITABLEafter its ownership 404. Offer status follows exchanges;POST /matchesrefuses flagged-expired offers and holds only active offers withexpired IS NOT TRUEand no passedexpires_at, checked withclock_timestamp()in the guarded write. Reject and cancel callreleaseOfferafter updating their own match; it andcloseProposalsfree only matched offers with no remaining proposed or matched hold (excluding proposals being closed; a completed match stopped holding in Sprint 138, BUG-093). Shared offers stay held and withdrawn offers stay withdrawn. Each release also compares the target CTID with a distinct scalar self-scan under the statement snapshot: a concurrent version change, including a release/re-hold cycle, defers freeing to a later sweep. CTID is statement-local, never persisted identity (spec B5, I1). No migration, event or dependency change. -
2026-11-04 (Sprint 137, BUG-091):
PUT /requests/:idkeeps its ownership 404 and body-status 400 checks first, then locks the request and reads its derived status in one transaction. A completed or cancelled ask returns409 REQUEST_CLOSEDbefore any write; a missing request under the lock returns 404. The edit also requirescontent_forgotten_at IS NULL, with a zero-row edit returning the same 409 to preserve forgotten content. Open, matched and dibs-pending asks remain editable. No migration, event or dependency change. -
2026-11-03 (Sprint 136, BUG-085 + BUG-084): an expired ask takes no new commitment, and
POST /matcheswrites under the request lock. An ask is past expiry whenexpired IS TRUE(the sweep's flag) orexpires_at <= clock_timestamp()(the hour before the sweep runs).lockRequestForCommitment(src/db/requestStatus.ts) reads such an open ask as'expired'; admin propose-match, match accept, dibs create, provider-offer accept andPOST /matchescall it and refuse withREQUEST_NOT_OPEN(409 at the lock;POST /matcheskeeps its 400 fast path for a flagged ask). Cancel, reject and dibs accept still calllockRequest, so an expired ask can be closed. The stored status does not change.POST /matchesnow runs lock → duplicate check (exact, 409ALREADY_OFFERED) → guarded offer hold (... AND offerer_id = $2 AND status = 'active'; a miss is 400OFFER_NOT_ACTIVE, the newerrorcode on both of its offer refusals) → insert, in one transaction;match_createdpublishes after the commit. Tests:tests/regression/sprint-136-request-followups.test.ts, roottests/integration/sprint-136-request-followups.integration.test.ts. No migration, event or dependency change. -
2026-11-01 (Sprint 135, BUG-075 + BUG-078): a request's status follows its rows, and
src/db/requestStatus.tsis the only module that writes it (reconcileRequestStatus,markRequestCancelled), plus cleanup-service'sexpireDibs.tsrequest write. The derived status iscancelledif cancelled, elsematched(amatchedmatch), elsecompleted(acompletedmatch), elsedibs_pending(apendingdibs), elseopen.lockRequestlocks the request row and returns that derived status, which every precondition reads. The ten writers (plus the test-only/expire) now guard their rows and derive instead of overwrite:PUT /matches/:id/accept,/reject,/complete,POST /requests/:id/propose-match,POST /requests/:id/dibs,PUT /requests/dibs/:id/acceptand/decline,PUT /requests/offers/:id/accept(now one transaction),PUT /requests/:idandDELETE /requests/:id. BUG-074's already-guardedDELETE /matches/:idnow shares the helper. New codes: 409REQUEST_NOT_OPEN(a request that is not open refuses a new match, dibs or provider-offer accept), 409REQUEST_NOT_CANCELLABLEandREQUEST_HAS_ACTIVE_EXCHANGE(cancel), 400STATUS_NOT_EDITABLE(an edit cannot set a status).closeProposalsfrees a proposal's offer only while it ismatched, so a withdrawn offer stays withdrawn (BUG-078).done_atkeeps its first stamp (COALESCE). A late "mark done" on a cancelled request completes the exchange and leaves the request cancelled.request_completedis no longer published (its only publisher was the status edit; it is still inUNCONSUMED_EVENTS). Tests: the promoted contract filestests/regression/sprint-135-request-status-{helper,gate,writers}.test.ts(the gate fails on a request-status write outside the reviewed list), cleanup-service'stests/regression/sprint-135-expire-dibs-guard.test.ts, and the real-SQL roottests/integration/sprint-135-request-status-guards.integration.test.ts(CI-only on Windows). No migration, schema or dependency change from this fix. The 2026-10-29 demo rows are not repaired here. -
2026-10-29 (Sprint 134 BUG-074):
DELETE /matches/:idandPUT /matches/:id/completechange a match only while it ismatched. Anything else answers 409MATCH_NOT_CANCELLABLE/MATCH_NOT_COMPLETABLE(ADR-074 string codes). The guard is in the write (UPDATE ... WHERE id = $1 AND status = 'matched'), not in a prior read, so a completion or cancel that commits in between is seen by the row re-check. Cancel locks the match row first and the request row second, the same order as complete, so the two cannot deadlock. Cancel then updates the request only while it is stillmatchedand no other match on it ismatched(completedif another completed match remains, elseopen), and frees the offer only while it ismatched. Complete's race path (guardedUPDATEhits 0 rows, re-read sayscompleted) keeps the idempotent 200Match already completed, as the pre-read fast path does. Tests: the promoted mocked-SQL contracttests/regression/sprint-134-bug-074-match-status-guards.test.tsand the real-SQL status matrix and race proofs in the roottests/integration/sprint-134-bug-074-match-status-guards.integration.test.ts(CI-only on Windows). No migration, event or dependency change from this fix;match_cancelledis still published and still unconsumed. -
2026-10-28 (Sprint 134 PR B, ADR-100 amendment):
GET /requests/:idreturnsviewer_partners, the viewer's completed exchanges on the ask (match_id,user_id,name,completed_at,rated_by_me,rating_community_id), newest first, capped at 20,[]for everyone else. It is a scalar subquery inside the existingrequestReadableSql-guarded statement, filtered per exchange bystatus = 'completed'ANDmatchParticipantSql: read permission is not partner status, so a rejected helper, the preferred provider and a reading member get[].rated_by_mereadsfeedback.feedbackby the viewer, as the dashboard'sratedecision does; ratings stay private (ADR-036). The frontend request page renders a rate-and-vouch panel from it. No migration, event or dependency change. Mocked SQL-contract tests intests/regression/sprint-134-pr-b-viewer-partners.test.ts; the exposure matrix runs against real SQL in the roottests/integration/sprint-134-pr-b-viewer-partners.integration.test.ts(CI-only on Windows). -
2026-10-27 (Sprint 134 PR V): request update, cancellation and privacy writes look up and mutate by request id and verified JWT requester. Foreign, absent and concurrently removed rows return the same 404 before publishing events.
GET /requests/:idnow appliesrequestReadableSqldirectly in SQL; reachability is consulted only to derivecan_offerfor an open, unexpired non-owner without a live match. Historical responders and preferred providers retain read access without gaining offer eligibility.buildRequestsQueryfilters and pages a candidate CTE before joining names/aggregating communities; a community filter still narrows the returned community names/ids and notes. Onedb/liveRole.isActiveMember(communityId, userId)now serves inventory, requests, feed and providers, including malformed-id rejection and active membership with a null role. The reversed provider helper is removed. The composite match index is deferred pending query-plan measurements on representative data.PUT /offers/:id/privacynow accepts onlyofferer_visibility_consent: legacyis_public-only bodies return 400 for the owner; mixed bodies update consent only. The response and privacy event omitis_public. Foreign/missing offers still return the same 404 before body validation. Offer reads remain owner or live community member. The inert column stays until a later schema PR; PR V has no migration or init.sql change and needs no demo-host operation. Local route/query tests supplement the root real-SQL read-boundary, request-detail and provider matrices, which exercise the queries against PostgreSQL in CI. Real-SQL tests do not run locally on Windows. No query-speed improvement is claimed. -
2026-10-27 (Sprint 134 PR L2, BUG-070):
requests.interaction_feedbackis dropped after PR L retired its routes/event.SocialKarmaFeedComposerno longer reads the retired community-health averages; its existing total-match activity term is min(100, matches × 2). The maintainer's 2026-10-27 decision makesqualityWeightthe tunable value, clamped to [0,1], default 0:strength = (1-w) * (2*activity + density) / 3 + w*quality. At w=0 the remaining terms split the full weight 2:1; w=0.4 reproduces the historical 40/40/20 mix. Synthetic tests now use realistic snapshots. The unimported productionFeedComposerand its obsolete tests/allowlist entry are removed. Reputation's nightly/fallback SQL is repaired through request_communities in the same PR. Live private ratings remain in reputation-servicePOST /reputation/feedback. Density cap (maintainer follow-up): the feed usesmin(100, network_density × 100), matching reputation's density contribution. The repaired cron begins creating snapshots that previously did not exist, so the card can move from its empty zero state to a computed score. Density above 1 is normal for an all-time metric; with quality weight zero and both terms capped, strength reaches 100. Density12.0000with 50+ completed matches returns 100 / Thriving, keeping the /100 card and bar bounded. Regression:tests/regression/sprint-134-pr-l2-feed.test.ts(50 and 75 completed matches). 25 matches with density 0.5 returns 50 / Growing. Optional normalized quality score and weight arguments are internal; there is no HTTP override or new quality source. Per-community weight incommunities.community_configsis a separate planned PR requiring a maintainer-allocated ADR and quality signal design. The weighting correction changes no migration or generated schema. -
2026-10-22 (Sprint 134 PR L, BUG-068, ADR-101 amendment): the dead interaction-feedback routes
POST/GET /matches/:id/feedback(src/routes/feedback.ts) are removed, with their mount and their three directed-surface allowlist entries. POST always 500ed onhelp_requests.community_idand no client called either route; see section 3.4. request-service no longer publishesinteraction_feedback_submitted(retired from the routing table), and the legacykarmyq-eventshandlers in the consumers are gone.requests.interaction_feedbackand the feed composer's always-0 averages stay until PR L2. -
2026-10-16 (Sprint 133 PR V, BUG-065 + BUG-064):
GET /requestslists only whatGET /requests/:idwould open. The read boundary is one SQL fragment,requestReadableSql(alias, viewerParam)insrc/db/eligibility.ts, which wraps the directed-audience predicate around own ∨ any-status match responder ∨ pre-selected provider ∨ directed ∨requestReachableSql(live member ∨ active sister link ∨trust_network/platformscope).buildRequestsQueryANDs it on the browse branch and always binds the viewer, so a spoofedrequester_idstays browse.getRequestReachabilitybuilds its columns from the same helpers. The community feed view,/community/:id/pulse,/community/:id/open-asksand/retention-policy?communityIdcheckcommunities.members(isActiveMember), not the JWT claim (sameNOT_A_MEMBER403), and/requests/feed/community-health, which had no membership check at all, now requires the same. A malformed community id is a plain 403 (no 22P02 → 500). Standing offers (GET /offers,GET /offers/:id) are readable by the offerer and live members of the offer's community only (is_publicis not consulted).PUT/DELETE/PUT /privacy /offers/:idand thePOST /matchesoffer_idlookup select by id AND offerer, so a foreign offer gets the same 404 as a missing one (it used to get 403). -
2026-10-10 (Sprint 133 PR S, BUG-056 + BUG-062):
GET /requests/:idis now gated: readable by the requester, a responder on a match of any status, a directed ask's audience (thedirectedAudienceSqlpredicate is unchanged), or a viewer inside the request's visibility audience (getRequestReachability). Everyone else gets the same 404 as a missing id.requester_emailis gone from the response. The request's pre-selected provider (preferred_provider_id→ theirprovider_profiles.user_id) can also read it, becausepreferred_provider_selectedlinks them there.GET /requests?include_admin_notes=truenow joins admin notes only for a live admin/moderator ofcommunity_id(it was honored for any caller); the list's breadth is BUG-065.GET /offers/:idno longer returnshelper_email(no client read it). -
2026-10-05 (Sprint 132 PR C completion delivery correction, ADR-099):
match_completednow saves one Bull job inkarmyq-completion-dispatch. The request-service dispatcher fans out tokarmyq-completion-reputation,karmyq-completion-notificationandkarmyq-completion-social-graph; workers no longer compete for the same completion job. Partial enqueue retries reuse match-based job IDs. Ten total attempts use exponential retries starting at 2 seconds; successful identities are retained for 24 hours without count eviction, failed jobs are retained. This is at-least-once delivery with bounded queue deduplication, not exactly-once effects. The legacy shared handlers that drained pre-upgrade events were removed in Sprint 134 PR L. Other event transports are unchanged. The existing gap between database completion and the first Redis enqueue is not covered by a transactional completion outbox; a publish failure there still needs operator recovery. Real integration cases assert all three subscriber effects. -
2026-10-04 (Sprint 132 PR C, ADR-099): directed item borrowing.
POST /requests/inventory/items/:id/borrowaccepts{community_id,duration_days,return_date?,description?}(duration integer 1–30, note ≤2000, UTC ISO return date). It locks the item, checks selected-community live audience/memberships, creates aborrowrequest withis_directed=true, nullable user/community target andinventory_item_id, and exactly onerequest_communitiesrow. Own/unavailable items return 400, non-audience/invalid selected audience 404. A resend reuses the caller's open ask under the item lock, retaining its original terms/attribution. The same transaction savesinventory.borrow_notification_outboxwith{request_id,requester_id,recipient_user_ids,title,inventory_item_id}. Onlydirected_request_createdpublishes after commit, onkarmyq-directed-notifications. Queue failure returns the committed ask (201); a 5-second relay retries pending intent, checks acknowledged but unconfirmed deliveries after 5 minutes, and retries exhausted failed jobs. Delivery re-resolves current request content/target admins, so outage retries cannot use stale recipient snapshots; deleted, closed and expired requests are terminal. As the ADR-099 cross-service acknowledgement exception, notification-service updates only delivered_at in this request-service-owned outbox after handling all eligible recipients or a terminal job.GET /requests/inventory/asks/incomingreturns{asks}: caller-targeted open, unexpired requests, excluding own asks and caller's live proposed/matched offers. The Helping UI offers through normalPOST /matches, then refetches inbox and commitments. Item availability is not changed by borrowing.notDirectedSqlguards all browse reads, pulse and admin actions;directedAudienceSqlguards detail and own-request listing (only caller-equalrequester_id). Personal audience = requester/target; community audience = requester/current active admins; existing responders retain their exchange history even after demotion or target deletion. Match reads/mutations and action items usematchParticipantSql; current live audience still gates new offers. Directed non-audience offers return the same 404 as missing IDs before lifecycle checks (also provider offer validation). Null targets never open public access. Ordinary POST rejects all four routing fields, even null/false. Detail addsis_directedanddirected_to:{kind,id,name}|null. Matches list addsis_directed; directed proposed commitments render while awaiting acceptance. Participant decision bands retain private mark-done/rating actions. Browse and offered-awaiting count/preview exclude private asks; private proposed matches render once in Helping commitments. Non-manager item share metadata contains only communities where both viewer and owner are active; managers retain configured shares. Activity stats constrain the nullable request JOIN rather than WHERE and use request_communities, preserving joins/new members with no public requests. Relationship context returns 204 for directed asks instead of inventing a public tier. SQL gate checks WHERE guards per query block/alias and exact reviewed exceptions. Outer-join ON semantics and unparenthesized dynamic fragments require exact review; it is conservative static coverage, not a general SQL authorization proof. Real-DB tests remain the runtime authority. The legacy feed mapper's absent expected_duration is null; its OpenRequest type explicitly admits null so the real FeedComposer import graph compiles under integration tests' strict settings. Pre-C image rollback after directed rows exist requires preserved guards or unavailable reads (ADR-099); additive DDL alone does not preserve privacy. -
2026-10-03 (Sprint 132 PR B, ADR-099): inventory catalog under
/requests/inventory. Personal items start private; shares require the owner's live active membership. Community property is managed by live active admins. Unavailable items are visible only to managers. Every inventory read usesitemAudienceSql, which composesitemManagerSql; every write uses the manager predicate. Sharing replaces the set atomically and rejects invalid memberships before deleting any existing shares. Item mutation locks serialize concurrent share/edit/delete operations. Creator attribution is nullableON DELETE SET NULL; deleting a creator preserves community ownership. The application predicates enforce access even for DB-owner connections.
Inventory catalog API (Sprint 132 PR B)
| Method | Path | Contract |
|---|---|---|
| GET | /requests/inventory/mine | Caller-owned personal items, all statuses, with shared_with: {id,name}[] |
| GET | /requests/inventory/community/:communityId | Live member only (403 otherwise); {community_owned,shared_by_members}, audience-filtered with member-owner attribution |
| GET | /requests/inventory/items/:id | Visible item; missing or outside audience returns 404 |
| POST | /requests/inventory/items | {name,description?,category,condition?,owner_community_id?}; 201; live admin required for community ownership |
| PATCH | /requests/inventory/items/:id | Manager only; bounded editable fields name,description,category,condition,status |
| DELETE | /requests/inventory/items/:id | Manager only; hard delete; {deleted:true} |
| PUT | /requests/inventory/items/:id/shares | Personal owner only; replace with up to 50 unique community UUIDs; empty list means private |
inventory.items owns one user or one community (XOR); inventory.item_shares owns the per-community
share set. Categories/conditions match the borrow vocabulary. The route validates name (trimmed,
1–120), description (≤2000), enums and UUIDs by hand. A visible item that the caller cannot manage
returns 403 on writes; a non-audience caller gets 404. Share writes on community property return 400.
Read responses expose share metadata to managers, and only viewer-accessible communities to others.
The community list checks both the viewer's and personal owner's membership in the selected community.
Mount /requests/inventory before /requests, including requestsRouter and its /:id route,
and before broad admin middleware. The real-app regression test guards this order.
Importing src/index.ts does not start a server; direct execution still initializes DB and Redis.
-
2026-10-01 (Sprint 132 PR A, ADR-099):
getUserProfilereadsauth.user_tagswheretag_type='skill', usingskill_slugor lowercase trimmed text with non-alphanumeric runs replaced by underscores. Sprint 133 PR A retires the legacy matched-feed route; the curated feed continues using the canonical skill store. No matching code reads the deprecatedauth.user_skills. Curated response and shared scoring contracts are unchanged. -
2026-10-06 (Sprint 132, BUG-061 — HIGH):
DELETE /requests/:idauthorized the requester from a bodyuser_id, so any logged-in user could cancel any request, including a private directed ask, by naming its requester.POST /offers(bodyofferer_id) andPUT/DELETE /offers/:id(bodyuser_id) had the same hole. All four now usereq.user.userId(401 without it) and ignore the body field; existing clients that still send it keep working. Tests:tests/regression/sprint-132-body-identity.test.ts(8 cases, red before the fix) and roottests/integration/sprint-132-body-identity.integration.test.ts. Community-service had the same pattern in six handlers, fixed in the same change. -
2026-09-30 (Sprint 132 PR S, BUG-057 — HIGH):
GET /matchesapplied only optional, client-supplied filters, so no filter meant every match on the platform anduser_id=<anyone>meant that person's;GET /matches/:idchecked only the id and returned requester/helper emails. Both now bind the JWT caller into a requester/responder predicate (PARTICIPANT_PREDICATEinsrc/routes/matches.ts, the same definition the accept/reject/complete/delete handlers use;POST /matchessetsmatches.offer_idonly to an active offer whoseofferer_idequals the responder (the JWT caller,src/routes/matches.tsoffer check), so the offerer is always the responder and the predicate needs no offerer term;responder_idis NOT NULL), and/:id404s for non-participants. The feedback routes on the same mount had the same hole:GET /matches/:id/feedbackchecked participation for a queryuser_id, andPOSTauthored feedback as a bodyfrom_user_id. Both now use the JWT caller (src/routes/feedback.ts). Every in-repo caller (webCommitmentsTab/MyRequestsTab/matches/[id], mobile feed/request detail, the simulation workflows) already passed or filtered to the caller's own id, so none loses data it used. RLS onrequests.matchesdoes not bind the owner connection, so this is enforced in SQL. -
2026-08-21 (Sprint 126 — idempotent match completion):
PUT /matches/:id/completeselectedm.statusand never checked it, so a participant could call it repeatedly; each call re-stampedcompleted_at = CURRENT_TIMESTAMPand re-publishedmatch_completed. Now a match already incompletedreturns success without writing or publishing. The duplicate award was already absorbed by ADR-096's projection identity, but the movingcompleted_atis the real hazard: it shifts the strictly-before as-of boundary, so a replay can select a different top-3 community set or cross a 10/50/100 milestone, producing rows under NEW identities the unique index cannot absorb — and it makes stored rows disagree with replay, which the standing backfill reports as a BLOCKINGCONFLICTING_KARMA_PROJECTION. One double-click could have refused the whole backfill. Found by the Sprint 126/security-reviewgate.
Quick Start
# Start this service
docker-compose up request-service
# Start in development mode
cd services/request-service && npm run dev
# Test this service
npm run test:integration -- integration/request-service.test.ts
# View logs
docker logs karmyq-request-service -f
# Health check
curl http://localhost:3003/health
1. Overview
1.1 Purpose
The Request Service manages polymorphic help requests (v9.0), help offers, and matches between requesters and helpers within communities. It implements skill-based matching and curated feed filtering to intelligently suggest relevant requests to users.
1.2 Responsibilities (v9.0)
- Polymorphic Request Management - CRUD for 5 request types (generic, ride, service, event, borrow)
- Curated Feed Filtering - Skill-based + preference-based feed curation with match scores
- Help Offer Management - CRUD operations for help offers
- Type-Specific Matching - Match using specialized algorithms per request type
- Privacy Controls - Social Karma v2.0 privacy and consent management
- Interaction Feedback - Collect exchange quality ratings (not person ratings)
- Event Publishing - Emit domain events for request lifecycle
- Context-bound Connections - Authorize reciprocal relationship context only for reachable requests and their ordinary/provider offers; derive both participant IDs server-side
Sprint 116: Request-scoped reciprocal relationship context
Three authenticated read routes expose the strict RelationshipContext contract:
GET /requests/:requestId/relationship-context— eligible helper ↔ requester before offering; the requester receives 204 for their own ask.GET /requests/:requestId/matches/:matchId/relationship-context— either ordinary match participant, with both IDs verified against the route request in one query.GET /requests/:requestId/provider-offers/:offerId/relationship-context— either requester or provider-offer owner; provider service metadata is attached only when the provider is the viewed counterpart. Sprint 116 PR B enriches this: the requester's view also carries the provider'scollectiveName(via an intra-requests-schema join onprovider_collective_members→provider_collectives, active collectives only, deterministic single pick). A solo provider discloses no collective, and the provider viewing their own offer never sees a collective label.
There is no arbitrary target-user route. Request-service owns every public authorization decision,
calls social-graph-service with only the derived pair and X-Internal-Secret (2.5-second timeout),
validates both the internal topology and final strict response, and returns retryable 503 on graph
failure. Existing offer/accept/decline/withdraw actions do not depend on this read.
The internal topology call accepts only the deployment's explicit service origins
(social-graph-service:3010, the integration-test service name, or local port 3010). An unrecognized
SOCIAL_GRAPH_API_URL fails as a configuration error before Axios runs, so request data can never
redirect this privileged service-to-service call to another host.
Participant reads distinguish permanent absence from dependency failure. If a historical
community-scoped match/provider offer remains participant-authorized but its original same-vs-sister
reachability tier can no longer be reconstructed after membership changes, the route returns 204
rather than inventing a tier or reporting a transient 503. A real social-graph/configuration/
contract failure remains 503; the internal client preserves a failure kind and cause so contract
drift/configuration is error-logged and transport/upstream failures are warning-logged.
The readLight + auth + tenant + DB-context middleware chain is mounted only on the three context
route patterns. Other /requests/* traffic enters the existing standard request chain once and does
not pay duplicate JWT verification, rate-limit accounting, or set_config work.
getRequestReachability now reports the most local truthful tier (same_community,
sister_community, trust_network, or platform). Provider-offer eligibility uses this same
visibility boundary instead of requiring shared community membership, so eligible intercommunity
requests work for providers too.
1.3 NOT Responsible For
- Karma Calculation - Handled by Reputation Service
- User Authentication - Handled by Auth Service
- Messaging - Handled by Messaging Service
- Community Management - Handled by Community Service
2. Architecture
2.1 Technology Stack
- Runtime: Node.js 18
- Framework: Express.js
- Database Schema:
requests - Event Queues: routed per consumer by
@karmyq/shared(karmyq-events-notification; ADR-101), plus the dedicatedkarmyq-completion-dispatchandkarmyq-directed-notifications(ADR-099). Unconsumed events are not enqueued. - External Services: PostgreSQL, Redis
2.2 Key Components (v9.0)
src/
├── index.ts # Express app initialization, route registration
├── routes/
│ ├── requests.ts # Polymorphic request CRUD + curated feed endpoint
│ ├── offers.ts # Help offer CRUD
│ └── matches.ts # Match creation and status updates
├── services/
│ └── matcher.ts # Type-specific matching algorithms
├── database/
│ └── db.ts # PostgreSQL connection pool
└── events/
└── publisher.ts # Redis event publishing (Bull)
Shared Packages (v9.0):
├── packages/shared/src/schemas/requests/
│ ├── index.ts # Zod discriminated union schema
│ ├── generic.ts # Generic request schema
│ ├── ride.ts # Ride request schema
│ ├── service.ts # Service request schema
│ ├── event.ts # Event request schema
│ └── borrow.ts # Borrow request schema
└── packages/shared/src/matching/
├── index.ts # Matching algorithm exports
├── types.ts # UserProfile, MatchScore interfaces
└── matchers/ # Type-specific matchers
├── generic.ts
├── ride.ts
├── service.ts
├── event.ts
└── borrow.ts
2.3 Database Schema
Tables Owned by This Service
requests.help_requests - Core polymorphic help request table (v9.0)
CREATE TABLE requests.help_requests (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
requester_id UUID NOT NULL REFERENCES auth.users(id),
title VARCHAR(255) NOT NULL,
description TEXT NOT NULL,
-- v9.0: Polymorphic Request System
request_type request_type_enum NOT NULL DEFAULT 'generic',
payload JSONB, -- Type-specific data
requirements JSONB, -- Type-specific requirements
-- Legacy fields (maintained for backward compatibility)
category VARCHAR(100), -- transportation, moving, childcare, etc.
urgency VARCHAR(50) DEFAULT 'medium', -- low, medium, high, critical
preferred_start_date TIMESTAMP,
preferred_end_date TIMESTAMP,
status VARCHAR(50) DEFAULT 'open', -- open, matched, completed, cancelled
expired BOOLEAN DEFAULT false,
-- ADR-022: Multi-Tier Visibility
visibility_scope visibility_scope_enum NOT NULL DEFAULT 'community',
visibility_max_degrees INTEGER DEFAULT 3 CHECK (visibility_max_degrees BETWEEN 1 AND 6),
-- Social Karma v2.0 Privacy
is_public BOOLEAN DEFAULT false,
requester_visibility_consent BOOLEAN DEFAULT false,
-- Sprint 36: Admin boost (Migration 015)
is_boosted BOOLEAN DEFAULT FALSE,
boosted_at TIMESTAMP,
boosted_expires_at TIMESTAMP,
boosted_by UUID REFERENCES auth.users(id) ON DELETE SET NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- ADR-022: Visibility scope enum
CREATE TYPE visibility_scope_enum AS ENUM ('community', 'trust_network', 'platform');
-- v9.0: Request Type Enum
CREATE TYPE request_type_enum AS ENUM ('generic', 'ride', 'service', 'event', 'borrow');
-- v9.0: Multi-community support
CREATE TABLE requests.request_communities (
request_id UUID NOT NULL REFERENCES requests.help_requests(id) ON DELETE CASCADE,
community_id UUID NOT NULL REFERENCES communities.communities(id) ON DELETE CASCADE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (request_id, community_id)
);
-- Indexes
CREATE INDEX idx_help_requests_community_id ON requests.help_requests(community_id);
CREATE INDEX idx_help_requests_status ON requests.help_requests(status);
CREATE INDEX idx_help_requests_category ON requests.help_requests(category);
Request status (Sprint 135, BUG-075). help_requests.status (open, dibs_pending, matched, completed,
cancelled; chk_help_requests_status) is derived from the request's rows, not set by hand: cancelled stays
cancelled; otherwise matched while a match is matched, completed once a match is completed, dibs_pending
while a dibs is pending, else open. Only src/db/requestStatus.ts writes it (reconcileRequestStatus, called
by every writer after its own row changes, in the same transaction and under the request lock; markRequestCancelled
for the requester's decision), plus cleanup-service's expireDibs.ts, which reopens a request only while it is
dibs_pending. lockRequest returns the derived status for preconditions. Gate:
tests/regression/sprint-135-request-status-gate.test.ts.
Expiry (Sprint 136, BUG-085). An open ask past its expiry (expired IS TRUE, or expires_at <= clock_timestamp() before the sweep flags it) takes no new commitment. The writers that start one (propose-match,
match accept, dibs create, provider-offer accept, POST /matches) read lockRequestForCommitment, which returns
'expired' for such an ask and the derived status otherwise; they answer REQUEST_NOT_OPEN. Cancel, reject and dibs
accept read lockRequest, which ignores expiry. Both share one derive statement: the Sprint 135 CASE, unchanged,
plus a past_expiry column. help_requests.status stays open on an expired ask.
requests.request_admin_notes - Community-scoped admin triage notes (Sprint 25)
CREATE TABLE requests.request_admin_notes (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
request_id UUID NOT NULL REFERENCES requests.help_requests(id) ON DELETE CASCADE,
community_id UUID NOT NULL REFERENCES communities.communities(id) ON DELETE CASCADE,
note TEXT NOT NULL,
updated_by UUID NOT NULL REFERENCES auth.users(id),
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(request_id, community_id)
);
One note per (request, community) pair; upserted via PATCH /requests/:id/admin-triage.
requests.help_offers - Help offers from community members
CREATE TABLE requests.help_offers (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
community_id UUID NOT NULL REFERENCES communities.communities(id),
offerer_id UUID NOT NULL REFERENCES auth.users(id),
title VARCHAR(255) NOT NULL,
description TEXT NOT NULL,
category VARCHAR(100) NOT NULL,
availability_start TIMESTAMP,
availability_end TIMESTAMP,
status VARCHAR(50) DEFAULT 'active', -- active, matched, expired
-- Social Karma v2.0 Privacy
is_public BOOLEAN DEFAULT false,
offerer_visibility_consent BOOLEAN DEFAULT false,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_help_offers_community_id ON requests.help_offers(community_id);
requests.matches - Connections between requests and responders
CREATE TABLE requests.matches (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
request_id UUID NOT NULL REFERENCES requests.help_requests(id),
offer_id UUID REFERENCES requests.help_offers(id),
responder_id UUID NOT NULL REFERENCES auth.users(id),
status VARCHAR(50) DEFAULT 'pending', -- pending, accepted, in_progress, completed, cancelled
-- Social Karma v2.0 Privacy
requester_visible BOOLEAN DEFAULT false,
responder_visible BOOLEAN DEFAULT false,
interaction_category VARCHAR(100),
-- Sprint 40: Admin propose-match (Migration 018)
admin_proposed BOOLEAN NOT NULL DEFAULT FALSE, -- TRUE when match created via propose-match admin route
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
completed_at TIMESTAMP,
requester_done_at TIMESTAMP, -- set when requester clicks Done (migration 017)
responder_done_at TIMESTAMP, -- set when responder clicks Done (migration 017)
UNIQUE(request_id, offer_id)
);
CREATE INDEX idx_matches_request_id ON requests.matches(request_id);
CREATE INDEX idx_matches_status ON requests.matches(status);
Retired in Sprint 134 PR L2: the interaction-feedback table and its indexes were dropped after the only writer was removed (BUG-068). Private feedback lives in feedback.feedback, owned by reputation-service.
Privacy Design Principles (Social Karma v2.0)
- Privacy First: All requests/offers default to
is_public = false - Two-Way Consent: Both parties must consent for names in featured stories
- Interaction Ratings: Rate the exchange quality, NOT the individual
requests.provider_rate_cards - Provider pricing entries (Sprint 29)
CREATE TABLE requests.provider_rate_cards (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
provider_id UUID NOT NULL REFERENCES requests.provider_profiles(id) ON DELETE CASCADE,
label VARCHAR(255) NOT NULL,
pricing_model VARCHAR(50) NOT NULL, -- 'standard', 'free', 'negotiable'
rate_amount NUMERIC(10,2), -- null for free/negotiable
rate_unit VARCHAR(50), -- 'per_hour', 'per_session', 'per_trip', 'flat'
currency CHAR(3) DEFAULT 'USD',
notes TEXT,
is_active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Cards are never hard-deleted; deactivation sets is_active = false.
requests.help_requests — Sprint 29 addition: preferred_provider_id UUID REFERENCES requests.provider_profiles(id) — optional field set when a requestor pre-selects a provider while filing a typed request.
requests.help_requests — Sprint 42 addition: scheduled_for TIMESTAMPTZ — nullable; when set, the request is a scheduled request eligible for the dibs flow. When null, the request is treated as ASAP and always broadcast publicly (dibs rejected).
requests.feed_events — Sprint 43 addition: append-only feed outcome log for weight tuning.
CREATE TABLE requests.feed_events (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
request_id UUID NOT NULL REFERENCES requests.help_requests(id) ON DELETE CASCADE,
event_type TEXT NOT NULL CHECK (event_type IN ('impression', 'offer_made', 'match_completed')),
feed_score NUMERIC(5,2),
feed_rank INTEGER,
source_tier TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
Indexed by (user_id, created_at DESC), (request_id, event_type), and (event_type, created_at DESC). Fire-and-forget writes — never blocks feed response.
requests.dibs - Private first-refusal records for scheduled requests (Sprint 42)
CREATE TABLE requests.dibs (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
request_id UUID NOT NULL REFERENCES requests.help_requests(id) ON DELETE CASCADE,
requester_id UUID NOT NULL REFERENCES auth.users(id),
provider_user_id UUID NOT NULL REFERENCES auth.users(id),
status VARCHAR(50) DEFAULT 'pending', -- pending, accepted, declined, expired
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
UNIQUE(request_id) -- one active dibs per request at a time
);
CREATE INDEX idx_dibs_request_id ON requests.dibs(request_id);
CREATE INDEX idx_dibs_provider_user_id ON requests.dibs(provider_user_id);
CREATE INDEX idx_dibs_status ON requests.dibs(status);
CREATE INDEX idx_dibs_expires_at ON requests.dibs(expires_at) WHERE status = 'pending';
provider.offers - Provider priced offers on help requests (Sprint 41)
CREATE TABLE provider.offers (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
provider_id UUID NOT NULL REFERENCES requests.provider_profiles(id) ON DELETE CASCADE,
provider_user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
request_id UUID NOT NULL REFERENCES requests.help_requests(id) ON DELETE CASCADE,
price NUMERIC(10,2), -- null means free / price TBD
note TEXT,
status VARCHAR(50) DEFAULT 'pending', -- pending, accepted, declined, withdrawn
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(provider_id, request_id) -- one offer per provider per request
);
Tables Read by This Service
auth.users- User details for requester/helper namesauth.platform_admins- Live platform admin grant for/admin/schemas(isLivePlatformAdmin, Sprint 141, ADR-105)auth.user_tags- Skill tags and nullable canonicalskill_slugfor skill-based matchingauth.user_feed_preferences- Feed visibility preferences (ADR-022)auth.social_distances- Trust distance between users (ADR-031)communities.communities- Community names, details, anddefault_request_scopecommunities.members- Verify community membershipcommunities.community_configs- Feed scoring weights (ADR-031)reputation.trust_scores- Trust scores for dibs candidate selection (ADR-051); no longer read for feed ranking (ADR-082 removed requester reputation from the feed)reputation.provider_trust_scores- Public provider trust scores for provider/collective listings and dibs (ADR-082 typed provider exception)
3. API Reference
3.1 Help Requests
GET /requests
Get all help requests with optional filters.
Query Parameters:
community_id(UUID) - Filter by communitystatus(string) - Filter by status (default: 'open')type(string) - Filter by categorylimit(number) - Max results (default: 50)offset(number) - Pagination offset (default: 0)include_admin_notes(boolean) - Whentrueandcommunity_idis also provided, each request in the response includes anadmin_notefield scoped to that community (sourced fromrequests.request_admin_notes). Only returned to active admins/moderators of the community.requester_id(UUID) - Equal to the caller: the private "my requests" list (directed-audience predicate only). Any other value is still browse and still gated.
Visibility boundary (BUG-065, Sprint 133 PR V): browse rows are filtered by requestReadableSql, the
same boundary GET /requests/:id enforces, so the list never shows a row the detail route would 404. The
list differs from the detail route in exactly three named ways, each pinned by the parity test in
tests/integration/sprint-133-pr-v-read-boundary.integration.test.ts: it drops expired = TRUE rows, it never
browses directed asks, and it drops the viewer's own live proposed/matched matches (BUG-002).
Response:
{
"success": true,
"data": [{
"id": "uuid",
"community_id": "uuid",
"community_name": "Seattle Mutual Aid",
"requester_id": "uuid",
"requester_name": "Alice Smith",
"title": "Need help moving furniture",
"description": "Moving couch upstairs, need 2-3 people",
"category": "moving",
"urgency": "medium",
"status": "open",
"created_at": "2025-01-10T12:00:00Z"
}],
"count": 1
}
Implementation: src/routes/requests.ts:8
Retired legacy matched feed (Sprint 133 PR A)
The legacy matched-feed route and unused frontend wrapper are removed. Use the curated
feed, which still reads caller skill tags through getUserProfile. Retirement tests assert
404 without DB access for authenticated, anonymous and legacy query callers.
GET /requests/curated (v9.18 + ADR-048 Feed Ranking v2, amended by ADR-082)
Get curated feed scored on six signals: skill match, trust DISTANCE (caller-relative degrees), community relevance, urgency, prior interaction (the caller's own decayed edge), and recency.
Sprint 112 (ADR-082) — reputation disclosure boundary: the requester's exact reputation is
removed from feed ranking entirely — the requester karma/trust lookup query is gone, the
requester-trust signal is fixed to 0, and the six weights are NORMALIZED to sum 1.0 at query time
(configured, unconfigured, AND sister paths use the same normalized vector, so none is depressed by a
dropped signal). feed_weight_requester_trust is NOT founder-configurable — config writes that set it
are rejected. The response NO LONGER exposes requesterKarma, requesterTrustScore, the composite
feedScore, the component priorInteractionScore/recencyScore, or matchBreakdown/feedBreakdown
(whose requesterTrust.raw was a reconstruction vector). Outward ranking is the server-sorted ORDER;
the unified-feed priority is a non-reversible RANK (1000 + position), never 1000 + feedScore.
Impressions are still logged fire-and-forget to requests.feed_events (internal feed_score column).
Query Parameters:
minScore- restricted to two FIXED server modes (ADR-082, anti-oracle):0/allwidens to every open ask; anything else/absent uses the default relevance threshold (30). Arbitrary intermediate thresholds are NOT honored (they collapse to the default) so the hidden composite cannot be probed via the inclusion boundary.limit(number) - Max results (default: 20)community_id(UUID) - Filter by specific community (optional)tier(string) - Filter by visibility tier:community,trust_network,platform,sister_community(optional)includeSisterCommunities(boolean) - Include requests from linked sister communities whereshow_in_sister_feeds=true, scored with trust_carry_factor applied (Sprint 15)view(string, Sprint 85/86 / ADR-066) - Whenview=home, returns the unified feed item union{ items: UnifiedFeedItem[] }(decisions + requests) for Dashboard Home. Whenview=community, returns the community-scoped union (requests + activity + story texture, no decisions) for a community's Requests tab.viewabsent keeps the legacy request-array shape (back-compat). Sprint 88 logs impressions for request items before both union early returns.
view=home / view=community response (Sprint 85/86 / ADR-066 — Unified Feed Model):
Each item is a discriminated union carrying a server-computed priority (action altitude — the client renders in array order):
type UnifiedFeedItem =
| { kind: 'request'; priority: number; data: RequestCardData } // a request you can fill (1000–1100)
| { kind: 'decision'; priority: number; data: DecisionData } // a response you owe (>=2000, home only)
| { kind: 'activity'; priority: number; data: ActivityData } // community texture (500, community only)
| { kind: 'story'; priority: number; data: StoryData } // community texture (100, community only)
- Action altitude bands: decisions
>= 2000> requests1000–1100(=1000 + rank, a non-reversible position in the server's feedScore-sorted list — ADR-082, NOT1000 + feedScore) > activity500> story100. Within decisions, a response a counterparty awaits (accept/decline) ranks above the member's own housekeeping (withdraw/mark-done). decisionitems (home only) are built from the member's proposed matches/offers (accept/decline as requester), matched items awaiting the member's mark-done, and pending dibs on the member's requests — the same data the Commitments tab reads. S86 UX: a responder's own proposed offer is no longer surfaced here (it's awaiting the requester, not a decision the responder owes — it lives in the Helping tab with a Withdraw action). Each decision also carriesdescription+payload/payload_typeso the band can expand inline to show request detail.match_scoreis normalized to one 0–100 integer scale at the API boundary (never 0–1), with a human-readablematch_reason.payload_type(Sprint 86 / ADR-067) — eachrequestitem carries a fine payload subtype derived from thecategorycolumn viacategoryToPayloadType()(distinct from the coarserequest_typeenum); it drives the card'sRequestPayloadRenderer. Unmapped categories →undefined(renderer no-ops, safe).- Prior-interaction signal reads the decayed edge weight (
social_graph.trust_edges_live.current_weight, ADR-011 /20260526-interaction-halflife), not a raw count — feed ranking reflects relationship shape, not history ("designed to forget").trust_edges_liveis a VIEW (read-only).
view=community specifics (Sprint 86 / ADR-066):
- Assembled entirely from request-service's own DB reads — no external feed service call (ADR-066 single-source). Texture queries are best-effort (each in try/catch; a failure degrades to "no texture", never breaks the feed).
- Requires
community_id→400 COMMUNITY_ID_REQUIREDif missing. Caller must be a live member of that community (communities.members, not the JWT claim; BUG-065) →403 NOT_A_MEMBERotherwise, before any texture read. activity= one community pulse (exchanges completed this week, new members, open-requests count, recent helpers).story= recent first-exchange narratives. Never includes adecisionitem.
Vocabulary reconciliation (Sprint 85 / ADR-066, migration 20260603-feed-vocab-reconciliation.sql):
- Urgency is one scale
urgent | high | medium | low(critical → urgent), enforced by CHECKchk_help_requests_urgency. - Status lifecycle
open | dibs_pending | matched | completed | cancelledis locked by CHECKchk_help_requests_status. There is nopendingstatus onhelp_requests; the member-facingproposed(awaiting-acceptance) token is derived in the curated handler from request + match state, not stored.
Authentication: Required (JWT token)
Response:
{
"success": true,
"data": {
"requests": [{
"id": "uuid",
"request_type": "service",
"title": "Need plumber for leak repair",
"description": "Kitchen pipe leaking...",
"urgency": "high",
"visibility_scope": "community",
"visibility_max_degrees": 3,
"payload": {
"service_category": "plumbing",
"skill_level_required": "intermediate"
},
"matchScore": 85,
"is_boosted": true,
"boosted_expires_at": "2026-03-27T12:00:00Z",
"sourceTier": "community",
"trustDegrees": 2,
"matchReasons": [
"You have plumbing skill",
"Skill level matches",
"High urgency bonus"
],
"community_name": "Seattle Mutual Aid",
"requester_name": "Alice Smith"
}],
"count": 15,
"tiers": {
"community": 10,
"trust_network": 3,
"platform": 2
},
"filters": {
"minMatchScore": 30,
"totalRequests": 50,
"matchedRequests": 15,
"subscribedTypes": ["generic", "service", "event"]
},
"feedPreferences": {
"feed_show_trust_network": true,
"feed_trust_network_max_degrees": 3,
"feed_show_platform": false,
"feed_platform_categories": ["digital", "questions"]
},
"userProfile": {
"skills": ["plumbing", "carpentry"],
"skillCount": 2
}
}
}
Sprint 112 (ADR-082): the example above shows the post-boundary shape. The feed no longer returns
feedScore,karmaScore/requesterKarma,requesterTrustScore,priorInteractionScore,recencyScore, ormatchBreakdown/feedBreakdown— the requester's exact reputation and the reconstruction-enabling composite stay internal.matchScore(skill match) andtrustDegrees(caller-relative degrees) remain; outward ranking is the server-sorted order.
Algorithm (ADR-031, amended by ADR-082):
- Fetch user feed preferences from
auth.user_feed_preferences - Fetch user preferences (subscribed request types from auth.user_request_preferences)
- Fetch skill tags from auth.user_tags, preferring skill_slug and normalizing unresolved tag text
- Get open requests across three tiers:
- Community: Requests in user's communities
- Trust Network: Requests with
visibility_scope != 'community'within trust degree limits - Platform: Requests with
visibility_scope = 'platform'(if user opted in)
- Batch-fetch trust DISTANCES (caller-relative degrees) from
auth.social_distances. Sprint 112 (ADR-082): the requester karma/trust lookup fromreputation.karma_records/reputation.trust_scoresis REMOVED — requester reputation is no longer read for ranking. - Resolve source tier per request using
resolveSourceTier()from@karmyq/shared/matching - Calculate feed scores from SIX signals using community-configurable weights, NORMALIZED to sum 1.0 at query time with requester-trust excluded (ADR-082); active boost adds +30 (capped at 100)
- Sort by tier priority (community > trust_network > platform), then by feedScore (internal only)
- Return top N in ranked order — NO scores/karma/trust exposed (ADR-082); outward signal is the order
Implementation: src/routes/requests.ts:194
GET /requests/community/:communityId/pulse (Sprint 89 / ADR-068)
The community's weekly help-loop pulse for the warm community Home hero ("This week in the
neighbourhood"). Reuses the exact S86 community-feed texture aggregation (extracted into the
shared fetchCommunityPulse() helper that also builds the in-feed activity card), so the hero
pulse and the in-feed ActivityCard can never report different numbers. Adds one new field
timeSensitive. Read-only; no schema change.
Authentication: Required (JWT). Members-only — gated on live membership in communities.members
(BUG-065: never the login-time JWT claim). A non-member caller → 403 NOT_A_MEMBER.
Unknown community → 404.
Window: last 7 days. openAsks/timeSensitive count only status='open' AND expired = FALSE
(matches the texture query so the pulse never overcounts vs the feed). recentJoins comes from the
server (communities.members.joined_at within 7 days) — there is no client-side member-recency seam.
Sprint 100 / F1 — truth: helpedThisWeek is COUNT(DISTINCT m.responder_id) (not COUNT(*)
over matches), over the same member-scoped, completed-in-7-days subset that feeds recentHelpers,
so the headline ("N neighbours helped each other") can never outrun the named helpers — one neighbour
who completes three exchanges is one helper, not three.
Response:
{
"success": true,
"data": {
"helpedThisWeek": 6,
"openAsks": 4,
"timeSensitive": 2,
"recentJoins": 1,
"recentHelpers": [{ "name": "Priya Sharma", "count": 3 }],
"windowDays": 7
}
}
Implementation: src/routes/requests.ts — router.get('/community/:communityId/pulse') + the
shared fetchCommunityPulse() helper.
GET /requests/community/:communityId/open-asks (Sprint 100 / F2)
The reachable, read-only list behind the pulse "N open asks across the community" row. Returns
every open + unexpired ask attached to the community — including the caller's own asks and asks
already offered on — using the identical predicate as the pulse openAsks count
(status='open' AND expired = FALSE, scoped via request_communities), so the count and the rows
can never diverge. Browse-only: the frontend renders these cards read-only (no Offer).
Members-only (live communities.members row, not the JWT claim → 403 NOT_A_MEMBER). Returns { items, count } of
canonical request-card data scoped to this community. Implementation: src/routes/requests.ts —
router.get('/community/:communityId/open-asks').
GET /requests/curated?view=home — offeredAwaiting (Sprint 100 / G1)
The home-feed response now carries offeredAwaiting: the count of open asks the member has offered
to help on and is still waiting to hear back on (responder, match proposed, request open +
unexpired). The curated feed hides asks the viewer already offered on and a pending offer isn't a
decision they owe, so this powers a single Home band ("You've offered to help on N open asks") that
keeps an active helper's Home from reading empty. Fail-soft: any error → 0 (band hidden).
Sprint 101 — offeredAwaitingItems: the home-feed response now also carries
offeredAwaitingItems, a small (server-capped, default 3) preview list so Home can render the actual
awaiting asks, each linking to its /requests/:id detail. Selected from the same predicate as
the count via DISTINCT ON (request_id) (count is COUNT(DISTINCT request_id)), so the count and the
items can never disagree — a helper holding two proposed match rows on one ask still counts and
previews as one. Each item carries { match_id, request_id, title, description, author_name, community_id, community_name, urgency, request_type, payload_type, status:'proposed', offered_at }.
Shared helper fetchOfferedAwaiting(userId, previewLimit) returns { count, items }; fail-soft to
{ count: 0, items: [] }.
Sprint 108 — suggestedAsHelper + admin-proposed decisions: the home-feed response also carries
suggestedAsHelper: { count, items } (same item shape as offeredAwaitingItems): the open asks where
an admin/matchmaker proposed THIS member as helper (admin_proposed = TRUE, proposed responder
match, request open + unexpired) and the member owes the accept/decline. Home renders the calm
SuggestedAsHelperPanel preview from it and links to Helping. Both bands share one private helper
fetchProposedResponderAsks(userId, adminProposed, previewLimit); fetchOfferedAwaiting calls it with
FALSE, fetchSuggestedAsHelper with TRUE. Separately, fetchDecisions now projects
m.admin_proposed and surfaces admin-proposed responder matches as member_role:'responder'
subject_kind:'match' decisions with accept_offer/decline_offer — these render in the Helping
DecisionBand (BUG-015 keeps the actionable band off Home), routed to PUT /matches/:id/accept|reject
(the responder is authorized for both, matches.ts:306 + the reject participant check). The flip is
symmetric: for an admin-proposed match the responder owes (the requester only waits); for a
self-offer the requester owes (the responder's offer is offered-awaiting).
GET /requests/offered-awaiting (Sprint 107 / BUG-023)
Canonical read endpoint for the same offered-awaiting predicate. Returns up to 50 distinct open,
unexpired asks where the authenticated member has a member-initiated (admin_proposed = FALSE)
proposed responder match and is waiting on the requester. This backs the Helping tab's Offers
awaiting requester section and uses fetchOfferedAwaiting(userId, 50), so Home's preview/count and
Helping's list cannot diverge. Admin-proposed matches are excluded: those await the member's
accept/decline (Helping renders them under "Awaiting Acceptance"), not the requester's response.
{ "success": true, "data": { "count": 2, "items": [{ "request_id": "uuid", "match_id": "uuid", "status": "proposed" }] } }
Route order: registered before router.get('/:id') so /requests/offered-awaiting is not
captured as a request id.
GET /requests/retention-policy (Sprint 90 / ADR-069)
Backs the /about/memory transparency page. Returns the resolved retention windows
(completed/expired/message, community → global → fallback via requests.retention_config) plus
the member's own held vs forgotten request counts. Read-only, no PII.
{ "success": true, "data": {
"windows": { "completedRequestWindowDays": 180, "expiredRequestWindowDays": 30, "messageWindowDays": 180 },
"counts": { "held": 4, "forgotten": 2 }
} }
Gated on live membership in communities.members when ?communityId= is supplied (non-member → 403; BUG-065).
Route order: registered before router.get('/:id') so the static path isn't captured as an id.
Window resolution is the pure exported resolveRetentionWindows(rows, communityId?) (mirrors the
cleanup-service memoryRetentionJob so the page and the forgetting job agree). The actual forgetting
runs in cleanup-service (ADR-069); this endpoint only reports.
Implementation: src/routes/requests.ts — router.get('/retention-policy') + resolveRetentionWindows().
GET /requests/:id (Sprint 101 — canonical viewer-aware detail)
Get specific request details. Sprint 101 makes this the canonical action surface: the response
derives viewer_relation server-side so the UI never guesses eligibility (and never shows an
Offer button that 403s on click).
viewer_relation: one ofown_request|already_offered|can_offer|not_actionable.can_offerrequires: askopen+expired = FALSE, not the viewer's own request, no liveproposed/matchedresponder match, AND the ask is within the viewer's visibility audience (getRequestReachability— member, trust_network/platform scope, or sister-reachable; the same boundaryPOST /matchesenforces).- Eligibility follows feed visibility, not membership and not "any UUID": a reachable open ask
in another community (trust-network / platform / sister) is
can_offer, but a community-scoped ask the viewer can't see isnot_actionable(no fake Offer button on something outside their audience). The feed's stochastic ranking within the visible set is not re-gated. - Expired-open / completed / cancelled / matched / out-of-audience asks resolve to
not_actionable.
- Read gate (Sprint 133, BUG-056): the response is returned only when the caller is the requester,
a responder on any-status match (
viewer_any_match; a completed helper keeps access after leaving the community), the pre-selected provider (viewer_is_preferred_provider), in a directed ask's audience (SQL predicate), or reachable. Otherwise 404 with the same body as a missing id. Norequester_email; the internalviewer_any_match/viewer_is_preferred_providercolumns are stripped. viewer_match:{ id, status }whenalready_offered, elsenull.viewer_partners(Sprint 134 PR B, ADR-100 amendment): always present, default[]. One entry per completed match on this request in which the viewer is the requester or that match's responder:{ match_id, user_id, name, completed_at, rated_by_me, rating_community_id }, orderedcompleted_at DESC NULLS LAST, match_id DESC, at most 20 (completed_atis sent as a UTC instant with an offset; the column istimestamp without time zone). The partner is the responder when the viewer is the requester, else the requester, so a helper never sees another helper. A rejected/cancelled helper, the preferred provider and any reading member get[](read permission is not partner status).rated_by_me= the viewer has afeedback.feedbackrow for that match;rating_community_id=MIN(request community), the rate decision's rule (nullhides the rating prompt). Several completed matches can exist (BUG-074); the page rates per match and vouches once per partner.payload_type: ADR-067 fine subtype fromcategory(drives the detail page's payload renderer).- The detail query now selects
r.expiredand no longer filtersexpired = FALSEin theWHERE, so expired-open asks return for finite-state display (previously 404'd).
Response:
{
"success": true,
"data": {
"id": "uuid",
"title": "Need help moving furniture",
"description": "Moving couch upstairs",
"category": "moving",
"urgency": "medium",
"status": "open",
"expired": false,
"requester_id": "uuid",
"requester_name": "Alice Smith",
"community_id": "uuid",
"community_name": "Seattle Mutual Aid",
"payload_type": "moving_help",
"viewer_relation": "can_offer",
"viewer_match": null,
"viewer_partners": [],
"created_at": "2025-01-10T12:00:00Z"
}
}
Implementation: src/routes/requests.ts — router.get('/:id').
POST /requests (v9.0 Polymorphic + ADR-022 Visibility)
Create new polymorphic help request (supports 5 types) with visibility scope.
Request (Generic):
{
"community_id": "uuid",
"request_type": "generic",
"title": "Need help moving furniture",
"description": "Moving couch upstairs, need 2-3 strong people",
"urgency": "medium",
"payload": {},
"visibility_scope": "community",
"visibility_max_degrees": 3
}
Visibility Fields (ADR-022):
visibility_scope- One of:community(default),trust_network,platform. Falls back to community'sdefault_request_scopeif omitted.visibility_max_degrees- Max trust hops for trust_network scope (1-6, default: 3)
Request (Service - Plumbing):
{
"community_id": "uuid",
"request_type": "service",
"title": "Need plumber for leak repair",
"description": "Kitchen pipe leaking, needs professional help",
"urgency": "high",
"payload": {
"service_category": "plumbing",
"skill_level_required": "intermediate",
"estimated_duration_hours": 2,
"budget_range": {
"min": 50,
"max": 100,
"currency": "USD"
},
"location_type": "on_site",
"certifications_required": ["Licensed Plumber"]
}
}
Request (Ride):
{
"community_id": "uuid",
"request_type": "ride",
"title": "Need ride to airport",
"description": "Flying out tomorrow morning",
"urgency": "medium",
"payload": {
"origin": {
"address": "123 Main St, Seattle, WA",
"lat": 47.6062,
"lng": -122.3321
},
"destination": {
"address": "SEA Airport",
"lat": 47.4502,
"lng": -122.3088
},
"seats_needed": 1,
"departure_time": "2024-06-15T10:00:00Z",
"preferences": {
"pet_friendly": false,
"luggage_space": "medium"
}
}
}
Multi-Community Posting (v9.0):
{
"post_to_all_communities": true,
"request_type": "generic",
"title": "Need general help",
"description": "..."
}
Validation:
- User must be active member of community (or all communities if post_to_all_communities)
- request_type must be one of: generic, ride, service, event, borrow
- payload must conform to type-specific Zod schema (see Section 3.6)
- Required fields:
community_id,requester_id,title,type
Validation under zod 4 (Sprint 131 D6, 2026-09-24). @karmyq/shared moved from zod 3 to zod 4.
The 400 envelope is unchanged: message is still Invalid request data: <path> — <first issue message>,
and errors is still validation.error.format(), with the same tree shape, issue paths and custom
messages. What changed:
- Default message copy (I4). A field with no custom message now carries zod 4's text and code.
Example, missing
title:RequiredbecameInvalid input: expected string, received undefined. Alsoinvalid_enum_value→invalid_value, andinvalid_string→invalid_format. - Newly rejected:
- text that is short in code points, e.g. a 3-emoji
titleagainstmin(5)(I1); - datetimes without seconds, e.g.
2026-10-01T10:00Z(I2); - non-finite numbers, e.g. JSON
1e400(I3); - integers above
Number.MAX_SAFE_INTEGERin.int()fields, e.g.roles[].count(I5).
- text that is short in code points, e.g. a 3-emoji
- Newly accepted: astral-heavy text within a
.max()bound counted in code points, e.g. 30 emoji inroles[].role_name(max(50)) (I1′).
Pinned by packages/shared/src/schemas/requests/__tests__/zod4-request-contract.test.ts.
Response:
{
"success": true,
"data": {
"id": "uuid",
"title": "Need help moving furniture",
"category": "moving",
"urgency": "high",
"status": "open",
"created_at": "2025-01-10T12:00:00Z"
},
"message": "Request created successfully"
}
Events Published: request_created (includes service_type field since Sprint 37 — notification-service uses this to route provider_request_matched to matching providers)
Implementation: src/routes/requests.ts:173
PUT /requests/:id
Update help request (requester only).
Request:
{
"user_id": "uuid",
"title": "Updated title",
"description": "Updated description",
"urgency": "low"
}
Authorization: Only the original requester can update
Refusal (Sprint 135, BUG-075): a body status is refused with 400 STATUS_NOT_EDITABLE ("A request's status
changes through its exchanges, not an edit"). It is checked after the ownership lookup, so a foreign or absent id still
answers 404. Nothing is written or published on a refusal.
Refusal (Sprint 137, BUG-091): after those two checks the edit runs in one transaction under the request lock
(lockRequest). A completed or cancelled ask answers 409 REQUEST_CLOSED ("A completed or cancelled request can't
be edited") before any write; a request that vanished under the lock answers 404. The UPDATE also requires
content_forgotten_at IS NULL, and a zero-row result returns the same 409, so nothing is written over a forgotten
ask's sentinel. Open, matched and dibs-pending asks stay editable.
Events Published: none from the status. request_completed is no longer published (Sprint 135).
Implementation: src/routes/requests.ts:1975
DELETE /requests/:id
Cancel help request (requester only). The caller is the JWT user; no body. A body user_id is
ignored (BUG-061). Non-requester → 403; no JWT identity → 401.
Sprint 135 (BUG-075): the cancel is decided on the request's derived status under the request lock (a pending dibs
on the ask is locked first). Only an open or dibs_pending request cancels:
- 409
REQUEST_NOT_CANCELLABLE("Only an open request can be cancelled") for acompletedorcancelledrequest; - 409
REQUEST_HAS_ACTIVE_EXCHANGE("This request has an exchange in progress, so it cannot be cancelled") for amatchedone.
A cancel that happens is markRequestCancelled (bound to the JWT requester), then closeProposals (every open proposal
is rejected, its offer freed only while matched), then the ask's pending dibs is expired in the same transaction,
with no event: it leaves the provider's pending list, and an accept or decline then answers 409 INVALID_STATE. The expiry is FOR UPDATE SKIP LOCKED, so a dibs another transaction holds is skipped
(the request lock is already held, so it must not wait): it stays pending on the cancelled ask, its accept then
refuses 409 REQUEST_NOT_OPEN, and cleanup-service expires it at expires_at. Every
refusal is decided before the first write.
Events Published: request_cancelled (only for a cancel that happened)
Implementation: src/routes/requests.ts:2056
PUT /requests/:id/privacy
Update privacy settings for a request (Social Karma v2.0).
Request:
{
"user_id": "uuid",
"is_public": true,
"requester_visibility_consent": true
}
Authorization: Only requester can update their request privacy
Events Published: privacy_settings.updated
Implementation: src/routes/requests.ts (Social Karma v2.0)
3.6 Polymorphic Request Type Schemas (v9.0)
This section documents the payload structure for each request type. All payloads are validated using Zod discriminated unions in packages/shared/src/schemas/requests/.
Generic Request
The default request type for simple help requests.
Payload Schema:
{
request_type: 'generic',
payload: {} // Empty object, no type-specific fields
}
Example:
{
"request_type": "generic",
"title": "Need help moving furniture",
"description": "Moving couch upstairs, need 2-3 people",
"urgency": "medium",
"payload": {}
}
Ride Request
For transportation help (rides, carpools, etc.).
Payload Schema:
{
request_type: 'ride',
payload: {
origin: {
address: string, // Human-readable address
lat: number, // Latitude (-90 to 90)
lng: number // Longitude (-180 to 180)
},
destination: {
address: string,
lat: number,
lng: number
},
seats_needed: number, // 1-10
departure_time: string, // ISO 8601 timestamp
preferences?: { // Optional
pet_friendly?: boolean,
luggage_space?: 'small' | 'medium' | 'large',
wheelchair_accessible?: boolean
}
}
}
Example:
{
"request_type": "ride",
"title": "Need ride to airport",
"description": "Flying out tomorrow morning",
"urgency": "medium",
"payload": {
"origin": {
"address": "123 Main St, Seattle, WA",
"lat": 47.6062,
"lng": -122.3321
},
"destination": {
"address": "SEA Airport",
"lat": 47.4502,
"lng": -122.3088
},
"seats_needed": 1,
"departure_time": "2024-06-15T10:00:00Z",
"preferences": {
"pet_friendly": false,
"luggage_space": "medium"
}
}
}
Borrow Request
For borrowing items from community members.
Payload Schema:
{
request_type: 'borrow',
payload: {
item_category: 'tools' | 'electronics' | 'furniture' | 'vehicles' |
'sports_equipment' | 'books' | 'clothing' | 'kitchen' | 'other',
item_description: string,
duration_days: number, // 1-30 days
return_date?: string, // ISO 8601 date (optional)
condition_min?: 'any' | 'good' | 'excellent', // Optional
images?: string[] // Array of image URLs (optional)
}
}
Example:
{
"request_type": "borrow",
"title": "Need ladder for weekend",
"description": "Painting exterior walls, need 6-8ft ladder",
"urgency": "low",
"payload": {
"item_category": "tools",
"item_description": "Extension ladder, 6-8 feet",
"duration_days": 2,
"return_date": "2024-06-17",
"condition_min": "good"
}
}
Service Request
For professional or skilled services.
Payload Schema:
{
request_type: 'service',
payload: {
service_category: 'plumbing' | 'electrical' | 'carpentry' | 'tutoring' |
'tech_support' | 'cleaning' | 'pet_care' | 'childcare' |
'landscaping' | 'photography' | 'legal' | 'financial' | 'other',
skill_level_required: 'beginner' | 'intermediate' | 'expert',
estimated_duration_hours?: number, // Optional
budget_range?: { // Optional
min: number,
max: number,
currency: string // e.g., 'USD'
},
location_type: 'on_site' | 'remote' | 'flexible',
preferred_schedule?: { // Optional
days: string[], // e.g., ['monday', 'tuesday']
times: string[] // e.g., ['morning', 'afternoon']
},
certifications_required?: string[] // Optional
}
}
Example:
{
"request_type": "service",
"title": "Need plumber for leak repair",
"description": "Kitchen pipe leaking, needs professional help",
"urgency": "high",
"payload": {
"service_category": "plumbing",
"skill_level_required": "intermediate",
"estimated_duration_hours": 2,
"budget_range": {
"min": 50,
"max": 100,
"currency": "USD"
},
"location_type": "on_site",
"certifications_required": ["Licensed Plumber"]
}
}
Event Request
For community events needing volunteers or participants.
Payload Schema:
{
request_type: 'event',
payload: {
event_type: 'volunteer' | 'social' | 'educational' | 'fundraiser' | 'meeting' | 'other',
event_date: string, // ISO 8601 timestamp
event_duration_hours?: number, // Optional
participants_needed: number, // 1-1000
location: {
is_virtual: boolean,
address?: string, // Required if not virtual
lat?: number, // Required if not virtual
lng?: number, // Required if not virtual
virtual_link?: string // Required if virtual
},
roles?: Array<{ // Optional
name: string,
count: number,
description: string
}>,
recurring?: { // Optional
frequency: 'daily' | 'weekly' | 'monthly',
end_date: string
}
}
}
Example (Physical Event):
{
"request_type": "event",
"title": "Community Garden Cleanup",
"description": "Monthly garden maintenance day",
"urgency": "low",
"payload": {
"event_type": "volunteer",
"event_date": "2024-06-20T09:00:00Z",
"event_duration_hours": 3,
"participants_needed": 10,
"location": {
"is_virtual": false,
"address": "456 Park Ave, Seattle, WA",
"lat": 47.6097,
"lng": -122.3331
},
"roles": [
{
"name": "Weeding",
"count": 5,
"description": "Help remove weeds"
},
{
"name": "Planting",
"count": 5,
"description": "Plant new flowers"
}
]
}
}
Example (Virtual Event):
{
"request_type": "event",
"title": "Online Tutoring Session",
"description": "Math help for high school students",
"urgency": "medium",
"payload": {
"event_type": "educational",
"event_date": "2024-06-18T18:00:00Z",
"event_duration_hours": 1,
"participants_needed": 2,
"location": {
"is_virtual": true,
"virtual_link": "https://zoom.us/j/123456789"
}
}
}
Validation Rules (All Types)
All polymorphic requests are validated using Zod discriminated unions. The request_type field acts as the discriminator, and TypeScript/Zod ensures the payload structure matches the selected type.
Validation Files:
packages/shared/src/schemas/requests/index.ts- Discriminated unionpackages/shared/src/schemas/requests/generic.ts- Generic schemapackages/shared/src/schemas/requests/ride.ts- Ride schemapackages/shared/src/schemas/requests/borrow.ts- Borrow schemapackages/shared/src/schemas/requests/service.ts- Service schemapackages/shared/src/schemas/requests/event.ts- Event schema
Type Guards:
import { isRideRequest, isBorrowRequest, isServiceRequest,
isEventRequest, isGenericRequest } from '@karmyq/shared/schemas/requests';
// Runtime type narrowing
if (isRideRequest(request)) {
// TypeScript knows request.payload has origin, destination, etc.
const distance = calculateDistance(
request.payload.origin,
request.payload.destination
);
}
Validation Example:
import { validateRequest } from '@karmyq/shared/schemas/requests';
const result = validateRequest({
request_type: 'service',
title: 'Need plumber',
description: 'Leak repair',
payload: {
service_category: 'plumbing',
skill_level_required: 'intermediate',
location_type: 'on_site'
}
});
if (result.success) {
// result.data is fully typed
console.log(result.data.payload.service_category);
} else {
// result.error contains Zod validation errors
console.error(result.error.errors);
}
PATCH /requests/:id/admin-triage
Override request urgency and/or add a community-scoped admin note (Sprint 25).
Auth: Caller must be an active admin or moderator of the community the request belongs to.
Request:
{
"community_id": "uuid",
"urgency": "high",
"note": "Escalated — requester confirmed no transport available"
}
community_id(required) - The community context for the triage actionurgency(optional) - One of'low','medium','high','critical'. Updateshelp_requests.urgencywhen provided.note(optional) - Free-text admin note. Upsertsrequests.request_admin_notes(one note per request per community).
At least one of urgency or note must be provided (400 if neither is present).
Response:
{ "message": "Triage saved" }
Errors:
400— Neitherurgencynornoteprovided403— Caller is not an admin or moderator of the request's community
Implementation: src/routes/requests.ts (Sprint 25)
POST /requests/:id/boost
Boost a request for 48 hours, adding a +0.3 feed score bonus via the request-service feed ranker (Sprint 36). Admin or moderator.
Auth: Caller must be an active admin or moderator of the community (Sprint 64).
Request:
{
"community_id": "uuid"
}
Response:
{
"success": true,
"message": "Request boosted",
"data": {
"id": "uuid",
"is_boosted": true,
"boosted_at": "2026-03-23T10:00:00Z",
"boosted_expires_at": "2026-03-25T10:00:00Z"
}
}
Sets is_boosted=TRUE, boosted_at=NOW(), boosted_expires_at=NOW()+48h, boosted_by=<caller>.
Errors:
403— Caller is not an admin or moderator of the community
Implementation: src/routes/adminActions.ts
DELETE /requests/:id/boost
Remove an active boost from a request (Sprint 36). Admin or moderator.
Auth: Caller must be an active admin or moderator of the community (Sprint 64).
Query Parameters:
community_id(UUID, required)
Response:
{
"success": true,
"message": "Boost removed"
}
Clears is_boosted, boosted_at, boosted_expires_at, and boosted_by.
Implementation: src/routes/adminActions.ts
POST /requests/:id/propose-match
Admin proposes a specific community member as a helper (Sprint 36). Creates a real requests.matches row with status='proposed'.
Auth: Caller must be an active admin of the community.
Request:
{
"user_id": "uuid",
"community_id": "uuid"
}
Response:
{
"success": true,
"message": "Match proposed",
"data": {
"match_id": "uuid",
"request_id": "uuid",
"responder_id": "uuid",
"status": "proposed"
}
}
Errors:
403— Caller is not an admin of the community404— Request or user not found409REQUEST_NOT_OPEN("This request is no longer open") — Sprint 135 (BUG-075): the request must deriveopenunder the request lock; the duplicate check and the insert run in the same transaction. A proposed match that already exists for the user is a 409 without a code, as before.
Implementation: src/routes/adminActions.ts:95
PATCH /requests/:id/urgent
Toggle request urgency between urgent and medium (Sprint 36). Admin only.
Auth: Caller must be an active admin of the community.
Request:
{
"urgent": true,
"community_id": "uuid"
}
urgent: true— setsurgency='urgent'urgent: false— setsurgency='medium'
Response:
{
"success": true,
"message": "Urgency updated",
"data": {
"id": "uuid",
"urgency": "urgent"
}
}
Errors:
403— Caller is not an admin of the community
Implementation: src/routes/adminActions.ts
3.2 Help Offers
Visibility boundary (BUG-064, Sprint 133 PR V): a standing offer is readable by its offerer and by live
(status = 'active') members of its community, decided in SQL by offerReadableSql. is_public and
offerer_visibility_consent are not consulted. A foreign offer answers exactly like a missing id on every route:
GET /offers/:id, PUT/DELETE /offers/:id, PUT /offers/:id/privacy (all 404 Offer not found) and
POST /matches with an offer_id that is not the caller's (404 Offer not found; only the owner reaches the
400 Offer is not active check).
GET /offers
Get the help offers the caller may read (their own, or their live communities' offers), with optional filters.
Query Parameters: community_id (narrows within the boundary, never widens it), status (default
active; the exact value all lists every status), type, limit, offset.
status=all (Sprint 140, BUG-099): the status predicate is ($1::text IS NULL OR o.status = $1), and exactly
all binds NULL. $1 stays the status and $2 the viewer for every request, and community_id/type/limit/
offset keep numbering from $3. Omitted still means active; every other value (unknown ones and ALL
included) keeps plain equality. The readable boundary and the expiry rule below are unchanged outer ANDs, so
all never shows an outsider's row or another member's expired active offer. Tests:
tests/regression/sprint-140-offer-status-all.test.ts (SQL/params) and root
tests/integration/sprint-140-offer-status-all.integration.test.ts (real rows).
Expiry hides an ACTIVE offer from other members only (Sprint 139, BUG-097; narrows Sprint 138's BUG-096): a
flagged or elapsed offer is left out of the list only when it is active AND the caller is not its offerer. Its owner
still sees it, and a non-active offer (matched, withdrawn, ...) stays in that status's history whatever its expiry.
The readable boundary stays an outer AND, so neither bypass widens who can read a row. Visibility is not
eligibility: holding the offer for a new match still refuses an expired one. Each list item also carries
expires_at (string | null) and expired (boolean | null), additively; the { offers, count, total } envelope
is unchanged. GET /offers/:id is unchanged (it still answers status: 'active' for an expired offer — Sprint 138 F3).
Implementation: src/routes/offers.ts router.get('/')
GET /offers/:id
Get one offer the caller may read (their own, or a live community's); otherwise 404.
Implementation: src/routes/offers.ts router.get('/:id')
POST /offers
Create new help offer. The offerer is the JWT caller; a body offerer_id is ignored (BUG-061).
PUT /offers/:id and DELETE /offers/:id likewise authorize the JWT caller as the offerer.
Request:
{
"community_id": "uuid",
"title": "I can help with moving",
"description": "Available on weekends, have truck",
"type": "moving"
}
Events Published: offer.created
Implementation: src/routes/offers.ts:99
PUT /offers/:id
Edit an offer's title and description (offerer only; a body status is refused with 400 STATUS_NOT_EDITABLE, Sprint 137, BUG-089).
The offerer is the JWT caller. A foreign or missing id answers 404 Offer not found first. A body status is then
refused with 400 STATUS_NOT_EDITABLE ("An offer's status changes through its exchanges, not an edit"): offer
status moves only through
DELETE /offers/:id (withdraw) and the exchange paths in src/routes/matches.ts / src/db/requestStatus.ts. Nothing is
written on a refusal.
Implementation: src/routes/offers.ts router.put('/:id')
DELETE /offers/:id
Withdraw an offer (offerer only; foreign or missing id → 404 Offer not found), setting status = 'withdrawn' and publishing offer_withdrawn.
A withdrawn offer is never brought back by a later release.
Implementation: src/routes/offers.ts router.delete('/:id')
PUT /offers/:id/privacy
Update privacy settings for an offer (Social Karma v2.0).
Implementation: src/routes/offers.ts (Social Karma v2.0)
3.3 Matches
GET /matches
The caller's matches: always restricted to matches where the JWT caller is the requester, the
responder (BUG-057, Sprint 132 PR S). The filters below only narrow that set. A user_id
query param is accepted from older clients but ignored: the caller is always the subject. No JWT
identity → 401.
Query Parameters:
request_id- Filter by requestoffer_id- Filter by offerstatus- Filter by status
Implementation: src/routes/matches.ts:8
GET /matches/:id
Match details (including requester/helper email) for a participant only (requester or
responder). Anyone else gets 404, so existence is not leaked (BUG-057, Sprint 132 PR S). Locked by
tests/regression/sprint-132-match-participant-scope.test.ts and the root
tests/integration/sprint-132-security-authz.integration.test.ts.
Implementation: src/routes/matches.ts:69
POST /matches
Create a member's offer to help (a proposed match). The responder is the verified JWT identity
(ADR-064) — a responder_id in the body is ignored, so a stale tab or forged body can't offer as
another user. Admin-proposed matches use POST /requests/:id/propose-match (adminActions), not this
route.
Eligibility = the request's feed-VISIBILITY boundary, not membership and not "any UUID".
"If it can be shown in a feed, it should be eligible" — the operative clause is can be shown.
Visibility is the deterministic access boundary the requester chooses via visibility_scope
(community / trust_network / platform) plus sister-community links; the feed's stochastic
explore/exploit RANKING within that visible set is a separate concern and is NOT re-gated here. The
shared helper getRequestReachability(requestId, userId) (src/db/eligibility.ts) mirrors the
curated feed's visibility predicate and is used by BOTH this mutation and the can_offer read, so
they never diverge: a member of a request community (community scope), any viewer for
trust_network/platform scope, or a viewer reachable via an active sister-community link. A
community-scoped ask the viewer can't see is not offerable even with a direct id. On top of
visibility, the mutation enforces the lifecycle invariants below.
Request:
{
"request_id": "uuid",
"offer_id": "uuid"
}
Note: offer_id is optional (direct response without offer). Any responder_id in the body is
ignored — the responder is always the authenticated user.
Validation:
- Request must exist, be
open, and unexpired (expired = FALSE) → else400 REQUEST_NOT_OPEN - Responder cannot offer on their own request →
400 OWN_REQUEST - Request must be within the responder's visibility audience (member OR trust_network/platform
scope OR sister-reachable, via
getRequestReachability) → else403 REQUEST_NOT_REACHABLE. This blocks offering on a community-private ask by direct id while allowing cross-community offers on trust-network / platform / sister asks. - One live offer per responder per request (no existing
proposed/matchedmatch) → else409 ALREADY_OFFERED(matcheshas no unique(request_id, responder_id); checked again, exactly, under the lock) - Linked offer (if
offer_idprovided) must exist and belong to the responder (404 Offer not found), and beactiveand not flaggedexpired→ else400 OFFER_NOT_ACTIVE
Write (Sprint 136, BUG-084). The checks above are a fast path. The write is one transaction:
lockRequestForCommitment (closed or past expiry since the read → 409 REQUEST_NOT_OPEN), the duplicate check again
(409 ALREADY_OFFERED), the guarded offer hold UPDATE requests.help_offers SET status = 'matched' WHERE id = $1 AND offerer_id = $2 AND status = 'active' AND expired IS NOT TRUE AND (expires_at IS NULL OR expires_at > clock_timestamp()) (Sprint 137, BUG-089: the two expiry arms; a miss → 400 OFFER_NOT_ACTIVE, before anything is written), then the
proposed insert. Lock order request → offer; no help_offers writer holds an offer lock and then waits on the request.
Events Published: match.created
Implementation: src/routes/matches.ts — router.post('/').
PUT /matches/:id/accept
Accepts a proposed match (Sprint 135, BUG-075). Participant authorization is unchanged (JWT identity, ADR-064).
One transaction: lockRequest, then the guarded UPDATE ... WHERE status = 'proposed', then closeProposals (the
other proposals are rejected and their offers freed only while matched, BUG-078), then reconcileRequestStatus
(the request becomes matched).
Responses (new):
- 409
REQUEST_NOT_OPEN("This request is no longer open") when the request derivesdibs_pending,completedorcancelled. - 409
ALREADY_MATCHED("This request was just matched with someone else") when it derivesmatched, or the match leftproposedfirst. Unchanged.
A refusal writes and publishes nothing.
Implementation: src/routes/matches.ts:281
PUT /matches/:id/reject
Rejects or withdraws a proposed match; both participants may (Sprint 62). Sprint 135 (BUG-075, BUG-078): the request lock
is taken first, the UPDATE carries AND status = 'proposed' (409 MATCH_NOT_PROPOSED otherwise, unchanged), the
linked offer returns to active only while it is matched (a withdrawn offer stays withdrawn), and the request is
derived by reconcileRequestStatus instead of reopened. A completed, cancelled or dibs_pending request stays so.
Implementation: src/routes/matches.ts:427
PUT /matches/:id/complete
Two-phase match completion. Each party calls this independently; the match
only becomes completed and karma fires when both parties have confirmed.
Request: no body. Identity comes from the JWT (ADR-064); a legacy user_id in the body is ignored.
Response:
{
"success": true,
"data": {
"fully_completed": false,
"waiting_for": "helper"
},
"message": "Your completion recorded — waiting for the other party"
}
Authorization: Only requester or responder can complete
Other responses (Sprint 134 BUG-074):
- 200
Match already completed({ fully_completed: true, waiting_for: null }) for a match that is alreadycompleted, on the pre-read fast path and on the race path. Nothing is stamped or published again. - 409
{ success: false, message: 'Only an exchange in progress can be marked done', error: 'MATCH_NOT_COMPLETABLE' }for a proposed, rejected or cancelled match. - 404 when the caller is not a participant or the match does not exist.
A mark is recorded only on a matched match: the done_at UPDATE carries AND status = 'matched'. Sprint 135
(BUG-078): the stamp is COALESCE(done_at, CURRENT_TIMESTAMP), so a repeat mark keeps the first time and answers the same
200 "waiting".
Side Effects (first party only): Sets requester_done_at or responder_done_at timestamp
Side Effects (both parties): Sets status = 'completed', derives the request status with
reconcileRequestStatus (a cancelled request stays cancelled; one with another matched exchange stays matched),
then calls releaseOffer (Sprint 138, BUG-093; after the request is reconciled, lock
order match, request, offer): the standing offer the match used is freed (matched to active, flagged expired if
its expires_at has passed) unless another proposed or matched exchange still uses it; a withdrawn offer stays
withdrawn. All of this runs in one transaction; after it commits, match_completed is published.
Events Published: match_completed (only when both parties have confirmed)
Implementation: src/routes/matches.ts:525
Schema changes (migration 017): Added requester_done_at TIMESTAMP and responder_done_at TIMESTAMP to requests.matches
DELETE /matches/:id
Cancels an exchange in progress (Sprint 134 BUG-074).
Request: no body. Identity comes from the JWT (req.user!.userId, ADR-064).
Authorization: Only the requester or the responder (matchParticipantSql).
Responses:
- 200
{ success: true, message: 'Match cancelled successfully' } - 409
{ success: false, message: 'Only an exchange in progress can be cancelled', error: 'MATCH_NOT_CANCELLABLE' }for a proposed, completed, rejected or already-cancelled match. No state change, no event. A match one side has already marked done is stillmatchedand can be cancelled. - 404 when the caller is not a participant or the match does not exist.
End states: the match becomes cancelled. Sprint 135: the request status is derived by reconcileRequestStatus
(matched while another match is matched, completed if one is completed, dibs_pending while a dibs waits,
else open); a cancelled request stays cancelled. The linked offer returns to active only while it is
matched; a withdrawn offer stays withdrawn. Lock order is match row, then request row.
Events Published: match_cancelled, after commit and only for a cancel that happened. It is in
UNCONSUMED_EVENTS (packages/shared/events/routes.ts), so it is not enqueued and nobody is notified.
Implementation: src/routes/matches.ts:678 — router.delete('/:id'); the complete route is at :525 and the accept and
reject routes at :281 and :427.
3.3b Provider Offer Endpoints (Sprint 41)
GET /requests/:id/offers
List pending provider offers on a specific help request. Requester only.
Authentication: Required (JWT token)
Response:
{
"success": true,
"data": {
"offers": [
{
"id": "uuid",
"provider_id": "uuid",
"provider_user_id": "uuid",
"provider_email": "provider@example.com",
"request_id": "uuid",
"price": 50.00,
"note": "I can help this weekend",
"status": "pending",
"created_at": "2026-03-26T10:00:00Z"
}
]
}
}
Implementation: src/routes/providerOffers.ts
PUT /requests/offers/:id/accept
Accept a pending provider offer. Creates a match between the requester and the provider.
Authentication: Required (JWT token — must be the requester)
Response:
{
"success": true,
"message": "Offer accepted",
"data": { "match_id": "uuid" }
}
Sprint 135 (BUG-075): acceptOffer (src/db/offersDb.ts) now runs in one transaction: lockRequest, then the
offer UPDATE ... WHERE status = 'pending', the match insert, closeProposals and reconcileRequestStatus. A request
that is not open answers 409 REQUEST_NOT_OPEN ("This request is no longer open"); an offer that is no longer
pending (a lost race) answers 404 NOT_FOUND. A refusal writes nothing.
Events Published: offer_accepted
Implementation: src/routes/requesterOffers.ts:30, src/db/offersDb.ts
PUT /requests/offers/:id/decline
Decline a pending provider offer.
Authentication: Required (JWT token — must be the requester)
Response:
{
"success": true,
"message": "Offer declined"
}
Events Published: offer_declined
Implementation: src/routes/providerOffers.ts
POST /providers/offers
Submit a provider offer on an open help request.
Authentication: Required (JWT token — must be an active provider)
Request:
{
"request_id": "uuid",
"price": 50.00,
"note": "Available this weekend"
}
Response:
{
"success": true,
"data": { "id": "uuid", "status": "pending" },
"message": "Offer submitted"
}
Request lock (Sprint 137, BUG-090): after the provider-profile and reachability fast paths, the route runs one
transaction: lockRequestForCommitment (an ask that closed or expired since the fast path → 409
REQUEST_NOT_OPEN, "This request is no longer open", with no insert; one deleted since the fast path → 404
REQUEST_NOT_FOUND, "Request not found", with no insert), then the duplicate check (409 DUPLICATE_OFFER)
and the insert on the same transaction client. The requester lookup and offer_submitted run after commit.
Events Published: offer_submitted
Implementation: src/routes/providerOffers.ts
GET /providers/offers
List offers submitted by the authenticated provider.
Authentication: Required (JWT token)
Response:
{
"success": true,
"data": {
"offers": [
{
"id": "uuid",
"request_id": "uuid",
"request_title": "Need help with plumbing",
"price": 50.00,
"note": "Available this weekend",
"status": "pending",
"created_at": "2026-03-26T10:00:00Z"
}
]
}
}
Implementation: src/routes/providerOffers.ts
PUT /providers/offers/:id/withdraw
Withdraw a pending provider offer.
Authentication: Required (JWT token — must be the offer owner)
Response:
{
"success": true,
"message": "Offer withdrawn"
}
Implementation: src/routes/providerOffers.ts
3.3c Dibs Endpoints (Sprint 42)
Dibs is a private first-refusal window for any request type. All requests (scheduled and ASAP) are eligible for dibs as of Sprint 50.
Eligibility rules:
- For service requests (
type = 'service'): candidate must have a provider profile withis_available = trueandpriorInteractions >= 1 - For all other request types (mutual aid, ride, event, borrow, generic): any community member with
priorInteractions >= 1is eligible - Only one active dibs record per request (
UNIQUE(request_id))
Window formula:
- Scheduled:
expires_at = created_at + 0.20 × (scheduled_for − created_at) - ASAP / non-scheduled:
expires_at = created_at + 24h
Status flow (Sprint 135, BUG-075): open → dibs_pending → matched (accept) | derived again (decline/expire: open
unless something else holds the request). The request status is always derived by reconcileRequestStatus; every dibs
write is guarded on the dibs still being pending. While a dibs is pending the ask is not open, so it refuses other
offers (409 REQUEST_NOT_OPEN). Cancelling the ask expires the pending dibs, and the provider's later accept or decline
answers 409 INVALID_STATE.
GET /requests/:id/dibs-candidate
Returns the top-scored dibs candidate for any request. Accepts optional ?type= query param — type=service uses provider-profile candidates; any other value (or missing) uses mutual-aid candidates.
Candidate selection — two-tier explore/exploit (ADR-051, Sprint 51):
- Tier 1 (exploit): Prior interactions ≥ 1 + available. Preferred.
- Tier 2 (explore): 0 prior interactions +
trustGraphConnection = 'direct'(exchange connections only) + available. Fallback when Tier 1 is empty.
Mutual aid trust scores (Sprint 51): getMutualAidCandidates reads reputation.trust_scores via correlated subquery (MAX(score) across requester's communities, default 50). Previously hardcoded to 50.
Returns null if no eligible candidate exists in either tier.
Authentication: Required (JWT token — must be the requester)
Response (Sprint 52): includes trustPath fetched from social-graph-service.
{
"success": true,
"data": {
"provider_user_id": "uuid",
"provider_id": "uuid",
"match_score": 87,
"prior_interactions": 3,
"trustPath": {
"degrees_of_separation": 2,
"path": [{ "id": "...", "name": "You" }, { "id": "...", "name": "Jordan" }, { "id": "...", "name": "Alice" }],
"connection_type": "exchange"
}
}
}
trustPath is null if no path found or social-graph is unavailable (non-fatal degradation).
Returns "data": null when no eligible candidate is found.
The server-computed reason is prior_similar_success | trusted_neighbor | provider_match | community_connection
(ADR-072 + Sprint 93 addendum); community_connection covers a zero-history community neighbour.
deriveDibsReason lives in src/services/dibsReason.ts.
Implementation: src/routes/dibs.ts
POST /requests/:id/dibs
Send dibs to a specific provider or community member. Valid for all request types (scheduled and ASAP).
Authentication: Required (JWT token — must be the requester)
Request:
{
"provider_id": "uuid"
}
Response (201):
{
"success": true,
"data": {
"id": "uuid",
"request_id": "uuid",
"provider_user_id": "uuid",
"status": "pending",
"expires_at": "2026-03-28T14:00:00Z",
"created_at": "2026-03-28T13:00:00Z"
}
}
Errors:
400 ASAP_NOT_ELIGIBLE— Request has noscheduled_for403 NO_PRIOR_INTERACTION— Provider has no prior interaction with requester409 DIBS_ALREADY_SENT— A pending dibs record already exists for this request409 REQUEST_NOT_OPEN("Request is not available for dibs") — the request is notopen; also on a race, because the lock re-reads the derived status in the transaction (Sprint 135)
Events Published: dibs_submitted
Implementation: src/routes/dibs.ts
PUT /requests/dibs/:id/accept
Provider accepts dibs. Creates a requests.matches record directly and derives the request status (matched).
Sprint 135 (BUG-075): the dibs row is locked first (its status and liveness, expires_at > clock_timestamp()), then
the request. The request must derive dibs_pending; the dibs UPDATE is guarded on pending and on
expires_at > clock_timestamp(), because the wait for the request lock can cross the deadline (PR #327 review). Stale
proposed matches are closed (closeProposals) before the request is derived. Refusals, none of which write or publish:
- 409
REQUEST_NOT_OPEN("This request is no longer waiting on your dibs") - 409
INVALID_STATE("Dibs is no longer pending"; the pre-read says "Dibs is already <status>") - 410
DIBS_EXPIRED("This dibs invitation has expired"), also when it expires while waiting on the dibs lock or on the request lock
Authentication: Required (JWT token — must be the dibs provider)
Response:
{
"success": true,
"data": {
"dibs_status": "accepted",
"match_id": "uuid"
}
}
Events Published: dibs_accepted
Implementation: src/routes/dibs.ts
PUT /requests/dibs/:id/decline
Provider declines dibs. Derives the request status (open for public broadcast unless something else holds it; a
completed, cancelled or matched request is not reopened). Sprint 135: the dibs UPDATE is guarded on pending;
a lost race answers 409 INVALID_STATE ("Dibs is no longer pending").
Authentication: Required (JWT token — must be the dibs provider)
Response:
{
"success": true,
"data": {
"dibs_status": "declined"
}
}
Events Published: dibs_declined
Implementation: src/routes/dibs.ts
GET /requests/dibs/pending-for-provider
Returns the authenticated provider's pending dibs records (status = pending).
Authentication: Required (JWT token)
Response:
{
"success": true,
"data": [
{
"id": "uuid",
"request_id": "uuid",
"request_title": "Need help with plumbing",
"scheduled_for": "2026-03-30T10:00:00Z",
"expires_at": "2026-03-28T16:00:00Z",
"status": "pending"
}
]
}
Implementation: src/routes/dibs.ts
POST /requests/dibs/:id/expire
TEST-ONLY: Force-expire a dibs record regardless of expires_at. Sets status to expired (guarded on pending, as decline)
and derives the request status.
Authentication: Required (JWT token)
Response:
{
"success": true,
"data": {
"dibs_status": "expired"
}
}
Implementation: src/routes/dibs.ts
3.3d Feed View Layer (Sprint 91 / ADR-071)
The personalized activity feed was folded in from the decommissioned feed-service (Sprint 91,
ADR-071). feed-service was a pure read/view layer with no Bull queue, cron, or events, so its five
live endpoints now serve from request-service under /requests/feed/*. The composers + ranker live
in src/services/feed/ (feedComposer.ts, socialKarmaFeedComposer.ts, basicFeedRanker.ts); the
router is src/routes/feed.ts, mounted before the generic /requests router so it isn't
swallowed by GET /requests/:id, with rateLimiters.relaxed, authMiddleware,
optionalTenantMiddleware, and dbContextMiddleware(pool).
Schema ownership: request-service now owns the feed schema — feed.preferences and
feed.dismissed_items (no migration; the tables stayed in place). feed.featured_stories is
orphaned (it backed a dropped endpoint) and is left in place, not dropped (see ADR-071).
Social proximity: the ranker calls social-graph POST /paths/batch via SOCIAL_GRAPH_API_URL
(same convention as dibs.ts), forwarding the caller's Authorization header (the old
x-user-id shortcut was dropped). It degrades gracefully (no throw) when social-graph is unavailable.
Dropped endpoints: the four dead feed-service endpoints (GET /feed/requests,
GET /feed/milestones, GET /feed/featured-stories, GET /feed/mixed) were not carried over —
they had no frontend caller. They now 404 under request-service.
GET /requests/feed
Ranked personalized feed for the authenticated user. Items are sorted by the ranker's score (descending; stable for ties); dismissed items are excluded.
Authentication: Required (JWT token)
Query Parameters:
limit(number) - Max items (default: 20)
Response:
{
"success": true,
"data": {
"items": [ { "id": "request_uuid", "type": "open_request", "data": {} } ],
"count": 1
}
}
Implementation: src/routes/feed.ts + src/services/feed/basicFeedRanker.ts
GET /requests/feed/preferences
Return the caller's feed preferences; returns sensible defaults when no row exists.
Authentication: Required (JWT token)
Implementation: src/routes/feed.ts
PUT /requests/feed/preferences
Upsert the caller's feed preferences (round-trips with GET).
Authentication: Required (JWT token)
Implementation: src/routes/feed.ts
POST /requests/feed/dismiss/:itemId
Dismiss a feed item (writes feed.dismissed_items); the item is excluded from the next
GET /requests/feed. itemId is <item_type>_<id>. Canonical dismiss path (the old frontend
/feed/:itemId/dismiss was retired).
Authentication: Required (JWT token)
Implementation: src/routes/feed.ts
GET /requests/feed/community-health
Community health hero metrics for the CommunityHealthHero component. Requires community_id
(400 if missing); returns 404 for an unknown community.
Authentication: Required (JWT token). Members-only since Sprint 133 PR V (BUG-065): a caller
without a live communities.members row (or with a malformed id) gets 403 NOT_A_MEMBER. No web
surface renders CommunityHealthHero today.
Implementation: src/routes/feed.ts + src/services/feed/socialKarmaFeedComposer.ts
3.4 Interaction Feedback (retired, Sprint 134 PR L)
POST and GET /matches/:id/feedback were removed in Sprint 134 PR L (BUG-068). POST always failed: it selected
help_requests.community_id, which does not exist, so it never wrote requests.interaction_feedback or published
interaction_feedback_submitted, and GET could only return empty feedback. No client called either route. Both paths
now fall through to the app's 404 NOT_FOUND. Members rate each other through reputation-service
POST /reputation/feedback (ADR-036). The requests.interaction_feedback table is dropped in PR L2 (migration 20261027-drop-interaction-feedback.sql).
3.5 Health Check
GET /providers
List all provider profiles. Optional query param: service_type. Public (no auth required).
F1 (Sprint 93 / ADR-073): when called WITH a bearer token, each provider is annotated with
shared_communities: [{ id, name }] — the communities the provider and the viewer both belong to,
via a live communities.members join keyed on the signed JWT userId (not the JWT communities
claim, so a stale token can't badge a left community). Unauthenticated responses are unchanged (no
shared_communities field). No schema change.
GET /providers/my
Get the authenticated user's own provider profiles. Auth required.
GET /providers/:id
Get a single provider profile by ID, including ride details if applicable.
POST /providers
Create a provider profile for the authenticated user.
PUT /providers/:id
Update a provider profile. Owner only.
DELETE /providers/:id
Delete a provider profile. Owner only.
GET /collectives
List all provider collectives. Optional query param: service_type.
GET /collectives/my
Get collectives the authenticated user belongs to (via their provider profiles). Auth required.
GET /collectives/:id
Get a collective with members and communities served.
POST /collectives
Create a new provider collective.
PUT /collectives/:id
Update a collective. Collective admin only.
DELETE /collectives/:id
Delete a collective. Collective admin only.
POST /collectives/:id/members
Join a collective as a member.
DELETE /collectives/:id/members/:providerId
Remove a member from a collective. Collective admin only.
POST /collectives/:id/communities
Link a collective to a community.
DELETE /collectives/:id/communities/:communityId
Unlink a collective from a community. Auth: collective admin OR community admin (Sprint 26).
GET /collectives/:id/stats
Returns aggregate performance stats for a collective: total_requests_matched, fulfillment_rate, avg_completion_hours (null if no completed matches), communities_served_count, available_member_count. Auth required.
PATCH /providers/:providerId/availability
Toggle a provider's availability status. Body: { is_available: boolean }. Auth: owner only (provider_profiles.user_id must match JWT userId). Returns { id, is_available }. (Sprint 26)
GET /requests/providers/:providerId/rate-cards
List active rate cards for a provider (public). Owner can pass ?include_inactive=true to include deactivated cards.
POST /requests/providers/:providerId/rate-cards
Create a new rate card for a provider. Auth: owner only. Body: { label, pricing_model, rate_amount?, rate_unit?, currency?, notes? }.
PUT /requests/providers/:providerId/rate-cards/:cardId
Update an existing rate card. Auth: owner only.
DELETE /requests/providers/:providerId/rate-cards/:cardId
Soft-delete a rate card — sets is_active = false. Auth: owner only. Card remains in database for historical reference.
Note: POST /requests now accepts optional preferred_provider_id (UUID) in the request body, allowing a requestor to pre-select a provider when filing a typed request.
GET /health
Service health check.
Response:
{
"service": "request-service",
"status": "healthy",
"timestamp": "2025-01-10T12:00:00Z"
}
4. Events
4.1 Published Events
Sprint 133 PR Q (ADR-101). The table below is historical: its dotted names and payloads predate the code. The live list of what this service publishes is
services/registry.json(held to the source bytests/regression/sprint-133-pr-q-event-routes.test.ts), and each event's queue comes frompackages/shared/events/routes.ts.publishEventresolvesnullfor an unconsumed event and throws for an unclassified one.
| Event Name | Queue | Payload | When Emitted |
|---|---|---|---|
request.created | karmyq-events | { request_id, requester_id, community_id, category } | After successful request creation |
request.completed | karmyq-events | { request_id, requester_id, community_id } | No longer published (Sprint 135: its only publisher was the removed PUT /requests/:id status edit); still listed in UNCONSUMED_EVENTS |
request.cancelled | karmyq-events | { request_id, requester_id, community_id } | When request is cancelled |
offer.created | karmyq-events | { offer_id, offerer_id, community_id, category } | After successful offer creation |
match.created | karmyq-events | { match_id, request_id, offer_id, responder_id } | When request and responder are matched |
match.completed | karmyq-events | { match_id, request_id, responder_id, completed_at } | When match is marked as completed |
privacy_settings.updated | karmyq-events | { entity_type, entity_id, is_public, visibility_consent } | When request/offer privacy changes (Social Karma v2.0) |
4.2 Consumed Events
None currently. Request Service does not consume events.
Note: In v9.0 (Everything App), this service will consume:
user.verified- To unlock premium request types (rides, services)
4.3 Event Publishing Pattern
// src/routes/requests.ts
import { publishEvent } from '../events/publisher';
// After successful request creation
await publishEvent('request.created', {
request_id: newRequest.id,
requester_id: req.user.id,
community_id: req.community.id,
category: newRequest.category
});
5. Key Patterns
5.1 Authentication & Authorization Flow
Standard Auth Pattern:
// All routes protected with auth middleware
router.post('/requests',
authenticateToken, // Verify JWT
extractCommunityContext, // Set req.community
requireRole('member'), // Check minimum role
async (req, res) => { ... }
);
Membership Verification:
// Verify user is active community member before allowing post
const memberCheck = await db.query(
`SELECT id FROM communities.members
WHERE community_id = $1 AND user_id = $2 AND status = 'active'`,
[community_id, requester_id]
);
if (memberCheck.rowCount === 0) {
return res.status(403).json({
success: false,
message: 'Only community members can post requests'
});
}
Requester-Only Updates:
// Only original requester can update/cancel their request
const requestCheck = await db.query(
`SELECT requester_id FROM requests.help_requests WHERE id = $1`,
[id]
);
if (requestCheck.rows[0].requester_id !== user_id) {
return res.status(403).json({
success: false,
message: 'Only the requester can update this request'
});
}
5.2 Skill-Based Matching Algorithm
Category-to-Skill Mapping:
| Category | Matched Skills |
|---|---|
| transportation | driving |
| moving | moving, handyman |
| childcare | childcare |
| pet_care | pet_care |
| tech_support | tech_support, coding |
| home_repair | home_repair, handyman, electrical, plumbing, carpentry |
| gardening | gardening |
| cooking | cooking, baking |
| tutoring | tutoring |
| language | languages |
| professional_advice | career_advice |
| cleaning | cleaning, organizing |
Matching Query Pattern:
SELECT
r.id, r.title, r.category, r.urgency,
CASE
WHEN r.urgency = 'high' THEN 3
WHEN r.urgency = 'medium' THEN 2
ELSE 1
END as urgency_priority,
c.name as community_name,
u.name as requester_name,
r.created_at
FROM requests.help_requests r
INNER JOIN communities.communities c ON r.community_id = c.id
INNER JOIN auth.users u ON r.requester_id = u.id
WHERE r.status = 'open'
AND r.requester_id != $1 -- Exclude user's own requests
AND EXISTS (
SELECT 1 FROM communities.members m
WHERE m.user_id = $1
AND m.community_id = r.community_id
AND m.status = 'active' -- Only user's communities
)
AND EXISTS (
SELECT 1 FROM auth.user_tags s
WHERE s.user_id = $1 AND s.tag_type = 'skill'
AND (
(r.category = 'moving' AND s.skill_slug IN ('moving', 'handyman'))
OR (r.category = 'tech_support' AND s.skill_slug IN ('tech_support', 'coding'))
-- ... other category mappings
)
)
ORDER BY urgency_priority DESC, r.created_at ASC
LIMIT $2;
5.3 Database Query Pattern (RLS-Aware)
// All queries respect community_id for multi-tenant isolation
const result = await db.query(
`SELECT * FROM requests.help_requests
WHERE community_id = $1 AND status = $2`,
[req.community.id, 'open']
);
5.4 Event Publishing Pattern
// Publish event after successful database operation
const newRequest = await db.query(
'INSERT INTO requests.help_requests (...) VALUES (...) RETURNING *',
[...]
);
// Fire and forget (don't block response)
await publishEvent('request.created', {
request_id: newRequest.rows[0].id,
requester_id: req.user.id,
community_id: req.community.id
});
return res.status(201).json({
success: true,
data: newRequest.rows[0]
});
6. Dependencies
6.1 Upstream Services (This service calls)
- Community Service (via database) - Verify community membership
- Auth Service (via database) - Get user details and skills
- Social Graph Service (internal HTTP) - Strict reciprocal identity/topology for an authorized request/offer pair; 2.5-second timeout and fail-soft read only
6.2 Downstream Services (This service is called by)
- Gateway - All client requests route through gateway
- Frontend (Web) - For browsing/creating requests and offers
- Frontend (Mobile) - Mobile app access
- Feed Service - Reads open requests for personalized feed
6.3 Event Consumers (Who listens to our events)
- Reputation Service - Listens to
match.completed→ Awards karma - Notification Service - Listens to
request.created→ Notifies community - Feed Service - Listens to
request.created→ Updates feed
6.4 Shared Libraries
@karmyq/shared/middleware-authenticateToken,extractCommunityContext,requireRole@karmyq/shared/utils/logger- Structured logging@karmyq/shared/database- PostgreSQL connection utilities@karmyq/shared/schemas/requests- Zod validation schemas for polymorphic requests (v9.0)@karmyq/shared/matching- Match scoring,resolveSourceTier(),DEFAULT_FEED_PREFERENCES, feed scoring utilities (ADR-031)
7. Testing
7.1 Unit Tests
Run Tests:
cd services/request-service
npm test
Test Structure:
src/__tests__/
├── requests.test.ts # Request CRUD and matching
├── offers.test.ts # Offer CRUD
└── matches.test.ts # Match creation and completion
7.2 Integration Tests
Run Integration Tests:
cd tests
npm run test:integration -- integration/request-service.test.ts
Test Scenarios:
- Request lifecycle (create → match → complete)
- Skill-based matching algorithm
- Privacy controls (Social Karma v2.0)
- Event publishing
7.3 Test Fixtures
Test Personas:
tests/fixtures/quick-seed.sql- 7 test personastests/fixtures/large-dataset.sql- 2000 users, realistic data
Mock Data:
// Example test request
const testRequest = {
community_id: 'test-community-uuid',
requester_id: 'test-user-uuid',
title: 'Test: Need help moving',
description: 'Moving couch upstairs',
type: 'moving',
urgency: 'high'
};
7.4 Key Test Scenarios
Generic Requests (v8.0 - Legacy Tests):
- Create generic request successfully
- Reject request with missing required fields
- Only requester can update their request
- User cannot match their own request
- Skill-based matching returns relevant requests
- Privacy settings update correctly
- Two-way consent logic works correctly
Polymorphic Requests (v9.0 - Production):
- Create generic request (backward compatibility) -
tests/integration/polymorphic-requests-lifecycle.test.ts - Create ride request with valid coordinates -
tests/integration/polymorphic-requests-lifecycle.test.ts - Create service request with skill requirements -
tests/integration/polymorphic-requests-lifecycle.test.ts - Create event request (physical + virtual) -
tests/integration/polymorphic-requests-lifecycle.test.ts - Create borrow request with item details -
tests/integration/polymorphic-requests-lifecycle.test.ts - Reject ride request with invalid coordinates -
tests/unit/validation.test.ts - Validate payload against Zod schema -
tests/unit/validation.test.ts - Emit
request.createdwithrequest_typefield -tests/integration/events.test.ts - Multi-community posting with post_to_all_communities -
tests/integration/polymorphic-requests-lifecycle.test.ts
Curated Feed & Matching (v9.0 - Production):
- Calculate match scores for all 5 request types -
tests/unit/curated-feed.test.ts(69 tests) - Filter by user skills and preferences -
tests/integration/curated-feed-preferences.test.ts - Sort by match score descending -
tests/unit/curated-feed.test.ts - Apply minimum match score threshold -
tests/integration/curated-feed-preferences.test.ts - Return match reasons and breakdown -
tests/unit/curated-feed.test.ts - Respect user request type subscriptions -
tests/integration/curated-feed-preferences.test.ts
User Preferences (v9.0 - Production):
- Subscribe/unsubscribe from request types -
tests/integration/curated-feed-preferences.test.ts - Add/remove user interests -
tests/integration/curated-feed-preferences.test.ts - Persist preferences across sessions -
tests/integration/curated-feed-preferences.test.ts - Filter curated feed by preferences -
tests/integration/curated-feed-preferences.test.ts
UX & Smart Defaults (v9.0 - Production):
- Generic type shown by default -
tests/unit/smart-defaults.test.tsx - Type selector collapsible (progressive disclosure) -
tests/unit/smart-defaults.test.tsx - Create generic request in < 3 clicks -
tests/e2e/12-polymorphic-requests-ux.spec.ts - Display match scores on request cards -
tests/e2e/12-polymorphic-requests-ux.spec.ts - Toggle between all requests and curated feed -
tests/e2e/12-polymorphic-requests-ux.spec.ts
Event Publishing:
-
request.createdevent published on creation -
match.completedevent published on completion - Events include all required payload fields
7.5 Manual Testing with curl
Create Request:
curl -X POST http://localhost:3003/requests \
-H "Content-Type: application/json" \
-d '{
"community_id": "uuid-here",
"requester_id": "uuid-here",
"title": "Need help moving couch",
"description": "Heavy couch, need 2-3 people",
"type": "moving",
"urgency": "high"
}'
Complete Match:
curl -X PUT http://localhost:3003/matches/uuid-here \
-H "Content-Type: application/json" \
-d '{
"status": "completed",
"user_id": "uuid-here"
}'
8. Configuration
8.1 Environment Variables
# Server
PORT=3003
NODE_ENV=development # development | production
# Database
DATABASE_URL=postgresql://karmyq_user:password@localhost:5432/karmyq_db
# Redis (for events)
REDIS_URL=redis://localhost:6379
# Logging
LOG_LEVEL=info # debug | info | warn | error
8.2 Feature Flags
Current (v8.0):
- All features enabled by default
Planned (v9.0 - Everything App):
# Feature flags for new verticals
ENABLE_RIDE_REQUESTS=false
ENABLE_BORROW_REQUESTS=false
ENABLE_SERVICE_REQUESTS=false
ENABLE_EVENT_REQUESTS=false
8.3 Database Connection Pool
// src/database/db.ts
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 20, // Maximum connections
idleTimeoutMillis: 30000, // Close idle connections after 30s
connectionTimeoutMillis: 2000
});
9. Monitoring & Observability
9.1 Key Metrics
Request Metrics:
- Total requests created (counter)
- Requests by category (counter with labels)
- Requests by urgency (counter with labels)
- Open requests count (gauge)
Match Metrics:
- Matches created (counter)
- Matches completed (counter)
- Time to first match (histogram)
API Performance:
- Request latency (histogram)
- Error rate (counter)
- Throughput (requests/second)
9.2 Logging
Structured JSON Logging:
import { logger } from '@karmyq/shared/utils/logger';
logger.info('Request created', {
request_id: newRequest.id,
requester_id: req.user.id,
community_id: req.community.id,
category: newRequest.category
});
logger.error('Failed to create request', {
error: err.message,
stack: err.stack,
requester_id: req.user.id
});
Log Levels:
DEBUG- Detailed query logs, matching algorithm stepsINFO- Request creation, match completionWARN- Invalid input, failed validationsERROR- Database errors, event publishing failures
9.3 Health Checks
Endpoint: GET /health
Health Check Logic:
// src/routes/health.ts
router.get('/health', async (req, res) => {
try {
// Check database connection
await db.query('SELECT 1');
// Check Redis connection
await redis.ping();
res.json({
service: 'request-service',
status: 'healthy',
timestamp: new Date().toISOString(),
checks: {
database: 'connected',
redis: 'connected'
}
});
} catch (error) {
res.status(503).json({
service: 'request-service',
status: 'unhealthy',
error: error.message
});
}
});
Monitoring Alerts:
- Database connection failures
- Redis connection failures
- High error rate (>5% of requests)
- High latency (P95 > 500ms)
10. Troubleshooting
10.1 Common Issues
Issue: Skill-based matching returns no results
Symptoms: The curated feed has no matching results
Diagnosis:
-
Check user has skills:
SELECT * FROM auth.user_tags WHERE user_id = 'uuid-here' AND tag_type = 'skill'; -
Check user is member of communities:
SELECT * FROM communities.members WHERE user_id = 'uuid-here' AND status = 'active'; -
Check requests exist in those communities:
SELECT * FROM requests.help_requests WHERE community_id IN (...) AND status = 'open'; -
Verify category-to-skill mapping matches user's skills
-
Ensure user is not the requester (excluded from results)
Solution:
- Add skills through
POST /auth/profile/tagsso the vocabulary resolver setsskill_slug. - Ensure user joined communities
- Verify skill mapping in Section 5.2
Issue: Request not appearing in list
Symptoms: Request exists but not in GET /requests response
Diagnosis:
-
Check request status:
SELECT status FROM requests.help_requests WHERE id = 'uuid-here'; -
Verify
community_idfilter if applied -
Check pagination (limit/offset)
-
Verify request hasn't been soft-deleted
Solution:
- Use correct status filter
- Increase limit or adjust offset
- Check all status values:
open,matched,completed,cancelled
Issue: Match creation fails
Symptoms: POST /matches returns 400 or 403
Diagnosis:
-
Verify request exists and is 'open':
SELECT id, status FROM requests.help_requests WHERE id = 'uuid-here'; -
If using offer, verify it's 'active':
SELECT id, status FROM requests.help_offers WHERE id = 'uuid-here'; -
Check responder is not requester
-
Look for duplicate match error (unique constraint)
Solution:
- Ensure request is in 'open' status
- Verify offer_id is valid (or omit for direct match)
- Different user_id for responder
Issue: Events not publishing
Symptoms: No events in Redis queue, downstream services not reacting
Diagnosis:
-
Check Redis connection:
docker exec -it karmyq-redis redis-cli PING -
Verify REDIS_URL environment variable
-
Check event publisher initialization in logs
-
Look for try-catch that swallows errors
Solution:
- Restart Redis:
docker-compose restart redis - Update REDIS_URL in
.env - Check publisher initialization:
src/events/publisher.ts
Issue: Database connection errors
Symptoms: 500 errors, "connection pool exhausted"
Diagnosis:
-
Check DATABASE_URL is correct
-
Verify PostgreSQL is running:
docker ps | grep postgres -
Test connection:
psql $DATABASE_URL -
Check requests schema exists:
\dn
Solution:
- Restart PostgreSQL:
docker-compose restart postgres - Verify connection string format
- Run migrations:
psql $DATABASE_URL < infrastructure/postgres/init.sql
10.2 Performance Issues
Issue: Slow skill-based matching queries
Solution:
- Verify indexes exist:
idx_help_requests_community_id,idx_help_requests_category auth.user_tagshas an existing user-id index; measure tag-query performance before adding indexes.- Consider materialized view for frequently accessed matches
Issue: High memory usage
Solution:
- Check connection pool size (default: 20)
- Verify connections are being released properly
- Monitor with:
docker stats karmyq-request-service
10.3 Recent Changes (v9.10)
Version 10.12.0 - Sprint 88 (2026-06-05) — Core Help-Loop Redesign
- FIXED:
GET /requests/curatednow parsesminScorewith explicit0support; missing or invalid values still default to30, butminScore=0no longer falls through to30. This repairs the new Dashboard Home / Community Home Show more open requests affordance and the pre-existing frontend Show All slider that already sentminScore: 0. - CHANGED:
view=homeandview=communityunion responses now log request impressions torequests.feed_eventsbefore their early returns. Decision, activity, and story union items are not logged as request impressions. - TESTS:
tests/tdd/sprint-88-curated-feed-controls.test.tslocks the parser behavior, min-score filter widening, and mocked impression INSERT shape without real-DB /setTimeouttiming.
Version 10.9.0 - Sprint 85 (2026-06-03) — Unified Feed: Dashboard Home (ADR-066)
- NEW:
GET /requests/curated?view=homereturns theUnifiedFeedItemunion (request | decision | activity | story) with a server-computed action-altitudepriority— decisions you owe rank above requests you can fill.viewabsent keeps the legacy request-array shape (back-compat). Pure assembly logic extracted tosrc/services/unifiedFeed.ts(unit-tested:tests/unit/curated-view-home.test.ts). - CHANGED (manifesto "designed to forget"):
handleCuratedFeed's prior-interaction signal now reads the decayed edge weightsocial_graph.trust_edges_live.current_weight(ADR-011 /20260526-interaction-halflife) instead of the binarysocial_graph.connections.type.trust_edges_liveis a VIEW — read-only. - VOCAB RECONCILIATION (migration
20260603-feed-vocab-reconciliation.sql): urgency reconciled to one scaleurgent|high|medium|low(critical→urgent) with CHECKchk_help_requests_urgency; status lifecycle locked by CHECKchk_help_requests_status(open|dibs_pending|matched|completed|cancelled). All urgency producers (create validator, admin triage, request wizard, community triage UI) and the two shared scorers (scoreUrgency,applyUrgencyBonus) reconciled in the same change sourgentis the top tier, not the default floor. - VERIFY-LOCK:
PUT /matches/:id/reject(Withdraw Offer) confirmed to allow both participants (Sprint 62); a clean rebuild purged a stale guard string that lived only indist/. New regressiontests/regression/sprint-85-withdraw-offer.test.tslocks that the responder can withdraw AND the request reopens when no proposed matches remain.
Version 10.8.0 - Sprint 83 (2026-06-02)
- SECURITY (ADR-064):
PUT /matches/:id/accept,/reject,/completenow authorize from the authenticated JWT identity (req.user!.userId), notreq.body.user_id. Previously any logged-in user could act on another user's match by supplying a participant's id in the body (broken access control / IDOR).completewas the most damaging — a forged completion publishedmatch_completed, which awards karma. The guard comparison logic is unchanged; only the identity source moved from body to token. A leftoverbody.user_idfrom un-deployed clients is tolerated (ignored). Non-identity body input (accept'stravel_time_minutes) still comes from the body. Locked bytests/regression/sprint-83-match-action-auth.test.ts. - KNOWN ISSUE:
DELETE /matches/:id(cancel) still readsbody.user_id— same IDOR class, deferred to a follow-up (outside Sprint 83 scope). See ADR-064 follow-ups.- Resolved: the route reads
req.user!.userId(src/routes/matches.ts); confirmed during BUG-074 planning, 2026-10-29.
- Resolved: the route reads
Version 10.2.0 - Sprint 73 (2026-05-29)
- DELETED:
src/services/matchService.ts— dead service class; routes use inline SQL; never called by any route - DELETED:
tests/regression/matchingLogic.test.ts— regression tests for deleted matchService.ts - DELETED:
tests/tdd/dynamic-schemas-api.test.ts,schema-caching.test.ts,schema-fallback.test.ts— placeholder tests; pool never initialized - CHANGED:
src/routes/matches.ts— removed commented-outfind-candidatesendpoint and dead import block; removed debugconsole.log; standardized GET /:id and POST / success/error responses to usesendSuccess/sendInternalError - CHANGED:
src/routes/requests.ts— extracted 562-line GET /curated handler intohandleCuratedFeednamed function; standardized catch-block 500 responses to usesendInternalError - FIXED:
src/routes/providers.ts— POST / now returns 409 when pg duplicate key error (code 23505) - TESTS:
tests/tdd/two-phase-completion.test.ts— fixed missing 5th mock for fire-and-forget feed_events INSERT - TESTS:
tests/tdd/providers-api.test.ts— fixed GET /:providerId mock (was missing rate_cards query)
Version 9.40.0 - Sprint 64 (2026-05-25)
- CHANGED:
src/routes/adminActions.ts—isAdminOfRequestCommunityrenamed toisAdminOrModOfRequestCommunity; filter now acceptsrole === 'admin' || role === 'moderator'. All four admin action endpoints (boost, remove-boost, propose-match, urgent-toggle) now accept moderator role in addition to admin. Frontend already showed boost/propose buttons to mods — backend was silently 403ing them.
Version 9.29.0 - Sprint 62 (2026-05-21)
- CHANGED:
PUT /matches/:id/reject— guard expanded to allow both requester AND responder to reject/withdraw. Previously only the requester could call this endpoint; responders received 403. Error message updated to "Only match participants can reject or withdraw." - CHANGED:
POST /requests— now validatesrequest_typeagainstcommunity.community_configs.enabled_request_typesfor the target community. If the community has configured enabled types, any request type not in the list is rejected with400 REQUEST_TYPE_NOT_ENABLED. Communities with no configured types continue to accept all request types (opt-in enforcement).- BUG-006 FIX (2026-06-08): enforcement now only considers known built-in type names (
generic|ride|service|event|borrow). Legacy names from older seed data (meal_share,tool_borrow,childcare, … — init.sql / migrations 011-012) are ignored, so anenabled_request_typesthat contains only legacy names reads as unrestricted (accepts any type), matching the empty/null case and the frontendCommunityConfigEditornormalization. Previously the raw legacy names were enforced verbatim, 400-ing validgenericrequests while the admin UI showed all types enabled.
- BUG-006 FIX (2026-06-08): enforcement now only considers known built-in type names (
Version 9.23.0 - Sprint 56 (2026-05-17)
- CHANGED:
src/events/publisher.ts— now delegates tocreatePublisher('request-service')from@karmyq/shared; local Bull setup removed - NEW:
src/utils/queryBuilder.ts— extracted 65-line SQL builder fromsrc/routes/requests.ts; exportsbuildRequestsQuery(filters)returning{ queryText, params } - CHANGED:
src/routes/requests.ts— GET /requests inline SQL builder replaced withbuildRequestsQuery()call; line count 1,391 → 1,334 - TESTS:
tests/unit/queryBuilder.test.ts— 9 unit tests covering all filter combinations
Version 9.15.0 - Sprint 41 (2026-03-26)
Provider offer flow — providers can now submit, list, and withdraw priced offers on open requests; requesters can accept or decline pending offers.
- NEW:
GET /requests/:id/offers— list provider offers on a specific request (requester only) - NEW:
PUT /requests/offers/:id/accept— accept a pending provider offer; creates a match - NEW:
PUT /requests/offers/:id/decline— decline a pending provider offer - NEW:
POST /providers/offers— submit a provider offer on an open help request - NEW:
GET /providers/offers— list offers submitted by the authenticated provider - NEW:
PUT /providers/offers/:id/withdraw— withdraw a pending provider offer - Schema: New
provider.offerstable (id,provider_id,provider_user_id,request_id,price,note,status,created_at,updated_at) - Events Published:
provider_went_on_duty,offer_submitted,offer_accepted,offer_declined - Files:
src/routes/providerOffers.ts
Version 9.14.0 - Sprint 40 (2026-03-25)
requests.matches.admin_proposed BOOLEAN NOT NULL DEFAULT FALSE— set to TRUE when match created via thePOST /requests/:id/propose-matchadmin route (migration 018)GET /requests/curatednow returnsis_boostedandboosted_expires_atfields per request item- Active boost contributes +30 to feedScore (capped at 100) during feed score calculation
Version 9.10.0 - Admin Power Actions (Sprint 36, 2026-03-23)
New admin action endpoints giving community admins direct control over request visibility and matching:
- Boost System —
POST /requests/:id/boost/DELETE /requests/:id/boost- Sets
is_boosted=TRUEwith a 48-hour expiry onrequests.help_requests - New columns added via migration 015:
is_boosted,boosted_at,boosted_expires_at,boosted_by - Boosted requests receive a +0.3 feed score bonus in the request-service feed ranker (capped at 1.0)
- Sets
- Propose Match —
POST /requests/:id/propose-match- Admin can propose a specific community member as a helper
- Creates a
requests.matchesrow withstatus='proposed'
- Toggle Urgency —
PATCH /requests/:id/urgent- Admin can flip urgency between
urgentandmedium - Distinct from the existing
PATCH /requests/:id/admin-triage(which also handles notes)
- Admin can flip urgency between
- All endpoints live in
src/routes/adminActions.tsand require the caller to be an active community admin
Version 9.0.0 - Polymorphic Request System (2026-02-05)
This major release transforms the request system from single-type generic requests to a polymorphic system supporting 5 specialized request types with intelligent feed curation.
Core Features:
-
Polymorphic Request Types (Days 1-5)
- Added
request_typeenum column:generic,ride,service,event,borrow - Added JSONB
payloadcolumn for type-specific data - Added JSONB
requirementscolumn for matching criteria - Implemented Zod discriminated union validation in
@karmyq/shared/schemas/requests - Created type-specific schemas for all 5 request types
- Added type guards for runtime type narrowing
- Added
-
Smart Defaults & Progressive Disclosure (Day 6)
- Default to
genericrequest type (reduces clicks from 3 to 2) - Collapsible type selector with progressive disclosure UX
- Request type examples and "Most Used" badges
- Target: < 3 clicks to create generic request (achieved: 2 clicks)
- Default to
-
Curated Feed with Match Scores (Day 7)
- New endpoint:
GET /requests/curatedwith match score calculation - Type-specific matching algorithms in
@karmyq/shared/matching - Match scores (0-100%) with transparency (reasons + breakdown)
- Skill-based filtering using user profile
- Result: 85% noise reduction (100 requests → 15 relevant)
- New endpoint:
-
User Preferences System (Day 8)
- Request type subscriptions (subscribe/unsubscribe per type)
- Interest-based filtering (service categories, item categories, event types)
- Preference persistence in
auth.user_request_preferencestable - Interest storage in
auth.user_intereststable - Result: 67% additional reduction (15 requests → 5 highly relevant)
- Combined: 95% total noise reduction
-
Multi-Community Posting (Days 1-5)
- New junction table:
requests.request_communities - Support for
post_to_all_communitiesflag - Requests can appear in multiple communities
- New junction table:
-
Comprehensive Testing (Days 9-12)
- 200+ tests covering all features
- Unit tests (69 tests for curated feed algorithm)
- Regression tests (40+ integration tests for polymorphic lifecycle)
- Integration tests (30+ tests for preferences + curated feed)
- E2E tests (25+ Playwright tests for complete user flows)
Database Changes:
-- Migration 009_polymorphic_requests.sql
ALTER TABLE requests.help_requests
ADD COLUMN request_type request_type_enum NOT NULL DEFAULT 'generic',
ADD COLUMN payload JSONB,
ADD COLUMN requirements JSONB;
CREATE TYPE request_type_enum AS ENUM ('generic', 'ride', 'service', 'event', 'borrow');
-- Migration 010_user_request_preferences.sql
CREATE TABLE auth.user_request_preferences (
user_id UUID NOT NULL,
request_type request_type_enum NOT NULL,
subscribed BOOLEAN DEFAULT true,
PRIMARY KEY (user_id, request_type)
);
CREATE TABLE auth.user_interests (
user_id UUID NOT NULL,
interest_type VARCHAR(50) NOT NULL,
interest_value VARCHAR(100) NOT NULL,
PRIMARY KEY (user_id, interest_type, interest_value)
);
API Changes:
- ✅ POST /requests - Now accepts polymorphic payloads with
request_type+payload - ✅ GET /requests/curated - New endpoint for intelligent feed curation
- ✅ Backward compatible - Generic requests work exactly as before
Frontend Changes:
- ✅ Smart defaults with progressive disclosure UX
- ✅ Curated feed toggle with match score slider
- ✅ Match score badges and reason tooltips
- ✅ Preferences page for type subscriptions and interests
Performance Impact:
- Payload column uses JSONB with GIN indexes for fast queries
- Curated feed endpoint optimized with user preference filtering
- Match score calculation in-memory (no additional DB queries per request)
Migration Path:
- All existing requests automatically assigned
request_type = 'generic' payload = {}for backward compatibility- No breaking changes to existing API contracts
10.4 Recent Fixes
Sprint 137 BUG-088..091 — exchange integrity:
- BUG-091: a completed or cancelled ask could be edited, including a forgotten one.
PUT /requests/:idwrote without the lock or a status check. It now locks, refuses with 409REQUEST_CLOSED, and requirescontent_forgotten_at IS NULL. - BUG-089: an offer's status was editable, and expired standing offers could be held.
PUT /offers/:idaccepted a body status (now 400STATUS_NOT_EDITABLE);POST /matchesheld offers regardless of expiry (now refused); match reject/cancel left the offermatched(now freed throughreleaseOffer, which keeps shared and withdrawn offers).sprint-137-offer-status-gate.test.tspins every help-offer status writer. - BUG-090:
POST /providers/offersinserted without the request lock, so an offer could land on an ask that had just closed. It now locks and re-checks in one transaction (409REQUEST_NOT_OPEN). - BUG-088: the expiry sweep left proposals and held offers behind; fixed in cleanup-service (see its CONTEXT.md,
releaseExpiredHolds).
Sprint 136 BUG-085 + BUG-084 — expired asks and POST /matches:
- BUG-085: an expired ask still took new commitments. The sweep sets
expired = TRUEand leaves the statusopen, andlockRequestnever readexpired, so propose-match, match accept, dibs create and provider-offer accept proceeded on an expired ask. They now readlockRequestForCommitmentand refuse it (409REQUEST_NOT_OPEN), asPOST /matchesalways did for a flagged ask. Cancel, reject and dibs accept still work on it. - BUG-084: a
POST /matchesproposal could land on an ask that had just closed and hold the helper's offer. The route read reachability, then inserted on the pool and set the offermatchedwith no guard, so a cancel or accept committing in between left a stranded proposal. It now writes under the request lock, re-checks the duplicate there, and holds the offer only while it is stillactive.
Sprint 135 BUG-075 + BUG-078 — request status guards:
- Request-status writers outside BUG-074's routes had no status guard, so completed asks were reopened or re-matched.
Accept set
matchedon any status, reject and dibs decline/expire reopened acompleted,cancelledordibs_pendingask, propose-match and the dibs and provider-offer accepts matched whatever the status,PUT /requests/:idwrote a bodystatus, andDELETE /requests/:idcancelled a completed ask or left a matched exchange on a cancelled one. Nowsrc/db/requestStatus.tsis the only writer: each route changes its own row with a guarded statement, then derives the request status under the request lock (lockRequestfor preconditions,reconcileRequestStatusafter the write). New refusals: 409REQUEST_NOT_OPEN,REQUEST_NOT_CANCELLABLE,REQUEST_HAS_ACTIVE_EXCHANGE, 400STATUS_NOT_EDITABLE. Provider-offer accept is one transaction. cleanup-service's dibs expiry writes only a still-pending dibs. - BUG-078 (1): reject and accept freed a withdrawn offer back to
active;closeProposalsand reject now free an offer only while it ismatched. (2): complete's finalize overwrote the request withcompleted(a cancelled request flipped, a request with a second matched helper closed); it now derives. (3): a repeat mark moveddone_at; it now keeps the first stamp (COALESCE). - Existing demo rows (119 requests with more than one completed match, 2026-10-29) are not repaired; a post-deploy recount
is the check. Tests:
tests/regression/sprint-135-request-status-{helper,gate,writers}.test.ts, cleanup-service'ssprint-135-expire-dibs-guard.test.ts, and the real-SQL roottests/integration/sprint-135-request-status-guards.integration.test.ts(CI-only on Windows).
Sprint 134 BUG-074 — match cancel and complete status guards:
DELETE /matches/:idcancelled a match whatever its status, andPUT /matches/:id/completerecorded a mark on any status butcompleted. A participant could undo a completed exchange after its karma was awarded (the standing backfill replays onlycompletedmatches, rating answered 409, vouch eligibility was lost), cancel a rejected match and reopen an ask another helper was matched on, and revive an offer the helper had withdrawn. A cancelled match could be completed by the other side's mark, and two simultaneous final marks both stampedcompleted_atand publishedmatch_completed. Both routes now put the guard in the write (AND status = 'matched') and answer 409MATCH_NOT_CANCELLABLE/MATCH_NOT_COMPLETABLE; cancel updates the request and offer conditionally, and complete keeps the idempotent 200 for an already-completed match. Existing demo rows are not repaired here (BUG-075). Tests:tests/regression/sprint-134-bug-074-match-status-guards.test.tsand the root real-SQLtests/integration/sprint-134-bug-074-match-status-guards.integration.test.ts(CI-only on Windows).
Sprint 134 PR K — Admin gates read the live role (ADR-102):
- BUG-069 — admin gates trusted the JWT
communitiesclaim. A demoted or removed admin kept admin powers until the token expired (1 h), and an admin of a community beyond the claim's 15 entries was refused.requireAdmin(/admin/schemasand the/requestsadmin-actions mount; "admin of any community"; since Sprint 141/admin/schemasneeds a platform admin and the prefilter isrequireAnyCommunityAdmin, ADR-105), the per-request admin/moderator gate on boost, unboost, propose-match and urgent, and the collective link/unlink community-admin check now readcommunities.membersthroughsrc/db/liveRole.ts(getLiveRole,isLiveAdmin,isLiveAdminOfAnyCommunity,hasLiveRoleInRequestCommunities; arguments(communityId, userId); a malformed id answers false, not a 500).db/inventoryDb.tsisActiveMemberdelegates to it. The deaduser.rolebranch and the legacycommunityMembershipsalias are gone. Tests:tests/regression/sprint-134-pr-k-live-role.test.ts, roottests/integration/sprint-134-pr-k-live-admin-role.integration.test.ts, and the static gatetests/regression/sprint-134-pr-k-claim-gate.test.ts. - BUG-071 — the requester-offer routes 403'd every requester who is not an admin somewhere.
requesterOffersRouter(GET /requests/:id/offers,PUT /requests/offers/:id/accept|decline) was mounted after the admin-actions mount, whose prefix-widerequireAdminran first. The admin chain now runs only on the routesadminActionsRouterdefines:app.all(adminChainPaths(adminActionsRouter, '/requests'), ...)reads them from the router and throws at startup on any layer it could not cover (router.use, an array or RegExp path). A route added there is gated automatically, nothing else under/requestsfalls through it, and an unmatched/requestspath is a plain 404. The mount order is unchanged.db/inventoryDb.tsisActiveAdminhad no callers and is deleted.
Sprint 134 PR L — Dead interaction-feedback routes retired (BUG-068):
- BUG-068 —
POST /matches/:matchId/feedbackalways failed. It selectedhelp_requests.community_id, which does not exist, so it 500ed before writing or publishing; the only caller (the simulation) discarded the error. Both feedback routes are removed rather than repaired (maintainer, 2026-10-16). Tests:tests/regression/sprint-134-bug-068-feedback-retired.test.ts(real app: both paths reach the 404 handler, no feedback SQL runs) and the live case intests/integration/sprint-132-security-authz.integration.test.ts.
Sprint 133 PR V — Request and offer read boundary (v11.89.0, #306):
- BUG-065 —
GET /requestslisted any community's asks to any signed-in user. The browse list now ANDsrequestReadableSql, the same boundary asGET /requests/:id, and the four community reads that trusted the JWT claim (feed view, pulse, open-asks, retention policy) checkcommunities.members. Tests:tests/integration/sprint-133-pr-v-read-boundary.integration.test.ts(list/detail parity by identity, stale claim),tests/regression/sprint-133-pr-v-read-boundary.test.ts. - BUG-064 — standing offers had no visibility gate. Offerer or live member only; a foreign offer is the same 404 as a missing one on every route. Same tests.
Sprint 107 — App Shell Clarity & Commitment Truth (v11.15.0, branch feature/sprint-107-app-shell-clarity):
- BUG-023 — Home offered-awaiting rows were not findable in Helping. Home already used
fetchOfferedAwaiting()throughGET /requests/curated?view=home, but Helping used separate match surfaces and did not list the same awaiting rows explicitly.GET /requests/offered-awaitingnow exposes the canonical predicate directly with a larger item limit for Helping. The endpoint is registered before/:idand returns{ count, items }from the same distinct-open-ask helper as Home. Test:tests/tdd/sprint-107-offered-awaiting-truth.test.ts.
Sprint 106 — Post-Facelift Correctness & Link-Up (v11.14.0, branch feature/sprint-106-correctness-linkup):
- BUG-014 — feed ranker projected
categoryasrequest_type.basicFeedRanker.tssetrequest_type: item.request.category(the mixed-vocabcategorycolumn, which holds skill tokens on legacy/seed rows), so a service ask was projected with a non-enumrequest_typeand the frontend offer-action copy fell through to "Offer help" instead of "Offer service". The ranker now selects and carries the persistedhr.request_typeenum (generic|ride|borrow|service|event), falling back to'generic'for null/legacy rows — never the category token.categorystill travels separately for the payload renderer. Test:tests/tdd/sprint-106-feed-request-type.test.ts. - BUG-013 — rating was not symmetric or durable. The decisions feed (
fetchDecisions) only owedaccept/decline/withdraw/mark_done/dibs; a finished exchange's rating unlocked in-place only for whoever clicked the finalmark_done, so the other party (and a reload) lost the affordance.fetchDecisionsnow adds a durableratedecision (unifiedFeed.tsDecisionAction, weight 5 — lowest altitude) for everystatus='completed'match the viewer has not yet rated, scoped byNOT EXISTS (SELECT 1 FROM feedback.feedback f WHERE f.request_match_id = m.id AND f.from_user_id = $1)(cross-schema read, shared DB), surfaced independently to both requester and responder. The band moved to the Helping tab (BUG-015). Test:tests/tdd/sprint-106-rating-decision.test.ts.
Sprint 98 — Trust Truth Audit (v11.7.0, branch feature/sprint-98-trust-truth-audit):
- BUG-098-004 — dibs candidates could be inactive members.
getMutualAidCandidatesandgetEligibleCandidates(src/db/dibsDb.ts) admitted anyone incommunities.membersof a shared community regardless of status, so a departed member could be surfaced as a first-ask candidate and labelledcommunity_connection. Both selection subqueries now requirecm.status = 'active'. This also closes the orphaned-exchange-connection admission path.providers.tsshared_communitiesalready filtered active on both sides (no change).deriveDibsReasonis now truthful by construction.
Sprint 97 — Release Readiness Data Quality (v11.6.0, branch feature/sprint-97-release-readiness-data-quality):
- BUG-097-002 — community pulse named non-member helpers.
fetchCommunityPulse()derived recent helper names throughrequests.matches → request_communitieswithout requiring the responder to be an active member of the community being rendered, so a helper who fulfilled a cross-posted request from a different community could be credited on this community's pulse (the live audit found 186 such pairs). The recent-helpers query nowJOIN communities.members mem ON mem.community_id = rc.community_id AND mem.user_id = m.responder_id AND mem.status='active', and theexchanges_completed_week(helpedThisWeek) count joins the same active-member subset (member-only semantics) so the headline count can never exceed the named member helpers. Verified read-only against the demo DB. Test:tests/tdd/sprint-97-community-pulse.test.ts.
Sprint 93 — Provider↔Community Link-Up (v11.2.0, branch feature/sprint-93-provider-linkup):
- F1 — community-scoped provider discovery (ADR-073).
GET /providersstays public, but when called WITH a token it annotates each provider withshared_communities(the communities the provider and viewer both belong to, via a livecommunities.membersjoin keyed on the signed JWT userId — not the JWT communities claim, so a stale token can't badge a left community). No schema change; unauthenticated responses unchanged. The directory UI groups "In your communities" vs "Other providers". Test:tests/tdd/sprint-93-provider-scope.test.ts. community_connectiondibs reason (ADR-072 addendum).deriveDibsReason(extracted tosrc/services/dibsReason.ts) returns the newcommunity_connectionreason for a zero-history neighbour (admitted via an exchange/community trust edge with 0 completed matches), instead of the falsetrusted_neighbor("you've worked with them before"). Reason union is nowprior_similar_success | trusted_neighbor | provider_match | community_connection. Pool admission unchanged. Test:tests/tdd/sprint-93-dibs-reason.test.ts.
Sprint 92 — Matching & Dibs Repair (v11.1.0, branch feature/sprint-92-matching-repair):
- BUG-008 — stranded
help_offerson match reject/accept. Creating a match set the linked offer to'matched', but only the cancel path restored it to'active'.PUT /matches/:id/rejectand theacceptpath's sibling rejection now free the linked offer(s) back to'active', so a reopened request is re-matchable and freed helpers re-enter the pool. Test:tests/tdd/sprint-92-matching.test.ts. - BUG-007 — dibs neighbor/provider framing (ADR-072 Option A). Candidates carry a
kind: 'neighbor' | 'provider'discriminator (getMutualAidCandidatesvsgetEligibleCandidates);POST /requests/:id/dibsvalidates a non-service nominee against the mutual-aid pool (no spuriousNO_PRIOR_INTERACTION).GET /requests/:id/dibs-candidatederives the facet from the persistedrequest_type(ignores?type=) and returns a server-computedreason(prior_similar_success|trusted_neighbor|provider_match) +relationshipContext(priorCompletedMatches/lastInteractionAt/similarCategory) so the UI renders the relationship judgment rather than recomputing it (ADR-072 §2 — server-side relationship routing). Candidate selection also routes by similarity: the scorer weightssimilarPriorInteractions(completed matches sharing the request's task-similarity key —deriveSimilarityKey/SIMILARITY_KEY_SQL: payload subtype likeservice_category/item_categorywhen present, elsecategory) so one prior similar task outranks many unrelated interactions. MatchacceptANDrejectare race-serialized (request-rowFOR UPDATE+ conditional status update → 409 on a lost race), and the dibs INSERT runs on the same transaction as thedibs_pendingtransition. Tests:tests/unit/dibs-candidate-kind.test.ts,tests/regression/sprint-52-trust-path.test.ts,tests/tdd/sprint-92-matching.test.ts. - BUG-005 — completion → rating unification. The decisions feed (
fetchDecisions) now returnscounterparty_id+community_idso the Dashboard can attribute a rating; the rating prompt fires onfully_completedfrom both surfaces (frontend shared helper). - BUG-002 — feed excludes the viewer's already-engaged requests. Every browsable open-request
query excludes requests where the viewer has a live (proposed/matched) match as responder.
Test:
tests/regression/sprint-92-feed-exclusion.test.ts.
10.5 Known Issues
Current Issues (v9.0.0):
-
Location-Based Matching Not Implemented
- Match scores don't yet consider geographic proximity for ride/service requests
- Planned: PostGIS integration for distance-based scoring
- Workaround: Users manually filter by community (implicit location)
-
Event Recurring Patterns Not Fully Implemented
- Event schema includes
recurringfield but no backend logic to create recurring instances - Planned: Scheduled job to generate recurring event requests
- Workaround: Users manually create multiple event requests
- Event schema includes
-
Image Upload for Borrow Requests Not Implemented
- Borrow schema includes
imagesfield but no upload endpoint - Planned: Image upload service integration
- Workaround: Users include image URLs in description
- Borrow schema includes
-
Budget Range Not Enforced in Matching
- Service requests include budget_range but not used in match score calculation
- Planned: Budget-based filtering in curated feed
- Workaround: Users manually review budget in request details
-
Certification Verification Not Automated
- Service requests can require certifications but no automated verification
- Planned: Integration with credential verification service
- Workaround: Manual verification during match acceptance
Resolved Issues:
-
✅ TypeScript Type Narrowing for Polymorphic Payloads (Resolved Day 6)
- Issue: TypeScript couldn't infer payload structure from request_type
- Solution: Implemented type guards (isRideRequest, isServiceRequest, etc.)
- Files:
packages/shared/src/schemas/requests/index.ts
-
✅ Jest Not Finding Regression Tests (Resolved Days 4-5)
- Issue: New regression test directory not included in jest.config.js
- Solution: Updated testMatch pattern to include
tests/regression/**/*.test.ts - Files:
services/request-service/jest.config.js
-
✅ Event Matcher Accessing Undefined Location (Resolved Day 7)
- Issue: Event location.is_virtual check failed when location undefined
- Solution: Added proper null checking and required location field validation
- Files:
packages/shared/src/matching/matchers/event.ts
-
✅ Workspace Alias Imports in Unit Tests (Resolved Day 6)
- Issue:
@karmyq/sharedimports failed in Jest tests - Solution: Changed to relative path imports from workspace root
- Files: All unit test files
- Issue:
-
✅ Provider offer acceptance did not close the request (Resolved 2026-05-06)
- Issue:
offersDb.acceptOfferinserted amatchedmatch record but never setrequests.help_requests.status = 'matched', leaving the requestopen. Old proposed matches remained visible in CommitmentsTab with an Accept button that fired "Match must be in proposed state to accept". - Solution: Added
UPDATE requests.help_requests SET status = 'matched'and a bulk reject of remainingproposedmatches — same pattern used bydibs.tsandmatches.tsaccept paths. - Files:
src/db/offersDb.ts
- Issue:
-
✅ validateRequestForOffer used stale JWT community IDs (Resolved 2026-05-06)
- Issue: Offer validation compared provider's JWT community array against request communities. Stale JWTs (or membership in >15 communities) caused "Request not found in your communities" for valid providers.
- Solution: Rewrote to JOIN
communities.memberslive, removing the JWT-sourcedcommunityIdsparameter. - Files:
src/db/providerOffersDb.ts,src/routes/providerOffers.ts
Performance Considerations:
- JSONB payload queries are fast with GIN indexes but not as fast as native columns
- Curated feed endpoint performs N+1 matching calculations (optimized with limit parameter)
- Match score calculation is CPU-bound but fast (~0.1ms per request)
- User preference lookup adds ~5ms to curated feed endpoint
11. Future Enhancements
11.1 v9.0 - Polymorphic Request System ✅ COMPLETED (2026-02-05)
- Polymorphic Data Model - Added
request_type,payload,requirementscolumns - Zod Schema Validation - Validate payloads against type-specific schemas
- Ride Requests - Origin/destination coordinates, seats needed, preferences
- Borrow Requests - Item category, condition, duration, return date
- Service Requests - Professional services with skill levels, budget, certifications
- Event Requests - Community events with RSVP, physical + virtual support
- Curated Feed - Match score algorithm with skill-based filtering
- User Preferences - Request type subscriptions and interest-based filtering
- Smart Defaults - Progressive disclosure UX (< 3 clicks to post)
- Multi-Community Posting - Requests visible across multiple communities
- Comprehensive Testing - 200+ tests (unit, regression, integration, E2E)
11.2 v9.1 - Provider Profiles (ADR-041) ✅ COMPLETED (2026-02-27)
New endpoints (see src/routes/providers.ts):
| Method | Path | Auth | Description |
|---|---|---|---|
| GET | /providers | Required | Browse active providers, filter by service_type. Annotates shared_communities from live membership. Auth added Sprint 125 / ADR-095 (was Public) |
| GET | /providers/:id | Required | Get single provider with ride details + trust score. Auth added Sprint 125 / ADR-095 (was Public) |
| GET | /providers/:id/rate-cards | Required | Rate cards; owner also gets inactive via ?include_inactive=true. Auth added Sprint 125 / ADR-095 (was Public) |
| GET | /providers/community/:communityId | Required + active member | Providers reachable through one community (Sprint 125 / ADR-095). Non-member → 403; opted-out or unconfigured community → 200 [], never 404 |
| POST | /providers | Required | Create provider profile (+ ride details if service_type=ride) |
| PUT | /providers/:id | Owner | Update profile or ride details |
| DELETE | /providers/:id | Owner | Delete profile (cascades reviews/trust scores) |
New tables (migration 022):
requests.provider_profiles— generic base (Sprint 26:is_available BOOLEAN DEFAULT FALSEadded via migration 20260314)requests.provider_ride_details— ride-specific extensionreputation.provider_reviews— stars + text, tied to match_idreputation.provider_trust_scores— computed cache (ADR-042)
Community config additions — ⚠️ these were written by the admin UI and read by nothing at all
until Sprint 125. They are now enforced together by src/services/providerReachService.ts
(ADR-095); enforcing a subset would leave an inert column behind again:
provider_services_enabled— opt-in per community. Thecommunity_configsjoin is INNER, so a community with no config row yields an empty layer rather than an error.provider_min_personal_trust_score— floor onreputation.trust_scores.score(user × community, ADR-037). Applied asCOALESCE(ts.score, 0) >= floorover aLEFT JOIN: a provider with no trust row scores 0 (fails closed). AnINNER JOINhere would silently drop every provider lacking a trust row even when the floor is 0. ⚠️ Not to be confused withreputation.provider_trust_scores.trust_score(provider-profile quality, ADR-042), which this endpoint uses only for ordering.provider_services_list— allowed service types. Empty means ALL types, not none (cardinality(list) = 0 OR service_type = ANY(list)); the column defaults to'{}'.
Reach gate route ordering: GET /providers/community/:communityId MUST stay registered above
GET /:providerId, which would otherwise capture the literal segment community. The path is
deliberately not /communities/:id/providers — nginx routes that prefix to community-service.
11.4 Matching Engine Enhancements
- Auto-matching algorithm (suggest best helpers)
- Location-based matching (PostGIS integration)
- Skill proficiency levels (beginner, intermediate, expert)
- Multi-helper requests (request needs 3 people)
11.3 Request Lifecycle
- Request expiration (auto-cancel old requests)
- Request templates (common request types)
- Recurring requests (weekly/monthly help)
- Request attachments/images
11.4 Quality & Trust
- Helper ratings aggregation
- Verified helper badges
- Request categories requiring verification (e.g., childcare)
12. Related Documentation
12.1 Architecture Documentation
12.2 Database Documentation
- Database Schema - Lines 91-144 (requests schema)
- Polymorphic Migration - v9.0
12.3 Testing Documentation
12.4 Development Guides
12.5 API Documentation
- API Gateway endpoints (TBD - v9.0)
- Swagger/OpenAPI spec (TBD - v9.0)
Appendix A: Request Categories Reference
Complete category-to-skill mapping for skill-based matching:
// src/services/matcher.ts
export const CATEGORY_SKILL_MAP = {
transportation: ['driving'],
moving: ['moving', 'handyman'],
childcare: ['childcare'],
pet_care: ['pet_care'],
tech_support: ['tech_support', 'coding'],
home_repair: ['home_repair', 'handyman', 'electrical', 'plumbing', 'carpentry'],
gardening: ['gardening'],
cooking: ['cooking', 'baking'],
tutoring: ['tutoring'],
language: ['languages'],
professional_advice: ['career_advice'],
cleaning: ['cleaning', 'organizing']
};
Appendix B: Development Tasks Reference
Add New Request Category
- Add to skill mapping in
src/routes/requests.ts - Update CATEGORY_SKILL_MAP in Appendix A
- Update documentation
Add New Request Field
- Create migration:
ALTER TABLE requests.help_requests ADD COLUMN ... - Update POST endpoint to accept field
- Update GET endpoints to return field
- Update tests
Change Urgency Levels
Update urgency priority calculation in skill matching query (see Section 5.2)
End of Request Service Context Documentation
This document is the gold standard for service documentation. All other services should follow this structure.
Sprint 116 post-deploy fix (2026-07-01) — provider-offer requester lookup
POST /providers/offers previously inserted the offer successfully and then queried
requests.help_requests.user_id while preparing the requester notification. The request table owns
that identity as requester_id, so PostgreSQL raised column "user_id" does not exist and the route
returned a misleading 500 after the write had already committed. The notification lookup now reads
requester_id; regression coverage requires a 201 response and the correct requester event payload.
Admin Schema API (Server-Driven UI - Phase 2)
Last Updated: 2026-02-17
Purpose: Enable non-technical admins to create and manage request type schemas without code deployments.
API Endpoints: All endpoints require a live platform admin (auth.platform_admins, Sprint 141, ADR-105). Anyone else, including a community admin, gets 403 PLATFORM_ADMIN_REQUIRED.
Schema Management
GET /admin/schemas- List all schemas (supports status, type, pagination filtering)GET /admin/schemas/:id- Get specific schema by ID (includes version history)POST /admin/schemas- Create new schema with type, sections, metadataPUT /admin/schemas/:id- Update schema (increments version automatically)POST /admin/schemas/:id/publish- Publish draft schema (validates structure: sections array, non-empty field keys/labels/types, valid summary field refs; returns 400 witherrors[]array on failure)POST /admin/schemas/:id/archive- Archive schema (hide from users)GET /admin/schemas/:id/versions- Get version history for rollbackPOST /admin/schemas/:id/rollback/:version- Rollback to specific versionPOST /admin/schemas/:id/variants- Create A/B test variantPOST /schemas/:type/validate- Validate schema payload (for testing)
Data Models:
- Uses
requests.ui_schemastable for schema storage - Uses
requests.ui_schema_versionsfor version history - JSON Schema validation in
requests.validation_rulesfor custom types
Frontend Integration:
/admin/schemas- Schema list with filtering/admin/schemas/new- Schema creation with form builder/admin/schemas/[id]/edit- Full editor with tabs (Sections/Fields/Preview/Versions)/admin/schemas/[id]/versions- Version timeline with rollback- Admin authentication middleware (super_admin/admin check)
Usage Example:
// Create new schema
const newSchema = {
type: 'dogwalking',
label: 'Dog Walking Request',
icon: '🐕',
color: '#f59e0b',
description: 'Help with walking your dog',
sections: [
{
id: 'section-1',
title: 'Dog Details',
fields: [
{ id: 'field-1', type: 'text', label: 'Dog Breed', required: true },
{ id: 'field-2', type: 'number', label: 'Duration (hours)', required: true }
]
}
]
}
await uiSchemaService.createSchema(newSchema)
Sprint 122 — Express 5 (2026-07-29)
@types/express 4.17.21 → 5.0.6. Express 5's path-to-regexp 8 widened route params to
string | string[] (a repeatable :ids+ or wildcard *splat segment captures an array), which
surfaced as TS2345 at every req.params read. Karmyq declares no such segment, so params are
narrowed back to string via RouteParams (exported from @karmyq/shared/middleware/auth)
rather than widened with as any. The invariant is enforced by
tests/regression/sprint-122-express5-route-params.test.ts, which fails if any route literal
introduces wildcard or repeatable syntax.
Changed: 8 handlers annotated Request<RouteParams> across src/routes/adminActions.ts (4),
requests.ts (2), admin-schemas.ts (1) and schemas.ts (1); plus src/routes/feed.ts, whose
own local AuthenticatedRequest now extends Request<RouteParams> (this service does declare
@karmyq/shared, so it imports the shared alias).
Express 4.18.2 → 5.2.1, supplied by the root package.json production dependency
(the Dockerfiles copy the root manifest and npm install --omit=dev). No endpoint, payload,
status code or event contract changed — feedback:check flags this service's src/routes/
diff as a "route change", but the diff is type annotations only, so the API Endpoints section
above is still accurate.
Express 5 semantics now in force: async handler rejections auto-forward to the error middleware,
res.status() throws RangeError on an out-of-range code, and req.query is a getter rather
than a writable own property.
⚠️ req.body default restored (the bug this PR actually shipped to CI). body-parser 1
initialised req.body to {} on every request; body-parser 2 leaves it undefined unless a
body was parsed, so const { x } = req.body throws a TypeError on a bodyless request and the
route's catch turns it into a 500. app.use(normalizeRequestBody) is now mounted immediately
after express.json() in src/index.ts to restore the Express 4 behaviour. It fills in only a
missing body, so a parsed array or explicit null is untouched.
Sprint 131 PR B2 — declared imports (2026-09-17)
Now declares cors, dotenv, express, jsonwebtoken, pg in dependencies at root's exact
ranges (BUG-046). They were imported but undeclared, resolving only through root hoisting. Resolved versions are
unchanged. tests/regression/sprint-131-workspace-declarations.test.ts fails on any undeclared import, and fails
when root's hoisted version stops satisfying a range declared here — so a root-only major bump (e.g. D1 dotenv 17)
must bump this manifest in the same PR. Range satisfaction alone could not enforce that: npm answers a stranded
range by nesting a satisfying older copy under the workspace, which keeps a plain satisfaction check green.
No endpoint, payload, event or schema change.
Sprint 131 D1 — dotenv 17 (2026-09-19)
dotenv 16.6.1 → 17.4.2 (root plus all 9 npm workspaces that declare it; the ranges moved together in
one PR, which the declarations gate requires. The two non-workspace test manifests, tests/e2e/package.json and
tests/load/package.json, deliberately stay on ^16.3.1 with their own nested installs — dotenv 16 accepts
quiet too, so their call sites are fixed either way). src/index.ts now calls dotenv.config({ quiet: true }).
quiet is not cosmetic here. dotenv 16 defaulted it to true; 17 defaults it to falsy, so a bare
config() prints ◇ injected env (N) from .env // tip: … on every call — and the tip is drawn at random
from an 8-entry list that includes third-party promo URLs. Without the flag this service would log a
non-deterministic marketing line on every container start.
tests/regression/sprint-131-dotenv-quiet.test.ts discovers the call sites from tracked source and fails
on any config() that omits quiet.
No endpoint, payload, event or schema change. parse() output is byte-identical between 16 and 17, and
nothing here reads config()’s return value.