@vemdev/mcp-server 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +128 -7
- package/dist/index.js +8 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../../../packages/core/dist/agent.js","../../../packages/schemas/dist/index.js","../../../packages/core/dist/fs.js","../../../packages/core/dist/git.js","../../../packages/core/dist/logs.js","../../../packages/core/dist/tasks.js","../../../packages/core/dist/sharded-fs.js","../../../packages/core/dist/agent-sessions.js","../../../packages/core/dist/config.js","../../../packages/core/dist/diff.js","../../../packages/core/dist/doctor.js","../../../packages/core/dist/env.js","../../../packages/core/dist/github-private-key.js","../../../packages/core/dist/logger.js","../../../packages/core/dist/secrets.js","../../../packages/core/dist/sync.js","../../../packages/core/dist/usage-metrics.js","../../../packages/core/dist/webhook.js"],"sourcesContent":["#!/usr/bin/env node\nimport { execSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { readdir, readFile, readlink, writeFile } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n\tCallToolRequestSchema,\n\tListToolsRequestSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport {\n\tapplyVemUpdate,\n\tCHANGELOG_DIR,\n\tConfigService,\n\tCURRENT_STATE_FILE,\n\tDECISIONS_DIR,\n\tcomputeSessionStats,\n\tgetRepoRoot,\n\tgetVemDir,\n\tlistAllAgentSessions,\n\tScalableLogService,\n\tSyncService,\n\tTaskService,\n\tUsageMetricsService,\n} from \"@vem/core\";\n\nconst server = new Server(\n\t{\n\t\tname: \"vem-mcp\",\n\t\tversion: \"0.1.0\",\n\t},\n\t{\n\t\tcapabilities: {\n\t\t\ttools: {},\n\t\t},\n\t},\n);\n\nconst taskService = new TaskService();\nconst configService = new ConfigService();\nconst syncService = new SyncService();\nconst metricsService = new UsageMetricsService();\n\nconst API_URL = process.env.VEM_API_URL || \"http://localhost:3002\";\n\nasync function trackHeartbeat(toolName: string, taskId?: string) {\n\ttry {\n\t\tconst apiKey = await configService.getApiKey();\n\t\tif (!apiKey) return;\n\n\t\tconst projectId = await configService.getProjectId();\n\t\tconst agentName = process.env.VEM_AGENT_NAME || \"mcp-agent\";\n\n\t\tawait metricsService.syncToCloud({\n\t\t\tapiUrl: API_URL,\n\t\t\tapiKey,\n\t\t\tprojectId,\n\t\t\theaders: await buildDeviceHeaders(configService),\n\t\t\tforce: true,\n\t\t\tevent: {\n\t\t\t\tfeatureFlag: \"agent_heartbeat\",\n\t\t\t\tmetadata: {\n\t\t\t\t\tagentName,\n\t\t\t\t\ttaskId,\n\t\t\t\t\tcommand: `mcp:${toolName}`,\n\t\t\t\t},\n\t\t\t},\n\t\t});\n\t} catch {\n\t\t// Silently fail\n\t}\n}\n\n// --- Git helper functions (matching CLI patterns) ---\n\nfunction getGitHash(): string | null {\n\ttry {\n\t\treturn execSync(\"git rev-parse HEAD\").toString().trim() || null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction getGitRemote(): string | null {\n\ttry {\n\t\treturn execSync(\"git remote get-url origin\").toString().trim() || null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction getCommits(limit = 50) {\n\ttry {\n\t\tconst output = execSync(\n\t\t\t`git log -n ${limit} --pretty=format:\"%H|%an|%cI|%s\"`,\n\t\t).toString();\n\t\treturn output\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => {\n\t\t\t\tconst [hash, author, date, ...msgParts] = line.split(\"|\");\n\t\t\t\treturn {\n\t\t\t\t\thash,\n\t\t\t\t\tauthor_name: author,\n\t\t\t\t\tcommitted_at: date,\n\t\t\t\t\tmessage: msgParts.join(\"|\"),\n\t\t\t\t};\n\t\t\t})\n\t\t\t.filter((c) => c.hash && c.message);\n\t} catch {\n\t\treturn [];\n\t}\n}\n\nasync function isVemDirty(): Promise<boolean> {\n\ttry {\n\t\tconst root = await getRepoRoot();\n\t\tconst status = execSync(\"git status --porcelain .vem\", { cwd: root })\n\t\t\t.toString()\n\t\t\t.trim();\n\t\treturn status.length > 0;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nasync function computeVemHash(): Promise<string | null> {\n\ttry {\n\t\tconst vemDir = await getVemDir();\n\t\tconst hash = createHash(\"sha256\");\n\n\t\tconst walk = async (currentDir: string) => {\n\t\t\tconst entries = await readdir(currentDir, { withFileTypes: true });\n\t\t\tentries.sort((a, b) => a.name.localeCompare(b.name));\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (entry.name === \"queue\") continue;\n\t\t\t\tconst fullPath = join(currentDir, entry.name);\n\t\t\t\tconst relPath = relative(vemDir, fullPath).split(\"\\\\\").join(\"/\");\n\t\t\t\tif (\n\t\t\t\t\trelPath === \"queue\" ||\n\t\t\t\t\trelPath.startsWith(\"queue/\") ||\n\t\t\t\t\trelPath === \"config.json\" ||\n\t\t\t\t\trelPath === \"current_context.md\" ||\n\t\t\t\t\trelPath === \"task_context.md\"\n\t\t\t\t) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (entry.isDirectory()) {\n\t\t\t\t\thash.update(`dir:${relPath}\\0`);\n\t\t\t\t\tawait walk(fullPath);\n\t\t\t\t} else if (entry.isFile()) {\n\t\t\t\t\thash.update(`file:${relPath}\\0`);\n\t\t\t\t\tconst data = await readFile(fullPath);\n\t\t\t\t\thash.update(data);\n\t\t\t\t} else if (entry.isSymbolicLink()) {\n\t\t\t\t\tconst target = await readlink(fullPath);\n\t\t\t\t\thash.update(`link:${relPath}\\0${target}\\0`);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tawait walk(vemDir);\n\t\treturn hash.digest(\"hex\");\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction normalizeForSnapshotHash(value: unknown): unknown {\n\tif (typeof value === \"string\") return value.normalize(\"NFC\");\n\tif (Array.isArray(value))\n\t\treturn value.map((entry) => normalizeForSnapshotHash(entry));\n\tif (value && typeof value === \"object\") {\n\t\tconst record = value as Record<string, unknown>;\n\t\tconst normalized: Record<string, unknown> = {};\n\t\tfor (const key of Object.keys(record).sort((a, b) => a.localeCompare(b))) {\n\t\t\tconst next = normalizeForSnapshotHash(record[key]);\n\t\t\tif (next !== undefined) normalized[key] = next;\n\t\t}\n\t\treturn normalized;\n\t}\n\tif (typeof value === \"number\" && !Number.isFinite(value)) return null;\n\treturn value;\n}\n\nfunction computeSnapshotHashFromPayload(snapshot: any): string {\n\tconst sortedTasks = Array.isArray(snapshot?.tasks?.tasks)\n\t\t? [...snapshot.tasks.tasks].sort((a: any, b: any) =>\n\t\t\t\tString(a?.id || \"\").localeCompare(String(b?.id || \"\")),\n\t\t\t)\n\t\t: [];\n\tconst canonical = normalizeForSnapshotHash({\n\t\ttasks: { tasks: sortedTasks },\n\t\tcontext: snapshot?.context || \"\",\n\t\tdecisions: snapshot?.decisions || \"\",\n\t\tchangelog: snapshot?.changelog || \"\",\n\t\tcurrent_state: snapshot?.current_state || \"\",\n\t});\n\treturn createHash(\"sha256\")\n\t\t.update(JSON.stringify(canonical), \"utf8\")\n\t\t.digest(\"hex\");\n}\n\nasync function buildDeviceHeaders(cs: ConfigService) {\n\tconst { deviceId, deviceName } = await cs.getOrCreateDeviceId();\n\tconst projectOrgId = await cs.getProjectOrgId();\n\treturn {\n\t\t\"X-Vem-Device-Id\": deviceId,\n\t\t\"X-Vem-Device-Name\": deviceName,\n\t\t\"X-Vem-Client\": \"mcp-server\",\n\t\t...(projectOrgId ? { \"X-Org-Id\": projectOrgId } : {}),\n\t};\n}\n\nserver.setRequestHandler(ListToolsRequestSchema, async () => {\n\treturn {\n\t\ttools: [\n\t\t\t{\n\t\t\t\tname: \"get_active_tasks\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Get list of VEM tasks from project memory. Use this to know what to do. Defaults to active tasks only.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tstatus: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tenum: [\"todo\", \"in-progress\", \"done\", \"all\"],\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Filter tasks by status. Default is to exclude done tasks.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"get_task_details\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Get detailed information about a specific task by its ID.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: { type: \"string\", description: \"The TASK-XXX id\" },\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"id\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"add_task\",\n\t\t\t\tdescription: \"Add a new task to VEM memory.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\ttitle: { type: \"string\" },\n\t\t\t\t\t\tdescription: { type: \"string\" },\n\t\t\t\t\t\tpriority: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tenum: [\"low\", \"medium\", \"high\", \"critical\"],\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttype: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tenum: [\"feature\", \"bug\", \"chore\"],\n\t\t\t\t\t\t},\n\t\t\t\t\t\tparent_id: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Optional parent task ID\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tvalidation_steps: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: { type: \"string\" },\n\t\t\t\t\t\t\tdescription: \"List of commands or steps to validate completion\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\treasoning: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Reasoning for creating this task.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"title\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"complete_task\",\n\t\t\t\tdescription: \"Mark a task as done in VEM memory.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: { type: \"string\", description: \"The TASK-XXX id\" },\n\t\t\t\t\t\tevidence: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Proof of completion (file path, test command, etc)\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\treasoning: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Why is this task considered done? Explain your reasoning.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"id\", \"evidence\", \"reasoning\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"start_task\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Mark a task as in-progress and attach the current agent session to it. Call this when you start working on a task. Returns the full task object so you can get its context.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The TASK-XXX id to start\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsession_id: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The current agent session ID\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsource: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tenum: [\"copilot\", \"claude\", \"gemini\"],\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Which AI tool is running (copilot | claude | gemini)\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsession_summary: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Optional brief summary of what this session intends to do\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"id\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"get_context\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Read the project's CONTEXT.md and CURRENT_STATE.md. Always call this at the start of a session to load project context.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"list_decisions\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"List architectural decisions recorded in VEM memory. Read these before making significant design choices to avoid conflicts.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tlimit: {\n\t\t\t\t\t\t\ttype: \"number\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Number of recent decisions to return (default: 20, max: 50)\",\n\t\t\t\t\t\t\tdefault: 20,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"update_current_state\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Update CURRENT_STATE.md with a summary of latest progress and next steps. Call this after completing meaningful work.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tcontent: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"The new content for CURRENT_STATE.md (replaces existing content)\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"content\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"search_memory\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Semantic search over project memory (tasks, context, decisions).\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tquery: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"The search query (e.g. 'auth tasks', 'database schema')\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"query\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"ask_question\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Ask a natural language question about the project codebase and memory (commits, diffs, tasks).\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tquestion: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"The question to ask (e.g. 'How does authentication work?')\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tpath: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Optional file path to limit the scope of the search\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"question\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"update_task\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Update a task's status, priority, or other fields. Use this to start working on a task, block it, or update its priority.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The TASK-XXX id\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tenum: [\"todo\", \"in-progress\", \"blocked\"],\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"New status for the task. Use 'in-progress' to start working, 'blocked' to mark as blocked, 'todo' to unblock.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tpriority: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tenum: [\"low\", \"medium\", \"high\", \"critical\"],\n\t\t\t\t\t\t\tdescription: \"New priority for the task.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\treasoning: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Explanation for the update. Required when blocking a task.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tblocked_by: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: { type: \"string\" },\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Task IDs that are blocking this task (when setting status to blocked).\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tvalidation_steps: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: { type: \"string\" },\n\t\t\t\t\t\t\tdescription: \"New list of validation steps (replaces existing)\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"id\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"add_decision\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Record an architectural decision in VEM memory. Use this when making significant technical choices (e.g., choosing libraries, changing architecture, setting patterns).\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\ttitle: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Short decision title (e.g., 'Use Zod for validation')\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Why this decision was needed - the problem or situation\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdecision: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"What was decided and key rationale\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\trelated_tasks: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: { type: \"string\" },\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Optional TASK-XXX references that motivated or implement this decision\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"title\", \"context\", \"decision\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"get_changelog\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Get recent changelog entries from VEM memory. Use this to understand what work has been done recently.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tlimit: {\n\t\t\t\t\t\t\ttype: \"number\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Number of recent entries to return (default: 10, max: 50)\",\n\t\t\t\t\t\t\tdefault: 10,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"delete_task\",\n\t\t\t\tdescription: \"Soft delete a task from VEM memory.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: { type: \"string\", description: \"The TASK-XXX id\" },\n\t\t\t\t\t\treasoning: { type: \"string\", description: \"Reason for deletion\" },\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"id\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"apply_vem_update\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Apply a complete vem_update block containing current_state, context, changelog_append, decisions_append, and task updates.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tcurrent_state: { type: \"string\" },\n\t\t\t\t\t\tcontext: { type: \"string\" },\n\t\t\t\t\t\tchangelog_append: {\n\t\t\t\t\t\t\toneOf: [\n\t\t\t\t\t\t\t\t{ type: \"string\" },\n\t\t\t\t\t\t\t\t{ type: \"array\", items: { type: \"string\" } },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdecisions_append: {\n\t\t\t\t\t\t\toneOf: [\n\t\t\t\t\t\t\t\t{ type: \"string\" },\n\t\t\t\t\t\t\t\t{ type: \"array\", items: { type: \"string\" } },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttasks: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: {\n\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\tid: { type: \"string\" },\n\t\t\t\t\t\t\t\t\tstatus: { type: \"string\" },\n\t\t\t\t\t\t\t\t\treasoning: { type: \"string\" },\n\t\t\t\t\t\t\t\t\tpriority: { type: \"string\" },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\trequired: [\"id\"],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"sync_push\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Push local VEM snapshot to the cloud. Syncs tasks, context, decisions, and changelog to the remote project.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tforce: {\n\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\tdescription: \"Push even if no changes detected since last push.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdry_run: {\n\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Preview what would be pushed without actually pushing.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"sync_pull\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Pull the latest VEM snapshot from the cloud. Updates local tasks, context, decisions, and changelog.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tforce: {\n\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\tdescription: \"Overwrite local changes without warning.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"get_task_context\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Read a task's working context and summary. Use this to retrieve scratchpad notes for a specific task.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The TASK-XXX id\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"id\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"update_task_context\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Set, append to, or clear a task's working context. Use this to maintain scratchpad notes across sessions.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The TASK-XXX id\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\toperation: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tenum: [\"set\", \"append\", \"clear\"],\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"'set' replaces context, 'append' adds to it, 'clear' removes it.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttext: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"The text content. Required for 'set' and 'append' operations.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"id\", \"operation\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"get_subtasks\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Get a parent task and all its subtasks. Use this to view the task hierarchy.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tparent_id: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The parent TASK-XXX id\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"parent_id\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"list_agent_sessions\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"List recent agent sessions for this repository from Copilot CLI, Claude CLI, and Gemini CLI. Call this at the start of a session to understand what previous sessions worked on and avoid duplicating effort.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tlimit: {\n\t\t\t\t\t\t\ttype: \"number\",\n\t\t\t\t\t\t\tdescription: \"Maximum number of sessions to return (default: 10)\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbranch: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Filter sessions by branch name\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsources: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: { type: \"string\", enum: [\"copilot\", \"claude\", \"gemini\"] },\n\t\t\t\t\t\t\tdescription: \"Which tools to include (default: all three)\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"save_session_stats\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Save statistics for an agent session onto its task. Call this when finishing a task to record session duration, turns, tool calls, and model usage. Stats are computed from the agent's session files.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\ttask_id: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The TASK-XXX id to attach stats to\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsession_id: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The agent session ID to compute stats for\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsource: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tenum: [\"copilot\", \"claude\", \"gemini\"],\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Which AI tool the session belongs to (default: copilot)\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"task_id\", \"session_id\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t};\n});\n\nserver.setRequestHandler(CallToolRequestSchema, async (request) => {\n\tconst { name, arguments: args } = request.params;\n\n\t// Track heartbeat for every tool call\n\tconst taskId =\n\t\t(args?.id as string) ||\n\t\t(args?.taskId as string) ||\n\t\tprocess.env.VEM_ACTIVE_TASK;\n\tvoid trackHeartbeat(name, taskId);\n\n\tif (name === \"get_active_tasks\") {\n\t\tconst tasks = await taskService.getTasks();\n\t\tconst status = args?.status as string | undefined;\n\n\t\tlet filtered = tasks;\n\t\tif (status === \"all\") {\n\t\t\t// return all\n\t\t} else if (status === \"done\") {\n\t\t\tfiltered = tasks.filter((t) => t.status === \"done\");\n\t\t} else if (status === \"todo\") {\n\t\t\tfiltered = tasks.filter((t) => t.status === \"todo\");\n\t\t} else if (status === \"in-progress\") {\n\t\t\tfiltered = tasks.filter((t) => t.status === \"in-progress\");\n\t\t} else {\n\t\t\t// default: active only (not done)\n\t\t\tfiltered = tasks.filter((t) => t.status !== \"done\");\n\t\t}\n\n\t\t// Annotate tasks that have session history with a handoff hint\n\t\tconst annotated = filtered.map((t) => {\n\t\t\tconst sessions = (t.sessions as any[]) || [];\n\t\t\tif (sessions.length === 0) return t;\n\t\t\tconst last = sessions[sessions.length - 1];\n\t\t\tconst hint = last.summary\n\t\t\t\t? `Last worked by ${last.source} on ${last.started_at.slice(0, 10)}: ${last.summary}`\n\t\t\t\t: `Last worked by ${last.source} on ${last.started_at.slice(0, 10)}`;\n\t\t\treturn { ...t, _last_session_hint: hint };\n\t\t});\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: JSON.stringify(annotated, null, 2),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"get_task_details\") {\n\t\tconst id = args?.id as string;\n\t\tif (!id) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: \"Task ID is required.\" }],\n\t\t\t};\n\t\t}\n\t\tconst task = await taskService.getTask(id);\n\t\tif (!task) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: `Task ${id} not found.` }],\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: JSON.stringify(task, null, 2) }],\n\t\t};\n\t}\n\n\tif (name === \"add_task\") {\n\t\tconst title = args?.title as string;\n\t\tconst description = (args?.description as string) || undefined;\n\t\tconst priority = (args?.priority as any) || \"medium\";\n\t\tconst reasoning = (args?.reasoning as string) || undefined;\n\t\tconst type = (args?.type as any) || undefined;\n\t\tconst parentId = (args?.parent_id as string) || undefined;\n\t\tconst validationSteps = (args?.validation_steps as string[]) || undefined;\n\n\t\tconst task = await taskService.addTask(\n\t\t\ttitle,\n\t\t\tdescription,\n\t\t\tpriority,\n\t\t\treasoning,\n\t\t\t{\n\t\t\t\ttype,\n\t\t\t\tparent_id: parentId,\n\t\t\t\tvalidation_steps: validationSteps,\n\t\t\t},\n\t\t);\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{ type: \"text\", text: `Task Added: ${task.id} (${task.title})` },\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"complete_task\") {\n\t\tconst id = args?.id as string;\n\t\tconst evidence = String(args?.evidence || \"\").trim();\n\n\t\tconst reasoning = String(args?.reasoning || \"\").trim();\n\t\tif (!evidence) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Evidence is required to complete a task.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\t\tif (!reasoning) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Reasoning is required to complete a task.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\n\t\tawait taskService.updateTask(id, {\n\t\t\tstatus: \"done\",\n\t\t\tevidence: [evidence],\n\t\t\treasoning,\n\t\t});\n\t\tconst vemDir = await getVemDir();\n\t\tawait writeFile(join(vemDir, \"exit_signal\"), \"\", \"utf-8\");\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Task ${id} marked as DONE. CLI will auto-close when the agent session ends.`,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"start_task\") {\n\t\tconst id = args?.id as string;\n\t\tconst sessionId = args?.session_id as string | undefined;\n\t\tconst source =\n\t\t\t(args?.source as \"copilot\" | \"claude\" | \"gemini\") || \"copilot\";\n\t\tconst sessionSummary = args?.session_summary as string | undefined;\n\n\t\tif (!id) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: \"Task ID is required.\" }],\n\t\t\t};\n\t\t}\n\n\t\tconst task = await taskService.getTask(id);\n\t\tif (!task) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: `Task ${id} not found.` }],\n\t\t\t};\n\t\t}\n\n\t\t// Build the new session ref\n\t\tconst sessionRef = sessionId\n\t\t\t? {\n\t\t\t\t\tid: sessionId,\n\t\t\t\t\tsource,\n\t\t\t\t\tstarted_at: new Date().toISOString(),\n\t\t\t\t\t...(sessionSummary ? { summary: sessionSummary } : {}),\n\t\t\t\t}\n\t\t\t: null;\n\n\t\t// Append session ref and mark in-progress\n\t\tconst existingSessions = (task.sessions as any[]) || [];\n\t\tconst patch: Record<string, any> = {\n\t\t\tstatus: \"in-progress\",\n\t\t\treasoning: sessionSummary\n\t\t\t\t? `Started by ${source} session: ${sessionSummary}`\n\t\t\t\t: `Started by ${source} agent`,\n\t\t\tsessions: sessionRef\n\t\t\t\t? [...existingSessions, sessionRef]\n\t\t\t\t: existingSessions,\n\t\t};\n\n\t\t// Auto-populate description from session summary if task has none\n\t\tif (!task.description && sessionSummary) {\n\t\t\tpatch.description = sessionSummary;\n\t\t}\n\n\t\tawait taskService.updateTask(id, patch);\n\t\tconst updated = await taskService.getTask(id);\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Task ${id} is now IN PROGRESS.\\n\\n${JSON.stringify(updated, null, 2)}`,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"search_memory\") {\n\t\tconst query = args?.query as string;\n\t\tconst apiKey = await configService.getApiKey();\n\n\t\tif (!apiKey) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Error: No API Key configured. Please run `vem login` in the CLI.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\n\t\ttry {\n\t\t\tconst { deviceId, deviceName } =\n\t\t\t\tawait configService.getOrCreateDeviceId();\n\t\t\tconst apiUrl = process.env.VEM_API_URL || \"http://localhost:3002\";\n\t\t\tconst res = await fetch(\n\t\t\t\t`${apiUrl}/search?q=${encodeURIComponent(query)}`,\n\t\t\t\t{\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\t\"X-Vem-Device-Id\": deviceId,\n\t\t\t\t\t\t\"X-Vem-Device-Name\": deviceName,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tif (!res.ok) {\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Search API Error: ${res.status} ${res.statusText}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst data = (await res.json()) as any;\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: JSON.stringify(data.results || [], null, 2),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t} catch (error: any) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{ type: \"text\", text: `Search Request Failed: ${error.message}` },\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\t}\n\n\tif (name === \"ask_question\") {\n\t\tconst question = args?.question as string;\n\t\tconst path = args?.path as string | undefined;\n\t\tconst apiKey = await configService.getApiKey();\n\t\tconst projectId = await configService.getProjectId();\n\n\t\tif (!apiKey) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Error: No API Key configured. Please run `vem login` in the CLI.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\n\t\tif (!projectId) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Error: No project linked. Please run `vem link` in the CLI.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\n\t\ttry {\n\t\t\tconst { deviceId, deviceName } =\n\t\t\t\tawait configService.getOrCreateDeviceId();\n\t\t\tconst apiUrl = process.env.VEM_API_URL || \"http://localhost:3002\";\n\n\t\t\tconst payload: any = { question };\n\t\t\tif (path) payload.path = path;\n\n\t\t\tconst res = await fetch(`${apiUrl}/projects/${projectId}/ask`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\"X-Vem-Device-Id\": deviceId,\n\t\t\t\t\t\"X-Vem-Device-Name\": deviceName,\n\t\t\t\t\t\"X-Vem-Client\": \"mcp-server\",\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t});\n\n\t\t\tif (!res.ok) {\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Ask API Error: ${res.status} ${res.statusText}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst data = (await res.json()) as any;\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: JSON.stringify(data, null, 2),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t} catch (error: any) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{ type: \"text\", text: `Ask Request Failed: ${error.message}` },\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\t}\n\n\tif (name === \"get_context\") {\n\t\tconst vemDir = await getVemDir();\n\t\tconst context = await configService.getContext();\n\t\tlet currentState = \"\";\n\t\ttry {\n\t\t\tcurrentState = await readFile(join(vemDir, CURRENT_STATE_FILE), \"utf-8\");\n\t\t} catch {\n\t\t\t// CURRENT_STATE.md may not exist yet\n\t\t}\n\t\tconst parts: string[] = [];\n\t\tif (context) parts.push(`## CONTEXT.md\\n\\n${context}`);\n\t\tif (currentState) parts.push(`## CURRENT_STATE.md\\n\\n${currentState}`);\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: parts.join(\"\\n\\n---\\n\\n\") || \"(no context yet)\" }],\n\t\t};\n\t}\n\n\tif (name === \"list_decisions\") {\n\t\tconst requestedLimit = (args?.limit as number) || 20;\n\t\tconst limit = Math.min(Math.max(1, requestedLimit), 50);\n\n\t\tconst decisionsService = new ScalableLogService(DECISIONS_DIR);\n\t\tconst entries = await decisionsService.getAllEntries();\n\t\tconst limitedEntries = entries.slice(0, limit);\n\n\t\tconst formatted = limitedEntries.map((entry) => ({\n\t\t\tid: entry.id,\n\t\t\ttitle: entry.title,\n\t\t\tdate: entry.created_at,\n\t\t\tcontent: entry.content,\n\t\t}));\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: formatted.length > 0\n\t\t\t\t\t\t? JSON.stringify(formatted, null, 2)\n\t\t\t\t\t\t: \"No decisions recorded yet.\",\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"update_current_state\") {\n\t\tconst content = args?.content as string;\n\t\tif (!content) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: \"Content is required.\" }],\n\t\t\t};\n\t\t}\n\t\tconst vemDir = await getVemDir();\n\t\tawait writeFile(join(vemDir, CURRENT_STATE_FILE), content, \"utf-8\");\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: \"CURRENT_STATE.md updated.\" }],\n\t\t};\n\t}\n\n\tif (name === \"update_task\") {\n\t\tconst id = args?.id as string;\n\t\tconst status = args?.status as string | undefined;\n\t\tconst priority = args?.priority as string | undefined;\n\t\tconst reasoning = args?.reasoning as string | undefined;\n\t\tconst blockedBy = args?.blocked_by as string[] | undefined;\n\t\tconst validationSteps = args?.validation_steps as string[] | undefined;\n\n\t\tif (!id) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: \"Task ID is required.\" }],\n\t\t\t};\n\t\t}\n\n\t\tconst task = await taskService.getTask(id);\n\t\tif (!task) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: `Task ${id} not found.` }],\n\t\t\t};\n\t\t}\n\n\t\t// Validate status transitions\n\t\tif (status === \"blocked\" && !reasoning) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Reasoning is required when blocking a task.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\n\t\tif (task.status === \"done\" && status) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Cannot change status of a completed task. Use complete_task to mark as done.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\n\t\tconst patch: Record<string, any> = {};\n\t\tif (status) patch.status = status;\n\t\tif (priority) patch.priority = priority;\n\t\tif (reasoning) patch.reasoning = reasoning;\n\t\tif (blockedBy) patch.blocked_by = blockedBy;\n\t\tif (validationSteps) patch.validation_steps = validationSteps;\n\n\t\t// Default reasoning for status changes\n\t\tif (status && !reasoning) {\n\t\t\tif (status === \"in-progress\") {\n\t\t\t\tpatch.reasoning = \"Started working on task\";\n\t\t\t} else if (status === \"todo\") {\n\t\t\t\tpatch.reasoning = \"Unblocked task\";\n\t\t\t}\n\t\t}\n\n\t\tawait taskService.updateTask(id, patch);\n\n\t\tconst statusMsg = status ? ` Status: ${status.toUpperCase()}.` : \"\";\n\t\tconst priorityMsg = priority ? ` Priority: ${priority}.` : \"\";\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Task ${id} updated.${statusMsg}${priorityMsg}`,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"add_decision\") {\n\t\tconst title = args?.title as string;\n\t\tconst context = args?.context as string;\n\t\tconst decision = args?.decision as string;\n\t\tconst relatedTasks = args?.related_tasks as string[] | undefined;\n\n\t\tif (!title || !context || !decision) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Title, context, and decision are required.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\n\t\tawait configService.recordDecision(title, context, decision, relatedTasks);\n\n\t\tconst taskInfo =\n\t\t\trelatedTasks && relatedTasks.length > 0\n\t\t\t\t? ` (related to: ${relatedTasks.join(\", \")})`\n\t\t\t\t: \"\";\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Decision recorded: ${title}${taskInfo}`,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"get_changelog\") {\n\t\tconst requestedLimit = (args?.limit as number) || 10;\n\t\tconst limit = Math.min(Math.max(1, requestedLimit), 50); // Clamp between 1 and 50\n\n\t\tconst changelogService = new ScalableLogService(CHANGELOG_DIR);\n\t\tconst entries = await changelogService.getAllEntries();\n\t\tconst limitedEntries = entries.slice(0, limit);\n\n\t\tconst formatted = limitedEntries.map((entry) => ({\n\t\t\tid: entry.id,\n\t\t\ttitle: entry.title,\n\t\t\tdate: entry.created_at,\n\t\t\tcontent: entry.content,\n\t\t}));\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: JSON.stringify(formatted, null, 2),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"delete_task\") {\n\t\tconst id = args?.id as string;\n\t\tconst reasoning = args?.reasoning as string | undefined;\n\n\t\tif (!id) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: \"Task ID is required.\" }],\n\t\t\t};\n\t\t}\n\n\t\tawait taskService.updateTask(id, {\n\t\t\tdeleted_at: new Date().toISOString(),\n\t\t\treasoning,\n\t\t});\n\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Task ${id} soft deleted.` }],\n\t\t};\n\t}\n\n\tif (name === \"apply_vem_update\") {\n\t\ttry {\n\t\t\tconst update = args as any;\n\t\t\tconst result = await applyVemUpdate(update);\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `Successfully applied vem_update:\\n- Tasks updated: ${result.updatedTasks.length}\\n- New tasks: ${result.newTasks.length}\\n- Changelog lines: ${result.changelogLines.length}\\n- Decisions: ${result.decisionsAppended ? \"Appended\" : \"No change\"}\\n- Context: ${result.contextUpdated ? \"Updated\" : \"No change\"}\\n- State: ${result.currentStateUpdated ? \"Updated\" : \"No change\"}`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t} catch (error: any) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{ type: \"text\", text: `Failed to apply update: ${error.message}` },\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\t}\n\n\tif (name === \"sync_push\") {\n\t\tconst force = args?.force as boolean | undefined;\n\t\tconst dryRun = args?.dry_run as boolean | undefined;\n\n\t\ttry {\n\t\t\tconst projectId = await configService.getProjectId();\n\t\t\tif (!projectId) {\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Error: Project not linked. Run `vem link` in the CLI first.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst apiKey = await configService.getApiKey();\n\t\t\tif (!apiKey) {\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Error: No API Key configured. Run `vem login` in the CLI.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst baseVersion = await configService.getLastVersion();\n\t\t\tconst gitHash = getGitHash();\n\t\t\tif (!gitHash) {\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Error: git HEAD not found. Create at least one commit before syncing snapshots.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst vemHash = await computeVemHash();\n\t\t\tconst lastPush = await configService.getLastPushState();\n\t\t\tconst hasChanges = !(\n\t\t\t\tvemHash &&\n\t\t\t\tlastPush.gitHash === gitHash &&\n\t\t\t\tlastPush.vemHash === vemHash\n\t\t\t);\n\n\t\t\tif (!hasChanges && !force) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"No changes since last push (git HEAD and .vem unchanged). Use force=true to push anyway.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst snapshot = await syncService.pack();\n\t\t\tconst snapshotHash = computeSnapshotHashFromPayload(snapshot);\n\n\t\t\tif (dryRun) {\n\t\t\t\tconst taskCount = snapshot.tasks?.tasks?.length || 0;\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Dry run preview:\\n- Project: ${projectId}\\n- Git hash: ${gitHash}\\n- Snapshot hash: ${snapshotHash}\\n- Base version: ${baseVersion || \"none\"}\\n- Tasks: ${taskCount}\\n- Context: ${snapshot.context ? \"yes\" : \"no\"}\\n- Current state: ${snapshot.current_state ? \"yes\" : \"no\"}\\n\\nVerification remains pending until Git webhook linkage is confirmed.\\n\\nNo changes pushed. Remove dry_run to push for real.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst repoUrl = getGitRemote();\n\t\t\tconst commits = getCommits(50);\n\t\t\tconst payload = {\n\t\t\t\t...snapshot,\n\t\t\t\t...(repoUrl ? { repo_url: repoUrl } : {}),\n\t\t\t\tbase_version: baseVersion,\n\t\t\t\tcommits,\n\t\t\t\tproject_id: projectId,\n\t\t\t\tgit_hash: gitHash,\n\t\t\t\tsnapshot_hash: snapshotHash,\n\t\t\t};\n\n\t\t\tconst apiUrl = process.env.VEM_API_URL || \"http://localhost:3002\";\n\t\t\tconst res = await fetch(`${apiUrl}/snapshots`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t});\n\n\t\t\tif (res.ok) {\n\t\t\t\tconst json = (await res.json()) as { version?: string };\n\t\t\t\tif (json.version) {\n\t\t\t\t\tawait configService.setLastVersion(json.version);\n\t\t\t\t}\n\t\t\t\tif (gitHash && vemHash) {\n\t\t\t\t\tawait configService.setLastPushState({ gitHash, vemHash });\n\t\t\t\t}\n\n\t\t\t\t// Auto-archive completed tasks\n\t\t\t\ttry {\n\t\t\t\t\tawait taskService.archiveTasks({ status: \"done\" });\n\t\t\t\t} catch {\n\t\t\t\t\t// Soft failure — don't fail the push\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Snapshot pushed successfully. Version: ${json.version || \"v1\"}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst data = (await res.json().catch(() => ({}))) as any;\n\n\t\t\tif (res.status === 409) {\n\t\t\t\tif (data.latest_version) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Conflict: local base version ${baseVersion || \"none\"} does not match latest ${data.latest_version}. Run sync_pull first, then retry.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (data.expected_repo_url) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Conflict: project is linked to ${data.expected_repo_url}, but local repo is ${repoUrl || \"(no git remote)\"}. Update git remote or re-link the project.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Conflict: ${data.error || \"Unknown conflict\"}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (res.status === 403) {\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext:\n\t\t\t\t\t\t\t\tdata.error ||\n\t\t\t\t\t\t\t\t\"Device limit reached. Disconnect a device or upgrade your plan.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (res.status === 404) {\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext:\n\t\t\t\t\t\t\t\tdata.error ||\n\t\t\t\t\t\t\t\t\"Project not found. It may have been deleted. Run `vem unlink` then `vem link` to reconnect.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Network/other error: enqueue for later\n\t\t\tawait syncService.enqueue(payload);\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `Push failed (${data.error || res.statusText}). Snapshot queued for later retry.`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t} catch (error: any) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: `Push failed: ${error.message}` }],\n\t\t\t};\n\t\t}\n\t}\n\n\tif (name === \"sync_pull\") {\n\t\tconst force = args?.force as boolean | undefined;\n\n\t\ttry {\n\t\t\tconst apiKey = await configService.getApiKey();\n\t\t\tif (!apiKey) {\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Error: No API Key configured. Run `vem login` in the CLI.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif ((await isVemDirty()) && !force) {\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Local .vem has uncommitted changes. Use force=true to overwrite, or commit your changes first.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst repoUrl = getGitRemote();\n\t\t\tconst projectId = await configService.getProjectId();\n\t\t\tif (!repoUrl && !projectId) {\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Error: No git remote or linked project found. Run `vem link` in the CLI.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst apiUrl = process.env.VEM_API_URL || \"http://localhost:3002\";\n\t\t\tconst query = new URLSearchParams();\n\t\t\tif (repoUrl) query.set(\"repo_url\", repoUrl);\n\t\t\tif (projectId) query.set(\"project_id\", projectId);\n\n\t\t\tconst res = await fetch(`${apiUrl}/snapshots/latest?${query}`, {\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tif (!res.ok) {\n\t\t\t\tif (res.status === 404) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"Project not found. It may have been deleted.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (res.status === 409) {\n\t\t\t\t\tconst data = (await res.json().catch(() => ({}))) as any;\n\t\t\t\t\treturn {\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: data.expected_repo_url\n\t\t\t\t\t\t\t\t\t? `Repo URL mismatch. Expected ${data.expected_repo_url}.`\n\t\t\t\t\t\t\t\t\t: data.error || \"Conflict detected.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (res.status === 403) {\n\t\t\t\t\tconst data = (await res.json().catch(() => ({}))) as any;\n\t\t\t\t\treturn {\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{ type: \"text\", text: data.error || \"Device limit reached.\" },\n\t\t\t\t\t\t],\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst err = await res.text();\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{ type: \"text\", text: `Pull API Error: ${res.status} ${err}` },\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst data = (await res.json()) as { snapshot: any; version?: string };\n\t\t\tif (!data.snapshot) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: \"No snapshot data available.\" }],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tawait syncService.unpack(data.snapshot);\n\t\t\tif (data.version) {\n\t\t\t\tawait configService.setLastVersion(data.version);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `Snapshot pulled and unpacked. Version: ${data.version || \"unknown\"}`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t} catch (error: any) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: `Pull failed: ${error.message}` }],\n\t\t\t};\n\t\t}\n\t}\n\n\tif (name === \"get_task_context\") {\n\t\tconst id = args?.id as string;\n\t\tif (!id) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: \"Task ID is required.\" }],\n\t\t\t};\n\t\t}\n\n\t\tconst task = await taskService.getTask(id);\n\t\tif (!task) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: `Task ${id} not found.` }],\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tid: task.id,\n\t\t\t\t\t\t\ttitle: task.title,\n\t\t\t\t\t\t\ttask_context: task.task_context || null,\n\t\t\t\t\t\t\ttask_context_summary: task.task_context_summary || null,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"update_task_context\") {\n\t\tconst id = args?.id as string;\n\t\tconst operation = args?.operation as string;\n\t\tconst text = args?.text as string | undefined;\n\n\t\tif (!id) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: \"Task ID is required.\" }],\n\t\t\t};\n\t\t}\n\t\tif (!operation || ![\"set\", \"append\", \"clear\"].includes(operation)) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Operation must be 'set', 'append', or 'clear'.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\t\tif ((operation === \"set\" || operation === \"append\") && !text) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `Text is required for '${operation}' operation.`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\n\t\tconst task = await taskService.getTask(id);\n\t\tif (!task) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: `Task ${id} not found.` }],\n\t\t\t};\n\t\t}\n\n\t\tlet nextContext = task.task_context || \"\";\n\t\tif (operation === \"clear\") {\n\t\t\tnextContext = \"\";\n\t\t} else if (operation === \"set\") {\n\t\t\tnextContext = text!;\n\t\t} else if (operation === \"append\") {\n\t\t\tnextContext = [nextContext, text!].filter(Boolean).join(\"\\n\");\n\t\t}\n\n\t\tawait taskService.updateTask(id, { task_context: nextContext });\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{ type: \"text\", text: `Task ${id} context updated (${operation}).` },\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"get_subtasks\") {\n\t\tconst parentId = args?.parent_id as string;\n\t\tif (!parentId) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: \"Parent task ID is required.\" }],\n\t\t\t};\n\t\t}\n\n\t\tconst allTasks = await taskService.getTasks();\n\t\tconst parent = allTasks.find((t) => t.id === parentId);\n\t\tif (!parent) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: `Parent task ${parentId} not found.` }],\n\t\t\t};\n\t\t}\n\n\t\tconst subtasks = allTasks\n\t\t\t.filter((t) => t.parent_id === parentId && !t.deleted_at)\n\t\t\t.sort((a, b) => (a.subtask_order ?? 0) - (b.subtask_order ?? 0));\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: JSON.stringify({ parent, subtasks }, null, 2),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"list_agent_sessions\") {\n\t\tconst limit = typeof args?.limit === \"number\" ? args.limit : 10;\n\t\tconst branch = typeof args?.branch === \"string\" ? args.branch : undefined;\n\t\tconst rawSources = args?.sources;\n\t\tconst sources =\n\t\t\tArray.isArray(rawSources) && rawSources.length > 0\n\t\t\t\t? (rawSources as (\"copilot\" | \"claude\" | \"gemini\")[])\n\t\t\t\t: undefined;\n\n\t\tlet gitRoot: string | undefined;\n\t\ttry {\n\t\t\tgitRoot = await getRepoRoot();\n\t\t} catch {\n\t\t\t// fallback: no filter\n\t\t}\n\n\t\tlet sessions = await listAllAgentSessions(gitRoot, sources);\n\t\tif (branch) {\n\t\t\tsessions = sessions.filter((s) => s.branch === branch);\n\t\t}\n\t\tsessions = sessions.slice(0, limit);\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\tsessions.map((s) => ({\n\t\t\t\t\t\t\tid: s.id,\n\t\t\t\t\t\t\tsource: s.source,\n\t\t\t\t\t\t\tsummary: s.summary,\n\t\t\t\t\t\t\tbranch: s.branch,\n\t\t\t\t\t\t\trepository: s.repository,\n\t\t\t\t\t\t\tcreated_at: s.created_at,\n\t\t\t\t\t\t\tupdated_at: s.updated_at,\n\t\t\t\t\t\t\tintents: s.intents,\n\t\t\t\t\t\t\tuser_messages: s.user_messages.slice(0, 3),\n\t\t\t\t\t\t})),\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"save_session_stats\") {\n\t\tconst taskId = args?.task_id as string;\n\t\tconst sessionId = args?.session_id as string;\n\t\tconst source =\n\t\t\t(args?.source as \"copilot\" | \"claude\" | \"gemini\") || \"copilot\";\n\n\t\tif (!taskId || !sessionId) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"task_id and session_id are required.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\n\t\tconst task = await taskService.getTask(taskId);\n\t\tif (!task) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: `Task ${taskId} not found.` }],\n\t\t\t};\n\t\t}\n\n\t\tconst stats = await computeSessionStats(sessionId, source);\n\t\tif (!stats) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `Could not compute stats for ${source} session ${sessionId}. Session file may not exist or is unreadable.`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\n\t\t// Update the matching session ref on the task (or append stats as a note if no match)\n\t\tconst existingSessions = ((task.sessions as any[]) || []).map((s: any) => {\n\t\t\tif (s.id === sessionId) {\n\t\t\t\treturn { ...s, stats };\n\t\t\t}\n\t\t\treturn s;\n\t\t});\n\n\t\t// If no matching session was found, still save the stats by appending a new session entry\n\t\tconst hasMatch = existingSessions.some((s: any) => s.id === sessionId);\n\t\tif (!hasMatch) {\n\t\t\texistingSessions.push({\n\t\t\t\tid: sessionId,\n\t\t\t\tsource,\n\t\t\t\tstarted_at: stats.ended_at ?? new Date().toISOString(),\n\t\t\t\tstats,\n\t\t\t});\n\t\t}\n\n\t\tawait taskService.updateTask(taskId, { sessions: existingSessions });\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Stats saved for session ${sessionId} on task ${taskId}:\\n${JSON.stringify(stats, null, 2)}`,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tthrow new Error(`Tool not found: ${name}`);\n});\n\nconst transport = new StdioServerTransport();\nawait server.connect(transport);\n","import path from \"node:path\";\nimport { TaskCreateSchema, TaskUpdateSchema, VemUpdateSchema, } from \"@vem/schemas\";\nimport fs from \"fs-extra\";\nimport { CHANGELOG_DIR, CONTEXT_FILE, CURRENT_STATE_FILE, DECISIONS_DIR, ensureVemFiles, getVemDir, } from \"./fs.js\";\nimport { getGitHeadHash } from \"./git.js\";\nimport { ScalableLogService } from \"./logs.js\";\nimport { TaskService } from \"./tasks.js\";\nconst VEM_UPDATE_FENCE = /```vem_update(?:\\s+v1)?\\s*([\\s\\S]*?)```/i;\nconst DEFAULT_TASK_CONTEXT_SUMMARY_MAX_CHARS = 1200;\nexport function formatVemPack(payload) {\n return `\\`\\`\\`vem_pack v1\\n${JSON.stringify(payload, null, 2)}\\n\\`\\`\\``;\n}\nexport function parseVemUpdateBlock(input) {\n const match = input.match(VEM_UPDATE_FENCE);\n const raw = (match?.[1] ?? input).trim();\n if (!raw) {\n throw new Error(\"No vem_update payload found.\");\n }\n let data;\n try {\n data = JSON.parse(raw);\n }\n catch (error) {\n throw new Error(`vem_update payload is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);\n }\n const parsed = VemUpdateSchema.safeParse(data);\n if (!parsed.success) {\n throw new Error(`vem_update payload failed validation: ${parsed.error.message}`);\n }\n return parsed.data;\n}\nfunction resolveAgentActor(actor) {\n const trimmed = actor?.trim();\n if (trimmed)\n return trimmed;\n const envActor = process.env.VEM_AGENT_NAME ||\n process.env.VEM_ACTOR ||\n process.env.VEM_AGENT;\n const normalized = envActor?.trim();\n return normalized || undefined;\n}\nfunction normalizeEvidence(evidence) {\n if (!evidence)\n return [];\n return evidence.map((entry) => entry.trim()).filter(Boolean);\n}\nfunction addValidationEvidence(evidence, validationSteps) {\n if (!validationSteps || validationSteps.length === 0) {\n return evidence;\n }\n const merged = [...evidence];\n let evidenceBlob = merged.join(\" \").toLowerCase();\n for (const step of validationSteps) {\n const normalizedStep = step.trim();\n if (!normalizedStep)\n continue;\n if (!evidenceBlob.includes(normalizedStep.toLowerCase())) {\n const entry = `Validated: ${normalizedStep}`;\n merged.push(entry);\n evidenceBlob = `${evidenceBlob}\\n${entry.toLowerCase()}`;\n }\n }\n return merged;\n}\nfunction summarizeTaskContext(taskContext) {\n const normalized = taskContext.trim();\n if (normalized.length <= DEFAULT_TASK_CONTEXT_SUMMARY_MAX_CHARS) {\n return normalized;\n }\n return `${normalized.slice(0, DEFAULT_TASK_CONTEXT_SUMMARY_MAX_CHARS - 15).trimEnd()}\\n...[truncated]`;\n}\nexport async function applyVemUpdate(update) {\n await ensureVemFiles();\n const taskService = new TaskService();\n const decisionsLog = new ScalableLogService(DECISIONS_DIR);\n const changelogLog = new ScalableLogService(CHANGELOG_DIR);\n const updatedTasks = [];\n const newTasks = [];\n if (update.tasks?.length) {\n for (const entry of update.tasks) {\n const parsed = TaskUpdateSchema.safeParse(entry);\n if (!parsed.success) {\n throw new Error(`Invalid task update for ${entry.id}: ${parsed.error.message}`);\n }\n const { id, ...patch } = parsed.data;\n const task = await taskService.getTask(id);\n if (!task) {\n throw new Error(`Task ${id} not found.`);\n }\n let cleaned = stripUndefined(patch);\n if (cleaned.status === \"done\" && task.status !== \"done\") {\n const actor = resolveAgentActor(cleaned.actor);\n const reasoning = cleaned.reasoning?.trim() ||\n `Completed via ${actor || \"agent\"} session.`;\n const baseEvidence = normalizeEvidence(cleaned.evidence);\n const evidenceSeed = baseEvidence.length > 0\n ? baseEvidence\n : [`Completed by agent ${actor || \"unknown\"}`];\n const evidence = addValidationEvidence(evidenceSeed, task.validation_steps);\n const taskContextSummary = cleaned.task_context_summary ??\n (task.task_context\n ? summarizeTaskContext(task.task_context)\n : undefined);\n cleaned = stripUndefined({\n ...cleaned,\n actor,\n reasoning,\n evidence,\n task_context_summary: taskContextSummary,\n });\n }\n const updated = await taskService.updateTask(id, cleaned);\n updatedTasks.push(updated);\n }\n }\n if (update.new_tasks?.length) {\n for (const entry of update.new_tasks) {\n const parsed = TaskCreateSchema.safeParse(entry);\n if (!parsed.success) {\n throw new Error(`Invalid new task payload: ${parsed.error.message}`);\n }\n const created = await taskService.addTask(parsed.data.title, parsed.data.description, parsed.data.priority ?? \"medium\", parsed.data.reasoning, stripUndefined({\n status: parsed.data.status,\n assignee: parsed.data.assignee,\n tags: parsed.data.tags,\n type: parsed.data.type,\n estimate_hours: parsed.data.estimate_hours,\n depends_on: parsed.data.depends_on,\n blocked_by: parsed.data.blocked_by,\n recurrence_rule: parsed.data.recurrence_rule,\n owner_id: parsed.data.owner_id,\n reviewer_id: parsed.data.reviewer_id,\n evidence: parsed.data.evidence,\n parent_id: parsed.data.parent_id,\n subtask_order: parsed.data.subtask_order,\n due_at: parsed.data.due_at,\n task_context: parsed.data.task_context,\n task_context_summary: parsed.data.task_context_summary,\n }));\n // Apply other fields if present (status, assignee, etc)\n const patch = stripUndefined({\n status: parsed.data.status,\n assignee: parsed.data.assignee,\n tags: parsed.data.tags,\n type: parsed.data.type,\n estimate_hours: parsed.data.estimate_hours,\n depends_on: parsed.data.depends_on,\n blocked_by: parsed.data.blocked_by,\n recurrence_rule: parsed.data.recurrence_rule,\n owner_id: parsed.data.owner_id,\n reviewer_id: parsed.data.reviewer_id,\n evidence: parsed.data.evidence,\n parent_id: parsed.data.parent_id,\n subtask_order: parsed.data.subtask_order,\n due_at: parsed.data.due_at,\n task_context: parsed.data.task_context,\n task_context_summary: parsed.data.task_context_summary,\n });\n let updated = created;\n if (Object.keys(patch).length > 0) {\n updated = await taskService.updateTask(created.id, patch);\n }\n newTasks.push(updated);\n }\n }\n const changelogLines = await appendChangelog(changelogLog, update.changelog_append);\n const decisionsAppendedRef = await appendDecisions(decisionsLog, update.decisions_append);\n const decisionsAppended = decisionsAppendedRef !== null;\n // Auto-link the new decision to all updated/new tasks via related_decisions\n if (decisionsAppendedRef) {\n const refId = typeof decisionsAppendedRef === \"string\"\n ? decisionsAppendedRef\n : decisionsAppendedRef.id;\n const allAffectedTasks = [...updatedTasks, ...newTasks];\n for (const task of allAffectedTasks) {\n const existing = Array.isArray(task.related_decisions)\n ? task.related_decisions\n : [];\n const alreadyLinked = existing.some((r) => typeof r === \"string\" ? r === refId : r.id === refId);\n if (!alreadyLinked) {\n const updated = await taskService.updateTask(task.id, {\n related_decisions: [...existing, decisionsAppendedRef],\n });\n // Replace in the result arrays\n const ui = updatedTasks.findIndex((t) => t.id === task.id);\n if (ui !== -1)\n updatedTasks[ui] = updated;\n const ni = newTasks.findIndex((t) => t.id === task.id);\n if (ni !== -1)\n newTasks[ni] = updated;\n }\n }\n }\n const currentStateUpdated = await writeCurrentState(update.current_state);\n const contextUpdated = await writeContext(update.context);\n return {\n updatedTasks,\n newTasks,\n changelogLines,\n decisionsAppended,\n decisionsAppendedRef,\n currentStateUpdated,\n contextUpdated,\n };\n}\nfunction stripUndefined(value) {\n return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));\n}\nfunction normalizeLines(value) {\n if (!value)\n return [];\n const raw = Array.isArray(value) ? value : value.split(/\\r?\\n/);\n return raw.map((line) => line.trim()).filter(Boolean);\n}\nasync function appendChangelog(log, value) {\n const additions = normalizeLines(value);\n if (additions.length === 0)\n return [];\n const content = additions.map((line) => `- ${line}`).join(\"\\n\");\n const commitHash = await getGitHeadHash();\n await log.addEntry(\"Agent Update\", content, { commitHash });\n return additions;\n}\n/** Extracts the first meaningful heading from decisions markdown (e.g. ## [ADR-001] My title → \"ADR-001: My title\") */\nfunction extractDecisionTitle(block) {\n const match = block.match(/^#{1,3}\\s+\\[([^\\]]+)\\]\\s+(.+)$/m);\n if (match)\n return `${match[1]}: ${match[2].trim()}`;\n // Fallback: first non-empty heading\n const plain = block.match(/^#{1,3}\\s+(.+)$/m);\n return plain?.[1]?.trim();\n}\nasync function appendDecisions(log, value) {\n if (!value)\n return null;\n const block = Array.isArray(value) ? value.join(\"\\n\").trim() : value.trim();\n if (!block)\n return null;\n const commitHash = await getGitHeadHash();\n const id = await log.addEntry(\"Agent Decision\", block, { commitHash });\n const title = extractDecisionTitle(block);\n return title ? { id, title, content: block } : { id, content: block };\n}\nasync function writeCurrentState(value) {\n if (value === undefined)\n return false;\n const dir = await getVemDir();\n const currentStatePath = path.join(dir, CURRENT_STATE_FILE);\n const next = value.trim().length > 0 ? `${value.trim()}\\n` : \"\";\n await fs.writeFile(currentStatePath, next, \"utf-8\");\n return true;\n}\nasync function writeContext(value) {\n if (value === undefined)\n return false;\n const dir = await getVemDir();\n const contextPath = path.join(dir, CONTEXT_FILE);\n const next = value.trim().length > 0 ? `${value.trim()}\\n` : \"\";\n await fs.writeFile(contextPath, next, \"utf-8\");\n return true;\n}\n","import { z } from \"zod\";\nexport const RelatedDecisionRefSchema = z.union([\n z.string(),\n z.object({\n id: z.string(),\n title: z.string().optional(),\n content: z.string().optional(),\n }),\n]);\nexport const AgentSessionStatsSchema = z.object({\n ended_at: z.string().datetime().optional(),\n session_duration_ms: z.number().int().optional(),\n turn_count: z.number().int().optional(),\n tool_call_count: z.number().int().optional(),\n model_breakdown: z.record(z.string(), z.number().int()).optional(),\n});\nexport const TaskSessionRefSchema = z.object({\n id: z.string(),\n source: z.enum([\"copilot\", \"claude\", \"gemini\"]),\n started_at: z.string().datetime(),\n summary: z.string().optional(),\n stats: AgentSessionStatsSchema.optional(),\n});\nexport const TaskActionSchema = z.object({\n type: z.enum([\n \"create\",\n \"update_status\",\n \"update_priority\",\n \"update_tags\",\n \"update_type\",\n \"update_estimate\",\n \"update_dependencies\",\n \"update_recurrence\",\n \"update_owner\",\n \"update_reviewer\",\n \"delete\",\n \"comment\",\n \"completion\",\n ]),\n reasoning: z.string().nullable().optional(),\n actor: z.string().nullable().optional(),\n created_at: z.string().datetime(),\n});\nexport const TaskStatusSchema = z.enum([\n \"todo\",\n \"in-progress\",\n \"blocked\",\n \"done\",\n]);\nexport const TaskPrioritySchema = z.enum([\"low\", \"medium\", \"high\", \"critical\"]);\nexport const TaskTypeSchema = z.enum([\"feature\", \"bug\", \"chore\"]);\nexport const TaskSchema = z.object({\n id: z.string(),\n title: z.string(),\n status: TaskStatusSchema,\n assignee: z.string().optional(),\n priority: TaskPrioritySchema.optional(),\n tags: z.array(z.string()).optional(),\n type: TaskTypeSchema.optional(),\n estimate_hours: z.number().optional(),\n depends_on: z.array(z.string()).optional(),\n blocked_by: z.array(z.string()).optional(),\n recurrence_rule: z.string().optional(),\n owner_id: z.string().optional(),\n reviewer_id: z.string().optional(),\n parent_id: z.string().optional(),\n subtask_order: z.number().int().optional(),\n description: z.string().optional(),\n task_context: z.string().optional(),\n task_context_summary: z.string().optional(),\n user_notes: z.string().optional(),\n related_decisions: z.array(RelatedDecisionRefSchema).optional(),\n evidence: z.array(z.string()).optional(),\n validation_steps: z.array(z.string()).optional(),\n sessions: z.array(TaskSessionRefSchema).optional(),\n actions: z.array(TaskActionSchema).optional(),\n created_at: z.string().datetime().optional(),\n updated_at: z.string().datetime().optional(),\n due_at: z.string().datetime().optional(),\n github_issue_number: z.number().optional(),\n deleted_at: z.string().datetime().optional(),\n});\nexport const TaskListSchema = z.object({\n tasks: z.array(TaskSchema),\n});\nexport const TaskUpdateSchema = z.object({\n id: z.string(),\n title: z.string().optional(),\n description: z.string().optional(),\n status: TaskStatusSchema.optional(),\n assignee: z.string().optional(),\n priority: TaskPrioritySchema.optional(),\n tags: z.array(z.string()).optional(),\n type: TaskTypeSchema.optional(),\n estimate_hours: z.number().optional(),\n depends_on: z.array(z.string()).optional(),\n blocked_by: z.array(z.string()).optional(),\n recurrence_rule: z.string().optional(),\n owner_id: z.string().optional(),\n reviewer_id: z.string().optional(),\n parent_id: z.string().optional(),\n subtask_order: z.number().int().optional(),\n due_at: z.string().datetime().optional(),\n evidence: z.array(z.string()).optional(),\n task_context: z.string().optional(),\n task_context_summary: z.string().optional(),\n user_notes: z.string().optional(),\n related_decisions: z.array(RelatedDecisionRefSchema).optional(),\n validation_steps: z.array(z.string()).optional(),\n reasoning: z.string().optional(),\n actor: z.string().optional(),\n github_issue_number: z.number().optional(),\n deleted_at: z.string().datetime().optional(),\n});\nexport const TaskCreateSchema = z.object({\n title: z.string(),\n description: z.string().optional(),\n status: TaskStatusSchema.optional(),\n assignee: z.string().optional(),\n priority: TaskPrioritySchema.optional(),\n tags: z.array(z.string()).optional(),\n type: TaskTypeSchema.optional(),\n estimate_hours: z.number().optional(),\n depends_on: z.array(z.string()).optional(),\n blocked_by: z.array(z.string()).optional(),\n recurrence_rule: z.string().optional(),\n owner_id: z.string().optional(),\n reviewer_id: z.string().optional(),\n parent_id: z.string().optional(),\n subtask_order: z.number().int().optional(),\n due_at: z.string().datetime().optional(),\n evidence: z.array(z.string()).optional(),\n task_context: z.string().optional(),\n task_context_summary: z.string().optional(),\n related_decisions: z.array(RelatedDecisionRefSchema).optional(),\n validation_steps: z.array(z.string()).optional(),\n reasoning: z.string().optional(),\n});\nexport const VemUpdateSchema = z.object({\n tasks: z.array(TaskUpdateSchema).optional(),\n new_tasks: z.array(TaskCreateSchema).optional(),\n changelog_append: z.union([z.string(), z.array(z.string())]).optional(),\n decisions_append: z.union([z.string(), z.array(z.string())]).optional(),\n current_state: z.string().optional(),\n context: z.string().optional(),\n});\n// Webhook event types\nexport const WebhookEventSchema = z.enum([\n \"task.created\",\n \"task.started\",\n \"task.blocked\",\n \"task.completed\",\n \"task.deleted\",\n \"snapshot.pushed\",\n \"snapshot.verified\",\n \"snapshot.failed\",\n \"decision.added\",\n \"changelog.updated\",\n \"drift.detected\",\n \"project.linked\",\n]);\nexport const WebhookSchema = z.object({\n id: z.string().uuid(),\n org_id: z.string(),\n project_id: z.string().nullable(),\n url: z.string().url(),\n secret: z.string(),\n enabled: z.boolean(),\n events: z.array(WebhookEventSchema),\n created_at: z.string().datetime(),\n updated_at: z.string().datetime(),\n created_by: z.string().nullable(),\n});\nexport const WebhookCreateSchema = z.object({\n url: z.string().url(\"Must be a valid URL\"),\n events: z.array(WebhookEventSchema).min(1, \"Must select at least one event\"),\n});\nexport const WebhookUpdateSchema = z.object({\n url: z.string().url().optional(),\n events: z.array(WebhookEventSchema).min(1).optional(),\n enabled: z.boolean().optional(),\n});\nexport const WebhookDeliverySchema = z.object({\n id: z.string().uuid(),\n webhook_id: z.string().uuid(),\n event_type: WebhookEventSchema,\n payload: z.any(),\n status_code: z.number().nullable(),\n success: z.boolean(),\n attempt: z.number().int().min(1).max(3),\n error_message: z.string().nullable(),\n delivered_at: z.string().datetime(),\n});\n","import path from \"node:path\";\nimport { findUp } from \"find-up-simple\";\nimport fs from \"fs-extra\";\nexport const VEM_DIR = \".vem\";\nexport const TASKS_DIR = \"tasks\";\nexport const DECISIONS_DIR = \"decisions\";\nexport const CHANGELOG_DIR = \"changelog\";\n// Legacy files (to be phased out)\nexport const TASKS_FILE = \"TASKS.json\";\nexport const DECISIONS_FILE = \"DECISIONS.md\";\nexport const CHANGELOG_FILE = \"CHANGELOG.md\";\nexport const CONTEXT_FILE = \"CONTEXT.md\";\nexport const CURRENT_STATE_FILE = \"CURRENT_STATE.md\";\nexport const SCRATCHPAD_FILE = \"scratchpad.md\";\nexport const QUEUE_DIR = \"queue\";\nexport async function getRepoRoot() {\n const gitDir = await findUp(\".git\", { type: \"directory\" });\n if (!gitDir) {\n throw new Error(\"Not inside a Git repository\");\n }\n return path.dirname(gitDir);\n}\nexport async function getVemDir() {\n const root = await getRepoRoot();\n return path.join(root, VEM_DIR);\n}\nexport async function ensureVemDir() {\n const dir = await getVemDir();\n await fs.ensureDir(dir);\n return dir;\n}\nexport async function isVemInitialized() {\n try {\n const dir = await getVemDir();\n return await fs.pathExists(dir);\n }\n catch {\n return false;\n }\n}\nexport async function ensureVemFiles() {\n const dir = await ensureVemDir();\n // Ensure new scalable directories\n await fs.ensureDir(path.join(dir, TASKS_DIR));\n await fs.ensureDir(path.join(dir, DECISIONS_DIR));\n await fs.ensureDir(path.join(dir, CHANGELOG_DIR));\n const contextPath = path.join(dir, CONTEXT_FILE);\n if (!(await fs.pathExists(contextPath))) {\n await fs.writeFile(contextPath, \"# Project Context: vem\\n\\nDescribe the high-level project context here.\\n\", \"utf-8\");\n }\n const currentStatePath = path.join(dir, CURRENT_STATE_FILE);\n if (!(await fs.pathExists(currentStatePath))) {\n await fs.writeFile(currentStatePath, \"# Current State\\n\\nSummarize what just changed, what is in progress, and what is next.\\n\", \"utf-8\");\n }\n}\n","import { execSync } from \"node:child_process\";\nimport { getRepoRoot } from \"./fs.js\";\nexport async function getGitHeadHash() {\n try {\n const root = await getRepoRoot();\n const hash = execSync(\"git rev-parse HEAD\", {\n cwd: root,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n .toString()\n .trim();\n return hash || null;\n }\n catch {\n return null;\n }\n}\nexport async function getGitLastCommitForPath(filePath) {\n try {\n const root = await getRepoRoot();\n const relative = filePath.startsWith(root)\n ? filePath.slice(root.length + 1)\n : filePath;\n const hash = execSync(`git log -1 --format=%H -- \"${relative.replace(/\"/g, '\\\\\"')}\"`, {\n cwd: root,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n .toString()\n .trim();\n return hash || null;\n }\n catch {\n return null;\n }\n}\n","import path from \"node:path\";\nimport fs from \"fs-extra\";\nimport { getVemDir } from \"./fs.js\";\nimport { getGitLastCommitForPath } from \"./git.js\";\nexport class ScalableLogService {\n subDir;\n constructor(subDir) {\n this.subDir = subDir;\n }\n async getBaseDir() {\n const vemDir = await getVemDir();\n const dir = path.join(vemDir, this.subDir);\n await fs.ensureDir(dir);\n return dir;\n }\n async addEntry(title, content, options) {\n const baseDir = await this.getBaseDir();\n const timestamp = new Date().toISOString();\n const id = `${timestamp.replace(/[:.]/g, \"-\")}-${title.toLowerCase().replace(/[^a-z0-9]/g, \"-\")}`;\n const filePath = path.join(baseDir, `${id}.md`);\n const commitLine = options?.commitHash\n ? `**Commit:** ${options.commitHash}\\n\\n`\n : \"\";\n const fullContent = `# ${title}\\n\\n**Date:** ${timestamp}\\n\\n${commitLine}${content}\\n`;\n await fs.writeFile(filePath, fullContent, \"utf-8\");\n return id;\n }\n async getAllEntries() {\n const baseDir = await this.getBaseDir();\n const files = await fs.readdir(baseDir);\n const entries = [];\n for (const file of files) {\n if (file.endsWith(\".md\")) {\n const content = await fs.readFile(path.join(baseDir, file), \"utf-8\");\n const id = path.parse(file).name;\n // Simple parsing for title (first # header)\n const titleMatch = content.match(/^#\\s+(.*)/);\n const title = titleMatch ? titleMatch[1] : id;\n entries.push({\n id,\n title,\n content,\n created_at: id\n .substring(0, 19)\n .replace(/-/g, (_m, offset) => offset === 10 ? \"T\" : offset === 13 || offset === 16 ? \":\" : \"-\"),\n file_path: path.join(baseDir, file),\n });\n }\n }\n // Sort by ID (which starts with timestamp)\n return entries.sort((a, b) => b.id.localeCompare(a.id));\n }\n async getMonolithicContent() {\n return this.getMonolithicContentWithOptions();\n }\n async getMonolithicContentWithOptions(options) {\n const entries = await this.getAllEntries();\n // reverse back to chronological for monolithic view\n const normalized = await Promise.all(entries.reverse().map(async (entry) => {\n if (!options?.includeCommitHashes)\n return entry.content;\n if (/^\\*\\*Commit:\\*\\*/m.test(entry.content))\n return entry.content;\n if (!entry.file_path)\n return entry.content;\n const commitHash = await getGitLastCommitForPath(entry.file_path);\n if (!commitHash)\n return entry.content;\n const dateMatch = entry.content.match(/^\\*\\*Date:\\*\\*.*$/m);\n if (!dateMatch) {\n return `**Commit:** ${commitHash}\\n\\n${entry.content}`;\n }\n return entry.content.replace(dateMatch[0], `${dateMatch[0]}\\n\\n**Commit:** ${commitHash}`);\n }));\n return normalized.join(\"\\n---\\n\\n\");\n }\n async archiveEntries(options) {\n const entries = await this.getAllEntries(); // Sorted by ID (date desc-ish)\n let toArchive = [];\n if (options.keepCount !== undefined) {\n toArchive = entries.slice(options.keepCount);\n }\n else if (options.olderThanDays !== undefined) {\n const now = new Date();\n const threshold = new Date(now.getTime() - options.olderThanDays * 24 * 60 * 60 * 1000);\n toArchive = entries.filter((e) => new Date(e.created_at) < threshold);\n }\n else {\n // If no options, default to keeping 20\n toArchive = entries.slice(20);\n }\n if (toArchive.length === 0)\n return 0;\n const baseDir = await this.getBaseDir();\n const archiveBase = path.join(baseDir, \"archive\");\n await fs.ensureDir(archiveBase);\n for (const entry of toArchive) {\n // Group by Year-Month\n const date = new Date(entry.created_at);\n const folder = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, \"0\")}`;\n const targetDir = path.join(archiveBase, folder);\n await fs.ensureDir(targetDir);\n const src = path.join(baseDir, `${entry.id}.md`);\n const dest = path.join(targetDir, `${entry.id}.md`);\n if (await fs.pathExists(src)) {\n await fs.move(src, dest, { overwrite: true });\n }\n }\n return toArchive.length;\n }\n}\n","import path from \"node:path\";\nimport fs from \"fs-extra\";\nimport { getVemDir, TASKS_DIR } from \"./fs.js\";\nimport { ShardedFileStorage, TaskIndex, } from \"./sharded-fs.js\";\nconst TASK_CONTEXT_SUMMARY_MAX_CHARS = 1200;\nfunction summarizeTaskContext(value) {\n const normalized = value.trim();\n if (normalized.length <= TASK_CONTEXT_SUMMARY_MAX_CHARS) {\n return normalized;\n }\n return `${normalized.slice(0, TASK_CONTEXT_SUMMARY_MAX_CHARS - 15).trimEnd()}\\n...[truncated]`;\n}\nexport class TaskService {\n storage = null;\n index = null;\n async init() {\n if (this.storage && this.index) {\n return { storage: this.storage, index: this.index };\n }\n const vemDir = await getVemDir();\n const baseDir = path.join(vemDir, TASKS_DIR);\n await fs.ensureDir(baseDir);\n this.storage = new ShardedFileStorage(baseDir);\n this.index = new TaskIndex(baseDir);\n return { storage: this.storage, index: this.index };\n }\n async getTasks() {\n const { storage } = await this.init();\n // For backward compatibility, we load all tasks.\n // In the future, we should probably prefer getTaskIndex or implement pagination.\n const active = await storage.loadAll();\n // Also include recently archived tasks (done within last 30 days) so\n // their sessions and evidence are visible in the cloud / web UI.\n const archived = await this.loadRecentArchivedTasks(30);\n const archivedIds = new Set(active.map((t) => t.id));\n for (const t of archived) {\n if (!archivedIds.has(t.id))\n active.push(t);\n }\n return active;\n }\n async loadRecentArchivedTasks(withinDays) {\n const vemDir = await getVemDir();\n const archiveDir = path.join(vemDir, TASKS_DIR, \"archive\");\n if (!(await fs.pathExists(archiveDir)))\n return [];\n const cutoff = Date.now() - withinDays * 24 * 60 * 60 * 1000;\n const result = [];\n const walk = async (dir) => {\n const entries = await fs.readdir(dir);\n for (const entry of entries) {\n const fullPath = path.join(dir, entry);\n const stat = await fs.stat(fullPath);\n if (stat.isDirectory()) {\n await walk(fullPath);\n continue;\n }\n if (!entry.endsWith(\".json\"))\n continue;\n if (stat.mtimeMs < cutoff)\n continue;\n try {\n const task = await fs.readJson(fullPath);\n if (task?.id)\n result.push(task);\n }\n catch {\n // skip malformed files\n }\n }\n };\n await walk(archiveDir);\n return result;\n }\n async getTaskIndex() {\n const { index } = await this.init();\n return index.load();\n }\n async getTask(id) {\n const { storage } = await this.init();\n return storage.load(id);\n }\n async listArchivedTaskIds() {\n const vemDir = await getVemDir();\n const archiveDir = path.join(vemDir, TASKS_DIR, \"archive\");\n if (!(await fs.pathExists(archiveDir))) {\n return [];\n }\n const ids = [];\n const walk = async (dir) => {\n const entries = await fs.readdir(dir);\n for (const entry of entries) {\n const fullPath = path.join(dir, entry);\n const stat = await fs.stat(fullPath);\n if (stat.isDirectory()) {\n await walk(fullPath);\n continue;\n }\n if (!entry.endsWith(\".json\"))\n continue;\n const id = path.parse(entry).name;\n if (/^TASK-\\d{3,}$/.test(id)) {\n ids.push(id);\n }\n }\n };\n await walk(archiveDir);\n return ids;\n }\n async getNextTaskId(storage) {\n const allTasks = await storage.loadAll();\n const archivedIds = await this.listArchivedTaskIds();\n const allIds = new Set([\n ...allTasks.map((task) => task.id),\n ...archivedIds,\n ]);\n // Find max existing sequential ID\n let maxId = 0;\n for (const id of allIds) {\n const match = id.match(/^TASK-(\\d{3,})$/);\n if (match) {\n const num = parseInt(match[1], 10);\n if (!Number.isNaN(num) && num > maxId) {\n maxId = num;\n }\n }\n }\n // Try to find the next available ID\n // In case of race conditions (file exists but not in index yet, though unlikely with single-threaded Node),\n // we could verify file existence, but storage.loadAll() already reads files.\n // We'll increment and check if it's taken in a loop just to be safe against some edge cases\n // or if we switch to index-only scanning later.\n let candidateNum = maxId + 1;\n let candidateId = `TASK-${String(candidateNum).padStart(3, \"0\")}`;\n // Double check against loaded tasks (already done via maxId, but good practice if logic changes)\n while (allIds.has(candidateId)) {\n candidateNum++;\n candidateId = `TASK-${String(candidateNum).padStart(3, \"0\")}`;\n }\n return candidateId;\n }\n async addTask(title, description, priority = \"medium\", reasoning, options) {\n const { storage, index } = await this.init();\n // Sequential ID generation with guardrails unless an explicit cache ID is provided.\n const explicitId = options?.id?.trim();\n const id = explicitId && explicitId.length > 0\n ? explicitId\n : await this.getNextTaskId(storage);\n const timestamp = new Date().toISOString();\n const blockingIds = await this.getBlockingIds(options?.depends_on, options?.blocked_by, storage);\n if (options?.status === \"done\" && blockingIds.length > 0) {\n throw new Error(\"Cannot mark task as done while dependencies are incomplete.\");\n }\n const initialStatus = blockingIds.length > 0 && options?.status !== \"done\"\n ? \"blocked\"\n : (options?.status ?? \"todo\");\n const newTask = {\n id,\n title,\n description,\n status: initialStatus,\n assignee: options?.assignee,\n priority,\n tags: options?.tags,\n type: options?.type,\n estimate_hours: options?.estimate_hours,\n depends_on: options?.depends_on,\n blocked_by: options?.blocked_by,\n recurrence_rule: options?.recurrence_rule,\n owner_id: options?.owner_id,\n reviewer_id: options?.reviewer_id,\n parent_id: options?.parent_id,\n subtask_order: options?.subtask_order,\n due_at: options?.due_at,\n task_context: options?.task_context,\n task_context_summary: options?.task_context_summary,\n evidence: options?.evidence,\n validation_steps: options?.validation_steps,\n created_at: timestamp,\n updated_at: timestamp,\n actions: [\n {\n type: \"create\",\n reasoning: reasoning ?? null,\n actor: options?.actor ?? null,\n created_at: timestamp,\n },\n ],\n };\n await storage.save(newTask);\n await index.updateEntry({\n id: newTask.id,\n title: newTask.title,\n status: newTask.status,\n assignee: newTask.assignee,\n priority: newTask.priority,\n updated_at: newTask.updated_at,\n });\n return newTask;\n }\n async updateTask(id, patch) {\n return this.updateTaskInternal(id, patch);\n }\n async updateTaskInternal(id, patch) {\n const { actor, ...taskPatch } = patch;\n const { storage, index } = await this.init();\n const currentTask = await storage.load(id);\n if (!currentTask) {\n throw new Error(`Task ${id} not found`);\n }\n const normalizeEvidence = (value) => value?.map((entry) => entry.trim()).filter(Boolean);\n const normalizeText = (value) => {\n if (value === undefined)\n return undefined;\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n };\n const hasOwn = (key) => Object.hasOwn(taskPatch, key);\n const normalizeStringArray = (value) => {\n if (!value)\n return value;\n return value.map((entry) => entry.trim()).filter(Boolean);\n };\n const statusProvided = taskPatch.status !== undefined;\n const tagsProvided = hasOwn(\"tags\");\n const dependsProvided = hasOwn(\"depends_on\");\n const blockedProvided = hasOwn(\"blocked_by\");\n const deletedProvided = hasOwn(\"deleted_at\");\n const validationProvided = hasOwn(\"validation_steps\");\n const nextStatus = taskPatch.status ?? currentTask.status;\n const nextPriority = taskPatch.priority ?? currentTask.priority;\n const nextEvidence = normalizeEvidence(taskPatch.evidence) ?? currentTask.evidence;\n const nextTags = tagsProvided\n ? (normalizeStringArray(taskPatch.tags) ?? [])\n : currentTask.tags;\n const nextType = taskPatch.type ?? currentTask.type;\n const nextEstimate = taskPatch.estimate_hours ?? currentTask.estimate_hours;\n const nextDependsOn = dependsProvided\n ? (normalizeStringArray(taskPatch.depends_on) ?? [])\n : currentTask.depends_on;\n const nextBlockedBy = blockedProvided\n ? (normalizeStringArray(taskPatch.blocked_by) ?? [])\n : currentTask.blocked_by;\n const nextRecurrence = taskPatch.recurrence_rule ?? currentTask.recurrence_rule;\n const nextOwner = taskPatch.owner_id ?? currentTask.owner_id;\n const nextReviewer = taskPatch.reviewer_id ?? currentTask.reviewer_id;\n const taskContextProvided = taskPatch.task_context !== undefined;\n const taskContextSummaryProvided = taskPatch.task_context_summary !== undefined;\n const nextTaskContext = taskContextProvided\n ? normalizeText(taskPatch.task_context)\n : currentTask.task_context;\n let nextTaskContextSummary = taskContextSummaryProvided\n ? normalizeText(taskPatch.task_context_summary)\n : currentTask.task_context_summary;\n const nextValidationSteps = validationProvided\n ? (normalizeStringArray(taskPatch.validation_steps) ?? [])\n : currentTask.validation_steps;\n const blockingIds = await this.getBlockingIds(nextDependsOn, nextBlockedBy, storage);\n const hasBlocking = blockingIds.length > 0;\n if (nextStatus === \"done\" && hasBlocking) {\n throw new Error(\"Cannot mark task as done while dependencies are incomplete.\");\n }\n let effectiveStatus = nextStatus;\n if (hasBlocking) {\n effectiveStatus = \"blocked\";\n }\n else if (!statusProvided && currentTask.status === \"blocked\") {\n effectiveStatus = \"todo\";\n }\n if (effectiveStatus === \"done\" && currentTask.status !== \"done\") {\n if (!taskPatch.reasoning) {\n throw new Error(\"Reasoning is required to mark a task as done.\");\n }\n if (!nextEvidence || nextEvidence.length === 0) {\n throw new Error(\"Evidence is required to mark a task as done. Provide file paths or verification commands.\");\n }\n if (nextValidationSteps && nextValidationSteps.length > 0) {\n const evidenceBlob = nextEvidence.join(\" \").toLowerCase();\n const missing = nextValidationSteps.filter((step) => !evidenceBlob.includes(step.toLowerCase()));\n if (missing.length > 0) {\n throw new Error(`Missing validation evidence for: ${missing.join(\", \")}.`);\n }\n }\n }\n const actions = currentTask.actions || [];\n const timestamp = new Date().toISOString();\n const actorValue = actor?.trim() || undefined;\n if (effectiveStatus !== currentTask.status) {\n actions.push({\n type: effectiveStatus === \"done\" ? \"completion\" : \"update_status\",\n reasoning: taskPatch.reasoning ?? null,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n else if (nextPriority !== currentTask.priority) {\n actions.push({\n type: \"update_priority\",\n reasoning: taskPatch.reasoning ?? null,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n else if (taskPatch.reasoning) {\n actions.push({\n type: \"comment\",\n reasoning: taskPatch.reasoning,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n if (tagsProvided) {\n const prevTags = currentTask.tags ?? [];\n const next = nextTags ?? [];\n if (prevTags.join(\"|\") !== next.join(\"|\")) {\n actions.push({\n type: \"update_tags\",\n reasoning: taskPatch.reasoning ?? null,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n }\n if (nextType !== currentTask.type) {\n actions.push({\n type: \"update_type\",\n reasoning: taskPatch.reasoning ?? null,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n if (nextEstimate !== currentTask.estimate_hours) {\n actions.push({\n type: \"update_estimate\",\n reasoning: taskPatch.reasoning ?? null,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n if (dependsProvided || blockedProvided) {\n const prevDepends = currentTask.depends_on ?? [];\n const prevBlocked = currentTask.blocked_by ?? [];\n const nextDepends = nextDependsOn ?? [];\n const nextBlocked = nextBlockedBy ?? [];\n if (prevDepends.join(\"|\") !== nextDepends.join(\"|\") ||\n prevBlocked.join(\"|\") !== nextBlocked.join(\"|\")) {\n actions.push({\n type: \"update_dependencies\",\n reasoning: taskPatch.reasoning ?? null,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n }\n if (nextRecurrence !== currentTask.recurrence_rule) {\n actions.push({\n type: \"update_recurrence\",\n reasoning: taskPatch.reasoning ?? null,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n if (nextOwner !== currentTask.owner_id) {\n actions.push({\n type: \"update_owner\",\n reasoning: taskPatch.reasoning ?? null,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n if (nextReviewer !== currentTask.reviewer_id) {\n actions.push({\n type: \"update_reviewer\",\n reasoning: taskPatch.reasoning ?? null,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n if (deletedProvided && taskPatch.deleted_at !== currentTask.deleted_at) {\n actions.push({\n type: \"delete\",\n reasoning: taskPatch.reasoning ?? null,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n let finalTaskContext = nextTaskContext;\n if (effectiveStatus === \"done\" && finalTaskContext) {\n if (!nextTaskContextSummary) {\n nextTaskContextSummary = summarizeTaskContext(finalTaskContext);\n }\n finalTaskContext = undefined;\n }\n const updatedTask = {\n ...currentTask,\n ...taskPatch,\n status: effectiveStatus,\n tags: nextTags,\n type: nextType,\n estimate_hours: nextEstimate,\n depends_on: nextDependsOn,\n blocked_by: nextBlockedBy,\n recurrence_rule: nextRecurrence,\n owner_id: nextOwner,\n reviewer_id: nextReviewer,\n evidence: nextEvidence,\n task_context: finalTaskContext,\n task_context_summary: nextTaskContextSummary,\n validation_steps: nextValidationSteps,\n actions,\n updated_at: timestamp,\n };\n // @ts-expect-error\n delete updatedTask.reasoning;\n // @ts-expect-error\n delete updatedTask.actor;\n await storage.save(updatedTask);\n await index.updateEntry({\n id: updatedTask.id,\n title: updatedTask.title,\n status: updatedTask.status,\n assignee: updatedTask.assignee,\n priority: updatedTask.priority,\n updated_at: updatedTask.updated_at,\n });\n if (updatedTask.parent_id) {\n await this.syncParentStatus(updatedTask.parent_id, storage);\n }\n return updatedTask;\n }\n async syncParentStatus(parentId, storage) {\n const parent = await storage.load(parentId);\n if (!parent)\n return;\n const allTasks = await storage.loadAll();\n const subtasks = allTasks.filter((task) => task.parent_id === parentId && !task.deleted_at);\n if (subtasks.length === 0)\n return;\n const allDone = subtasks.every((task) => task.status === \"done\");\n if (allDone) {\n if (parent.status === \"done\")\n return;\n const subtaskIds = subtasks.map((task) => task.id).join(\", \");\n await this.updateTaskInternal(parentId, {\n status: \"done\",\n reasoning: \"Auto-completed because all subtasks are done.\",\n evidence: [`Subtasks completed: ${subtaskIds}`],\n });\n return;\n }\n if (parent.status !== \"done\")\n return;\n await this.updateTaskInternal(parentId, {\n status: \"in-progress\",\n reasoning: \"Auto-reopened because a subtask is not done.\",\n });\n }\n async getBlockingIds(dependsOn, blockedBy, storage) {\n const blockers = new Set();\n const ids = [...(dependsOn ?? []), ...(blockedBy ?? [])].filter(Boolean);\n if (ids.length === 0)\n return [];\n for (const id of ids) {\n const task = await storage.load(id);\n if (!task || task.deleted_at || task.status !== \"done\") {\n blockers.add(id);\n }\n }\n return Array.from(blockers);\n }\n async archiveTasks(options) {\n const { storage, index } = await this.init();\n const entries = await index.load();\n if (!options.status && options.olderThanDays === undefined) {\n throw new Error(\"Must provide at least one filter (status or olderThanDays)\");\n }\n const now = new Date();\n const threshold = options.olderThanDays !== undefined\n ? new Date(now.getTime() - options.olderThanDays * 24 * 60 * 60 * 1000)\n : null;\n const candidates = entries.filter((entry) => {\n let matches = true;\n if (options.status) {\n matches = matches && entry.status === options.status;\n }\n if (threshold && entry.updated_at) {\n matches = matches && new Date(entry.updated_at) < threshold;\n }\n return matches;\n });\n if (candidates.length === 0)\n return 0;\n const vemDir = await getVemDir();\n const baseDir = path.join(vemDir, TASKS_DIR);\n const archiveBase = path.join(baseDir, \"archive\");\n await fs.ensureDir(archiveBase);\n let count = 0;\n for (const entry of candidates) {\n const task = await storage.load(entry.id);\n if (task) {\n const date = new Date(task.created_at || new Date());\n const folder = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, \"0\")}`;\n const targetDir = path.join(archiveBase, folder);\n await fs.ensureDir(targetDir);\n const destWithId = path.join(targetDir, `${task.id}.json`);\n await fs.writeJson(destWithId, task, { spaces: 2 });\n // Remove from active storage and index\n await storage.delete(entry.id);\n await index.removeEntry(entry.id);\n count++;\n }\n }\n return count;\n }\n}\n","import crypto from \"node:crypto\";\nimport path from \"node:path\";\nimport fs from \"fs-extra\";\nexport class ShardedFileStorage {\n baseDir;\n objectsDirName;\n constructor(baseDir, objectsDirName = \"objects\") {\n this.baseDir = baseDir;\n this.objectsDirName = objectsDirName;\n }\n getObjectsDir() {\n return path.join(this.baseDir, this.objectsDirName);\n }\n getShard(id) {\n const hash = crypto.createHash(\"sha1\").update(id).digest(\"hex\");\n return hash.substring(0, 2);\n }\n getFilePath(id) {\n const shard = this.getShard(id);\n return path.join(this.getObjectsDir(), shard, `${id}.json`);\n }\n async save(record) {\n const filePath = this.getFilePath(record.id);\n await fs.ensureDir(path.dirname(filePath));\n await fs.writeJson(filePath, record, { spaces: 2 });\n }\n async load(id) {\n const filePath = this.getFilePath(id);\n if (!(await fs.pathExists(filePath))) {\n return null;\n }\n return fs.readJson(filePath);\n }\n async delete(id) {\n const filePath = this.getFilePath(id);\n if (await fs.pathExists(filePath)) {\n await fs.remove(filePath);\n }\n }\n async listIds() {\n const objectsDir = this.getObjectsDir();\n if (!(await fs.pathExists(objectsDir))) {\n return [];\n }\n const shards = await fs.readdir(objectsDir);\n const ids = [];\n for (const shard of shards) {\n const shardPath = path.join(objectsDir, shard);\n const stat = await fs.stat(shardPath);\n if (!stat.isDirectory())\n continue;\n const files = await fs.readdir(shardPath);\n for (const file of files) {\n if (file.endsWith(\".json\")) {\n ids.push(path.parse(file).name);\n }\n }\n }\n return ids;\n }\n async loadAll() {\n const ids = await this.listIds();\n const result = [];\n for (const id of ids) {\n const record = await this.load(id);\n if (record) {\n result.push(record);\n }\n }\n return result;\n }\n}\nexport class TaskIndex {\n indexPath;\n constructor(baseDir) {\n this.indexPath = path.join(baseDir, \"index.json\");\n }\n async load() {\n if (!(await fs.pathExists(this.indexPath))) {\n return [];\n }\n try {\n const data = await fs.readJson(this.indexPath);\n return data.entries || [];\n }\n catch {\n return [];\n }\n }\n async save(entries) {\n await fs.ensureDir(path.dirname(this.indexPath));\n await fs.writeJson(this.indexPath, { entries }, { spaces: 2 });\n }\n async updateEntry(entry) {\n const entries = await this.load();\n const index = entries.findIndex((e) => e.id === entry.id);\n if (index !== -1) {\n entries[index] = entry;\n }\n else {\n entries.push(entry);\n }\n await this.save(entries);\n }\n async removeEntry(id) {\n const entries = await this.load();\n const filtered = entries.filter((e) => e.id !== id);\n await this.save(filtered);\n }\n}\n","/** Convert a CopilotSession / CopilotSessionDetail to the unified AgentSession shape. */\nexport function fromCopilotSession(s) {\n return {\n id: s.id,\n source: \"copilot\",\n summary: s.summary,\n branch: s.branch,\n repository: s.repository,\n git_root: s.git_root,\n cwd: s.cwd,\n created_at: s.created_at,\n updated_at: s.updated_at,\n intents: \"intents\" in s ? s.intents : [],\n user_messages: \"user_messages\" in s ? s.user_messages : [],\n };\n}\n/**\n * List agent sessions from all supported tools (Copilot, Claude, Gemini),\n * optionally filtered to the given git root, sorted newest-first.\n */\nexport async function listAllAgentSessions(gitRoot, sources = [\"copilot\", \"claude\", \"gemini\"]) {\n const [{ listCopilotSessions }, { listClaudeSessions }, { listGeminiSessions },] = await Promise.all([\n import(\"./copilot-sessions.js\"),\n import(\"./claude-sessions.js\"),\n import(\"./gemini-sessions.js\"),\n ]);\n const results = await Promise.all([\n sources.includes(\"copilot\")\n ? listCopilotSessions(gitRoot).then((ss) => ss.map(fromCopilotSession))\n : Promise.resolve([]),\n sources.includes(\"claude\")\n ? listClaudeSessions(gitRoot)\n : Promise.resolve([]),\n sources.includes(\"gemini\")\n ? listGeminiSessions(gitRoot)\n : Promise.resolve([]),\n ]);\n const all = results.flat();\n all.sort((a, b) => {\n if (!a.updated_at)\n return 1;\n if (!b.updated_at)\n return -1;\n return b.updated_at.localeCompare(a.updated_at);\n });\n return all;\n}\n/**\n * Compute statistics for a session from any supported agent tool.\n * Returns null if stats cannot be computed.\n */\nexport async function computeSessionStats(sessionId, source) {\n const { computeCopilotSessionStats } = await import(\"./copilot-sessions.js\");\n const { computeClaudeSessionStats } = await import(\"./claude-sessions.js\");\n const { computeGeminiSessionStats } = await import(\"./gemini-sessions.js\");\n switch (source) {\n case \"copilot\":\n return computeCopilotSessionStats(sessionId);\n case \"claude\":\n return computeClaudeSessionStats(sessionId);\n case \"gemini\":\n return computeGeminiSessionStats(sessionId);\n default:\n return null;\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport { homedir, hostname } from \"node:os\";\nimport path from \"node:path\";\nimport fs from \"fs-extra\";\nimport { CONTEXT_FILE, DECISIONS_DIR, getVemDir } from \"./fs.js\";\nimport { getGitHeadHash } from \"./git.js\";\nimport { ScalableLogService } from \"./logs.js\";\nexport const CONFIG_FILE = \"config.json\";\nexport class ConfigService {\n async getLocalPath() {\n const dir = await getVemDir();\n return path.join(dir, CONFIG_FILE);\n }\n getGlobalPath() {\n return path.join(homedir(), \".vem\", CONFIG_FILE);\n }\n async readLocalConfig() {\n try {\n // If we are not in a repo, getLocalPath might throw or we just catch it here\n const filePath = await this.getLocalPath();\n if (!(await fs.pathExists(filePath)))\n return {};\n return fs.readJson(filePath);\n }\n catch {\n // Ignore error (e.g. not in a repo), return empty local config\n return {};\n }\n }\n async readGlobalConfig() {\n try {\n const filePath = this.getGlobalPath();\n if (!(await fs.pathExists(filePath)))\n return {};\n return fs.readJson(filePath);\n }\n catch {\n return {};\n }\n }\n async writeLocalConfig(update) {\n const filePath = await this.getLocalPath();\n const current = await this.readLocalConfig();\n const next = { ...current, ...update };\n // Only write valid local keys to local config\n const clean = {\n last_version: next.last_version,\n project_id: next.project_id,\n project_org_id: next.project_org_id,\n linked_remote_name: next.linked_remote_name,\n linked_remote_url: next.linked_remote_url,\n last_push_git_hash: next.last_push_git_hash,\n last_push_vem_hash: next.last_push_vem_hash,\n last_synced_vem_hash: next.last_synced_vem_hash,\n };\n await fs.outputJson(filePath, clean, { spaces: 2 });\n }\n async writeGlobalConfig(update) {\n const filePath = this.getGlobalPath();\n const current = await this.readGlobalConfig();\n const next = { ...current, ...update };\n // Only write valid global keys to global config\n const clean = {\n api_key: next.api_key,\n device_id: next.device_id,\n device_name: next.device_name,\n };\n await fs.outputJson(filePath, clean, { spaces: 2 });\n }\n // --- Global Scoped ---\n async getApiKey() {\n const config = await this.readGlobalConfig();\n return config.api_key || process.env.VEM_API_KEY;\n }\n async getDeviceId() {\n const config = await this.readGlobalConfig();\n return config.device_id;\n }\n async getOrCreateDeviceId() {\n const config = await this.readGlobalConfig();\n if (config.device_id && config.device_name) {\n return { deviceId: config.device_id, deviceName: config.device_name };\n }\n let deviceId = config.device_id;\n if (!deviceId) {\n deviceId = randomUUID();\n }\n let deviceName = config.device_name;\n if (!deviceName) {\n deviceName = hostname();\n }\n await this.writeGlobalConfig({\n device_id: deviceId,\n device_name: deviceName,\n });\n return { deviceId, deviceName };\n }\n async setApiKey(key) {\n await this.writeGlobalConfig({ api_key: key || undefined });\n }\n // --- Local Scoped ---\n async getProjectId() {\n const config = await this.readLocalConfig();\n return config.project_id || process.env.VEM_PROJECT_ID;\n }\n async getProjectOrgId() {\n const config = await this.readLocalConfig();\n return config.project_org_id;\n }\n async getLinkedRemoteName() {\n const config = await this.readLocalConfig();\n return config.linked_remote_name;\n }\n async getLinkedRemoteUrl() {\n const config = await this.readLocalConfig();\n return config.linked_remote_url;\n }\n async getLastVersion() {\n const config = await this.readLocalConfig();\n return config.last_version;\n }\n async setLastVersion(version) {\n await this.writeLocalConfig({ last_version: version });\n }\n async getLastPushState() {\n const config = await this.readLocalConfig();\n return {\n gitHash: config.last_push_git_hash,\n vemHash: config.last_push_vem_hash,\n };\n }\n async setLastPushState(state) {\n await this.writeLocalConfig({\n last_push_git_hash: state.gitHash,\n last_push_vem_hash: state.vemHash,\n });\n }\n async getLastSyncedVemHash() {\n const config = await this.readLocalConfig();\n return config.last_synced_vem_hash;\n }\n async setLastSyncedVemHash(vemHash) {\n await this.writeLocalConfig({\n last_synced_vem_hash: vemHash || undefined,\n });\n }\n async setProjectId(projectId) {\n await this.writeLocalConfig({ project_id: projectId || undefined });\n }\n async setProjectOrgId(orgId) {\n await this.writeLocalConfig({ project_org_id: orgId || undefined });\n }\n async setLinkedRemote(binding) {\n await this.writeLocalConfig({\n linked_remote_name: binding?.name || undefined,\n linked_remote_url: binding?.url || undefined,\n });\n }\n // --- Context (Local) ---\n async getContextPath() {\n try {\n const dir = await getVemDir();\n return path.join(dir, CONTEXT_FILE);\n }\n catch {\n return \"\";\n }\n }\n async getContext() {\n const filePath = await this.getContextPath();\n if (!filePath || !(await fs.pathExists(filePath))) {\n return \"\";\n }\n return fs.readFile(filePath, \"utf-8\");\n }\n async updateContext(content) {\n const filePath = await this.getContextPath();\n if (!filePath)\n throw new Error(\"Cannot update context: Not in a git repository.\");\n await fs.writeFile(filePath, content, \"utf-8\");\n }\n async recordDecision(title, context, decision, relatedTasks) {\n const decisionsLog = new ScalableLogService(DECISIONS_DIR);\n let entry = `**Decision:** ${decision}\\n\\n**Context:** ${context}`;\n if (relatedTasks && relatedTasks.length > 0) {\n entry = `**Related Tasks:** ${relatedTasks.join(\", \")}\\n\\n${entry}`;\n }\n const commitHash = await getGitHeadHash();\n await decisionsLog.addEntry(title, entry, { commitHash });\n }\n}\n","import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\nimport fs from \"fs-extra\";\nimport { CHANGELOG_DIR, CONTEXT_FILE, CURRENT_STATE_FILE, DECISIONS_DIR, getVemDir, } from \"./fs.js\";\nimport { ScalableLogService } from \"./logs.js\";\nimport { TaskService } from \"./tasks.js\";\nfunction _hashContent(content) {\n return createHash(\"sha256\").update(content).digest(\"hex\").slice(0, 8);\n}\nexport class DiffService {\n async compareWithLastPush(_lastPushData) {\n // For now, we'll implement a simplified version that compares local state\n // In a full implementation, this would fetch from cloud API\n const vemDir = await getVemDir();\n const taskService = new TaskService();\n const tasks = await taskService.getTasks();\n const decisionsService = new ScalableLogService(DECISIONS_DIR);\n const decisions = await decisionsService.getAllEntries();\n const changelogService = new ScalableLogService(CHANGELOG_DIR);\n const changelog = await changelogService.getAllEntries();\n const currentStatePath = path.join(vemDir, CURRENT_STATE_FILE);\n const currentStateExists = await fs.pathExists(currentStatePath);\n const currentStateContent = currentStateExists\n ? await fs.readFile(currentStatePath, \"utf-8\")\n : \"\";\n const contextPath = path.join(vemDir, CONTEXT_FILE);\n const contextExists = await fs.pathExists(contextPath);\n const contextContent = contextExists\n ? await fs.readFile(contextPath, \"utf-8\")\n : \"\";\n // Simplified diff - in real implementation, compare with lastPushData\n // For now, we'll just report what exists locally\n const result = {\n tasks: {\n added: tasks.filter((t) => t.status !== \"done\").map((t) => t.id),\n modified: [],\n deleted: [],\n },\n decisions: {\n added: decisions.map((d) => d.id),\n modified: [],\n deleted: [],\n },\n changelog: {\n added: changelog.map((c) => c.id),\n modified: [],\n deleted: [],\n },\n currentState: {\n changed: currentStateContent.length > 0,\n lineCount: currentStateContent.split(\"\\n\").length,\n },\n context: {\n changed: contextContent.length > 0,\n },\n summary: {\n totalChanges: 0,\n },\n };\n result.summary.totalChanges =\n result.tasks.added.length +\n result.tasks.modified.length +\n result.decisions.added.length +\n result.changelog.added.length +\n (result.currentState.changed ? 1 : 0);\n return result;\n }\n}\n","import path from \"node:path\";\nimport fs from \"fs-extra\";\nimport { ConfigService } from \"./config.js\";\nimport { CHANGELOG_DIR, CONTEXT_FILE, CURRENT_STATE_FILE, DECISIONS_DIR, getRepoRoot, getVemDir, TASKS_DIR, } from \"./fs.js\";\nimport { TaskService } from \"./tasks.js\";\nexport class DoctorService {\n configService = new ConfigService();\n taskService = new TaskService();\n async runAllChecks() {\n const results = [];\n // Authentication checks\n results.push(await this.checkApiKey());\n results.push(await this.checkDeviceId());\n // Project setup checks\n results.push(await this.checkProjectLinked());\n results.push(await this.checkVemDirectory());\n results.push(await this.checkRequiredFiles());\n // Git integration checks\n results.push(await this.checkGitRepository());\n // Data integrity checks\n results.push(await this.checkTaskIntegrity());\n return results;\n }\n async checkApiKey() {\n try {\n const apiKey = await this.configService.getApiKey();\n if (!apiKey) {\n return {\n name: \"API Key\",\n status: \"fail\",\n message: \"API key not configured\",\n fix: \"Run: vem login\",\n autoFixable: false,\n };\n }\n return {\n name: \"API Key\",\n status: \"pass\",\n message: \"API key configured\",\n };\n }\n catch (error) {\n return {\n name: \"API Key\",\n status: \"fail\",\n message: `Error checking API key: ${error.message}`,\n autoFixable: false,\n };\n }\n }\n async checkDeviceId() {\n try {\n const deviceId = await this.configService.getDeviceId();\n if (!deviceId) {\n return {\n name: \"Device ID\",\n status: \"warn\",\n message: \"Device ID not registered (will be created on next operation)\",\n autoFixable: true,\n };\n }\n return {\n name: \"Device ID\",\n status: \"pass\",\n message: \"Device ID registered\",\n };\n }\n catch (error) {\n return {\n name: \"Device ID\",\n status: \"fail\",\n message: `Error checking device ID: ${error.message}`,\n autoFixable: false,\n };\n }\n }\n async checkProjectLinked() {\n try {\n const projectId = await this.configService.getProjectId();\n if (!projectId) {\n return {\n name: \"Project Link\",\n status: \"fail\",\n message: \"Project not linked to cloud\",\n fix: \"Run: vem init\",\n autoFixable: false,\n };\n }\n return {\n name: \"Project Link\",\n status: \"pass\",\n message: `Project linked (${projectId})`,\n };\n }\n catch (error) {\n return {\n name: \"Project Link\",\n status: \"fail\",\n message: `Error checking project link: ${error.message}`,\n autoFixable: false,\n };\n }\n }\n async checkVemDirectory() {\n try {\n const vemDir = await getVemDir();\n const exists = await fs.pathExists(vemDir);\n if (!exists) {\n return {\n name: \".vem Directory\",\n status: \"fail\",\n message: \".vem/ directory does not exist\",\n fix: \"Run: vem init\",\n autoFixable: true,\n };\n }\n // Check subdirectories\n const tasksDir = path.join(vemDir, TASKS_DIR);\n const decisionsDir = path.join(vemDir, DECISIONS_DIR);\n const changelogDir = path.join(vemDir, CHANGELOG_DIR);\n const tasksDirExists = await fs.pathExists(tasksDir);\n const decisionsDirExists = await fs.pathExists(decisionsDir);\n const changelogDirExists = await fs.pathExists(changelogDir);\n if (!tasksDirExists || !decisionsDirExists || !changelogDirExists) {\n return {\n name: \".vem Directory\",\n status: \"warn\",\n message: \"Missing subdirectories in .vem/\",\n fix: \"Run: vem init\",\n autoFixable: true,\n };\n }\n return {\n name: \".vem Directory\",\n status: \"pass\",\n message: \".vem/ directory structure valid\",\n };\n }\n catch (error) {\n return {\n name: \".vem Directory\",\n status: \"fail\",\n message: `Error checking .vem directory: ${error.message}`,\n autoFixable: false,\n };\n }\n }\n async checkRequiredFiles() {\n try {\n const vemDir = await getVemDir();\n const contextPath = path.join(vemDir, CONTEXT_FILE);\n const currentStatePath = path.join(vemDir, CURRENT_STATE_FILE);\n const contextExists = await fs.pathExists(contextPath);\n const currentStateExists = await fs.pathExists(currentStatePath);\n if (!contextExists || !currentStateExists) {\n return {\n name: \"Required Files\",\n status: \"warn\",\n message: \"Missing CONTEXT.md or CURRENT_STATE.md\",\n fix: \"Run: vem init\",\n autoFixable: true,\n };\n }\n return {\n name: \"Required Files\",\n status: \"pass\",\n message: \"All required files present\",\n };\n }\n catch (error) {\n return {\n name: \"Required Files\",\n status: \"fail\",\n message: `Error checking required files: ${error.message}`,\n autoFixable: false,\n };\n }\n }\n async checkGitRepository() {\n try {\n await getRepoRoot();\n return {\n name: \"Git Repository\",\n status: \"pass\",\n message: \"Inside git repository\",\n };\n }\n catch (_error) {\n return {\n name: \"Git Repository\",\n status: \"fail\",\n message: \"Not inside a git repository\",\n autoFixable: false,\n };\n }\n }\n async checkTaskIntegrity() {\n try {\n const tasks = await this.taskService.getTasks();\n // Check for duplicate IDs\n const ids = new Set();\n const duplicates = [];\n for (const task of tasks) {\n if (ids.has(task.id)) {\n duplicates.push(task.id);\n }\n ids.add(task.id);\n }\n if (duplicates.length > 0) {\n return {\n name: \"Task Integrity\",\n status: \"fail\",\n message: `Duplicate task IDs found: ${duplicates.join(\", \")}`,\n autoFixable: false,\n };\n }\n // Check for orphaned references\n const orphanedRefs = [];\n for (const task of tasks) {\n if (task.blocked_by) {\n for (const blockerId of task.blocked_by) {\n if (!ids.has(blockerId)) {\n orphanedRefs.push(`${task.id} references ${blockerId}`);\n }\n }\n }\n }\n if (orphanedRefs.length > 0) {\n return {\n name: \"Task Integrity\",\n status: \"warn\",\n message: `Orphaned task references: ${orphanedRefs[0]}`,\n fix: `Run: vem task update ${orphanedRefs[0].split(\" \")[0]} --blocked-by \"\"`,\n autoFixable: false,\n };\n }\n return {\n name: \"Task Integrity\",\n status: \"pass\",\n message: `All ${tasks.length} tasks valid`,\n };\n }\n catch (error) {\n return {\n name: \"Task Integrity\",\n status: \"fail\",\n message: `Error checking task integrity: ${error.message}`,\n autoFixable: false,\n };\n }\n }\n}\n","import { z } from \"zod\";\n/**\n * Validates environment variables against a schema and exits the process if invalid.\n */\nexport function validateEnv(schema, serviceName) {\n try {\n return schema.parse(process.env);\n }\n catch (error) {\n if (error instanceof z.ZodError) {\n console.error(`\\n❌ Invalid environment variables for ${serviceName}:`);\n for (const issue of error.issues) {\n console.error(` - ${issue.path.join(\".\")}: ${issue.message}`);\n }\n console.error(\"\\nPlease check your .env file or deployment configuration.\\n\");\n process.exit(1);\n }\n throw error;\n }\n}\n/**\n * Common environment variables used across multiple services.\n */\nexport const commonEnvSchema = {\n NODE_ENV: z\n .enum([\"development\", \"production\", \"test\"])\n .default(\"development\"),\n INTERNAL_API_SECRET: z.string().min(1, \"INTERNAL_API_SECRET is required\"),\n DATABASE_URL: z.string().url(\"DATABASE_URL must be a valid URL\"),\n};\n","import { createPrivateKey } from \"node:crypto\";\nconst PEM_BEGIN_PATTERN = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/;\nconst PEM_END_PATTERN = /-----END [A-Z0-9 ]*PRIVATE KEY-----/;\nconst PEM_ANY_PATTERN = /(-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----)([\\s\\S]*?)(-----END [A-Z0-9 ]*PRIVATE KEY-----)/;\nfunction hasPemMarkers(value) {\n return PEM_BEGIN_PATTERN.test(value) && PEM_END_PATTERN.test(value);\n}\nfunction stripWrappingQuotes(value) {\n if (value.length < 2)\n return value;\n const first = value[0];\n const last = value[value.length - 1];\n if ((first === '\"' && last === '\"') || (first === \"'\" && last === \"'\")) {\n return value.slice(1, -1);\n }\n return value;\n}\nfunction normalizeLineBreaks(value) {\n return value\n .replace(/\\\\r\\\\n/g, \"\\n\")\n .replace(/\\\\n/g, \"\\n\")\n .replace(/\\\\r/g, \"\\n\")\n .replace(/\\r\\n/g, \"\\n\")\n .replace(/\\r/g, \"\\n\");\n}\nfunction stripBase64DataPrefix(value) {\n const match = value.match(/^data:[^;]+;base64,(.+)$/i);\n return match ? match[1] : value;\n}\nfunction canonicalizePem(value) {\n const match = value.match(PEM_ANY_PATTERN);\n if (!match)\n return value;\n const [, begin, body, end] = match;\n const compactBody = body.replace(/\\s+/g, \"\");\n if (!compactBody)\n return value;\n const wrappedBody = compactBody.match(/.{1,64}/g)?.join(\"\\n\") ?? compactBody;\n return `${begin}\\n${wrappedBody}\\n${end}\\n`;\n}\nfunction tryDecodeBase64Pem(value) {\n const compact = value.replace(/\\s+/g, \"\");\n if (!compact || compact.length % 4 !== 0)\n return value;\n if (!/^[A-Za-z0-9+/=]+$/.test(compact))\n return value;\n try {\n const decoded = Buffer.from(compact, \"base64\").toString(\"utf8\");\n return hasPemMarkers(decoded) ? decoded : value;\n }\n catch {\n return value;\n }\n}\n/**\n * Accepts common deployment representations for GitHub App private keys:\n * - Raw multiline PEM\n * - PEM with escaped newlines (\\n)\n * - Base64-encoded PEM payload\n */\nexport function normalizeGithubPrivateKey(rawValue) {\n let normalized = normalizeLineBreaks(stripWrappingQuotes(rawValue.trim()));\n if (!hasPemMarkers(normalized)) {\n const maybeBase64 = stripBase64DataPrefix(stripWrappingQuotes(normalized.trim()));\n normalized = normalizeLineBreaks(stripWrappingQuotes(tryDecodeBase64Pem(maybeBase64).trim()));\n }\n normalized = canonicalizePem(normalized);\n if (!hasPemMarkers(normalized)) {\n throw new Error(\"Invalid GH_PRIVATE_KEY format. Expected PEM (raw PEM, escaped \\\\n PEM, or base64-encoded PEM).\");\n }\n if (!normalized.endsWith(\"\\n\")) {\n normalized = `${normalized}\\n`;\n }\n try {\n createPrivateKey(normalized);\n }\n catch (error) {\n throw new Error(`Invalid GH_PRIVATE_KEY content. Parsed as PEM but Node/OpenSSL rejected it: ${String(error?.message ?? error)}`);\n }\n return normalized;\n}\n","import pino from \"pino\";\nconst isDev = process.env.NODE_ENV === \"development\";\nexport const logger = pino({\n level: process.env.LOG_LEVEL || \"info\",\n // GCP Cloud Logging uses 'severity' instead of 'level'\n // We map pino levels to Google Cloud severity levels\n formatters: {\n level(label) {\n return { severity: label.toUpperCase() };\n },\n },\n // In development, we use pino-pretty for readability\n // In production, we want raw JSON for Cloud Logging\n transport: isDev\n ? {\n target: \"pino-pretty\",\n options: {\n colorize: true,\n ignore: \"pid,hostname\",\n translateTime: \"SYS:standard\",\n },\n }\n : undefined,\n serializers: {\n err: pino.stdSerializers.err,\n error: pino.stdSerializers.err,\n },\n redact: {\n paths: [\n \"req.headers.authorization\",\n \"req.headers['x-api-key']\",\n \"*.password\",\n \"*.secret\",\n \"*.token\",\n ],\n remove: true,\n },\n});\n","import { createHash, timingSafeEqual } from \"node:crypto\";\n/**\n * Compares a bearer token against a secret using constant-time comparison.\n * Both values are hashed to a fixed-length digest before comparison so that\n * the comparison time does not leak the secret's length.\n */\nexport function bearerSecretMatches(token, secret) {\n const expected = createHash(\"sha256\").update(secret).digest();\n const actual = createHash(\"sha256\").update(token).digest();\n return timingSafeEqual(actual, expected);\n}\nconst SECRET_PATTERNS = [\n {\n name: \"private_key\",\n regex: /-----BEGIN (?:RSA|EC|DSA|OPENSSH|PGP) PRIVATE KEY-----/g,\n replace: \"[REDACTED:private_key]\",\n },\n {\n name: \"aws_access_key\",\n regex: /\\bAKIA[0-9A-Z]{16}\\b/g,\n replace: \"[REDACTED:aws_access_key]\",\n },\n {\n name: \"aws_secret_key\",\n regex: /\\b(aws_secret_access_key)\\b\\s*[:=]\\s*([A-Za-z0-9/+=]{40})/gi,\n replace: (_match, key) => `${key}=[REDACTED:aws_secret_key]`,\n },\n {\n name: \"github_token\",\n regex: /\\bghp_[A-Za-z0-9]{36}\\b/g,\n replace: \"[REDACTED:github_token]\",\n },\n {\n name: \"github_pat\",\n regex: /\\bgithub_pat_[A-Za-z0-9_]{22,}\\b/g,\n replace: \"[REDACTED:github_pat]\",\n },\n {\n name: \"slack_token\",\n regex: /\\bxox[baprs]-[A-Za-z0-9-]{10,}\\b/g,\n replace: \"[REDACTED:slack_token]\",\n },\n];\nexport function redactSecrets(input) {\n if (!input)\n return input;\n let output = input;\n for (const pattern of SECRET_PATTERNS) {\n if (pattern.regex.test(output)) {\n if (typeof pattern.replace === \"string\") {\n output = output.replace(pattern.regex, pattern.replace);\n }\n else {\n output = output.replace(pattern.regex, pattern.replace);\n }\n }\n pattern.regex.lastIndex = 0;\n }\n return output;\n}\nexport function detectSecrets(input) {\n if (!input)\n return [];\n const matches = new Set();\n for (const pattern of SECRET_PATTERNS) {\n if (pattern.regex.test(input)) {\n matches.add(pattern.name);\n }\n pattern.regex.lastIndex = 0;\n }\n return Array.from(matches);\n}\n","import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\nimport fs from \"fs-extra\";\nimport { CHANGELOG_DIR, CONTEXT_FILE, CURRENT_STATE_FILE, DECISIONS_DIR, getRepoRoot, getVemDir, } from \"./fs.js\";\nimport { ScalableLogService } from \"./logs.js\";\nimport { detectSecrets, redactSecrets } from \"./secrets.js\";\nimport { TaskService } from \"./tasks.js\";\nexport const KNOWN_AGENT_INSTRUCTION_FILES = [\n \"AGENTS.md\",\n \"CLAUDE.md\",\n \"GEMINI.md\",\n \"CURSOR.md\",\n \"copilot-instructions.md\",\n \"COPILOT_INSTRUCTIONS.md\",\n \".github/copilot-instructions.md\",\n];\nconst KNOWN_AGENT_INSTRUCTION_FILE_SET = new Set(KNOWN_AGENT_INSTRUCTION_FILES);\nfunction normalizeInstructionPath(value) {\n if (typeof value !== \"string\")\n return null;\n const normalized = value.trim().replace(/\\\\/g, \"/\");\n if (!normalized)\n return null;\n const collapsed = path.posix.normalize(normalized);\n if (collapsed === \".\" ||\n collapsed === \"..\" ||\n collapsed.startsWith(\"../\") ||\n collapsed.startsWith(\"/\")) {\n return null;\n }\n return KNOWN_AGENT_INSTRUCTION_FILE_SET.has(collapsed) ? collapsed : null;\n}\nconst DEFAULT_AGENT_PACK_OPTIONS = {\n contextMaxChars: 16000,\n currentStateMaxChars: 8000,\n decisionEntryLimit: 8,\n decisionMaxChars: 9000,\n decisionEntryMaxChars: 1200,\n changelogEntryLimit: 12,\n changelogMaxChars: 12000,\n changelogEntryMaxChars: 900,\n activeTaskLimit: 20,\n recentDoneTaskLimit: 5,\n taskTextMaxChars: 600,\n taskEvidenceLimit: 5,\n taskValidationLimit: 8,\n};\nfunction normalizeForSnapshotHash(value) {\n if (typeof value === \"string\") {\n return value.normalize(\"NFC\");\n }\n if (Array.isArray(value)) {\n return value.map((entry) => normalizeForSnapshotHash(entry));\n }\n if (value && typeof value === \"object\") {\n const record = value;\n const normalized = {};\n for (const key of Object.keys(record).sort((a, b) => a.localeCompare(b))) {\n const next = normalizeForSnapshotHash(record[key]);\n if (next !== undefined) {\n normalized[key] = next;\n }\n }\n return normalized;\n }\n if (typeof value === \"number\" && !Number.isFinite(value)) {\n return null;\n }\n return value;\n}\nfunction sortTasksForSnapshotHash(taskList) {\n const sortedTasks = [...taskList.tasks].sort((a, b) => a.id.localeCompare(b.id));\n return { tasks: sortedTasks };\n}\nexport function computeSnapshotHash(payload) {\n const normalizedInstructions = (payload.agent_instructions ?? [])\n .map((entry) => {\n const normalizedPath = normalizeInstructionPath(entry.path);\n if (!normalizedPath)\n return null;\n return {\n path: normalizedPath,\n content: typeof entry.content === \"string\" ? entry.content : \"\",\n };\n })\n .filter((entry) => Boolean(entry))\n .sort((a, b) => a.path.localeCompare(b.path));\n const canonical = normalizeForSnapshotHash({\n tasks: sortTasksForSnapshotHash(payload.tasks),\n context: payload.context,\n decisions: payload.decisions,\n changelog: payload.changelog,\n current_state: payload.current_state,\n agent_instructions: normalizedInstructions,\n });\n return createHash(\"sha256\")\n .update(JSON.stringify(canonical), \"utf8\")\n .digest(\"hex\");\n}\nfunction truncateText(value, maxChars) {\n if (value.length <= maxChars)\n return value;\n return `${value.slice(0, Math.max(0, maxChars - 15)).trimEnd()}\\n...[truncated]`;\n}\nfunction normalizeTaskText(value, maxChars) {\n if (!value)\n return undefined;\n const normalized = value.trim();\n if (!normalized)\n return undefined;\n return truncateText(normalized, maxChars);\n}\nfunction sortByUpdatedAtDesc(tasks) {\n return [...tasks].sort((a, b) => (b.updated_at ?? b.created_at ?? \"\").localeCompare(a.updated_at ?? a.created_at ?? \"\"));\n}\nexport class SyncService {\n taskService = new TaskService();\n decisionsLog = new ScalableLogService(DECISIONS_DIR);\n changelogLog = new ScalableLogService(CHANGELOG_DIR);\n async getQueueDir() {\n const dir = await getVemDir();\n const queueDir = path.join(dir, \"queue\");\n await fs.ensureDir(queueDir);\n return queueDir;\n }\n async getContextPath() {\n const dir = await getVemDir();\n return path.join(dir, CONTEXT_FILE);\n }\n async getCurrentStatePath() {\n const dir = await getVemDir();\n return path.join(dir, CURRENT_STATE_FILE);\n }\n async collectAgentInstructionFiles() {\n const repoRoot = await getRepoRoot();\n const files = [];\n for (const relativePath of KNOWN_AGENT_INSTRUCTION_FILES) {\n const absolutePath = path.join(repoRoot, relativePath);\n if (!(await fs.pathExists(absolutePath)))\n continue;\n const stat = await fs.stat(absolutePath);\n if (!stat.isFile())\n continue;\n const content = await fs.readFile(absolutePath, \"utf-8\");\n files.push({ path: relativePath, content });\n }\n return files;\n }\n async unpackAgentInstructionFiles(entries) {\n if (!Array.isArray(entries) || entries.length === 0)\n return;\n const repoRoot = await getRepoRoot();\n const resolvedRoot = path.resolve(repoRoot);\n for (const entry of entries) {\n const normalizedPath = normalizeInstructionPath(entry?.path);\n if (!normalizedPath)\n continue;\n if (typeof entry.content !== \"string\")\n continue;\n const destination = path.resolve(repoRoot, normalizedPath);\n if (destination !== resolvedRoot &&\n !destination.startsWith(`${resolvedRoot}${path.sep}`)) {\n continue;\n }\n await fs.ensureDir(path.dirname(destination));\n await fs.writeFile(destination, entry.content, \"utf-8\");\n }\n }\n async pack() {\n const tasks = await this.taskService.getTasks();\n const decisions = await this.decisionsLog.getMonolithicContentWithOptions({\n includeCommitHashes: true,\n });\n const changelog = await this.changelogLog.getMonolithicContentWithOptions({\n includeCommitHashes: true,\n });\n const secretMatches = [];\n const addSecretMatch = (path, value) => {\n if (!value)\n return;\n const types = detectSecrets(value);\n if (types.length > 0) {\n secretMatches.push({ path, types });\n }\n };\n const contextPath = await this.getContextPath();\n let context = \"\";\n if (await fs.pathExists(contextPath)) {\n const raw = await fs.readFile(contextPath, \"utf-8\");\n addSecretMatch(\".vem/CONTEXT.md\", raw);\n context = redactSecrets(raw);\n }\n const currentStatePath = await this.getCurrentStatePath();\n let currentState = \"\";\n if (await fs.pathExists(currentStatePath)) {\n const raw = await fs.readFile(currentStatePath, \"utf-8\");\n addSecretMatch(\".vem/CURRENT_STATE.md\", raw);\n currentState = redactSecrets(raw);\n }\n addSecretMatch(\".vem/DECISIONS.md\", decisions);\n addSecretMatch(\".vem/CHANGELOG.md\", changelog);\n const agentInstructions = await this.collectAgentInstructionFiles();\n const redactedAgentInstructions = agentInstructions.map((entry) => {\n addSecretMatch(entry.path, entry.content);\n return {\n path: entry.path,\n content: redactSecrets(entry.content),\n };\n });\n const redactedTasks = {\n tasks: tasks.map((task) => ({\n ...task,\n title: redactSecrets(task.title),\n description: task.description\n ? redactSecrets(task.description)\n : undefined,\n task_context: task.task_context\n ? redactSecrets(task.task_context)\n : undefined,\n task_context_summary: task.task_context_summary\n ? redactSecrets(task.task_context_summary)\n : undefined,\n evidence: task.evidence?.map((entry) => redactSecrets(entry)),\n })),\n };\n for (const task of tasks) {\n const basePath = `.vem/tasks/objects/${task.id}.json`;\n addSecretMatch(`${basePath}#title`, task.title);\n if (task.description) {\n addSecretMatch(`${basePath}#description`, task.description);\n }\n if (task.task_context) {\n addSecretMatch(`${basePath}#task_context`, task.task_context);\n }\n if (task.task_context_summary) {\n addSecretMatch(`${basePath}#task_context_summary`, task.task_context_summary);\n }\n if (task.evidence) {\n task.evidence.forEach((entry, index) => {\n addSecretMatch(`${basePath}#evidence[${index}]`, entry);\n });\n }\n }\n return {\n tasks: redactedTasks,\n context,\n decisions: redactSecrets(decisions),\n changelog: redactSecrets(changelog),\n current_state: currentState,\n agent_instructions: redactedAgentInstructions,\n secret_scan_report: {\n scanned_at: new Date().toISOString(),\n matches: secretMatches,\n total: secretMatches.length,\n },\n };\n }\n async buildCompactLog(log, label, entryLimit, entryMaxChars, totalMaxChars) {\n const entries = await log.getAllEntries();\n if (entries.length === 0)\n return \"\";\n const selected = entries.slice(0, entryLimit);\n const blocks = selected.map((entry) => {\n const body = truncateText(entry.content.trim(), entryMaxChars);\n return `## ${entry.title}\\n**Date:** ${entry.created_at}\\n\\n${body}`;\n });\n const header = `_Showing ${selected.length} of ${entries.length} ${label} entries._`;\n const combined = [header, ...blocks].join(\"\\n\\n---\\n\\n\");\n return truncateText(combined, totalMaxChars);\n }\n buildCompactTaskList(tasks, options) {\n const visibleTasks = tasks.filter((task) => !task.deleted_at);\n const active = sortByUpdatedAtDesc(visibleTasks.filter((task) => task.status !== \"done\")).slice(0, options.activeTaskLimit);\n const recentDone = sortByUpdatedAtDesc(visibleTasks.filter((task) => task.status === \"done\")).slice(0, options.recentDoneTaskLimit);\n const selectedById = new Map();\n for (const task of [...active, ...recentDone]) {\n selectedById.set(task.id, task);\n }\n return {\n tasks: Array.from(selectedById.values()).map((task) => ({\n id: task.id,\n title: task.title,\n status: task.status,\n priority: task.priority,\n assignee: task.assignee,\n type: task.type,\n description: normalizeTaskText(task.description, options.taskTextMaxChars),\n task_context_summary: normalizeTaskText(task.task_context_summary, options.taskTextMaxChars),\n evidence: task.evidence\n ?.slice(0, options.taskEvidenceLimit)\n .map((entry) => truncateText(entry, options.taskTextMaxChars)),\n validation_steps: task.validation_steps?.slice(0, options.taskValidationLimit),\n depends_on: task.depends_on,\n blocked_by: task.blocked_by,\n created_at: task.created_at,\n updated_at: task.updated_at,\n due_at: task.due_at,\n })),\n };\n }\n async packForAgent(options = {}) {\n const merged = {\n ...DEFAULT_AGENT_PACK_OPTIONS,\n ...options,\n };\n const full = await this.pack();\n const compactTasks = this.buildCompactTaskList(full.tasks.tasks, merged);\n const compactDecisions = await this.buildCompactLog(this.decisionsLog, \"decision\", merged.decisionEntryLimit, merged.decisionEntryMaxChars, merged.decisionMaxChars);\n const compactChangelog = await this.buildCompactLog(this.changelogLog, \"changelog\", merged.changelogEntryLimit, merged.changelogEntryMaxChars, merged.changelogMaxChars);\n return {\n ...full,\n tasks: compactTasks,\n context: truncateText(full.context, merged.contextMaxChars),\n current_state: truncateText(full.current_state, merged.currentStateMaxChars),\n decisions: compactDecisions,\n changelog: compactChangelog,\n };\n }\n async unpack(payload) {\n const vemDir = await getVemDir();\n await fs.ensureDir(vemDir);\n // Unpack tasks to sharded storage\n // Note: This replaces all local tasks with payload tasks.\n // For a real sync, we might want a merge strategy.\n const { storage, index } = await this.taskService.init();\n const taskIds = await storage.listIds();\n for (const id of taskIds) {\n await storage.delete(id);\n }\n const newIndexEntries = [];\n for (const task of payload.tasks.tasks) {\n await storage.save(task);\n newIndexEntries.push({\n id: task.id,\n title: task.title,\n status: task.status,\n assignee: task.assignee,\n priority: task.priority,\n updated_at: task.updated_at,\n });\n }\n await index.save(newIndexEntries);\n const contextPath = await this.getContextPath();\n await fs.writeFile(contextPath, payload.context, \"utf-8\");\n // Logs are harder to \"unpack\" because they are split.\n // For now, we'll just save the monolithic blob as a \"Sync-Import\" entry if it differs significantly,\n // or just rewrite the directory if we assume the server is the source of truth.\n // Given the requirement, let's just make sure they are accessible.\n // Simplified: just save as legacy files if we can't easily split back?\n // No, let's just create one big entry for the import if there's no better way.\n if (payload.decisions) {\n await this.decisionsLog.addEntry(\"Imported from Sync\", payload.decisions);\n }\n if (payload.changelog) {\n await this.changelogLog.addEntry(\"Imported from Sync\", payload.changelog);\n }\n const currentStatePath = await this.getCurrentStatePath();\n await fs.writeFile(currentStatePath, payload.current_state ?? \"\", \"utf-8\");\n await this.unpackAgentInstructionFiles(payload.agent_instructions);\n }\n async enqueue(payload) {\n const queueDir = await this.getQueueDir();\n const id = `${Date.now()}-${Math.random().toString(36).substring(2, 9)}.json`;\n const filePath = path.join(queueDir, id);\n await fs.writeJson(filePath, payload, { spaces: 2 });\n return id;\n }\n async getQueue() {\n const queueDir = await this.getQueueDir();\n const files = await fs.readdir(queueDir);\n const queue = [];\n for (const file of files) {\n if (file.endsWith(\".json\")) {\n try {\n const payload = await fs.readJson(path.join(queueDir, file));\n queue.push({ id: file, payload });\n }\n catch (error) {\n console.error(`Error reading queued snapshot ${file}:`, error);\n }\n }\n }\n return queue.sort((a, b) => a.id.localeCompare(b.id));\n }\n async removeFromQueue(id) {\n const queueDir = await this.getQueueDir();\n const filePath = path.join(queueDir, id);\n if (await fs.pathExists(filePath)) {\n await fs.remove(filePath);\n }\n }\n}\n","import { join } from \"node:path\";\nimport fs from \"fs-extra\";\nimport { getVemDir } from \"./fs.js\";\n/**\n * Service for tracking CLI usage metrics and calculating power scores\n */\nexport class UsageMetricsService {\n metricsPath = null;\n baseDir;\n /**\n * Power score weights for various features\n */\n static POWER_SCORES = {\n agent: 30,\n strict_memory: 20,\n task_driven: 20,\n finalize: 15,\n search: 10,\n ask: 10,\n archive: 5,\n };\n static DEFAULT_SYNC_INTERVAL_MS = 5 * 60 * 1000;\n static DEFAULT_SYNC_TIMEOUT_MS = 7000;\n constructor(baseDir) {\n this.baseDir = baseDir;\n if (baseDir) {\n this.metricsPath = join(baseDir, \".usage-metrics.json\");\n }\n }\n async getMetricsPath() {\n if (this.metricsPath) {\n return this.metricsPath;\n }\n const vemDir = await getVemDir();\n this.metricsPath = join(vemDir, \".usage-metrics.json\");\n return this.metricsPath;\n }\n /**\n * Track a command execution\n */\n async trackCommand(command) {\n try {\n const data = await this.loadMetrics();\n // Increment command count\n data.commandCounts[command] = (data.commandCounts[command] || 0) + 1;\n // Update special timestamps\n if (command === \"agent\") {\n data.lastAgentRun = Date.now();\n }\n else if (command === \"push\") {\n data.lastPush = Date.now();\n }\n await this.saveMetrics(data);\n }\n catch (_error) {\n // Silently fail - metrics shouldn't break CLI\n // In production, we might want to log this error\n }\n }\n /**\n * Track a feature flag usage\n */\n async trackFeature(feature) {\n try {\n const data = await this.loadMetrics();\n data.featureFlags[feature] = true;\n await this.saveMetrics(data);\n }\n catch (_error) {\n // Silently fail - metrics shouldn't break CLI\n }\n }\n /**\n * Check if a feature has been used\n */\n async hasUsedFeature(feature) {\n try {\n const data = await this.loadMetrics();\n return (data.commandCounts[feature] > 0 || data.featureFlags[feature] === true);\n }\n catch (_error) {\n // Silently fail - metrics shouldn't break CLI\n return false;\n }\n }\n /**\n * Get usage statistics including power score\n */\n async getStats() {\n try {\n const data = await this.loadMetrics();\n const powerScore = this.calculatePowerScore(data);\n const totalCommands = Object.values(data.commandCounts).reduce((sum, count) => sum + count, 0);\n return {\n commandCounts: data.commandCounts,\n featureFlags: data.featureFlags,\n lastAgentRun: data.lastAgentRun,\n lastPush: data.lastPush,\n powerScore,\n totalCommands,\n };\n }\n catch (_error) {\n // Return empty stats on error\n return {\n commandCounts: {},\n featureFlags: {},\n lastAgentRun: null,\n lastPush: null,\n powerScore: 0,\n totalCommands: 0,\n };\n }\n }\n /**\n * Sync usage metrics to cloud API.\n * This is best-effort and should never throw.\n */\n async syncToCloud(options) {\n try {\n if (!this.isCloudSyncEnabled()) {\n return { synced: false, reason: \"disabled_by_privacy\" };\n }\n if (!options.apiUrl || !options.apiKey) {\n return { synced: false, reason: \"missing_credentials\" };\n }\n const data = await this.loadMetrics();\n const stats = await this.getStats();\n const signature = JSON.stringify({\n commandCounts: data.commandCounts,\n featureFlags: data.featureFlags,\n lastAgentRun: data.lastAgentRun,\n lastPush: data.lastPush,\n });\n const now = Date.now();\n const minIntervalMs = options.minIntervalMs ?? UsageMetricsService.DEFAULT_SYNC_INTERVAL_MS;\n if (!options.force) {\n if (data.lastSyncedAt && now - data.lastSyncedAt < minIntervalMs) {\n return { synced: false, reason: \"throttled\" };\n }\n if (data.lastSyncedSignature === signature) {\n return { synced: false, reason: \"unchanged\" };\n }\n }\n const apiUrl = options.apiUrl.replace(/\\/+$/, \"\");\n const endpoint = `${apiUrl}/api/metrics/usage`;\n const timeoutMs = options.timeoutMs ?? UsageMetricsService.DEFAULT_SYNC_TIMEOUT_MS;\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n const events = options.event && (options.event.command || options.event.featureFlag)\n ? [\n {\n command: options.event.command,\n feature_flag: options.event.featureFlag,\n metadata: options.event.metadata,\n timestamp: options.event.timestamp ?? now,\n },\n ]\n : [];\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${options.apiKey}`,\n \"Content-Type\": \"application/json\",\n ...(options.headers ?? {}),\n },\n body: JSON.stringify({\n project_id: options.projectId,\n events,\n stats: {\n commandCounts: stats.commandCounts,\n featureFlags: stats.featureFlags,\n lastAgentRun: stats.lastAgentRun,\n lastPush: stats.lastPush,\n powerScore: stats.powerScore,\n totalCommands: stats.totalCommands,\n },\n }),\n signal: controller.signal,\n }).finally(() => {\n clearTimeout(timeout);\n });\n if (!response.ok) {\n return {\n synced: false,\n reason: `http_${response.status}`,\n };\n }\n data.lastSyncedAt = now;\n data.lastSyncedSignature = signature;\n await this.saveMetrics(data);\n return { synced: true };\n }\n catch {\n return { synced: false, reason: \"network_error\" };\n }\n }\n /**\n * Calculate power score based on feature usage\n */\n calculatePowerScore(data) {\n let score = 0;\n // Add points for commands\n for (const [command, count] of Object.entries(data.commandCounts)) {\n if (count > 0 && UsageMetricsService.POWER_SCORES[command]) {\n score += UsageMetricsService.POWER_SCORES[command];\n }\n }\n // Add points for features\n for (const [feature, enabled] of Object.entries(data.featureFlags)) {\n if (enabled && UsageMetricsService.POWER_SCORES[feature]) {\n score += UsageMetricsService.POWER_SCORES[feature];\n }\n }\n return score;\n }\n /**\n * Load metrics from disk\n */\n async loadMetrics() {\n try {\n const metricsPath = await this.getMetricsPath();\n if (await fs.pathExists(metricsPath)) {\n const content = await fs.readFile(metricsPath, \"utf-8\");\n return JSON.parse(content);\n }\n }\n catch (_error) {\n // If file doesn't exist or is corrupted, return empty data\n }\n return {\n commandCounts: {},\n featureFlags: {},\n lastAgentRun: null,\n lastPush: null,\n lastSyncedAt: null,\n lastSyncedSignature: null,\n };\n }\n /**\n * Save metrics to disk\n */\n async saveMetrics(data) {\n const metricsPath = await this.getMetricsPath();\n await fs.writeFile(metricsPath, JSON.stringify(data, null, 2), \"utf-8\");\n }\n isCloudSyncEnabled() {\n const disabled = (process.env.VEM_DISABLE_METRICS || \"\").toLowerCase();\n if (disabled === \"1\" || disabled === \"true\" || disabled === \"yes\") {\n return false;\n }\n const privacyMode = (process.env.VEM_PRIVACY_MODE || \"\").toLowerCase();\n if (privacyMode === \"strict\" || privacyMode === \"local-only\") {\n return false;\n }\n return true;\n }\n}\n","import crypto from \"node:crypto\";\nimport dns from \"node:dns\";\n/**\n * Returns true if the given IPv4 or IPv6 address falls within a private,\n * loopback, or link-local range that must be blocked to prevent SSRF.\n */\nfunction isPrivateIp(ip) {\n // IPv6 loopback and ULA (fc00::/7 covers fc00:: – fdff::)\n if (ip.includes(\":\")) {\n const normalized = ip.toLowerCase();\n if (normalized === \"::1\")\n return true;\n if (/^fc[0-9a-f]{2}:/i.test(normalized))\n return true;\n if (/^fd[0-9a-f]{2}:/i.test(normalized))\n return true;\n if (/^fe80:/i.test(normalized))\n return true; // link-local\n return false;\n }\n // IPv4\n const parts = ip.split(\".\").map(Number);\n if (parts.length !== 4 || parts.some((p) => Number.isNaN(p)))\n return false;\n const [a, b, _c] = parts;\n return (a === 127 || // 127.0.0.0/8 loopback\n a === 10 || // 10.0.0.0/8 private\n (a === 172 && b >= 16 && b <= 31) || // 172.16.0.0/12 private\n (a === 192 && b === 168) || // 192.168.0.0/16 private\n (a === 169 && b === 254) || // 169.254.0.0/16 link-local / AWS metadata\n (a === 100 && b >= 64 && b <= 127) || // 100.64.0.0/10 CGNAT / Tailscale\n a === 0 // 0.0.0.0/8\n );\n}\nasync function resolveAndValidateWebhookHostname(hostname) {\n const normalizedHost = hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n // Reject bare hostnames that are obviously local before DNS lookup.\n if (normalizedHost === \"localhost\" || normalizedHost === \"0.0.0.0\") {\n throw new Error(\"Webhook URLs must not target private or loopback addresses\");\n }\n let resolvedAddresses;\n try {\n const result = await Promise.race([\n dns.promises.lookup(normalizedHost, { all: true, verbatim: false }),\n new Promise((_, reject) => setTimeout(() => reject(new Error(\"DNS lookup timed out\")), 3000)),\n ]);\n resolvedAddresses = result;\n }\n catch (err) {\n throw new Error(`Webhook URL DNS lookup failed: ${err.message}`);\n }\n if (!Array.isArray(resolvedAddresses) || resolvedAddresses.length === 0) {\n throw new Error(\"Webhook URL DNS lookup failed: no addresses resolved\");\n }\n const privateAddress = resolvedAddresses.find(({ address }) => isPrivateIp(address));\n if (privateAddress) {\n throw new Error(`Webhook URLs must not target private or loopback addresses (resolved to ${privateAddress.address})`);\n }\n}\n/**\n * Validate a webhook URL for SSRF safety.\n * Rejects non-https schemes and resolves the hostname via DNS to block\n * private/loopback IP addresses even when provided through a DNS alias.\n * Throws with a descriptive message if the URL is blocked.\n */\nexport async function validateWebhookUrl(url) {\n let parsed;\n try {\n parsed = new URL(url);\n }\n catch {\n throw new Error(\"Invalid URL\");\n }\n if (parsed.protocol !== \"https:\") {\n throw new Error(\"Webhook URLs must use https\");\n }\n await resolveAndValidateWebhookHostname(parsed.hostname);\n}\nexport class WebhookService {\n /**\n * Detect if a URL is a Slack webhook\n */\n isSlackUrl(url) {\n return url.includes(\"hooks.slack.com/services/\");\n }\n /**\n * Detect if a URL is a Discord webhook\n */\n isDiscordUrl(url) {\n return (url.includes(\"discord.com/api/webhooks/\") ||\n url.includes(\"discordapp.com/api/webhooks/\"));\n }\n /**\n * Get a friendly title for the event\n */\n getEventTitle(event, data) {\n switch (event) {\n case \"task.created\":\n return `🆕 Task Created: ${data.title || \"Unnamed Task\"}`;\n case \"task.started\":\n return `🚀 Task Started: ${data.title || \"Unnamed Task\"}`;\n case \"task.blocked\":\n return `🛑 Task Blocked: ${data.title || \"Unnamed Task\"}`;\n case \"task.completed\":\n return `✅ Task Completed: ${data.title || \"Unnamed Task\"}`;\n case \"task.deleted\":\n return `🗑️ Task Deleted: ${data.title || \"Unnamed Task\"}`;\n case \"snapshot.pushed\":\n return \"📦 New Memory Snapshot Pushed\";\n case \"snapshot.verified\":\n return \"🛡️ Memory Snapshot Verified\";\n case \"snapshot.failed\":\n return \"❌ Memory Snapshot Verification Failed\";\n case \"decision.added\":\n return \"🧠 New Architectural Decision Recorded\";\n case \"changelog.updated\":\n return \"📝 Project Changelog Updated\";\n case \"drift.detected\":\n return \"⚠️ Truth Drift Detected\";\n case \"project.linked\":\n return \"🔗 Project Linked to Repository\";\n default:\n return `VEM Event: ${event}`;\n }\n }\n /**\n * Get theme color for the event\n */\n getEventColor(event) {\n switch (event) {\n case \"task.created\":\n case \"task.started\":\n case \"project.linked\":\n return 0x3b82f6; // Blue\n case \"task.completed\":\n case \"snapshot.verified\":\n return 0x10b981; // Emerald\n case \"task.blocked\":\n case \"drift.detected\":\n return 0xf59e0b; // Amber\n case \"snapshot.failed\":\n case \"task.deleted\":\n return 0xef4444; // Red\n case \"snapshot.pushed\":\n case \"decision.added\":\n case \"changelog.updated\":\n return 0x8b5cf6; // Purple\n default:\n return 0x6b7280; // Gray\n }\n }\n /**\n * Format payload for Slack Block Kit\n */\n formatSlackPayload(payload) {\n const title = this.getEventTitle(payload.event, payload.data);\n const fields = [\n {\n type: \"mrkdwn\",\n text: `*Organization:*\\n${payload.org_id}`,\n },\n ];\n if (payload.project_name) {\n fields.push({\n type: \"mrkdwn\",\n text: `*Project:*\\n${payload.project_name}`,\n });\n }\n // Add event-specific data\n if (payload.event.startsWith(\"task.\")) {\n if (payload.data.task_id) {\n fields.push({\n type: \"mrkdwn\",\n text: `*Task ID:*\\n${payload.data.task_id}`,\n });\n }\n if (payload.data.status) {\n fields.push({\n type: \"mrkdwn\",\n text: `*Status:*\\n${payload.data.status}`,\n });\n }\n }\n const blocks = [\n {\n type: \"header\",\n text: {\n type: \"plain_text\",\n text: title,\n emoji: true,\n },\n },\n {\n type: \"section\",\n fields,\n },\n ];\n // Add link button if available\n if (payload.data.url) {\n blocks.push({\n type: \"actions\",\n elements: [\n {\n type: \"button\",\n text: {\n type: \"plain_text\",\n text: \"View in VEM\",\n emoji: true,\n },\n url: payload.data.url,\n style: payload.event === \"snapshot.failed\" ? \"danger\" : \"primary\",\n },\n ],\n });\n }\n blocks.push({\n type: \"context\",\n elements: [\n {\n type: \"mrkdwn\",\n text: `VEM Webhook • ${new Date(payload.timestamp).toLocaleString()}`,\n },\n ],\n });\n return { blocks };\n }\n /**\n * Format payload for Discord Embeds\n */\n formatDiscordPayload(payload) {\n const title = this.getEventTitle(payload.event, payload.data);\n const color = this.getEventColor(payload.event);\n const fields = [];\n if (payload.project_name) {\n fields.push({\n name: \"Project\",\n value: payload.project_name,\n inline: true,\n });\n }\n // Add event-specific fields\n if (payload.event.startsWith(\"task.\")) {\n if (payload.data.task_id) {\n fields.push({\n name: \"Task ID\",\n value: String(payload.data.task_id),\n inline: true,\n });\n }\n if (payload.data.status) {\n fields.push({\n name: \"Status\",\n value: String(payload.data.status),\n inline: true,\n });\n }\n }\n if (payload.event === \"snapshot.pushed\" ||\n payload.event === \"snapshot.verified\") {\n if (payload.data.git_hash) {\n fields.push({\n name: \"Git Hash\",\n value: `\\`${String(payload.data.git_hash).slice(0, 7)}\\``,\n inline: true,\n });\n }\n }\n return {\n embeds: [\n {\n title,\n url: payload.data.url || undefined,\n color,\n fields,\n footer: {\n text: \"VEM Webhook Notification\",\n },\n timestamp: payload.timestamp,\n },\n ],\n };\n }\n /**\n * Generate HMAC SHA-256 signature for webhook payload\n */\n generateSignature(payload, secret) {\n const body = JSON.stringify(payload);\n const signature = crypto\n .createHmac(\"sha256\", secret)\n .update(body)\n .digest(\"hex\");\n return `sha256=${signature}`;\n }\n /**\n * Deliver a single webhook\n */\n async deliverWebhook(webhook, payload, _attempt = 1) {\n try {\n // Re-validate URL + DNS on every delivery attempt to mitigate rebinding.\n await validateWebhookUrl(webhook.url);\n }\n catch (urlErr) {\n return {\n webhook_id: webhook.id,\n success: false,\n error_message: urlErr.message,\n };\n }\n try {\n const isSlack = this.isSlackUrl(webhook.url);\n const isDiscord = this.isDiscordUrl(webhook.url);\n // Transform payload for Slack/Discord\n let body = payload;\n if (isSlack) {\n body = this.formatSlackPayload(payload);\n }\n else if (isDiscord) {\n body = this.formatDiscordPayload(payload);\n }\n const signature = this.generateSignature(payload, webhook.secret);\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout\n const response = await fetch(webhook.url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Webhook-Signature\": signature,\n \"X-Webhook-Event\": payload.event,\n \"X-Webhook-Delivery\": crypto.randomUUID(),\n \"User-Agent\": \"VEM-Webhooks/1.0\",\n },\n body: JSON.stringify(body),\n signal: controller.signal,\n // Avoid following redirects to an unvalidated destination.\n redirect: \"manual\",\n });\n clearTimeout(timeoutId);\n return {\n webhook_id: webhook.id,\n success: response.ok,\n status_code: response.status,\n error_message: response.ok\n ? undefined\n : `HTTP ${response.status}: ${response.statusText}`,\n };\n }\n catch (error) {\n const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n return {\n webhook_id: webhook.id,\n success: false,\n error_message: errorMessage,\n };\n }\n }\n /**\n * Find and trigger all webhooks subscribed to an event\n * @param findWebhooks - Database query function to find matching webhooks\n * @param recordDelivery - Database insert function to record delivery\n * @param eventType - The event type\n * @param orgId - Organization ID\n * @param projectId - Project ID (null for org-level events)\n * @param data - Event-specific data\n */\n async triggerWebhooks(findWebhooks, recordDelivery, eventType, orgId, projectId, data, projectName) {\n // Find all enabled webhooks subscribed to this event\n const webhooks = await findWebhooks({\n orgId,\n projectId,\n eventType,\n });\n if (webhooks.length === 0) {\n return;\n }\n // Build webhook payload\n const payload = {\n event: eventType,\n timestamp: new Date().toISOString(),\n org_id: orgId,\n project_id: projectId,\n project_name: projectName,\n data,\n };\n // Deliver to all webhooks (don't await - fire and forget for now)\n const deliveryPromises = webhooks.map(async (webhook) => {\n const result = await this.deliverWebhook(webhook, payload, 1);\n // Record delivery in database\n await recordDelivery({\n webhookId: webhook.id,\n eventType,\n payload,\n statusCode: result.status_code,\n success: result.success,\n attempt: 1,\n errorMessage: result.error_message,\n });\n });\n // Don't block on deliveries - they happen in background\n Promise.all(deliveryPromises).catch((err) => {\n console.error(\"[webhook] Unhandled error in webhook delivery batch:\", err);\n });\n }\n}\n"],"mappings":";;;;;;AACA,SAAS,YAAAA,iBAAgB;AACzB,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,SAAS,UAAU,UAAU,iBAAiB;AACvD,SAAS,QAAAC,OAAM,gBAAgB;AAC/B,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC;AAAA,EACC;AAAA,EACA;AAAA,OACM;;;ACVP,OAAOC,WAAU;;;ACAjB,SAAS,SAAS;AACX,IAAM,2BAA2B,EAAE,MAAM;AAAA,EAC5C,EAAE,OAAO;AAAA,EACT,EAAE,OAAO;AAAA,IACL,IAAI,EAAE,OAAO;AAAA,IACb,OAAO,EAAE,OAAO,EAAE,SAAS;AAAA,IAC3B,SAAS,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,CAAC;AACL,CAAC;AACM,IAAM,0BAA0B,EAAE,OAAO;AAAA,EAC5C,UAAU,EAAE,OAAO,EAA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,CAAC,MAAW;AACzE,UAAI,EAAE,OAAO,WAAW;AACvB,eAAO,EAAE,GAAG,GAAG,MAAM;AAAA,MACtB;AACA,aAAO;AAAA,IACR,CAAC;AAGD,UAAM,WAAW,iBAAiB,KAAK,CAAC,MAAW,EAAE,OAAO,SAAS;AACrE,QAAI,CAAC,UAAU;AACd,uBAAiB,KAAK;AAAA,QACrB,IAAI;AAAA,QACJ;AAAA,QACA,YAAY,MAAM,aAAY,oBAAI,KAAK,GAAE,YAAY;AAAA,QACrD;AAAA,MACD,CAAC;AAAA,IACF;AAEA,UAAM,YAAY,WAAWA,SAAQ,EAAE,UAAU,iBAAiB,CAAC;AAEnE,WAAO;AAAA,MACN,SAAS;AAAA,QACR;AAAA,UACC,MAAM;AAAA,UACN,MAAM,2BAA2B,SAAS,YAAYA,OAAM;AAAA,EAAM,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC;AAAA,QACjG;AAAA,MACD;AAAA,IACD;AAAA,EACD;AAEA,QAAM,IAAI,MAAM,mBAAmB,IAAI,EAAE;AAC1C,CAAC;AAED,IAAM,YAAY,IAAI,qBAAqB;AAC3C,MAAM,OAAO,QAAQ,SAAS;","names":["execSync","createHash","join","path","fs","relative","path","fs","path","fs","path","fs","path","fs","path","fs","normalizeEvidence","summarizeTaskContext","taskService","path","fs","path","fs","path","fs","path","fs","path","fs","z","z","createHash","createHash","path","fs","path","path","fs","fs","fs","crypto","execSync","createHash","join","path","data","taskId"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../../../packages/core/dist/agent.js","../../../packages/schemas/dist/index.js","../../../packages/core/dist/fs.js","../../../packages/core/dist/git.js","../../../packages/core/dist/logs.js","../../../packages/core/dist/tasks.js","../../../packages/core/dist/sharded-fs.js","../../../packages/core/dist/agent-sessions.js","../../../packages/core/dist/config.js","../../../packages/core/dist/diff.js","../../../packages/core/dist/doctor.js","../../../packages/core/dist/env.js","../../../packages/core/dist/github-private-key.js","../../../packages/core/dist/logger.js","../../../packages/core/dist/secrets.js","../../../packages/core/dist/sync.js","../../../packages/core/dist/usage-metrics.js","../../../packages/core/dist/webhook.js"],"sourcesContent":["#!/usr/bin/env node\nimport { execSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { readdir, readFile, readlink, writeFile } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n\tCallToolRequestSchema,\n\tListToolsRequestSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport {\n\tapplyVemUpdate,\n\tCHANGELOG_DIR,\n\tConfigService,\n\tCURRENT_STATE_FILE,\n\tcomputeSessionStats,\n\tDECISIONS_DIR,\n\tgetRepoRoot,\n\tgetVemDir,\n\tlistAllAgentSessions,\n\tScalableLogService,\n\tSyncService,\n\tTaskService,\n\tUsageMetricsService,\n} from \"@vem/core\";\n\nconst server = new Server(\n\t{\n\t\tname: \"vem-mcp\",\n\t\tversion: \"0.1.0\",\n\t},\n\t{\n\t\tcapabilities: {\n\t\t\ttools: {},\n\t\t},\n\t},\n);\n\nconst taskService = new TaskService();\nconst configService = new ConfigService();\nconst syncService = new SyncService();\nconst metricsService = new UsageMetricsService();\n\nconst API_URL = process.env.VEM_API_URL || \"http://localhost:3002\";\n\nasync function trackHeartbeat(toolName: string, taskId?: string) {\n\ttry {\n\t\tconst apiKey = await configService.getApiKey();\n\t\tif (!apiKey) return;\n\n\t\tconst projectId = await configService.getProjectId();\n\t\tconst agentName = process.env.VEM_AGENT_NAME || \"mcp-agent\";\n\n\t\tawait metricsService.syncToCloud({\n\t\t\tapiUrl: API_URL,\n\t\t\tapiKey,\n\t\t\tprojectId,\n\t\t\theaders: await buildDeviceHeaders(configService),\n\t\t\tforce: true,\n\t\t\tevent: {\n\t\t\t\tfeatureFlag: \"agent_heartbeat\",\n\t\t\t\tmetadata: {\n\t\t\t\t\tagentName,\n\t\t\t\t\ttaskId,\n\t\t\t\t\tcommand: `mcp:${toolName}`,\n\t\t\t\t},\n\t\t\t},\n\t\t});\n\t} catch {\n\t\t// Silently fail\n\t}\n}\n\n// --- Git helper functions (matching CLI patterns) ---\n\nfunction getGitHash(): string | null {\n\ttry {\n\t\treturn execSync(\"git rev-parse HEAD\").toString().trim() || null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction getGitRemote(): string | null {\n\ttry {\n\t\treturn execSync(\"git remote get-url origin\").toString().trim() || null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction getCommits(limit = 50) {\n\ttry {\n\t\tconst output = execSync(\n\t\t\t`git log -n ${limit} --pretty=format:\"%H|%an|%cI|%s\"`,\n\t\t).toString();\n\t\treturn output\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => {\n\t\t\t\tconst [hash, author, date, ...msgParts] = line.split(\"|\");\n\t\t\t\treturn {\n\t\t\t\t\thash,\n\t\t\t\t\tauthor_name: author,\n\t\t\t\t\tcommitted_at: date,\n\t\t\t\t\tmessage: msgParts.join(\"|\"),\n\t\t\t\t};\n\t\t\t})\n\t\t\t.filter((c) => c.hash && c.message);\n\t} catch {\n\t\treturn [];\n\t}\n}\n\nasync function isVemDirty(): Promise<boolean> {\n\ttry {\n\t\tconst root = await getRepoRoot();\n\t\tconst status = execSync(\"git status --porcelain .vem\", { cwd: root })\n\t\t\t.toString()\n\t\t\t.trim();\n\t\treturn status.length > 0;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nasync function computeVemHash(): Promise<string | null> {\n\ttry {\n\t\tconst vemDir = await getVemDir();\n\t\tconst hash = createHash(\"sha256\");\n\n\t\tconst walk = async (currentDir: string) => {\n\t\t\tconst entries = await readdir(currentDir, { withFileTypes: true });\n\t\t\tentries.sort((a, b) => a.name.localeCompare(b.name));\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (entry.name === \"queue\") continue;\n\t\t\t\tconst fullPath = join(currentDir, entry.name);\n\t\t\t\tconst relPath = relative(vemDir, fullPath).split(\"\\\\\").join(\"/\");\n\t\t\t\tif (\n\t\t\t\t\trelPath === \"queue\" ||\n\t\t\t\t\trelPath.startsWith(\"queue/\") ||\n\t\t\t\t\trelPath === \"config.json\" ||\n\t\t\t\t\trelPath === \"current_context.md\" ||\n\t\t\t\t\trelPath === \"task_context.md\"\n\t\t\t\t) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (entry.isDirectory()) {\n\t\t\t\t\thash.update(`dir:${relPath}\\0`);\n\t\t\t\t\tawait walk(fullPath);\n\t\t\t\t} else if (entry.isFile()) {\n\t\t\t\t\thash.update(`file:${relPath}\\0`);\n\t\t\t\t\tconst data = await readFile(fullPath);\n\t\t\t\t\thash.update(data);\n\t\t\t\t} else if (entry.isSymbolicLink()) {\n\t\t\t\t\tconst target = await readlink(fullPath);\n\t\t\t\t\thash.update(`link:${relPath}\\0${target}\\0`);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tawait walk(vemDir);\n\t\treturn hash.digest(\"hex\");\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction normalizeForSnapshotHash(value: unknown): unknown {\n\tif (typeof value === \"string\") return value.normalize(\"NFC\");\n\tif (Array.isArray(value))\n\t\treturn value.map((entry) => normalizeForSnapshotHash(entry));\n\tif (value && typeof value === \"object\") {\n\t\tconst record = value as Record<string, unknown>;\n\t\tconst normalized: Record<string, unknown> = {};\n\t\tfor (const key of Object.keys(record).sort((a, b) => a.localeCompare(b))) {\n\t\t\tconst next = normalizeForSnapshotHash(record[key]);\n\t\t\tif (next !== undefined) normalized[key] = next;\n\t\t}\n\t\treturn normalized;\n\t}\n\tif (typeof value === \"number\" && !Number.isFinite(value)) return null;\n\treturn value;\n}\n\nfunction computeSnapshotHashFromPayload(snapshot: any): string {\n\tconst sortedTasks = Array.isArray(snapshot?.tasks?.tasks)\n\t\t? [...snapshot.tasks.tasks].sort((a: any, b: any) =>\n\t\t\t\tString(a?.id || \"\").localeCompare(String(b?.id || \"\")),\n\t\t\t)\n\t\t: [];\n\tconst canonical = normalizeForSnapshotHash({\n\t\ttasks: { tasks: sortedTasks },\n\t\tcontext: snapshot?.context || \"\",\n\t\tdecisions: snapshot?.decisions || \"\",\n\t\tchangelog: snapshot?.changelog || \"\",\n\t\tcurrent_state: snapshot?.current_state || \"\",\n\t});\n\treturn createHash(\"sha256\")\n\t\t.update(JSON.stringify(canonical), \"utf8\")\n\t\t.digest(\"hex\");\n}\n\nasync function buildDeviceHeaders(cs: ConfigService) {\n\tconst { deviceId, deviceName } = await cs.getOrCreateDeviceId();\n\tconst projectOrgId = await cs.getProjectOrgId();\n\treturn {\n\t\t\"X-Vem-Device-Id\": deviceId,\n\t\t\"X-Vem-Device-Name\": deviceName,\n\t\t\"X-Vem-Client\": \"mcp-server\",\n\t\t...(projectOrgId ? { \"X-Org-Id\": projectOrgId } : {}),\n\t};\n}\n\nserver.setRequestHandler(ListToolsRequestSchema, async () => {\n\treturn {\n\t\ttools: [\n\t\t\t{\n\t\t\t\tname: \"get_active_tasks\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Get list of VEM tasks from project memory. Use this to know what to do. Defaults to active tasks only.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tstatus: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tenum: [\"todo\", \"in-progress\", \"done\", \"all\"],\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Filter tasks by status. Default is to exclude done tasks.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"get_task_details\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Get detailed information about a specific task by its ID.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: { type: \"string\", description: \"The TASK-XXX id\" },\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"id\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"add_task\",\n\t\t\t\tdescription: \"Add a new task to VEM memory.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\ttitle: { type: \"string\" },\n\t\t\t\t\t\tdescription: { type: \"string\" },\n\t\t\t\t\t\tpriority: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tenum: [\"low\", \"medium\", \"high\", \"critical\"],\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttype: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tenum: [\"feature\", \"bug\", \"chore\"],\n\t\t\t\t\t\t},\n\t\t\t\t\t\tparent_id: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Optional parent task ID\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tvalidation_steps: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: { type: \"string\" },\n\t\t\t\t\t\t\tdescription: \"List of commands or steps to validate completion\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\treasoning: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Reasoning for creating this task.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"title\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"complete_task\",\n\t\t\t\tdescription: \"Mark a task as done in VEM memory.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: { type: \"string\", description: \"The TASK-XXX id\" },\n\t\t\t\t\t\tevidence: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Proof of completion (file path, test command, etc)\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\treasoning: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Why is this task considered done? Explain your reasoning.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"id\", \"evidence\", \"reasoning\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"start_task\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Mark a task as in-progress and attach the current agent session to it. Call this when you start working on a task. Returns the full task object so you can get its context.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The TASK-XXX id to start\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsession_id: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The current agent session ID\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsource: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tenum: [\"copilot\", \"claude\", \"gemini\"],\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Which AI tool is running (copilot | claude | gemini)\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsession_summary: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Optional brief summary of what this session intends to do\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"id\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"get_context\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Read the project's CONTEXT.md and CURRENT_STATE.md. Always call this at the start of a session to load project context.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"list_decisions\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"List architectural decisions recorded in VEM memory. Read these before making significant design choices to avoid conflicts.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tlimit: {\n\t\t\t\t\t\t\ttype: \"number\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Number of recent decisions to return (default: 20, max: 50)\",\n\t\t\t\t\t\t\tdefault: 20,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"update_current_state\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Update CURRENT_STATE.md with a summary of latest progress and next steps. Call this after completing meaningful work.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tcontent: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"The new content for CURRENT_STATE.md (replaces existing content)\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"content\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"search_memory\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Semantic search over project memory (tasks, context, decisions).\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tquery: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"The search query (e.g. 'auth tasks', 'database schema')\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"query\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"ask_question\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Ask a natural language question about the project codebase and memory (commits, diffs, tasks).\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tquestion: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"The question to ask (e.g. 'How does authentication work?')\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tpath: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Optional file path to limit the scope of the search\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"question\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"update_task\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Update a task's status, priority, or other fields. Use this to start working on a task, block it, or update its priority.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The TASK-XXX id\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tenum: [\"todo\", \"in-progress\", \"blocked\"],\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"New status for the task. Use 'in-progress' to start working, 'blocked' to mark as blocked, 'todo' to unblock.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tpriority: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tenum: [\"low\", \"medium\", \"high\", \"critical\"],\n\t\t\t\t\t\t\tdescription: \"New priority for the task.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\treasoning: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Explanation for the update. Required when blocking a task.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tblocked_by: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: { type: \"string\" },\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Task IDs that are blocking this task (when setting status to blocked).\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tvalidation_steps: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: { type: \"string\" },\n\t\t\t\t\t\t\tdescription: \"New list of validation steps (replaces existing)\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"id\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"add_decision\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Record an architectural decision in VEM memory. Use this when making significant technical choices (e.g., choosing libraries, changing architecture, setting patterns).\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\ttitle: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Short decision title (e.g., 'Use Zod for validation')\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Why this decision was needed - the problem or situation\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdecision: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"What was decided and key rationale\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\trelated_tasks: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: { type: \"string\" },\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Optional TASK-XXX references that motivated or implement this decision\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"title\", \"context\", \"decision\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"get_changelog\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Get recent changelog entries from VEM memory. Use this to understand what work has been done recently.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tlimit: {\n\t\t\t\t\t\t\ttype: \"number\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Number of recent entries to return (default: 10, max: 50)\",\n\t\t\t\t\t\t\tdefault: 10,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"delete_task\",\n\t\t\t\tdescription: \"Soft delete a task from VEM memory.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: { type: \"string\", description: \"The TASK-XXX id\" },\n\t\t\t\t\t\treasoning: { type: \"string\", description: \"Reason for deletion\" },\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"id\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"apply_vem_update\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Apply a complete vem_update block containing current_state, context, changelog_append, decisions_append, and task updates.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tcurrent_state: { type: \"string\" },\n\t\t\t\t\t\tcontext: { type: \"string\" },\n\t\t\t\t\t\tchangelog_append: {\n\t\t\t\t\t\t\toneOf: [\n\t\t\t\t\t\t\t\t{ type: \"string\" },\n\t\t\t\t\t\t\t\t{ type: \"array\", items: { type: \"string\" } },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdecisions_append: {\n\t\t\t\t\t\t\toneOf: [\n\t\t\t\t\t\t\t\t{ type: \"string\" },\n\t\t\t\t\t\t\t\t{ type: \"array\", items: { type: \"string\" } },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttasks: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: {\n\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\tid: { type: \"string\" },\n\t\t\t\t\t\t\t\t\tstatus: { type: \"string\" },\n\t\t\t\t\t\t\t\t\treasoning: { type: \"string\" },\n\t\t\t\t\t\t\t\t\tpriority: { type: \"string\" },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\trequired: [\"id\"],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"sync_push\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Push local VEM snapshot to the cloud. Syncs tasks, context, decisions, and changelog to the remote project.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tforce: {\n\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\tdescription: \"Push even if no changes detected since last push.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdry_run: {\n\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Preview what would be pushed without actually pushing.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"sync_pull\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Pull the latest VEM snapshot from the cloud. Updates local tasks, context, decisions, and changelog.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tforce: {\n\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\tdescription: \"Overwrite local changes without warning.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"get_task_context\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Read a task's working context and summary. Use this to retrieve scratchpad notes for a specific task.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The TASK-XXX id\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"id\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"update_task_context\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Set, append to, or clear a task's working context. Use this to maintain scratchpad notes across sessions.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tid: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The TASK-XXX id\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\toperation: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tenum: [\"set\", \"append\", \"clear\"],\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"'set' replaces context, 'append' adds to it, 'clear' removes it.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttext: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"The text content. Required for 'set' and 'append' operations.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"id\", \"operation\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"get_subtasks\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Get a parent task and all its subtasks. Use this to view the task hierarchy.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tparent_id: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The parent TASK-XXX id\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"parent_id\"],\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"list_agent_sessions\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"List recent agent sessions for this repository from Copilot CLI, Claude CLI, and Gemini CLI. Call this at the start of a session to understand what previous sessions worked on and avoid duplicating effort.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tlimit: {\n\t\t\t\t\t\t\ttype: \"number\",\n\t\t\t\t\t\t\tdescription: \"Maximum number of sessions to return (default: 10)\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbranch: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Filter sessions by branch name\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsources: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: { type: \"string\", enum: [\"copilot\", \"claude\", \"gemini\"] },\n\t\t\t\t\t\t\tdescription: \"Which tools to include (default: all three)\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"save_session_stats\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Save statistics for an agent session onto its task. Call this when finishing a task to record session duration, turns, tool calls, and model usage. Stats are computed from the agent's session files.\",\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\ttask_id: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The TASK-XXX id to attach stats to\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsession_id: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"The agent session ID to compute stats for\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsource: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tenum: [\"copilot\", \"claude\", \"gemini\"],\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Which AI tool the session belongs to (default: copilot)\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"task_id\", \"session_id\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t};\n});\n\nserver.setRequestHandler(CallToolRequestSchema, async (request) => {\n\tconst { name, arguments: args } = request.params;\n\n\t// Track heartbeat for every tool call\n\tconst taskId =\n\t\t(args?.id as string) ||\n\t\t(args?.taskId as string) ||\n\t\tprocess.env.VEM_ACTIVE_TASK;\n\tvoid trackHeartbeat(name, taskId);\n\n\tif (name === \"get_active_tasks\") {\n\t\tconst tasks = await taskService.getTasks();\n\t\tconst status = args?.status as string | undefined;\n\n\t\tlet filtered = tasks;\n\t\tif (status === \"all\") {\n\t\t\t// return all\n\t\t} else if (status === \"done\") {\n\t\t\tfiltered = tasks.filter((t) => t.status === \"done\");\n\t\t} else if (status === \"todo\") {\n\t\t\tfiltered = tasks.filter((t) => t.status === \"todo\");\n\t\t} else if (status === \"in-progress\") {\n\t\t\tfiltered = tasks.filter((t) => t.status === \"in-progress\");\n\t\t} else {\n\t\t\t// default: active only (not done)\n\t\t\tfiltered = tasks.filter((t) => t.status !== \"done\");\n\t\t}\n\n\t\t// Annotate tasks that have session history with a handoff hint\n\t\tconst annotated = filtered.map((t) => {\n\t\t\tconst sessions = (t.sessions as any[]) || [];\n\t\t\tif (sessions.length === 0) return t;\n\t\t\tconst last = sessions[sessions.length - 1];\n\t\t\tconst hint = last.summary\n\t\t\t\t? `Last worked by ${last.source} on ${last.started_at.slice(0, 10)}: ${last.summary}`\n\t\t\t\t: `Last worked by ${last.source} on ${last.started_at.slice(0, 10)}`;\n\t\t\treturn { ...t, _last_session_hint: hint };\n\t\t});\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: JSON.stringify(annotated, null, 2),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"get_task_details\") {\n\t\tconst id = args?.id as string;\n\t\tif (!id) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: \"Task ID is required.\" }],\n\t\t\t};\n\t\t}\n\t\tconst task = await taskService.getTask(id);\n\t\tif (!task) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: `Task ${id} not found.` }],\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: JSON.stringify(task, null, 2) }],\n\t\t};\n\t}\n\n\tif (name === \"add_task\") {\n\t\tconst title = args?.title as string;\n\t\tconst description = (args?.description as string) || undefined;\n\t\tconst priority = (args?.priority as any) || \"medium\";\n\t\tconst reasoning = (args?.reasoning as string) || undefined;\n\t\tconst type = (args?.type as any) || undefined;\n\t\tconst parentId = (args?.parent_id as string) || undefined;\n\t\tconst validationSteps = (args?.validation_steps as string[]) || undefined;\n\n\t\tconst task = await taskService.addTask(\n\t\t\ttitle,\n\t\t\tdescription,\n\t\t\tpriority,\n\t\t\treasoning,\n\t\t\t{\n\t\t\t\ttype,\n\t\t\t\tparent_id: parentId,\n\t\t\t\tvalidation_steps: validationSteps,\n\t\t\t},\n\t\t);\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{ type: \"text\", text: `Task Added: ${task.id} (${task.title})` },\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"complete_task\") {\n\t\tconst id = args?.id as string;\n\t\tconst evidence = String(args?.evidence || \"\").trim();\n\n\t\tconst reasoning = String(args?.reasoning || \"\").trim();\n\t\tif (!evidence) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Evidence is required to complete a task.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\t\tif (!reasoning) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Reasoning is required to complete a task.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\n\t\tawait taskService.updateTask(id, {\n\t\t\tstatus: \"done\",\n\t\t\tevidence: [evidence],\n\t\t\treasoning,\n\t\t});\n\t\tconst vemDir = await getVemDir();\n\t\tawait writeFile(join(vemDir, \"exit_signal\"), \"\", \"utf-8\");\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Task ${id} marked as DONE. CLI will auto-close when the agent session ends.`,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"start_task\") {\n\t\tconst id = args?.id as string;\n\t\tconst sessionId = args?.session_id as string | undefined;\n\t\tconst source =\n\t\t\t(args?.source as \"copilot\" | \"claude\" | \"gemini\") || \"copilot\";\n\t\tconst sessionSummary = args?.session_summary as string | undefined;\n\n\t\tif (!id) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: \"Task ID is required.\" }],\n\t\t\t};\n\t\t}\n\n\t\tconst task = await taskService.getTask(id);\n\t\tif (!task) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: `Task ${id} not found.` }],\n\t\t\t};\n\t\t}\n\n\t\t// Build the new session ref\n\t\tconst sessionRef = sessionId\n\t\t\t? {\n\t\t\t\t\tid: sessionId,\n\t\t\t\t\tsource,\n\t\t\t\t\tstarted_at: new Date().toISOString(),\n\t\t\t\t\t...(sessionSummary ? { summary: sessionSummary } : {}),\n\t\t\t\t}\n\t\t\t: null;\n\n\t\t// Append session ref and mark in-progress\n\t\tconst existingSessions = (task.sessions as any[]) || [];\n\t\tconst patch: Record<string, any> = {\n\t\t\tstatus: \"in-progress\",\n\t\t\treasoning: sessionSummary\n\t\t\t\t? `Started by ${source} session: ${sessionSummary}`\n\t\t\t\t: `Started by ${source} agent`,\n\t\t\tsessions: sessionRef\n\t\t\t\t? [...existingSessions, sessionRef]\n\t\t\t\t: existingSessions,\n\t\t};\n\n\t\t// Auto-populate description from session summary if task has none\n\t\tif (!task.description && sessionSummary) {\n\t\t\tpatch.description = sessionSummary;\n\t\t}\n\n\t\tawait taskService.updateTask(id, patch);\n\t\tconst updated = await taskService.getTask(id);\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Task ${id} is now IN PROGRESS.\\n\\n${JSON.stringify(updated, null, 2)}`,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"search_memory\") {\n\t\tconst query = args?.query as string;\n\t\tconst apiKey = await configService.getApiKey();\n\n\t\tif (!apiKey) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Error: No API Key configured. Please run `vem login` in the CLI.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\n\t\ttry {\n\t\t\tconst { deviceId, deviceName } =\n\t\t\t\tawait configService.getOrCreateDeviceId();\n\t\t\tconst apiUrl = process.env.VEM_API_URL || \"http://localhost:3002\";\n\t\t\tconst res = await fetch(\n\t\t\t\t`${apiUrl}/search?q=${encodeURIComponent(query)}`,\n\t\t\t\t{\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\t\"X-Vem-Device-Id\": deviceId,\n\t\t\t\t\t\t\"X-Vem-Device-Name\": deviceName,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tif (!res.ok) {\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Search API Error: ${res.status} ${res.statusText}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst data = (await res.json()) as any;\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: JSON.stringify(data.results || [], null, 2),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t} catch (error: any) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{ type: \"text\", text: `Search Request Failed: ${error.message}` },\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\t}\n\n\tif (name === \"ask_question\") {\n\t\tconst question = args?.question as string;\n\t\tconst path = args?.path as string | undefined;\n\t\tconst apiKey = await configService.getApiKey();\n\t\tconst projectId = await configService.getProjectId();\n\n\t\tif (!apiKey) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Error: No API Key configured. Please run `vem login` in the CLI.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\n\t\tif (!projectId) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Error: No project linked. Please run `vem link` in the CLI.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\n\t\ttry {\n\t\t\tconst { deviceId, deviceName } =\n\t\t\t\tawait configService.getOrCreateDeviceId();\n\t\t\tconst apiUrl = process.env.VEM_API_URL || \"http://localhost:3002\";\n\n\t\t\tconst payload: any = { question };\n\t\t\tif (path) payload.path = path;\n\n\t\t\tconst res = await fetch(`${apiUrl}/projects/${projectId}/ask`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\"X-Vem-Device-Id\": deviceId,\n\t\t\t\t\t\"X-Vem-Device-Name\": deviceName,\n\t\t\t\t\t\"X-Vem-Client\": \"mcp-server\",\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t});\n\n\t\t\tif (!res.ok) {\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Ask API Error: ${res.status} ${res.statusText}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst data = (await res.json()) as any;\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: JSON.stringify(data, null, 2),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t} catch (error: any) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{ type: \"text\", text: `Ask Request Failed: ${error.message}` },\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\t}\n\n\tif (name === \"get_context\") {\n\t\tconst vemDir = await getVemDir();\n\t\tconst context = await configService.getContext();\n\t\tlet currentState = \"\";\n\t\ttry {\n\t\t\tcurrentState = await readFile(join(vemDir, CURRENT_STATE_FILE), \"utf-8\");\n\t\t} catch {\n\t\t\t// CURRENT_STATE.md may not exist yet\n\t\t}\n\t\tconst parts: string[] = [];\n\t\tif (context) parts.push(`## CONTEXT.md\\n\\n${context}`);\n\t\tif (currentState) parts.push(`## CURRENT_STATE.md\\n\\n${currentState}`);\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{ type: \"text\", text: parts.join(\"\\n\\n---\\n\\n\") || \"(no context yet)\" },\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"list_decisions\") {\n\t\tconst requestedLimit = (args?.limit as number) || 20;\n\t\tconst limit = Math.min(Math.max(1, requestedLimit), 50);\n\n\t\tconst decisionsService = new ScalableLogService(DECISIONS_DIR);\n\t\tconst entries = await decisionsService.getAllEntries();\n\t\tconst limitedEntries = entries.slice(0, limit);\n\n\t\tconst formatted = limitedEntries.map((entry) => ({\n\t\t\tid: entry.id,\n\t\t\ttitle: entry.title,\n\t\t\tdate: entry.created_at,\n\t\t\tcontent: entry.content,\n\t\t}));\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext:\n\t\t\t\t\t\tformatted.length > 0\n\t\t\t\t\t\t\t? JSON.stringify(formatted, null, 2)\n\t\t\t\t\t\t\t: \"No decisions recorded yet.\",\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"update_current_state\") {\n\t\tconst content = args?.content as string;\n\t\tif (!content) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: \"Content is required.\" }],\n\t\t\t};\n\t\t}\n\t\tconst vemDir = await getVemDir();\n\t\tawait writeFile(join(vemDir, CURRENT_STATE_FILE), content, \"utf-8\");\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: \"CURRENT_STATE.md updated.\" }],\n\t\t};\n\t}\n\n\tif (name === \"update_task\") {\n\t\tconst id = args?.id as string;\n\t\tconst status = args?.status as string | undefined;\n\t\tconst priority = args?.priority as string | undefined;\n\t\tconst reasoning = args?.reasoning as string | undefined;\n\t\tconst blockedBy = args?.blocked_by as string[] | undefined;\n\t\tconst validationSteps = args?.validation_steps as string[] | undefined;\n\n\t\tif (!id) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: \"Task ID is required.\" }],\n\t\t\t};\n\t\t}\n\n\t\tconst task = await taskService.getTask(id);\n\t\tif (!task) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: `Task ${id} not found.` }],\n\t\t\t};\n\t\t}\n\n\t\t// Validate status transitions\n\t\tif (status === \"blocked\" && !reasoning) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Reasoning is required when blocking a task.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\n\t\tif (task.status === \"done\" && status) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Cannot change status of a completed task. Use complete_task to mark as done.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\n\t\tconst patch: Record<string, any> = {};\n\t\tif (status) patch.status = status;\n\t\tif (priority) patch.priority = priority;\n\t\tif (reasoning) patch.reasoning = reasoning;\n\t\tif (blockedBy) patch.blocked_by = blockedBy;\n\t\tif (validationSteps) patch.validation_steps = validationSteps;\n\n\t\t// Default reasoning for status changes\n\t\tif (status && !reasoning) {\n\t\t\tif (status === \"in-progress\") {\n\t\t\t\tpatch.reasoning = \"Started working on task\";\n\t\t\t} else if (status === \"todo\") {\n\t\t\t\tpatch.reasoning = \"Unblocked task\";\n\t\t\t}\n\t\t}\n\n\t\tawait taskService.updateTask(id, patch);\n\n\t\tconst statusMsg = status ? ` Status: ${status.toUpperCase()}.` : \"\";\n\t\tconst priorityMsg = priority ? ` Priority: ${priority}.` : \"\";\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Task ${id} updated.${statusMsg}${priorityMsg}`,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"add_decision\") {\n\t\tconst title = args?.title as string;\n\t\tconst context = args?.context as string;\n\t\tconst decision = args?.decision as string;\n\t\tconst relatedTasks = args?.related_tasks as string[] | undefined;\n\n\t\tif (!title || !context || !decision) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Title, context, and decision are required.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\n\t\tawait configService.recordDecision(title, context, decision, relatedTasks);\n\n\t\tconst taskInfo =\n\t\t\trelatedTasks && relatedTasks.length > 0\n\t\t\t\t? ` (related to: ${relatedTasks.join(\", \")})`\n\t\t\t\t: \"\";\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Decision recorded: ${title}${taskInfo}`,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"get_changelog\") {\n\t\tconst requestedLimit = (args?.limit as number) || 10;\n\t\tconst limit = Math.min(Math.max(1, requestedLimit), 50); // Clamp between 1 and 50\n\n\t\tconst changelogService = new ScalableLogService(CHANGELOG_DIR);\n\t\tconst entries = await changelogService.getAllEntries();\n\t\tconst limitedEntries = entries.slice(0, limit);\n\n\t\tconst formatted = limitedEntries.map((entry) => ({\n\t\t\tid: entry.id,\n\t\t\ttitle: entry.title,\n\t\t\tdate: entry.created_at,\n\t\t\tcontent: entry.content,\n\t\t}));\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: JSON.stringify(formatted, null, 2),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"delete_task\") {\n\t\tconst id = args?.id as string;\n\t\tconst reasoning = args?.reasoning as string | undefined;\n\n\t\tif (!id) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: \"Task ID is required.\" }],\n\t\t\t};\n\t\t}\n\n\t\tawait taskService.updateTask(id, {\n\t\t\tdeleted_at: new Date().toISOString(),\n\t\t\treasoning,\n\t\t});\n\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Task ${id} soft deleted.` }],\n\t\t};\n\t}\n\n\tif (name === \"apply_vem_update\") {\n\t\ttry {\n\t\t\tconst update = args as any;\n\t\t\tconst result = await applyVemUpdate(update);\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `Successfully applied vem_update:\\n- Tasks updated: ${result.updatedTasks.length}\\n- New tasks: ${result.newTasks.length}\\n- Changelog lines: ${result.changelogLines.length}\\n- Decisions: ${result.decisionsAppended ? \"Appended\" : \"No change\"}\\n- Context: ${result.contextUpdated ? \"Updated\" : \"No change\"}\\n- State: ${result.currentStateUpdated ? \"Updated\" : \"No change\"}`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t} catch (error: any) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{ type: \"text\", text: `Failed to apply update: ${error.message}` },\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\t}\n\n\tif (name === \"sync_push\") {\n\t\tconst force = args?.force as boolean | undefined;\n\t\tconst dryRun = args?.dry_run as boolean | undefined;\n\n\t\ttry {\n\t\t\tconst projectId = await configService.getProjectId();\n\t\t\tif (!projectId) {\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Error: Project not linked. Run `vem link` in the CLI first.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst apiKey = await configService.getApiKey();\n\t\t\tif (!apiKey) {\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Error: No API Key configured. Run `vem login` in the CLI.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst baseVersion = await configService.getLastVersion();\n\t\t\tconst gitHash = getGitHash();\n\t\t\tif (!gitHash) {\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Error: git HEAD not found. Create at least one commit before syncing snapshots.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst vemHash = await computeVemHash();\n\t\t\tconst lastPush = await configService.getLastPushState();\n\t\t\tconst hasChanges = !(\n\t\t\t\tvemHash &&\n\t\t\t\tlastPush.gitHash === gitHash &&\n\t\t\t\tlastPush.vemHash === vemHash\n\t\t\t);\n\n\t\t\tif (!hasChanges && !force) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"No changes since last push (git HEAD and .vem unchanged). Use force=true to push anyway.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst snapshot = await syncService.pack();\n\t\t\tconst snapshotHash = computeSnapshotHashFromPayload(snapshot);\n\n\t\t\tif (dryRun) {\n\t\t\t\tconst taskCount = snapshot.tasks?.tasks?.length || 0;\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Dry run preview:\\n- Project: ${projectId}\\n- Git hash: ${gitHash}\\n- Snapshot hash: ${snapshotHash}\\n- Base version: ${baseVersion || \"none\"}\\n- Tasks: ${taskCount}\\n- Context: ${snapshot.context ? \"yes\" : \"no\"}\\n- Current state: ${snapshot.current_state ? \"yes\" : \"no\"}\\n\\nVerification remains pending until Git webhook linkage is confirmed.\\n\\nNo changes pushed. Remove dry_run to push for real.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst repoUrl = getGitRemote();\n\t\t\tconst commits = getCommits(50);\n\t\t\tconst payload = {\n\t\t\t\t...snapshot,\n\t\t\t\t...(repoUrl ? { repo_url: repoUrl } : {}),\n\t\t\t\tbase_version: baseVersion,\n\t\t\t\tcommits,\n\t\t\t\tproject_id: projectId,\n\t\t\t\tgit_hash: gitHash,\n\t\t\t\tsnapshot_hash: snapshotHash,\n\t\t\t};\n\n\t\t\tconst apiUrl = process.env.VEM_API_URL || \"http://localhost:3002\";\n\t\t\tconst res = await fetch(`${apiUrl}/snapshots`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t});\n\n\t\t\tif (res.ok) {\n\t\t\t\tconst json = (await res.json()) as { version?: string };\n\t\t\t\tif (json.version) {\n\t\t\t\t\tawait configService.setLastVersion(json.version);\n\t\t\t\t}\n\t\t\t\tif (gitHash && vemHash) {\n\t\t\t\t\tawait configService.setLastPushState({ gitHash, vemHash });\n\t\t\t\t}\n\n\t\t\t\t// Auto-archive completed tasks\n\t\t\t\ttry {\n\t\t\t\t\tawait taskService.archiveTasks({ status: \"done\" });\n\t\t\t\t} catch {\n\t\t\t\t\t// Soft failure — don't fail the push\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Snapshot pushed successfully. Version: ${json.version || \"v1\"}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst data = (await res.json().catch(() => ({}))) as any;\n\n\t\t\tif (res.status === 409) {\n\t\t\t\tif (data.latest_version) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Conflict: local base version ${baseVersion || \"none\"} does not match latest ${data.latest_version}. Run sync_pull first, then retry.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (data.expected_repo_url) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Conflict: project is linked to ${data.expected_repo_url}, but local repo is ${repoUrl || \"(no git remote)\"}. Update git remote or re-link the project.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Conflict: ${data.error || \"Unknown conflict\"}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (res.status === 403) {\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext:\n\t\t\t\t\t\t\t\tdata.error ||\n\t\t\t\t\t\t\t\t\"Device limit reached. Disconnect a device or upgrade your plan.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (res.status === 404) {\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext:\n\t\t\t\t\t\t\t\tdata.error ||\n\t\t\t\t\t\t\t\t\"Project not found. It may have been deleted. Run `vem unlink` then `vem link` to reconnect.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Network/other error: enqueue for later\n\t\t\tawait syncService.enqueue(payload);\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `Push failed (${data.error || res.statusText}). Snapshot queued for later retry.`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t} catch (error: any) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: `Push failed: ${error.message}` }],\n\t\t\t};\n\t\t}\n\t}\n\n\tif (name === \"sync_pull\") {\n\t\tconst force = args?.force as boolean | undefined;\n\n\t\ttry {\n\t\t\tconst apiKey = await configService.getApiKey();\n\t\t\tif (!apiKey) {\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Error: No API Key configured. Run `vem login` in the CLI.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif ((await isVemDirty()) && !force) {\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Local .vem has uncommitted changes. Use force=true to overwrite, or commit your changes first.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst repoUrl = getGitRemote();\n\t\t\tconst projectId = await configService.getProjectId();\n\t\t\tif (!repoUrl && !projectId) {\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Error: No git remote or linked project found. Run `vem link` in the CLI.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst apiUrl = process.env.VEM_API_URL || \"http://localhost:3002\";\n\t\t\tconst query = new URLSearchParams();\n\t\t\tif (repoUrl) query.set(\"repo_url\", repoUrl);\n\t\t\tif (projectId) query.set(\"project_id\", projectId);\n\n\t\t\tconst res = await fetch(`${apiUrl}/snapshots/latest?${query}`, {\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t...(await buildDeviceHeaders(configService)),\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tif (!res.ok) {\n\t\t\t\tif (res.status === 404) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"Project not found. It may have been deleted.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (res.status === 409) {\n\t\t\t\t\tconst data = (await res.json().catch(() => ({}))) as any;\n\t\t\t\t\treturn {\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: data.expected_repo_url\n\t\t\t\t\t\t\t\t\t? `Repo URL mismatch. Expected ${data.expected_repo_url}.`\n\t\t\t\t\t\t\t\t\t: data.error || \"Conflict detected.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (res.status === 403) {\n\t\t\t\t\tconst data = (await res.json().catch(() => ({}))) as any;\n\t\t\t\t\treturn {\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{ type: \"text\", text: data.error || \"Device limit reached.\" },\n\t\t\t\t\t\t],\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst err = await res.text();\n\t\t\t\treturn {\n\t\t\t\t\tisError: true,\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{ type: \"text\", text: `Pull API Error: ${res.status} ${err}` },\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst data = (await res.json()) as { snapshot: any; version?: string };\n\t\t\tif (!data.snapshot) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: \"No snapshot data available.\" }],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tawait syncService.unpack(data.snapshot);\n\t\t\tif (data.version) {\n\t\t\t\tawait configService.setLastVersion(data.version);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `Snapshot pulled and unpacked. Version: ${data.version || \"unknown\"}`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t} catch (error: any) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: `Pull failed: ${error.message}` }],\n\t\t\t};\n\t\t}\n\t}\n\n\tif (name === \"get_task_context\") {\n\t\tconst id = args?.id as string;\n\t\tif (!id) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: \"Task ID is required.\" }],\n\t\t\t};\n\t\t}\n\n\t\tconst task = await taskService.getTask(id);\n\t\tif (!task) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: `Task ${id} not found.` }],\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tid: task.id,\n\t\t\t\t\t\t\ttitle: task.title,\n\t\t\t\t\t\t\ttask_context: task.task_context || null,\n\t\t\t\t\t\t\ttask_context_summary: task.task_context_summary || null,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"update_task_context\") {\n\t\tconst id = args?.id as string;\n\t\tconst operation = args?.operation as string;\n\t\tconst text = args?.text as string | undefined;\n\n\t\tif (!id) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: \"Task ID is required.\" }],\n\t\t\t};\n\t\t}\n\t\tif (!operation || ![\"set\", \"append\", \"clear\"].includes(operation)) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Operation must be 'set', 'append', or 'clear'.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\t\tif ((operation === \"set\" || operation === \"append\") && !text) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `Text is required for '${operation}' operation.`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\n\t\tconst task = await taskService.getTask(id);\n\t\tif (!task) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: `Task ${id} not found.` }],\n\t\t\t};\n\t\t}\n\n\t\tlet nextContext = task.task_context || \"\";\n\t\tif (operation === \"clear\") {\n\t\t\tnextContext = \"\";\n\t\t} else if (operation === \"set\") {\n\t\t\tnextContext = text!;\n\t\t} else if (operation === \"append\") {\n\t\t\tnextContext = [nextContext, text!].filter(Boolean).join(\"\\n\");\n\t\t}\n\n\t\tawait taskService.updateTask(id, { task_context: nextContext });\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{ type: \"text\", text: `Task ${id} context updated (${operation}).` },\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"get_subtasks\") {\n\t\tconst parentId = args?.parent_id as string;\n\t\tif (!parentId) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: \"Parent task ID is required.\" }],\n\t\t\t};\n\t\t}\n\n\t\tconst allTasks = await taskService.getTasks();\n\t\tconst parent = allTasks.find((t) => t.id === parentId);\n\t\tif (!parent) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: `Parent task ${parentId} not found.` }],\n\t\t\t};\n\t\t}\n\n\t\tconst subtasks = allTasks\n\t\t\t.filter((t) => t.parent_id === parentId && !t.deleted_at)\n\t\t\t.sort((a, b) => (a.subtask_order ?? 0) - (b.subtask_order ?? 0));\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: JSON.stringify({ parent, subtasks }, null, 2),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"list_agent_sessions\") {\n\t\tconst limit = typeof args?.limit === \"number\" ? args.limit : 10;\n\t\tconst branch = typeof args?.branch === \"string\" ? args.branch : undefined;\n\t\tconst rawSources = args?.sources;\n\t\tconst sources =\n\t\t\tArray.isArray(rawSources) && rawSources.length > 0\n\t\t\t\t? (rawSources as (\"copilot\" | \"claude\" | \"gemini\")[])\n\t\t\t\t: undefined;\n\n\t\tlet gitRoot: string | undefined;\n\t\ttry {\n\t\t\tgitRoot = await getRepoRoot();\n\t\t} catch {\n\t\t\t// fallback: no filter\n\t\t}\n\n\t\tlet sessions = await listAllAgentSessions(gitRoot, sources);\n\t\tif (branch) {\n\t\t\tsessions = sessions.filter((s) => s.branch === branch);\n\t\t}\n\t\tsessions = sessions.slice(0, limit);\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\tsessions.map((s) => ({\n\t\t\t\t\t\t\tid: s.id,\n\t\t\t\t\t\t\tsource: s.source,\n\t\t\t\t\t\t\tsummary: s.summary,\n\t\t\t\t\t\t\tbranch: s.branch,\n\t\t\t\t\t\t\trepository: s.repository,\n\t\t\t\t\t\t\tcreated_at: s.created_at,\n\t\t\t\t\t\t\tupdated_at: s.updated_at,\n\t\t\t\t\t\t\tintents: s.intents,\n\t\t\t\t\t\t\tuser_messages: s.user_messages.slice(0, 3),\n\t\t\t\t\t\t})),\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tif (name === \"save_session_stats\") {\n\t\tconst taskId = args?.task_id as string;\n\t\tconst sessionId = args?.session_id as string;\n\t\tconst source =\n\t\t\t(args?.source as \"copilot\" | \"claude\" | \"gemini\") || \"copilot\";\n\n\t\tif (!taskId || !sessionId) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"task_id and session_id are required.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\n\t\tconst task = await taskService.getTask(taskId);\n\t\tif (!task) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [{ type: \"text\", text: `Task ${taskId} not found.` }],\n\t\t\t};\n\t\t}\n\n\t\tconst stats = await computeSessionStats(sessionId, source);\n\t\tif (!stats) {\n\t\t\treturn {\n\t\t\t\tisError: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `Could not compute stats for ${source} session ${sessionId}. Session file may not exist or is unreadable.`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\n\t\t// Update the matching session ref on the task (or append stats as a note if no match)\n\t\tconst existingSessions = ((task.sessions as any[]) || []).map((s: any) => {\n\t\t\tif (s.id === sessionId) {\n\t\t\t\treturn { ...s, stats };\n\t\t\t}\n\t\t\treturn s;\n\t\t});\n\n\t\t// If no matching session was found, still save the stats by appending a new session entry\n\t\tconst hasMatch = existingSessions.some((s: any) => s.id === sessionId);\n\t\tif (!hasMatch) {\n\t\t\texistingSessions.push({\n\t\t\t\tid: sessionId,\n\t\t\t\tsource,\n\t\t\t\tstarted_at: stats.ended_at ?? new Date().toISOString(),\n\t\t\t\tstats,\n\t\t\t});\n\t\t}\n\n\t\tawait taskService.updateTask(taskId, { sessions: existingSessions });\n\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Stats saved for session ${sessionId} on task ${taskId}:\\n${JSON.stringify(stats, null, 2)}`,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tthrow new Error(`Tool not found: ${name}`);\n});\n\nconst transport = new StdioServerTransport();\n\n// Support --api-key <key> CLI flag so users can pass their key directly\n// without needing to run `vem login` first.\n// Priority: --api-key flag > VEM_API_KEY env var > ~/.vem/config.json (set by vem login)\nconst apiKeyFlagIndex = process.argv.indexOf(\"--api-key\");\nif (apiKeyFlagIndex !== -1 && process.argv[apiKeyFlagIndex + 1]) {\n\tconst flagKey = process.argv[apiKeyFlagIndex + 1];\n\tawait configService.setApiKey(flagKey);\n}\n\nawait server.connect(transport);\n","import path from \"node:path\";\nimport { TaskCreateSchema, TaskUpdateSchema, VemUpdateSchema, } from \"@vem/schemas\";\nimport fs from \"fs-extra\";\nimport { CHANGELOG_DIR, CONTEXT_FILE, CURRENT_STATE_FILE, DECISIONS_DIR, ensureVemFiles, getVemDir, } from \"./fs.js\";\nimport { getGitHeadHash } from \"./git.js\";\nimport { ScalableLogService } from \"./logs.js\";\nimport { TaskService } from \"./tasks.js\";\nconst VEM_UPDATE_FENCE = /```vem_update(?:\\s+v1)?\\s*([\\s\\S]*?)```/i;\nconst DEFAULT_TASK_CONTEXT_SUMMARY_MAX_CHARS = 1200;\nexport function formatVemPack(payload) {\n return `\\`\\`\\`vem_pack v1\\n${JSON.stringify(payload, null, 2)}\\n\\`\\`\\``;\n}\nexport function parseVemUpdateBlock(input) {\n const match = input.match(VEM_UPDATE_FENCE);\n const raw = (match?.[1] ?? input).trim();\n if (!raw) {\n throw new Error(\"No vem_update payload found.\");\n }\n let data;\n try {\n data = JSON.parse(raw);\n }\n catch (error) {\n throw new Error(`vem_update payload is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);\n }\n const parsed = VemUpdateSchema.safeParse(data);\n if (!parsed.success) {\n throw new Error(`vem_update payload failed validation: ${parsed.error.message}`);\n }\n return parsed.data;\n}\nfunction resolveAgentActor(actor) {\n const trimmed = actor?.trim();\n if (trimmed)\n return trimmed;\n const envActor = process.env.VEM_AGENT_NAME ||\n process.env.VEM_ACTOR ||\n process.env.VEM_AGENT;\n const normalized = envActor?.trim();\n return normalized || undefined;\n}\nfunction normalizeEvidence(evidence) {\n if (!evidence)\n return [];\n return evidence.map((entry) => entry.trim()).filter(Boolean);\n}\nfunction addValidationEvidence(evidence, validationSteps) {\n if (!validationSteps || validationSteps.length === 0) {\n return evidence;\n }\n const merged = [...evidence];\n let evidenceBlob = merged.join(\" \").toLowerCase();\n for (const step of validationSteps) {\n const normalizedStep = step.trim();\n if (!normalizedStep)\n continue;\n if (!evidenceBlob.includes(normalizedStep.toLowerCase())) {\n const entry = `Validated: ${normalizedStep}`;\n merged.push(entry);\n evidenceBlob = `${evidenceBlob}\\n${entry.toLowerCase()}`;\n }\n }\n return merged;\n}\nfunction summarizeTaskContext(taskContext) {\n const normalized = taskContext.trim();\n if (normalized.length <= DEFAULT_TASK_CONTEXT_SUMMARY_MAX_CHARS) {\n return normalized;\n }\n return `${normalized.slice(0, DEFAULT_TASK_CONTEXT_SUMMARY_MAX_CHARS - 15).trimEnd()}\\n...[truncated]`;\n}\nexport async function applyVemUpdate(update) {\n await ensureVemFiles();\n const taskService = new TaskService();\n const decisionsLog = new ScalableLogService(DECISIONS_DIR);\n const changelogLog = new ScalableLogService(CHANGELOG_DIR);\n const updatedTasks = [];\n const newTasks = [];\n if (update.tasks?.length) {\n for (const entry of update.tasks) {\n const parsed = TaskUpdateSchema.safeParse(entry);\n if (!parsed.success) {\n throw new Error(`Invalid task update for ${entry.id}: ${parsed.error.message}`);\n }\n const { id, ...patch } = parsed.data;\n const task = await taskService.getTask(id);\n if (!task) {\n throw new Error(`Task ${id} not found.`);\n }\n let cleaned = stripUndefined(patch);\n if (cleaned.status === \"done\" && task.status !== \"done\") {\n const actor = resolveAgentActor(cleaned.actor);\n const reasoning = cleaned.reasoning?.trim() ||\n `Completed via ${actor || \"agent\"} session.`;\n const baseEvidence = normalizeEvidence(cleaned.evidence);\n const evidenceSeed = baseEvidence.length > 0\n ? baseEvidence\n : [`Completed by agent ${actor || \"unknown\"}`];\n const evidence = addValidationEvidence(evidenceSeed, task.validation_steps);\n const taskContextSummary = cleaned.task_context_summary ??\n (task.task_context\n ? summarizeTaskContext(task.task_context)\n : undefined);\n cleaned = stripUndefined({\n ...cleaned,\n actor,\n reasoning,\n evidence,\n task_context_summary: taskContextSummary,\n });\n }\n const updated = await taskService.updateTask(id, cleaned);\n updatedTasks.push(updated);\n }\n }\n if (update.new_tasks?.length) {\n for (const entry of update.new_tasks) {\n const parsed = TaskCreateSchema.safeParse(entry);\n if (!parsed.success) {\n throw new Error(`Invalid new task payload: ${parsed.error.message}`);\n }\n const created = await taskService.addTask(parsed.data.title, parsed.data.description, parsed.data.priority ?? \"medium\", parsed.data.reasoning, stripUndefined({\n status: parsed.data.status,\n assignee: parsed.data.assignee,\n tags: parsed.data.tags,\n type: parsed.data.type,\n estimate_hours: parsed.data.estimate_hours,\n depends_on: parsed.data.depends_on,\n blocked_by: parsed.data.blocked_by,\n recurrence_rule: parsed.data.recurrence_rule,\n owner_id: parsed.data.owner_id,\n reviewer_id: parsed.data.reviewer_id,\n evidence: parsed.data.evidence,\n parent_id: parsed.data.parent_id,\n subtask_order: parsed.data.subtask_order,\n due_at: parsed.data.due_at,\n task_context: parsed.data.task_context,\n task_context_summary: parsed.data.task_context_summary,\n }));\n // Apply other fields if present (status, assignee, etc)\n const patch = stripUndefined({\n status: parsed.data.status,\n assignee: parsed.data.assignee,\n tags: parsed.data.tags,\n type: parsed.data.type,\n estimate_hours: parsed.data.estimate_hours,\n depends_on: parsed.data.depends_on,\n blocked_by: parsed.data.blocked_by,\n recurrence_rule: parsed.data.recurrence_rule,\n owner_id: parsed.data.owner_id,\n reviewer_id: parsed.data.reviewer_id,\n evidence: parsed.data.evidence,\n parent_id: parsed.data.parent_id,\n subtask_order: parsed.data.subtask_order,\n due_at: parsed.data.due_at,\n task_context: parsed.data.task_context,\n task_context_summary: parsed.data.task_context_summary,\n });\n let updated = created;\n if (Object.keys(patch).length > 0) {\n updated = await taskService.updateTask(created.id, patch);\n }\n newTasks.push(updated);\n }\n }\n const changelogLines = await appendChangelog(changelogLog, update.changelog_append);\n const decisionsAppendedRef = await appendDecisions(decisionsLog, update.decisions_append);\n const decisionsAppended = decisionsAppendedRef !== null;\n // Auto-link the new decision to all updated/new tasks via related_decisions\n if (decisionsAppendedRef) {\n const refId = typeof decisionsAppendedRef === \"string\"\n ? decisionsAppendedRef\n : decisionsAppendedRef.id;\n const allAffectedTasks = [...updatedTasks, ...newTasks];\n for (const task of allAffectedTasks) {\n const existing = Array.isArray(task.related_decisions)\n ? task.related_decisions\n : [];\n const alreadyLinked = existing.some((r) => typeof r === \"string\" ? r === refId : r.id === refId);\n if (!alreadyLinked) {\n const updated = await taskService.updateTask(task.id, {\n related_decisions: [...existing, decisionsAppendedRef],\n });\n // Replace in the result arrays\n const ui = updatedTasks.findIndex((t) => t.id === task.id);\n if (ui !== -1)\n updatedTasks[ui] = updated;\n const ni = newTasks.findIndex((t) => t.id === task.id);\n if (ni !== -1)\n newTasks[ni] = updated;\n }\n }\n }\n const currentStateUpdated = await writeCurrentState(update.current_state);\n const contextUpdated = await writeContext(update.context);\n return {\n updatedTasks,\n newTasks,\n changelogLines,\n decisionsAppended,\n decisionsAppendedRef,\n currentStateUpdated,\n contextUpdated,\n };\n}\nfunction stripUndefined(value) {\n return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));\n}\nfunction normalizeLines(value) {\n if (!value)\n return [];\n const raw = Array.isArray(value) ? value : value.split(/\\r?\\n/);\n return raw.map((line) => line.trim()).filter(Boolean);\n}\nasync function appendChangelog(log, value) {\n const additions = normalizeLines(value);\n if (additions.length === 0)\n return [];\n const content = additions.map((line) => `- ${line}`).join(\"\\n\");\n const commitHash = await getGitHeadHash();\n await log.addEntry(\"Agent Update\", content, { commitHash });\n return additions;\n}\n/** Extracts the first meaningful heading from decisions markdown (e.g. ## [ADR-001] My title → \"ADR-001: My title\") */\nfunction extractDecisionTitle(block) {\n const match = block.match(/^#{1,3}\\s+\\[([^\\]]+)\\]\\s+(.+)$/m);\n if (match)\n return `${match[1]}: ${match[2].trim()}`;\n // Fallback: first non-empty heading\n const plain = block.match(/^#{1,3}\\s+(.+)$/m);\n return plain?.[1]?.trim();\n}\nasync function appendDecisions(log, value) {\n if (!value)\n return null;\n const block = Array.isArray(value) ? value.join(\"\\n\").trim() : value.trim();\n if (!block)\n return null;\n const commitHash = await getGitHeadHash();\n const id = await log.addEntry(\"Agent Decision\", block, { commitHash });\n const title = extractDecisionTitle(block);\n return title ? { id, title, content: block } : { id, content: block };\n}\nasync function writeCurrentState(value) {\n if (value === undefined)\n return false;\n const dir = await getVemDir();\n const currentStatePath = path.join(dir, CURRENT_STATE_FILE);\n const next = value.trim().length > 0 ? `${value.trim()}\\n` : \"\";\n await fs.writeFile(currentStatePath, next, \"utf-8\");\n return true;\n}\nasync function writeContext(value) {\n if (value === undefined)\n return false;\n const dir = await getVemDir();\n const contextPath = path.join(dir, CONTEXT_FILE);\n const next = value.trim().length > 0 ? `${value.trim()}\\n` : \"\";\n await fs.writeFile(contextPath, next, \"utf-8\");\n return true;\n}\n","import { z } from \"zod\";\nexport const RelatedDecisionRefSchema = z.union([\n z.string(),\n z.object({\n id: z.string(),\n title: z.string().optional(),\n content: z.string().optional(),\n }),\n]);\nexport const AgentSessionStatsSchema = z.object({\n ended_at: z.string().datetime().optional(),\n session_duration_ms: z.number().int().optional(),\n turn_count: z.number().int().optional(),\n tool_call_count: z.number().int().optional(),\n model_breakdown: z.record(z.string(), z.number().int()).optional(),\n});\nexport const TaskSessionRefSchema = z.object({\n id: z.string(),\n source: z.enum([\"copilot\", \"claude\", \"gemini\"]),\n started_at: z.string().datetime(),\n summary: z.string().optional(),\n stats: AgentSessionStatsSchema.optional(),\n});\nexport const TaskActionSchema = z.object({\n type: z.enum([\n \"create\",\n \"update_status\",\n \"update_priority\",\n \"update_tags\",\n \"update_type\",\n \"update_estimate\",\n \"update_dependencies\",\n \"update_recurrence\",\n \"update_owner\",\n \"update_reviewer\",\n \"delete\",\n \"comment\",\n \"completion\",\n ]),\n reasoning: z.string().nullable().optional(),\n actor: z.string().nullable().optional(),\n created_at: z.string().datetime(),\n});\nexport const TaskStatusSchema = z.enum([\n \"todo\",\n \"in-progress\",\n \"blocked\",\n \"done\",\n]);\nexport const TaskPrioritySchema = z.enum([\"low\", \"medium\", \"high\", \"critical\"]);\nexport const TaskTypeSchema = z.enum([\"feature\", \"bug\", \"chore\"]);\nexport const TaskSchema = z.object({\n id: z.string(),\n title: z.string(),\n status: TaskStatusSchema,\n assignee: z.string().optional(),\n priority: TaskPrioritySchema.optional(),\n tags: z.array(z.string()).optional(),\n type: TaskTypeSchema.optional(),\n estimate_hours: z.number().optional(),\n depends_on: z.array(z.string()).optional(),\n blocked_by: z.array(z.string()).optional(),\n recurrence_rule: z.string().optional(),\n owner_id: z.string().optional(),\n reviewer_id: z.string().optional(),\n parent_id: z.string().optional(),\n subtask_order: z.number().int().optional(),\n description: z.string().optional(),\n task_context: z.string().optional(),\n task_context_summary: z.string().optional(),\n user_notes: z.string().optional(),\n related_decisions: z.array(RelatedDecisionRefSchema).optional(),\n evidence: z.array(z.string()).optional(),\n validation_steps: z.array(z.string()).optional(),\n sessions: z.array(TaskSessionRefSchema).optional(),\n actions: z.array(TaskActionSchema).optional(),\n created_at: z.string().datetime().optional(),\n updated_at: z.string().datetime().optional(),\n due_at: z.string().datetime().optional(),\n github_issue_number: z.number().optional(),\n deleted_at: z.string().datetime().optional(),\n});\nexport const TaskListSchema = z.object({\n tasks: z.array(TaskSchema),\n});\nexport const TaskUpdateSchema = z.object({\n id: z.string(),\n title: z.string().optional(),\n description: z.string().optional(),\n status: TaskStatusSchema.optional(),\n assignee: z.string().optional(),\n priority: TaskPrioritySchema.optional(),\n tags: z.array(z.string()).optional(),\n type: TaskTypeSchema.optional(),\n estimate_hours: z.number().optional(),\n depends_on: z.array(z.string()).optional(),\n blocked_by: z.array(z.string()).optional(),\n recurrence_rule: z.string().optional(),\n owner_id: z.string().optional(),\n reviewer_id: z.string().optional(),\n parent_id: z.string().optional(),\n subtask_order: z.number().int().optional(),\n due_at: z.string().datetime().optional(),\n evidence: z.array(z.string()).optional(),\n task_context: z.string().optional(),\n task_context_summary: z.string().optional(),\n user_notes: z.string().optional(),\n related_decisions: z.array(RelatedDecisionRefSchema).optional(),\n validation_steps: z.array(z.string()).optional(),\n reasoning: z.string().optional(),\n actor: z.string().optional(),\n github_issue_number: z.number().optional(),\n deleted_at: z.string().datetime().optional(),\n});\nexport const TaskCreateSchema = z.object({\n title: z.string(),\n description: z.string().optional(),\n status: TaskStatusSchema.optional(),\n assignee: z.string().optional(),\n priority: TaskPrioritySchema.optional(),\n tags: z.array(z.string()).optional(),\n type: TaskTypeSchema.optional(),\n estimate_hours: z.number().optional(),\n depends_on: z.array(z.string()).optional(),\n blocked_by: z.array(z.string()).optional(),\n recurrence_rule: z.string().optional(),\n owner_id: z.string().optional(),\n reviewer_id: z.string().optional(),\n parent_id: z.string().optional(),\n subtask_order: z.number().int().optional(),\n due_at: z.string().datetime().optional(),\n evidence: z.array(z.string()).optional(),\n task_context: z.string().optional(),\n task_context_summary: z.string().optional(),\n related_decisions: z.array(RelatedDecisionRefSchema).optional(),\n validation_steps: z.array(z.string()).optional(),\n reasoning: z.string().optional(),\n});\nexport const VemUpdateSchema = z.object({\n tasks: z.array(TaskUpdateSchema).optional(),\n new_tasks: z.array(TaskCreateSchema).optional(),\n changelog_append: z.union([z.string(), z.array(z.string())]).optional(),\n decisions_append: z.union([z.string(), z.array(z.string())]).optional(),\n current_state: z.string().optional(),\n context: z.string().optional(),\n});\n// Webhook event types\nexport const WebhookEventSchema = z.enum([\n \"task.created\",\n \"task.started\",\n \"task.blocked\",\n \"task.completed\",\n \"task.deleted\",\n \"snapshot.pushed\",\n \"snapshot.verified\",\n \"snapshot.failed\",\n \"decision.added\",\n \"changelog.updated\",\n \"drift.detected\",\n \"project.linked\",\n]);\nexport const WebhookSchema = z.object({\n id: z.string().uuid(),\n org_id: z.string(),\n project_id: z.string().nullable(),\n url: z.string().url(),\n secret: z.string(),\n enabled: z.boolean(),\n events: z.array(WebhookEventSchema),\n created_at: z.string().datetime(),\n updated_at: z.string().datetime(),\n created_by: z.string().nullable(),\n});\nexport const WebhookCreateSchema = z.object({\n url: z.string().url(\"Must be a valid URL\"),\n events: z.array(WebhookEventSchema).min(1, \"Must select at least one event\"),\n});\nexport const WebhookUpdateSchema = z.object({\n url: z.string().url().optional(),\n events: z.array(WebhookEventSchema).min(1).optional(),\n enabled: z.boolean().optional(),\n});\nexport const WebhookDeliverySchema = z.object({\n id: z.string().uuid(),\n webhook_id: z.string().uuid(),\n event_type: WebhookEventSchema,\n payload: z.any(),\n status_code: z.number().nullable(),\n success: z.boolean(),\n attempt: z.number().int().min(1).max(3),\n error_message: z.string().nullable(),\n delivered_at: z.string().datetime(),\n});\n","import path from \"node:path\";\nimport { findUp } from \"find-up-simple\";\nimport fs from \"fs-extra\";\nexport const VEM_DIR = \".vem\";\nexport const TASKS_DIR = \"tasks\";\nexport const DECISIONS_DIR = \"decisions\";\nexport const CHANGELOG_DIR = \"changelog\";\n// Legacy files (to be phased out)\nexport const TASKS_FILE = \"TASKS.json\";\nexport const DECISIONS_FILE = \"DECISIONS.md\";\nexport const CHANGELOG_FILE = \"CHANGELOG.md\";\nexport const CONTEXT_FILE = \"CONTEXT.md\";\nexport const CURRENT_STATE_FILE = \"CURRENT_STATE.md\";\nexport const SCRATCHPAD_FILE = \"scratchpad.md\";\nexport const QUEUE_DIR = \"queue\";\nexport async function getRepoRoot() {\n const gitDir = await findUp(\".git\", { type: \"directory\" });\n if (!gitDir) {\n throw new Error(\"Not inside a Git repository\");\n }\n return path.dirname(gitDir);\n}\nexport async function getVemDir() {\n const root = await getRepoRoot();\n return path.join(root, VEM_DIR);\n}\nexport async function ensureVemDir() {\n const dir = await getVemDir();\n await fs.ensureDir(dir);\n return dir;\n}\nexport async function isVemInitialized() {\n try {\n const dir = await getVemDir();\n return await fs.pathExists(dir);\n }\n catch {\n return false;\n }\n}\nexport async function ensureVemFiles() {\n const dir = await ensureVemDir();\n // Ensure new scalable directories\n await fs.ensureDir(path.join(dir, TASKS_DIR));\n await fs.ensureDir(path.join(dir, DECISIONS_DIR));\n await fs.ensureDir(path.join(dir, CHANGELOG_DIR));\n const contextPath = path.join(dir, CONTEXT_FILE);\n if (!(await fs.pathExists(contextPath))) {\n await fs.writeFile(contextPath, \"# Project Context: vem\\n\\nDescribe the high-level project context here.\\n\", \"utf-8\");\n }\n const currentStatePath = path.join(dir, CURRENT_STATE_FILE);\n if (!(await fs.pathExists(currentStatePath))) {\n await fs.writeFile(currentStatePath, \"# Current State\\n\\nSummarize what just changed, what is in progress, and what is next.\\n\", \"utf-8\");\n }\n}\n","import { execSync } from \"node:child_process\";\nimport { getRepoRoot } from \"./fs.js\";\nexport async function getGitHeadHash() {\n try {\n const root = await getRepoRoot();\n const hash = execSync(\"git rev-parse HEAD\", {\n cwd: root,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n .toString()\n .trim();\n return hash || null;\n }\n catch {\n return null;\n }\n}\nexport async function getGitLastCommitForPath(filePath) {\n try {\n const root = await getRepoRoot();\n const relative = filePath.startsWith(root)\n ? filePath.slice(root.length + 1)\n : filePath;\n const hash = execSync(`git log -1 --format=%H -- \"${relative.replace(/\"/g, '\\\\\"')}\"`, {\n cwd: root,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n .toString()\n .trim();\n return hash || null;\n }\n catch {\n return null;\n }\n}\n","import path from \"node:path\";\nimport fs from \"fs-extra\";\nimport { getVemDir } from \"./fs.js\";\nimport { getGitLastCommitForPath } from \"./git.js\";\nexport class ScalableLogService {\n subDir;\n constructor(subDir) {\n this.subDir = subDir;\n }\n async getBaseDir() {\n const vemDir = await getVemDir();\n const dir = path.join(vemDir, this.subDir);\n await fs.ensureDir(dir);\n return dir;\n }\n async addEntry(title, content, options) {\n const baseDir = await this.getBaseDir();\n const timestamp = new Date().toISOString();\n const id = `${timestamp.replace(/[:.]/g, \"-\")}-${title.toLowerCase().replace(/[^a-z0-9]/g, \"-\")}`;\n const filePath = path.join(baseDir, `${id}.md`);\n const commitLine = options?.commitHash\n ? `**Commit:** ${options.commitHash}\\n\\n`\n : \"\";\n const fullContent = `# ${title}\\n\\n**Date:** ${timestamp}\\n\\n${commitLine}${content}\\n`;\n await fs.writeFile(filePath, fullContent, \"utf-8\");\n return id;\n }\n async getAllEntries() {\n const baseDir = await this.getBaseDir();\n const files = await fs.readdir(baseDir);\n const entries = [];\n for (const file of files) {\n if (file.endsWith(\".md\")) {\n const content = await fs.readFile(path.join(baseDir, file), \"utf-8\");\n const id = path.parse(file).name;\n // Simple parsing for title (first # header)\n const titleMatch = content.match(/^#\\s+(.*)/);\n const title = titleMatch ? titleMatch[1] : id;\n entries.push({\n id,\n title,\n content,\n created_at: id\n .substring(0, 19)\n .replace(/-/g, (_m, offset) => offset === 10 ? \"T\" : offset === 13 || offset === 16 ? \":\" : \"-\"),\n file_path: path.join(baseDir, file),\n });\n }\n }\n // Sort by ID (which starts with timestamp)\n return entries.sort((a, b) => b.id.localeCompare(a.id));\n }\n async getMonolithicContent() {\n return this.getMonolithicContentWithOptions();\n }\n async getMonolithicContentWithOptions(options) {\n const entries = await this.getAllEntries();\n // reverse back to chronological for monolithic view\n const normalized = await Promise.all(entries.reverse().map(async (entry) => {\n if (!options?.includeCommitHashes)\n return entry.content;\n if (/^\\*\\*Commit:\\*\\*/m.test(entry.content))\n return entry.content;\n if (!entry.file_path)\n return entry.content;\n const commitHash = await getGitLastCommitForPath(entry.file_path);\n if (!commitHash)\n return entry.content;\n const dateMatch = entry.content.match(/^\\*\\*Date:\\*\\*.*$/m);\n if (!dateMatch) {\n return `**Commit:** ${commitHash}\\n\\n${entry.content}`;\n }\n return entry.content.replace(dateMatch[0], `${dateMatch[0]}\\n\\n**Commit:** ${commitHash}`);\n }));\n return normalized.join(\"\\n---\\n\\n\");\n }\n async archiveEntries(options) {\n const entries = await this.getAllEntries(); // Sorted by ID (date desc-ish)\n let toArchive = [];\n if (options.keepCount !== undefined) {\n toArchive = entries.slice(options.keepCount);\n }\n else if (options.olderThanDays !== undefined) {\n const now = new Date();\n const threshold = new Date(now.getTime() - options.olderThanDays * 24 * 60 * 60 * 1000);\n toArchive = entries.filter((e) => new Date(e.created_at) < threshold);\n }\n else {\n // If no options, default to keeping 20\n toArchive = entries.slice(20);\n }\n if (toArchive.length === 0)\n return 0;\n const baseDir = await this.getBaseDir();\n const archiveBase = path.join(baseDir, \"archive\");\n await fs.ensureDir(archiveBase);\n for (const entry of toArchive) {\n // Group by Year-Month\n const date = new Date(entry.created_at);\n const folder = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, \"0\")}`;\n const targetDir = path.join(archiveBase, folder);\n await fs.ensureDir(targetDir);\n const src = path.join(baseDir, `${entry.id}.md`);\n const dest = path.join(targetDir, `${entry.id}.md`);\n if (await fs.pathExists(src)) {\n await fs.move(src, dest, { overwrite: true });\n }\n }\n return toArchive.length;\n }\n}\n","import path from \"node:path\";\nimport fs from \"fs-extra\";\nimport { getVemDir, TASKS_DIR } from \"./fs.js\";\nimport { ShardedFileStorage, TaskIndex, } from \"./sharded-fs.js\";\nconst TASK_CONTEXT_SUMMARY_MAX_CHARS = 1200;\nfunction summarizeTaskContext(value) {\n const normalized = value.trim();\n if (normalized.length <= TASK_CONTEXT_SUMMARY_MAX_CHARS) {\n return normalized;\n }\n return `${normalized.slice(0, TASK_CONTEXT_SUMMARY_MAX_CHARS - 15).trimEnd()}\\n...[truncated]`;\n}\nexport class TaskService {\n storage = null;\n index = null;\n async init() {\n if (this.storage && this.index) {\n return { storage: this.storage, index: this.index };\n }\n const vemDir = await getVemDir();\n const baseDir = path.join(vemDir, TASKS_DIR);\n await fs.ensureDir(baseDir);\n this.storage = new ShardedFileStorage(baseDir);\n this.index = new TaskIndex(baseDir);\n return { storage: this.storage, index: this.index };\n }\n async getTasks() {\n const { storage } = await this.init();\n // For backward compatibility, we load all tasks.\n // In the future, we should probably prefer getTaskIndex or implement pagination.\n const active = await storage.loadAll();\n // Also include recently archived tasks (done within last 30 days) so\n // their sessions and evidence are visible in the cloud / web UI.\n const archived = await this.loadRecentArchivedTasks(30);\n const archivedIds = new Set(active.map((t) => t.id));\n for (const t of archived) {\n if (!archivedIds.has(t.id))\n active.push(t);\n }\n return active;\n }\n async loadRecentArchivedTasks(withinDays) {\n const vemDir = await getVemDir();\n const archiveDir = path.join(vemDir, TASKS_DIR, \"archive\");\n if (!(await fs.pathExists(archiveDir)))\n return [];\n const cutoff = Date.now() - withinDays * 24 * 60 * 60 * 1000;\n const result = [];\n const walk = async (dir) => {\n const entries = await fs.readdir(dir);\n for (const entry of entries) {\n const fullPath = path.join(dir, entry);\n const stat = await fs.stat(fullPath);\n if (stat.isDirectory()) {\n await walk(fullPath);\n continue;\n }\n if (!entry.endsWith(\".json\"))\n continue;\n if (stat.mtimeMs < cutoff)\n continue;\n try {\n const task = await fs.readJson(fullPath);\n if (task?.id)\n result.push(task);\n }\n catch {\n // skip malformed files\n }\n }\n };\n await walk(archiveDir);\n return result;\n }\n async getTaskIndex() {\n const { index } = await this.init();\n return index.load();\n }\n async getTask(id) {\n const { storage } = await this.init();\n return storage.load(id);\n }\n async listArchivedTaskIds() {\n const vemDir = await getVemDir();\n const archiveDir = path.join(vemDir, TASKS_DIR, \"archive\");\n if (!(await fs.pathExists(archiveDir))) {\n return [];\n }\n const ids = [];\n const walk = async (dir) => {\n const entries = await fs.readdir(dir);\n for (const entry of entries) {\n const fullPath = path.join(dir, entry);\n const stat = await fs.stat(fullPath);\n if (stat.isDirectory()) {\n await walk(fullPath);\n continue;\n }\n if (!entry.endsWith(\".json\"))\n continue;\n const id = path.parse(entry).name;\n if (/^TASK-\\d{3,}$/.test(id)) {\n ids.push(id);\n }\n }\n };\n await walk(archiveDir);\n return ids;\n }\n async getNextTaskId(storage) {\n const allTasks = await storage.loadAll();\n const archivedIds = await this.listArchivedTaskIds();\n const allIds = new Set([\n ...allTasks.map((task) => task.id),\n ...archivedIds,\n ]);\n // Find max existing sequential ID\n let maxId = 0;\n for (const id of allIds) {\n const match = id.match(/^TASK-(\\d{3,})$/);\n if (match) {\n const num = parseInt(match[1], 10);\n if (!Number.isNaN(num) && num > maxId) {\n maxId = num;\n }\n }\n }\n // Try to find the next available ID\n // In case of race conditions (file exists but not in index yet, though unlikely with single-threaded Node),\n // we could verify file existence, but storage.loadAll() already reads files.\n // We'll increment and check if it's taken in a loop just to be safe against some edge cases\n // or if we switch to index-only scanning later.\n let candidateNum = maxId + 1;\n let candidateId = `TASK-${String(candidateNum).padStart(3, \"0\")}`;\n // Double check against loaded tasks (already done via maxId, but good practice if logic changes)\n while (allIds.has(candidateId)) {\n candidateNum++;\n candidateId = `TASK-${String(candidateNum).padStart(3, \"0\")}`;\n }\n return candidateId;\n }\n async addTask(title, description, priority = \"medium\", reasoning, options) {\n const { storage, index } = await this.init();\n // Sequential ID generation with guardrails unless an explicit cache ID is provided.\n const explicitId = options?.id?.trim();\n const id = explicitId && explicitId.length > 0\n ? explicitId\n : await this.getNextTaskId(storage);\n const timestamp = new Date().toISOString();\n const blockingIds = await this.getBlockingIds(options?.depends_on, options?.blocked_by, storage);\n if (options?.status === \"done\" && blockingIds.length > 0) {\n throw new Error(\"Cannot mark task as done while dependencies are incomplete.\");\n }\n const initialStatus = blockingIds.length > 0 && options?.status !== \"done\"\n ? \"blocked\"\n : (options?.status ?? \"todo\");\n const newTask = {\n id,\n title,\n description,\n status: initialStatus,\n assignee: options?.assignee,\n priority,\n tags: options?.tags,\n type: options?.type,\n estimate_hours: options?.estimate_hours,\n depends_on: options?.depends_on,\n blocked_by: options?.blocked_by,\n recurrence_rule: options?.recurrence_rule,\n owner_id: options?.owner_id,\n reviewer_id: options?.reviewer_id,\n parent_id: options?.parent_id,\n subtask_order: options?.subtask_order,\n due_at: options?.due_at,\n task_context: options?.task_context,\n task_context_summary: options?.task_context_summary,\n evidence: options?.evidence,\n validation_steps: options?.validation_steps,\n created_at: timestamp,\n updated_at: timestamp,\n actions: [\n {\n type: \"create\",\n reasoning: reasoning ?? null,\n actor: options?.actor ?? null,\n created_at: timestamp,\n },\n ],\n };\n await storage.save(newTask);\n await index.updateEntry({\n id: newTask.id,\n title: newTask.title,\n status: newTask.status,\n assignee: newTask.assignee,\n priority: newTask.priority,\n updated_at: newTask.updated_at,\n });\n return newTask;\n }\n async updateTask(id, patch) {\n return this.updateTaskInternal(id, patch);\n }\n async updateTaskInternal(id, patch) {\n const { actor, ...taskPatch } = patch;\n const { storage, index } = await this.init();\n const currentTask = await storage.load(id);\n if (!currentTask) {\n throw new Error(`Task ${id} not found`);\n }\n const normalizeEvidence = (value) => value?.map((entry) => entry.trim()).filter(Boolean);\n const normalizeText = (value) => {\n if (value === undefined)\n return undefined;\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n };\n const hasOwn = (key) => Object.hasOwn(taskPatch, key);\n const normalizeStringArray = (value) => {\n if (!value)\n return value;\n return value.map((entry) => entry.trim()).filter(Boolean);\n };\n const statusProvided = taskPatch.status !== undefined;\n const tagsProvided = hasOwn(\"tags\");\n const dependsProvided = hasOwn(\"depends_on\");\n const blockedProvided = hasOwn(\"blocked_by\");\n const deletedProvided = hasOwn(\"deleted_at\");\n const validationProvided = hasOwn(\"validation_steps\");\n const nextStatus = taskPatch.status ?? currentTask.status;\n const nextPriority = taskPatch.priority ?? currentTask.priority;\n const nextEvidence = normalizeEvidence(taskPatch.evidence) ?? currentTask.evidence;\n const nextTags = tagsProvided\n ? (normalizeStringArray(taskPatch.tags) ?? [])\n : currentTask.tags;\n const nextType = taskPatch.type ?? currentTask.type;\n const nextEstimate = taskPatch.estimate_hours ?? currentTask.estimate_hours;\n const nextDependsOn = dependsProvided\n ? (normalizeStringArray(taskPatch.depends_on) ?? [])\n : currentTask.depends_on;\n const nextBlockedBy = blockedProvided\n ? (normalizeStringArray(taskPatch.blocked_by) ?? [])\n : currentTask.blocked_by;\n const nextRecurrence = taskPatch.recurrence_rule ?? currentTask.recurrence_rule;\n const nextOwner = taskPatch.owner_id ?? currentTask.owner_id;\n const nextReviewer = taskPatch.reviewer_id ?? currentTask.reviewer_id;\n const taskContextProvided = taskPatch.task_context !== undefined;\n const taskContextSummaryProvided = taskPatch.task_context_summary !== undefined;\n const nextTaskContext = taskContextProvided\n ? normalizeText(taskPatch.task_context)\n : currentTask.task_context;\n let nextTaskContextSummary = taskContextSummaryProvided\n ? normalizeText(taskPatch.task_context_summary)\n : currentTask.task_context_summary;\n const nextValidationSteps = validationProvided\n ? (normalizeStringArray(taskPatch.validation_steps) ?? [])\n : currentTask.validation_steps;\n const blockingIds = await this.getBlockingIds(nextDependsOn, nextBlockedBy, storage);\n const hasBlocking = blockingIds.length > 0;\n if (nextStatus === \"done\" && hasBlocking) {\n throw new Error(\"Cannot mark task as done while dependencies are incomplete.\");\n }\n let effectiveStatus = nextStatus;\n if (hasBlocking) {\n effectiveStatus = \"blocked\";\n }\n else if (!statusProvided && currentTask.status === \"blocked\") {\n effectiveStatus = \"todo\";\n }\n if (effectiveStatus === \"done\" && currentTask.status !== \"done\") {\n if (!taskPatch.reasoning) {\n throw new Error(\"Reasoning is required to mark a task as done.\");\n }\n if (!nextEvidence || nextEvidence.length === 0) {\n throw new Error(\"Evidence is required to mark a task as done. Provide file paths or verification commands.\");\n }\n if (nextValidationSteps && nextValidationSteps.length > 0) {\n const evidenceBlob = nextEvidence.join(\" \").toLowerCase();\n const missing = nextValidationSteps.filter((step) => !evidenceBlob.includes(step.toLowerCase()));\n if (missing.length > 0) {\n throw new Error(`Missing validation evidence for: ${missing.join(\", \")}.`);\n }\n }\n }\n const actions = currentTask.actions || [];\n const timestamp = new Date().toISOString();\n const actorValue = actor?.trim() || undefined;\n if (effectiveStatus !== currentTask.status) {\n actions.push({\n type: effectiveStatus === \"done\" ? \"completion\" : \"update_status\",\n reasoning: taskPatch.reasoning ?? null,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n else if (nextPriority !== currentTask.priority) {\n actions.push({\n type: \"update_priority\",\n reasoning: taskPatch.reasoning ?? null,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n else if (taskPatch.reasoning) {\n actions.push({\n type: \"comment\",\n reasoning: taskPatch.reasoning,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n if (tagsProvided) {\n const prevTags = currentTask.tags ?? [];\n const next = nextTags ?? [];\n if (prevTags.join(\"|\") !== next.join(\"|\")) {\n actions.push({\n type: \"update_tags\",\n reasoning: taskPatch.reasoning ?? null,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n }\n if (nextType !== currentTask.type) {\n actions.push({\n type: \"update_type\",\n reasoning: taskPatch.reasoning ?? null,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n if (nextEstimate !== currentTask.estimate_hours) {\n actions.push({\n type: \"update_estimate\",\n reasoning: taskPatch.reasoning ?? null,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n if (dependsProvided || blockedProvided) {\n const prevDepends = currentTask.depends_on ?? [];\n const prevBlocked = currentTask.blocked_by ?? [];\n const nextDepends = nextDependsOn ?? [];\n const nextBlocked = nextBlockedBy ?? [];\n if (prevDepends.join(\"|\") !== nextDepends.join(\"|\") ||\n prevBlocked.join(\"|\") !== nextBlocked.join(\"|\")) {\n actions.push({\n type: \"update_dependencies\",\n reasoning: taskPatch.reasoning ?? null,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n }\n if (nextRecurrence !== currentTask.recurrence_rule) {\n actions.push({\n type: \"update_recurrence\",\n reasoning: taskPatch.reasoning ?? null,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n if (nextOwner !== currentTask.owner_id) {\n actions.push({\n type: \"update_owner\",\n reasoning: taskPatch.reasoning ?? null,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n if (nextReviewer !== currentTask.reviewer_id) {\n actions.push({\n type: \"update_reviewer\",\n reasoning: taskPatch.reasoning ?? null,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n if (deletedProvided && taskPatch.deleted_at !== currentTask.deleted_at) {\n actions.push({\n type: \"delete\",\n reasoning: taskPatch.reasoning ?? null,\n actor: actorValue ?? null,\n created_at: timestamp,\n });\n }\n let finalTaskContext = nextTaskContext;\n if (effectiveStatus === \"done\" && finalTaskContext) {\n if (!nextTaskContextSummary) {\n nextTaskContextSummary = summarizeTaskContext(finalTaskContext);\n }\n finalTaskContext = undefined;\n }\n const updatedTask = {\n ...currentTask,\n ...taskPatch,\n status: effectiveStatus,\n tags: nextTags,\n type: nextType,\n estimate_hours: nextEstimate,\n depends_on: nextDependsOn,\n blocked_by: nextBlockedBy,\n recurrence_rule: nextRecurrence,\n owner_id: nextOwner,\n reviewer_id: nextReviewer,\n evidence: nextEvidence,\n task_context: finalTaskContext,\n task_context_summary: nextTaskContextSummary,\n validation_steps: nextValidationSteps,\n actions,\n updated_at: timestamp,\n };\n // @ts-expect-error\n delete updatedTask.reasoning;\n // @ts-expect-error\n delete updatedTask.actor;\n await storage.save(updatedTask);\n await index.updateEntry({\n id: updatedTask.id,\n title: updatedTask.title,\n status: updatedTask.status,\n assignee: updatedTask.assignee,\n priority: updatedTask.priority,\n updated_at: updatedTask.updated_at,\n });\n if (updatedTask.parent_id) {\n await this.syncParentStatus(updatedTask.parent_id, storage);\n }\n return updatedTask;\n }\n async syncParentStatus(parentId, storage) {\n const parent = await storage.load(parentId);\n if (!parent)\n return;\n const allTasks = await storage.loadAll();\n const subtasks = allTasks.filter((task) => task.parent_id === parentId && !task.deleted_at);\n if (subtasks.length === 0)\n return;\n const allDone = subtasks.every((task) => task.status === \"done\");\n if (allDone) {\n if (parent.status === \"done\")\n return;\n const subtaskIds = subtasks.map((task) => task.id).join(\", \");\n await this.updateTaskInternal(parentId, {\n status: \"done\",\n reasoning: \"Auto-completed because all subtasks are done.\",\n evidence: [`Subtasks completed: ${subtaskIds}`],\n });\n return;\n }\n if (parent.status !== \"done\")\n return;\n await this.updateTaskInternal(parentId, {\n status: \"in-progress\",\n reasoning: \"Auto-reopened because a subtask is not done.\",\n });\n }\n async getBlockingIds(dependsOn, blockedBy, storage) {\n const blockers = new Set();\n const ids = [...(dependsOn ?? []), ...(blockedBy ?? [])].filter(Boolean);\n if (ids.length === 0)\n return [];\n for (const id of ids) {\n const task = await storage.load(id);\n if (!task || task.deleted_at || task.status !== \"done\") {\n blockers.add(id);\n }\n }\n return Array.from(blockers);\n }\n async archiveTasks(options) {\n const { storage, index } = await this.init();\n const entries = await index.load();\n if (!options.status && options.olderThanDays === undefined) {\n throw new Error(\"Must provide at least one filter (status or olderThanDays)\");\n }\n const now = new Date();\n const threshold = options.olderThanDays !== undefined\n ? new Date(now.getTime() - options.olderThanDays * 24 * 60 * 60 * 1000)\n : null;\n const candidates = entries.filter((entry) => {\n let matches = true;\n if (options.status) {\n matches = matches && entry.status === options.status;\n }\n if (threshold && entry.updated_at) {\n matches = matches && new Date(entry.updated_at) < threshold;\n }\n return matches;\n });\n if (candidates.length === 0)\n return 0;\n const vemDir = await getVemDir();\n const baseDir = path.join(vemDir, TASKS_DIR);\n const archiveBase = path.join(baseDir, \"archive\");\n await fs.ensureDir(archiveBase);\n let count = 0;\n for (const entry of candidates) {\n const task = await storage.load(entry.id);\n if (task) {\n const date = new Date(task.created_at || new Date());\n const folder = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, \"0\")}`;\n const targetDir = path.join(archiveBase, folder);\n await fs.ensureDir(targetDir);\n const destWithId = path.join(targetDir, `${task.id}.json`);\n await fs.writeJson(destWithId, task, { spaces: 2 });\n // Remove from active storage and index\n await storage.delete(entry.id);\n await index.removeEntry(entry.id);\n count++;\n }\n }\n return count;\n }\n}\n","import crypto from \"node:crypto\";\nimport path from \"node:path\";\nimport fs from \"fs-extra\";\nexport class ShardedFileStorage {\n baseDir;\n objectsDirName;\n constructor(baseDir, objectsDirName = \"objects\") {\n this.baseDir = baseDir;\n this.objectsDirName = objectsDirName;\n }\n getObjectsDir() {\n return path.join(this.baseDir, this.objectsDirName);\n }\n getShard(id) {\n const hash = crypto.createHash(\"sha1\").update(id).digest(\"hex\");\n return hash.substring(0, 2);\n }\n getFilePath(id) {\n const shard = this.getShard(id);\n return path.join(this.getObjectsDir(), shard, `${id}.json`);\n }\n async save(record) {\n const filePath = this.getFilePath(record.id);\n await fs.ensureDir(path.dirname(filePath));\n await fs.writeJson(filePath, record, { spaces: 2 });\n }\n async load(id) {\n const filePath = this.getFilePath(id);\n if (!(await fs.pathExists(filePath))) {\n return null;\n }\n return fs.readJson(filePath);\n }\n async delete(id) {\n const filePath = this.getFilePath(id);\n if (await fs.pathExists(filePath)) {\n await fs.remove(filePath);\n }\n }\n async listIds() {\n const objectsDir = this.getObjectsDir();\n if (!(await fs.pathExists(objectsDir))) {\n return [];\n }\n const shards = await fs.readdir(objectsDir);\n const ids = [];\n for (const shard of shards) {\n const shardPath = path.join(objectsDir, shard);\n const stat = await fs.stat(shardPath);\n if (!stat.isDirectory())\n continue;\n const files = await fs.readdir(shardPath);\n for (const file of files) {\n if (file.endsWith(\".json\")) {\n ids.push(path.parse(file).name);\n }\n }\n }\n return ids;\n }\n async loadAll() {\n const ids = await this.listIds();\n const result = [];\n for (const id of ids) {\n const record = await this.load(id);\n if (record) {\n result.push(record);\n }\n }\n return result;\n }\n}\nexport class TaskIndex {\n indexPath;\n constructor(baseDir) {\n this.indexPath = path.join(baseDir, \"index.json\");\n }\n async load() {\n if (!(await fs.pathExists(this.indexPath))) {\n return [];\n }\n try {\n const data = await fs.readJson(this.indexPath);\n return data.entries || [];\n }\n catch {\n return [];\n }\n }\n async save(entries) {\n await fs.ensureDir(path.dirname(this.indexPath));\n await fs.writeJson(this.indexPath, { entries }, { spaces: 2 });\n }\n async updateEntry(entry) {\n const entries = await this.load();\n const index = entries.findIndex((e) => e.id === entry.id);\n if (index !== -1) {\n entries[index] = entry;\n }\n else {\n entries.push(entry);\n }\n await this.save(entries);\n }\n async removeEntry(id) {\n const entries = await this.load();\n const filtered = entries.filter((e) => e.id !== id);\n await this.save(filtered);\n }\n}\n","/** Convert a CopilotSession / CopilotSessionDetail to the unified AgentSession shape. */\nexport function fromCopilotSession(s) {\n return {\n id: s.id,\n source: \"copilot\",\n summary: s.summary,\n branch: s.branch,\n repository: s.repository,\n git_root: s.git_root,\n cwd: s.cwd,\n created_at: s.created_at,\n updated_at: s.updated_at,\n intents: \"intents\" in s ? s.intents : [],\n user_messages: \"user_messages\" in s ? s.user_messages : [],\n };\n}\n/**\n * List agent sessions from all supported tools (Copilot, Claude, Gemini),\n * optionally filtered to the given git root, sorted newest-first.\n */\nexport async function listAllAgentSessions(gitRoot, sources = [\"copilot\", \"claude\", \"gemini\"]) {\n const [{ listCopilotSessions }, { listClaudeSessions }, { listGeminiSessions },] = await Promise.all([\n import(\"./copilot-sessions.js\"),\n import(\"./claude-sessions.js\"),\n import(\"./gemini-sessions.js\"),\n ]);\n const results = await Promise.all([\n sources.includes(\"copilot\")\n ? listCopilotSessions(gitRoot).then((ss) => ss.map(fromCopilotSession))\n : Promise.resolve([]),\n sources.includes(\"claude\")\n ? listClaudeSessions(gitRoot)\n : Promise.resolve([]),\n sources.includes(\"gemini\")\n ? listGeminiSessions(gitRoot)\n : Promise.resolve([]),\n ]);\n const all = results.flat();\n all.sort((a, b) => {\n if (!a.updated_at)\n return 1;\n if (!b.updated_at)\n return -1;\n return b.updated_at.localeCompare(a.updated_at);\n });\n return all;\n}\n/**\n * Compute statistics for a session from any supported agent tool.\n * Returns null if stats cannot be computed.\n */\nexport async function computeSessionStats(sessionId, source) {\n const { computeCopilotSessionStats } = await import(\"./copilot-sessions.js\");\n const { computeClaudeSessionStats } = await import(\"./claude-sessions.js\");\n const { computeGeminiSessionStats } = await import(\"./gemini-sessions.js\");\n switch (source) {\n case \"copilot\":\n return computeCopilotSessionStats(sessionId);\n case \"claude\":\n return computeClaudeSessionStats(sessionId);\n case \"gemini\":\n return computeGeminiSessionStats(sessionId);\n default:\n return null;\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport { homedir, hostname } from \"node:os\";\nimport path from \"node:path\";\nimport fs from \"fs-extra\";\nimport { CONTEXT_FILE, DECISIONS_DIR, getVemDir } from \"./fs.js\";\nimport { getGitHeadHash } from \"./git.js\";\nimport { ScalableLogService } from \"./logs.js\";\nexport const CONFIG_FILE = \"config.json\";\nexport class ConfigService {\n async getLocalPath() {\n const dir = await getVemDir();\n return path.join(dir, CONFIG_FILE);\n }\n getGlobalPath() {\n return path.join(homedir(), \".vem\", CONFIG_FILE);\n }\n async readLocalConfig() {\n try {\n // If we are not in a repo, getLocalPath might throw or we just catch it here\n const filePath = await this.getLocalPath();\n if (!(await fs.pathExists(filePath)))\n return {};\n return fs.readJson(filePath);\n }\n catch {\n // Ignore error (e.g. not in a repo), return empty local config\n return {};\n }\n }\n async readGlobalConfig() {\n try {\n const filePath = this.getGlobalPath();\n if (!(await fs.pathExists(filePath)))\n return {};\n return fs.readJson(filePath);\n }\n catch {\n return {};\n }\n }\n async writeLocalConfig(update) {\n const filePath = await this.getLocalPath();\n const current = await this.readLocalConfig();\n const next = { ...current, ...update };\n // Only write valid local keys to local config\n const clean = {\n last_version: next.last_version,\n project_id: next.project_id,\n project_org_id: next.project_org_id,\n linked_remote_name: next.linked_remote_name,\n linked_remote_url: next.linked_remote_url,\n last_push_git_hash: next.last_push_git_hash,\n last_push_vem_hash: next.last_push_vem_hash,\n last_synced_vem_hash: next.last_synced_vem_hash,\n };\n await fs.outputJson(filePath, clean, { spaces: 2 });\n }\n async writeGlobalConfig(update) {\n const filePath = this.getGlobalPath();\n const current = await this.readGlobalConfig();\n const next = { ...current, ...update };\n // Only write valid global keys to global config\n const clean = {\n api_key: next.api_key,\n device_id: next.device_id,\n device_name: next.device_name,\n };\n await fs.outputJson(filePath, clean, { spaces: 2 });\n }\n // --- Global Scoped ---\n async getApiKey() {\n const config = await this.readGlobalConfig();\n return config.api_key || process.env.VEM_API_KEY;\n }\n async getDeviceId() {\n const config = await this.readGlobalConfig();\n return config.device_id;\n }\n async getOrCreateDeviceId() {\n const config = await this.readGlobalConfig();\n if (config.device_id && config.device_name) {\n return { deviceId: config.device_id, deviceName: config.device_name };\n }\n let deviceId = config.device_id;\n if (!deviceId) {\n deviceId = randomUUID();\n }\n let deviceName = config.device_name;\n if (!deviceName) {\n deviceName = hostname();\n }\n await this.writeGlobalConfig({\n device_id: deviceId,\n device_name: deviceName,\n });\n return { deviceId, deviceName };\n }\n async setApiKey(key) {\n await this.writeGlobalConfig({ api_key: key || undefined });\n }\n // --- Local Scoped ---\n async getProjectId() {\n const config = await this.readLocalConfig();\n return config.project_id || process.env.VEM_PROJECT_ID;\n }\n async getProjectOrgId() {\n const config = await this.readLocalConfig();\n return config.project_org_id;\n }\n async getLinkedRemoteName() {\n const config = await this.readLocalConfig();\n return config.linked_remote_name;\n }\n async getLinkedRemoteUrl() {\n const config = await this.readLocalConfig();\n return config.linked_remote_url;\n }\n async getLastVersion() {\n const config = await this.readLocalConfig();\n return config.last_version;\n }\n async setLastVersion(version) {\n await this.writeLocalConfig({ last_version: version });\n }\n async getLastPushState() {\n const config = await this.readLocalConfig();\n return {\n gitHash: config.last_push_git_hash,\n vemHash: config.last_push_vem_hash,\n };\n }\n async setLastPushState(state) {\n await this.writeLocalConfig({\n last_push_git_hash: state.gitHash,\n last_push_vem_hash: state.vemHash,\n });\n }\n async getLastSyncedVemHash() {\n const config = await this.readLocalConfig();\n return config.last_synced_vem_hash;\n }\n async setLastSyncedVemHash(vemHash) {\n await this.writeLocalConfig({\n last_synced_vem_hash: vemHash || undefined,\n });\n }\n async setProjectId(projectId) {\n await this.writeLocalConfig({ project_id: projectId || undefined });\n }\n async setProjectOrgId(orgId) {\n await this.writeLocalConfig({ project_org_id: orgId || undefined });\n }\n async setLinkedRemote(binding) {\n await this.writeLocalConfig({\n linked_remote_name: binding?.name || undefined,\n linked_remote_url: binding?.url || undefined,\n });\n }\n // --- Context (Local) ---\n async getContextPath() {\n try {\n const dir = await getVemDir();\n return path.join(dir, CONTEXT_FILE);\n }\n catch {\n return \"\";\n }\n }\n async getContext() {\n const filePath = await this.getContextPath();\n if (!filePath || !(await fs.pathExists(filePath))) {\n return \"\";\n }\n return fs.readFile(filePath, \"utf-8\");\n }\n async updateContext(content) {\n const filePath = await this.getContextPath();\n if (!filePath)\n throw new Error(\"Cannot update context: Not in a git repository.\");\n await fs.writeFile(filePath, content, \"utf-8\");\n }\n async recordDecision(title, context, decision, relatedTasks) {\n const decisionsLog = new ScalableLogService(DECISIONS_DIR);\n let entry = `**Decision:** ${decision}\\n\\n**Context:** ${context}`;\n if (relatedTasks && relatedTasks.length > 0) {\n entry = `**Related Tasks:** ${relatedTasks.join(\", \")}\\n\\n${entry}`;\n }\n const commitHash = await getGitHeadHash();\n await decisionsLog.addEntry(title, entry, { commitHash });\n }\n}\n","import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\nimport fs from \"fs-extra\";\nimport { CHANGELOG_DIR, CONTEXT_FILE, CURRENT_STATE_FILE, DECISIONS_DIR, getVemDir, } from \"./fs.js\";\nimport { ScalableLogService } from \"./logs.js\";\nimport { TaskService } from \"./tasks.js\";\nfunction _hashContent(content) {\n return createHash(\"sha256\").update(content).digest(\"hex\").slice(0, 8);\n}\nexport class DiffService {\n async compareWithLastPush(_lastPushData) {\n // For now, we'll implement a simplified version that compares local state\n // In a full implementation, this would fetch from cloud API\n const vemDir = await getVemDir();\n const taskService = new TaskService();\n const tasks = await taskService.getTasks();\n const decisionsService = new ScalableLogService(DECISIONS_DIR);\n const decisions = await decisionsService.getAllEntries();\n const changelogService = new ScalableLogService(CHANGELOG_DIR);\n const changelog = await changelogService.getAllEntries();\n const currentStatePath = path.join(vemDir, CURRENT_STATE_FILE);\n const currentStateExists = await fs.pathExists(currentStatePath);\n const currentStateContent = currentStateExists\n ? await fs.readFile(currentStatePath, \"utf-8\")\n : \"\";\n const contextPath = path.join(vemDir, CONTEXT_FILE);\n const contextExists = await fs.pathExists(contextPath);\n const contextContent = contextExists\n ? await fs.readFile(contextPath, \"utf-8\")\n : \"\";\n // Simplified diff - in real implementation, compare with lastPushData\n // For now, we'll just report what exists locally\n const result = {\n tasks: {\n added: tasks.filter((t) => t.status !== \"done\").map((t) => t.id),\n modified: [],\n deleted: [],\n },\n decisions: {\n added: decisions.map((d) => d.id),\n modified: [],\n deleted: [],\n },\n changelog: {\n added: changelog.map((c) => c.id),\n modified: [],\n deleted: [],\n },\n currentState: {\n changed: currentStateContent.length > 0,\n lineCount: currentStateContent.split(\"\\n\").length,\n },\n context: {\n changed: contextContent.length > 0,\n },\n summary: {\n totalChanges: 0,\n },\n };\n result.summary.totalChanges =\n result.tasks.added.length +\n result.tasks.modified.length +\n result.decisions.added.length +\n result.changelog.added.length +\n (result.currentState.changed ? 1 : 0);\n return result;\n }\n}\n","import path from \"node:path\";\nimport fs from \"fs-extra\";\nimport { ConfigService } from \"./config.js\";\nimport { CHANGELOG_DIR, CONTEXT_FILE, CURRENT_STATE_FILE, DECISIONS_DIR, getRepoRoot, getVemDir, TASKS_DIR, } from \"./fs.js\";\nimport { TaskService } from \"./tasks.js\";\nexport class DoctorService {\n configService = new ConfigService();\n taskService = new TaskService();\n async runAllChecks() {\n const results = [];\n // Authentication checks\n results.push(await this.checkApiKey());\n results.push(await this.checkDeviceId());\n // Project setup checks\n results.push(await this.checkProjectLinked());\n results.push(await this.checkVemDirectory());\n results.push(await this.checkRequiredFiles());\n // Git integration checks\n results.push(await this.checkGitRepository());\n // Data integrity checks\n results.push(await this.checkTaskIntegrity());\n return results;\n }\n async checkApiKey() {\n try {\n const apiKey = await this.configService.getApiKey();\n if (!apiKey) {\n return {\n name: \"API Key\",\n status: \"fail\",\n message: \"API key not configured\",\n fix: \"Run: vem login\",\n autoFixable: false,\n };\n }\n return {\n name: \"API Key\",\n status: \"pass\",\n message: \"API key configured\",\n };\n }\n catch (error) {\n return {\n name: \"API Key\",\n status: \"fail\",\n message: `Error checking API key: ${error.message}`,\n autoFixable: false,\n };\n }\n }\n async checkDeviceId() {\n try {\n const deviceId = await this.configService.getDeviceId();\n if (!deviceId) {\n return {\n name: \"Device ID\",\n status: \"warn\",\n message: \"Device ID not registered (will be created on next operation)\",\n autoFixable: true,\n };\n }\n return {\n name: \"Device ID\",\n status: \"pass\",\n message: \"Device ID registered\",\n };\n }\n catch (error) {\n return {\n name: \"Device ID\",\n status: \"fail\",\n message: `Error checking device ID: ${error.message}`,\n autoFixable: false,\n };\n }\n }\n async checkProjectLinked() {\n try {\n const projectId = await this.configService.getProjectId();\n if (!projectId) {\n return {\n name: \"Project Link\",\n status: \"fail\",\n message: \"Project not linked to cloud\",\n fix: \"Run: vem init\",\n autoFixable: false,\n };\n }\n return {\n name: \"Project Link\",\n status: \"pass\",\n message: `Project linked (${projectId})`,\n };\n }\n catch (error) {\n return {\n name: \"Project Link\",\n status: \"fail\",\n message: `Error checking project link: ${error.message}`,\n autoFixable: false,\n };\n }\n }\n async checkVemDirectory() {\n try {\n const vemDir = await getVemDir();\n const exists = await fs.pathExists(vemDir);\n if (!exists) {\n return {\n name: \".vem Directory\",\n status: \"fail\",\n message: \".vem/ directory does not exist\",\n fix: \"Run: vem init\",\n autoFixable: true,\n };\n }\n // Check subdirectories\n const tasksDir = path.join(vemDir, TASKS_DIR);\n const decisionsDir = path.join(vemDir, DECISIONS_DIR);\n const changelogDir = path.join(vemDir, CHANGELOG_DIR);\n const tasksDirExists = await fs.pathExists(tasksDir);\n const decisionsDirExists = await fs.pathExists(decisionsDir);\n const changelogDirExists = await fs.pathExists(changelogDir);\n if (!tasksDirExists || !decisionsDirExists || !changelogDirExists) {\n return {\n name: \".vem Directory\",\n status: \"warn\",\n message: \"Missing subdirectories in .vem/\",\n fix: \"Run: vem init\",\n autoFixable: true,\n };\n }\n return {\n name: \".vem Directory\",\n status: \"pass\",\n message: \".vem/ directory structure valid\",\n };\n }\n catch (error) {\n return {\n name: \".vem Directory\",\n status: \"fail\",\n message: `Error checking .vem directory: ${error.message}`,\n autoFixable: false,\n };\n }\n }\n async checkRequiredFiles() {\n try {\n const vemDir = await getVemDir();\n const contextPath = path.join(vemDir, CONTEXT_FILE);\n const currentStatePath = path.join(vemDir, CURRENT_STATE_FILE);\n const contextExists = await fs.pathExists(contextPath);\n const currentStateExists = await fs.pathExists(currentStatePath);\n if (!contextExists || !currentStateExists) {\n return {\n name: \"Required Files\",\n status: \"warn\",\n message: \"Missing CONTEXT.md or CURRENT_STATE.md\",\n fix: \"Run: vem init\",\n autoFixable: true,\n };\n }\n return {\n name: \"Required Files\",\n status: \"pass\",\n message: \"All required files present\",\n };\n }\n catch (error) {\n return {\n name: \"Required Files\",\n status: \"fail\",\n message: `Error checking required files: ${error.message}`,\n autoFixable: false,\n };\n }\n }\n async checkGitRepository() {\n try {\n await getRepoRoot();\n return {\n name: \"Git Repository\",\n status: \"pass\",\n message: \"Inside git repository\",\n };\n }\n catch (_error) {\n return {\n name: \"Git Repository\",\n status: \"fail\",\n message: \"Not inside a git repository\",\n autoFixable: false,\n };\n }\n }\n async checkTaskIntegrity() {\n try {\n const tasks = await this.taskService.getTasks();\n // Check for duplicate IDs\n const ids = new Set();\n const duplicates = [];\n for (const task of tasks) {\n if (ids.has(task.id)) {\n duplicates.push(task.id);\n }\n ids.add(task.id);\n }\n if (duplicates.length > 0) {\n return {\n name: \"Task Integrity\",\n status: \"fail\",\n message: `Duplicate task IDs found: ${duplicates.join(\", \")}`,\n autoFixable: false,\n };\n }\n // Check for orphaned references\n const orphanedRefs = [];\n for (const task of tasks) {\n if (task.blocked_by) {\n for (const blockerId of task.blocked_by) {\n if (!ids.has(blockerId)) {\n orphanedRefs.push(`${task.id} references ${blockerId}`);\n }\n }\n }\n }\n if (orphanedRefs.length > 0) {\n return {\n name: \"Task Integrity\",\n status: \"warn\",\n message: `Orphaned task references: ${orphanedRefs[0]}`,\n fix: `Run: vem task update ${orphanedRefs[0].split(\" \")[0]} --blocked-by \"\"`,\n autoFixable: false,\n };\n }\n return {\n name: \"Task Integrity\",\n status: \"pass\",\n message: `All ${tasks.length} tasks valid`,\n };\n }\n catch (error) {\n return {\n name: \"Task Integrity\",\n status: \"fail\",\n message: `Error checking task integrity: ${error.message}`,\n autoFixable: false,\n };\n }\n }\n}\n","import { z } from \"zod\";\n/**\n * Validates environment variables against a schema and exits the process if invalid.\n */\nexport function validateEnv(schema, serviceName) {\n try {\n return schema.parse(process.env);\n }\n catch (error) {\n if (error instanceof z.ZodError) {\n console.error(`\\n❌ Invalid environment variables for ${serviceName}:`);\n for (const issue of error.issues) {\n console.error(` - ${issue.path.join(\".\")}: ${issue.message}`);\n }\n console.error(\"\\nPlease check your .env file or deployment configuration.\\n\");\n process.exit(1);\n }\n throw error;\n }\n}\n/**\n * Common environment variables used across multiple services.\n */\nexport const commonEnvSchema = {\n NODE_ENV: z\n .enum([\"development\", \"production\", \"test\"])\n .default(\"development\"),\n INTERNAL_API_SECRET: z.string().min(1, \"INTERNAL_API_SECRET is required\"),\n DATABASE_URL: z.string().url(\"DATABASE_URL must be a valid URL\"),\n};\n","import { createPrivateKey } from \"node:crypto\";\nconst PEM_BEGIN_PATTERN = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/;\nconst PEM_END_PATTERN = /-----END [A-Z0-9 ]*PRIVATE KEY-----/;\nconst PEM_ANY_PATTERN = /(-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----)([\\s\\S]*?)(-----END [A-Z0-9 ]*PRIVATE KEY-----)/;\nfunction hasPemMarkers(value) {\n return PEM_BEGIN_PATTERN.test(value) && PEM_END_PATTERN.test(value);\n}\nfunction stripWrappingQuotes(value) {\n if (value.length < 2)\n return value;\n const first = value[0];\n const last = value[value.length - 1];\n if ((first === '\"' && last === '\"') || (first === \"'\" && last === \"'\")) {\n return value.slice(1, -1);\n }\n return value;\n}\nfunction normalizeLineBreaks(value) {\n return value\n .replace(/\\\\r\\\\n/g, \"\\n\")\n .replace(/\\\\n/g, \"\\n\")\n .replace(/\\\\r/g, \"\\n\")\n .replace(/\\r\\n/g, \"\\n\")\n .replace(/\\r/g, \"\\n\");\n}\nfunction stripBase64DataPrefix(value) {\n const match = value.match(/^data:[^;]+;base64,(.+)$/i);\n return match ? match[1] : value;\n}\nfunction canonicalizePem(value) {\n const match = value.match(PEM_ANY_PATTERN);\n if (!match)\n return value;\n const [, begin, body, end] = match;\n const compactBody = body.replace(/\\s+/g, \"\");\n if (!compactBody)\n return value;\n const wrappedBody = compactBody.match(/.{1,64}/g)?.join(\"\\n\") ?? compactBody;\n return `${begin}\\n${wrappedBody}\\n${end}\\n`;\n}\nfunction tryDecodeBase64Pem(value) {\n const compact = value.replace(/\\s+/g, \"\");\n if (!compact || compact.length % 4 !== 0)\n return value;\n if (!/^[A-Za-z0-9+/=]+$/.test(compact))\n return value;\n try {\n const decoded = Buffer.from(compact, \"base64\").toString(\"utf8\");\n return hasPemMarkers(decoded) ? decoded : value;\n }\n catch {\n return value;\n }\n}\n/**\n * Accepts common deployment representations for GitHub App private keys:\n * - Raw multiline PEM\n * - PEM with escaped newlines (\\n)\n * - Base64-encoded PEM payload\n */\nexport function normalizeGithubPrivateKey(rawValue) {\n let normalized = normalizeLineBreaks(stripWrappingQuotes(rawValue.trim()));\n if (!hasPemMarkers(normalized)) {\n const maybeBase64 = stripBase64DataPrefix(stripWrappingQuotes(normalized.trim()));\n normalized = normalizeLineBreaks(stripWrappingQuotes(tryDecodeBase64Pem(maybeBase64).trim()));\n }\n normalized = canonicalizePem(normalized);\n if (!hasPemMarkers(normalized)) {\n throw new Error(\"Invalid GH_PRIVATE_KEY format. Expected PEM (raw PEM, escaped \\\\n PEM, or base64-encoded PEM).\");\n }\n if (!normalized.endsWith(\"\\n\")) {\n normalized = `${normalized}\\n`;\n }\n try {\n createPrivateKey(normalized);\n }\n catch (error) {\n throw new Error(`Invalid GH_PRIVATE_KEY content. Parsed as PEM but Node/OpenSSL rejected it: ${String(error?.message ?? error)}`);\n }\n return normalized;\n}\n","import pino from \"pino\";\nconst isDev = process.env.NODE_ENV === \"development\";\nexport const logger = pino({\n level: process.env.LOG_LEVEL || \"info\",\n // GCP Cloud Logging uses 'severity' instead of 'level'\n // We map pino levels to Google Cloud severity levels\n formatters: {\n level(label) {\n return { severity: label.toUpperCase() };\n },\n },\n // In development, we use pino-pretty for readability\n // In production, we want raw JSON for Cloud Logging\n transport: isDev\n ? {\n target: \"pino-pretty\",\n options: {\n colorize: true,\n ignore: \"pid,hostname\",\n translateTime: \"SYS:standard\",\n },\n }\n : undefined,\n serializers: {\n err: pino.stdSerializers.err,\n error: pino.stdSerializers.err,\n },\n redact: {\n paths: [\n \"req.headers.authorization\",\n \"req.headers['x-api-key']\",\n \"*.password\",\n \"*.secret\",\n \"*.token\",\n ],\n remove: true,\n },\n});\n","import { createHash, timingSafeEqual } from \"node:crypto\";\n/**\n * Compares a bearer token against a secret using constant-time comparison.\n * Both values are hashed to a fixed-length digest before comparison so that\n * the comparison time does not leak the secret's length.\n */\nexport function bearerSecretMatches(token, secret) {\n const expected = createHash(\"sha256\").update(secret).digest();\n const actual = createHash(\"sha256\").update(token).digest();\n return timingSafeEqual(actual, expected);\n}\nconst SECRET_PATTERNS = [\n {\n name: \"private_key\",\n regex: /-----BEGIN (?:RSA|EC|DSA|OPENSSH|PGP) PRIVATE KEY-----/g,\n replace: \"[REDACTED:private_key]\",\n },\n {\n name: \"aws_access_key\",\n regex: /\\bAKIA[0-9A-Z]{16}\\b/g,\n replace: \"[REDACTED:aws_access_key]\",\n },\n {\n name: \"aws_secret_key\",\n regex: /\\b(aws_secret_access_key)\\b\\s*[:=]\\s*([A-Za-z0-9/+=]{40})/gi,\n replace: (_match, key) => `${key}=[REDACTED:aws_secret_key]`,\n },\n {\n name: \"github_token\",\n regex: /\\bghp_[A-Za-z0-9]{36}\\b/g,\n replace: \"[REDACTED:github_token]\",\n },\n {\n name: \"github_pat\",\n regex: /\\bgithub_pat_[A-Za-z0-9_]{22,}\\b/g,\n replace: \"[REDACTED:github_pat]\",\n },\n {\n name: \"slack_token\",\n regex: /\\bxox[baprs]-[A-Za-z0-9-]{10,}\\b/g,\n replace: \"[REDACTED:slack_token]\",\n },\n];\nexport function redactSecrets(input) {\n if (!input)\n return input;\n let output = input;\n for (const pattern of SECRET_PATTERNS) {\n if (pattern.regex.test(output)) {\n if (typeof pattern.replace === \"string\") {\n output = output.replace(pattern.regex, pattern.replace);\n }\n else {\n output = output.replace(pattern.regex, pattern.replace);\n }\n }\n pattern.regex.lastIndex = 0;\n }\n return output;\n}\nexport function detectSecrets(input) {\n if (!input)\n return [];\n const matches = new Set();\n for (const pattern of SECRET_PATTERNS) {\n if (pattern.regex.test(input)) {\n matches.add(pattern.name);\n }\n pattern.regex.lastIndex = 0;\n }\n return Array.from(matches);\n}\n","import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\nimport fs from \"fs-extra\";\nimport { CHANGELOG_DIR, CONTEXT_FILE, CURRENT_STATE_FILE, DECISIONS_DIR, getRepoRoot, getVemDir, } from \"./fs.js\";\nimport { ScalableLogService } from \"./logs.js\";\nimport { detectSecrets, redactSecrets } from \"./secrets.js\";\nimport { TaskService } from \"./tasks.js\";\nexport const KNOWN_AGENT_INSTRUCTION_FILES = [\n \"AGENTS.md\",\n \"CLAUDE.md\",\n \"GEMINI.md\",\n \"CURSOR.md\",\n \"copilot-instructions.md\",\n \"COPILOT_INSTRUCTIONS.md\",\n \".github/copilot-instructions.md\",\n];\nconst KNOWN_AGENT_INSTRUCTION_FILE_SET = new Set(KNOWN_AGENT_INSTRUCTION_FILES);\nfunction normalizeInstructionPath(value) {\n if (typeof value !== \"string\")\n return null;\n const normalized = value.trim().replace(/\\\\/g, \"/\");\n if (!normalized)\n return null;\n const collapsed = path.posix.normalize(normalized);\n if (collapsed === \".\" ||\n collapsed === \"..\" ||\n collapsed.startsWith(\"../\") ||\n collapsed.startsWith(\"/\")) {\n return null;\n }\n return KNOWN_AGENT_INSTRUCTION_FILE_SET.has(collapsed) ? collapsed : null;\n}\nconst DEFAULT_AGENT_PACK_OPTIONS = {\n contextMaxChars: 16000,\n currentStateMaxChars: 8000,\n decisionEntryLimit: 8,\n decisionMaxChars: 9000,\n decisionEntryMaxChars: 1200,\n changelogEntryLimit: 12,\n changelogMaxChars: 12000,\n changelogEntryMaxChars: 900,\n activeTaskLimit: 20,\n recentDoneTaskLimit: 5,\n taskTextMaxChars: 600,\n taskEvidenceLimit: 5,\n taskValidationLimit: 8,\n};\nfunction normalizeForSnapshotHash(value) {\n if (typeof value === \"string\") {\n return value.normalize(\"NFC\");\n }\n if (Array.isArray(value)) {\n return value.map((entry) => normalizeForSnapshotHash(entry));\n }\n if (value && typeof value === \"object\") {\n const record = value;\n const normalized = {};\n for (const key of Object.keys(record).sort((a, b) => a.localeCompare(b))) {\n const next = normalizeForSnapshotHash(record[key]);\n if (next !== undefined) {\n normalized[key] = next;\n }\n }\n return normalized;\n }\n if (typeof value === \"number\" && !Number.isFinite(value)) {\n return null;\n }\n return value;\n}\nfunction sortTasksForSnapshotHash(taskList) {\n const sortedTasks = [...taskList.tasks].sort((a, b) => a.id.localeCompare(b.id));\n return { tasks: sortedTasks };\n}\nexport function computeSnapshotHash(payload) {\n const normalizedInstructions = (payload.agent_instructions ?? [])\n .map((entry) => {\n const normalizedPath = normalizeInstructionPath(entry.path);\n if (!normalizedPath)\n return null;\n return {\n path: normalizedPath,\n content: typeof entry.content === \"string\" ? entry.content : \"\",\n };\n })\n .filter((entry) => Boolean(entry))\n .sort((a, b) => a.path.localeCompare(b.path));\n const canonical = normalizeForSnapshotHash({\n tasks: sortTasksForSnapshotHash(payload.tasks),\n context: payload.context,\n decisions: payload.decisions,\n changelog: payload.changelog,\n current_state: payload.current_state,\n agent_instructions: normalizedInstructions,\n });\n return createHash(\"sha256\")\n .update(JSON.stringify(canonical), \"utf8\")\n .digest(\"hex\");\n}\nfunction truncateText(value, maxChars) {\n if (value.length <= maxChars)\n return value;\n return `${value.slice(0, Math.max(0, maxChars - 15)).trimEnd()}\\n...[truncated]`;\n}\nfunction normalizeTaskText(value, maxChars) {\n if (!value)\n return undefined;\n const normalized = value.trim();\n if (!normalized)\n return undefined;\n return truncateText(normalized, maxChars);\n}\nfunction sortByUpdatedAtDesc(tasks) {\n return [...tasks].sort((a, b) => (b.updated_at ?? b.created_at ?? \"\").localeCompare(a.updated_at ?? a.created_at ?? \"\"));\n}\nexport class SyncService {\n taskService = new TaskService();\n decisionsLog = new ScalableLogService(DECISIONS_DIR);\n changelogLog = new ScalableLogService(CHANGELOG_DIR);\n async getQueueDir() {\n const dir = await getVemDir();\n const queueDir = path.join(dir, \"queue\");\n await fs.ensureDir(queueDir);\n return queueDir;\n }\n async getContextPath() {\n const dir = await getVemDir();\n return path.join(dir, CONTEXT_FILE);\n }\n async getCurrentStatePath() {\n const dir = await getVemDir();\n return path.join(dir, CURRENT_STATE_FILE);\n }\n async collectAgentInstructionFiles() {\n const repoRoot = await getRepoRoot();\n const files = [];\n for (const relativePath of KNOWN_AGENT_INSTRUCTION_FILES) {\n const absolutePath = path.join(repoRoot, relativePath);\n if (!(await fs.pathExists(absolutePath)))\n continue;\n const stat = await fs.stat(absolutePath);\n if (!stat.isFile())\n continue;\n const content = await fs.readFile(absolutePath, \"utf-8\");\n files.push({ path: relativePath, content });\n }\n return files;\n }\n async unpackAgentInstructionFiles(entries) {\n if (!Array.isArray(entries) || entries.length === 0)\n return;\n const repoRoot = await getRepoRoot();\n const resolvedRoot = path.resolve(repoRoot);\n for (const entry of entries) {\n const normalizedPath = normalizeInstructionPath(entry?.path);\n if (!normalizedPath)\n continue;\n if (typeof entry.content !== \"string\")\n continue;\n const destination = path.resolve(repoRoot, normalizedPath);\n if (destination !== resolvedRoot &&\n !destination.startsWith(`${resolvedRoot}${path.sep}`)) {\n continue;\n }\n await fs.ensureDir(path.dirname(destination));\n await fs.writeFile(destination, entry.content, \"utf-8\");\n }\n }\n async pack() {\n const tasks = await this.taskService.getTasks();\n const decisions = await this.decisionsLog.getMonolithicContentWithOptions({\n includeCommitHashes: true,\n });\n const changelog = await this.changelogLog.getMonolithicContentWithOptions({\n includeCommitHashes: true,\n });\n const secretMatches = [];\n const addSecretMatch = (path, value) => {\n if (!value)\n return;\n const types = detectSecrets(value);\n if (types.length > 0) {\n secretMatches.push({ path, types });\n }\n };\n const contextPath = await this.getContextPath();\n let context = \"\";\n if (await fs.pathExists(contextPath)) {\n const raw = await fs.readFile(contextPath, \"utf-8\");\n addSecretMatch(\".vem/CONTEXT.md\", raw);\n context = redactSecrets(raw);\n }\n const currentStatePath = await this.getCurrentStatePath();\n let currentState = \"\";\n if (await fs.pathExists(currentStatePath)) {\n const raw = await fs.readFile(currentStatePath, \"utf-8\");\n addSecretMatch(\".vem/CURRENT_STATE.md\", raw);\n currentState = redactSecrets(raw);\n }\n addSecretMatch(\".vem/DECISIONS.md\", decisions);\n addSecretMatch(\".vem/CHANGELOG.md\", changelog);\n const agentInstructions = await this.collectAgentInstructionFiles();\n const redactedAgentInstructions = agentInstructions.map((entry) => {\n addSecretMatch(entry.path, entry.content);\n return {\n path: entry.path,\n content: redactSecrets(entry.content),\n };\n });\n const redactedTasks = {\n tasks: tasks.map((task) => ({\n ...task,\n title: redactSecrets(task.title),\n description: task.description\n ? redactSecrets(task.description)\n : undefined,\n task_context: task.task_context\n ? redactSecrets(task.task_context)\n : undefined,\n task_context_summary: task.task_context_summary\n ? redactSecrets(task.task_context_summary)\n : undefined,\n evidence: task.evidence?.map((entry) => redactSecrets(entry)),\n })),\n };\n for (const task of tasks) {\n const basePath = `.vem/tasks/objects/${task.id}.json`;\n addSecretMatch(`${basePath}#title`, task.title);\n if (task.description) {\n addSecretMatch(`${basePath}#description`, task.description);\n }\n if (task.task_context) {\n addSecretMatch(`${basePath}#task_context`, task.task_context);\n }\n if (task.task_context_summary) {\n addSecretMatch(`${basePath}#task_context_summary`, task.task_context_summary);\n }\n if (task.evidence) {\n task.evidence.forEach((entry, index) => {\n addSecretMatch(`${basePath}#evidence[${index}]`, entry);\n });\n }\n }\n return {\n tasks: redactedTasks,\n context,\n decisions: redactSecrets(decisions),\n changelog: redactSecrets(changelog),\n current_state: currentState,\n agent_instructions: redactedAgentInstructions,\n secret_scan_report: {\n scanned_at: new Date().toISOString(),\n matches: secretMatches,\n total: secretMatches.length,\n },\n };\n }\n async buildCompactLog(log, label, entryLimit, entryMaxChars, totalMaxChars) {\n const entries = await log.getAllEntries();\n if (entries.length === 0)\n return \"\";\n const selected = entries.slice(0, entryLimit);\n const blocks = selected.map((entry) => {\n const body = truncateText(entry.content.trim(), entryMaxChars);\n return `## ${entry.title}\\n**Date:** ${entry.created_at}\\n\\n${body}`;\n });\n const header = `_Showing ${selected.length} of ${entries.length} ${label} entries._`;\n const combined = [header, ...blocks].join(\"\\n\\n---\\n\\n\");\n return truncateText(combined, totalMaxChars);\n }\n buildCompactTaskList(tasks, options) {\n const visibleTasks = tasks.filter((task) => !task.deleted_at);\n const active = sortByUpdatedAtDesc(visibleTasks.filter((task) => task.status !== \"done\")).slice(0, options.activeTaskLimit);\n const recentDone = sortByUpdatedAtDesc(visibleTasks.filter((task) => task.status === \"done\")).slice(0, options.recentDoneTaskLimit);\n const selectedById = new Map();\n for (const task of [...active, ...recentDone]) {\n selectedById.set(task.id, task);\n }\n return {\n tasks: Array.from(selectedById.values()).map((task) => ({\n id: task.id,\n title: task.title,\n status: task.status,\n priority: task.priority,\n assignee: task.assignee,\n type: task.type,\n description: normalizeTaskText(task.description, options.taskTextMaxChars),\n task_context_summary: normalizeTaskText(task.task_context_summary, options.taskTextMaxChars),\n evidence: task.evidence\n ?.slice(0, options.taskEvidenceLimit)\n .map((entry) => truncateText(entry, options.taskTextMaxChars)),\n validation_steps: task.validation_steps?.slice(0, options.taskValidationLimit),\n depends_on: task.depends_on,\n blocked_by: task.blocked_by,\n created_at: task.created_at,\n updated_at: task.updated_at,\n due_at: task.due_at,\n })),\n };\n }\n async packForAgent(options = {}) {\n const merged = {\n ...DEFAULT_AGENT_PACK_OPTIONS,\n ...options,\n };\n const full = await this.pack();\n const compactTasks = this.buildCompactTaskList(full.tasks.tasks, merged);\n const compactDecisions = await this.buildCompactLog(this.decisionsLog, \"decision\", merged.decisionEntryLimit, merged.decisionEntryMaxChars, merged.decisionMaxChars);\n const compactChangelog = await this.buildCompactLog(this.changelogLog, \"changelog\", merged.changelogEntryLimit, merged.changelogEntryMaxChars, merged.changelogMaxChars);\n return {\n ...full,\n tasks: compactTasks,\n context: truncateText(full.context, merged.contextMaxChars),\n current_state: truncateText(full.current_state, merged.currentStateMaxChars),\n decisions: compactDecisions,\n changelog: compactChangelog,\n };\n }\n async unpack(payload) {\n const vemDir = await getVemDir();\n await fs.ensureDir(vemDir);\n // Unpack tasks to sharded storage\n // Note: This replaces all local tasks with payload tasks.\n // For a real sync, we might want a merge strategy.\n const { storage, index } = await this.taskService.init();\n const taskIds = await storage.listIds();\n for (const id of taskIds) {\n await storage.delete(id);\n }\n const newIndexEntries = [];\n for (const task of payload.tasks.tasks) {\n await storage.save(task);\n newIndexEntries.push({\n id: task.id,\n title: task.title,\n status: task.status,\n assignee: task.assignee,\n priority: task.priority,\n updated_at: task.updated_at,\n });\n }\n await index.save(newIndexEntries);\n const contextPath = await this.getContextPath();\n await fs.writeFile(contextPath, payload.context, \"utf-8\");\n // Logs are harder to \"unpack\" because they are split.\n // For now, we'll just save the monolithic blob as a \"Sync-Import\" entry if it differs significantly,\n // or just rewrite the directory if we assume the server is the source of truth.\n // Given the requirement, let's just make sure they are accessible.\n // Simplified: just save as legacy files if we can't easily split back?\n // No, let's just create one big entry for the import if there's no better way.\n if (payload.decisions) {\n await this.decisionsLog.addEntry(\"Imported from Sync\", payload.decisions);\n }\n if (payload.changelog) {\n await this.changelogLog.addEntry(\"Imported from Sync\", payload.changelog);\n }\n const currentStatePath = await this.getCurrentStatePath();\n await fs.writeFile(currentStatePath, payload.current_state ?? \"\", \"utf-8\");\n await this.unpackAgentInstructionFiles(payload.agent_instructions);\n }\n async enqueue(payload) {\n const queueDir = await this.getQueueDir();\n const id = `${Date.now()}-${Math.random().toString(36).substring(2, 9)}.json`;\n const filePath = path.join(queueDir, id);\n await fs.writeJson(filePath, payload, { spaces: 2 });\n return id;\n }\n async getQueue() {\n const queueDir = await this.getQueueDir();\n const files = await fs.readdir(queueDir);\n const queue = [];\n for (const file of files) {\n if (file.endsWith(\".json\")) {\n try {\n const payload = await fs.readJson(path.join(queueDir, file));\n queue.push({ id: file, payload });\n }\n catch (error) {\n console.error(`Error reading queued snapshot ${file}:`, error);\n }\n }\n }\n return queue.sort((a, b) => a.id.localeCompare(b.id));\n }\n async removeFromQueue(id) {\n const queueDir = await this.getQueueDir();\n const filePath = path.join(queueDir, id);\n if (await fs.pathExists(filePath)) {\n await fs.remove(filePath);\n }\n }\n}\n","import { join } from \"node:path\";\nimport fs from \"fs-extra\";\nimport { getVemDir } from \"./fs.js\";\n/**\n * Service for tracking CLI usage metrics and calculating power scores\n */\nexport class UsageMetricsService {\n metricsPath = null;\n baseDir;\n /**\n * Power score weights for various features\n */\n static POWER_SCORES = {\n agent: 30,\n strict_memory: 20,\n task_driven: 20,\n finalize: 15,\n search: 10,\n ask: 10,\n archive: 5,\n };\n static DEFAULT_SYNC_INTERVAL_MS = 5 * 60 * 1000;\n static DEFAULT_SYNC_TIMEOUT_MS = 7000;\n constructor(baseDir) {\n this.baseDir = baseDir;\n if (baseDir) {\n this.metricsPath = join(baseDir, \".usage-metrics.json\");\n }\n }\n async getMetricsPath() {\n if (this.metricsPath) {\n return this.metricsPath;\n }\n const vemDir = await getVemDir();\n this.metricsPath = join(vemDir, \".usage-metrics.json\");\n return this.metricsPath;\n }\n /**\n * Track a command execution\n */\n async trackCommand(command) {\n try {\n const data = await this.loadMetrics();\n // Increment command count\n data.commandCounts[command] = (data.commandCounts[command] || 0) + 1;\n // Update special timestamps\n if (command === \"agent\") {\n data.lastAgentRun = Date.now();\n }\n else if (command === \"push\") {\n data.lastPush = Date.now();\n }\n await this.saveMetrics(data);\n }\n catch (_error) {\n // Silently fail - metrics shouldn't break CLI\n // In production, we might want to log this error\n }\n }\n /**\n * Track a feature flag usage\n */\n async trackFeature(feature) {\n try {\n const data = await this.loadMetrics();\n data.featureFlags[feature] = true;\n await this.saveMetrics(data);\n }\n catch (_error) {\n // Silently fail - metrics shouldn't break CLI\n }\n }\n /**\n * Check if a feature has been used\n */\n async hasUsedFeature(feature) {\n try {\n const data = await this.loadMetrics();\n return (data.commandCounts[feature] > 0 || data.featureFlags[feature] === true);\n }\n catch (_error) {\n // Silently fail - metrics shouldn't break CLI\n return false;\n }\n }\n /**\n * Get usage statistics including power score\n */\n async getStats() {\n try {\n const data = await this.loadMetrics();\n const powerScore = this.calculatePowerScore(data);\n const totalCommands = Object.values(data.commandCounts).reduce((sum, count) => sum + count, 0);\n return {\n commandCounts: data.commandCounts,\n featureFlags: data.featureFlags,\n lastAgentRun: data.lastAgentRun,\n lastPush: data.lastPush,\n powerScore,\n totalCommands,\n };\n }\n catch (_error) {\n // Return empty stats on error\n return {\n commandCounts: {},\n featureFlags: {},\n lastAgentRun: null,\n lastPush: null,\n powerScore: 0,\n totalCommands: 0,\n };\n }\n }\n /**\n * Sync usage metrics to cloud API.\n * This is best-effort and should never throw.\n */\n async syncToCloud(options) {\n try {\n if (!this.isCloudSyncEnabled()) {\n return { synced: false, reason: \"disabled_by_privacy\" };\n }\n if (!options.apiUrl || !options.apiKey) {\n return { synced: false, reason: \"missing_credentials\" };\n }\n const data = await this.loadMetrics();\n const stats = await this.getStats();\n const signature = JSON.stringify({\n commandCounts: data.commandCounts,\n featureFlags: data.featureFlags,\n lastAgentRun: data.lastAgentRun,\n lastPush: data.lastPush,\n });\n const now = Date.now();\n const minIntervalMs = options.minIntervalMs ?? UsageMetricsService.DEFAULT_SYNC_INTERVAL_MS;\n if (!options.force) {\n if (data.lastSyncedAt && now - data.lastSyncedAt < minIntervalMs) {\n return { synced: false, reason: \"throttled\" };\n }\n if (data.lastSyncedSignature === signature) {\n return { synced: false, reason: \"unchanged\" };\n }\n }\n const apiUrl = options.apiUrl.replace(/\\/+$/, \"\");\n const endpoint = `${apiUrl}/api/metrics/usage`;\n const timeoutMs = options.timeoutMs ?? UsageMetricsService.DEFAULT_SYNC_TIMEOUT_MS;\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n const events = options.event && (options.event.command || options.event.featureFlag)\n ? [\n {\n command: options.event.command,\n feature_flag: options.event.featureFlag,\n metadata: options.event.metadata,\n timestamp: options.event.timestamp ?? now,\n },\n ]\n : [];\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${options.apiKey}`,\n \"Content-Type\": \"application/json\",\n ...(options.headers ?? {}),\n },\n body: JSON.stringify({\n project_id: options.projectId,\n events,\n stats: {\n commandCounts: stats.commandCounts,\n featureFlags: stats.featureFlags,\n lastAgentRun: stats.lastAgentRun,\n lastPush: stats.lastPush,\n powerScore: stats.powerScore,\n totalCommands: stats.totalCommands,\n },\n }),\n signal: controller.signal,\n }).finally(() => {\n clearTimeout(timeout);\n });\n if (!response.ok) {\n return {\n synced: false,\n reason: `http_${response.status}`,\n };\n }\n data.lastSyncedAt = now;\n data.lastSyncedSignature = signature;\n await this.saveMetrics(data);\n return { synced: true };\n }\n catch {\n return { synced: false, reason: \"network_error\" };\n }\n }\n /**\n * Calculate power score based on feature usage\n */\n calculatePowerScore(data) {\n let score = 0;\n // Add points for commands\n for (const [command, count] of Object.entries(data.commandCounts)) {\n if (count > 0 && UsageMetricsService.POWER_SCORES[command]) {\n score += UsageMetricsService.POWER_SCORES[command];\n }\n }\n // Add points for features\n for (const [feature, enabled] of Object.entries(data.featureFlags)) {\n if (enabled && UsageMetricsService.POWER_SCORES[feature]) {\n score += UsageMetricsService.POWER_SCORES[feature];\n }\n }\n return score;\n }\n /**\n * Load metrics from disk\n */\n async loadMetrics() {\n try {\n const metricsPath = await this.getMetricsPath();\n if (await fs.pathExists(metricsPath)) {\n const content = await fs.readFile(metricsPath, \"utf-8\");\n return JSON.parse(content);\n }\n }\n catch (_error) {\n // If file doesn't exist or is corrupted, return empty data\n }\n return {\n commandCounts: {},\n featureFlags: {},\n lastAgentRun: null,\n lastPush: null,\n lastSyncedAt: null,\n lastSyncedSignature: null,\n };\n }\n /**\n * Save metrics to disk\n */\n async saveMetrics(data) {\n const metricsPath = await this.getMetricsPath();\n await fs.writeFile(metricsPath, JSON.stringify(data, null, 2), \"utf-8\");\n }\n isCloudSyncEnabled() {\n const disabled = (process.env.VEM_DISABLE_METRICS || \"\").toLowerCase();\n if (disabled === \"1\" || disabled === \"true\" || disabled === \"yes\") {\n return false;\n }\n const privacyMode = (process.env.VEM_PRIVACY_MODE || \"\").toLowerCase();\n if (privacyMode === \"strict\" || privacyMode === \"local-only\") {\n return false;\n }\n return true;\n }\n}\n","import crypto from \"node:crypto\";\nimport dns from \"node:dns\";\n/**\n * Returns true if the given IPv4 or IPv6 address falls within a private,\n * loopback, or link-local range that must be blocked to prevent SSRF.\n */\nfunction isPrivateIp(ip) {\n // IPv6 loopback and ULA (fc00::/7 covers fc00:: – fdff::)\n if (ip.includes(\":\")) {\n const normalized = ip.toLowerCase();\n if (normalized === \"::1\")\n return true;\n if (/^fc[0-9a-f]{2}:/i.test(normalized))\n return true;\n if (/^fd[0-9a-f]{2}:/i.test(normalized))\n return true;\n if (/^fe80:/i.test(normalized))\n return true; // link-local\n return false;\n }\n // IPv4\n const parts = ip.split(\".\").map(Number);\n if (parts.length !== 4 || parts.some((p) => Number.isNaN(p)))\n return false;\n const [a, b, _c] = parts;\n return (a === 127 || // 127.0.0.0/8 loopback\n a === 10 || // 10.0.0.0/8 private\n (a === 172 && b >= 16 && b <= 31) || // 172.16.0.0/12 private\n (a === 192 && b === 168) || // 192.168.0.0/16 private\n (a === 169 && b === 254) || // 169.254.0.0/16 link-local / AWS metadata\n (a === 100 && b >= 64 && b <= 127) || // 100.64.0.0/10 CGNAT / Tailscale\n a === 0 // 0.0.0.0/8\n );\n}\nasync function resolveAndValidateWebhookHostname(hostname) {\n const normalizedHost = hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n // Reject bare hostnames that are obviously local before DNS lookup.\n if (normalizedHost === \"localhost\" || normalizedHost === \"0.0.0.0\") {\n throw new Error(\"Webhook URLs must not target private or loopback addresses\");\n }\n let resolvedAddresses;\n try {\n const result = await Promise.race([\n dns.promises.lookup(normalizedHost, { all: true, verbatim: false }),\n new Promise((_, reject) => setTimeout(() => reject(new Error(\"DNS lookup timed out\")), 3000)),\n ]);\n resolvedAddresses = result;\n }\n catch (err) {\n throw new Error(`Webhook URL DNS lookup failed: ${err.message}`);\n }\n if (!Array.isArray(resolvedAddresses) || resolvedAddresses.length === 0) {\n throw new Error(\"Webhook URL DNS lookup failed: no addresses resolved\");\n }\n const privateAddress = resolvedAddresses.find(({ address }) => isPrivateIp(address));\n if (privateAddress) {\n throw new Error(`Webhook URLs must not target private or loopback addresses (resolved to ${privateAddress.address})`);\n }\n}\n/**\n * Validate a webhook URL for SSRF safety.\n * Rejects non-https schemes and resolves the hostname via DNS to block\n * private/loopback IP addresses even when provided through a DNS alias.\n * Throws with a descriptive message if the URL is blocked.\n */\nexport async function validateWebhookUrl(url) {\n let parsed;\n try {\n parsed = new URL(url);\n }\n catch {\n throw new Error(\"Invalid URL\");\n }\n if (parsed.protocol !== \"https:\") {\n throw new Error(\"Webhook URLs must use https\");\n }\n await resolveAndValidateWebhookHostname(parsed.hostname);\n}\nexport class WebhookService {\n /**\n * Detect if a URL is a Slack webhook\n */\n isSlackUrl(url) {\n return url.includes(\"hooks.slack.com/services/\");\n }\n /**\n * Detect if a URL is a Discord webhook\n */\n isDiscordUrl(url) {\n return (url.includes(\"discord.com/api/webhooks/\") ||\n url.includes(\"discordapp.com/api/webhooks/\"));\n }\n /**\n * Get a friendly title for the event\n */\n getEventTitle(event, data) {\n switch (event) {\n case \"task.created\":\n return `🆕 Task Created: ${data.title || \"Unnamed Task\"}`;\n case \"task.started\":\n return `🚀 Task Started: ${data.title || \"Unnamed Task\"}`;\n case \"task.blocked\":\n return `🛑 Task Blocked: ${data.title || \"Unnamed Task\"}`;\n case \"task.completed\":\n return `✅ Task Completed: ${data.title || \"Unnamed Task\"}`;\n case \"task.deleted\":\n return `🗑️ Task Deleted: ${data.title || \"Unnamed Task\"}`;\n case \"snapshot.pushed\":\n return \"📦 New Memory Snapshot Pushed\";\n case \"snapshot.verified\":\n return \"🛡️ Memory Snapshot Verified\";\n case \"snapshot.failed\":\n return \"❌ Memory Snapshot Verification Failed\";\n case \"decision.added\":\n return \"🧠 New Architectural Decision Recorded\";\n case \"changelog.updated\":\n return \"📝 Project Changelog Updated\";\n case \"drift.detected\":\n return \"⚠️ Truth Drift Detected\";\n case \"project.linked\":\n return \"🔗 Project Linked to Repository\";\n default:\n return `VEM Event: ${event}`;\n }\n }\n /**\n * Get theme color for the event\n */\n getEventColor(event) {\n switch (event) {\n case \"task.created\":\n case \"task.started\":\n case \"project.linked\":\n return 0x3b82f6; // Blue\n case \"task.completed\":\n case \"snapshot.verified\":\n return 0x10b981; // Emerald\n case \"task.blocked\":\n case \"drift.detected\":\n return 0xf59e0b; // Amber\n case \"snapshot.failed\":\n case \"task.deleted\":\n return 0xef4444; // Red\n case \"snapshot.pushed\":\n case \"decision.added\":\n case \"changelog.updated\":\n return 0x8b5cf6; // Purple\n default:\n return 0x6b7280; // Gray\n }\n }\n /**\n * Format payload for Slack Block Kit\n */\n formatSlackPayload(payload) {\n const title = this.getEventTitle(payload.event, payload.data);\n const fields = [\n {\n type: \"mrkdwn\",\n text: `*Organization:*\\n${payload.org_id}`,\n },\n ];\n if (payload.project_name) {\n fields.push({\n type: \"mrkdwn\",\n text: `*Project:*\\n${payload.project_name}`,\n });\n }\n // Add event-specific data\n if (payload.event.startsWith(\"task.\")) {\n if (payload.data.task_id) {\n fields.push({\n type: \"mrkdwn\",\n text: `*Task ID:*\\n${payload.data.task_id}`,\n });\n }\n if (payload.data.status) {\n fields.push({\n type: \"mrkdwn\",\n text: `*Status:*\\n${payload.data.status}`,\n });\n }\n }\n const blocks = [\n {\n type: \"header\",\n text: {\n type: \"plain_text\",\n text: title,\n emoji: true,\n },\n },\n {\n type: \"section\",\n fields,\n },\n ];\n // Add link button if available\n if (payload.data.url) {\n blocks.push({\n type: \"actions\",\n elements: [\n {\n type: \"button\",\n text: {\n type: \"plain_text\",\n text: \"View in VEM\",\n emoji: true,\n },\n url: payload.data.url,\n style: payload.event === \"snapshot.failed\" ? \"danger\" : \"primary\",\n },\n ],\n });\n }\n blocks.push({\n type: \"context\",\n elements: [\n {\n type: \"mrkdwn\",\n text: `VEM Webhook • ${new Date(payload.timestamp).toLocaleString()}`,\n },\n ],\n });\n return { blocks };\n }\n /**\n * Format payload for Discord Embeds\n */\n formatDiscordPayload(payload) {\n const title = this.getEventTitle(payload.event, payload.data);\n const color = this.getEventColor(payload.event);\n const fields = [];\n if (payload.project_name) {\n fields.push({\n name: \"Project\",\n value: payload.project_name,\n inline: true,\n });\n }\n // Add event-specific fields\n if (payload.event.startsWith(\"task.\")) {\n if (payload.data.task_id) {\n fields.push({\n name: \"Task ID\",\n value: String(payload.data.task_id),\n inline: true,\n });\n }\n if (payload.data.status) {\n fields.push({\n name: \"Status\",\n value: String(payload.data.status),\n inline: true,\n });\n }\n }\n if (payload.event === \"snapshot.pushed\" ||\n payload.event === \"snapshot.verified\") {\n if (payload.data.git_hash) {\n fields.push({\n name: \"Git Hash\",\n value: `\\`${String(payload.data.git_hash).slice(0, 7)}\\``,\n inline: true,\n });\n }\n }\n return {\n embeds: [\n {\n title,\n url: payload.data.url || undefined,\n color,\n fields,\n footer: {\n text: \"VEM Webhook Notification\",\n },\n timestamp: payload.timestamp,\n },\n ],\n };\n }\n /**\n * Generate HMAC SHA-256 signature for webhook payload\n */\n generateSignature(payload, secret) {\n const body = JSON.stringify(payload);\n const signature = crypto\n .createHmac(\"sha256\", secret)\n .update(body)\n .digest(\"hex\");\n return `sha256=${signature}`;\n }\n /**\n * Deliver a single webhook\n */\n async deliverWebhook(webhook, payload, _attempt = 1) {\n try {\n // Re-validate URL + DNS on every delivery attempt to mitigate rebinding.\n await validateWebhookUrl(webhook.url);\n }\n catch (urlErr) {\n return {\n webhook_id: webhook.id,\n success: false,\n error_message: urlErr.message,\n };\n }\n try {\n const isSlack = this.isSlackUrl(webhook.url);\n const isDiscord = this.isDiscordUrl(webhook.url);\n // Transform payload for Slack/Discord\n let body = payload;\n if (isSlack) {\n body = this.formatSlackPayload(payload);\n }\n else if (isDiscord) {\n body = this.formatDiscordPayload(payload);\n }\n const signature = this.generateSignature(payload, webhook.secret);\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout\n const response = await fetch(webhook.url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Webhook-Signature\": signature,\n \"X-Webhook-Event\": payload.event,\n \"X-Webhook-Delivery\": crypto.randomUUID(),\n \"User-Agent\": \"VEM-Webhooks/1.0\",\n },\n body: JSON.stringify(body),\n signal: controller.signal,\n // Avoid following redirects to an unvalidated destination.\n redirect: \"manual\",\n });\n clearTimeout(timeoutId);\n return {\n webhook_id: webhook.id,\n success: response.ok,\n status_code: response.status,\n error_message: response.ok\n ? undefined\n : `HTTP ${response.status}: ${response.statusText}`,\n };\n }\n catch (error) {\n const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n return {\n webhook_id: webhook.id,\n success: false,\n error_message: errorMessage,\n };\n }\n }\n /**\n * Find and trigger all webhooks subscribed to an event\n * @param findWebhooks - Database query function to find matching webhooks\n * @param recordDelivery - Database insert function to record delivery\n * @param eventType - The event type\n * @param orgId - Organization ID\n * @param projectId - Project ID (null for org-level events)\n * @param data - Event-specific data\n */\n async triggerWebhooks(findWebhooks, recordDelivery, eventType, orgId, projectId, data, projectName) {\n // Find all enabled webhooks subscribed to this event\n const webhooks = await findWebhooks({\n orgId,\n projectId,\n eventType,\n });\n if (webhooks.length === 0) {\n return;\n }\n // Build webhook payload\n const payload = {\n event: eventType,\n timestamp: new Date().toISOString(),\n org_id: orgId,\n project_id: projectId,\n project_name: projectName,\n data,\n };\n // Deliver to all webhooks (don't await - fire and forget for now)\n const deliveryPromises = webhooks.map(async (webhook) => {\n const result = await this.deliverWebhook(webhook, payload, 1);\n // Record delivery in database\n await recordDelivery({\n webhookId: webhook.id,\n eventType,\n payload,\n statusCode: result.status_code,\n success: result.success,\n attempt: 1,\n errorMessage: result.error_message,\n });\n });\n // Don't block on deliveries - they happen in background\n Promise.all(deliveryPromises).catch((err) => {\n console.error(\"[webhook] Unhandled error in webhook delivery batch:\", err);\n });\n }\n}\n"],"mappings":";;;;;;AACA,SAAS,YAAAA,iBAAgB;AACzB,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,SAAS,UAAU,UAAU,iBAAiB;AACvD,SAAS,QAAAC,OAAM,gBAAgB;AAC/B,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC;AAAA,EACC;AAAA,EACA;AAAA,OACM;;;ACVP,OAAOC,WAAU;;;ACAjB,SAAS,SAAS;AACX,IAAM,2BAA2B,EAAE,MAAM;AAAA,EAC5C,EAAE,OAAO;AAAA,EACT,EAAE,OAAO;AAAA,IACL,IAAI,EAAE,OAAO;AAAA,IACb,OAAO,EAAE,OAAO,EAAE,SAAS;AAAA,IAC3B,SAAS,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,CAAC;AACL,CAAC;AACM,IAAM,0BAA0B,EAAE,OAAO;AAAA,EAC5C,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,EACzC,qBAAqB,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS;AAAA,EAC/C,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS;AAAA,EACtC,iBAAiB,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS;AAAA,EAC3C,iBAAiB,EAAE,OAAO,EAAE,OAAO,GAAG,E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B,IAAI;AAAA,QACJ;AAAA,QACA,YAAY,MAAM,aAAY,oBAAI,KAAK,GAAE,YAAY;AAAA,QACrD;AAAA,MACD,CAAC;AAAA,IACF;AAEA,UAAM,YAAY,WAAWA,SAAQ,EAAE,UAAU,iBAAiB,CAAC;AAEnE,WAAO;AAAA,MACN,SAAS;AAAA,QACR;AAAA,UACC,MAAM;AAAA,UACN,MAAM,2BAA2B,SAAS,YAAYA,OAAM;AAAA,EAAM,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC;AAAA,QACjG;AAAA,MACD;AAAA,IACD;AAAA,EACD;AAEA,QAAM,IAAI,MAAM,mBAAmB,IAAI,EAAE;AAC1C,CAAC;AAED,IAAM,YAAY,IAAI,qBAAqB;AAK3C,IAAM,kBAAkB,QAAQ,KAAK,QAAQ,WAAW;AACxD,IAAI,oBAAoB,MAAM,QAAQ,KAAK,kBAAkB,CAAC,GAAG;AAChE,QAAM,UAAU,QAAQ,KAAK,kBAAkB,CAAC;AAChD,QAAM,cAAc,UAAU,OAAO;AACtC;AAEA,MAAM,OAAO,QAAQ,SAAS;","names":["execSync","createHash","join","path","fs","relative","path","fs","path","fs","path","fs","path","fs","path","fs","normalizeEvidence","summarizeTaskContext","taskService","path","fs","path","fs","path","fs","path","fs","path","fs","z","z","createHash","createHash","path","fs","path","path","fs","fs","fs","crypto","execSync","createHash","join","path","data","taskId"]}
|