From 46bf9b83bffc9b982d4b177d6da34073fccb512c Mon Sep 17 00:00:00 2001 From: caelum0x Date: Sun, 28 Jun 2026 18:48:46 +0300 Subject: [PATCH] feat: round-5 external harvest (22 features ported from external/ into 5 products) Harvest valuable features from external/ reference repos, adapted to each product's stack and wired in; all products typecheck clean. - gitgram-web (5): clickable @mention/#hashtag linkify in rendered content (munia), + feed/notification/accessibility patterns; install @testing-library/dom - gitgram-backend (3): feed thread dedup + muted-thread removal (bluesky), GitHub star/follow write-back via OAuth (gh-social) - gitgram-mobile (4): double-tap-to-like + heart bounce (proximity), haptics layer (bluesky useHaptics), + gesture/feed UX - aitm-api (4): beads ready/dependency-DAG endpoints + atomic claim (beads) - aitm-mcp (6): beads_ready work-queue tool, context-efficient projections, transport arg aliasing (context7/pal-mcp/beads) Co-Authored-By: Claude Opus 4.8 (1M context) --- aitimemachine/api-server/src/routes/beads.ts | 513 +++++++++++++++++- .../api-server/src/routes/context7.ts | 91 +++- .../api-server/src/routes/gitnexus.ts | 39 ++ .../src/services/gitNexusService.ts | 107 ++++ .../api-server/src/services/memoryService.ts | 102 ++++ aitimemachine/mcp/src/index.ts | 8 + .../mcp/src/tools/register-beads-tools.ts | 214 +++++++- gitgram/backend/prisma/schema.prisma | 11 + .../src/controllers/githubController.ts | 140 +++++ .../backend/src/controllers/postController.ts | 78 ++- gitgram/backend/src/routes/github.ts | 122 +++++ gitgram/backend/src/services/feedTuner.ts | 158 +++++- gitgram/backend/src/services/githubService.ts | 158 ++++++ gitgram/backend/src/services/selfLabels.ts | 111 ++++ gitgram/mobile/app/(modals)/create-post.tsx | 72 ++- gitgram/mobile/app/_layout.tsx | 5 + gitgram/mobile/app/chat/[userId].tsx | 3 + gitgram/mobile/app/menu.tsx | 44 ++ .../mobile/components/Moment/MomentCard.tsx | 88 ++- gitgram/mobile/components/Post/PostCard.tsx | 51 +- gitgram/mobile/components/Reel/ReelPlayer.tsx | 43 +- .../mobile/components/Story/StoryViewer.tsx | 18 + .../components/common/ImageAltTextDialog.tsx | 210 +++++++ .../common/Lightbox/LightboxProvider.tsx | 133 +++++ .../components/common/Lightbox/index.ts | 4 + .../common/Lightbox/lightboxStore.ts | 46 ++ .../components/common/Lightbox/useLightbox.ts | 24 + .../components/common/LikeBounceAnimation.tsx | 97 ++++ .../components/common/OptimizedImage.tsx | 67 ++- gitgram/mobile/hooks/useHaptics.ts | 36 ++ gitgram/mobile/package.json | 2 + gitgram/mobile/store/settingsStore.ts | 64 +++ gitgram/web/app/post/[id]/page.tsx | 4 + gitgram/web/app/settings/moderation/page.tsx | 271 +++++++++ gitgram/web/app/settings/page.tsx | 1 + gitgram/web/app/settings/profile/page.tsx | 73 ++- gitgram/web/components/CommentThread.tsx | 3 +- gitgram/web/components/CropImageDialog.tsx | 140 +++++ gitgram/web/components/Feed.tsx | 37 +- gitgram/web/components/FollowButton.tsx | 28 +- gitgram/web/components/MuteThreadButton.tsx | 54 ++ gitgram/web/components/PostCard.tsx | 3 +- gitgram/web/components/RichContent.tsx | 7 +- .../components/composer/ContentComposer.tsx | 55 +- .../components/composer/SortableMediaGrid.tsx | 175 ++++++ .../components/repo/RepoInteractionPanel.tsx | 105 +++- gitgram/web/hooks/useModeration.ts | 25 + gitgram/web/package.json | 11 +- gitgram/web/services/githubService.ts | 68 +++ gitgram/web/tsconfig.json | 6 +- gitgram/web/tsconfig.tsbuildinfo | 2 +- gitgram/web/utils/linkify.tsx | 87 +++ gitgram/web/utils/moderation.ts | 221 ++++++++ package-lock.json | 403 +++++++++----- 54 files changed, 4381 insertions(+), 257 deletions(-) create mode 100644 gitgram/backend/src/services/selfLabels.ts create mode 100644 gitgram/mobile/components/common/ImageAltTextDialog.tsx create mode 100644 gitgram/mobile/components/common/Lightbox/LightboxProvider.tsx create mode 100644 gitgram/mobile/components/common/Lightbox/index.ts create mode 100644 gitgram/mobile/components/common/Lightbox/lightboxStore.ts create mode 100644 gitgram/mobile/components/common/Lightbox/useLightbox.ts create mode 100644 gitgram/mobile/components/common/LikeBounceAnimation.tsx create mode 100644 gitgram/mobile/hooks/useHaptics.ts create mode 100644 gitgram/mobile/store/settingsStore.ts create mode 100644 gitgram/web/app/settings/moderation/page.tsx create mode 100644 gitgram/web/components/CropImageDialog.tsx create mode 100644 gitgram/web/components/MuteThreadButton.tsx create mode 100644 gitgram/web/components/composer/SortableMediaGrid.tsx create mode 100644 gitgram/web/hooks/useModeration.ts create mode 100644 gitgram/web/utils/linkify.tsx create mode 100644 gitgram/web/utils/moderation.ts diff --git a/aitimemachine/api-server/src/routes/beads.ts b/aitimemachine/api-server/src/routes/beads.ts index dcb736c4..a76ef096 100644 --- a/aitimemachine/api-server/src/routes/beads.ts +++ b/aitimemachine/api-server/src/routes/beads.ts @@ -1,10 +1,16 @@ import { Router, Request, Response } from "express"; import { execFile, exec } from "child_process"; import { promisify } from "util"; -import { ingestTask, type BeadsTask } from "../services/memoryService.js"; +import { + ingestTask, + addDependency, + listDependencies, + findDependencyCycles, + type BeadsTask, +} from "../services/memoryService.js"; import { resolveBeadsBinary } from "../services/engineManager.js"; import { logger } from "../lib/monitoring.js"; -import { apiKeyAuth } from "../middleware/auth.js"; +import { apiKeyAuth, AuthenticatedRequest } from "../middleware/auth.js"; const execFileAsync = promisify(execFile); const execAsync = promisify(exec); @@ -18,6 +24,99 @@ function beadsBin(): string { return resolveBeadsBinary().path ?? "bd"; } +/** + * Parse the trimmed stdout of a `bd ... --json` invocation. The binary emits an + * empty body for some commands; in that case `null` is returned rather than + * throwing a JSON parse error. + */ +function parseBeadsJson(stdout: string): unknown { + const trimmed = stdout.trim(); + if (trimmed.length === 0) { + return null; + } + return JSON.parse(trimmed) as unknown; +} + +/** A non-empty, trimmed string, or null when the value is absent/blank. */ +function cleanId(value: unknown): string | null { + if (typeof value !== "string") { + return null; + } + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; +} + +/** + * Coerce a query-string value (string | string[] | undefined) to a single + * trimmed string. Express types repeated/array query params, so collapse them. + */ +function singleQueryValue(value: unknown): string | undefined { + if (typeof value === "string") { + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : undefined; + } + if (Array.isArray(value) && value.length > 0) { + return singleQueryValue(value[0]); + } + return undefined; +} + +/** + * Parse a comma-separated (or array) label value into a clean array of + * non-empty labels. + */ +function labelList(value: unknown): string[] { + if (Array.isArray(value)) { + return value + .map((label) => (typeof label === "string" ? label.trim() : "")) + .filter((label) => label.length > 0); + } + const raw = singleQueryValue(value); + if (!raw) { + return []; + } + return raw + .split(",") + .map((label) => label.trim()) + .filter((label) => label.length > 0); +} + +/** + * Parse a bounded integer from a value. Returns undefined when absent or not a + * finite integer; clamps the result into [min, max]. + */ +function boundedInt( + value: unknown, + min: number, + max: number +): number | undefined { + const raw = + typeof value === "number" ? String(value) : singleQueryValue(value); + if (raw === undefined) { + return undefined; + } + const parsed = Number.parseInt(raw, 10); + if (!Number.isFinite(parsed)) { + return undefined; + } + return Math.min(Math.max(parsed, min), max); +} + +const DEPENDENCY_TYPES = [ + "blocks", + "related", + "parent-child", + "discovered-from", +] as const; +type DependencyType = (typeof DEPENDENCY_TYPES)[number]; + +function isDependencyType(value: unknown): value is DependencyType { + return ( + typeof value === "string" && + (DEPENDENCY_TYPES as readonly string[]).includes(value) + ); +} + const router = Router(); // Every beads endpoint reads or mutates task-management state and shells out @@ -35,6 +134,229 @@ router.get("/tasks", async (_req: Request, res: Response) => { } }); +// GET /beads/ready — work-queue query: unblocked, ready-to-work tasks. +// Optional filters: priority (0-4), assignee, unassigned, labels (AND), +// labelsAny (OR), limit (1-100), sort (priority|hybrid|oldest). +// +// With ?claim=1 (or claim=true) the first ready task matching the filters is +// atomically claimed (assignee=actor + status=in_progress) in a single +// compare-and-swap step, so concurrent agents cannot grab the same task. Per +// the beads CLI, --claim cannot be combined with --assignee/--unassigned, so +// those filters are ignored when claiming. +router.get("/ready", async (req: AuthenticatedRequest, res: Response) => { + const claim = + singleQueryValue(req.query.claim) === "1" || + singleQueryValue(req.query.claim) === "true"; + + const args: string[] = ["ready", "--json"]; + + const priority = boundedInt(req.query.priority, 0, 4); + if (priority !== undefined) { + args.push("--priority", String(priority)); + } + + if (claim) { + args.push("--claim"); + } else { + const assignee = singleQueryValue(req.query.assignee); + if (assignee) { + args.push("--assignee", assignee); + } + if (singleQueryValue(req.query.unassigned) === "true") { + args.push("--unassigned"); + } + } + + for (const label of labelList(req.query.labels)) { + args.push("--label", label); + } + for (const label of labelList(req.query.labelsAny)) { + args.push("--label-any", label); + } + + const limit = boundedInt(req.query.limit, 1, 100); + if (limit !== undefined) { + args.push("--limit", String(limit)); + } + + // --sort only applies to the query form; claiming takes the first match. + if (!claim) { + const sort = singleQueryValue(req.query.sort); + if (sort === "priority" || sort === "hybrid" || sort === "oldest") { + args.push("--sort", sort); + } + } + + try { + const { stdout } = await execFileAsync(beadsBin(), args); + const data = parseBeadsJson(stdout) ?? []; + + // When a claim succeeds, write the claimed task through to the unified + // memory layer so it is searchable (best-effort, never blocks the response). + if (claim) { + const claimed = Array.isArray(data) ? data[0] : data; + if (claimed && typeof claimed === "object" && !Array.isArray(claimed)) { + void ingestTask(claimed as BeadsTask, { userId: req.user?.userId }).catch( + (error: unknown) => { + logger.warn("beads: claim memory write-through failed", { + details: String(error), + }); + } + ); + } + } + + res.json({ success: true, data }); + } catch (err: unknown) { + res.status(500).json({ + success: false, + error: err instanceof Error ? err.message : "Failed to query ready tasks", + }); + } +}); + +// GET /beads/blocked — list blocked tasks and the dependencies blocking them. +router.get("/blocked", async (_req: Request, res: Response) => { + try { + const { stdout } = await execFileAsync(beadsBin(), ["blocked", "--json"]); + res.json({ success: true, data: parseBeadsJson(stdout) ?? [] }); + } catch (err: unknown) { + res.status(500).json({ + success: false, + error: + err instanceof Error ? err.message : "Failed to query blocked tasks", + }); + } +}); + +// GET /beads/stats — totals (open/in_progress/closed/blocked/ready) plus the +// average lead time. Backed by `bd status --json` (alias: `bd stats`). +router.get("/stats", async (_req: Request, res: Response) => { + try { + const { stdout } = await execFileAsync(beadsBin(), [ + "status", + "--json", + "--no-activity", + ]); + res.json({ success: true, data: parseBeadsJson(stdout) }); + } catch (err: unknown) { + res.status(500).json({ + success: false, + error: err instanceof Error ? err.message : "Failed to get statistics", + }); + } +}); + +// PUT /beads/tasks/:id/claim — atomically claim a single task. +// +// Sets assignee (to the configured actor) and status=in_progress in one +// compare-and-swap step. This is the multi-agent-safe primitive: two agents +// racing on the same task cannot both win the claim. Idempotent when the task +// is already claimed by the same actor; a 409 is returned when another actor +// holds the claim. +router.put("/tasks/:id/claim", async (req: AuthenticatedRequest, res: Response) => { + const id = cleanId(req.params.id); + if (!id) { + return res.status(400).json({ success: false, error: "task id is required" }); + } + + try { + const { stdout } = await execFileAsync(beadsBin(), ["update", id, "--claim", "--json"]); + const data = parseBeadsJson(stdout); + + const claimed = Array.isArray(data) ? data[0] : data; + if (claimed && typeof claimed === "object" && !Array.isArray(claimed)) { + void ingestTask(claimed as BeadsTask, { userId: req.user?.userId }).catch( + (error: unknown) => { + logger.warn("beads: claim memory write-through failed", { + details: String(error), + }); + } + ); + } + + res.json({ success: true, data }); + } catch (err: unknown) { + // The CLI exits non-zero when the compare-and-swap claim fails because the + // task is already in progress / claimed by another actor. Surface that as a + // 409 so callers can retry a different task instead of treating it as a + // server fault. + const message = err instanceof Error ? err.message : "Failed to claim task"; + const conflict = /claim|in[_ ]?progress|already/i.test(message); + res.status(conflict ? 409 : 500).json({ success: false, error: message }); + } +}); + +// POST /beads/deps — add a dependency edge to the DAG: `blocked` depends on +// `blocker`. The binary runs a cycle check and refuses an edge that would +// create a cycle (surfaced here as 409). body: { blocked, blocker, type? } +router.post("/deps", async (req: Request, res: Response) => { + const body = req.body as { blocked?: unknown; blocker?: unknown; type?: unknown }; + const blocked = cleanId(body.blocked); + const blocker = cleanId(body.blocker); + + if (!blocked || !blocker) { + return res.status(400).json({ + success: false, + error: "both blocked and blocker task ids are required", + }); + } + if (blocked === blocker) { + return res + .status(400) + .json({ success: false, error: "a task cannot depend on itself" }); + } + + const type = isDependencyType(body.type) ? body.type : undefined; + + try { + const data = await addDependency(blocked, blocker, type); + res.status(201).json({ success: true, data }); + } catch (err: unknown) { + const message = err instanceof Error ? err.message : "Failed to add dependency"; + const isCycle = /cycle/i.test(message); + res.status(isCycle ? 409 : 500).json({ success: false, error: message }); + } +}); + +// GET /beads/deps?id=:id&direction=down|up — list dependency edges for a task. +// direction=down (default): what :id depends on (its blockers) +// direction=up: what depends on :id (issues it blocks) +router.get("/deps", async (req: Request, res: Response) => { + const id = cleanId(req.query.id); + if (!id) { + return res + .status(400) + .json({ success: false, error: "id query param is required" }); + } + + const direction = singleQueryValue(req.query.direction) === "up" ? "up" : "down"; + + try { + const data = await listDependencies(id, direction); + res.json({ success: true, data }); + } catch (err: unknown) { + res.status(500).json({ + success: false, + error: err instanceof Error ? err.message : "Failed to list dependencies", + }); + } +}); + +// GET /beads/deps/cycles — detect dependency cycles across the whole DAG. +router.get("/deps/cycles", async (_req: Request, res: Response) => { + try { + const data = await findDependencyCycles(); + res.json({ success: true, data }); + } catch (err: unknown) { + res.status(500).json({ + success: false, + error: + err instanceof Error ? err.message : "Failed to detect dependency cycles", + }); + } +}); + // POST /beads/tasks — create a task // body: { title: string, deps?: string[] } router.post("/tasks", async (req: Request, res: Response) => { @@ -52,8 +374,7 @@ router.post("/tasks", async (req: Request, res: Response) => { try { const { stdout } = await execFileAsync(beadsBin(), args); - const trimmed = stdout.trim(); - const data: unknown = trimmed ? JSON.parse(trimmed) : null; + const data = parseBeadsJson(stdout); // Write-through into the unified memory layer (best-effort; never blocks // the response). Falls back to the title when the binary returns no JSON. @@ -71,15 +392,61 @@ router.post("/tasks", async (req: Request, res: Response) => { } }); +// POST /beads/tasks/:id/deps — add a dependency edge from this task to another. +// body: { dependsOn: string, type?: blocks|related|parent-child|discovered-from } +// Models the blocker an agent discovers mid-task (e.g. a discovered-from edge). +router.post("/tasks/:id/deps", async (req: Request, res: Response) => { + const id = cleanId(req.params.id); + if (!id) { + return res.status(400).json({ success: false, error: "task id is required" }); + } + + const body = req.body as { dependsOn?: unknown; type?: unknown }; + const dependsOn = cleanId(body.dependsOn); + if (!dependsOn) { + return res + .status(400) + .json({ success: false, error: "dependsOn (a task id) is required" }); + } + + let depType: DependencyType = "blocks"; + if (body.type !== undefined) { + if (!isDependencyType(body.type)) { + return res.status(400).json({ + success: false, + error: `type must be one of: ${DEPENDENCY_TYPES.join(", ")}`, + }); + } + depType = body.type; + } + + // `bd dep add --type ` records that depends + // on . + try { + const { stdout } = await execFileAsync(beadsBin(), [ + "dep", + "add", + id, + dependsOn, + "--type", + depType, + ]); + res.status(201).json({ success: true, data: parseBeadsJson(stdout) }); + } catch (err: unknown) { + res.status(500).json({ + success: false, + error: err instanceof Error ? err.message : "Failed to add dependency", + }); + } +}); + // PUT /beads/tasks/:id/ready — mark task ready router.put("/tasks/:id/ready", async (req: Request, res: Response) => { const { id } = req.params; try { const { stdout } = await execFileAsync(beadsBin(), ["ready", id]); - const trimmed = stdout.trim(); - const data: unknown = trimmed ? JSON.parse(trimmed) : null; - res.json({ success: true, data }); + res.json({ success: true, data: parseBeadsJson(stdout) }); } catch (err: unknown) { res.status(500).json({ success: false, error: err instanceof Error ? err.message : "Failed to mark task ready" }); } @@ -91,14 +458,140 @@ router.put("/tasks/:id/done", async (req: Request, res: Response) => { try { const { stdout } = await execFileAsync(beadsBin(), ["done", id]); - const trimmed = stdout.trim(); - const data: unknown = trimmed ? JSON.parse(trimmed) : null; - res.json({ success: true, data }); + res.json({ success: true, data: parseBeadsJson(stdout) }); } catch (err: unknown) { res.status(500).json({ success: false, error: err instanceof Error ? err.message : "Failed to mark task done" }); } }); +// PATCH /beads/tasks/:id — edit task fields (title/priority/assignee/status/ +// labels). Only provided fields are applied; at least one must be present. +router.patch("/tasks/:id", async (req: Request, res: Response) => { + const id = cleanId(req.params.id); + if (!id) { + return res.status(400).json({ success: false, error: "task id is required" }); + } + + const body = req.body as { + title?: unknown; + priority?: unknown; + assignee?: unknown; + status?: unknown; + labels?: unknown; + }; + + const args: string[] = ["update", id]; + let changed = false; + + const title = cleanId(body.title); + if (title) { + args.push("--title", title); + changed = true; + } + + if (body.priority !== undefined) { + const priority = boundedInt(body.priority, 0, 4); + if (priority === undefined) { + return res + .status(400) + .json({ success: false, error: "priority must be an integer 0-4" }); + } + args.push("--priority", String(priority)); + changed = true; + } + + if (body.assignee !== undefined) { + // An explicit empty string clears the assignee; a value sets it. + const assignee = typeof body.assignee === "string" ? body.assignee.trim() : ""; + args.push("--assignee", assignee); + changed = true; + } + + const status = cleanId(body.status); + if (status) { + args.push("--status", status); + changed = true; + } + + if (body.labels !== undefined) { + const labels = labelList(body.labels); + // Replace the full label set so the update is deterministic. + args.push("--set-labels", labels.join(",")); + changed = true; + } + + if (!changed) { + return res.status(400).json({ + success: false, + error: "at least one of title, priority, assignee, status, labels is required", + }); + } + + try { + const { stdout } = await execFileAsync(beadsBin(), args); + res.json({ success: true, data: parseBeadsJson(stdout) }); + } catch (err: unknown) { + res.status(500).json({ + success: false, + error: err instanceof Error ? err.message : "Failed to update task", + }); + } +}); + +// POST /beads/tasks/:id/close — close a task with an audit-trail reason. +// body: { reason?: string } +router.post("/tasks/:id/close", async (req: Request, res: Response) => { + const id = cleanId(req.params.id); + if (!id) { + return res.status(400).json({ success: false, error: "task id is required" }); + } + + const body = req.body as { reason?: unknown }; + const reason = cleanId(body.reason) ?? "Completed"; + + try { + const { stdout } = await execFileAsync(beadsBin(), [ + "close", + id, + "--reason", + reason, + ]); + res.json({ success: true, data: parseBeadsJson(stdout) }); + } catch (err: unknown) { + res.status(500).json({ + success: false, + error: err instanceof Error ? err.message : "Failed to close task", + }); + } +}); + +// POST /beads/tasks/:id/reopen — reopen a closed task (e.g. a regressed fix). +// body: { reason?: string } +router.post("/tasks/:id/reopen", async (req: Request, res: Response) => { + const id = cleanId(req.params.id); + if (!id) { + return res.status(400).json({ success: false, error: "task id is required" }); + } + + const body = req.body as { reason?: unknown }; + const reason = cleanId(body.reason); + + const args: string[] = ["reopen", id]; + if (reason) { + args.push("--reason", reason); + } + + try { + const { stdout } = await execFileAsync(beadsBin(), args); + res.json({ success: true, data: parseBeadsJson(stdout) }); + } catch (err: unknown) { + res.status(500).json({ + success: false, + error: err instanceof Error ? err.message : "Failed to reopen task", + }); + } +}); + // GET /beads/tasks/:id — get a single task router.get("/tasks/:id", async (req: Request, res: Response) => { const { id } = req.params; diff --git a/aitimemachine/api-server/src/routes/context7.ts b/aitimemachine/api-server/src/routes/context7.ts index aeb726a6..ad02801e 100644 --- a/aitimemachine/api-server/src/routes/context7.ts +++ b/aitimemachine/api-server/src/routes/context7.ts @@ -25,28 +25,79 @@ const router = Router(); router.use(apiKeyAuth); // ============================================================================ -// In-process Context7 client +// Per-request Context7 client +// +// The Context7 key is resolved per request so each tenant/user can supply their +// own key (and consume their own rate limit) instead of every caller sharing +// one server-wide key. Resolution order mirrors the upstream Context7 MCP +// server's `extractApiKey`: +// 1. Authorization: Bearer +// 2. X-Context7-Key / Context7-API-Key headers +// then falls back to the server-wide CONTEXT7_API_KEY env var. +// +// Note: the product's own API auth uses the `x-api-key` header, so we do NOT +// read `x-api-key` here (it carries the AITM key, not the Context7 key) — +// `X-Context7-Key` is the dedicated per-request Context7 header. +// +// Clients are cached by key so we don't reconstruct an SDK instance on every +// request, while still keeping per-key isolation. // ============================================================================ -let _client: Context7 | null = null; +const clientCache = new Map(); + +/** Read a single header value, taking the first entry of array-valued headers. */ +function headerValue(value: string | string[] | undefined): string | undefined { + if (Array.isArray(value)) { + return value[0]; + } + return value; +} + +/** Extract a Bearer token from an Authorization header, if present. */ +function extractBearerToken(authorization: string | string[] | undefined): string | undefined { + const header = headerValue(authorization); + if (!header) { + return undefined; + } + const match = /^Bearer\s+(.+)$/i.exec(header.trim()); + return match ? match[1].trim() : undefined; +} /** - * Lazily construct the SDK client. Returns null if no API key is configured so - * callers can surface a clean "unavailable" state instead of crashing. + * Resolve the effective Context7 API key for a request: a per-request key from + * headers when supplied, otherwise the server-wide env key. Returns null when + * no key is available at all. */ -function getClient(): Context7 | null { - if (_client) { - return _client; - } +function resolveApiKey(req: Request): string | null { + const fromRequest = + extractBearerToken(req.headers.authorization) || + headerValue(req.headers["x-context7-key"]) || + headerValue(req.headers["context7-api-key"]); - const apiKey = process.env.CONTEXT7_API_KEY; + const key = (fromRequest && fromRequest.trim()) || process.env.CONTEXT7_API_KEY; + return key && key.trim().length > 0 ? key.trim() : null; +} + +/** + * Build (or reuse) an SDK client for the request's effective key. Returns null + * when no key is configured so callers can surface a clean "unavailable" state + * instead of crashing. + */ +function getClient(req: Request): Context7 | null { + const apiKey = resolveApiKey(req); if (!apiKey) { return null; } + const cached = clientCache.get(apiKey); + if (cached) { + return cached; + } + try { - _client = new Context7({ apiKey }); - return _client; + const client = new Context7({ apiKey }); + clientCache.set(apiKey, client); + return client; } catch (error: unknown) { const msg = error instanceof Error ? error.message : String(error); logger.warn("context7: failed to initialise SDK client", { reason: msg }); @@ -54,10 +105,12 @@ function getClient(): Context7 | null { } } -function requireClient(): Context7 { - const client = getClient(); +function requireClient(req: Request): Context7 { + const client = getClient(req); if (!client) { - throw new Error("Context7 not configured: set CONTEXT7_API_KEY"); + throw new Error( + "Context7 not configured: provide an X-Context7-Key header or set CONTEXT7_API_KEY" + ); } return client; } @@ -84,11 +137,11 @@ const searchQuerySchema = z.object({ router.get( "/status", - asyncHandler(async (_req: Request, res: Response) => { + asyncHandler(async (req: Request, res: Response) => { let available = false; let latencyMs: number | null = null; - const client = getClient(); + const client = getClient(req); if (client) { const start = Date.now(); try { @@ -135,7 +188,7 @@ router.get( const { q } = parsed.data; logger.info("context7: search", { query: q }); - const libraries: Library[] = await requireClient().searchLibrary(q, q, { + const libraries: Library[] = await requireClient(req).searchLibrary(q, q, { type: "json", }); @@ -168,7 +221,7 @@ router.get( logger.info("context7: get library docs", { libraryId: id, version, topic, tokens }); - const docs: Documentation[] = await requireClient().getContext(topic, id, { + const docs: Documentation[] = await requireClient(req).getContext(topic, id, { type: "json", }); @@ -206,7 +259,7 @@ router.get( // The SDK requires a non-empty libraryName; fall back to the query (or a // broad term) so a bare /libraries listing still returns results. const libraryName = q || "library"; - const libraries: Library[] = await requireClient().searchLibrary( + const libraries: Library[] = await requireClient(req).searchLibrary( q || "popular libraries", libraryName, { type: "json" } diff --git a/aitimemachine/api-server/src/routes/gitnexus.ts b/aitimemachine/api-server/src/routes/gitnexus.ts index d2e4a3c0..bfca1ba3 100644 --- a/aitimemachine/api-server/src/routes/gitnexus.ts +++ b/aitimemachine/api-server/src/routes/gitnexus.ts @@ -19,6 +19,7 @@ import { getApiRoutes, getDependencyGraph, searchSymbols, + detectChanges, } from "../services/gitNexusService.js"; const router = Router(); @@ -58,6 +59,18 @@ const symbolQuerySchema = workspaceQuerySchema.extend({ .max(500, "query must be 500 characters or less"), }); +const detectChangesBodySchema = z + .object({ + scope: z.enum(["unstaged", "staged", "all", "compare"]).default("unstaged"), + baseRef: z.string().min(1).max(255).optional(), + worktree: z.string().min(1).max(2048).optional(), + repo: z.string().min(1).max(2048).optional(), + }) + .refine((v) => v.scope !== "compare" || (v.baseRef && v.baseRef.length > 0), { + message: "baseRef is required when scope is 'compare'", + path: ["baseRef"], + }); + // ============================================================================ // GET /gitnexus/status // ============================================================================ @@ -121,6 +134,32 @@ router.post( }) ); +// ============================================================================ +// POST /gitnexus/detect-changes +// Map a git diff (uncommitted/staged/compare) to affected processes + risk. +// ============================================================================ + +router.post( + "/detect-changes", + asyncHandler(async (req: Request, res: Response) => { + const parsed = detectChangesBodySchema.safeParse(req.body ?? {}); + if (!parsed.success) { + const first = parsed.error.errors[0]; + throw Errors.invalidParameter( + first?.path.join(".") || "body", + first?.message ?? "Invalid request body" + ); + } + + const { scope, baseRef, worktree, repo } = parsed.data; + + logger.info("gitnexus: detectChanges", { scope, baseRef, repo }); + const data = await detectChanges({ scope, baseRef, worktree, repo }); + + return res.json({ success: true, data }); + }) +); + // ============================================================================ // GET /gitnexus/routes // ============================================================================ diff --git a/aitimemachine/api-server/src/services/gitNexusService.ts b/aitimemachine/api-server/src/services/gitNexusService.ts index 9005183e..d585156e 100644 --- a/aitimemachine/api-server/src/services/gitNexusService.ts +++ b/aitimemachine/api-server/src/services/gitNexusService.ts @@ -59,6 +59,7 @@ const METHOD_ALIASES: Readonly> = { gn_dep_graph: "cypher", gn_symbol_search: "query", gn_ping: "list_repos", + gn_detect_changes: "detect_changes", // Bare aliases (idempotent passthrough). context: "context", impact: "impact", @@ -66,6 +67,7 @@ const METHOD_ALIASES: Readonly> = { dep_graph: "cypher", symbol_search: "query", ping: "list_repos", + detect_changes: "detect_changes", }; function resolveToolName(method: string): string { @@ -115,6 +117,38 @@ export interface Symbol { exported: boolean; } +/** Which set of git changes to analyse for {@link detectChanges}. */ +export type ChangeScope = "unstaged" | "staged" | "all" | "compare"; + +export interface DetectChangesOptions { + /** Which changes to analyse. Defaults to "unstaged". */ + scope?: ChangeScope; + /** Base ref for the "compare" scope (e.g. "main"). */ + baseRef?: string; + /** Absolute path to a linked git worktree when changes live there. */ + worktree?: string; + /** Repository name/path; omit when a single repo is indexed. */ + repo?: string; +} + +/** + * Result of mapping a git diff to its blast radius. The GitNexus backend may + * return additional fields; the structured ones below are normalised, and the + * full payload is preserved under {@link ChangeAnalysis.raw}. + */ +export interface ChangeAnalysis { + /** Symbols touched by the diff (free-form strings as reported by the engine). */ + changedSymbols: string[]; + /** Execution flows / processes affected by the changed symbols. */ + affectedProcesses: string[]; + /** Risk classification of the change set, when the engine provides one. */ + riskLevel: string | null; + /** Human-readable risk/summary text, when provided. */ + summary: string | null; + /** The unnormalised backend payload for callers that need full detail. */ + raw: unknown; +} + // ============================================================================ // Core transport — in-process dispatch (drop-in replacement for the old // JSON-RPC `callGitNexus`). Same signature and same error-prefix contract @@ -351,6 +385,79 @@ export async function searchSymbols( }); } +/** + * Maps a git diff (uncommitted, staged, or compared against a base ref) to the + * processes it affects and an overall risk summary — the "blast radius" signal + * AITM needs when an agent checkpoints or opens a PR. + * + * Delegates to the GitNexus `detect_changes` tool and normalises its response + * into {@link ChangeAnalysis}. Returns safe empty defaults (with the raw + * payload preserved) when the backend returns an unexpected shape. + */ +export async function detectChanges( + options: DetectChangesOptions = {} +): Promise { + const params: Record = { + scope: options.scope ?? "unstaged", + }; + if (options.baseRef) { + params["base_ref"] = options.baseRef; + } + if (options.worktree) { + params["worktree"] = options.worktree; + } + if (options.repo) { + params["repo"] = options.repo; + } + + const result = await callGitNexus("gn_detect_changes", params); + + const empty: ChangeAnalysis = { + changedSymbols: [], + affectedProcesses: [], + riskLevel: null, + summary: null, + raw: result, + }; + + if (!isRecord(result)) { + logger.error("gitNexus: unexpected shape from detect_changes", undefined, { + result: String(result), + }); + return empty; + } + + const asStringArray = (value: unknown): string[] => + Array.isArray(value) + ? value.map((v) => + typeof v === "string" + ? v + : isRecord(v) && typeof v["name"] === "string" + ? (v["name"] as string) + : String(v) + ) + : []; + + const changedSymbols = asStringArray( + result["changedSymbols"] ?? result["changed_symbols"] ?? result["symbols"] + ); + const affectedProcesses = asStringArray( + result["affectedProcesses"] ?? result["affected_processes"] ?? result["processes"] + ); + const riskLevel = + typeof result["riskLevel"] === "string" + ? (result["riskLevel"] as string) + : typeof result["risk_level"] === "string" + ? (result["risk_level"] as string) + : typeof result["risk"] === "string" + ? (result["risk"] as string) + : null; + const summary = + typeof result["summary"] === "string" ? (result["summary"] as string) : null; + + return { changedSymbols, affectedProcesses, riskLevel, summary, raw: result }; +} + // ============================================================================ // Availability probe // ============================================================================ diff --git a/aitimemachine/api-server/src/services/memoryService.ts b/aitimemachine/api-server/src/services/memoryService.ts index 64f5c119..52bc1843 100644 --- a/aitimemachine/api-server/src/services/memoryService.ts +++ b/aitimemachine/api-server/src/services/memoryService.ts @@ -14,14 +14,19 @@ */ import crypto from "crypto"; +import { execFile } from "child_process"; +import { promisify } from "util"; import { db, schema } from "../db/index.js"; import { getEmbeddingService, type EmbeddingService, } from "./embeddings.js"; +import { resolveBeadsBinary } from "./engineManager.js"; import type { SavedContextSource } from "../db/schema.js"; import { logger } from "../lib/monitoring.js"; +const execFileAsync = promisify(execFile); + /** * Resolve where ingested memory should be persisted. Both fields are required * by the saved_contexts schema (NOT NULL FKs to users/projects). Callers that @@ -267,3 +272,100 @@ export async function ingestLibraryDoc( }, }); } + +// ============================================================================ +// Beads dependency-graph helpers +// +// Thin wrappers over the `bd` binary (resolved via engineManager) that expose +// the dependency DAG operations the multi-agent orchestration relies on: +// `bd dep add`, `bd dep list`, and `bd dep cycles`. These return the parsed +// `--json` payload from the binary. Kept here (next to ingestTask) so all +// beads-backed memory operations live in one service. +// ============================================================================ + +function beadsBinary(): string { + return resolveBeadsBinary().path ?? "bd"; +} + +function parseBeadsJson(stdout: string): unknown { + const trimmed = stdout.trim(); + if (trimmed.length === 0) { + return null; + } + try { + return JSON.parse(trimmed) as unknown; + } catch { + // Some `bd` mutations emit a human-readable confirmation rather than JSON; + // surface the raw message instead of throwing. + return { message: trimmed }; + } +} + +/** Allowed beads dependency edge types (mirrors `bd dep add -t`). */ +export type BeadsDependencyType = + | "blocks" + | "tracks" + | "related" + | "parent-child" + | "discovered-from" + | "until" + | "caused-by" + | "validates" + | "relates-to" + | "supersedes"; + +const VALID_DEP_TYPES: ReadonlySet = new Set([ + "blocks", + "tracks", + "related", + "parent-child", + "discovered-from", + "until", + "caused-by", + "validates", + "relates-to", + "supersedes", +]); + +/** + * Add a dependency edge: `blocked` depends on `blocker`. Runs the per-edge + * cycle check (the binary refuses and errors if the edge would create a cycle). + * Throws on failure (e.g. unknown id, or a would-be cycle) so the caller can + * map it to an HTTP status. + */ +export async function addDependency( + blocked: string, + blocker: string, + type?: string +): Promise { + const args = ["dep", "add", blocked, blocker]; + if (type && VALID_DEP_TYPES.has(type)) { + args.push("--type", type); + } + args.push("--json"); + + const { stdout } = await execFileAsync(beadsBinary(), args); + return parseBeadsJson(stdout); +} + +/** + * List dependencies for a task. `direction='down'` (default) returns what the + * task depends on (its blockers); `direction='up'` returns what depends on it. + */ +export async function listDependencies( + id: string, + direction: "up" | "down" = "down" +): Promise { + const args = ["dep", "list", id, `--direction=${direction}`, "--json"]; + const { stdout } = await execFileAsync(beadsBinary(), args); + return parseBeadsJson(stdout); +} + +/** + * Detect dependency cycles across the whole graph. Returns the parsed analysis + * from `bd dep cycles --json`. + */ +export async function findDependencyCycles(): Promise { + const { stdout } = await execFileAsync(beadsBinary(), ["dep", "cycles", "--json"]); + return parseBeadsJson(stdout); +} diff --git a/aitimemachine/mcp/src/index.ts b/aitimemachine/mcp/src/index.ts index 5629b1c5..4b0adb7b 100644 --- a/aitimemachine/mcp/src/index.ts +++ b/aitimemachine/mcp/src/index.ts @@ -10,6 +10,7 @@ import { getDisabledTools, getToolAvailability, getUnknownDisabledTools, + getProtectedEssentialTools, } from './lib/stable-tools.js'; import { formatHiddenFamiliesWarning, @@ -138,6 +139,13 @@ if (unknownDisabledTools.length > 0) { console.warn(`Unknown tools in DISABLED_TOOLS: ${unknownDisabledTools.join(', ')}`); } +const protectedEssentialTools = getProtectedEssentialTools(TOOL_SELECTION_OPTIONS); +if (protectedEssentialTools.length > 0) { + console.warn( + `Cannot disable essential tools (ignored in DISABLED_TOOLS): ${protectedEssentialTools.join(', ')}` + ); +} + function ensureLibLoaded() { if (!lib) { throw new Error('AITM core library not loaded yet'); diff --git a/aitimemachine/mcp/src/tools/register-beads-tools.ts b/aitimemachine/mcp/src/tools/register-beads-tools.ts index e3d22b6a..f8785603 100644 --- a/aitimemachine/mcp/src/tools/register-beads-tools.ts +++ b/aitimemachine/mcp/src/tools/register-beads-tools.ts @@ -52,6 +52,45 @@ async function beadsPatch( return jsonResponse(data); } +async function beadsPut( + endpoint: string, + body?: unknown +): Promise> { + const data = await aitmApiRequest(LABEL, `/beads${endpoint}`, { + method: 'PUT', + body, + }); + return jsonResponse(data); +} + +/** + * Build a query-string from a set of params, skipping undefined/empty values + * and joining array values with commas. Returns "" when no params are set. + */ +function buildQuery( + params: Readonly> +): string { + const search = new URLSearchParams(); + for (const [key, value] of Object.entries(params)) { + if (value === undefined) { + continue; + } + if (Array.isArray(value)) { + const joined = value.map((item) => item.trim()).filter(Boolean).join(','); + if (joined.length > 0) { + search.set(key, joined); + } + continue; + } + const str = String(value).trim(); + if (str.length > 0) { + search.set(key, str); + } + } + const qs = search.toString(); + return qs.length > 0 ? `?${qs}` : ''; +} + export const registerBeadsTools = createToolRegistrar([ defineTool({ name: 'beads_list_tasks', @@ -79,7 +118,7 @@ export const registerBeadsTools = createToolRegistrar([ id: z.string().describe('The ID of the task to mark as ready'), }, annotations: idempotentMutationAnnotations(), - run: async (args) => beadsPatch(`/tasks/${args.id}/ready`), + run: async (args) => beadsPut(`/tasks/${encodeURIComponent(args.id)}/ready`), }), defineTool({ @@ -89,7 +128,7 @@ export const registerBeadsTools = createToolRegistrar([ id: z.string().describe('The ID of the task to mark as done'), }, annotations: idempotentMutationAnnotations(), - run: async (args) => beadsPatch(`/tasks/${args.id}/done`), + run: async (args) => beadsPut(`/tasks/${encodeURIComponent(args.id)}/done`), }), defineTool({ @@ -99,7 +138,176 @@ export const registerBeadsTools = createToolRegistrar([ id: z.string().describe('The ID of the task to retrieve'), }, annotations: readOnlyAnnotations(), - run: async (args) => beadsGet(`/tasks/${args.id}`), + run: async (args) => beadsGet(`/tasks/${encodeURIComponent(args.id)}`), + }), + + defineTool({ + name: 'beads_ready', + description: + 'Query the Beads work queue for tasks that are unblocked and ready to work on right now (all dependencies satisfied). This is the core "what can I work on next?" primitive for autonomous agents. Supports filtering by priority, assignee, labels, and a result limit.', + schema: { + priority: z + .number() + .int() + .min(0) + .max(4) + .optional() + .describe('Filter to a single priority level (0 = highest, 4 = lowest)'), + assignee: z + .string() + .optional() + .describe('Filter to tasks assigned to this assignee'), + unassigned: z + .boolean() + .optional() + .describe('When true, return only tasks with no assignee'), + labels: z + .array(z.string()) + .optional() + .describe('AND filter: task must have ALL of these labels'), + labelsAny: z + .array(z.string()) + .optional() + .describe('OR filter: task must have AT LEAST ONE of these labels'), + limit: z + .number() + .int() + .min(1) + .max(100) + .optional() + .describe('Maximum number of ready tasks to return (1-100)'), + sort: z + .enum(['priority', 'hybrid', 'oldest']) + .optional() + .describe('Sort policy for the returned ready tasks'), + }, + annotations: readOnlyAnnotations(), + run: async (args) => + beadsGet( + `/ready${buildQuery({ + priority: args.priority, + assignee: args.assignee, + unassigned: args.unassigned, + labels: args.labels, + labelsAny: args.labelsAny, + limit: args.limit, + sort: args.sort, + })}` + ), + }), + + defineTool({ + name: 'beads_blocked', + description: + 'List Beads tasks that are currently blocked, along with the dependencies blocking each one. Use this to see what is stuck in the DAG and why, so an operator or agent can unblock autonomous work.', + schema: {}, + annotations: readOnlyAnnotations(), + run: async () => beadsGet('/blocked'), + }), + + defineTool({ + name: 'beads_stats', + description: + 'Get aggregate statistics for the Beads DAG: totals by state (open, in_progress, closed, blocked), the count of ready tasks, and the average lead time. A cheap, high-signal health check for an orchestrator or dashboard.', + schema: {}, + annotations: readOnlyAnnotations(), + run: async () => beadsGet('/stats'), + }), + + defineTool({ + name: 'beads_add_dependency', + description: + 'Add a dependency edge from one Beads task to another after creation. Use this when an agent discovers a blocker mid-task (a discovered-from edge) or otherwise needs to refine the DAG. The dependency type defaults to "blocks".', + schema: { + id: z.string().describe('The task that has the dependency'), + dependsOn: z + .string() + .describe('The task that must be resolved first (the dependency)'), + type: z + .enum(['blocks', 'related', 'parent-child', 'discovered-from']) + .optional() + .describe('The kind of dependency edge to create (default: blocks)'), + }, + annotations: mutatingAnnotations(), + run: async (args) => + beadsPost(`/tasks/${encodeURIComponent(args.id)}/deps`, { + dependsOn: args.dependsOn, + type: args.type, + }), + }), + + defineTool({ + name: 'beads_update_task', + description: + 'Update editable fields of an existing Beads task: title, priority, assignee, status, and/or labels. Only the fields you provide are changed; at least one field is required.', + schema: { + id: z.string().describe('The ID of the task to update'), + title: z.string().optional().describe('New title for the task'), + priority: z + .number() + .int() + .min(0) + .max(4) + .optional() + .describe('New priority (0 = highest, 4 = lowest)'), + assignee: z + .string() + .optional() + .describe('New assignee (pass an empty string to clear the assignee)'), + status: z + .string() + .optional() + .describe('New status (e.g. open, in_progress, blocked, deferred, closed)'), + labels: z + .array(z.string()) + .optional() + .describe('Replace the full set of labels with this list'), + }, + annotations: mutatingAnnotations(), + run: async (args) => + beadsPatch(`/tasks/${encodeURIComponent(args.id)}`, { + title: args.title, + priority: args.priority, + assignee: args.assignee, + status: args.status, + labels: args.labels, + }), + }), + + defineTool({ + name: 'beads_close_task', + description: + 'Close (complete) a Beads task with an optional human-readable reason that is recorded for the audit trail. Use this to explain why an agent finished or abandoned the work.', + schema: { + id: z.string().describe('The ID of the task to close'), + reason: z + .string() + .optional() + .describe('Why the task is being closed (default: "Completed")'), + }, + annotations: idempotentMutationAnnotations(), + run: async (args) => + beadsPost(`/tasks/${encodeURIComponent(args.id)}/close`, { + reason: args.reason, + }), + }), + + defineTool({ + name: 'beads_reopen_task', + description: + 'Reopen a previously closed Beads task, for example when a fix regresses and the work must be revisited. An optional reason is recorded.', + schema: { + id: z.string().describe('The ID of the task to reopen'), + reason: z + .string() + .optional() + .describe('Why the task is being reopened'), + }, + annotations: idempotentMutationAnnotations(), + run: async (args) => + beadsPost(`/tasks/${encodeURIComponent(args.id)}/reopen`, { + reason: args.reason, + }), }), ]); diff --git a/gitgram/backend/prisma/schema.prisma b/gitgram/backend/prisma/schema.prisma index ce453a57..f1ed3ed4 100644 --- a/gitgram/backend/prisma/schema.prisma +++ b/gitgram/backend/prisma/schema.prisma @@ -86,6 +86,10 @@ model User { emailVerified Boolean @default(false) verified Boolean @default(false) isPrivate Boolean @default(false) + // Viewer opt-in for author-self-labeled adult content. When false (default), + // posts an author marked as adult (sexual/nudity/porn) are hidden from this + // user's feed. See services/selfLabels.ts. + adultContentEnabled Boolean @default(false) isBanned Boolean @default(false) bannedAt DateTime? bannedReason String? @@ -373,6 +377,13 @@ model Post { isArchived Boolean @default(false) archivedAt DateTime? + // Author self-labeling / content warnings (ported from Bluesky SELF_LABELS). + // Voluntary, author-applied sensitivity tags. Each maps to a hide-or-warn + // behavior in the feed pipeline. Adult labels (sexual, nudity, porn) hide by + // default; graphic-media and spoiler warn (blur) by default. + selfLabels String[] @default([]) // e.g. ["sexual", "graphic-media", "spoiler"] + contentWarning String? // optional free-text warning shown alongside the label + // Optional geotagging for map / nearby discovery location String? latitude Float? diff --git a/gitgram/backend/src/controllers/githubController.ts b/gitgram/backend/src/controllers/githubController.ts index 1efa78c8..8e17bd80 100644 --- a/gitgram/backend/src/controllers/githubController.ts +++ b/gitgram/backend/src/controllers/githubController.ts @@ -9,6 +9,23 @@ import logger from '../utils/logger' import { asyncHandler, Errors, ApiError } from '../middleware/errorHandler' import { getCachedProfile, setCachedProfile, setCachedRepo } from '../utils/githubProfileCache' import { fetchGitHubTrending } from '../services/ghSocialBridge' +import { GitHubService } from '../services/githubService' +import { createNotification } from '../services/notificationService' + +/** + * Resolve the authenticated user's stored GitHub OAuth token, or throw a + * 400 telling them to connect GitHub. Shared by all two-way GitHub actions. + */ +async function requireUserGitHubToken(userId: string): Promise { + const user = await prisma.user.findUnique({ + where: { id: userId }, + select: { githubAccessToken: true }, + }) + if (!user?.githubAccessToken) { + throw Errors.badRequest('GitHub account not linked. Connect GitHub in settings first.') + } + return user.githubAccessToken +} export const githubController = { // Existing endpoints @@ -677,4 +694,127 @@ export const githubController = { res.json({ message: 'Activity cache cleared successfully' }) }), + + // ============================================ + // TWO-WAY GITHUB ACTIONS (write-back via user OAuth token) + // Ported from gh-social: star/unstar a repo and follow/unfollow a user on + // GitHub.com, plus live "have I starred / am I following" status checks. + // ============================================ + + /** + * Star a repository on GitHub.com using the user's OAuth token. + * PUT /api/v1/github/star/:owner/:repo + */ + starRepo: asyncHandler(async (req: AuthRequest, res: Response) => { + const { owner, repo } = req.params + const userId = req.userId! + const token = await requireUserGitHubToken(userId) + + const github = new GitHubService(token) + const fullName = `${owner}/${repo}` + const starred = await github.starRepo(fullName) + + res.json({ message: 'Repository starred on GitHub', repository: fullName, starred }) + }), + + /** + * Remove a star from a repository on GitHub.com. + * DELETE /api/v1/github/star/:owner/:repo + */ + unstarRepo: asyncHandler(async (req: AuthRequest, res: Response) => { + const { owner, repo } = req.params + const userId = req.userId! + const token = await requireUserGitHubToken(userId) + + const github = new GitHubService(token) + const fullName = `${owner}/${repo}` + const starred = await github.unstarRepo(fullName) + + res.json({ message: 'Repository unstarred on GitHub', repository: fullName, starred }) + }), + + /** + * Live check: has the user starred this repo on GitHub.com? + * GET /api/v1/github/star/:owner/:repo + */ + getStarStatus: asyncHandler(async (req: AuthRequest, res: Response) => { + const { owner, repo } = req.params + const userId = req.userId! + const token = await requireUserGitHubToken(userId) + + const github = new GitHubService(token) + const fullName = `${owner}/${repo}` + const starred = await github.hasStarred(fullName) + + res.json({ repository: fullName, starred }) + }), + + /** + * Follow a GitHub user on GitHub.com using the user's OAuth token. + * When the followed GitHub user maps to a Gitgram account, send them an + * in-app notification (mirrors gh-social's follow notification). + * PUT /api/v1/github/follow-user/:username + */ + followGitHubUser: asyncHandler(async (req: AuthRequest, res: Response) => { + const { username } = req.params + const userId = req.userId! + const token = await requireUserGitHubToken(userId) + + const github = new GitHubService(token) + const following = await github.followUser(username) + + // Notify the target if they have a Gitgram account linked to this GitHub login. + const actor = await prisma.user.findUnique({ + where: { id: userId }, + select: { username: true }, + }) + const target = await prisma.user.findFirst({ + where: { githubUsername: { equals: username, mode: 'insensitive' } }, + select: { id: true }, + }) + if (target && target.id !== userId && actor?.username) { + try { + await createNotification( + target.id, + 'FOLLOW', + `${actor.username} followed you on GitHub`, + userId + ) + } catch (notifyError: unknown) { + logger.error('Failed to send GitHub follow notification:', notifyError) + } + } + + res.json({ message: 'User followed on GitHub', username, following }) + }), + + /** + * Unfollow a GitHub user on GitHub.com. + * DELETE /api/v1/github/follow-user/:username + */ + unfollowGitHubUser: asyncHandler(async (req: AuthRequest, res: Response) => { + const { username } = req.params + const userId = req.userId! + const token = await requireUserGitHubToken(userId) + + const github = new GitHubService(token) + const following = await github.unfollowUser(username) + + res.json({ message: 'User unfollowed on GitHub', username, following }) + }), + + /** + * Live check: is the user following this GitHub user? + * GET /api/v1/github/follow-user/:username + */ + getFollowUserStatus: asyncHandler(async (req: AuthRequest, res: Response) => { + const { username } = req.params + const userId = req.userId! + const token = await requireUserGitHubToken(userId) + + const github = new GitHubService(token) + const following = await github.isFollowing(username) + + res.json({ username, following }) + }), } diff --git a/gitgram/backend/src/controllers/postController.ts b/gitgram/backend/src/controllers/postController.ts index 6443fd04..4e8a5e5a 100644 --- a/gitgram/backend/src/controllers/postController.ts +++ b/gitgram/backend/src/controllers/postController.ts @@ -13,6 +13,7 @@ import { validateCheckpoint, buildCheckpointRef, formatCheckpointDescription } f import type { AitmCheckpointRef } from '../services/aitmService'; import { getCachedComments, setCachedComments, invalidateCommentCache } from '../utils/commentCache'; import { tuneFeed, type TunableFeedItem } from '../services/feedTuner'; +import { normalizeSelfLabels, decideSelfLabel } from '../services/selfLabels'; export const createPost = asyncHandler(async (req: AuthRequest, res: Response) => { const { @@ -29,6 +30,8 @@ export const createPost = asyncHandler(async (req: AuthRequest, res: Response) = diffSummary, changedFiles, changeStoryTitle, + selfLabels, + contentWarning, } = req.body; const account = await prisma.account.findFirst({ where: { userId: req.userId } }); if (!account) throw Errors.notFound('Account'); @@ -103,6 +106,13 @@ export const createPost = asyncHandler(async (req: AuthRequest, res: Response) = const effectiveType = checkpointId ? 'CHANGE_STORY' : type; + // Author self-labeling / content warnings (voluntary sensitivity tags). + const normalizedSelfLabels = normalizeSelfLabels(selfLabels); + const normalizedContentWarning = + typeof contentWarning === 'string' && contentWarning.trim().length > 0 + ? contentWarning.trim().slice(0, 300) + : null; + // Validate and resolve AITM checkpoint metadata (optional — allows post even if AITM is down) let resolvedAitmCheckpointRef: AitmCheckpointRef | null = null; const effectiveAitmCheckpointId = typeof checkpointId === 'string' && checkpointId.trim() ? checkpointId.trim() : null; @@ -128,6 +138,8 @@ export const createPost = asyncHandler(async (req: AuthRequest, res: Response) = aitmProjectId: effectiveAitmProjectId, aitmCheckpointRef: resolvedAitmCheckpointRef ?? undefined, type: effectiveType, + selfLabels: normalizedSelfLabels, + contentWarning: normalizedContentWarning, }, include: { user: { @@ -197,13 +209,41 @@ export const createPost = asyncHandler(async (req: AuthRequest, res: Response) = res.status(201).json({ post: { ...post, linkPreviews } }); }); +/** + * Derive the thread-root key for a feed post. + * + * Gitgram posts are flat (no native reply chain), so the closest analog to a + * Bluesky thread is an AITM change-story progression: a run of posts about the + * same AITM project/checkpoint. Collapsing those keeps a busy change-story from + * flooding the following feed, surfacing its highest-ranked entry once. + * + * We deliberately do NOT key on `repositoryId` alone — a repository can host + * many distinct, unrelated posts, and collapsing all of them would regress the + * general feed. Only the AITM-project subject is treated as a thread root. + */ +function deriveThreadRoot(post: Record): string | null { + const aitmProjectId = post.aitmProjectId; + if (typeof aitmProjectId === 'string' && aitmProjectId.length > 0) { + return `aitm:${aitmProjectId}`; + } + return null; +} + /** Map a raw feed post to the minimal shape required by FeedTuner. */ function toTunableItem(post: Record): TunableFeedItem { + const selfLabel = decideSelfLabel({ + selfLabels: (post.selfLabels as string[] | null | undefined) ?? null, + contentWarning: (post.contentWarning as string | null | undefined) ?? null, + }); return { ...(post as TunableFeedItem), id: post.id as string, type: 'post', authorId: (post.userId as string | null) ?? null, + rootPostId: deriveThreadRoot(post), + // Attach the self-label decision so the client can blur 'warn' posts and so + // the feed can drop 'hide' posts (see applySelfLabelBehavior). + selfLabel, score: (post.likesCount as number ?? 0) * 2 + (post.commentsCount as number ?? 0) * 3, likesCount: post.likesCount as number | undefined, commentsCount: post.commentsCount as number | undefined, @@ -212,18 +252,47 @@ function toTunableItem(post: Record): TunableFeedItem { }; } +/** + * Apply author self-label hide/warn behavior to a tuned feed. + * + * `hide` items (adult content) are removed unless the viewer is the author or + * has opted into adult content. `warn` items stay in the feed carrying their + * `selfLabel` decision so the client can blur them behind the warning. + */ +function applySelfLabelBehavior( + items: TunableFeedItem[], + opts: { viewerId: string; adultContentEnabled: boolean } +): TunableFeedItem[] { + return items.filter(item => { + const decision = item.selfLabel as ReturnType | undefined; + if (!decision || decision.behavior !== 'hide') return true; + // Always show the author their own labeled post. + if (item.authorId && item.authorId === opts.viewerId) return true; + return opts.adultContentEnabled; + }); +} + export const getFeed = asyncHandler(async (req: AuthRequest, res: Response) => { const userId = req.userId!; const { page = 1, limit = 20, cursor } = req.query; + // Viewer's opt-in for author-self-labeled adult content (default: hidden). + const viewer = await prisma.user.findUnique({ + where: { id: userId }, + select: { adultContentEnabled: true }, + }); + const adultContentEnabled = viewer?.adultContentEnabled ?? false; + const labelOpts = { viewerId: userId, adultContentEnabled }; + if (typeof cursor === 'string' && cursor.trim()) { const result = await FeedService.getPersonalizedFeedCursor( userId, cursor.trim(), Number(limit) ); - const tunedPosts = tuneFeed( - (result.posts as Record[]).map(toTunableItem) + const tunedPosts = applySelfLabelBehavior( + tuneFeed((result.posts as Record[]).map(toTunableItem)), + labelOpts ); res.json({ ...result, posts: tunedPosts }); return; @@ -242,8 +311,9 @@ export const getFeed = asyncHandler(async (req: AuthRequest, res: Response) => { return; } - const tunedPosts = tuneFeed( - (posts as Record[]).map(toTunableItem) + const tunedPosts = applySelfLabelBehavior( + tuneFeed((posts as Record[]).map(toTunableItem)), + labelOpts ); res.json({ posts: tunedPosts, isDiscover: false }); diff --git a/gitgram/backend/src/routes/github.ts b/gitgram/backend/src/routes/github.ts index f13f598f..a649cdbd 100644 --- a/gitgram/backend/src/routes/github.ts +++ b/gitgram/backend/src/routes/github.ts @@ -405,6 +405,128 @@ router.delete('/bookmark/:owner/:repo', authenticate, githubController.unbookmar */ router.get('/stats/:owner/:repo', githubController.getRepositoryStats); +// ============================================ +// TWO-WAY GITHUB ACTIONS (write-back via user OAuth token) +// Ported from gh-social. Star/unstar a repo and follow/unfollow a GitHub user +// on GitHub.com, plus live status checks. All require the user's linked GitHub +// OAuth token (stored on the user record) and an authenticated session. +// ============================================ + +/** + * @swagger + * /api/v1/github/star/{owner}/{repo}: + * get: + * summary: Check whether the authenticated user has starred a repo on GitHub + * tags: [GitHub] + * security: + * - bearerAuth: [] + * parameters: + * - in: path + * name: owner + * required: true + * schema: + * type: string + * - in: path + * name: repo + * required: true + * schema: + * type: string + * responses: + * 200: + * description: Star status + * put: + * summary: Star a repository on GitHub.com + * tags: [GitHub] + * security: + * - bearerAuth: [] + * parameters: + * - in: path + * name: owner + * required: true + * schema: + * type: string + * - in: path + * name: repo + * required: true + * schema: + * type: string + * responses: + * 200: + * description: Repository starred + * delete: + * summary: Remove a star from a repository on GitHub.com + * tags: [GitHub] + * security: + * - bearerAuth: [] + * parameters: + * - in: path + * name: owner + * required: true + * schema: + * type: string + * - in: path + * name: repo + * required: true + * schema: + * type: string + * responses: + * 200: + * description: Repository unstarred + */ +router.get('/star/:owner/:repo', authenticate, githubController.getStarStatus); +router.put('/star/:owner/:repo', authenticate, githubController.starRepo); +router.delete('/star/:owner/:repo', authenticate, githubController.unstarRepo); + +/** + * @swagger + * /api/v1/github/follow-user/{username}: + * get: + * summary: Check whether the authenticated user follows a GitHub user + * tags: [GitHub] + * security: + * - bearerAuth: [] + * parameters: + * - in: path + * name: username + * required: true + * schema: + * type: string + * responses: + * 200: + * description: Follow status + * put: + * summary: Follow a GitHub user on GitHub.com + * tags: [GitHub] + * security: + * - bearerAuth: [] + * parameters: + * - in: path + * name: username + * required: true + * schema: + * type: string + * responses: + * 200: + * description: User followed + * delete: + * summary: Unfollow a GitHub user on GitHub.com + * tags: [GitHub] + * security: + * - bearerAuth: [] + * parameters: + * - in: path + * name: username + * required: true + * schema: + * type: string + * responses: + * 200: + * description: User unfollowed + */ +router.get('/follow-user/:username', authenticate, githubController.getFollowUserStatus); +router.put('/follow-user/:username', authenticate, githubController.followGitHubUser); +router.delete('/follow-user/:username', authenticate, githubController.unfollowGitHubUser); + // ============================================ // GITHUB ACTIVITY FEED ENDPOINTS // ============================================ diff --git a/gitgram/backend/src/services/feedTuner.ts b/gitgram/backend/src/services/feedTuner.ts index 3f935c51..4140c950 100644 --- a/gitgram/backend/src/services/feedTuner.ts +++ b/gitgram/backend/src/services/feedTuner.ts @@ -33,6 +33,37 @@ export interface TunableFeedItem { type: FeedItemType; /** Author/owner identifier — null for system or anonymous items. */ authorId: string | null; + /** + * Identifier of the conversation/thread this item belongs to. + * + * Ported from Bluesky's `FeedViewPostsSlice.rootUri` concept: multiple items + * that share the same thread root collapse to a single entry (the most recent) + * so a busy thread surfaces once instead of flooding the feed. + * + * In Gitgram a "thread" is the set of posts about the same subject. Callers + * derive this from a stable subject key — typically the repository id or the + * AITM project/checkpoint id. When absent, the item is treated as its own + * thread root and is never collapsed. + */ + rootPostId?: string | null; + /** + * Explicit thread identifier. When both `threadId` and `rootPostId` are set, + * `threadId` wins. Provided as a convenience alias so callers that already + * model threads can pass through without reshaping the field name. + */ + threadId?: string | null; + /** + * When true, this item belongs to a thread the viewer has muted and should be + * dropped by `removeMutedThreads`. The backend has no thread-mute store yet, + * so callers that lack mute data simply leave this undefined. + */ + isThreadMuted?: boolean; + /** + * When true, this item is a reply whose parent/root context could not be + * resolved (an "orphan"). `removeOrphans` drops these so the feed never shows + * a dangling reply with no visible context. + */ + isOrphan?: boolean; /** Pre-computed feed ranking score (higher = better). */ score: number; /** Optional trending score override; computed on-the-fly when absent. */ @@ -113,6 +144,28 @@ export interface FeedTunerOptions { * @default [] */ sponsoredItems?: ReadonlyArray; + + /** + * When true, collapse items that share the same thread root so each + * conversation appears at most once (its highest-ranked entry survives). + * Ported from Bluesky's `FeedTuner.dedupThreads`. + * @default true + */ + dedupeThreads?: boolean; + + /** + * When true, drop items flagged `isThreadMuted`. + * Ported from Bluesky's `FeedTuner.removeMutedThreads`. + * @default true + */ + removeMutedThreads?: boolean; + + /** + * When true, drop items flagged `isOrphan` (replies whose context could not + * be resolved). Ported from Bluesky's `FeedTuner.removeOrphans`. + * @default true + */ + removeOrphans?: boolean; } // --------------------------------------------------------------------------- @@ -126,6 +179,9 @@ const DEFAULT_TRENDING_BOOST_THRESHOLD = 50; const DEFAULT_TRENDING_BOOST_MULTIPLIER = 1.5; const DEFAULT_DIVERSITY_PENALTY_AFTER = 3; const DEFAULT_DIVERSITY_PENALTY_MULTIPLIER = 0.5; +const DEFAULT_DEDUPE_THREADS = true; +const DEFAULT_REMOVE_MUTED_THREADS = true; +const DEFAULT_REMOVE_ORPHANS = true; // --------------------------------------------------------------------------- // Internal helpers (pure functions — no side-effects) @@ -383,6 +439,64 @@ function deduplicateById(items: ReadonlyArray): TunableFeedItem }); } +/** + * Resolve the thread-root key for an item. + * + * `threadId` takes precedence over `rootPostId`. When neither is present the + * item is its own thread root (it can never collapse another item) and we + * return `null` to signal "no shared thread". + */ +function threadRootKey(item: TunableFeedItem): string | null { + if (typeof item.threadId === 'string' && item.threadId.length > 0) { + return item.threadId; + } + if (typeof item.rootPostId === 'string' && item.rootPostId.length > 0) { + return item.rootPostId; + } + return null; +} + +/** + * Collapse items that share the same thread root so each conversation surfaces + * once. The FIRST item encountered for a given root wins; later items sharing + * that root are dropped. + * + * Callers are expected to pass items already ordered so the "winning" entry per + * thread (e.g. the most recent / highest-ranked) appears first. The tuner runs + * this AFTER `sortByScore`, so the highest-scoring entry of each thread is kept, + * mirroring Bluesky's "you only see the most recent reply" behaviour for the + * following feed. + * + * Items without a thread root (see `threadRootKey`) are always preserved. + * Returns a new array — input is not modified. + */ +function deduplicateByThreadRoot(items: ReadonlyArray): TunableFeedItem[] { + const seenRoots = new Set(); + return items.filter(item => { + const root = threadRootKey(item); + if (root === null) return true; // standalone item, never collapsed + if (seenRoots.has(root)) return false; + seenRoots.add(root); + return true; + }); +} + +/** + * Drop items flagged `isThreadMuted`. Ported from Bluesky's + * `FeedTuner.removeMutedThreads`. Returns a new array. + */ +function dropMutedThreads(items: ReadonlyArray): TunableFeedItem[] { + return items.filter(item => item.isThreadMuted !== true); +} + +/** + * Drop items flagged `isOrphan`. Ported from Bluesky's + * `FeedTuner.removeOrphans`. Returns a new array. + */ +function dropOrphans(items: ReadonlyArray): TunableFeedItem[] { + return items.filter(item => item.isOrphan !== true); +} + // --------------------------------------------------------------------------- // FeedTuner class // --------------------------------------------------------------------------- @@ -409,6 +523,9 @@ export class FeedTuner { diversityPenaltyAfter: options.diversityPenaltyAfter ?? DEFAULT_DIVERSITY_PENALTY_AFTER, diversityPenaltyMultiplier: options.diversityPenaltyMultiplier ?? DEFAULT_DIVERSITY_PENALTY_MULTIPLIER, sponsoredItems: options.sponsoredItems ?? [], + dedupeThreads: options.dedupeThreads ?? DEFAULT_DEDUPE_THREADS, + removeMutedThreads: options.removeMutedThreads ?? DEFAULT_REMOVE_MUTED_THREADS, + removeOrphans: options.removeOrphans ?? DEFAULT_REMOVE_ORPHANS, }; } @@ -416,12 +533,16 @@ export class FeedTuner { * Process a raw feed array and return a tuned feed. * * Pipeline: - * 1. Deduplicate - * 2. Apply score adjustments (trending boost + diversity penalty) - * 3. Re-sort by adjusted score - * 4. Enforce author run limit - * 5. Interleave content types - * 6. Inject sponsored items + * 1. Deduplicate by id + * 2. Drop orphaned replies (removeOrphans) + * 3. Drop muted threads (removeMutedThreads) + * 4. Apply score adjustments (trending boost + diversity penalty) + * 5. Re-sort by adjusted score + * 6. Collapse threads by root (dedupThreads) — keeps the highest-scoring + * entry per thread, so it runs after the sort + * 7. Enforce author run limit + * 8. Interleave content types + * 9. Inject sponsored items * * @param posts - Raw feed items (not mutated). * @returns New array of tuned feed items. @@ -429,14 +550,25 @@ export class FeedTuner { tune(posts: ReadonlyArray): TunableFeedItem[] { if (posts.length === 0) return []; - const step1 = deduplicateById(posts); - const step2 = applyScoreAdjustments(step1, this.options); - const step3 = sortByScore(step2); - const step4 = enforceAuthorRun(step3, this.options.maxAuthorRun); - const step5 = interleaveContentTypes(step4); - const step6 = injectSponsored(step5, this.options.sponsoredItems, this.options.sponsoredInterval); + const deduped = deduplicateById(posts); + const withoutOrphans = this.options.removeOrphans ? dropOrphans(deduped) : deduped; + const withoutMuted = this.options.removeMutedThreads + ? dropMutedThreads(withoutOrphans) + : withoutOrphans; + const adjusted = applyScoreAdjustments(withoutMuted, this.options); + const sorted = sortByScore(adjusted); + const threadDeduped = this.options.dedupeThreads + ? deduplicateByThreadRoot(sorted) + : sorted; + const runLimited = enforceAuthorRun(threadDeduped, this.options.maxAuthorRun); + const interleaved = interleaveContentTypes(runLimited); + const withSponsored = injectSponsored( + interleaved, + this.options.sponsoredItems, + this.options.sponsoredInterval + ); - return step6; + return withSponsored; } } diff --git a/gitgram/backend/src/services/githubService.ts b/gitgram/backend/src/services/githubService.ts index 903c0ca9..51f6f1e5 100644 --- a/gitgram/backend/src/services/githubService.ts +++ b/gitgram/backend/src/services/githubService.ts @@ -10,11 +10,43 @@ const CACHE_TTL = { SEARCH: 1 * 60 * 60, // 1 hour }; +/** Parse an "owner/repo" string into its parts, validating the shape. */ +function parseRepoFullName(fullName: string): { owner: string; repo: string } { + const trimmed = (fullName || '').trim().replace(/\.git$/i, ''); + const parts = trimmed.split('/').filter(Boolean); + if (parts.length !== 2) { + throw new Error(`Invalid repository full name: "${fullName}". Expected "owner/repo".`); + } + return { owner: parts[0], repo: parts[1] }; +} + +/** Strip a leading "@" and surrounding whitespace from a username. */ +function normalizeUsername(username: string): string { + const normalized = (username || '').trim().replace(/^@/, ''); + if (!normalized) { + throw new Error('A GitHub username is required.'); + } + return normalized; +} + +/** Narrow an unknown Octokit error to detect a 404 (not-found) response. */ +function isNotFoundError(error: unknown): boolean { + return ( + typeof error === 'object' && + error !== null && + 'status' in error && + (error as { status?: number }).status === 404 + ); +} + export class GitHubService { private octokit: Octokit; private redis: any; + /** The per-user OAuth token, when this instance was built for a user. */ + private readonly userAccessToken?: string; constructor(accessToken?: string) { + this.userAccessToken = accessToken; this.octokit = new Octokit({ auth: accessToken || GITHUB_TOKEN, }); @@ -333,6 +365,132 @@ export class GitHubService { return results; } + // ============================================ + // TWO-WAY GITHUB ACTIONS (write-back via user OAuth token) + // + // Ported from gh-social (githubApi.ts: starAction, followAction, + // hasIStarredTheRepo, amIFollowingTheUser). These require a per-user OAuth + // token with the `public_repo`/`user:follow` scopes — construct the service + // with `new GitHubService(userAccessToken)`. The shared app token used by + // the singleton MUST NOT be used here, so each method guards against it. + // ============================================ + + /** + * Guard: write actions require a per-user OAuth token, never the shared + * app/server token. Throws a clear error when the service was built without + * an explicit token. + */ + private assertUserToken(): void { + if (!this.userAccessToken) { + throw new Error( + 'A GitHub user access token is required for write actions. ' + + 'Construct GitHubService with the user OAuth token.' + ); + } + } + + /** + * Star a repository on GitHub.com on behalf of the authenticated user. + * Idempotent: starring an already-starred repo still resolves to starred. + * @param fullName - "owner/repo" + * @returns true when the repo is starred after the call. + */ + async starRepo(fullName: string): Promise { + this.assertUserToken(); + const { owner, repo } = parseRepoFullName(fullName); + try { + await this.octokit.activity.starRepoForAuthenticatedUser({ owner, repo }); + return true; + } catch (error: unknown) { + logger.error(`Failed to star repo ${fullName}:`, error); + throw new Error('Failed to star repository on GitHub'); + } + } + + /** + * Remove a star from a repository on GitHub.com. + * Idempotent: unstarring a not-starred repo still resolves to not-starred. + * @returns true when the repo is no longer starred after the call. + */ + async unstarRepo(fullName: string): Promise { + this.assertUserToken(); + const { owner, repo } = parseRepoFullName(fullName); + try { + await this.octokit.activity.unstarRepoForAuthenticatedUser({ owner, repo }); + return true; + } catch (error: unknown) { + logger.error(`Failed to unstar repo ${fullName}:`, error); + throw new Error('Failed to unstar repository on GitHub'); + } + } + + /** + * Live check: has the authenticated user starred this repo? + * GitHub returns 204 when starred and 404 when not. + */ + async hasStarred(fullName: string): Promise { + this.assertUserToken(); + const { owner, repo } = parseRepoFullName(fullName); + try { + await this.octokit.activity.checkRepoIsStarredByAuthenticatedUser({ owner, repo }); + return true; + } catch (error: unknown) { + if (isNotFoundError(error)) return false; + logger.error(`Failed to check star status for ${fullName}:`, error); + throw new Error('Failed to check star status on GitHub'); + } + } + + /** + * Follow a GitHub user on behalf of the authenticated user. + * Idempotent. + * @returns true when the user is followed after the call. + */ + async followUser(username: string): Promise { + this.assertUserToken(); + const normalized = normalizeUsername(username); + try { + await this.octokit.users.follow({ username: normalized }); + return true; + } catch (error: unknown) { + logger.error(`Failed to follow user ${normalized}:`, error); + throw new Error('Failed to follow user on GitHub'); + } + } + + /** + * Unfollow a GitHub user. Idempotent. + * @returns true when the user is no longer followed after the call. + */ + async unfollowUser(username: string): Promise { + this.assertUserToken(); + const normalized = normalizeUsername(username); + try { + await this.octokit.users.unfollow({ username: normalized }); + return true; + } catch (error: unknown) { + logger.error(`Failed to unfollow user ${normalized}:`, error); + throw new Error('Failed to unfollow user on GitHub'); + } + } + + /** + * Live check: is the authenticated user following this GitHub user? + * GitHub returns 204 when following and 404 when not. + */ + async isFollowing(username: string): Promise { + this.assertUserToken(); + const normalized = normalizeUsername(username); + try { + await this.octokit.users.checkPersonIsFollowedByAuthenticated({ username: normalized }); + return true; + } catch (error: unknown) { + if (isNotFoundError(error)) return false; + logger.error(`Failed to check follow status for ${normalized}:`, error); + throw new Error('Failed to check follow status on GitHub'); + } + } + /** * Get rate limit status */ diff --git a/gitgram/backend/src/services/selfLabels.ts b/gitgram/backend/src/services/selfLabels.ts new file mode 100644 index 00000000..52b37a41 --- /dev/null +++ b/gitgram/backend/src/services/selfLabels.ts @@ -0,0 +1,111 @@ +/** + * selfLabels.ts + * + * Author self-labeling / content warnings. + * + * Ported from Bluesky's moderation model (src/lib/moderation.ts: SELF_LABELS, + * ADULT_CONTENT_LABELS, OTHER_SELF_LABELS and the hide-vs-warn behavior). An + * AUTHOR voluntarily marks their own post as sensitive; each label maps to a + * `hide` or `warn` behavior the feed pipeline applies before rendering. + * + * This complements (does not replace) the platform-driven auto-moderation + * (nsfwDetectionService etc.) — it is a low-friction, trust-building signal the + * author opts into. + * + * All exports are pure data + pure functions; no I/O, no mutation. + */ + +/** Adult-content self labels. These HIDE the post by default. */ +export const ADULT_CONTENT_LABELS = ['sexual', 'nudity', 'porn'] as const; + +/** Non-adult self labels. These WARN (blur) by default. */ +export const OTHER_SELF_LABELS = ['graphic-media', 'spoiler'] as const; + +/** Every recognised self label. */ +export const SELF_LABELS = [...ADULT_CONTENT_LABELS, ...OTHER_SELF_LABELS] as const; + +export type AdultSelfLabel = (typeof ADULT_CONTENT_LABELS)[number]; +export type OtherSelfLabel = (typeof OTHER_SELF_LABELS)[number]; +export type SelfLabel = (typeof SELF_LABELS)[number]; + +/** Behavior the feed pipeline applies for a labeled post. */ +export type LabelBehavior = 'hide' | 'warn'; + +const ADULT_SET: ReadonlySet = new Set(ADULT_CONTENT_LABELS); +const SELF_LABEL_SET: ReadonlySet = new Set(SELF_LABELS); + +/** Type guard: is this string a recognised self label? */ +export function isSelfLabel(value: string): value is SelfLabel { + return SELF_LABEL_SET.has(value); +} + +/** + * Validate and normalise an arbitrary input into a deduped list of recognised + * self labels. Unknown entries are dropped silently. Returns a new array. + */ +export function normalizeSelfLabels(input: unknown): SelfLabel[] { + const raw = Array.isArray(input) + ? input + : typeof input === 'string' + ? input.split(',') + : []; + + const seen = new Set(); + for (const entry of raw) { + if (typeof entry !== 'string') continue; + const candidate = entry.trim().toLowerCase(); + if (isSelfLabel(candidate)) seen.add(candidate); + } + return [...seen]; +} + +/** + * The strongest behavior implied by a set of labels. + * - any adult label -> 'hide' + * - any other self label -> 'warn' + * - no labels -> null (no behavior) + */ +export function behaviorForLabels(labels: ReadonlyArray): LabelBehavior | null { + let hasWarn = false; + for (const label of labels) { + if (ADULT_SET.has(label)) return 'hide'; + if (SELF_LABEL_SET.has(label)) hasWarn = true; + } + return hasWarn ? 'warn' : null; +} + +/** A post viewed through the self-label lens. */ +export interface SelfLabeledPost { + selfLabels?: string[] | null; + contentWarning?: string | null; +} + +/** Moderation decision attached to a feed item for the client to honour. */ +export interface SelfLabelDecision { + /** Behavior to apply; null when the post carries no self labels. */ + behavior: LabelBehavior | null; + /** Recognised labels present on the post. */ + labels: SelfLabel[]; + /** Optional author-supplied warning text. */ + contentWarning: string | null; +} + +/** + * Compute the moderation decision for a post from its self labels. + * + * Hide vs warn semantics mirror Bluesky: `hide` means the post is collapsed out + * of the feed unless the viewer has explicitly opted into adult content; `warn` + * means the post stays in the feed but the client should blur it behind the + * warning until tapped. + */ +export function decideSelfLabel(post: SelfLabeledPost): SelfLabelDecision { + const labels = normalizeSelfLabels(post.selfLabels); + return { + behavior: behaviorForLabels(labels), + labels, + contentWarning: + typeof post.contentWarning === 'string' && post.contentWarning.trim().length > 0 + ? post.contentWarning.trim() + : null, + }; +} diff --git a/gitgram/mobile/app/(modals)/create-post.tsx b/gitgram/mobile/app/(modals)/create-post.tsx index a1f20f39..a11f4ff8 100644 --- a/gitgram/mobile/app/(modals)/create-post.tsx +++ b/gitgram/mobile/app/(modals)/create-post.tsx @@ -21,6 +21,9 @@ import { scheduledPostsService } from '../../services/scheduledPostsService'; import { userService } from '../../services/userService'; import { logger } from '../../utils/logger'; import Icon from 'react-native-vector-icons/MaterialIcons'; +import ImageAltTextDialog from '../../components/common/ImageAltTextDialog'; +import { useSettingsStore } from '../../store/settingsStore'; +import { useToast } from '../../hooks/useToast'; interface TaggablePerson { id: string; @@ -34,6 +37,7 @@ interface SelectedMedia { uri: string; type: MediaType; mimeType?: string; + alt?: string; } const inferMediaType = (asset: ImagePicker.ImagePickerAsset): MediaType => @@ -50,11 +54,14 @@ export default function CreatePostScreen() { const router = useRouter(); const params = useLocalSearchParams<{ schedule?: string }>(); const isScheduling = params.schedule === 'true'; + const altTextRequired = useSettingsStore((state) => state.altTextRequired); + const { showToast, ToastComponent } = useToast(); const [content, setContent] = useState(''); const [media, setMedia] = useState(null); const [taggedPeople, setTaggedPeople] = useState([]); const [loading, setLoading] = useState(false); + const [altDialogVisible, setAltDialogVisible] = useState(false); const [tagModalVisible, setTagModalVisible] = useState(false); const [tagQuery, setTagQuery] = useState(''); @@ -104,9 +111,19 @@ export default function CreatePostScreen() { ); }; + const saveAltText = (altText: string) => { + setMedia((prev) => (prev ? { ...prev, alt: altText } : prev)); + }; + const handlePost = async () => { if (!content && !media) return; + // Enforce alt text on images when the preference is enabled (accessibility). + if (altTextRequired && media?.type === 'image' && !media.alt?.trim()) { + showToast('Please add alt text to your image before posting.', 'error'); + return; + } + setLoading(true); try { const formData = new FormData(); @@ -120,6 +137,9 @@ export default function CreatePostScreen() { type: buildMimeType(media, filename), } as unknown as Blob); formData.append('mediaType', media.type); + if (media.alt?.trim()) { + formData.append('altTexts[]', media.alt.trim()); + } } taggedPeople.forEach((person) => { @@ -181,11 +201,32 @@ export default function CreatePostScreen() { Video selected ) : ( - + )} setMedia(null)}> + {media.type === 'image' && ( + setAltDialogVisible(true)} + accessibilityRole="button" + accessibilityLabel={media.alt ? 'Edit alt text' : 'Add alt text'} + > + + + {media.alt ? 'ALT added' : 'Add alt text'} + + + )} )} @@ -261,6 +302,18 @@ export default function CreatePostScreen() { )} + + {media?.type === 'image' && ( + setAltDialogVisible(false)} + /> + )} + + {ToastComponent} ); } @@ -314,6 +367,23 @@ const styles = StyleSheet.create({ borderRadius: 12, padding: 4, }, + altButton: { + position: 'absolute', + left: 8, + bottom: 8, + flexDirection: 'row', + alignItems: 'center', + gap: 4, + backgroundColor: 'rgba(0,0,0,0.6)', + borderRadius: 14, + paddingHorizontal: 10, + paddingVertical: 6, + }, + altButtonText: { + color: '#FFF', + fontSize: 12, + fontWeight: '600', + }, taggedRow: { flexDirection: 'row', flexWrap: 'wrap', diff --git a/gitgram/mobile/app/_layout.tsx b/gitgram/mobile/app/_layout.tsx index 02c1c2ae..88c5e6a7 100644 --- a/gitgram/mobile/app/_layout.tsx +++ b/gitgram/mobile/app/_layout.tsx @@ -3,9 +3,11 @@ import { Stack } from 'expo-router'; import { GestureHandlerRootView } from 'react-native-gesture-handler'; import { SafeAreaProvider } from 'react-native-safe-area-context'; import { useAuthStore } from '../store/authStore'; +import { useSettingsStore } from '../store/settingsStore'; import { ErrorBoundary } from '../components/common/ErrorBoundary'; import NetworkStatus from '../components/common/NetworkStatus'; import { ToastProvider } from '../components/proximity/Toast'; +import { LightboxProvider } from '../components/common/Lightbox'; import { pushNotificationService } from '../services/pushNotificationService'; import { paymentDeepLinkHandler } from '../utils/paymentDeepLinkHandler'; import { setupNotificationDeepLinkHandler, handleNotificationDeepLink } from '../utils/notificationDeepLinkHandler'; @@ -13,9 +15,11 @@ import { logger } from '../utils/logger'; export default function RootLayout() { const { initialize, isAuthenticated } = useAuthStore(); + const hydrateSettings = useSettingsStore((state) => state.hydrate); useEffect(() => { initialize(); + hydrateSettings(); }, []); useEffect(() => { @@ -66,6 +70,7 @@ export default function RootLayout() { + diff --git a/gitgram/mobile/app/chat/[userId].tsx b/gitgram/mobile/app/chat/[userId].tsx index 7976c1b6..96412629 100644 --- a/gitgram/mobile/app/chat/[userId].tsx +++ b/gitgram/mobile/app/chat/[userId].tsx @@ -19,6 +19,7 @@ import LoadingSpinner from '../../components/common/LoadingSpinner'; import EmptyState from '../../components/common/EmptyState'; import * as ImagePicker from 'expo-image-picker'; import { logger } from '../../utils/logger'; +import { useHaptics } from '../../hooks/useHaptics'; const TYPING_DEBOUNCE_MS = 2000; // Stop typing after 2 seconds of no input @@ -114,6 +115,7 @@ interface Message { export default function ChatScreen() { const { userId } = useLocalSearchParams<{ userId: string }>(); const router = useRouter(); + const haptics = useHaptics(); const [messages, setMessages] = useState([]); const [loading, setLoading] = useState(true); const [messageText, setMessageText] = useState(''); @@ -229,6 +231,7 @@ export default function ChatScreen() { try { setSending(true); + haptics('Light'); // Stop typing indicator when sending emitTypingStop(); diff --git a/gitgram/mobile/app/menu.tsx b/gitgram/mobile/app/menu.tsx index 0c6ffab8..8018bc2c 100644 --- a/gitgram/mobile/app/menu.tsx +++ b/gitgram/mobile/app/menu.tsx @@ -5,6 +5,7 @@ import { StyleSheet, TouchableOpacity, ScrollView, + Switch, } from 'react-native'; import { useRouter } from 'expo-router'; import { Image } from 'expo-image'; @@ -12,6 +13,8 @@ import Icon from 'react-native-vector-icons/MaterialIcons'; import { SafeAreaView } from 'react-native-safe-area-context'; import { Colors } from '../constants/Colors'; import { useAuthStore } from '../store/authStore'; +import { useSettingsStore } from '../store/settingsStore'; +import { useHaptics } from '../hooks/useHaptics'; import { authService } from '../services/authService'; import { logger } from '../utils/logger'; @@ -31,6 +34,19 @@ interface MenuItem { export default function MenuScreen() { const router = useRouter(); const { user, logout } = useAuthStore(); + const hapticsDisabled = useSettingsStore((state) => state.hapticsDisabled); + const setHapticsDisabled = useSettingsStore((state) => state.setHapticsDisabled); + const altTextRequired = useSettingsStore((state) => state.altTextRequired); + const setAltTextRequired = useSettingsStore((state) => state.setAltTextRequired); + const haptics = useHaptics(); + + const toggleHaptics = (value: boolean) => { + // Fire a confirming buzz only when turning haptics back on. + if (!value) { + haptics('Light'); + } + void setHapticsDisabled(!value); + }; const handleLogout = () => { const run = async () => { @@ -101,6 +117,27 @@ export default function MenuScreen() { + + + Haptic Feedback + + + + + Require Alt Text + void setAltTextRequired(value)} + trackColor={{ false: Colors.border, true: Colors.primary }} + thumbColor={Colors.white} + /> + + {menuItems.map((item, index) => { if (item.divider) { return ; @@ -192,6 +229,13 @@ const styles = StyleSheet.create({ borderBottomWidth: 1, borderBottomColor: Colors.border, }, + toggleRow: { + flexDirection: 'row', + alignItems: 'center', + padding: 16, + borderBottomWidth: 1, + borderBottomColor: Colors.border, + }, menuLabel: { flex: 1, fontSize: 16, diff --git a/gitgram/mobile/components/Moment/MomentCard.tsx b/gitgram/mobile/components/Moment/MomentCard.tsx index 669ab137..35f086ad 100644 --- a/gitgram/mobile/components/Moment/MomentCard.tsx +++ b/gitgram/mobile/components/Moment/MomentCard.tsx @@ -1,4 +1,4 @@ -import React, { useState } from 'react'; +import React, { useRef, useState } from 'react'; import { View, Text, @@ -11,6 +11,12 @@ import { Image } from 'expo-image'; import { momentService } from '../../services/momentService'; import { logger } from '../../utils/logger'; import Icon from 'react-native-vector-icons/MaterialIcons'; +import { useHaptics } from '../../hooks/useHaptics'; +import LikeBounceAnimation, { + LikeBounceAnimationHandle, +} from '../common/LikeBounceAnimation'; + +const DOUBLE_PRESS_DELAY = 300; interface MomentCardProps { moment: { @@ -31,32 +37,71 @@ interface MomentCardProps { export default function MomentCard({ moment }: MomentCardProps) { const router = useRouter(); + const haptics = useHaptics(); + const likeBounceRef = useRef(null); + const lastTapRef = useRef(0); const [isLiked, setIsLiked] = useState(false); const [likesCount, setLikesCount] = useState(moment.likesCount); + const [liking, setLiking] = useState(false); + + const handleLike = async (mode: 'toggle' | 'like-only' = 'toggle') => { + if (liking) return; + if (mode === 'like-only' && isLiked) return; + + haptics('Medium'); + + const previousIsLiked = isLiked; + setIsLiked(!previousIsLiked); + setLikesCount((prev) => (!previousIsLiked ? prev + 1 : prev - 1)); + setLiking(true); - const handleLike = async () => { try { const response = await momentService.likeMoment(moment.id); setIsLiked(response.liked); - setLikesCount((prev) => (response.liked ? prev + 1 : prev - 1)); + setLikesCount(moment.likesCount + (response.liked ? 1 : 0)); } catch (error) { + // Roll back the optimistic update on failure. + setIsLiked(previousIsLiked); + setLikesCount((prev) => (!previousIsLiked ? prev - 1 : prev + 1)); logger.error('Like moment error:', error); + } finally { + setLiking(false); } }; + const handlePreviewPress = () => { + const now = Date.now(); + if (now - lastTapRef.current < DOUBLE_PRESS_DELAY) { + lastTapRef.current = 0; + likeBounceRef.current?.animate(); + void handleLike('like-only'); + return; + } + lastTapRef.current = now; + router.push(`/moments/${moment.id}`); + }; + return ( - router.push(`/moments/${moment.id}`)} - > - - - + + + + + + + + + - - - - + + @@ -81,10 +126,10 @@ export default function MomentCard({ moment }: MomentCardProps) { { - e.stopPropagation(); - handleLike(); - }} + onPress={() => handleLike('toggle')} + disabled={liking} + accessibilityRole="button" + accessibilityLabel={isLiked ? 'Unlike moment' : 'Like moment'} > { - e.stopPropagation(); - router.push(`/moments/${moment.id}/reactions`); - }} + onPress={() => router.push(`/moments/${moment.id}/reactions`)} > {moment.commentsCount} - + ); } diff --git a/gitgram/mobile/components/Post/PostCard.tsx b/gitgram/mobile/components/Post/PostCard.tsx index e9de20cb..f8d1712e 100644 --- a/gitgram/mobile/components/Post/PostCard.tsx +++ b/gitgram/mobile/components/Post/PostCard.tsx @@ -1,10 +1,9 @@ -import React, { useState } from 'react'; +import React, { useRef, useState } from 'react'; import { View, Text, StyleSheet, TouchableOpacity, - ScrollView, } from 'react-native'; import { useRouter } from 'expo-router'; import { Image } from 'expo-image'; @@ -12,10 +11,17 @@ import { Colors } from '../../constants/Colors'; import { postService } from '../../services/postService'; import { logger } from '../../utils/logger'; import { useAuthStore } from '../../store/authStore'; +import { useHaptics } from '../../hooks/useHaptics'; import PostOptionsModal from '../common/PostOptionsModal'; import ReportModal from '../common/ReportModal'; import CodeBlock from '../common/CodeBlock'; import RichContent from '../common/RichContent'; +import LikeBounceAnimation, { + LikeBounceAnimationHandle, +} from '../common/LikeBounceAnimation'; +import { useLightbox } from '../common/Lightbox'; + +const DOUBLE_PRESS_DELAY = 300; interface Post { id: string; @@ -46,16 +52,25 @@ interface PostCardProps { export default function PostCard({ post, onLike, showFullContent = false }: PostCardProps) { const router = useRouter(); const { user } = useAuthStore(); + const haptics = useHaptics(); + const openLightbox = useLightbox(); const [isLiked, setIsLiked] = useState(post.isLiked); const [likesCount, setLikesCount] = useState(post.likesCount); const [loading, setLoading] = useState(false); const [showOptionsModal, setShowOptionsModal] = useState(false); const [showReportModal, setShowReportModal] = useState(false); + const likeBounceRef = useRef(null); + const lastTapRef = useRef(0); const isOwner = user?.id === post.user.id; - const handleLike = async () => { + // mode: 'toggle' for the like button, 'like-only' for double-tap (which never + // unlikes, matching Instagram/TikTok behaviour). + const handleLike = async (mode: 'toggle' | 'like-only' = 'toggle') => { if (loading) return; + if (mode === 'like-only' && isLiked) return; + + haptics('Medium'); // Optimistic update - update UI immediately const previousIsLiked = isLiked; @@ -81,6 +96,26 @@ export default function PostCard({ post, onLike, showFullContent = false }: Post } }; + const handleImagePress = () => { + const now = Date.now(); + if (now - lastTapRef.current < DOUBLE_PRESS_DELAY) { + lastTapRef.current = 0; + likeBounceRef.current?.animate(); + void handleLike('like-only'); + return; + } + lastTapRef.current = now; + if (!showFullContent) { + router.push(`/post/${post.id}`); + } + }; + + const handleImageLongPress = () => { + if (!post.mediaUrl) return; + haptics('Light'); + openLightbox([{ uri: post.mediaUrl, alt: post.content || undefined }], 0); + }; + return ( {/* Card Header */} @@ -106,7 +141,9 @@ export default function PostCard({ post, onLike, showFullContent = false }: Post {/* Project Visual */} {post.mediaType === 'image' && post.mediaUrl && ( !showFullContent && router.push(`/post/${post.id}`)} + onPress={handleImagePress} + onLongPress={handleImageLongPress} + delayLongPress={350} activeOpacity={showFullContent ? 1 : 0.9} > + )} @@ -135,8 +174,10 @@ export default function PostCard({ post, onLike, showFullContent = false }: Post handleLike('toggle')} disabled={loading} + accessibilityRole="button" + accessibilityLabel={isLiked ? 'Unlike post' : 'Like post'} > {isLiked ? '❤️' : '🤍'} diff --git a/gitgram/mobile/components/Reel/ReelPlayer.tsx b/gitgram/mobile/components/Reel/ReelPlayer.tsx index 053ab8e6..d96c82ba 100644 --- a/gitgram/mobile/components/Reel/ReelPlayer.tsx +++ b/gitgram/mobile/components/Reel/ReelPlayer.tsx @@ -1,4 +1,4 @@ -import React, { useState } from 'react'; +import React, { useRef, useState } from 'react'; import { View, StyleSheet, TouchableOpacity, Dimensions } from 'react-native'; import { Video, ResizeMode } from 'expo-av'; import { ThemedText } from '../ui/ThemedText'; @@ -7,6 +7,12 @@ import { Image } from 'expo-image'; import Icon from 'react-native-vector-icons/MaterialIcons'; import ReportModal from '../common/ReportModal'; import { VISUAL_EFFECTS } from '../../store/reelEditorStore'; +import { useHaptics } from '../../hooks/useHaptics'; +import LikeBounceAnimation, { + LikeBounceAnimationHandle, +} from '../common/LikeBounceAnimation'; + +const DOUBLE_PRESS_DELAY = 300; const { width, height } = Dimensions.get('window'); @@ -63,6 +69,9 @@ export default function ReelPlayer({ user: { username: username || 'user', avatar: '' }, }; const video = React.useRef