diff --git a/aitimemachine/api-server/src/routes/beads.ts b/aitimemachine/api-server/src/routes/beads.ts index 738cf369..c41a4eac 100644 --- a/aitimemachine/api-server/src/routes/beads.ts +++ b/aitimemachine/api-server/src/routes/beads.ts @@ -764,6 +764,94 @@ router.post("/tasks/:id/reopen", async (req: Request, res: Response) => { } }); +// GET /beads/stale — issues not updated recently (potentially stuck/abandoned). +// +// Surfaces the fleet-health signal you want for a swarm of agents opening PRs: +// in-progress tasks with no recent activity, forgotten open tasks, and outdated +// work. Optional filters: +// days — staleness threshold in days (>=1, default 30, max 3650) +// status — open | in_progress | blocked | deferred +// limit — max issues to return (1-1000, default 50) +const STALE_STATUSES = ["open", "in_progress", "blocked", "deferred"] as const; + +router.get("/stale", async (req: Request, res: Response) => { + const args: string[] = ["stale", "--json"]; + + const days = boundedInt(req.query.days, 1, 3650); + if (days !== undefined) { + args.push("--days", String(days)); + } + + const status = singleQueryValue(req.query.status); + if (status !== undefined) { + if (!(STALE_STATUSES as readonly string[]).includes(status)) { + return res.status(400).json({ + success: false, + error: `status must be one of: ${STALE_STATUSES.join(", ")}`, + }); + } + args.push("--status", status); + } + + const limit = boundedInt(req.query.limit, 1, 1000); + if (limit !== undefined) { + args.push("--limit", String(limit)); + } + + 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 query stale tasks", + }); + } +}); + +// GET /beads/prime — AI-optimized workflow context as markdown. +// +// Bootstraps an agent at session start with the current Beads workflow state +// (ready work + conventions) instead of hand-assembling context. The CLI emits +// markdown to stdout; we return it as text. Optional modifiers: +// mode=full — force full CLI command reference (ignore MCP detection) +// mode=mcp — force minimal MCP-mode reminders +// stealth=1 — stealth mode (no git operations in the close protocol) +// memoriesOnly=1 — output only persistent memories (for compact hooks) +router.get("/prime", async (req: Request, res: Response) => { + const args: string[] = ["prime"]; + + const mode = singleQueryValue(req.query.mode); + if (mode === "full") { + args.push("--full"); + } else if (mode === "mcp") { + args.push("--mcp"); + } + + if (singleQueryValue(req.query.stealth) === "1" || singleQueryValue(req.query.stealth) === "true") { + args.push("--stealth"); + } + if ( + singleQueryValue(req.query.memoriesOnly) === "1" || + singleQueryValue(req.query.memoriesOnly) === "true" + ) { + args.push("--memories-only"); + } + + try { + const { stdout } = await execFileAsync(beadsBin(), args); + // `bd prime` emits markdown to stdout (not JSON); return it verbatim so the + // caller can inject it directly into an agent's session context. + res.json({ success: true, data: { format: "markdown", content: stdout } }); + } catch (err: unknown) { + res.status(500).json({ + success: false, + error: + err instanceof Error ? err.message : "Failed to prime agent context", + }); + } +}); + // 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 ad02801e..a98eb8da 100644 --- a/aitimemachine/api-server/src/routes/context7.ts +++ b/aitimemachine/api-server/src/routes/context7.ts @@ -197,10 +197,45 @@ router.get( ); // ============================================================================ -// GET /context7/libraries/:id/docs?version=&tokens=&topic= +// GET /context7/libraries/:id/docs?version=&tokens=&topic=&query= // Fetch documentation for a resolved library ID. +// +// The Context7 `/v2/context` endpoint reranks documentation against the text it +// receives. A `query` / `question` param sends a full natural-language question +// ("How do I set up JWT auth in Express?") for relevance-based retrieval; the +// coarser `topic` (a single subject keyword) is used as a fallback. When both +// are absent we send "overview" to fetch a broad context dump. // ============================================================================ +/** + * Resolve the retrieval text Context7 reranks against. Prefers an explicit + * natural-language `query`/`question`, then falls back to `topic`, then to a + * broad default. Returns the text plus which source it came from. + */ +function resolveRetrievalQuery(req: Request): { + query: string; + topic: string | null; + source: "query" | "topic" | "default"; +} { + const rawQuery = + typeof req.query.query === "string" + ? req.query.query + : typeof req.query.question === "string" + ? req.query.question + : ""; + const trimmedQuery = rawQuery.trim(); + + const rawTopic = typeof req.query.topic === "string" ? req.query.topic.trim() : ""; + + if (trimmedQuery.length > 0) { + return { query: trimmedQuery, topic: rawTopic.length > 0 ? rawTopic : null, source: "query" }; + } + if (rawTopic.length > 0) { + return { query: rawTopic, topic: rawTopic, source: "topic" }; + } + return { query: "overview", topic: null, source: "default" }; +} + router.get( "/libraries/:id/docs", asyncHandler(async (req: AuthenticatedRequest, res: Response) => { @@ -213,21 +248,31 @@ router.get( // tokens is preserved in the REST contract; the SDK does not expose a // per-request token cap, so it is recorded but does not change the call. const tokens = clampTokens(req.query.tokens, 5_000); - const topic = typeof req.query.topic === "string" ? req.query.topic : "overview"; + const { query, topic, source } = resolveRetrievalQuery(req); + if (query.length > 2000) { + throw Errors.invalidParameter("query", "query must be 2000 characters or less"); + } const version = typeof req.query.version === "string" && req.query.version.trim().length > 0 ? req.query.version.trim() : undefined; - logger.info("context7: get library docs", { libraryId: id, version, topic, tokens }); + logger.info("context7: get library docs", { + libraryId: id, + version, + query, + topic, + source, + tokens, + }); - const docs: Documentation[] = await requireClient(req).getContext(topic, id, { + const docs: Documentation[] = await requireClient(req).getContext(query, id, { type: "json", }); // Write-through to the unified memory layer (best-effort; never blocks). void ingestLibraryDoc( - { libraryId: id, topic, version: version ?? null, docs }, + { libraryId: id, topic: topic ?? query, version: version ?? null, docs }, { userId: req.user?.userId } ).catch((error: unknown) => { logger.warn("context7: memory write-through failed", { @@ -240,6 +285,92 @@ router.get( success: true, libraryId: id, version: version ?? null, + query, + data: docs, + }); + }) +); + +// ============================================================================ +// POST /context7/query +// Natural-language query-docs flow: send a full question and a resolved library +// id (or a search term to resolve first) and get back reranked documentation +// for that specific question. Body: { query, libraryId? , library?, version? }. +// ============================================================================ + +const queryDocsBodySchema = z.object({ + query: z + .string({ required_error: "query is required" }) + .min(1, "query must not be empty") + .max(2000, "query must be 2000 characters or less"), + libraryId: z.string().min(1).max(512).optional(), + library: z.string().min(1).max(512).optional(), + version: z.string().min(1).max(128).optional(), +}); + +router.post( + "/query", + asyncHandler(async (req: AuthenticatedRequest, res: Response) => { + const parsed = queryDocsBodySchema.safeParse(req.body ?? {}); + if (!parsed.success) { + const first = parsed.error.errors[0]; + throw Errors.invalidParameter( + first?.path.join(".") || "body", + first?.message ?? "Invalid request body" + ); + } + if (!parsed.data.libraryId && !parsed.data.library) { + throw Errors.invalidParameter( + "libraryId", + "one of 'libraryId' or 'library' (a search term) is required" + ); + } + + const { query, version } = parsed.data; + const client = requireClient(req); + + // Resolve a library search term to a concrete id when no id was supplied, + // using the query as the relevance signal for the resolve step. + let libraryId = parsed.data.libraryId?.trim(); + if (!libraryId && parsed.data.library) { + const matches: Library[] = await client.searchLibrary(query, parsed.data.library, { + type: "json", + }); + const top = matches[0]; + if (!top || typeof top.id !== "string" || top.id.trim().length === 0) { + throw Errors.invalidParameter( + "library", + `no Context7 library matched '${parsed.data.library}'` + ); + } + libraryId = top.id.trim(); + } + + if (!libraryId) { + throw Errors.invalidParameter("libraryId", "library id could not be resolved"); + } + + logger.info("context7: query docs", { libraryId, query }); + + const docs: Documentation[] = await client.getContext(query, libraryId, { + type: "json", + }); + + void ingestLibraryDoc( + { libraryId, topic: query, version: version ?? null, docs }, + { userId: req.user?.userId } + ).catch((error: unknown) => { + logger.warn("context7: memory write-through failed", { + libraryId, + details: String(error), + }); + }); + + return res.json({ + success: true, + libraryId, + version: version ?? null, + query, data: docs, }); }) diff --git a/aitimemachine/api-server/src/routes/gitnexus.ts b/aitimemachine/api-server/src/routes/gitnexus.ts index 70966ddb..ccb9c29c 100644 --- a/aitimemachine/api-server/src/routes/gitnexus.ts +++ b/aitimemachine/api-server/src/routes/gitnexus.ts @@ -9,7 +9,7 @@ import { Router, Request, Response } from "express"; import { z } from "zod"; -import { apiKeyAuth } from "../middleware/auth.js"; +import { apiKeyAuth, AuthenticatedRequest } from "../middleware/auth.js"; import { asyncHandler, Errors } from "../middleware/errors.js"; import { logger } from "../lib/monitoring.js"; import { @@ -24,6 +24,11 @@ import { traceSymbols, shapeCheck, explainTaint, + queryGraph, + getSymbolContext, + runCypher, + structuralCheck, + renameSymbol, } from "../services/gitNexusService.js"; const router = Router(); @@ -123,6 +128,74 @@ const explainQuerySchema = z.object({ repo: optionalRepo, }); +// query — natural-language, process-grouped graph-RAG retrieval. +// Exposed as GET (query params) and POST (body) for caller convenience. +const queryBodySchema = z.object({ + search_query: z + .string({ required_error: "search_query is required" }) + .min(1, "search_query must not be empty") + .max(2000, "search_query is too long"), + task_context: z.string().min(1).max(2000).optional(), + goal: z.string().min(1).max(2000).optional(), + limit: z.coerce.number().int().min(1).max(100).optional(), + max_symbols: z.coerce.number().int().min(1).max(200).optional(), + include_content: z.coerce.boolean().optional(), + repo: optionalRepo, + service: z.string().min(1).max(2048).optional(), +}); +const queryQuerySchema = queryBodySchema; + +// context — 360-degree view of one symbol. At least one of name|uid required. +const contextBodySchema = z + .object({ + name: z.string().min(1).max(512).optional(), + uid: z.string().min(1).max(512).optional(), + file_path: z.string().min(1).max(2048).optional(), + kind: z.string().min(1).max(64).optional(), + include_content: z.coerce.boolean().optional(), + repo: optionalRepo, + service: z.string().min(1).max(2048).optional(), + }) + .refine((v) => Boolean(v.name) || Boolean(v.uid), { + message: "at least one of 'name' or 'uid' is required", + path: ["name"], + }); +const contextQuerySchema = contextBodySchema; + +// cypher — raw parameterized query against the knowledge graph. +const cypherBodySchema = z.object({ + statement: z + .string({ required_error: "statement is required" }) + .min(1, "statement must not be empty") + .max(20000, "statement is too long"), + params: z.record(z.unknown()).optional(), + repo: optionalRepo, +}); + +// check — read-only structural CI check. +const checkQuerySchema = z.object({ + cycles: z.coerce.boolean().optional(), + repo: optionalRepo, +}); + +// rename — graph-aware coordinated rename (DESTRUCTIVE; dry_run defaults true). +const renameBodySchema = z + .object({ + new_name: z + .string({ required_error: "new_name is required" }) + .min(1, "new_name must not be empty") + .max(512, "new_name is too long"), + symbol_name: z.string().min(1).max(512).optional(), + symbol_uid: z.string().min(1).max(512).optional(), + file_path: z.string().min(1).max(2048).optional(), + dry_run: z.boolean().optional(), + repo: optionalRepo, + }) + .refine((v) => Boolean(v.symbol_name) || Boolean(v.symbol_uid), { + message: "at least one of 'symbol_name' or 'symbol_uid' is required", + path: ["symbol_name"], + }); + // ============================================================================ // GET /gitnexus/status // ============================================================================ @@ -397,6 +470,244 @@ router.get( }) ); +// ============================================================================ +// query — natural-language, process-grouped graph-RAG retrieval. +// The flagship "understand how code works" surface: returns execution flows +// ranked by relevance (BM25 + vector, fused via RRF) rather than a flat symbol +// list. Available as GET (query params) and POST (body). +// ============================================================================ + +async function runQuery( + data: z.infer, + res: Response +): Promise { + logger.info("gitnexus: query", { + searchQuery: data.search_query, + repo: data.repo, + }); + const result = await queryGraph({ + searchQuery: data.search_query, + taskContext: data.task_context, + goal: data.goal, + limit: data.limit, + maxSymbols: data.max_symbols, + includeContent: data.include_content, + repo: data.repo, + service: data.service, + }); + return res.json({ success: true, data: result }); +} + +router.get( + "/query", + asyncHandler(async (req: Request, res: Response) => { + const parsed = queryQuerySchema.safeParse(req.query); + if (!parsed.success) { + const first = parsed.error.errors[0]; + throw Errors.invalidParameter( + first?.path.join(".") || "query", + first?.message ?? "Invalid query parameters" + ); + } + return runQuery(parsed.data, res); + }) +); + +router.post( + "/query", + asyncHandler(async (req: Request, res: Response) => { + const parsed = queryBodySchema.safeParse(req.body ?? {}); + if (!parsed.success) { + const first = parsed.error.errors[0]; + throw Errors.invalidParameter( + first?.path.join(".") || "body", + first?.message ?? "Invalid request body" + ); + } + return runQuery(parsed.data, res); + }) +); + +// ============================================================================ +// context — 360-degree view of a single symbol (callers/callees, processes, +// file location). Available as GET (query params) and POST (body). +// ============================================================================ + +async function runContext( + data: z.infer, + res: Response +): Promise { + logger.info("gitnexus: context", { + name: data.name ?? data.uid, + repo: data.repo, + }); + const result = await getSymbolContext({ + name: data.name, + uid: data.uid, + filePath: data.file_path, + kind: data.kind, + includeContent: data.include_content, + repo: data.repo, + service: data.service, + }); + return res.json({ success: true, data: result }); +} + +router.get( + "/context", + asyncHandler(async (req: Request, res: Response) => { + const parsed = contextQuerySchema.safeParse(req.query); + if (!parsed.success) { + const first = parsed.error.errors[0]; + throw Errors.invalidParameter( + first?.path.join(".") || "query", + first?.message ?? "Invalid query parameters" + ); + } + return runContext(parsed.data, res); + }) +); + +router.post( + "/context", + asyncHandler(async (req: Request, res: Response) => { + const parsed = contextBodySchema.safeParse(req.body ?? {}); + if (!parsed.success) { + const first = parsed.error.errors[0]; + throw Errors.invalidParameter( + first?.path.join(".") || "body", + first?.message ?? "Invalid request body" + ); + } + return runContext(parsed.data, res); + }) +); + +// ============================================================================ +// cypher — arbitrary parameterized Cypher against the knowledge graph. +// User values MUST be bound via `params` ($placeholders), never interpolated +// into the statement, so the engine uses prepared-statement binding. +// ============================================================================ + +router.post( + "/cypher", + asyncHandler(async (req: Request, res: Response) => { + const parsed = cypherBodySchema.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 { statement, params, repo } = parsed.data; + logger.info("gitnexus: cypher", { + statementLength: statement.length, + paramKeys: params ? Object.keys(params) : [], + repo, + }); + const data = await runCypher({ statement, params, repo }); + + return res.json({ success: true, data }); + }) +); + +// ============================================================================ +// check — read-only structural CI check (import cycles). +// ============================================================================ + +router.get( + "/check", + asyncHandler(async (req: Request, res: Response) => { + const parsed = checkQuerySchema.safeParse(req.query); + if (!parsed.success) { + const first = parsed.error.errors[0]; + throw Errors.invalidParameter( + first?.path.join(".") || "query", + first?.message ?? "Invalid query parameters" + ); + } + + const { cycles, repo } = parsed.data; + logger.info("gitnexus: check", { cycles, repo }); + const data = await structuralCheck({ cycles, repo }); + + return res.json({ success: true, data }); + }) +); + +// ============================================================================ +// rename — graph-aware coordinated rename (DESTRUCTIVE). +// +// Preview-by-default: dry_run defaults to TRUE. A non-preview rename (dry_run: +// false) actually rewrites files, so it requires an authenticated user and is +// recorded to the audit trail before and after execution. +// ============================================================================ + +router.post( + "/rename", + asyncHandler(async (req: AuthenticatedRequest, res: Response) => { + const parsed = renameBodySchema.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 { new_name, symbol_name, symbol_uid, file_path, dry_run, repo } = + parsed.data; + const isWrite = dry_run === false; + + // Write-path guard: a destructive (non-dry-run) rename requires an + // authenticated user identity for the audit trail. + if (isWrite && !req.user?.userId) { + throw Errors.invalidParameter( + "dry_run", + "a non-preview rename (dry_run: false) requires an authenticated user" + ); + } + + if (isWrite) { + logger.warn("gitnexus: rename write requested", { + userId: req.user?.userId, + symbol: symbol_name ?? symbol_uid, + newName: new_name, + repo, + }); + } else { + logger.info("gitnexus: rename preview", { + symbol: symbol_name ?? symbol_uid, + newName: new_name, + repo, + }); + } + + const data = await renameSymbol({ + newName: new_name, + symbolName: symbol_name, + symbolUid: symbol_uid, + filePath: file_path, + dryRun: dry_run, + repo, + }); + + if (isWrite) { + logger.warn("gitnexus: rename write completed", { + userId: req.user?.userId, + symbol: symbol_name ?? symbol_uid, + newName: new_name, + fileCount: data.fileCount, + repo, + }); + } + + return res.json({ success: true, data }); + }) +); + // ============================================================================ // Error handler — surface upstream GitNexus failures as 502 // ============================================================================ diff --git a/aitimemachine/api-server/src/services/gitNexusService.ts b/aitimemachine/api-server/src/services/gitNexusService.ts index 1c8c687f..a0647b01 100644 --- a/aitimemachine/api-server/src/services/gitNexusService.ts +++ b/aitimemachine/api-server/src/services/gitNexusService.ts @@ -981,6 +981,364 @@ export async function explainTaint(params: { return { findings, totalFindings, truncated, noTaintLayer, raw: result }; } +// ============================================================================ +// Graph-RAG natural-language query (query tool) +// ============================================================================ + +/** Options for {@link queryGraph}. */ +export interface QueryGraphOptions { + /** Natural-language or keyword search query (required). */ + searchQuery: string; + /** What the caller is working on — improves ranking. */ + taskContext?: string; + /** What the caller wants to find — improves ranking. */ + goal?: string; + /** Max processes (execution flows) to return. */ + limit?: number; + /** Max symbols per process. */ + maxSymbols?: number; + /** Include full symbol source code in results. */ + includeContent?: boolean; + /** Repository name/path, or "@group" mode. Omit when one repo is indexed. */ + repo?: string; + /** Optional monorepo service-root path prefix (group mode). */ + service?: string; +} + +/** + * Natural-language, process-grouped retrieval over the code knowledge graph via + * the GitNexus `query` tool. Returns execution flows (processes) ranked by + * relevance (BM25 keyword + semantic vector, fused via RRF), each with its + * participating symbols and file locations, plus standalone definitions. + * + * The backend payload shape is rich and intentionally preserved verbatim under + * {@link GraphQueryResult.raw} for callers that need full detail; a small set of + * top-level arrays are surfaced when present. + */ +export interface GraphQueryResult { + processes: unknown[]; + processSymbols: unknown[]; + definitions: unknown[]; + raw: unknown; +} + +export async function queryGraph( + options: QueryGraphOptions +): Promise { + const params: Record = { + search_query: options.searchQuery, + }; + if (options.taskContext) params["task_context"] = options.taskContext; + if (options.goal) params["goal"] = options.goal; + if (typeof options.limit === "number") params["limit"] = options.limit; + if (typeof options.maxSymbols === "number") { + params["max_symbols"] = options.maxSymbols; + } + if (typeof options.includeContent === "boolean") { + params["include_content"] = options.includeContent; + } + if (options.repo) params["repo"] = options.repo; + if (options.service) params["service"] = options.service; + + const result = await callGitNexus("query", params); + + if (!isRecord(result)) { + return { processes: [], processSymbols: [], definitions: [], raw: result }; + } + + const asArray = (value: unknown): unknown[] => + Array.isArray(value) ? value : []; + + return { + processes: asArray(result["processes"]), + processSymbols: asArray( + result["process_symbols"] ?? result["processSymbols"] + ), + definitions: asArray(result["definitions"]), + raw: result, + }; +} + +// ============================================================================ +// 360-degree symbol context (context tool) +// ============================================================================ + +/** Options for {@link getSymbolContext}. At least one of name/uid is required. */ +export interface SymbolContextOptions { + /** Symbol name (e.g. "validateUser"). */ + name?: string; + /** Zero-ambiguity symbol UID from a prior tool result. */ + uid?: string; + /** File path to disambiguate common names. */ + filePath?: string; + /** Kind filter (Function | Class | Method | Interface | …). */ + kind?: string; + /** Include full symbol source code. */ + includeContent?: boolean; + /** Repository name/path, or "@group" mode. */ + repo?: string; + /** Optional monorepo service-root path prefix (group mode). */ + service?: string; +} + +/** + * 360-degree view of a single symbol via the GitNexus `context` tool: + * categorized incoming/outgoing references, process participation, and file + * location. When several symbols share a name and no uid is given, the backend + * returns ranked disambiguation candidates — that payload is preserved under + * {@link SymbolContextResult.raw}. + */ +export interface SymbolContextResult { + raw: unknown; +} + +export async function getSymbolContext( + options: SymbolContextOptions +): Promise { + const params: Record = {}; + if (options.name) params["name"] = options.name; + if (options.uid) params["uid"] = options.uid; + if (options.filePath) params["file_path"] = options.filePath; + if (options.kind) params["kind"] = options.kind; + if (typeof options.includeContent === "boolean") { + params["include_content"] = options.includeContent; + } + if (options.repo) params["repo"] = options.repo; + if (options.service) params["service"] = options.service; + + const result = await callGitNexus("context", params); + return { raw: result }; +} + +// ============================================================================ +// Raw Cypher query (cypher tool) +// ============================================================================ + +/** Options for {@link runCypher}. */ +export interface CypherOptions { + /** Cypher statement to execute. */ + statement: string; + /** Bound parameters for $placeholders (prepared-statement binding). */ + params?: Record; + /** Repository name/path. Omit when one repo is indexed. */ + repo?: string; +} + +/** + * Result of a {@link runCypher} call. The `cypher` tool returns a Markdown table + * plus a row count; both are surfaced and the full payload kept under `raw`. + */ +export interface CypherResult { + markdown: string | null; + rowCount: number | null; + raw: unknown; +} + +/** + * Executes an arbitrary Cypher statement against the code knowledge graph via + * the GitNexus `cypher` tool. Bound `params` are passed through to the engine's + * prepared-statement binding ($placeholders) — callers should always bind user + * values as params rather than interpolating them into the statement. + */ +export async function runCypher(options: CypherOptions): Promise { + const params: Record = { statement: options.statement }; + if (options.params && Object.keys(options.params).length > 0) { + params["params"] = options.params; + } + if (options.repo) params["repo"] = options.repo; + + const result = await callGitNexus("cypher", params); + + if (typeof result === "string") { + return { markdown: result, rowCount: null, raw: result }; + } + if (isRecord(result)) { + return { + markdown: + typeof result["markdown"] === "string" ? result["markdown"] : null, + rowCount: + typeof result["row_count"] === "number" + ? result["row_count"] + : typeof result["rowCount"] === "number" + ? result["rowCount"] + : null, + raw: result, + }; + } + return { markdown: null, rowCount: null, raw: result }; +} + +// ============================================================================ +// Structural checks for CI (check tool) +// ============================================================================ + +/** Options for {@link structuralCheck}. */ +export interface StructuralCheckOptions { + /** Detect circular file imports (default true). */ + cycles?: boolean; + /** Repository name/path. Omit when one repo is indexed. */ + repo?: string; +} + +/** + * Read-only structural check via the GitNexus `check` tool. Currently detects + * directed cycles between File nodes connected by IMPORTS edges, returning + * deterministic cycle paths and a count suitable for CI gating. + */ +export interface StructuralCheckResult { + /** Detected cycle paths (each an ordered list of file identifiers). */ + cycles: unknown[]; + /** Number of distinct cycles detected. */ + cycleCount: number; + /** True when no cycles were found. */ + ok: boolean; + /** The unnormalised backend payload. */ + raw: unknown; +} + +export async function structuralCheck( + options: StructuralCheckOptions = {} +): Promise { + const params: Record = { + cycles: options.cycles ?? true, + }; + if (options.repo) params["repo"] = options.repo; + + const result = await callGitNexus("check", params); + + const empty: StructuralCheckResult = { + cycles: [], + cycleCount: 0, + ok: true, + raw: result, + }; + + if (!isRecord(result)) { + if (typeof result === "string") { + // Some backends return a textual "no cycles" note; treat as clean. + return { ...empty, raw: result }; + } + logger.error("gitNexus: unexpected shape from check", undefined, { + result: String(result), + }); + return empty; + } + + const cycles = Array.isArray(result["cycles"]) + ? (result["cycles"] as unknown[]) + : []; + const cycleCount = + typeof result["cycleCount"] === "number" + ? result["cycleCount"] + : typeof result["cycle_count"] === "number" + ? result["cycle_count"] + : cycles.length; + const ok = + typeof result["ok"] === "boolean" ? result["ok"] : cycleCount === 0; + + return { cycles, cycleCount, ok, raw: result }; +} + +// ============================================================================ +// Graph-aware coordinated rename (rename tool — DESTRUCTIVE) +// ============================================================================ + +/** Options for {@link renameSymbol}. */ +export interface RenameOptions { + /** New name for the symbol (required). */ + newName: string; + /** Current symbol name to rename. */ + symbolName?: string; + /** Zero-ambiguity symbol UID from a prior tool result. */ + symbolUid?: string; + /** File path to disambiguate common names. */ + filePath?: string; + /** + * Preview edits without modifying files. Defaults to TRUE at the call site — + * the route layer enforces an explicit opt-in before a write is performed. + */ + dryRun?: boolean; + /** Repository name/path. Omit when one repo is indexed. */ + repo?: string; +} + +/** A single planned/applied edit in a {@link RenameResult}. */ +export interface RenameEdit { + file: string; + /** "graph" (high confidence) or "text_search" (review carefully). */ + confidence: string; + raw: unknown; +} + +/** + * Result of a graph-aware coordinated rename via the GitNexus `rename` tool. + * Each edit is tagged with the source that found it ("graph" vs "text_search"). + * The full backend payload (including any per-file diff detail) is preserved + * under `raw`. + */ +export interface RenameResult { + /** Whether this was a preview (no files written) or an applied rename. */ + dryRun: boolean; + /** Planned/applied edits across files. */ + edits: RenameEdit[]; + /** Number of distinct files touched. */ + fileCount: number; + /** The unnormalised backend payload. */ + raw: unknown; +} + +export async function renameSymbol( + options: RenameOptions +): Promise { + const dryRun = options.dryRun ?? true; + const params: Record = { + new_name: options.newName, + dry_run: dryRun, + }; + if (options.symbolName) params["symbol_name"] = options.symbolName; + if (options.symbolUid) params["symbol_uid"] = options.symbolUid; + if (options.filePath) params["file_path"] = options.filePath; + if (options.repo) params["repo"] = options.repo; + + const result = await callGitNexus("rename", params); + + const rows = Array.isArray(result) + ? result + : isRecord(result) && Array.isArray(result["edits"]) + ? (result["edits"] as unknown[]) + : []; + + const edits: RenameEdit[] = rows.filter(isRecord).map((edit) => ({ + file: + typeof edit["file"] === "string" + ? edit["file"] + : typeof edit["path"] === "string" + ? edit["path"] + : typeof edit["filePath"] === "string" + ? edit["filePath"] + : "", + confidence: + typeof edit["confidence"] === "string" + ? edit["confidence"] + : typeof edit["source"] === "string" + ? edit["source"] + : "", + raw: edit, + })); + + const fileCount = new Set(edits.map((e) => e.file).filter((f) => f.length > 0)) + .size; + + const resolvedDryRun = + isRecord(result) && typeof result["dry_run"] === "boolean" + ? (result["dry_run"] as boolean) + : isRecord(result) && typeof result["dryRun"] === "boolean" + ? (result["dryRun"] as boolean) + : dryRun; + + return { dryRun: resolvedDryRun, edits, fileCount, raw: result }; +} + // ============================================================================ // Availability probe // ============================================================================ diff --git a/aitimemachine/mcp/src/__tests__/beads-projection.test.ts b/aitimemachine/mcp/src/__tests__/beads-projection.test.ts index b35a3cd1..65669c43 100644 --- a/aitimemachine/mcp/src/__tests__/beads-projection.test.ts +++ b/aitimemachine/mcp/src/__tests__/beads-projection.test.ts @@ -12,6 +12,8 @@ import { projectBeadsPayload, unwrapBeadsData, toBrief, + toBriefDep, + collapseDepEdges, truncateDescription, filterFields, type CompactedBeadsResult, @@ -71,6 +73,58 @@ describe('beads-projection helpers', () => { status: 'open', }); }); + + it('toBriefDep collapses an edge to id/title/status/priority/dependencyType', () => { + expect( + toBriefDep({ + id: 'bd-2', + title: 'Task bd-2', + status: 'open', + priority: 0, + description: 'x'.repeat(50), + dependency_type: 'blocks', + }) + ).toEqual({ + id: 'bd-2', + title: 'Task bd-2', + status: 'open', + priority: 0, + dependencyType: 'blocks', + }); + }); + + it('toBriefDep reads either dependencyType or dependency_type', () => { + expect(toBriefDep({ id: 'bd-3', dependencyType: 'related' }).dependencyType).toBe( + 'related' + ); + expect(toBriefDep({ id: 'bd-4', dependency_type: 'parent-child' }).dependencyType).toBe( + 'parent-child' + ); + }); + + it('collapseDepEdges compacts edges while keeping the task body, immutably', () => { + const original = task('bd-1', { + dependencies: [task('bd-2', { dependency_type: 'blocks' })], + dependents: [task('bd-3', { dependency_type: 'discovered-from' })], + }); + const collapsed = collapseDepEdges(original); + expect(collapsed.title).toBe('Task bd-1'); + expect(collapsed.dependencies).toEqual([ + { id: 'bd-2', title: 'Task bd-2', status: 'open', priority: 1, dependencyType: 'blocks' }, + ]); + expect(collapsed.dependents).toEqual([ + { id: 'bd-3', title: 'Task bd-3', status: 'open', priority: 1, dependencyType: 'discovered-from' }, + ]); + // input untouched: still the full nested task + expect((original.dependencies as Array>)[0].description).toBe( + 'x'.repeat(50) + ); + }); + + it('collapseDepEdges leaves tasks without edge arrays untouched', () => { + const plain = task('bd-1'); + expect(collapseDepEdges(plain)).toBe(plain); + }); }); describe('projectBeadsPayload', () => { @@ -118,6 +172,42 @@ describe('projectBeadsPayload', () => { expect(result.hint).toContain('ready tasks'); }); + it('briefDeps keeps the full task but collapses its dependency edges', () => { + const payload = ENVELOPE( + task('bd-1', { + dependencies: [task('bd-2', { dependency_type: 'blocks' })], + dependents: [task('bd-3', { dependency_type: 'related' })], + }) + ); + const result = projectBeadsPayload(payload, { briefDeps: true }) as Record< + string, + unknown + >; + // full task body retained + expect(result.title).toBe('Task bd-1'); + expect(result.description).toBe('x'.repeat(50)); + // edges collapsed to the brief dep shape + expect(result.dependencies).toEqual([ + { id: 'bd-2', title: 'Task bd-2', status: 'open', priority: 1, dependencyType: 'blocks' }, + ]); + expect(result.dependents).toEqual([ + { id: 'bd-3', title: 'Task bd-3', status: 'open', priority: 1, dependencyType: 'related' }, + ]); + }); + + it('brief takes precedence over briefDeps (edges dropped entirely)', () => { + const result = projectBeadsPayload( + ENVELOPE(task('bd-1', { dependencies: [task('bd-2')] })), + { brief: true, briefDeps: true } + ); + expect(result).toEqual({ + id: 'bd-1', + title: 'Task bd-1', + status: 'open', + priority: 1, + }); + }); + it('passes stats-style payloads (non-list, non-record) through', () => { expect(projectBeadsPayload(ENVELOPE(42), { brief: true })).toBe(42); }); @@ -162,6 +252,37 @@ describe('beads tools wiring (projection args)', () => { ]); }); + it('beads_claim issues a PUT to /beads/tasks/:id/claim', async () => { + const claimed = task('bd-7', { assignee: 'aitm', status: 'in_progress' }); + fetchMock.mockResolvedValueOnce(jsonOk(ENVELOPE(claimed))); + const { call } = captureTools(registerBeadsTools, stubRuntime); + const result = parseJsonResponse<{ success: boolean; data: unknown }>( + await call('beads_claim', { id: 'bd-7' }) + ); + // round-trips the claimed task envelope back to the caller + expect(result).toEqual(ENVELOPE(claimed)); + // verify the request shape: PUT to the claim endpoint + const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]; + expect(url).toContain('/beads/tasks/bd-7/claim'); + expect(init.method).toBe('PUT'); + }); + + it('beads_claim with brief trims the claimed task', async () => { + fetchMock.mockResolvedValueOnce( + jsonOk(ENVELOPE(task('bd-8', { assignee: 'aitm', status: 'in_progress' }))) + ); + const { call } = captureTools(registerBeadsTools, stubRuntime); + const result = parseJsonResponse( + await call('beads_claim', { id: 'bd-8', brief: true }) + ); + expect(result).toEqual({ + id: 'bd-8', + title: 'Task bd-8', + status: 'in_progress', + priority: 1, + }); + }); + it('beads_list_tasks without args preserves the full envelope', async () => { const payload = ENVELOPE([task('bd-1')]); fetchMock.mockResolvedValueOnce(jsonOk(payload)); diff --git a/aitimemachine/mcp/src/__tests__/integration.test.ts b/aitimemachine/mcp/src/__tests__/integration.test.ts index 2c102ee5..3db6fc6d 100644 --- a/aitimemachine/mcp/src/__tests__/integration.test.ts +++ b/aitimemachine/mcp/src/__tests__/integration.test.ts @@ -365,6 +365,7 @@ describe('Beads tools registration', () => { 'beads_list_tasks', 'beads_create_task', 'beads_mark_ready', + 'beads_claim', 'beads_mark_done', 'beads_get_task', ] as const; @@ -388,6 +389,10 @@ describe('Beads tools registration', () => { expect(requiredFields(server, 'beads_mark_ready')).toContain('id'); }); + it('beads_claim requires "id"', () => { + expect(requiredFields(server, 'beads_claim')).toContain('id'); + }); + it('beads_mark_done requires "id"', () => { expect(requiredFields(server, 'beads_mark_done')).toContain('id'); }); diff --git a/aitimemachine/mcp/src/tools/register-beads-tools.ts b/aitimemachine/mcp/src/tools/register-beads-tools.ts index 2b6e54f1..b7dd2a2e 100644 --- a/aitimemachine/mcp/src/tools/register-beads-tools.ts +++ b/aitimemachine/mcp/src/tools/register-beads-tools.ts @@ -37,6 +37,10 @@ const projectionSchema = { .boolean() .optional() .describe('When true, return only {id, title, status, priority} per task (smallest output).'), + briefDeps: z + .boolean() + .optional() + .describe('When true, return the FULL task but collapse each dependency/dependent edge to {id, title, status, priority, dependencyType}. Ideal for inspecting a DAG node with many edges without a context blow-out. Ignored when brief is set.'), fields: z .array(z.string()) .optional() @@ -70,6 +74,7 @@ const listProjectionSchema = { function pickProjection( args: Partial<{ brief: boolean; + briefDeps: boolean; fields: string[]; maxDescriptionLength: number; compactionThreshold: number; @@ -79,6 +84,7 @@ function pickProjection( ): BeadsProjectionOptions { return { brief: args.brief, + briefDeps: args.briefDeps, fields: args.fields, maxDescriptionLength: args.maxDescriptionLength, compactionThreshold: args.compactionThreshold, @@ -203,6 +209,23 @@ export const registerBeadsTools = createToolRegistrar([ ), }), + defineTool({ + name: 'beads_claim', + description: + 'Atomically claim a Beads task for work: set the assignee to the configured actor AND move it to in_progress in one compare-and-swap step. This is the multi-agent-safe "grab the next piece of work" primitive — two agents racing on the same task cannot both win. The claim is idempotent when the task is already claimed by the same actor; when another actor already holds it the AITM API returns 409 (surfaced here as an error) so the agent should retry a different ready task. Pair with beads_ready to find candidates, then beads_claim to lock one in.', + schema: { + id: z.string().describe('The ID of the task to claim for work'), + ...projectionSchema, + }, + annotations: idempotentMutationAnnotations(), + run: async (args) => + beadsPut( + `/tasks/${encodeURIComponent(args.id)}/claim`, + undefined, + pickProjection(args) + ), + }), + defineTool({ name: 'beads_mark_done', description: 'Mark a Beads task as done (completed). This will unblock any downstream tasks that depend on this task.', diff --git a/gitgram/backend/prisma/schema.prisma b/gitgram/backend/prisma/schema.prisma index 21524a0b..3b4d4883 100644 --- a/gitgram/backend/prisma/schema.prisma +++ b/gitgram/backend/prisma/schema.prisma @@ -384,6 +384,13 @@ model Post { selfLabels String[] @default([]) // e.g. ["sexual", "graphic-media", "spoiler"] contentWarning String? // optional free-text warning shown alongside the label + // Detected spoken/natural language of the post body, as an ISO 639-1/639-2 + // code (e.g. "en", "es", "pt"). Distinct from programming-language fields on + // Repository/Project. Used by the feed pipeline's preferredLangOnly tuner step + // to filter content to a viewer's natural-language preferences. Null when the + // language could not be detected; such posts are never filtered out. + contentLanguage String? + // Optional geotagging for map / nearby discovery location String? latitude Float? @@ -415,6 +422,7 @@ model Post { @@index([aitmProjectId]) @@index([createdAt]) @@index([isArchived]) + @@index([contentLanguage]) } model Comment { diff --git a/gitgram/backend/src/controllers/feedFeedbackController.ts b/gitgram/backend/src/controllers/feedFeedbackController.ts new file mode 100644 index 00000000..3505fd2e --- /dev/null +++ b/gitgram/backend/src/controllers/feedFeedbackController.ts @@ -0,0 +1,77 @@ +import { Response } from 'express'; +import { AuthRequest } from '../middleware/auth'; +import { asyncHandler, Errors } from '../middleware/errorHandler'; +import logger from '../utils/logger'; + +/** + * Feed-feedback signals, ported from Bluesky's feed-feedback interactions. + * These are best-effort personalisation hints used to improve discover-feed + * ranking over time. + */ +const VALID_SIGNALS = ['requestLess', 'requestMore', 'seen'] as const; +type FeedSignal = (typeof VALID_SIGNALS)[number]; + +interface FeedSignalEvent { + postId: string; + signal: FeedSignal; + feedContext?: string; +} + +const MAX_EVENTS = 50; + +function isValidEvent(value: unknown): value is FeedSignalEvent { + if (!value || typeof value !== 'object') return false; + const e = value as Record; + return ( + typeof e.postId === 'string' && + e.postId.length > 0 && + e.postId.length <= 50 && + typeof e.signal === 'string' && + (VALID_SIGNALS as readonly string[]).includes(e.signal) && + (e.feedContext === undefined || typeof e.feedContext === 'string') + ); +} + +/** + * Record a batch of feed-feedback signals for the authenticated user. + * POST /api/v1/posts/feedback { events: FeedSignalEvent[] } + */ +export const recordFeedFeedback = asyncHandler(async (req: AuthRequest, res: Response) => { + const userId = req.user?.id; + if (!userId) { + throw Errors.unauthorized('Authentication required'); + } + + const { events } = req.body as { events?: unknown }; + + if (!Array.isArray(events)) { + throw Errors.badRequest('events must be an array'); + } + + if (events.length === 0) { + res.json({ success: true, recorded: 0 }); + return; + } + + if (events.length > MAX_EVENTS) { + throw Errors.badRequest(`Maximum ${MAX_EVENTS} events per request`); + } + + const valid = events.filter(isValidEvent); + + // Best-effort: surface these as structured ranking signals. Downstream + // personalisation / analytics can consume the log stream without requiring a + // schema migration in this change. + for (const event of valid) { + logger.info('feed-feedback signal', { + userId, + postId: event.postId, + signal: event.signal, + feedContext: event.feedContext, + }); + } + + res.json({ success: true, recorded: valid.length }); +}); + +export default { recordFeedFeedback }; diff --git a/gitgram/backend/src/controllers/postController.ts b/gitgram/backend/src/controllers/postController.ts index 6f0e2f1f..38cb95e8 100644 --- a/gitgram/backend/src/controllers/postController.ts +++ b/gitgram/backend/src/controllers/postController.ts @@ -15,6 +15,10 @@ import { getCachedComments, setCachedComments, invalidateCommentCache } from '.. import { tuneFeed, type TunableFeedItem } from '../services/feedTuner'; import { normalizeSelfLabels, decideSelfLabel } from '../services/selfLabels'; import { computeMutedFeedFlags } from '../services/mutedWordsService'; +import { + computePreferredLanguageFlags, + getPreferredLanguagesForUser, +} from '../services/languagePreferenceService'; export const createPost = asyncHandler(async (req: AuthRequest, res: Response) => { const { @@ -250,6 +254,7 @@ function toTunableItem(post: Record): TunableFeedItem { commentsCount: post.commentsCount as number | undefined, sharesCount: post.sharesCount as number | undefined, createdAt: post.createdAt as Date | string | undefined, + contentLanguage: (post.contentLanguage as string | null | undefined) ?? null, }; } @@ -298,6 +303,49 @@ async function applyMutedWords( ); } +/** + * Mark each feed item with `isPreferredLanguage` so `tuneFeed`'s + * `preferredLangOnly` step can keep only posts in the viewer's preferred + * natural languages (Bluesky `FeedTuner.preferredLangOnly` parity). The tuner's + * never-empty-page fallback ensures the feed never goes blank. + * + * Returns the (possibly unchanged) items plus a `preferredLangOnly` flag telling + * the caller whether the viewer has any natural-language preference at all; when + * false the tuner step is left disabled (a no-op for the largely-English + * audience) and no per-item flags are computed. + */ +async function applyPreferredLanguage( + items: TunableFeedItem[], + viewerId: string +): Promise<{ items: TunableFeedItem[]; preferredLangOnly: boolean }> { + if (items.length === 0) { + return { items, preferredLangOnly: false }; + } + + const preferred = await getPreferredLanguagesForUser(viewerId); + if (preferred.size === 0) { + // Viewer expressed no natural-language preference: skip filtering entirely. + return { items, preferredLangOnly: false }; + } + + const flags = await computePreferredLanguageFlags( + viewerId, + items.map(item => ({ + id: item.id, + contentLanguage: + typeof item.contentLanguage === 'string' ? item.contentLanguage : null, + })) + ); + + const marked = items.map(item => + flags.get(item.id) === false + ? { ...item, isPreferredLanguage: false } + : { ...item, isPreferredLanguage: true } + ); + + return { items: marked, preferredLangOnly: true }; +} + export const getFeed = asyncHandler(async (req: AuthRequest, res: Response) => { const userId = req.userId!; const { page = 1, limit = 20, cursor } = req.query; @@ -316,11 +364,16 @@ export const getFeed = asyncHandler(async (req: AuthRequest, res: Response) => { cursor.trim(), Number(limit) ); - const markedCursorItems = await applyMutedWords( + const mutedCursorItems = await applyMutedWords( (result.posts as Record[]).map(toTunableItem), userId ); - const tunedPosts = applySelfLabelBehavior(tuneFeed(markedCursorItems), labelOpts); + const { items: markedCursorItems, preferredLangOnly: cursorLangOnly } = + await applyPreferredLanguage(mutedCursorItems, userId); + const tunedPosts = applySelfLabelBehavior( + tuneFeed(markedCursorItems, { preferredLangOnly: cursorLangOnly }), + labelOpts + ); res.json({ ...result, posts: tunedPosts }); return; } @@ -338,11 +391,16 @@ export const getFeed = asyncHandler(async (req: AuthRequest, res: Response) => { return; } - const markedItems = await applyMutedWords( + const mutedItems = await applyMutedWords( (posts as Record[]).map(toTunableItem), userId ); - const tunedPosts = applySelfLabelBehavior(tuneFeed(markedItems), labelOpts); + const { items: markedItems, preferredLangOnly } = + await applyPreferredLanguage(mutedItems, userId); + const tunedPosts = applySelfLabelBehavior( + tuneFeed(markedItems, { preferredLangOnly }), + labelOpts + ); res.json({ posts: tunedPosts, isDiscover: false }); }); diff --git a/gitgram/backend/src/routes/posts.ts b/gitgram/backend/src/routes/posts.ts index 49110a71..576c95f5 100644 --- a/gitgram/backend/src/routes/posts.ts +++ b/gitgram/backend/src/routes/posts.ts @@ -138,6 +138,11 @@ router.get('/tagged/:userId', optionalAuth, postController.getTaggedPosts); import { getOptimalPostingTimes } from '../controllers/scheduledPostsController'; router.get('/optimal-times', authenticate, getOptimalPostingTimes); +// Feed-feedback signals (not-interested / show-more / seen) for personalisation. +// Registered before the '/:id' routes so 'feedback' is not parsed as an id. +import { recordFeedFeedback } from '../controllers/feedFeedbackController'; +router.post('/feedback', authenticate, interactionLimiter, recordFeedFeedback); + /** * @swagger * /api/v1/posts/archived: diff --git a/gitgram/backend/src/services/feedTuner.ts b/gitgram/backend/src/services/feedTuner.ts index fc226422..874d31bf 100644 --- a/gitgram/backend/src/services/feedTuner.ts +++ b/gitgram/backend/src/services/feedTuner.ts @@ -72,6 +72,19 @@ export interface TunableFeedItem { * a dangling reply with no visible context. */ isOrphan?: boolean; + /** + * Detected spoken/natural-language code of this item's content (ISO 639-1 or + * 639-2, e.g. "en"). Undefined/null when the language is unknown. Consumed by + * the `preferredLangOnly` step, which keeps an item when this matches one of + * the viewer's preferred languages. Items whose language is unknown are always + * kept (never filtered out) so undetected posts are not silently hidden. + * + * Ported from Bluesky's `FeedTuner.preferredLangOnly` (which calls + * `isPostInLanguage`); Gitgram precomputes the per-item match flag in + * services/languagePreferenceService.ts before tuning, so the tuner stays + * content-agnostic and does no language detection itself. + */ + isPreferredLanguage?: boolean; /** Pre-computed feed ranking score (higher = better). */ score: number; /** Optional trending score override; computed on-the-fly when absent. */ @@ -183,6 +196,24 @@ export interface FeedTunerOptions { * @default true */ removeOrphans?: boolean; + + /** + * When true, keep only items whose detected content language matches one of + * the viewer's preferred languages (`isPreferredLanguage === true`). Items + * with an unknown language (`isPreferredLanguage === undefined`) are always + * kept so undetected posts are never hidden. + * + * Ported from Bluesky's `FeedTuner.preferredLangOnly`. Crucially it carries + * Bluesky's "never return an empty page" fallback: if the language filter + * would clear out the entire page, the original (unfiltered) set is returned + * so the feed never goes blank. + * + * Defaults to FALSE: filtering only happens when a caller opts in (typically + * because the viewer has configured natural-language preferences). For the + * largely-English, dev-centric default audience the step is a no-op. + * @default false + */ + preferredLangOnly?: boolean; } // --------------------------------------------------------------------------- @@ -200,6 +231,7 @@ const DEFAULT_DEDUPE_THREADS = true; const DEFAULT_REMOVE_MUTED_THREADS = true; const DEFAULT_REMOVE_MUTED_WORDS = true; const DEFAULT_REMOVE_ORPHANS = true; +const DEFAULT_PREFERRED_LANG_ONLY = false; // --------------------------------------------------------------------------- // Internal helpers (pure functions — no side-effects) @@ -524,6 +556,35 @@ function dropMutedWords(items: ReadonlyArray): TunableFeedItem[ return items.filter(item => item.isMutedWord !== true); } +/** + * Keep only items whose detected content language matches the viewer's + * preferred languages. Ported from Bluesky's `FeedTuner.preferredLangOnly`. + * + * Semantics: + * - An item with `isPreferredLanguage === true` is kept. + * - An item with `isPreferredLanguage === undefined` (unknown language) is + * kept, so undetected posts are never silently hidden. + * - An item with `isPreferredLanguage === false` (known, non-preferred + * language) is dropped. + * - "Never return an empty page": if the filter clears out the ENTIRE input, + * the original set is returned unchanged so the feed never goes blank. + * + * Returns a new array — input is not modified. + */ +function filterPreferredLanguage( + items: ReadonlyArray +): TunableFeedItem[] { + const candidates = items.filter(item => item.isPreferredLanguage !== false); + + // If the language filter cleared out the entire page, fall back to the + // original set so that something always shows (Bluesky parity). + if (candidates.length === 0) { + return [...items]; + } + + return candidates; +} + // --------------------------------------------------------------------------- // FeedTuner class // --------------------------------------------------------------------------- @@ -554,6 +615,7 @@ export class FeedTuner { removeMutedThreads: options.removeMutedThreads ?? DEFAULT_REMOVE_MUTED_THREADS, removeMutedWords: options.removeMutedWords ?? DEFAULT_REMOVE_MUTED_WORDS, removeOrphans: options.removeOrphans ?? DEFAULT_REMOVE_ORPHANS, + preferredLangOnly: options.preferredLangOnly ?? DEFAULT_PREFERRED_LANG_ONLY, }; } @@ -565,13 +627,15 @@ export class FeedTuner { * 2. Drop orphaned replies (removeOrphans) * 3. Drop muted threads (removeMutedThreads) * 4. Drop muted words/tags (removeMutedWords) - * 5. Apply score adjustments (trending boost + diversity penalty) - * 6. Re-sort by adjusted score - * 7. Collapse threads by root (dedupThreads) — keeps the highest-scoring + * 5. Filter to preferred natural languages (preferredLangOnly), with a + * never-empty-page fallback + * 6. Apply score adjustments (trending boost + diversity penalty) + * 7. Re-sort by adjusted score + * 8. Collapse threads by root (dedupThreads) — keeps the highest-scoring * entry per thread, so it runs after the sort - * 8. Enforce author run limit - * 9. Interleave content types - * 10. Inject sponsored items + * 9. Enforce author run limit + * 10. Interleave content types + * 11. Inject sponsored items * * @param posts - Raw feed items (not mutated). * @returns New array of tuned feed items. @@ -587,7 +651,10 @@ export class FeedTuner { const withoutMuted = this.options.removeMutedWords ? dropMutedWords(withoutMutedThreads) : withoutMutedThreads; - const adjusted = applyScoreAdjustments(withoutMuted, this.options); + const langFiltered = this.options.preferredLangOnly + ? filterPreferredLanguage(withoutMuted) + : withoutMuted; + const adjusted = applyScoreAdjustments(langFiltered, this.options); const sorted = sortByScore(adjusted); const threadDeduped = this.options.dedupeThreads ? deduplicateByThreadRoot(sorted) diff --git a/gitgram/backend/src/services/languagePreferenceService.ts b/gitgram/backend/src/services/languagePreferenceService.ts new file mode 100644 index 00000000..04fd478a --- /dev/null +++ b/gitgram/backend/src/services/languagePreferenceService.ts @@ -0,0 +1,180 @@ +/** + * languagePreferenceService.ts + * + * Natural-language (spoken-language) feed preferences. + * + * Ported from Bluesky's `FeedTuner.preferredLangOnly` + the + * `src/state/preferences/feed-tuners.tsx` wiring (which feeds the viewer's + * `contentLanguages` into the tuner). Bluesky calls `isPostInLanguage(post, + * preferredLangsCode2)` per post; Gitgram precomputes the same per-post match + * flag here so the tuner (services/feedTuner.ts) stays content-agnostic. + * + * The list of preferred natural languages is read from the existing + * `UserLanguagePreference` model. That table is ALSO populated with PROGRAMMING + * languages by the recommendation/search subsystems (e.g. "TypeScript", + * "Python"), so this service filters the rows down to recognised spoken-language + * codes only. Programming-language rows are simply ignored — they never + * participate in feed language filtering, and this service never writes to the + * table, so the recommendation feature is unaffected. + * + * Every export is a PURE function or a thin Prisma data-access wrapper; the + * matcher performs no I/O and never mutates its inputs. + */ + +import { prisma } from '../utils/prisma'; + +/** + * Recognised spoken/natural-language codes (ISO 639-1, with a few common 639-2 + * codes). Used to distinguish a viewer's natural-language preferences from the + * programming-language entries that share the `UserLanguagePreference` table. + * + * This is intentionally a curated allow-list rather than an exhaustive registry: + * it covers the languages a content-language detector is realistically going to + * emit, while reliably excluding programming-language names ("Go", "C", "R", + * etc. are NOT spoken-language codes here). + */ +const SPOKEN_LANGUAGE_CODES: ReadonlySet = new Set([ + 'aa', 'ab', 'af', 'ak', 'am', 'ar', 'as', 'ay', 'az', + 'be', 'bg', 'bm', 'bn', 'bo', 'br', 'bs', + 'ca', 'cs', 'cy', + 'da', 'de', 'dv', 'dz', + 'ee', 'el', 'en', 'eo', 'es', 'et', 'eu', + 'fa', 'ff', 'fi', 'fo', 'fr', 'fy', + 'ga', 'gd', 'gl', 'gn', 'gu', 'gv', + 'ha', 'he', 'hi', 'hr', 'ht', 'hu', 'hy', + 'id', 'ig', 'is', 'it', + 'ja', 'jv', + 'ka', 'kk', 'km', 'kn', 'ko', 'ku', 'kw', 'ky', + 'la', 'lb', 'lo', 'lt', 'lv', + 'mg', 'mi', 'mk', 'ml', 'mn', 'mr', 'ms', 'mt', 'my', + 'nb', 'ne', 'nl', 'nn', 'no', + 'oc', 'om', 'or', + 'pa', 'pl', 'ps', 'pt', + 'qu', + 'rm', 'rn', 'ro', 'ru', 'rw', + 'sa', 'sd', 'se', 'sg', 'si', 'sk', 'sl', 'sn', 'so', 'sq', 'sr', 'su', 'sv', 'sw', + 'ta', 'te', 'tg', 'th', 'ti', 'tk', 'tl', 'tn', 'to', 'tr', 'ts', 'tt', + 'ug', 'uk', 'ur', 'uz', + 've', 'vi', + 'wo', + 'xh', + 'yi', 'yo', + 'zh', 'zu', +]); + +/** + * Normalise a language tag to its lowercase ISO 639-1/639-2 base code. + * + * Accepts BCP-47-ish tags ("en-US", "pt_BR", "zh-Hant") and reduces them to the + * primary subtag ("en", "pt", "zh"). Returns '' when the input is unusable. + * Mirrors Bluesky's `code3ToCode2`/`toCode2`-style normalisation at the + * coarse-grained level the feed filter needs. + */ +export function normalizeLanguageCode(input: string | null | undefined): string { + if (typeof input !== 'string') return ''; + const trimmed = input.trim().toLowerCase(); + if (trimmed.length === 0) return ''; + // Primary subtag only: split on '-' or '_'. + const primary = trimmed.split(/[-_]/)[0]; + return primary; +} + +/** Is `code` a recognised spoken/natural-language code (after normalisation)? */ +export function isSpokenLanguageCode(code: string | null | undefined): boolean { + const normalized = normalizeLanguageCode(code); + return normalized.length > 0 && SPOKEN_LANGUAGE_CODES.has(normalized); +} + +/** + * Decide whether a post's content language matches the viewer's preferred + * natural languages. Pure; performs no I/O. Mirrors the boolean returned by + * Bluesky's `isPostInLanguage`. + * + * Semantics: + * - Empty `preferredLanguages` => no preference, everything matches (true). + * - Unknown/undetected `contentLanguage` => true (never hide undetected posts). + * - Otherwise => true iff the normalised content language is in the preferred + * set. + * + * @returns true when the post should be considered in-language for this viewer. + */ +export function isPostInPreferredLanguage( + contentLanguage: string | null | undefined, + preferredLanguages: ReadonlySet +): boolean { + if (preferredLanguages.size === 0) return true; + const code = normalizeLanguageCode(contentLanguage); + if (code.length === 0) return true; // unknown language: always keep + return preferredLanguages.has(code); +} + +/** + * Load the viewer's PREFERRED NATURAL languages from `UserLanguagePreference`, + * filtered to recognised spoken-language codes and ordered by descending weight + * then score. Programming-language rows are excluded. Returns a normalised, + * de-duplicated set of ISO-639 base codes (empty when the viewer has no spoken + * language preferences configured). + */ +export async function getPreferredLanguagesForUser( + userId: string +): Promise> { + const rows = await prisma.userLanguagePreference.findMany({ + where: { userId }, + orderBy: [{ weight: 'desc' }, { score: 'desc' }], + select: { language: true }, + }); + + const preferred = new Set(); + for (const row of rows) { + if (isSpokenLanguageCode(row.language)) { + preferred.add(normalizeLanguageCode(row.language)); + } + } + return preferred; +} + +/** A feed post considered for preferred-language marking. */ +export interface FeedLanguageCandidate { + id: string; + /** Detected content language code, or null when unknown. */ + contentLanguage: string | null; +} + +/** + * For each feed post, decide whether it is in one of the viewer's preferred + * natural languages. Returns a map of post id -> match flag where: + * + * - `true` the post is in a preferred language (or its language is + * unknown, which is always kept). + * - `false` the post has a known, non-preferred language and should be + * dropped by the tuner's `preferredLangOnly` step. + * + * When the viewer has NO spoken-language preferences configured, every value is + * `true` (no filtering) and no per-post work is needed. This mirrors the feed + * read path's `computeMutedFeedFlags` shape so the controller can apply both + * uniformly. + */ +export async function computePreferredLanguageFlags( + userId: string, + candidates: ReadonlyArray +): Promise> { + const result = new Map(); + for (const c of candidates) result.set(c.id, true); + + if (candidates.length === 0) return result; + + const preferred = await getPreferredLanguagesForUser(userId); + if (preferred.size === 0) { + // No preference => everything is "in language". + return result; + } + + for (const candidate of candidates) { + result.set( + candidate.id, + isPostInPreferredLanguage(candidate.contentLanguage, preferred) + ); + } + + return result; +} diff --git a/gitgram/mobile/app/(tabs)/_layout.tsx b/gitgram/mobile/app/(tabs)/_layout.tsx index 40aa2f05..a8896c76 100644 --- a/gitgram/mobile/app/(tabs)/_layout.tsx +++ b/gitgram/mobile/app/(tabs)/_layout.tsx @@ -2,6 +2,7 @@ import { Tabs } from 'expo-router'; import { Colors } from '../../constants/Colors'; import Icon from 'react-native-vector-icons/MaterialIcons'; import { emitSoftReset } from '../../utils/events'; +import MinimalShellTabBar from '../../components/navigation/MinimalShellTabBar'; /** * Fires a soft reset (scroll-to-top + refresh) when the user taps the tab that @@ -23,6 +24,7 @@ const softResetListeners = ({ export default function TabsLayout() { return ( } screenOptions={{ headerShown: false, tabBarActiveTintColor: Colors.primary, diff --git a/gitgram/mobile/app/(tabs)/home.tsx b/gitgram/mobile/app/(tabs)/home.tsx index 01c1a2a7..a5544318 100644 --- a/gitgram/mobile/app/(tabs)/home.tsx +++ b/gitgram/mobile/app/(tabs)/home.tsx @@ -12,6 +12,7 @@ import { FlatList, RefreshControl, TouchableOpacity, + Animated, NativeSyntheticEvent, NativeScrollEvent, } from 'react-native'; @@ -31,6 +32,10 @@ import { adService } from '../../services/adService'; import repositoryService from '../../services/repositoryService'; import { storyService } from '../../services/storyService'; import { usePostViewTracking } from '../../hooks/usePostViewTracking'; +import { + useMinimalShell, + useMinimalHeaderStyle, +} from '../../hooks/useMinimalShell'; import { listenSoftReset } from '../../utils/events'; import { logger } from '../../utils/logger'; import { useRouter } from 'expo-router'; @@ -40,6 +45,9 @@ type FeedItem = { type: 'post' | 'ad' | 'repo'; data: any; index: number }; // Distance (px) the user must scroll down before the "load latest" pill appears. const LOAD_LATEST_OFFSET = 320; +// Height of the top app bar; the minimal-shell header collapses by this much. +const HEADER_HEIGHT = 56; + interface TrendingRepo { fullName: string; description?: string; @@ -117,6 +125,11 @@ export default function HomeScreen() { // a background poll surfaces fresher content. const newestPostIdRef = useRef(null); + // Hide-on-scroll: collapse the header (and bottom tab bar) on downward + // scroll, reveal on upward scroll. Shared with the tab bar via a singleton. + const minimalShell = useMinimalShell(); + const headerAnimStyle = useMinimalHeaderStyle(HEADER_HEIGHT); + const { onViewableItemsChanged, reset: resetViewTracking } = usePostViewTracking({ logContext: 'home-feed', @@ -240,8 +253,9 @@ export default function HomeScreen() { const scrollToTopAndRefresh = useCallback(() => { listRef.current?.scrollToOffset({ offset: 0, animated: true }); setScrolledDown(false); + minimalShell.reveal(); handleRefresh(); - }, []); + }, [minimalShell]); // Soft reset: re-pressing the Home tab scrolls to top and reloads. useEffect(() => { @@ -283,8 +297,10 @@ export default function HomeScreen() { const next = offsetY > LOAD_LATEST_OFFSET; return prev === next ? prev : next; }); + // Drive the collapsing header + tab bar. + minimalShell.onScroll(event); }, - [], + [minimalShell], ); if (loading && posts.length === 0) { @@ -327,6 +343,12 @@ export default function HomeScreen() { return items; }, [posts, ads, trendingRepos]); + // Remove a post the viewer hid ("Not interested") or whose author they + // blocked, so it disappears from the feed immediately. + const handleHidePost = useCallback((postId: string) => { + setPosts((prev) => prev.filter((p) => p?.id !== postId)); + }, []); + const renderItem = useCallback(({ item }: { item: FeedItem }) => { if (item.type === 'ad') { return ; @@ -334,8 +356,8 @@ export default function HomeScreen() { if (item.type === 'repo') { return )} />; } - return ; - }, []); + return ; + }, [handleHidePost]); const keyExtractor = useCallback((item: FeedItem) => { if (item.type === 'ad') return `ad-${item.data.id}`; @@ -347,8 +369,8 @@ export default function HomeScreen() { return ( - {/* Top App Bar */} - + {/* Top App Bar — collapses on downward scroll (minimal shell). */} + 💻 Gitgram @@ -374,7 +396,7 @@ export default function HomeScreen() { 📤 - + {/* Main Content Feed */} @@ -468,12 +490,21 @@ const styles = StyleSheet.create({ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', - height: 56, + height: HEADER_HEIGHT, paddingHorizontal: 16, borderBottomWidth: 1, borderBottomColor: Colors.border, backgroundColor: Colors.background, }, + // Absolutely positioned so collapsing it reclaims vertical feed space; the + // list compensates with matching top padding. + headerAbsolute: { + position: 'absolute', + top: 0, + left: 0, + right: 0, + zIndex: 10, + }, headerLeft: { flexDirection: 'row', alignItems: 'center', @@ -511,6 +542,7 @@ const styles = StyleSheet.create({ position: 'relative', }, listContent: { + paddingTop: HEADER_HEIGHT, // Clear the absolutely-positioned app bar paddingBottom: 80, // Space for bottom tab bar }, skeletonList: { diff --git a/gitgram/mobile/app/(tabs)/notifications.tsx b/gitgram/mobile/app/(tabs)/notifications.tsx index a40cf8f3..f24d8ff1 100644 --- a/gitgram/mobile/app/(tabs)/notifications.tsx +++ b/gitgram/mobile/app/(tabs)/notifications.tsx @@ -12,20 +12,16 @@ import { useRouter } from 'expo-router'; import { Colors } from '../../constants/Colors'; import LoadingSpinner from '../../components/common/LoadingSpinner'; import GestureActionView from '../../components/common/GestureActionView'; -import { notificationService } from '../../services/notificationService'; +import { + notificationService, + groupNotifications, + type Notification, + type GroupedNotification, +} from '../../services/notificationService'; import { userService } from '../../services/userService'; import { useToast } from '../../hooks/useToast'; import { listenSoftReset } from '../../utils/events'; - -interface Notification { - id: string; - type: string; - title: string; - body: string; - isRead: boolean; - createdAt: string; - data?: Record; -} +import { timeAgo } from '../../utils/timeAgo'; const getStringValue = (data: Record | undefined, key: string): string | undefined => { const value = data?.[key]; @@ -40,7 +36,7 @@ export default function NotificationsScreen() { const [followingUsers, setFollowingUsers] = useState>(new Set()); const [followLoading, setFollowLoading] = useState>(new Set()); const { showToast, ToastComponent } = useToast(); - const listRef = useRef>(null); + const listRef = useRef>(null); useEffect(() => { loadNotifications(); @@ -217,69 +213,118 @@ export default function NotificationsScreen() { } }; - const formatTime = (dateString: string) => { - const date = new Date(dateString); - const now = new Date(); - const diff = now.getTime() - date.getTime(); - const minutes = Math.floor(diff / 60000); - const hours = Math.floor(minutes / 60); - const days = Math.floor(hours / 24); + // Avatar entries for a grouped row's actor stack (deduped, base actor first). + const getGroupActors = useCallback( + (group: GroupedNotification): { username: string; avatar?: string }[] => { + const all = [group.notification, ...group.additional]; + const seen = new Set(); + const actors: { username: string; avatar?: string }[] = []; + for (const n of all) { + const username = getStringValue(n.data, 'username') || 'user'; + const userId = getStringValue(n.data, 'userId') || username; + if (seen.has(userId)) continue; + seen.add(userId); + actors.push({ username, avatar: getStringValue(n.data, 'avatar') }); + } + return actors; + }, + [], + ); - if (minutes < 1) return 'just now'; - if (minutes < 60) return `${minutes}m ago`; - if (hours < 24) return `${hours}h ago`; - if (days < 7) return `${days}d ago`; - return date.toLocaleDateString(); - }; + // Builds the aggregated headline, e.g. "@alice and 5 others liked your post". + const buildGroupText = useCallback( + (group: GroupedNotification): { actorLabel: string; body: string } => { + const actors = getGroupActors(group); + const primary = actors[0]?.username ?? 'user'; + const extra = group.actorCount - 1; + const actorLabel = + extra <= 0 + ? `@${primary}` + : extra === 1 && actors[1] + ? `@${primary} and @${actors[1].username}` + : `@${primary} and ${extra} ${extra === 1 ? 'other' : 'others'}`; + return { actorLabel, body: group.notification.body }; + }, + [getGroupActors], + ); - const renderNotification = ({ item }: { item: Notification }) => { - const { icon, color } = getNotificationIcon(item.type); - const userId = getStringValue(item.data, 'userId'); - const username = getStringValue(item.data, 'username') || 'user'; - const thumbnail = getStringValue(item.data, 'thumbnail'); + const renderNotification = ({ item }: { item: GroupedNotification }) => { + const base = item.notification; + const { icon, color } = getNotificationIcon(base.type); + const userId = getStringValue(base.data, 'userId'); + const thumbnail = getStringValue(base.data, 'thumbnail'); const isFollowing = userId ? followingUsers.has(userId) : false; const isLoading = userId ? followLoading.has(userId) : false; + const { actorLabel, body } = buildGroupText(item); + const actors = getGroupActors(item); + const isGroup = item.actorCount > 1; + const ids = [base.id, ...item.additional.map((n) => n.id)]; + const allRead = base.isRead && item.additional.every((n) => n.isRead); return ( handleMarkOneRead(item), + action: () => ids.forEach((id) => handleMarkOneRead({ ...base, id })), }, right: { color: Colors.error, icon: 'delete', label: 'Delete', - action: () => handleDelete(item.id), + action: () => ids.forEach((id) => handleDelete(id)), }, }} > handleNotificationPress(item)} + style={[styles.notificationItem, !allRead && styles.unreadNotification]} + onPress={() => handleNotificationPress(base)} activeOpacity={0.7} > - - {icon} - + {isGroup ? ( + + {actors.slice(0, 3).map((actor, idx) => ( + + {actor.avatar ? ( + + ) : ( + + + {actor.username.charAt(0).toUpperCase()} + + + )} + + ))} + + {icon} + + + ) : ( + + {icon} + + )} - @{username}{' '} - {item.body} + {actorLabel}{' '} + {body} - {formatTime(item.createdAt)} + {timeAgo(base.createdAt, { format: 'long' })} ago {thumbnail && ( )} - {item.type === 'follow' && userId && !isFollowing && ( + {!isGroup && base.type === 'follow' && userId && !isFollowing && ( { @@ -295,7 +340,7 @@ export default function NotificationsScreen() { )} )} - {item.type === 'follow' && userId && isFollowing && ( + {!isGroup && base.type === 'follow' && userId && isFollowing && ( Following @@ -313,6 +358,8 @@ export default function NotificationsScreen() { ? notifications.filter(n => n.type !== 'following') : notifications.filter(n => n.type === 'following'); + const groupedNotifications = groupNotifications(filteredNotifications); + return ( {ToastComponent} @@ -366,9 +413,9 @@ export default function NotificationsScreen() { {/* Notifications List */} item.id} + keyExtractor={(item) => item.key} ItemSeparatorComponent={() => } ListEmptyComponent={ @@ -471,6 +518,46 @@ const styles = StyleSheet.create({ iconBadgeText: { fontSize: 20, }, + avatarStack: { + width: 84, + height: 48, + justifyContent: 'center', + }, + stackedAvatar: { + position: 'absolute', + }, + stackedAvatarImg: { + width: 36, + height: 36, + borderRadius: 18, + borderWidth: 2, + borderColor: Colors.background, + }, + stackedAvatarFallback: { + backgroundColor: Colors.primary, + alignItems: 'center', + justifyContent: 'center', + }, + stackedAvatarInitial: { + color: Colors.text, + fontSize: 14, + fontWeight: '700', + }, + miniBadge: { + position: 'absolute', + bottom: 0, + left: 28, + width: 22, + height: 22, + borderRadius: 11, + alignItems: 'center', + justifyContent: 'center', + borderWidth: 2, + borderColor: Colors.background, + }, + miniBadgeText: { + fontSize: 11, + }, notificationContent: { flex: 1, }, diff --git a/gitgram/mobile/components/Post/PostCard.tsx b/gitgram/mobile/components/Post/PostCard.tsx index f8d1712e..30767b25 100644 --- a/gitgram/mobile/components/Post/PostCard.tsx +++ b/gitgram/mobile/components/Post/PostCard.tsx @@ -4,14 +4,18 @@ import { Text, StyleSheet, TouchableOpacity, + Alert, } from 'react-native'; import { useRouter } from 'expo-router'; import { Image } from 'expo-image'; import { Colors } from '../../constants/Colors'; import { postService } from '../../services/postService'; +import { userService } from '../../services/userService'; import { logger } from '../../utils/logger'; import { useAuthStore } from '../../store/authStore'; import { useHaptics } from '../../hooks/useHaptics'; +import { useToast } from '../../hooks/useToast'; +import { timeAgo } from '../../utils/timeAgo'; import PostOptionsModal from '../common/PostOptionsModal'; import ReportModal from '../common/ReportModal'; import CodeBlock from '../common/CodeBlock'; @@ -47,23 +51,88 @@ interface PostCardProps { onLike?: () => void; onPress?: () => void; showFullContent?: boolean; + /** + * Called when the viewer hides this post ("Not interested") or blocks its + * author. The parent can drop the post from its feed list; if omitted the + * card hides itself locally. + */ + onHide?: (postId: string) => void; } -export default function PostCard({ post, onLike, showFullContent = false }: PostCardProps) { +export default function PostCard({ post, onLike, showFullContent = false, onHide }: PostCardProps) { const router = useRouter(); const { user } = useAuthStore(); const haptics = useHaptics(); const openLightbox = useLightbox(); + const { showToast, ToastComponent } = useToast(); 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 [hidden, setHidden] = useState(false); + const [isBlocked, setIsBlocked] = useState(false); + const [blocking, setBlocking] = useState(false); const likeBounceRef = useRef(null); const lastTapRef = useRef(0); const isOwner = user?.id === post.user.id; + // Hide this post from the viewer's feed ("Not interested"). Purely + // client-side: the parent feed can prune it, otherwise we self-hide. + const handleHidePost = () => { + haptics('Light'); + if (onHide) { + onHide(post.id); + } else { + setHidden(true); + } + showToast('Post hidden', 'success'); + }; + + const handleBlockUser = () => { + if (blocking) return; + const action = isBlocked ? 'Unblock' : 'Block'; + Alert.alert( + `${action} @${post.user.username}?`, + isBlocked + ? 'They will be able to see your content and interact with you again.' + : "You won't see their posts and they won't be able to interact with you.", + [ + { text: 'Cancel', style: 'cancel' }, + { + text: action, + style: isBlocked ? 'default' : 'destructive', + onPress: async () => { + setBlocking(true); + try { + if (isBlocked) { + await userService.unblockUser(post.user.id); + setIsBlocked(false); + showToast(`Unblocked @${post.user.username}`, 'success'); + } else { + await userService.blockUser(post.user.id); + setIsBlocked(true); + showToast(`Blocked @${post.user.username}`, 'success'); + // A blocked author's post should leave the feed immediately. + if (onHide) { + onHide(post.id); + } else { + setHidden(true); + } + } + } catch (error) { + logger.error('Block user error:', error); + showToast(`Failed to ${action.toLowerCase()} user`, 'error'); + } finally { + setBlocking(false); + } + }, + }, + ], + ); + }; + // 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') => { @@ -116,8 +185,13 @@ export default function PostCard({ post, onLike, showFullContent = false }: Post openLightbox([{ uri: post.mediaUrl, alt: post.content || undefined }], 0); }; + if (hidden) { + return null; + } + return ( + {ToastComponent} {/* Card Header */} {post.user.username[0].toUpperCase()} )} - {post.user.username} + + {post.user.username} + {timeAgo(post.createdAt)} + setShowOptionsModal(true)}> ⋯ @@ -232,6 +309,10 @@ export default function PostCard({ post, onLike, showFullContent = false }: Post onClose={() => setShowOptionsModal(false)} onReport={() => setShowReportModal(true)} onShare={() => router.push(`/post/${post.id}/share`)} + onHidePost={handleHidePost} + onBlockUser={handleBlockUser} + authorUsername={post.user.username} + isBlocked={isBlocked} isOwner={isOwner} /> @@ -284,11 +365,19 @@ const styles = StyleSheet.create({ fontWeight: 'bold', fontSize: 16, }, + headerTextWrap: { + flexShrink: 1, + }, username: { color: Colors.text, fontWeight: 'bold', fontSize: 14, }, + timestamp: { + color: Colors.textSecondary, + fontSize: 12, + marginTop: 1, + }, moreButton: { width: 32, height: 32, diff --git a/gitgram/mobile/components/common/PostOptionsModal.tsx b/gitgram/mobile/components/common/PostOptionsModal.tsx index 6eb6ca7d..faf2030c 100644 --- a/gitgram/mobile/components/common/PostOptionsModal.tsx +++ b/gitgram/mobile/components/common/PostOptionsModal.tsx @@ -18,6 +18,14 @@ interface PostOptionsModalProps { isOwner?: boolean; onEdit?: () => void; onDelete?: () => void; + /** Hide this post / "Not interested" — client-side feed filter. */ + onHidePost?: () => void; + /** Block the post's author. */ + onBlockUser?: () => void; + /** Username shown in the block/hide labels for clarity. */ + authorUsername?: string; + /** Whether the author is already blocked (toggles label to Unblock). */ + isBlocked?: boolean; } interface OptionItem { @@ -38,6 +46,10 @@ export default function PostOptionsModal({ isOwner = false, onEdit, onDelete, + onHidePost, + onBlockUser, + authorUsername, + isBlocked = false, }: PostOptionsModalProps) { const handleOptionPress = (onPress: () => void) => { onClose(); @@ -70,6 +82,22 @@ export default function PostOptionsModal({ onPress: () => onEdit?.(), hidden: !isOwner || !onEdit, }, + { + // Client-side "not interested" filter — hides the post from the feed. + label: 'Hide this post', + icon: '🙈', + onPress: () => onHidePost?.(), + hidden: isOwner || !onHidePost, + }, + { + label: isBlocked + ? `Unblock${authorUsername ? ` @${authorUsername}` : ''}` + : `Block${authorUsername ? ` @${authorUsername}` : ''}`, + icon: '🚫', + onPress: () => onBlockUser && handleOptionPress(onBlockUser), + destructive: !isBlocked, + hidden: isOwner || !onBlockUser, + }, { label: 'Report', icon: '🚩', diff --git a/gitgram/mobile/components/navigation/MinimalShellTabBar.tsx b/gitgram/mobile/components/navigation/MinimalShellTabBar.tsx new file mode 100644 index 00000000..33e9290e --- /dev/null +++ b/gitgram/mobile/components/navigation/MinimalShellTabBar.tsx @@ -0,0 +1,33 @@ +import React from 'react'; +import { Animated } from 'react-native'; +import { + BottomTabBar, + type BottomTabBarProps, +} from '@react-navigation/bottom-tabs'; + +import { useMinimalFooterStyle } from '../../hooks/useMinimalShell'; + +/** Height of the tab bar; the footer collapses by this much when hidden. */ +const TAB_BAR_HEIGHT = 80; + +/** + * Bottom tab bar that participates in the "minimal shell" hide-on-scroll: + * it slides down and fades out as the shared shell collapses (driven by the + * feed's scroll via `useMinimalShell`), and reveals on upward scroll. + * + * Wraps the default `BottomTabBar` in an `Animated.View` so we keep all the + * stock tab behavior (icons, labels, accessibility, soft-reset listeners) + * while animating the container. The bar stays in normal layout flow so other + * tab screens keep their existing bottom spacing — it slides off-screen on + * collapse rather than being absolutely positioned, avoiding any cross-tab + * content-overlap regression. + */ +export default function MinimalShellTabBar(props: BottomTabBarProps) { + const footerStyle = useMinimalFooterStyle(TAB_BAR_HEIGHT); + + return ( + + + + ); +} diff --git a/gitgram/mobile/components/proximity/PostCard.tsx b/gitgram/mobile/components/proximity/PostCard.tsx index ad65a94d..9108d4f3 100644 --- a/gitgram/mobile/components/proximity/PostCard.tsx +++ b/gitgram/mobile/components/proximity/PostCard.tsx @@ -9,6 +9,7 @@ import { import { Image } from 'expo-image'; import { useRouter } from 'expo-router'; import { logger } from '../../utils/logger'; +import { timeAgo } from '../../utils/timeAgo'; import { postService } from '../../services/postService'; interface PostAuthor { @@ -29,18 +30,6 @@ interface PostCardProps { post: Post; } -function formatTimestamp(iso: string): string { - const diff = Date.now() - new Date(iso).getTime(); - const minutes = Math.floor(diff / 60_000); - if (minutes < 1) return 'just now'; - if (minutes < 60) return `${minutes}m ago`; - const hours = Math.floor(minutes / 60); - if (hours < 24) return `${hours}h ago`; - const days = Math.floor(hours / 24); - if (days < 7) return `${days}d ago`; - return new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }); -} - export default function PostCard({ post }: PostCardProps) { const router = useRouter(); const [likes, setLikes] = useState(post.likes); @@ -111,7 +100,7 @@ export default function PostCard({ post }: PostCardProps) { {post.author.username} - {formatTimestamp(post.createdAt)} + {timeAgo(post.createdAt)} diff --git a/gitgram/mobile/hooks/useMinimalShell.ts b/gitgram/mobile/hooks/useMinimalShell.ts new file mode 100644 index 00000000..84c8049f --- /dev/null +++ b/gitgram/mobile/hooks/useMinimalShell.ts @@ -0,0 +1,151 @@ +import { useCallback, useEffect, useRef } from 'react'; +import { + Animated, + Easing, + type NativeScrollEvent, + type NativeSyntheticEvent, +} from 'react-native'; + +/** + * "Minimal shell" hide-on-scroll, reimplemented from Bluesky's + * useMinimalShellTransform + ScrollContext + minimal-mode state + * (src/lib/hooks/useMinimalShellTransform.ts). + * + * Bluesky drives this with reanimated shared values; we reimplement on the RN + * `Animated` API the product already uses (LoadLatestButton, GestureActionView) + * so no new dependency is pulled in. + * + * `mode` is a single shared Animated.Value in [0, 1]: + * 0 = shell fully visible, 1 = shell fully hidden (collapsed). + * + * The value is a module-level singleton so the feed header and the bottom tab + * bar (which live in different component trees) collapse and reveal in sync. + */ + +// Singleton: shared by every consumer (header + tab bar) so they animate as one. +const sharedMode = new Animated.Value(0); + +// Distance (px) the user must scroll in a direction before we flip the shell. +const SCROLL_THRESHOLD = 12; +// Don't react to scrolls near the very top — the header should always be shown. +const TOP_REVEAL_OFFSET = 24; +const ANIM_DURATION = 200; + +function setMode(target: 0 | 1): void { + Animated.timing(sharedMode, { + toValue: target, + duration: ANIM_DURATION, + easing: Easing.out(Easing.cubic), + // translate/opacity are native-driver safe. + useNativeDriver: true, + }).start(); +} + +export interface MinimalShellScroll { + /** Attach to a scrollable's `onScroll`. Pair with `scrollEventThrottle`. */ + onScroll: (event: NativeSyntheticEvent) => void; + /** Force the shell back to fully-visible (e.g. on tab focus / soft reset). */ + reveal: () => void; +} + +/** + * Returns a scroll handler that collapses the shell on downward scroll and + * reveals it on upward scroll. Call once per scrollable feed. + */ +export function useMinimalShell(): MinimalShellScroll { + const lastOffset = useRef(0); + const lastMode = useRef<0 | 1>(0); + + const onScroll = useCallback( + (event: NativeSyntheticEvent) => { + const offsetY = event.nativeEvent.contentOffset.y; + const delta = offsetY - lastOffset.current; + + // Always reveal near the top regardless of direction. + if (offsetY <= TOP_REVEAL_OFFSET) { + if (lastMode.current !== 0) { + lastMode.current = 0; + setMode(0); + } + lastOffset.current = offsetY; + return; + } + + if (Math.abs(delta) < SCROLL_THRESHOLD) { + return; + } + + const next: 0 | 1 = delta > 0 ? 1 : 0; // scrolling down hides, up reveals + if (next !== lastMode.current) { + lastMode.current = next; + setMode(next); + } + lastOffset.current = offsetY; + }, + [], + ); + + const reveal = useCallback(() => { + lastMode.current = 0; + lastOffset.current = 0; + setMode(0); + }, []); + + // Reset the shared shell when the consuming screen unmounts so a collapsed + // header never leaks into a screen without a scroll handler. + useEffect(() => { + return () => { + setMode(0); + }; + }, []); + + return { onScroll, reveal }; +} + +/** + * Animated style for a top header: slides up and fades out as the shell + * collapses. `height` is the header's pixel height (the collapse distance). + */ +export function useMinimalHeaderStyle(height: number): { + opacity: Animated.AnimatedInterpolation; + transform: { translateY: Animated.AnimatedInterpolation }[]; +} { + return { + opacity: sharedMode.interpolate({ + inputRange: [0, 1], + outputRange: [1, 0], + }), + transform: [ + { + translateY: sharedMode.interpolate({ + inputRange: [0, 1], + outputRange: [0, -height], + }), + }, + ], + }; +} + +/** + * Animated style for the bottom tab bar: slides down and fades out as the + * shell collapses. `height` is the tab bar's pixel height. + */ +export function useMinimalFooterStyle(height: number): { + opacity: Animated.AnimatedInterpolation; + transform: { translateY: Animated.AnimatedInterpolation }[]; +} { + return { + opacity: sharedMode.interpolate({ + inputRange: [0, 1], + outputRange: [1, 0], + }), + transform: [ + { + translateY: sharedMode.interpolate({ + inputRange: [0, 1], + outputRange: [0, height], + }), + }, + ], + }; +} diff --git a/gitgram/mobile/services/notificationService.ts b/gitgram/mobile/services/notificationService.ts index de49165e..fba48cf8 100644 --- a/gitgram/mobile/services/notificationService.ts +++ b/gitgram/mobile/services/notificationService.ts @@ -1,5 +1,137 @@ import api from './api'; +// --------------------------------------------------------------------------- +// Notification types + grouping +// --------------------------------------------------------------------------- + +/** A single notification as returned by GET /notifications. */ +export interface Notification { + id: string; + type: string; + title: string; + body: string; + isRead: boolean; + createdAt: string; + data?: Record; +} + +/** + * A notification row after grouping. `additional` holds same-reason, + * same-subject events that were collapsed into this row (newest-first base + * notification, oldest collapsed events appended). `actorCount` is the total + * number of distinct events represented (1 + additional.length). + */ +export interface GroupedNotification { + /** Stable key for list rendering. */ + key: string; + /** The representative (most recent) notification for this group. */ + notification: Notification; + /** Other notifications merged into this group, if any. */ + additional: Notification[]; + /** Total number of events represented by this row. */ + actorCount: number; +} + +/** + * Reasons whose events are safe to collapse into a single row. Ported from + * Bluesky's GROUPABLE_REASONS (src/state/queries/notifications/util.ts) and + * mapped to the product's notification `type` vocabulary. Comment/mention-style + * events are intentionally excluded so each carries its own context. + */ +const GROUPABLE_TYPES = new Set(['like', 'follow', 'star', 'repost', 'fork']); + +/** 48h window (in ms) within which same-subject events are grouped. */ +const GROUP_WINDOW_MS = 1000 * 60 * 60 * 48; + +const getStringField = ( + data: Record | undefined, + key: string, +): string | undefined => { + const value = data?.[key]; + return typeof value === 'string' ? value : undefined; +}; + +/** + * The subject a notification refers to (post/repo/etc). Two events group only + * when they share a type AND a subject, so we derive a stable subject key from + * the notification payload. + */ +function getSubjectKey(notif: Notification): string | undefined { + const data = notif.data; + return ( + getStringField(data, 'postId') ?? + getStringField(data, 'repoFullName') ?? + (getStringField(data, 'repoOwner') && getStringField(data, 'repoName') + ? `${getStringField(data, 'repoOwner')}/${getStringField(data, 'repoName')}` + : undefined) ?? + getStringField(data, 'targetId') + ); +} + +/** The actor (user) responsible for a notification, if identifiable. */ +function getActorKey(notif: Notification): string | undefined { + return getStringField(notif.data, 'userId'); +} + +/** + * Collapses same-type, same-subject notifications that occur within a 48h + * window into single grouped rows ("Alice and 5 others liked your post"). + * + * Pure function, ported from Bluesky's `groupNotifications` and adapted to the + * product's flat Notification shape (no atproto dependency). Input order is + * preserved for the resulting representative rows; distinct actors only are + * grouped (an actor never groups with themselves on the same subject). + */ +export function groupNotifications( + notifs: Notification[], +): GroupedNotification[] { + const grouped: GroupedNotification[] = []; + + for (const notif of notifs) { + const ts = new Date(notif.createdAt).getTime(); + let didGroup = false; + + if (GROUPABLE_TYPES.has(notif.type)) { + const subject = getSubjectKey(notif); + const actor = getActorKey(notif); + + for (const group of grouped) { + const base = group.notification; + if (base.type !== notif.type) continue; + if (getSubjectKey(base) !== subject) continue; + + const baseTs = new Date(base.createdAt).getTime(); + if (Math.abs(baseTs - ts) >= GROUP_WINDOW_MS) continue; + + // Don't group an actor with themselves (avoids "Alice and Alice"). + const baseActor = getActorKey(base); + const groupActors = new Set( + [baseActor, ...group.additional.map(getActorKey)].filter( + (a): a is string => typeof a === 'string', + ), + ); + if (actor && groupActors.has(actor)) continue; + + group.additional.push(notif); + group.actorCount += 1; + didGroup = true; + break; + } + } + + if (!didGroup) { + grouped.push({ + key: `notif-${notif.id}-${notif.type}`, + notification: notif, + additional: [], + actorCount: 1, + }); + } + } + + return grouped; +} + export const notificationService = { getNotifications: async (page = 1, limit = 20, unreadOnly = false) => { const response = await api.get('/notifications', { diff --git a/gitgram/mobile/utils/timeAgo.ts b/gitgram/mobile/utils/timeAgo.ts new file mode 100644 index 00000000..55369a09 --- /dev/null +++ b/gitgram/mobile/utils/timeAgo.ts @@ -0,0 +1,158 @@ +import { differenceInSeconds } from 'date-fns'; + +/** + * Relative-time ("time ago") helpers, ported from Bluesky's `useTimeAgo` + * (src/lib/hooks/useTimeAgo.ts) and adapted to the product's plain-function / + * no-i18n-framework conventions. + * + * The opinionated ruleset is preserved verbatim: + * - All months are considered exactly 30 days. + * - `earlier` is assumed to be <= `later`; otherwise the result is 'now'. + * - Differences under the `NOW` threshold collapse to 'now'. + * - All values round down (configurable to round up for future timestamps). + * - Differences of >= 12 months fall back to a localized date string. + * + * Consolidating this here removes the per-screen drift from the ~15 inline + * timestamp formatters scattered across the app (PostCard variants, + * notifications, reading-list, scheduled posts, messages, story/archive, ...). + */ + +export type DateInput = number | string | Date; + +export type DateDiffFormat = 'long' | 'short'; + +export type DateDiffUnit = 'now' | 'second' | 'minute' | 'hour' | 'day' | 'month'; + +export interface DateDiff { + value: number; + unit: DateDiffUnit; + earlier: Date; + later: Date; +} + +/** Below this many seconds the difference is reported as "now". */ +const NOW = 5; +const MINUTE = 60; +const HOUR = MINUTE * 60; +const DAY = HOUR * 24; +const MONTH_30 = DAY * 30; + +/** + * Returns the difference between `earlier` and `later`, based on the + * opinionated rules described in the module header. + */ +export function dateDiff( + earlier: DateInput, + later: DateInput, + rounding: 'up' | 'down' = 'down', +): DateDiff { + const e = new Date(earlier); + const l = new Date(later); + const diffSeconds = differenceInSeconds(l, e); + + const round = (seconds: number, per: number): number => + rounding === 'up' ? Math.ceil(seconds / per) : Math.floor(seconds / per); + + let value = 0; + let unit: DateDiffUnit = 'now'; + + if (diffSeconds < NOW) { + value = 0; + unit = 'now'; + } else if (diffSeconds < MINUTE) { + value = diffSeconds; + unit = 'second'; + } else if (diffSeconds < HOUR) { + value = round(diffSeconds, MINUTE); + unit = 'minute'; + } else if (diffSeconds < DAY) { + value = round(diffSeconds, HOUR); + unit = 'hour'; + } else if (diffSeconds < MONTH_30) { + value = round(diffSeconds, DAY); + unit = 'day'; + } else { + value = round(diffSeconds, MONTH_30); + unit = 'month'; + } + + return { value, unit, earlier: e, later: l }; +} + +const NARROW_SUFFIX: Record, string> = { + second: 's', + minute: 'm', + hour: 'h', + day: 'd', +}; + +const LONG_LABEL: Record, string> = { + second: 'second', + minute: 'minute', + hour: 'hour', + day: 'day', +}; + +function pluralize(value: number, label: string): string { + return `${value} ${label}${value === 1 ? '' : 's'}`; +} + +/** + * Formats a `DateDiff` as a natural-language string. + * + * - `short` (default): narrow form, e.g. `5m`, `3h`, `2d`, `4mo`, `now`. + * - `long`: spelled out, e.g. `5 minutes`, `1 hour`, `now`. + * - Differences >= 12 months render as a localized date string. + */ +export function formatDateDiff( + diff: DateDiff, + format: DateDiffFormat = 'short', +): string { + const long = format === 'long'; + + switch (diff.unit) { + case 'now': + return 'now'; + case 'second': + case 'minute': + case 'hour': + case 'day': + return long + ? pluralize(diff.value, LONG_LABEL[diff.unit]) + : `${diff.value}${NARROW_SUFFIX[diff.unit]}`; + case 'month': + if (diff.value < 12) { + return long ? pluralize(diff.value, 'month') : `${diff.value}mo`; + } + return diff.earlier.toLocaleDateString(); + } +} + +/** + * Convenience helper: difference between `earlier` and now (or an explicit + * `later`), formatted in one call. This is the function most screens want. + * + * @example timeAgo(post.createdAt) // "5m" + * @example timeAgo(post.createdAt, { format: 'long' }) // "5 minutes" + */ +export function timeAgo( + earlier: DateInput, + options?: { later?: DateInput; format?: DateDiffFormat }, +): string { + const later = options?.later ?? Date.now(); + return formatDateDiff(dateDiff(earlier, later, 'down'), options?.format); +} + +/** + * Variant for future timestamps (e.g. scheduled posts): rounds up and measures + * from now to the (later) target. + * + * @example timeUntil(scheduledFor) // "3d" + */ +export function timeUntil( + later: DateInput, + options?: { earlier?: DateInput; format?: DateDiffFormat }, +): string { + const earlier = options?.earlier ?? Date.now(); + return formatDateDiff(dateDiff(earlier, later, 'up'), options?.format); +} diff --git a/gitgram/web/components/EmbedPlayer.tsx b/gitgram/web/components/EmbedPlayer.tsx new file mode 100644 index 00000000..a06254ed --- /dev/null +++ b/gitgram/web/components/EmbedPlayer.tsx @@ -0,0 +1,91 @@ +'use client' + +import { useState } from 'react' +import { + EMBED_PLAYER_LABELS, + getEmbedPlayerAspect, + type EmbedPlayerParams, +} from '@/utils/embedPlayer' + +interface EmbedPlayerProps { + params: EmbedPlayerParams + /** Original URL, used for the "open externally" affordance and alt text. */ + url: string + className?: string +} + +/** + * Renders an inline media player for a recognised provider (YouTube, Twitch, + * Spotify, Vimeo, SoundCloud, Apple Music, Giphy). + * + * To avoid auto-loading third-party iframes (and the privacy / performance + * cost that entails), non-GIF embeds start as a click-to-load facade showing + * the provider name. Only after the user opts in do we mount the iframe. + * GIFs render directly as images since they carry no autoplay-with-audio cost. + */ +export default function EmbedPlayer({ params, url, className = '' }: EmbedPlayerProps) { + const [activated, setActivated] = useState(false) + const aspect = getEmbedPlayerAspect(params.type) + const label = EMBED_PLAYER_LABELS[params.source] + + const frameStyle: React.CSSProperties = aspect.aspectRatio + ? { aspectRatio: String(aspect.aspectRatio) } + : { height: aspect.height } + + // GIFs: render as a plain image, no iframe, no facade. + if (params.isGif) { + return ( +
+ {/* eslint-disable-next-line @next/next/no-img-element */} + {`${label} +
+ ) + } + + if (!activated) { + return ( + + ) + } + + return ( +
+