Update tuning scripts and add task creation to sync_vikunja.js

This commit is contained in:
Variet-Worker
2026-04-06 21:49:56 +09:00
parent 626a089b6b
commit 7c7a899fd5
61 changed files with 8705 additions and 1566 deletions

View File

@@ -1,86 +0,0 @@
import os
import glob
import re
skill_dir = r"C:\Users\Certes\.gemini\antigravity\skills"
translations = {
"Manage parallel workstreams — list, create, switch, status, progress, complete, and resume": "병렬 작업 스트림 관리 — 목록, 생성, 전환, 상태, 진행률, 완료 및 재개",
"Validate built features through conversational UAT": "대화형 UAT를 통해 구현된 기능 검증",
"Retroactively audit and fill Nyquist validation gaps for a completed phase": "완료된 단계에 대한 검증 누락 사후 감사 및 보완",
"Update GSD to latest version with changelog display": "GSD를 최신 버전으로 업데이트하고 변경 사항 표시",
"Retroactive 6-pillar visual audit of implemented frontend code": "구현된 프론트엔드 코드에 대한 6개 요소 시각적 사후 감사",
"Generate UI design contract (UI-SPEC.md) for frontend phases": "프론트엔드 단계를 위한 UI 디자인 명세서(UI-SPEC.md) 생성",
"Manage persistent context threads for cross-session work": "교차 세션 작업을 위한 영구 컨텍스트 스레드 관리",
"Display project statistics — phases, plans, requirements, git metrics, and timeline": "프로젝트 통계 표시 — 단계, 계획, 요구사항, Git 지표 및 타임라인",
"Create PR, run review, and prepare for merge after verification passes": "검증 통과 후 PR 생성, 리뷰 실행 및 병합 준비",
"Configure GSD workflow toggles and model profile": "GSD 워크플로우 옵션 및 모델 프로필 구성",
"Switch model profile for GSD agents (quality/balanced/budget/inherit)": "GSD 요원의 모델 프로필 전환 (고품질/균형/예산/상속)",
"Generate a session report with token usage estimates, work summary, and outcomes": "토큰 사용량, 작업 요약 및 결과를 포함한 세션 보고서 생성",
"Review and promote backlog items to active milestone": "백로그 항목을 검토하고 활성 마일스톤으로 승격",
"Request cross-AI peer review of phase plans from external AI CLIs": "외부 AI CLI에 단계 계획에 대한 교차 AI 동료 리뷰 요청",
"Resume work from previous session with full context restoration": "전체 컨텍스트 복원과 함께 이전 세션에서 작업 재개",
"Research how to implement a phase (standalone - usually use /gsd-plan-phase instead)": "단계를 구현하는 방법 리서치 (단독 실행 - 보통 /gsd-plan-phase 사용)",
"Remove a GSD workspace and clean up worktrees": "GSD 워크스페이스 제거 및 워크트리 정리",
"Remove a future phase from roadmap and renumber subsequent phases": "로드맵에서 향후 단계를 제거하고 이후 단계 번호 재지정",
"Reapply local modifications after a GSD update": "GSD 업데이트 후 로컬 수정 사항 재적용",
"Execute a quick task with GSD guarantees (atomic commits, state tracking) but skip optional agents": "GSD 보장(원자적 커밋, 상태 추적)을 사용하여 빠른 작업을 실행하되 선택적 요원 생략",
"Check project progress, show context, and route to next action (execute or plan)": "프로젝트 진행 상황 확인, 컨텍스트 표시 및 다음 작업(실행 또는 계획)으로 라우팅",
"Generate developer behavioral profile and create Claude-discoverable artifacts": "개발자 행동 프로필을 생성하고 AI가 인지할 수 있는 문서 작성",
"Create a clean PR branch by filtering out .planning/ commits — ready for code review": ".planning/ 커밋을 필터링하여 깔끔한 PR 브랜치 생성 — 코드 리뷰 준비",
"Capture a forward-looking idea with trigger conditions — surfaces automatically at the right milestone": "향후 아이디어를 트리거 조건과 함께 캡처 — 적절한 마일스톤에서 자동 표시",
"Create detailed phase plan (PLAN.md) with verification loop": "검증 루프를 포함한 상세 단계 계획(PLAN.md) 생성",
"Create phases to close all gaps identified by milestone audit": "마일스톤 감사에서 식별된 모든 격차를 해소하기 위한 단계 생성",
"Create context handoff when pausing work mid-phase": "작업 중단 시 컨텍스트 인수인계 파일 생성",
"Zero-friction idea capture. Append, list, or promote notes to todos.": "방해 없는 아이디어 캡처. 메모 추가, 나열 또는 할 일로 승격.",
"Automatically advance to the next logical step in the GSD workflow": "GSD 워크플로우의 다음 논리적 단계로 자동 진행",
"Create an isolated workspace with repo copies and independent .planning/": "외부 레포 사본 및 독립적인 .planning/을 갖춘 격리된 워크스페이스 생성",
"Initialize a new project with deep context gathering and PROJECT.md": "심층 컨텍스트 수집 및 PROJECT.md와 함께 새 프로젝트 초기화",
"Start a new milestone cycle — update PROJECT.md and route to requirements": "새로운 마일스톤 주기 시작 — PROJECT.md 업데이트 및 요구사항 재정의",
"Generate a comprehensive project summary from milestone artifacts for team onboarding and review": "팀 온보딩 및 리뷰를 위해 마일스톤 산출물에서 종합적인 프로젝트 요약 생성",
"Analyze codebase with parallel mapper agents to produce .planning/codebase/ documents": "병렬 매퍼 요원으로 코드베이스를 분석하여 .planning/codebase/ 문서 생성",
"Interactive command center for managing multiple phases from one terminal": "하나의 터미널에서 여러 단계를 관리하는 대화형 명령 센터",
"List active GSD workspaces and their status": "활성 GSD 워크스페이스 및 상태 나열",
"Surface the agent's assumptions about a phase approach before planning": "계획 전 단계적 접근 방식에 대한 요원의 가정을 미리 표시",
"Join the GSD Discord community": "GSD 디스코드 커뮤니티 참가",
"Insert urgent work as decimal phase (e.g., 72.1) between existing phases": "기존 단계 사이에 소수점 단계(예: 72.1)로 긴급 작업 삽입",
"Show available GSD commands and usage guide": "사용 가능한 GSD 명령어 및 사용 가이드 표시",
"Diagnose planning directory health and optionally repair issues": "계획 디렉토리 상태 진단 및 선택적으로 문제 복구",
"Post-mortem investigation for failed GSD workflows — analyzes git history, artifacts, and state to diagnose what went wrong": "실패한 GSD 워크플로우에 대한 사후 조사 — git 기록, 문서 및 상태 분석",
"Execute a trivial task inline — no subagents, no planning overhead": "인라인으로 사소한 작업 실행 — 서브 에이전트 및 계획 오버헤드 없음",
"Execute all plans in a phase with wave-based parallelization": "웨이브(Wave) 기반 병렬 처리를 사용하여 단계의 모든 계획 실행",
"Route freeform text to the right GSD command automatically": "자유 형식 텍스트를 적절한 GSD 명령으로 자동 라우팅",
"Systematic debugging with persistent state across context resets": "컨텍스트가 리셋되어도 상태를 유지하는 체계적인 디버깅",
"Gather phase context through adaptive questioning before planning. Use --auto to skip interactive questions (the agent picks recommended defaults).": "계획 전 심층 질문을 통해 단계 컨텍스트 수집. 대화형 건너뛰기(--auto) 가능.",
"Archive completed milestone and prepare for next version": "완료된 마일스톤 보관 및 다음 버전 준비",
"List pending todos and select one to work on": "보류 중인 할 일 목록 표시 및 작업할 항목 선택",
"Cross-phase audit of all outstanding UAT and verification items": "모든 미결 UAT 및 검증 항목에 대한 전체 단계 교차 감사",
"Audit milestone completion against original intent before archiving": "보관 전 원래 의도와 비교하여 마일스톤 달성 여부 감사",
"Capture idea or task as todo from current conversation context": "현재 대화 컨텍스트에서 아이디어 또는 작업을 할 일로 캡처",
"Generate tests for a completed phase based on UAT criteria and implementation": "UAT 기준 및 구현을 기반으로 완료된 단계에 대한 테스트 생성",
"Add phase to end of current milestone in roadmap": "로드맵의 현재 마일스톤 끝에 새 단계 추가",
"Add an idea to the backlog parking lot (999.x numbering)": "백로그 주차장(999.x 넘버링)에 아이디어 추가",
"Run all remaining phases autonomously — discuss→plan→execute per phase": "모든 남은 단계를 완전히 자율적으로 실행 (논의→계획→실행 루프)",
"Archive accumulated phase directories from completed milestones": "완료된 마일스톤에서 쌓인 단계 디렉토리 보관 및 정리"
}
modified_count = 0
for filepath in glob.glob(os.path.join(skill_dir, "gsd-*", "SKILL.md")):
try:
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
new_content = content
for eng, kor in translations.items():
pattern = re.compile(r"^description:\s*" + re.escape(eng) + r"\s*$", re.MULTILINE)
new_content = pattern.sub(f"description: {kor}", new_content)
if new_content != content:
with open(filepath, 'w', encoding='utf-8') as f:
f.write(new_content)
modified_count += 1
except Exception as e:
print(f"Error processing {filepath}: {e}")
print(f"Successfully translated {modified_count} SKILL.md files.")

View File

@@ -1,253 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
UI/UX Pro Max Core - BM25 search engine for UI/UX style guides
"""
import csv
import re
from pathlib import Path
from math import log
from collections import defaultdict
# ============ CONFIGURATION ============
DATA_DIR = Path(__file__).parent.parent / "data"
MAX_RESULTS = 3
CSV_CONFIG = {
"style": {
"file": "styles.csv",
"search_cols": ["Style Category", "Keywords", "Best For", "Type", "AI Prompt Keywords"],
"output_cols": ["Style Category", "Type", "Keywords", "Primary Colors", "Effects & Animation", "Best For", "Performance", "Accessibility", "Framework Compatibility", "Complexity", "AI Prompt Keywords", "CSS/Technical Keywords", "Implementation Checklist", "Design System Variables"]
},
"color": {
"file": "colors.csv",
"search_cols": ["Product Type", "Notes"],
"output_cols": ["Product Type", "Primary (Hex)", "Secondary (Hex)", "CTA (Hex)", "Background (Hex)", "Text (Hex)", "Notes"]
},
"chart": {
"file": "charts.csv",
"search_cols": ["Data Type", "Keywords", "Best Chart Type", "Accessibility Notes"],
"output_cols": ["Data Type", "Keywords", "Best Chart Type", "Secondary Options", "Color Guidance", "Accessibility Notes", "Library Recommendation", "Interactive Level"]
},
"landing": {
"file": "landing.csv",
"search_cols": ["Pattern Name", "Keywords", "Conversion Optimization", "Section Order"],
"output_cols": ["Pattern Name", "Keywords", "Section Order", "Primary CTA Placement", "Color Strategy", "Conversion Optimization"]
},
"product": {
"file": "products.csv",
"search_cols": ["Product Type", "Keywords", "Primary Style Recommendation", "Key Considerations"],
"output_cols": ["Product Type", "Keywords", "Primary Style Recommendation", "Secondary Styles", "Landing Page Pattern", "Dashboard Style (if applicable)", "Color Palette Focus"]
},
"ux": {
"file": "ux-guidelines.csv",
"search_cols": ["Category", "Issue", "Description", "Platform"],
"output_cols": ["Category", "Issue", "Platform", "Description", "Do", "Don't", "Code Example Good", "Code Example Bad", "Severity"]
},
"typography": {
"file": "typography.csv",
"search_cols": ["Font Pairing Name", "Category", "Mood/Style Keywords", "Best For", "Heading Font", "Body Font"],
"output_cols": ["Font Pairing Name", "Category", "Heading Font", "Body Font", "Mood/Style Keywords", "Best For", "Google Fonts URL", "CSS Import", "Tailwind Config", "Notes"]
},
"icons": {
"file": "icons.csv",
"search_cols": ["Category", "Icon Name", "Keywords", "Best For"],
"output_cols": ["Category", "Icon Name", "Keywords", "Library", "Import Code", "Usage", "Best For", "Style"]
},
"react": {
"file": "react-performance.csv",
"search_cols": ["Category", "Issue", "Keywords", "Description"],
"output_cols": ["Category", "Issue", "Platform", "Description", "Do", "Don't", "Code Example Good", "Code Example Bad", "Severity"]
},
"web": {
"file": "web-interface.csv",
"search_cols": ["Category", "Issue", "Keywords", "Description"],
"output_cols": ["Category", "Issue", "Platform", "Description", "Do", "Don't", "Code Example Good", "Code Example Bad", "Severity"]
}
}
STACK_CONFIG = {
"html-tailwind": {"file": "stacks/html-tailwind.csv"},
"react": {"file": "stacks/react.csv"},
"nextjs": {"file": "stacks/nextjs.csv"},
"astro": {"file": "stacks/astro.csv"},
"vue": {"file": "stacks/vue.csv"},
"nuxtjs": {"file": "stacks/nuxtjs.csv"},
"nuxt-ui": {"file": "stacks/nuxt-ui.csv"},
"svelte": {"file": "stacks/svelte.csv"},
"swiftui": {"file": "stacks/swiftui.csv"},
"react-native": {"file": "stacks/react-native.csv"},
"flutter": {"file": "stacks/flutter.csv"},
"shadcn": {"file": "stacks/shadcn.csv"},
"jetpack-compose": {"file": "stacks/jetpack-compose.csv"}
}
# Common columns for all stacks
_STACK_COLS = {
"search_cols": ["Category", "Guideline", "Description", "Do", "Don't"],
"output_cols": ["Category", "Guideline", "Description", "Do", "Don't", "Code Good", "Code Bad", "Severity", "Docs URL"]
}
AVAILABLE_STACKS = list(STACK_CONFIG.keys())
# ============ BM25 IMPLEMENTATION ============
class BM25:
"""BM25 ranking algorithm for text search"""
def __init__(self, k1=1.5, b=0.75):
self.k1 = k1
self.b = b
self.corpus = []
self.doc_lengths = []
self.avgdl = 0
self.idf = {}
self.doc_freqs = defaultdict(int)
self.N = 0
def tokenize(self, text):
"""Lowercase, split, remove punctuation, filter short words"""
text = re.sub(r'[^\w\s]', ' ', str(text).lower())
return [w for w in text.split() if len(w) > 2]
def fit(self, documents):
"""Build BM25 index from documents"""
self.corpus = [self.tokenize(doc) for doc in documents]
self.N = len(self.corpus)
if self.N == 0:
return
self.doc_lengths = [len(doc) for doc in self.corpus]
self.avgdl = sum(self.doc_lengths) / self.N
for doc in self.corpus:
seen = set()
for word in doc:
if word not in seen:
self.doc_freqs[word] += 1
seen.add(word)
for word, freq in self.doc_freqs.items():
self.idf[word] = log((self.N - freq + 0.5) / (freq + 0.5) + 1)
def score(self, query):
"""Score all documents against query"""
query_tokens = self.tokenize(query)
scores = []
for idx, doc in enumerate(self.corpus):
score = 0
doc_len = self.doc_lengths[idx]
term_freqs = defaultdict(int)
for word in doc:
term_freqs[word] += 1
for token in query_tokens:
if token in self.idf:
tf = term_freqs[token]
idf = self.idf[token]
numerator = tf * (self.k1 + 1)
denominator = tf + self.k1 * (1 - self.b + self.b * doc_len / self.avgdl)
score += idf * numerator / denominator
scores.append((idx, score))
return sorted(scores, key=lambda x: x[1], reverse=True)
# ============ SEARCH FUNCTIONS ============
def _load_csv(filepath):
"""Load CSV and return list of dicts"""
with open(filepath, 'r', encoding='utf-8') as f:
return list(csv.DictReader(f))
def _search_csv(filepath, search_cols, output_cols, query, max_results):
"""Core search function using BM25"""
if not filepath.exists():
return []
data = _load_csv(filepath)
# Build documents from search columns
documents = [" ".join(str(row.get(col, "")) for col in search_cols) for row in data]
# BM25 search
bm25 = BM25()
bm25.fit(documents)
ranked = bm25.score(query)
# Get top results with score > 0
results = []
for idx, score in ranked[:max_results]:
if score > 0:
row = data[idx]
results.append({col: row.get(col, "") for col in output_cols if col in row})
return results
def detect_domain(query):
"""Auto-detect the most relevant domain from query"""
query_lower = query.lower()
domain_keywords = {
"color": ["color", "palette", "hex", "#", "rgb"],
"chart": ["chart", "graph", "visualization", "trend", "bar", "pie", "scatter", "heatmap", "funnel"],
"landing": ["landing", "page", "cta", "conversion", "hero", "testimonial", "pricing", "section"],
"product": ["saas", "ecommerce", "e-commerce", "fintech", "healthcare", "gaming", "portfolio", "crypto", "dashboard"],
"style": ["style", "design", "ui", "minimalism", "glassmorphism", "neumorphism", "brutalism", "dark mode", "flat", "aurora", "prompt", "css", "implementation", "variable", "checklist", "tailwind"],
"ux": ["ux", "usability", "accessibility", "wcag", "touch", "scroll", "animation", "keyboard", "navigation", "mobile"],
"typography": ["font", "typography", "heading", "serif", "sans"],
"icons": ["icon", "icons", "lucide", "heroicons", "symbol", "glyph", "pictogram", "svg icon"],
"react": ["react", "next.js", "nextjs", "suspense", "memo", "usecallback", "useeffect", "rerender", "bundle", "waterfall", "barrel", "dynamic import", "rsc", "server component"],
"web": ["aria", "focus", "outline", "semantic", "virtualize", "autocomplete", "form", "input type", "preconnect"]
}
scores = {domain: sum(1 for kw in keywords if kw in query_lower) for domain, keywords in domain_keywords.items()}
best = max(scores, key=scores.get)
return best if scores[best] > 0 else "style"
def search(query, domain=None, max_results=MAX_RESULTS):
"""Main search function with auto-domain detection"""
if domain is None:
domain = detect_domain(query)
config = CSV_CONFIG.get(domain, CSV_CONFIG["style"])
filepath = DATA_DIR / config["file"]
if not filepath.exists():
return {"error": f"File not found: {filepath}", "domain": domain}
results = _search_csv(filepath, config["search_cols"], config["output_cols"], query, max_results)
return {
"domain": domain,
"query": query,
"file": config["file"],
"count": len(results),
"results": results
}
def search_stack(query, stack, max_results=MAX_RESULTS):
"""Search stack-specific guidelines"""
if stack not in STACK_CONFIG:
return {"error": f"Unknown stack: {stack}. Available: {', '.join(AVAILABLE_STACKS)}"}
filepath = DATA_DIR / STACK_CONFIG[stack]["file"]
if not filepath.exists():
return {"error": f"Stack file not found: {filepath}", "stack": stack}
results = _search_csv(filepath, _STACK_COLS["search_cols"], _STACK_COLS["output_cols"], query, max_results)
return {
"domain": "stack",
"stack": stack,
"query": query,
"file": STACK_CONFIG[stack]["file"],
"count": len(results),
"results": results
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,114 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
UI/UX Pro Max Search - BM25 search engine for UI/UX style guides
Usage: python search.py "<query>" [--domain <domain>] [--stack <stack>] [--max-results 3]
python search.py "<query>" --design-system [-p "Project Name"]
python search.py "<query>" --design-system --persist [-p "Project Name"] [--page "dashboard"]
Domains: style, prompt, color, chart, landing, product, ux, typography
Stacks: html-tailwind, react, nextjs
Persistence (Master + Overrides pattern):
--persist Save design system to design-system/MASTER.md
--page Also create a page-specific override file in design-system/pages/
"""
import argparse
import sys
import io
from core import CSV_CONFIG, AVAILABLE_STACKS, MAX_RESULTS, search, search_stack
from design_system import generate_design_system, persist_design_system
# Force UTF-8 for stdout/stderr to handle emojis on Windows (cp1252 default)
if sys.stdout.encoding and sys.stdout.encoding.lower() != 'utf-8':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
if sys.stderr.encoding and sys.stderr.encoding.lower() != 'utf-8':
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
def format_output(result):
"""Format results for Claude consumption (token-optimized)"""
if "error" in result:
return f"Error: {result['error']}"
output = []
if result.get("stack"):
output.append(f"## UI Pro Max Stack Guidelines")
output.append(f"**Stack:** {result['stack']} | **Query:** {result['query']}")
else:
output.append(f"## UI Pro Max Search Results")
output.append(f"**Domain:** {result['domain']} | **Query:** {result['query']}")
output.append(f"**Source:** {result['file']} | **Found:** {result['count']} results\n")
for i, row in enumerate(result['results'], 1):
output.append(f"### Result {i}")
for key, value in row.items():
value_str = str(value)
if len(value_str) > 300:
value_str = value_str[:300] + "..."
output.append(f"- **{key}:** {value_str}")
output.append("")
return "\n".join(output)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="UI Pro Max Search")
parser.add_argument("query", help="Search query")
parser.add_argument("--domain", "-d", choices=list(CSV_CONFIG.keys()), help="Search domain")
parser.add_argument("--stack", "-s", choices=AVAILABLE_STACKS, help="Stack-specific search (html-tailwind, react, nextjs)")
parser.add_argument("--max-results", "-n", type=int, default=MAX_RESULTS, help="Max results (default: 3)")
parser.add_argument("--json", action="store_true", help="Output as JSON")
# Design system generation
parser.add_argument("--design-system", "-ds", action="store_true", help="Generate complete design system recommendation")
parser.add_argument("--project-name", "-p", type=str, default=None, help="Project name for design system output")
parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format for design system")
# Persistence (Master + Overrides pattern)
parser.add_argument("--persist", action="store_true", help="Save design system to design-system/MASTER.md (creates hierarchical structure)")
parser.add_argument("--page", type=str, default=None, help="Create page-specific override file in design-system/pages/")
parser.add_argument("--output-dir", "-o", type=str, default=None, help="Output directory for persisted files (default: current directory)")
args = parser.parse_args()
# Design system takes priority
if args.design_system:
result = generate_design_system(
args.query,
args.project_name,
args.format,
persist=args.persist,
page=args.page,
output_dir=args.output_dir
)
print(result)
# Print persistence confirmation
if args.persist:
project_slug = args.project_name.lower().replace(' ', '-') if args.project_name else "default"
print("\n" + "=" * 60)
print(f"✅ Design system persisted to design-system/{project_slug}/")
print(f" 📄 design-system/{project_slug}/MASTER.md (Global Source of Truth)")
if args.page:
page_filename = args.page.lower().replace(' ', '-')
print(f" 📄 design-system/{project_slug}/pages/{page_filename}.md (Page Overrides)")
print("")
print(f"📖 Usage: When building a page, check design-system/{project_slug}/pages/[page].md first.")
print(f" If exists, its rules override MASTER.md. Otherwise, use MASTER.md.")
print("=" * 60)
# Stack search
elif args.stack:
result = search_stack(args.query, args.stack, args.max_results)
if args.json:
import json
print(json.dumps(result, indent=2, ensure_ascii=False))
else:
print(format_output(result))
# Domain search
else:
result = search(args.query, args.domain, args.max_results)
if args.json:
import json
print(json.dumps(result, indent=2, ensure_ascii=False))
else:
print(format_output(result))

View File

@@ -4,21 +4,29 @@ const path = require('path');
// 1. Get arguments
const args = process.argv.slice(2);
if (args.length < 2) {
console.error("Usage: node sync_vikunja.js <task_id> <message_or_commit>");
console.error("Usage:");
console.error(" node sync_vikunja.js <task_id> <message> # Update existing task");
console.error(" node sync_vikunja.js create \"<title>\" \"<message>\" # Create new task");
process.exit(1);
}
const taskId = args[0];
const commandOrId = args[0];
const message = args[1];
// 2. Load configuration from .env.agent
const envPath = path.join(__dirname, '../config/.env.agent');
if (!fs.existsSync(envPath)) {
console.error("Error: .agent/config/.env.agent file not found. Please create it from the template.");
const envPath = path.join(__dirname, '../../.env.agent');
const fallbackEnvPath = path.join(__dirname, '../config/.env.agent');
let envContent = '';
if (fs.existsSync(envPath)) {
envContent = fs.readFileSync(envPath, 'utf8');
} else if (fs.existsSync(fallbackEnvPath)) {
envContent = fs.readFileSync(fallbackEnvPath, 'utf8');
} else {
console.error("Error: .env.agent file not found.");
process.exit(1);
}
const envContent = fs.readFileSync(envPath, 'utf8');
const env = {};
envContent.split('\n').forEach(line => {
const match = line.match(/^([^#=]+)="?(.*?)"?$/);
@@ -29,6 +37,7 @@ envContent.split('\n').forEach(line => {
const apiUrl = env.VIKUNJA_API_URL;
const apiToken = env.VIKUNJA_API_TOKEN;
const projectId = env.VIKUNJA_PROJECT_ID || 14;
if (!apiUrl || !apiToken || apiUrl.includes('[YOUR_')) {
console.error("Error: VIKUNJA_API_URL or VIKUNJA_API_TOKEN is not configured correctly in .env.agent.");
@@ -40,52 +49,59 @@ if (env.AGENT_OPERATING_MODE === "TEST") {
process.exit(0);
}
// 3. Helper to make API calls using native fetch (Node 18+)
async function markTaskDoneAndComment(taskId, message) {
const FETCH_OPTS = {
headers: {
'Authorization': `Bearer ${apiToken}`,
'Content-Type': 'application/json'
}
};
async function createTaskAndComment(title, message) {
try {
console.log(`Connecting to Vikunja API for Task ${taskId}...`);
// Update task status to done
const patchRes = await fetch(`${apiUrl}/tasks/${taskId}`, {
method: 'POST', // Vikunja uses POST to task endpoint for updates
headers: {
'Authorization': `Bearer ${apiToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ done: true })
});
if (!patchRes.ok) {
throw new Error(`Failed to mark task as done: ${patchRes.statusText}`);
}
console.log(`✅ Task ${taskId} successfully marked as Done.`);
// Add comment
const commentRes = await fetch(`${apiUrl}/tasks/${taskId}/comments`, {
console.log(`Creating new task in Project ${projectId}...`);
const createRes = await fetch(`${apiUrl}/projects/${projectId}/tasks`, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${apiToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
text: `[Agent Automator] Phase completed.\nReason/Hash: ${message}`
...FETCH_OPTS,
body: JSON.stringify({
title: title,
description: message,
done: true
})
});
if (!commentRes.ok) {
console.error(`Warning: Task marked as done, but failed to attach comment: ${commentRes.statusText}`);
} else {
console.log("✅ Comment attached successfully.");
}
} catch (error) {
console.error("❌ Failed to sync with Vikunja:");
// Mask the token if it somehow leaks via error message
const secureErr = error.message.replace(new RegExp(apiToken, 'g'), "********");
console.error(secureErr);
if (!createRes.ok) throw new Error(`Create failed: ${createRes.statusText}`);
const task = await createRes.json();
console.log(`✅ Task created and marked Done! ID: #${task.id}`);
} catch (e) {
console.error("❌ Failed:", e.message);
process.exit(1);
}
}
markTaskDoneAndComment(taskId, message);
async function markTaskDoneAndComment(taskId, message) {
try {
console.log(`Updating Task ${taskId}...`);
const patchRes = await fetch(`${apiUrl}/tasks/${taskId}`, {
method: 'POST',
...FETCH_OPTS,
body: JSON.stringify({ done: true })
});
if (!patchRes.ok) throw new Error(`Update failed: ${patchRes.statusText}`);
console.log(`✅ Task ${taskId} marked as Done.`);
await fetch(`${apiUrl}/tasks/${taskId}/comments`, {
method: 'PUT', ...FETCH_OPTS, body: JSON.stringify({ text: `[Agent Automator] Phase completed.\nReason/Hash: ${message}` })
});
console.log("✅ Comment attached.");
} catch (e) {
console.error("❌ Failed:", e.message);
process.exit(1);
}
}
if (commandOrId === "create") {
createTaskAndComment(message, args[2] || "Task fully completed.");
} else {
markTaskDoneAndComment(commandOrId, message);
}