#!/bin/bash # Sandbox script for testing Plannotator OpenCode plugin locally # # Usage: # ./sandbox-opencode.sh [--workflow MODE] [--planning-agents AGENTS] [--disable-sharing] [--keep] [--no-git] # # Options: # --workflow MODE Plugin workflow to test: manual | plan-agent | all-agents # Default: plan-agent # --planning-agents Comma-separated planning agent names for plan-agent mode # Default: plan # --disable-sharing Create opencode.json with "share": "disabled" to test # the sharing disable feature without env var pollution # --keep Don't clean up sandbox on exit (for debugging) # --no-git Don't initialize git repo (tests non-git fallback) # # What it does: # 1. Clears OpenCode-related caches # 2. Builds the plugin (ensures latest code) # 3. Creates a temp directory with git repo # 4. Creates sample files with uncommitted changes (for /plannotator-review) # 5. Creates two minimal folders for reproducing folder-annotation draft collisions # 6. Writes workflow-specific OpenCode config # 7. Sets up the local plugin # 8. Launches OpenCode in the sandbox # # To test: # - Plan mode behavior varies by --workflow # - Code review: Run /plannotator-review to review the sample changes set -e SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)" PLUGIN_DIR="$PROJECT_ROOT/apps/opencode-plugin" CLEAR_CACHE_SCRIPT="$PROJECT_ROOT/scripts/clear-opencode-cache.sh" PLUGIN_LOADER_RELATIVE_PATH="./.opencode/plannotator.ts" # Parse CLI flags WORKFLOW="plan-agent" PLANNING_AGENTS="plan" DISABLE_SHARING=false KEEP_SANDBOX=false NO_GIT=false while [ $# -gt 0 ]; do case "$1" in --workflow) if [ -z "${2:-}" ]; then echo "--workflow requires an argument" >&2 exit 1 fi WORKFLOW="$2" shift 2 ;; --planning-agents) if [ -z "${2:-}" ]; then echo "--planning-agents requires an argument" >&2 exit 1 fi PLANNING_AGENTS="$2" shift 2 ;; --disable-sharing) DISABLE_SHARING=true shift ;; --keep) KEEP_SANDBOX=true shift ;; --no-git) NO_GIT=true shift ;; *) echo "Unknown option: $1" >&2 exit 1 ;; esac done case "$WORKFLOW" in manual|plan-agent|all-agents) ;; *) echo "Invalid --workflow value: $WORKFLOW" >&2 echo "Expected one of: manual, plan-agent, all-agents" >&2 exit 1 ;; esac planning_agents_json() { local raw="$1" local IFS=',' local parts=() local item for item in $raw; do item="${item#"${item%%[![:space:]]*}"}" item="${item%"${item##*[![:space:]]}"}" if [ -n "$item" ]; then parts+=("\"$item\"") fi done if [ ${#parts[@]} -eq 0 ]; then parts+=("\"plan\"") fi local IFS=', ' printf '[%s]' "${parts[*]}" } echo "=== Plannotator OpenCode Sandbox ===" echo "" # Clear OpenCode caches so the sandbox always starts from a fresh plugin state echo "Clearing OpenCode caches..." bash "$CLEAR_CACHE_SCRIPT" echo "" # Build the plugin (includes building dependencies) echo "Building plugin..." cd "$PROJECT_ROOT" bun run build:hook > /dev/null 2>&1 # Required: opencode copies HTML from hook dist bun run build:review > /dev/null 2>&1 # Required: opencode copies HTML from review dist bun run build:opencode echo "" # Create temp directory SANDBOX_DIR=$(mktemp -d) echo "Created sandbox: $SANDBOX_DIR" # Cleanup on exit (unless --keep) cleanup() { echo "" if [ "$KEEP_SANDBOX" = true ]; then echo "Keeping sandbox at: $SANDBOX_DIR" echo "To clean up manually: rm -rf $SANDBOX_DIR" else echo "Cleaning up sandbox..." rm -rf "$SANDBOX_DIR" echo "Done." fi } trap cleanup EXIT # Initialize git repo (unless --no-git) cd "$SANDBOX_DIR" if [ "$NO_GIT" = false ]; then git init -q git config user.email "test@example.com" git config user.name "Test User" fi # Create initial project structure mkdir -p src/{api,components,hooks,utils,types} mkdir -p docs/folder-draft-a docs/folder-draft-b mkdir -p tests cat > package.json << 'EOF' { "name": "task-manager-app", "version": "1.0.0", "type": "module", "scripts": { "dev": "vite", "build": "tsc && vite build", "test": "vitest" }, "dependencies": { "react": "^18.2.0", "react-dom": "^18.2.0" }, "devDependencies": { "typescript": "^5.0.0", "vite": "^5.0.0", "vitest": "^1.0.0" } } EOF cat > tsconfig.json << 'EOF' { "compilerOptions": { "target": "ES2020", "module": "ESNext", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "outDir": "./dist" }, "include": ["src/**/*"], "exclude": ["node_modules"] } EOF # Types cat > src/types/index.ts << 'EOF' export interface User { id: string; name: string; email: string; createdAt: Date; } export interface Task { id: string; title: string; description: string; status: 'pending' | 'in_progress' | 'completed'; assigneeId: string; dueDate: Date; createdAt: Date; updatedAt: Date; } export interface ApiResponse { data: T; error?: string; status: number; } EOF # API client cat > src/api/client.ts << 'EOF' const API_BASE = 'https://api.example.com'; export async function fetchApi( endpoint: string, options: RequestInit = {} ): Promise { const response = await fetch(`${API_BASE}${endpoint}`, { ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); if (!response.ok) { throw new Error(`API error: ${response.status}`); } return response.json(); } EOF # Minimal folder-annotation repro fixture cat > docs/folder-draft-a/spec.md << 'EOF' # Folder Draft A - This folder exists only to reproduce draft collisions. - Leave a draft here, then open folder B. EOF cat > docs/folder-draft-b/spec.md << 'EOF' # Folder Draft B - This folder exists only to reproduce draft collisions. - If the bug is present, it will show folder A's draft. EOF # Task API cat > src/api/tasks.ts << 'EOF' import { fetchApi } from './client'; import type { Task, ApiResponse } from '../types'; export async function getTasks(): Promise { const response = await fetchApi>('/tasks'); return response.data; } export async function getTask(id: string): Promise { const response = await fetchApi>(`/tasks/${id}`); return response.data; } export async function createTask(task: Omit): Promise { const response = await fetchApi>('/tasks', { method: 'POST', body: JSON.stringify(task), }); return response.data; } export async function updateTask(id: string, updates: Partial): Promise { const response = await fetchApi>(`/tasks/${id}`, { method: 'PATCH', body: JSON.stringify(updates), }); return response.data; } export async function deleteTask(id: string): Promise { await fetchApi(`/tasks/${id}`, { method: 'DELETE' }); } EOF # User API cat > src/api/users.ts << 'EOF' import { fetchApi } from './client'; import type { User, ApiResponse } from '../types'; export async function getUsers(): Promise { const response = await fetchApi>('/users'); return response.data; } export async function getUser(id: string): Promise { const response = await fetchApi>(`/users/${id}`); return response.data; } export async function getCurrentUser(): Promise { const response = await fetchApi>('/users/me'); return response.data; } EOF # Utils cat > src/utils/formatters.ts << 'EOF' export function formatDate(date: Date): string { return date.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric', }); } export function formatDateTime(date: Date): string { return date.toLocaleString('en-US', { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', }); } export function formatRelativeTime(date: Date): string { const now = new Date(); const diff = now.getTime() - date.getTime(); const seconds = Math.floor(diff / 1000); const minutes = Math.floor(seconds / 60); const hours = Math.floor(minutes / 60); const days = Math.floor(hours / 24); if (days > 0) return `${days} day${days > 1 ? 's' : ''} ago`; if (hours > 0) return `${hours} hour${hours > 1 ? 's' : ''} ago`; if (minutes > 0) return `${minutes} minute${minutes > 1 ? 's' : ''} ago`; return 'just now'; } export function truncateText(text: string, maxLength: number): string { if (text.length <= maxLength) return text; return text.slice(0, maxLength - 3) + '...'; } EOF cat > src/utils/validators.ts << 'EOF' export function isValidEmail(email: string): boolean { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegex.test(email); } export function isValidTaskTitle(title: string): boolean { return title.length >= 3 && title.length <= 100; } export function isValidTaskDescription(description: string): boolean { return description.length <= 500; } EOF # Hooks cat > src/hooks/useTasks.ts << 'EOF' import { useState, useEffect, useCallback } from 'react'; import { getTasks, createTask, updateTask, deleteTask } from '../api/tasks'; import type { Task } from '../types'; export function useTasks() { const [tasks, setTasks] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const fetchTasks = useCallback(async () => { try { setLoading(true); const data = await getTasks(); setTasks(data); setError(null); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to fetch tasks'); } finally { setLoading(false); } }, []); useEffect(() => { fetchTasks(); }, [fetchTasks]); const addTask = useCallback(async (task: Omit) => { const newTask = await createTask(task); setTasks(prev => [...prev, newTask]); return newTask; }, []); const editTask = useCallback(async (id: string, updates: Partial) => { const updated = await updateTask(id, updates); setTasks(prev => prev.map(t => t.id === id ? updated : t)); return updated; }, []); const removeTask = useCallback(async (id: string) => { await deleteTask(id); setTasks(prev => prev.filter(t => t.id !== id)); }, []); return { tasks, loading, error, fetchTasks, addTask, editTask, removeTask }; } EOF cat > src/hooks/useAuth.ts << 'EOF' import { useState, useEffect, useCallback } from 'react'; import { getCurrentUser } from '../api/users'; import type { User } from '../types'; export function useAuth() { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { getCurrentUser() .then(setUser) .catch(() => setUser(null)) .finally(() => setLoading(false)); }, []); const logout = useCallback(() => { setUser(null); localStorage.removeItem('auth_token'); }, []); return { user, loading, logout, isAuthenticated: !!user }; } EOF # Components cat > src/components/TaskCard.tsx << 'EOF' import React from 'react'; import type { Task } from '../types'; import { formatRelativeTime } from '../utils/formatters'; interface TaskCardProps { task: Task; onEdit: (task: Task) => void; onDelete: (id: string) => void; } export function TaskCard({ task, onEdit, onDelete }: TaskCardProps) { const statusColors = { pending: 'bg-yellow-100 text-yellow-800', in_progress: 'bg-blue-100 text-blue-800', completed: 'bg-green-100 text-green-800', }; return (

{task.title}

{task.status.replace('_', ' ')}

{task.description}

Updated {formatRelativeTime(task.updatedAt)}
); } EOF cat > src/components/TaskList.tsx << 'EOF' import React from 'react'; import { TaskCard } from './TaskCard'; import type { Task } from '../types'; interface TaskListProps { tasks: Task[]; onEdit: (task: Task) => void; onDelete: (id: string) => void; loading?: boolean; } export function TaskList({ tasks, onEdit, onDelete, loading }: TaskListProps) { if (loading) { return
Loading tasks...
; } if (tasks.length === 0) { return (
No tasks yet. Create one to get started!
); } return (
{tasks.map(task => ( ))}
); } EOF cat > src/components/TaskForm.tsx << 'EOF' import React, { useState } from 'react'; import type { Task } from '../types'; import { isValidTaskTitle, isValidTaskDescription } from '../utils/validators'; interface TaskFormProps { initialData?: Partial; onSubmit: (data: Omit) => void; onCancel: () => void; } export function TaskForm({ initialData, onSubmit, onCancel }: TaskFormProps) { const [title, setTitle] = useState(initialData?.title || ''); const [description, setDescription] = useState(initialData?.description || ''); const [status, setStatus] = useState(initialData?.status || 'pending'); const [errors, setErrors] = useState<{ title?: string; description?: string }>({}); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); const newErrors: { title?: string; description?: string } = {}; if (!isValidTaskTitle(title)) { newErrors.title = 'Title must be between 3 and 100 characters'; } if (!isValidTaskDescription(description)) { newErrors.description = 'Description must be less than 500 characters'; } if (Object.keys(newErrors).length > 0) { setErrors(newErrors); return; } onSubmit({ title, description, status, assigneeId: initialData?.assigneeId || '', dueDate: initialData?.dueDate || new Date(), }); }; return (
setTitle(e.target.value)} className="w-full border rounded px-3 py-2" /> {errors.title &&

{errors.title}

}