repo
stringclasses
20 values
path
stringlengths
6
94
lang
stringclasses
5 values
n_chars
int64
81
200k
sha256
stringlengths
64
64
content
stringlengths
81
200k
eren23/non_linear_ai_chat
frontend/src/store/__tests__/useTaskStore.test.ts
ts
22,985
e795e23be0347599922585f201c53fd76cd1aa3cc12914172b158a525722667f
/** * Tests for useTaskStore. * * Tests cover: * - Initial state * - getCacheKey β€” deterministic key from filters * - isCacheValid β€” TTL check * - fetchTasks β€” API call, caching, loading state, forceRefresh, error handling * - completeTask β€” optimistic update + API call + refresh * - archiveTask β€” optimistic u...
eren23/non_linear_ai_chat
frontend/src/store/__tests__/useGraphStore.staleDetection.diamond.test.ts
ts
20,181
297b78ec0ad25b7e40e54bafd767311efdc985cdcb6b8b3cdf9b17a9d4464ba7
/** * Tests for stale detection with diamond DAG patterns. * * Diamond DAGs are graphs where two or more paths from a common ancestor * converge at a shared descendant (synthesis node). These patterns exercise * the BFS traversal in findRecursiveChildren and verify that markChildrenAsStale * correctly handles mul...
eren23/non_linear_ai_chat
frontend/src/store/__tests__/useAuthStore.test.ts
ts
18,976
2549b3b88401d4b25f1c192a67abcff68bcfb7d7861839b9401aac9e0db2ceb4
/** * Tests for authentication store. * * Tests cover: * - Initial state * - checkAuth - authentication verification * - setUser - direct user setting * - logout - session termination * - loadUserPreferences - preference loading * - updateUserPreferences - preference updates * - Error handling */ import { d...
eren23/non_linear_ai_chat
frontend/src/store/__tests__/useAuthStore-security.test.ts
ts
14,144
b4b8ca7498f27d1c49cd66e1932ba2ff1e3c9bbf2fb4cbe33255806357c4109e
/** * Security-focused edge case tests for the authentication store. * * These tests verify behavior under adversarial or unusual conditions: * - Guard against unnecessary API calls (re-initialization) * - Graceful degradation on network / API failures * - Complete state cleanup on logout (no credential leaks) *...
eren23/non_linear_ai_chat
frontend/src/store/__tests__/useNotesStore.test.ts
ts
21,194
f0134a9ac9a54043661fcd953c191005690b02f34834f085dd7cebe4a661b613
/** * Tests for useNotesStore. * * Tests cover: * - Initial state * - getCacheKey β€” deterministic key from filters * - isCacheValid β€” TTL check * - fetchNotes β€” API call, caching, loading state, force refresh, error handling * - fetchMoreNotes β€” pagination/append behavior * - createNote β€” API call + cache inva...
eren23/non_linear_ai_chat
frontend/src/store/__tests__/useAgentStore.test.ts
ts
26,522
23fe816cdfb14ab2a8be44e851ab6407fabf170a63e9715635cbe15c116e5bba
/** * Tests for the useAgentStore Zustand store. * * Tests cover: * - Initial state values * - setSetupDialogOpen * - startSession (success + error) * - stopSession (with/without sessionId) * - pauseSession / resumeSession * - sendMessage * - respondToPermission * - reset * - Socket handlers (_handle* metho...
eren23/non_linear_ai_chat
frontend/src/store/__tests__/useCollaborationStore-enhanced.test.ts
ts
17,872
dc6d18cc24b98b175d588dc2a81dd3e11c01a8457dd5832c244b3e748ebc9192
/** * Enhanced tests for the collaboration store. * * These tests go beyond the basic test suite to cover: * - Round-robin color assignment from USER_COLORS (8 colors, wrapping) * - Color index reset behavior via reset() * - Multi-lock cascading cleanup when removing a collaborator * - setCursors color inheritan...
eren23/non_linear_ai_chat
frontend/src/store/__tests__/useGraphStore.nodes.test.ts
ts
21,373
f38c095e517ce72af97b1cc7c7f397618c2e87975db6f3ea7d750740ea929ab9
/** * Tests for node CRUD operations in the graph store. * * These tests use REAL slice implementations to ensure proper code coverage. * The node slice handles: * - Adding chat nodes (with parent-child relationships) * - Adding information nodes (standalone content nodes) * - Adding media generation nodes (imag...
eren23/non_linear_ai_chat
frontend/src/store/__tests__/useCaptureStore.test.ts
ts
24,797
5fe47c36ebd9c089ad908faaa8cfe50b3ce0b0eb5db93b8e90938a006e06e261
/** * Tests for useCaptureStore - core actions and selectors. * * Covers fetchCaptures, fetchCaptureById, fetchStats, setFilters, * deleteCapture, updateCapture, toggleCapture, bulkOperation, * processCapture, selection actions, initSocketListeners, * fetchGroupedCaptures, getDomainGroups, toggleGroupExpanded, *...
eren23/non_linear_ai_chat
frontend/src/store/__tests__/useGraphStore.ancestry.test.ts
ts
19,216
af681973fe30729fd5052006ddf42bc973f7108b14969873795b361d5c8c61e1
/** * Tests for ancestry chain traversal functionality. * * These tests use REAL slice implementations to ensure proper code coverage. * The ancestry chain is CRITICAL for LLM context building: * - Determines which messages are sent to the LLM * - Must include ALL parent branches (not just first parent) * - Must...
eren23/non_linear_ai_chat
frontend/src/store/__tests__/useCollaborationStore.test.ts
ts
13,023
9d7a1a607b0f38e5473d4f4007ef2a78567799de4140bc5ee8f5eb127ddd522b
/** * Tests for the collaboration store. * * The collaboration store manages real-time collaboration state: * - Active collaborators (users currently in the flow) * - Node locks (prevents concurrent edits) * - Cursor positions (shows where others are) */ import { describe, it, expect, beforeEach } from 'vitest'...
eren23/non_linear_ai_chat
frontend/src/store/__tests__/useFeatureStore.test.ts
ts
8,256
3f00cf24969e83ac151f8a33f5807bfcb26500813e2b0b959cfdd51656071af7
/** * Tests for useFeatureStore. * * Tests cover: * - Initial state (all features default to true, not initialized) * - setFeatures β€” sets features and marks initialized=true * - isEnabled β€” returns feature value, defaults to true for unknown keys * - getFeatureDisplayName β€” maps feature keys to display names *...
eren23/non_linear_ai_chat
frontend/src/store/__tests__/useTourStore.test.ts
ts
9,006
90942156bfe39f993c39905d87b00fb1a8b9bb264e773aafaf8c8a9e372d1d4e
/** * Tests for useTourStore. * * Tests cover: * - Initial state (not running, stepIndex 0, hasCompleted from localStorage) * - startTour β€” sets isRunning=true, resets stepIndex=0 * - stopTour β€” sets isRunning=false * - nextStep β€” increments stepIndex * - prevStep β€” decrements stepIndex, clamped at 0 * - goToS...
eren23/non_linear_ai_chat
frontend/src/store/__tests__/useCaptureStore.importToExistingNode.test.ts
ts
14,645
c66bcd52d0d11812185252ef5b68c83a53b61f962bb07fafb8381a87592e2a67
/** * Unit tests for useCaptureStore.importCaptureToExistingNode. * * Tests importing capture content into an existing info node: adding text sub-nodes, * merging webLinks/tags (with deduplication), and adding photo sub-nodes. */ import { describe, it, expect, vi, beforeEach } from 'vitest'; // -----------------...
eren23/non_linear_ai_chat
specs/001-telegram-advanced/contracts/interfaces.ts
ts
7,799
97f9c314856c1a97eaa885e30026e380620c30f2de1516815c31f5e96de78b24
/** * Telegram Advanced Interface - TypeScript Interfaces * * These interfaces define the contract for new/extended types. * Implementation should match these exactly. */ // ============================================================================ // Conversation Context Extensions // =========================...
eren23/non_linear_ai_chat
specs/001-mcp-server-engineering/contracts/module-interface.ts
ts
7,027
9e10391987829727f0a074d2654d92feaf9a4f1eef758012f9d147957fbd43af
/** * MCP Server Module Interface Contract * * This file defines the TypeScript interfaces that every domain module must implement. * It serves as the API contract between the module registry (core) and domain modules. * * NOTE: This is a design contract, not production code. The actual implementation * will be ...
eren23/non_linear_ai_chat
mcp-server/src/errors.ts
ts
13,354
903d4f9286bc32cdd79e1cb91aa9818749427490c181f6267064aeb312f9c117
/** * Structured error system for the Spider Chat MCP Server. * * Maps HTTP errors (from axios) and validation errors (from Zod) into * categorized MCP errors that agents can interpret for retry logic, * rephrasing, or surfacing to the user. * * Security (FR-015, R12): All error mapping functions strip sensitive...
eren23/non_linear_ai_chat
mcp-server/src/types.ts
ts
10,647
8ac7099be2eca186c0afa415b8fc2ef3547b3867152789f33c11c74823ed1f66
/** * Core type definitions for the Spider Chat MCP Server. * * This module defines the foundational interfaces and types used across * all MCP server modules. It establishes the contract between tool/resource * definitions, their handlers, and the server runtime. * * Key design decisions: * - ToolDefinition us...
eren23/non_linear_ai_chat
mcp-server/src/logger.ts
ts
4,367
dcfe52497343a38c60fd52dee6aebaf97ac0e6e7c1d07bed4dc69aec3afaf8bf
/** * Structured stderr logger for the MCP server. * * stdout is reserved for the MCP JSON-RPC protocol -- ALL diagnostic * output MUST go to stderr via console.error. This module provides a * level-filtered, named logger that writes structured messages to stderr * with automatic credential sanitization (FR-015, ...
eren23/non_linear_ai_chat
mcp-server/src/client.ts
ts
2,962
f45743b45579c6db2629689610209f4730d444bc2732c54c236cb0dd641566e0
import axios, { AxiosError, AxiosInstance } from 'axios'; import { ServerConfig } from './types.js'; import { createLogger } from './logger.js'; import { mapHttpError } from './errors.js'; /** * Creates a pre-configured axios instance for the Spider Chat backend API. * * All requests are scoped to the `/api/mcp` pr...
eren23/non_linear_ai_chat
mcp-server/src/registry.ts
ts
9,525
1270d7e9c065b84c104eea4c1c7a6e0ebf41a56f8cae5ecc1b30557360c7917c
import { readdir } from 'node:fs/promises'; import { join, extname } from 'node:path'; import { pathToFileURL } from 'node:url'; import { McpError as SdkMcpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js'; import type { McpModule, ToolDefinition, ResourceDefinition, ResourceEntry, ResourceContent,...
eren23/non_linear_ai_chat
mcp-server/src/index.ts
ts
5,414
4d5385f5ecdc1728bd35e833a531ba38acc6dfcf701c2734226e6446b48fe248
#!/usr/bin/env node /** * Spider Chat MCP Server β€” Entry Point * * Bootstraps the MCP server by loading configuration, creating clients, * auto-discovering domain modules from the `modules/` directory, and * wiring tool + resource handlers to the MCP SDK transport. * * stdout is reserved for the MCP JSON-RPC pr...
eren23/non_linear_ai_chat
mcp-server/src/config.ts
ts
2,169
e031449a5f1dadef7e0aff9257f56493078e598ba33b01c1612c4d7d62ed8969
import * as dotenv from 'dotenv'; dotenv.config(); import type { ServerConfig } from './types.js'; const VALID_MODES = ['readonly', 'readwrite'] as const; const VALID_LOG_LEVELS = ['debug', 'info', 'warn', 'error'] as const; /** * Loads server configuration from environment variables. * * Required: * SPIDERCHA...
eren23/non_linear_ai_chat
mcp-server/src/__tests__/errors.test.ts
ts
27,048
a4123ba1154cc3a0e55046f0e74fd5c62dee583c079e68baeeb1221e0c0de33c
import { describe, it, expect } from 'vitest'; import { z } from 'zod'; import type { AxiosError } from 'axios'; import { McpError, mapHttpError, mapZodError, toToolResult, createPartialResult, sanitizeResourceId, validateExternalUrl } from '../errors.js'; // -----------------------------------------------------------...
eren23/non_linear_ai_chat
mcp-server/src/__tests__/canvas.test.ts
ts
12,433
7c1f5e3b16aadcb7dfe162a4295ecf4f8982e5e3f8206de22b48279a6c32d087
import { describe, it, expect, vi } from 'vitest'; import type { AxiosInstance } from 'axios'; import canvasModule from '../modules/canvas.js'; import type { HandlerContext, ToolResult } from '../types.js'; // --------------------------------------------------------------------------- // Helpers // -------------------...
eren23/non_linear_ai_chat
mcp-server/src/__tests__/modules.test.ts
ts
55,089
0391cdaaba9683e45f6ebdf7672cda6810e96787693e547c06a5140cbf87efce
import { describe, it, expect, vi } from 'vitest'; import type { AxiosInstance } from 'axios'; import libraryModule from '../modules/library.js'; import searchModule from '../modules/search.js'; import factsModule from '../modules/facts.js'; import memoriesModule from '../modules/memories.js'; import remindersModule fr...
eren23/non_linear_ai_chat
mcp-server/src/__tests__/registry.test.ts
ts
25,362
e04d43cb604286bb9c51ad7483f1b80de092052d0f589698ad0307c952904e9b
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { z } from 'zod'; import { McpError as SdkMcpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js'; import { ModuleRegistry } from '../registry.js'; import { McpError } from '../errors.js'; import type { ServerConfig, Logger, HandlerCont...
eren23/non_linear_ai_chat
mcp-server/src/__tests__/config.test.ts
ts
8,422
c3c4836fc08ae6f34643807fce43b938dc1399f270886be24640712686dd6140
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import type { ServerConfig } from '../types.js'; // --------------------------------------------------------------------------- // Constants // --------------------------------------------------------------------------- const DEFAULT_API_URL = ...
eren23/non_linear_ai_chat
mcp-server/src/__tests__/logger.test.ts
ts
11,761
c8a693850eb3c592758eb46d7fa123e45ddcd9c5f14ee203aa5c27a1e9b9c522
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { createLogger, sanitize } from '../logger.js'; import type { ServerConfig } from '../types.js'; // --------------------------------------------------------------------------- // Helpers // ------------------------------------------------...
eren23/non_linear_ai_chat
mcp-server/src/modules/relationships.ts
ts
4,651
2b332de98fae55c93d3c02e6a4bc4fe43d985c11c478396fa51ab43c96ebcc6d
/** * Relationships MCP Module * * Exposes read-only tools for querying interpersonal relationships and * retrieving contextual information about specific people stored in * Spider Chat. * * Tools: * - get_relationships β€” List relationships with optional type/strength filters * - get_person_context β€” Retrieve...
eren23/non_linear_ai_chat
mcp-server/src/modules/canvas.ts
ts
20,329
f20fd782d9848e5a61b71b25b82ac4476ee694651a778258585a4e905f3fc340
/** * Canvas Module β€” MCP write tools for manipulating Spider Chat flow canvases. * * Provides direct canvas mutation tools that bypass the agent reasoning loop, * enabling Excalidraw-like speed (<500ms per operation) when driven by an * external LLM via MCP. * * All tools are mode: 'write' and require the serve...
eren23/non_linear_ai_chat
mcp-server/src/modules/toolSearch.ts
ts
2,884
7644882ca5b5314ec024035a0bc5a21fe45f575d421eab100d5c5c3b3463af88
/** * Tool Search Module β€” meta-tool for discovering on-demand tools. * * By default the server returns only "entry point" tools from ListTools. * The rest are registered but hidden from discovery to keep per-session * tool-definition token overhead low. Agents locate hidden tools by * calling `tool_search` with ...
eren23/non_linear_ai_chat
mcp-server/src/modules/commitments.ts
ts
3,821
8aae8eef2d839df16a27aac19f77ede0625df1392180431e5ba0d930a4c82da8
/** * Commitments MCP Module * * Exposes a read-only tool for listing task commitments extracted from * conversations in Spider Chat. Scoped to 'commitments' and operates * in 'read' mode. * * Tools: * - get_commitments β€” Browse task commitments with optional status, * date, and assignment filters */ impor...
eren23/non_linear_ai_chat
mcp-server/src/modules/search.ts
ts
4,181
5f994c761bacd015834d2ae055592d1ff6982b6411c2874c8e95db7051edffc9
/** * Search MCP Module * * Exposes a read-only tool for performing unified searches across flows, * memories, and facts stored in Spider Chat. Results are returned in a * single paginated response grouped by category. * * Tools: * - unified_search -- Search across flows, memories, and facts simultaneously. */...
eren23/non_linear_ai_chat
mcp-server/src/modules/memories.ts
ts
7,043
c329cdeaf290cd0fc2ba6806bfe0ecbcbd63cd476eb9762ab31eaf14c211b056
/** * Memories MCP Module * * Exposes tools for searching and creating memories stored in Spider Chat. * Memories are auto-extracted knowledge fragments categorized by type * (personal info, tasks, responsibilities, learnings, etc.) with an * importance score. * * Read tools (always available): * - search_memo...
eren23/non_linear_ai_chat
mcp-server/src/modules/flows.ts
ts
17,315
f6f67d9f05c6ed13abf761eea18c0023720cf3da5a175bd9be98986ccb08cce6
/** * Flows Module β€” MCP tools for querying and navigating Spider Chat flows. * * Tools: * - search_flows Search flows by query string and optional tags. * - get_flow_nodes Retrieve all nodes (or a filtered subset) for a flow. * - list_flow_groups List available flow groups with pagination...
eren23/non_linear_ai_chat
mcp-server/src/modules/agent.ts
ts
6,136
ea0a2ac2f5b2a900ab399e21a05873455a4a22b0ce9d905ab1c8f57b075f912a
/** * Agent Module β€” MCP tools for controlling AI agent sessions. * * Provides tools to check agent status, stop, pause, and resume * agent sessions. All operations resolve the session from the * authenticated user's MCP token (no session ID needed). * * All tools are mode: 'write' and require the server to run ...
eren23/non_linear_ai_chat
mcp-server/src/modules/context.ts
ts
5,057
65605153845acd7a56e1b1cea8dfba9498f1e5a6d89f7ed08e2099d353d7edf4
/** * Context Module -- MCP tools for retrieving contextual information from * Spider Chat's memory system and conversation ancestry chains. * * Tools: * - get_relevant_context Fetch memories and facts relevant to a query. * - get_conversation_chain Retrieve the ancestry chain for a specific node * ...
eren23/non_linear_ai_chat
mcp-server/src/modules/captures.ts
ts
15,013
8f3e90050964232883633e1caf1ed6714af18dd8cfb2ea157f9244081a4b2153
/** * Captures MCP Module * * Exposes read and write tools for managing browser extension captures * in Spider Chat. Captures are lightweight bookmarks of web content * that can be processed into full library documents with RAG indexing. * * Read tools (always available): * - search_captures β€” List/search cap...
eren23/non_linear_ai_chat
mcp-server/src/modules/notes.ts
ts
21,148
eb8e81fb90b7b92e51012b90691a92f1fd96e23fa1b5ef2e2a281c9a3efcde78
/** * Notes MCP Module * * Exposes read and write tools for managing wiki-style notes in Spider Chat. * All tools are scoped to 'notes'. * * Read tools (always available): * - search_notes β€” Full-text / AI / hybrid search across notes * - get_note β€” Fetch a single note by ID, optionally with b...
eren23/non_linear_ai_chat
mcp-server/src/modules/reminders.ts
ts
5,889
5946dbde948cf35387d272af3d156834041fce2eb44afa3aad2aa69df9c19e72
/** * Reminders MCP Module * * Exposes read-only tools for listing and fetching reminders stored in * Spider Chat. All tools are scoped to 'reminders' and operate in 'read' mode. * * Tools: * - list_reminders β€” Browse reminders with optional status and recurring filters * - get_reminder β€” Fetch a single remin...
eren23/non_linear_ai_chat
mcp-server/src/modules/agentMode.ts
ts
5,520
119ac2c1fbced01a8205623d04834c14b962163a8355fdef0218e4999ec6d27a
/** * Agent Mode Module β€” MCP tools for connecting/disconnecting from flows. * * When connected, the MCP user appears as a visible collaborator in the * flow owner's UI. This gives flow owners awareness and control over * remote MCP editing sessions. * * Tools: * - agent_mode_connect Connect to a flow as a...
eren23/non_linear_ai_chat
mcp-server/src/modules/library.ts
ts
9,970
63b3b2409edc5190aa73f97a71c7cad994c251d1175da218b36e31a51c6ba651
/** * Library module for the Spider Chat MCP Server. * * Exposes four read-only tools for interacting with the user's document * library: searching, retrieving, listing, and getting AI-powered * document suggestions based on conversational context. * * All list/search tools follow FR-013 (limit + offset paginati...
eren23/non_linear_ai_chat
mcp-server/src/modules/web.ts
ts
6,629
00af0309575cdfe2b6843c6caed399a6b351c6177aab04b505014b5386cd4dec
/** * Web operations module for the Spider Chat MCP Server. * * Exposes tools for web search and URL scraping via the web-ops service. * All tools are read-only and use `ctx.webOpsApi` for backend communication. */ import { z } from 'zod'; import type { McpModule, HandlerContext, ToolResult, ToolHandler } from '....
eren23/non_linear_ai_chat
mcp-server/src/modules/facts.ts
ts
4,883
406cd2376e7e8f7a44fff757e294ca462f9eba7fbcf5af0da4f1b1c2a7457433
/** * Facts MCP Module * * Exposes a read-only tool for searching user facts stored in Spider Chat. * Facts represent extracted knowledge about the user (identity, preferences, * goals, etc.) with associated importance scores. * * Tools: * - search_facts β€” Search user facts with optional type/importance filters...
eren23/non_linear_ai_chat
mcp-server/src/modules/__tests__/memories.functional.test.ts
ts
15,396
1ce0ebb00a1cc2d011cb26a41f94eea2bdb9ece00e4c6381791df06f841ae107
import { describe, it, expect, vi, beforeEach } from 'vitest'; import type { HandlerContext, ToolResult } from '../../types.js'; import memoriesModule from '../memories.js'; // --------------------------------------------------------------------------- // Helpers // ----------------------------------------------------...
eren23/non_linear_ai_chat
mcp-server/src/modules/__tests__/flows.functional.test.ts
ts
14,804
c7ed694c19182cb737a2cbbe3558b1ae032c9e4749ea67421f8c463305264813
import { describe, it, expect, vi, beforeEach } from 'vitest'; import type { AxiosInstance } from 'axios'; import flowsModule from '../flows.js'; import type { HandlerContext, ToolResult } from '../../types.js'; // --------------------------------------------------------------------------- // Helpers // --------------...
eren23/non_linear_ai_chat
mcp-server/src/modules/__tests__/canvas.functional.test.ts
ts
17,734
e964fd9706c8663968b5ceedc88501905a43e04d7188010553047c5d633a0bd8
import { describe, it, expect, vi, beforeEach } from 'vitest'; import type { AxiosInstance } from 'axios'; import canvasModule from '../canvas.js'; import type { HandlerContext, ToolResult } from '../../types.js'; // --------------------------------------------------------------------------- // Helpers // ------------...
eren23/non_linear_ai_chat
mcp-server/src/modules/__tests__/facts.functional.test.ts
ts
10,287
6928b3960bab36083f931e8e6fa99080b847b8b6b2ac94ec915eea7768559cb2
import { describe, it, expect, vi, beforeEach } from 'vitest'; import type { HandlerContext, ToolResult } from '../../types.js'; import factsModule from '../facts.js'; // --------------------------------------------------------------------------- // Helpers // ----------------------------------------------------------...
eren23/non_linear_ai_chat
mcp-server/src/modules/__tests__/web.functional.test.ts
ts
9,902
cea818b0f99fb7c747a9caabd097c95f5625f267c0da67f8a1f85f47b93ea3cf
import { describe, it, expect, vi, beforeEach } from 'vitest'; import type { HandlerContext, ToolResult } from '../../types.js'; import webModule from '../web.js'; // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------...
eren23/non_linear_ai_chat
mcp-server/src/modules/__tests__/agent.functional.test.ts
ts
12,059
3874b0393c387ea6c9d5fb8c60122a23d177fdfca7f5ddb72b128d05f987f86d
import { describe, it, expect, vi, beforeEach } from 'vitest'; import type { HandlerContext, ToolResult } from '../../types.js'; import agentModule from '../agent.js'; // --------------------------------------------------------------------------- // Helpers // ----------------------------------------------------------...
eren23/non_linear_ai_chat
mcp-server/src/modules/__tests__/captures.functional.test.ts
ts
16,373
712986e33674d3e3fe1279421a8482ed7834bb7013f206a16aeef8b7e73dd167
import { describe, it, expect, vi, beforeEach } from 'vitest'; import type { AxiosInstance } from 'axios'; import capturesModule from '../captures.js'; import type { HandlerContext, ToolResult } from '../../types.js'; // --------------------------------------------------------------------------- // Helpers // --------...
eren23/non_linear_ai_chat
mcp-server/src/modules/__tests__/notes.functional.test.ts
ts
25,344
b57b4c7bab93d8c6724a65c7f41b18972d618ac179abf1ef16dce5584f11b867
import { describe, it, expect, vi, beforeEach } from 'vitest'; import type { AxiosInstance } from 'axios'; import notesModule from '../notes.js'; import type { HandlerContext, ToolResult } from '../../types.js'; // --------------------------------------------------------------------------- // Helpers // --------------...
eren23/non_linear_ai_chat
tests/benchmarks/ancestry.bench.ts
ts
2,535
3d58f73a25517c3e6e5f60ddb59d8ea9dfd7d02eead630ef85425228cb57ecf2
/** * Ancestry Chain Computation Benchmark * * Measures performance of getAncestryChain across different graph sizes. * * Run: * npx vitest bench tests/benchmarks/ancestry.bench.ts */ import { bench, describe } from 'vitest'; import { getAncestryChain, type GraphNode, type GraphEdge } from '../../backend/src/...
eren23/non_linear_ai_chat
tests/benchmarks/tokenEstimation.bench.ts
ts
1,742
03d0b1b7aa60db010d73ef45ca7222f7c45d90467178b55c3af72d382b2097c2
/** * Token Estimation Benchmark * * Measures performance of token estimation across different text sizes. * * Run: * npx vitest bench tests/benchmarks/tokenEstimation.bench.ts */ import { bench, describe } from 'vitest'; // Simple token estimation (char-based approximation) function estimateTokensSimple(tex...
eren23/non_linear_ai_chat
diagram-converter/metrics.py
py
2,605
548d4a6f182f5d89e37a6e119b70db8c297442dc92028f78ffda3bedb194e00c
""" Prometheus metrics for Diagram Converter. Tracks conversion counts, durations, and element counts. """ import time from contextlib import contextmanager class Metrics: """Simple Prometheus-compatible metrics collector.""" def __init__(self): self._conversions_total = {"success": 0, "error": 0} ...
eren23/non_linear_ai_chat
diagram-converter/ocr_engine.py
py
13,329
cb7bdd65a02585a5d95e644fcee1fe97d4d1c9533bee7e7125acf4661715596a
""" Parallel OCR Engine for Diagram Text Extraction Runs multiple OCR backends in parallel and merges results with confidence-weighted deduplication. Supports: - Tesseract (general text) - PaddleOCR (general text, CJK support) - Pix2Text (LaTeX / mathematical formula detection) """ import asyncio import logging...
eren23/non_linear_ai_chat
diagram-converter/drawio_builder.py
py
20,747
1c4c8cd582bec904ab24716e2c19375e55ab186aca85b0e6bd6655599afe76bc
""" DrawIO XML Builder Converts segmented diagram elements and OCR text into valid mxGraphModel XML that can be opened in draw.io / diagrams.net. DrawIO XML structure: <mxGraphModel> <root> <mxCell id="0"/> <!-- root cell --> <mxCell id="1" parent="0"/> <!-- default ...
eren23/non_linear_ai_chat
diagram-converter/pipeline.py
py
11,134
7e223148635a6add343695c1f5120d6cdff4926e9d5193e1885d96def81f5ddb
""" Diagram Conversion Pipeline Orchestrates the full conversion from image to DrawIO XML: 1. Image preprocessing (resize, normalize) 2. Segmentation (SAM3 or OpenCV fallback) 3. OCR (parallel multi-engine) 4. DrawIO XML generation 5. SVG preview rendering 6. Metadata collection """ import logging import ...
eren23/non_linear_ai_chat
diagram-converter/main.py
py
12,628
ef225e7db4a80452d4c0fbcecc05269fc17ea36dfbb56a294409f640a581701d
""" Diagram Converter Microservice FastAPI service that converts static diagram images into editable DrawIO files. Pipeline: SAM3 segmentation + parallel OCR -> DrawIO XML generation. Follows the same patterns as python-backend/main.py for auth, health checks, etc. """ import logging import os import sys import time...
eren23/non_linear_ai_chat
diagram-converter/segmentation.py
py
17,688
b33f0127ce206c1e40363b8d98cecca5dec1a93168c2463a77f75fd76e6b558d
""" Diagram Segmentation Engine Wraps SAM3 (segment-anything-2) for diagram element detection. Falls back to OpenCV contour-based segmentation when SAM is unavailable. """ import hashlib import logging import time from dataclasses import dataclass, field from enum import Enum from typing import List, Optional, Tuple ...
eren23/non_linear_ai_chat
diagram-converter/tests/test_drawio_builder.py
py
5,535
923074398e52df57ccb2a308c29618a601b070b15972fbef72e8905b22d07f41
""" Tests for DrawIO XML builder. Covers shape cell creation, connector detection, and text assignment. """ import pytest from lxml import etree from drawio_builder import DrawIOBuilder, generate_svg_from_drawio from ocr_engine import TextBlock from segmentation import ElementLabel, SegmentedElement def _make_elem...
eren23/non_linear_ai_chat
diagram-converter/tests/test_pipeline.py
py
5,059
f0ab98dd51ed8f5dd340dbe216fc9040533473d8a26851b2db714cea2c63a950
""" Tests for the diagram conversion pipeline. Covers basic image conversion, OpenCV fallback, empty images, and XML validity. """ import asyncio import io from unittest.mock import patch import pytest from lxml import etree from PIL import Image def _make_image(width: int = 200, height: int = 200, color: str = "w...
eren23/non_linear_ai_chat
backend/scripts/migrateUserTiers.ts
ts
3,106
7c20a36cfa5c04b51e0e9788285e62e1076a64a0e0fc8dc77965ffb5fef176fd
/** * Migration script to set all existing users to 'pro' tier. * Run with: npx tsx scripts/migrateUserTiers.ts * * You can hardcode the MongoDB URI below if needed. */ import { MongoClient } from 'mongodb'; // HARDCODE YOUR MONGODB URI HERE IF NEEDED // Example: 'mongodb://admin:password@localhost:27017/nonlin...
eren23/non_linear_ai_chat
backend/scripts/exportPrompts.ts
ts
3,180
7fac1fa86821e89210a481f45ce94f9596cd8816c00f6bc61d3ecbbab0139ca6
/** * Export prompts to markdown for AI context. * Run with: npm run export:prompts */ // Load environment variables FIRST import dotenv from 'dotenv'; import path from 'path'; dotenv.config({ path: path.resolve(__dirname, '../.env') }); import { connectDatabase, closeDatabase } from '../src/services/database'; im...
eren23/non_linear_ai_chat
backend/scripts/migrateMemoriesPersistence.ts
ts
4,520
5fbbdf54975f83afa279865fdb87a7239fc128c3b4953c27efe67982ebc921ec
/** * Migration script: Add persistence levels and visibility to existing memories * * Run with: npx ts-node backend/scripts/migrateMemoriesPersistence.ts */ import dotenv from 'dotenv'; import path from 'path'; // Load environment variables dotenv.config({ path: path.resolve(__dirname, '../.env') }); import { ...
eren23/non_linear_ai_chat
backend/scripts/seedPrompts.ts
ts
10,969
93c692962a0f8a6139482329068522753132e4e4b9de575dde0e951a15f759ae
/** * Seed system prompts into database. * Run with: npm run seed:prompts */ // Load environment variables FIRST import dotenv from 'dotenv'; import path from 'path'; dotenv.config({ path: path.resolve(__dirname, '../.env') }); import { connectDatabase, closeDatabase, getPromptsCollection } from '../src/services/d...
eren23/non_linear_ai_chat
backend/scripts/add-allowed-email.ts
ts
2,428
983ebad3347fdb2d8125f6d82fac602137db33c78b774ecfb3368af0bb7cb523
/** * Script to add email(s) to the allowed list. * * You can hardcode emails in the `HARDCODED_EMAILS` array below, or provide an email address via command line argument: * npx tsx scripts/add-allowed-email.ts <email> */ import dotenv from 'dotenv'; import path from 'path'; import { MongoClient } from 'mongod...
eren23/non_linear_ai_chat
backend/scripts/verify-graph-config.ts
ts
3,027
a3134f69c0e2c535e84155991e692a736eccef66957de1e5fd12b438b9fc8d40
import { getMemoryGraph, createMemory, getMemoriesCollection } from '../src/services/memories'; import { ObjectId } from 'mongodb'; import { connectDatabase, closeDatabase } from '../src/services/database'; import { randomUUID } from 'crypto'; const TEST_USER_ID = new ObjectId().toString(); async function cleanData(...
eren23/non_linear_ai_chat
backend/scripts/seedTestData.ts
ts
3,022
b5073131626724efb9e3765e82f9d1a716ca0d54d6367d20a29148fc3d6f041a
import { MongoClient, ObjectId } from 'mongodb'; const mongoUri = process.env.MONGO_URI || process.env.MONGODB_URI || 'mongodb://localhost:27017/nonlinear'; const userId = new ObjectId('000000000000000000000001'); const flowId = new ObjectId('000000000000000000000002'); const sharedToken = '0123456789abcdef0123...
eren23/non_linear_ai_chat
backend/scripts/telegram-e2e-auth.ts
ts
1,741
141851dd77f8877a8fab3b6bc0d221e34d9c93efdd475be96c1d9fef7c8a49c9
#!/usr/bin/env tsx /** * One-time auth script for Telegram E2E tests. * * Usage: * npx tsx backend/scripts/telegram-e2e-auth.ts * * Prerequisites: * 1. Go to https://my.telegram.org/apps and create an application * 2. Note your API ID and API Hash * * This script will prompt you to log in with your phon...
eren23/non_linear_ai_chat
backend/scripts/fix-mcp-token-scopes.ts
ts
2,873
14e9d2af263e8d3fd29c97a6f38a607425edd1aab94c32204a9c28308acaaff7
/** * Script to add `mcp:write` scope to existing API tokens that only have `mcp:read`. * * The MCP canvas write tools (canvas_create_node, canvas_edit_node, etc.) require * `mcp:write` scope, but tokens created with default settings only get `mcp:read`. * * Usage: * npx tsx scripts/fix-mcp-token-scopes.ts ...
eren23/non_linear_ai_chat
backend/scripts/backfillFlowMetadata.ts
ts
2,978
a114d5b5750637bd6cebaf7472a0573ae698741cfea0072014e04cf3c711be3a
/** * Migration script: Backfill flow metadata for existing flows * * Run with: npx ts-node backend/scripts/backfillFlowMetadata.ts */ import dotenv from 'dotenv'; import path from 'path'; // Load environment variables dotenv.config({ path: path.resolve(__dirname, '../.env') }); import { connectDatabase, getFlo...
eren23/non_linear_ai_chat
backend/scripts/populateModels.ts
ts
2,040
bdc271a5c63104e32b010b95e6bcd65589656c58bbfb6af3ca6c76f56bb3d1c6
/** * Script to populate models from config into the database. * Run with: npx tsx scripts/populateModels.ts * * You can hardcode the MongoDB URI below if needed. */ import { MongoClient } from 'mongodb'; import { upsertModelConfig } from '../src/services/models'; import { MODELS } from '../src/config/models'; ...
eren23/non_linear_ai_chat
backend/scripts/reembed-migration.ts
ts
13,099
aea3509a921d637533c35b28a196966b437733ce05c7b95809b608f0856438f4
/** * Re-embed migration script: gemini-embedding-001 (3072 dim) β†’ qwen3-embedding-8b (4096 dim). * * Blue/green strategy: walks every existing Qdrant collection (v1, unsuffixed) in-place, * creates a parallel `<name>_v2` collection at 4096 dims, scrolls all points, re-embeds * each point's text via `generateEmbed...
eren23/non_linear_ai_chat
backend/src/app.ts
ts
16,125
7fffeaa0c6f259fe89b4e58696f2a3ccb804717364d66a1cdab6d0e51a593530
/** * Express Application Setup * * This file configures the Express app with middleware, session handling, * and Passport authentication. Routes are mounted in routes/index.ts. */ import express from 'express'; import cors from 'cors'; import helmet from 'helmet'; import compression from 'compression'; import s...
eren23/non_linear_ai_chat
backend/src/index.ts
ts
7,464
3a12e32988412c8ce273234e1c1550a735043f952aea143b11b03cf56351c24f
/** * Non-Linear AI Explorer - Node.js Backend * * Main entrypoint that bootstraps and starts the server. * * Architecture: * - app.ts: Express application configuration * - server.ts: HTTP server lifecycle management * - bootstrap/: Application initialization * - routes/: API route handlers * - services/: Bu...
eren23/non_linear_ai_chat
backend/src/instrumentation.ts
ts
3,876
3ee0b14d71b56f615cb5e3300e837166ad2a28630bf56e0d507647b090b1d384
/** * OpenTelemetry Instrumentation * * Call `initOtel()` at the very top of your entry point (before Express, etc.) * to set up auto-instrumentation. * * Controlled by environment variables: * ENABLE_OTEL=true β€” Master switch (disabled by default) * OTEL_EXPORTER_OTLP_ENDPOINT β€” OTLP endpoin...
eren23/non_linear_ai_chat
backend/src/server.ts
ts
7,651
d7f575bf5571989bfc7571b2789a1674e68467ba62a3e2a91f75cd1b96be74d8
/** * HTTP Server Setup and Lifecycle Management * * This file handles server creation, Socket.io initialization, * and graceful shutdown procedures. */ import { createServer, Server } from 'http'; import type { Application } from 'express'; import { createLogger } from './services/logger.js'; import { initialize...
eren23/non_linear_ai_chat
backend/src/middleware/validation.ts
ts
2,585
c5f2b3bdf3bfb2eacf8c9d34cf55daf2cd6a68ca336828e97a9e1e4341951f75
/** * Request validation middleware using Zod. */ import { Request, Response, NextFunction } from 'express'; import { z, ZodSchema } from 'zod'; /** * Validation error response format. */ export interface ValidationError { error: string; details: Array<{ field: string; message: string; }>; } /** *...
eren23/non_linear_ai_chat
backend/src/middleware/videoLimits.ts
ts
2,448
ce357c54749cee30863c07a4548c72e22752e71c9d855281ab5eccf4aa3754e9
/** * Video generation limits middleware. * Enforces tier-based limits before video generation. */ import { Request, Response, NextFunction } from 'express'; import { getVideoTierLimits } from '../config/pricing'; import { getUserVideoGenerationThisMonth } from '../services/tokenTracking'; import { VideoTierLimits ...
eren23/non_linear_ai_chat
backend/src/middleware/performanceMetrics.ts
ts
11,846
12788dc0a21c02880d8580ee73d71701486c41168a0fe4426f1ebc1782bc41bb
/** * Performance Metrics Middleware * * Express middleware for capturing API performance metrics. * Extends the graphMetrics pattern to all critical endpoints. * * Tracks: * - Per-endpoint latency (p50/p95/p99) * - Error rates * - Request throughput * - Streaming metrics (TTFT, tokens/s) */ import { Reques...
eren23/non_linear_ai_chat
backend/src/middleware/alwaysOnAccess.ts
ts
667
aa3bd53e052afe1b8ae7edabd5f68a819ec29a59b860fbf08fe9b6f8683ebf1f
/** * Admin-only gate for always-on capture routes (extension signals, audio capture, etc.). * Export name is historical; enforcement is `user.isAdmin`, not tier policy. */ import { Request, Response, NextFunction } from 'express'; /** * Require `req.user.isAdmin` for always-on endpoints. */ export function requ...
eren23/non_linear_ai_chat
backend/src/middleware/errorHandler.ts
ts
6,666
044974dc8465bed0c74fe39626fd18a60c2ce125255643f1a82a094cd4967f2d
/** * Centralized error handling middleware. */ import { Request, Response, NextFunction } from 'express'; import { logError } from '../services/errorLogger'; import { isSentryEnabled } from '../services/sentry'; import { createLogger } from '../services/logger.js'; /** * Standard error response format. */ export...
eren23/non_linear_ai_chat
backend/src/middleware/concurrentLimiter.ts
ts
1,813
04bdccca98f784b4a13792a69616371f2baaa2c170d7e68d8ddc7697707af9b0
/** * Shared per-user concurrent LLM generation limiter. * * Prevents a single user from opening too many simultaneous LLM calls * (generation, parallel-generate, notes AI, image gen) across all endpoints. */ import { Request, Response, NextFunction } from 'express'; const MAX_CONCURRENT_GENERATIONS_PER_USER = 5...
eren23/non_linear_ai_chat
backend/src/middleware/mcpAudit.ts
ts
4,112
c281720d861005a4c235d29ce804278e217687ee9c76f27edd2db644cc764b0a
/** * MCP Audit Logging Middleware * * Logs all MCP API requests to MongoDB for security monitoring and incident investigation. * Stores: timestamp, userId, token prefix, endpoint, method, resource IDs, status, IP. * Collection uses a 90-day TTL index for automatic cleanup. */ import { Request, Response, NextFun...
eren23/non_linear_ai_chat
backend/src/middleware/actorContext.ts
ts
6,609
5fde72c9ce43aa2c148c01a367e5ebfb107a6ae8220a239b93b2466e7a73cdf5
/** * Actor Context β€” identifies WHO is performing a write so service-layer code * can decide whether to snapshot prior content into `content_revisions`. * * The source is derived from auth/path signals at the HTTP boundary, then * propagated via AsyncLocalStorage so deep service calls (e.g. updateNote, * updateM...
eren23/non_linear_ai_chat
backend/src/middleware/priority.ts
ts
5,967
d1ecb37e57eb96a1c014029b9b4f3afff6013f2578f519d984e52c97a77dd6c1
/** * Request Priority Middleware * * Assigns priority levels to routes and implements adaptive throttling * to ensure critical APIs (generation, chat) are never blocked by * non-critical requests (image serving, file downloads). */ import { Request, Response, NextFunction } from 'express'; import { createLogg...
eren23/non_linear_ai_chat
backend/src/middleware/rateLimit.ts
ts
11,196
9992b38e66b01dfcf7a82cd70e07c5c194ade78740ac44c7e70f7aba0eff3c81
/** * Rate limiting middleware for IP and account-based protection. * Prevents DDoS and abuse while keeping it smooth for legitimate users. * * Uses Redis for distributed rate limiting when available. * Falls back to in-memory with conservative limits when Redis is unavailable. */ import { Request, Response, Nex...
eren23/non_linear_ai_chat
backend/src/middleware/featureGuard.ts
ts
1,227
a3597302c5f1b8b50b34de28edd3b8cadabd70bc9ec487a272e4b9491d5c6f29
/** * Feature guard middleware. * Returns 503 Service Unavailable when a feature is disabled. */ import { Request, Response, NextFunction } from 'express'; import { FeatureName, isFeatureEnabled, getFeatureDisplayName, } from '../services/featureFlags'; /** * Create middleware that guards a route based on a...
eren23/non_linear_ai_chat
backend/src/middleware/database.ts
ts
5,989
0edcd7b8da17fb167bea420408b4d2bb25a52ecd5772b1ff9089c952b7c2490b
/** * Database connection middleware. * Ensures database is connected before processing requests. * Uses promise-based waiting to guarantee no race conditions. */ import { Request, Response, NextFunction } from 'express'; import { isDatabaseHealthy, isDatabaseConnected, isConnectionFullyReady, waitForConne...
eren23/non_linear_ai_chat
backend/src/middleware/tokenAuth.ts
ts
10,876
bb2c4a531f9d443a4b23fccb09ed8216b88ad38cec878623841b155b1fdfe222
/** * API Token Authentication middleware. * For use with MCP and external integrations. */ import { Request, Response, NextFunction } from 'express'; import { validateApiToken, getUserTier } from '../services/users'; import { logError } from '../services/errorLogger'; import { checkAndIncrementRateLimit } from '.....
eren23/non_linear_ai_chat
backend/src/middleware/csrf.ts
ts
6,329
a0b6c3d0fb5b3aa307fc1d2eca71f210782c758f10038767bf3d3b5e3749a286
/** * CSRF Protection Middleware * * Implements the Double Submit Cookie pattern for CSRF protection. * This approach: * 1. Sets a random token in a cookie * 2. Requires the token to be sent in a header (X-CSRF-Token) * 3. Validates that cookie token matches header token * * This works because: * - Attacker s...
eren23/non_linear_ai_chat
backend/src/middleware/asyncHandler.ts
ts
5,957
1723aabde7fd9b94cc6a7c8410cf9b1a5d7a15c7eccfba2bd4408805b942e545
/** * Async handler wrapper to eliminate repetitive try/catch blocks in routes. * Automatically catches errors and passes them to Express error handling middleware. * * @example * // BEFORE (repeated ~500 times): * router.get('/resource', async (req, res) => { * try { * const data = await getData(); * ...
eren23/non_linear_ai_chat
backend/src/middleware/turnstile.ts
ts
2,781
815f5184e277aa33d2bffdd37cc386a06309824ae892bb194e00a61efed80b3a
/** * Cloudflare Turnstile CAPTCHA verification middleware. * * When TURNSTILE_SECRET_KEY is set, validates the `turnstileToken` field * in the request body against the Cloudflare siteverify endpoint. * When not set, passes through (graceful degradation for local dev). */ import { Request, Response, NextFunction...
eren23/non_linear_ai_chat
backend/src/middleware/auth.ts
ts
2,294
386fa03e21db440c2e173891b108fe00dc6f30740313e89f93d61244ff43492e
/** * Authentication middleware. */ import { Request, Response, NextFunction } from 'express'; import { createLogger } from '../services/logger.js'; const log = createLogger('middleware.auth'); // Extend Express types to include user and passport session declare global { namespace Express { interface User { ...
eren23/non_linear_ai_chat
backend/src/middleware/__tests__/featureGuard.test.ts
ts
14,331
9295ecdd676db2250ac4f4659be51a403593869b72d435e4fa1ae47f78cd2e8a
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { Request, Response, NextFunction } from 'express'; import { requireFeature, checkFeature } from '../featureGuard'; // Mock the featureFlags service vi.mock('../../services/featureFlags', () => ({ isFeatureEnabled: vi.fn(), getFeature...
eren23/non_linear_ai_chat
backend/src/middleware/__tests__/compression.test.ts
ts
5,765
b4d34139fff1b155c7eea4ab68ed11ff652c03d4a588b426cf360199540bc1d5
/** * Unit tests for the compression middleware configuration. * * These tests replicate the compression setup from app.ts in a minimal * Express application and verify: * - JSON responses larger than the 1KB threshold are compressed * - Responses smaller than 1KB are NOT compressed * - SSE (text/event-stream...
eren23/non_linear_ai_chat
backend/src/middleware/__tests__/cors.test.ts
ts
9,640
3a2a6b7d87c977886ca300826c476c573b021f990ad9c9e7aaa36054a42cfb0d
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import express from 'express'; import cors from 'cors'; import request from 'supertest'; import { buildAllowedOrigins, createOriginValidator } from '../../config/cors'; /** * CORS Configuration Tests * * Uses the shared buildAllowedOrigins() ...
eren23/non_linear_ai_chat
backend/src/middleware/__tests__/alwaysOnAccess.test.ts
ts
4,488
42334dd0a78015e7cb85f4047b02176ddf2dbffe60d35d7f4aec36d3efda9602
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { Request, Response, NextFunction } from 'express'; import { requireAlwaysOnAccess } from '../alwaysOnAccess'; function createMockRequest(user?: any): Partial<Request> { return { user }; } function createMockResponse(): Partial<Response> & { sta...