# -*- coding: utf-8 -*- """ ๐Ÿ”ฑ [Imperial Coding Arsenal] ์‰๋„์šฐ ๋ธŒ๋ ˆ์ธ ์—์ด์ „ํ‹ฑ ์ฝ”๋”ฉ ๋„๊ตฌ ์„ธํŠธ Claude Code ๋ฐฉ์‹์˜ ์ฝ”๋”ฉ ์›Œํฌํ”Œ๋กœ(ํƒ์ƒ‰ โ†’ ์ฝ๊ธฐ โ†’ ์ˆ˜์ • โ†’ ๊ฒ€์ฆ โ†’ ๋ฐ˜๋ณต)๋ฅผ ์‰๋„์šฐ ๋ธŒ๋ ˆ์ธ์— ์ด์‹ํ•˜๊ธฐ ์œ„ํ•œ ๋„๊ตฌ ๋ชจ์Œ์ž…๋‹ˆ๋‹ค. - Gemini AFC ๊ฒฝ๋กœ: CodingToolkit์˜ public ๋ฉ”์„œ๋“œ๋ฅผ callable๋กœ ์ง์ ‘ ๋“ฑ๋ก - OpenAI ํ˜ธํ™˜ ๊ฒฝ๋กœ(Atlas/OpenRouter): OPENAI_SCHEMAS + execute() ๋””์ŠคํŒจ์ฒ˜ """ import fnmatch import hashlib import json import os import re import shutil import subprocess import logging import threading import time logger = logging.getLogger("ShadowBrain.Coding") # ์ž‘์—… ๋ฃจํŠธ โ€” ์ด ๋ฐ”๊นฅ์˜ ํŒŒ์ผ์€ ๊ฑด๋“œ๋ฆฌ์ง€ ์•Š๋Š”๋‹ค (์•ˆ์ „ ๊ฐ€๋“œ) DEFAULT_ROOT = r"D:\Git_Work\jarvis_taemin" # ๐Ÿ”ฑ [Per-Request Root Override] ํ—ค์ž„๋‹ฌ 'ํƒœ๋ฏธ๋‹ˆ ์ฝ”๋“œ'๊ฐ€ ๊ณ ๋ฅธ ํ”„๋กœ์ ํŠธ ํด๋”(cwd)๋ฅผ # ํ•ด๋‹น ์š”์ฒญ ์Šค๋ ˆ๋“œ์—์„œ๋งŒ ์ž‘์—… ๋ฃจํŠธ๋กœ ์“ฐ๊ธฐ ์œ„ํ•œ ์Šค๋ ˆ๋“œ ๋กœ์ปฌ ์˜ค๋ฒ„๋ผ์ด๋“œ. # think() ๋„๊ตฌ ๋ฃจํ”„๋Š” ์š”์ฒญ ์Šค๋ ˆ๋“œ ์•ˆ์—์„œ ๋™๊ธฐ์ ์œผ๋กœ ๋Œ๋ฏ€๋กœ thread-local์ด ์ •ํ™•ํžˆ ๊ฒฉ๋ฆฌํ•œ๋‹ค. _ROOT_OVERRIDE = threading.local() def set_coding_root_override(path: str): """ํ˜„์žฌ ์š”์ฒญ ์Šค๋ ˆ๋“œ์˜ ์ฝ”๋”ฉ ์ž‘์—… ๋ฃจํŠธ๋ฅผ ์ง€์ •ํ•œ๋‹ค (์š”์ฒญ ์ข…๋ฃŒ ์‹œ clear ํ•„์ˆ˜).""" _ROOT_OVERRIDE.value = os.path.abspath(path) if path else None def clear_coding_root_override(): _ROOT_OVERRIDE.value = None # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # ๐Ÿงญ [Per-Turn Agent State] ํƒœ๋ฏธ๋‹ˆ ์ฝ”๋”ฉ ํ„ด ์ƒํƒœ (์Šค๋ ˆ๋“œ ๋กœ์ปฌ, ๋ฃจํŠธ ์˜ค๋ฒ„๋ผ์ด๋“œ์™€ ๋™์ผ ์ˆ˜๋ช…) # - read_files : ์ด๋ฒˆ ํ„ด์— code_read_file ๋กœ ์ฝ์€ ํŒŒ์ผ ์ง‘ํ•ฉ โ†’ read-before-edit ๊ฐ•์ œ # - plan : ๐Ÿ“ ํ”Œ๋žœ ๋ชจ๋“œ โ€” ํŒŒ์ผ ์ˆ˜์ •/์ƒ์„ฑยท์ƒํƒœ ๋ณ€๊ฒฝ ๋ช…๋ น์„ '๋„๊ตฌ ๋ ˆ๋ฒจ'์—์„œ ์ฐจ๋‹จ # - changes : ์ด๋ฒˆ ํ„ด์— ์ˆ˜์ •/์ƒ์„ฑํ•œ ํŒŒ์ผ ๋ชฉ๋ก [{path, action}] โ†’ CLI ๋ณ€๊ฒฝ ์š”์•ฝ # - session : ์„ธ์…˜ ํ‚ค โ†’ ์ฒดํฌํฌ์ธํŠธ(undo) ๋””๋ ‰ํ† ๋ฆฌ ๊ท€์† # ๋ฆด๋ ˆ์ด(relays/taemini.py)๊ฐ€ ํ„ด ์‹œ์ž‘์— begin_coding_turn, ์ข…๋ฃŒ์— end_coding_turn์„ # ํ˜ธ์ถœํ•œ๋‹ค. ์ด ์ƒํƒœ๊ฐ€ ์—†์œผ๋ฉด(ํƒ€ ์ฑ„๋„์˜ ์ฝ”๋”ฉ ๋ชจ๋“œ) ๊ฐ€๋“œ๋Š” ์ „๋ถ€ ๋น„ํ™œ์„ฑ โ€” ๊ธฐ์กด ๋™์ž‘ ์œ ์ง€. # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ _TURN_STATE = threading.local() CHECKPOINT_BASE = os.path.join(os.path.expanduser("~"), ".shadow_brain", "checkpoints") _CHECKPOINT_KEEP = 20 # ์„ธ์…˜๋‹น ๋ณด๊ด€ํ•˜๋Š” ํ„ด ์ฒดํฌํฌ์ธํŠธ ์ˆ˜ def begin_coding_turn(session_key: str = "", plan_mode: bool = False, user_id: str = "anonymous"): _TURN_STATE.value = { "session": (session_key or "").strip(), "plan": bool(plan_mode), "uid": (user_id or "anonymous").strip() or "anonymous", "read_files": set(), "changes": [], "ckpt_dir": None, "backed_up": set(), } def end_coding_turn(): """ํ„ด ์ƒํƒœ๋ฅผ ๊ฑท๊ณ  ์ด๋ฒˆ ํ„ด ๋ณ€๊ฒฝ ํŒŒ์ผ ๋ชฉ๋ก [{path, action}] ์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ๊ฐ™์€ ํŒŒ์ผ ๋‹คํšŒ ์ˆ˜์ •์€ 1๊ฑด์œผ๋กœ ํ•ฉ์น˜๋˜ 'create'๊ฐ€ ์žˆ์œผ๋ฉด ๊ทธ๊ฒƒ์„ ์šฐ์„  ํ‘œ๊ธฐ.""" st = getattr(_TURN_STATE, "value", None) _TURN_STATE.value = None seen = {} for ch in (st or {}).get("changes") or []: prev = seen.get(ch["path"]) if prev is None or ch["action"] == "create": seen[ch["path"]] = ch["action"] return [{"path": p, "action": a} for p, a in seen.items()] def _turn(): return getattr(_TURN_STATE, "value", None) def _session_ckpt_root(session_key: str) -> str: h = hashlib.sha1((session_key or "default").encode("utf-8")).hexdigest()[:16] return os.path.join(CHECKPOINT_BASE, h) def _checkpoint_before_change(full_path: str, root: str): """์ˆ˜์ •/์ƒ์„ฑ ์ง์ „ ์›๋ณธ ๋ฐฑ์—… โ€” /undo(ํ„ด ๋‹จ์œ„ ๋กค๋ฐฑ)์˜ ์žฌ๋ฃŒ. ํ„ด๋‹น ํŒŒ์ผ๋ณ„ ์ตœ์ดˆ 1ํšŒ๋งŒ ๋ฐฑ์—…(์›๋ณธ ๋ณด์กด). ์‹คํŒจ๋Š” ์กฐ์šฉํžˆ ๋ฌด์‹œ(ํŽธ์ง‘์„ ๋ง‰์ง€ ์•Š๋Š”๋‹ค).""" st = _turn() if st is None or not st.get("session"): return try: if full_path in st["backed_up"]: return st["backed_up"].add(full_path) if st["ckpt_dir"] is None: sess_root = _session_ckpt_root(st["session"]) os.makedirs(sess_root, exist_ok=True) # ์˜ค๋ž˜๋œ ํ„ด ์ฒดํฌํฌ์ธํŠธ ์ •๋ฆฌ (์„ธ์…˜๋‹น ์ตœ์‹  _CHECKPOINT_KEEP๊ฐœ ์œ ์ง€) turns = sorted(d for d in os.listdir(sess_root) if os.path.isdir(os.path.join(sess_root, d))) if len(turns) >= _CHECKPOINT_KEEP: for old in turns[:len(turns) - (_CHECKPOINT_KEEP - 1)]: shutil.rmtree(os.path.join(sess_root, old), ignore_errors=True) st["ckpt_dir"] = os.path.join(sess_root, str(int(time.time() * 1000))) os.makedirs(st["ckpt_dir"], exist_ok=True) manifest_path = os.path.join(st["ckpt_dir"], "manifest.json") try: with open(manifest_path, "r", encoding="utf-8") as f: manifest = json.load(f) or [] except Exception: manifest = [] entry = {"path": full_path, "backup": None} if os.path.isfile(full_path): if os.path.getsize(full_path) > 5 * 1024 * 1024: return # 5MB ์ดˆ๊ณผ ํŒŒ์ผ์€ ๋ฐฑ์—… ์ƒ๋žต (undo ๋Œ€์ƒ์—์„œ ์ œ์™ธ) bak = f"{len(manifest):04d}.bak" shutil.copy2(full_path, os.path.join(st["ckpt_dir"], bak)) entry["backup"] = bak manifest.append(entry) with open(manifest_path, "w", encoding="utf-8") as f: json.dump(manifest, f, ensure_ascii=False) except Exception as ck_err: logger.warning(f"[Coding Checkpoint] ๋ฐฑ์—… ์‹คํŒจ(ํŽธ์ง‘์€ ๊ณ„์†): {ck_err}") def _record_change(full_path: str, root: str, action: str): st = _turn() if st is None: return try: rel = os.path.relpath(full_path, root) except Exception: rel = full_path st["changes"].append({"path": rel, "action": action}) def undo_last_coding_turn(session_key: str): """์„ธ์…˜์˜ ๊ฐ€์žฅ ์ตœ๊ทผ ํ„ด ์ฒดํฌํฌ์ธํŠธ๋ฅผ ๋ณต์›ํ•œ๋‹ค (Claude Code /rewind ๋“ฑ๊ฐ€). ๋ฐ˜ํ™˜: ๋ณต์›๋œ ํ•ญ๋ชฉ ๋ฆฌ์ŠคํŠธ [{path, action(restored|deleted)}]. ์—†์œผ๋ฉด ๋นˆ ๋ฆฌ์ŠคํŠธ.""" sess_root = _session_ckpt_root(session_key) if not os.path.isdir(sess_root): return [] turns = sorted((d for d in os.listdir(sess_root) if os.path.isdir(os.path.join(sess_root, d))), reverse=True) for turn in turns: turn_dir = os.path.join(sess_root, turn) manifest_path = os.path.join(turn_dir, "manifest.json") try: with open(manifest_path, "r", encoding="utf-8") as f: manifest = json.load(f) or [] except Exception: shutil.rmtree(turn_dir, ignore_errors=True) continue restored = [] for entry in reversed(manifest): path = entry.get("path") or "" bak = entry.get("backup") try: if bak: bak_full = os.path.join(turn_dir, os.path.basename(bak)) if os.path.isfile(bak_full): shutil.copy2(bak_full, path) restored.append({"path": path, "action": "restored"}) elif os.path.isfile(path): os.remove(path) # ์ด๋ฒˆ ํ„ด์— ์ƒˆ๋กœ ๋งŒ๋“  ํŒŒ์ผ โ†’ ์‚ญ์ œ๋กœ ๋ณต์› restored.append({"path": path, "action": "deleted"}) except Exception as undo_err: logger.warning(f"[Coding Undo] ๋ณต์› ์‹คํŒจ {path}: {undo_err}") shutil.rmtree(turn_dir, ignore_errors=True) if restored: return restored return [] # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # ๐Ÿ“š [์ž๊ฐ€ ๋ฌด์žฅ] ์Šคํ‚ฌ ์ž๊ฐ€ ์ƒ์„ฑ/์žฅ์ฐฉ โ€” ์—์ด์ „ํŠธ๊ฐ€ ํ•„์š”ํ•œ ์ „๋ฌธ ์ง€์‹์„ ์Šค์Šค๋กœ ๋ฒผ๋ ค ์ž…๋Š”๋‹ค. # ์Šคํ‚ฌ ๋ณผํŠธ: /.agent/skills//SKILL.md (์ง์—… ์žฅ์ฐฉ ์Šคํ‚ฌ๊ณผ ๋™์ผ ๋ณด๊ด€์†Œ). # ์„ธ์…˜ ์žฅ์ฐฉ: local_guardian_store 'session_skills:' โ€” ๋ฆด๋ ˆ์ด๊ฐ€ ํ„ด๋งˆ๋‹ค ์ฝ์–ด # ์‹œ์Šคํ…œ ์ง€์‹œ์— ์ฃผ์ž…ํ•œ๋‹ค. ์ง์—…(job)์˜ ์žฅ์ฐฉ ๋ชฉ๋ก์€ ์ ˆ๋Œ€ ๊ฑด๋“œ๋ฆฌ์ง€ ์•Š๋Š”๋‹ค(์ง์—…=๋งˆ์™•๋‹˜ # ์†Œ๊ด€, ํด๋ฐฑ ๊ธˆ์ง€ ํ—Œ์žฅ ๋ณด์กด) โ€” ์„ธ์…˜ ์žฅ์ฐฉ์€ ๊ทธ ์œ„์— ์–นํžˆ๋Š” ์ž์œจ ๊ณ„์ธต์ด๋‹ค. # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ _SKILL_NAME_RE = re.compile(r"^[\w๊ฐ€-ํžฃ][\w๊ฐ€-ํžฃ .-]{0,60}$") _SESSION_SKILLS_CAP = 6 # ์„ธ์…˜๋‹น ์žฅ์ฐฉ ์ƒํ•œ (์ดˆ๊ณผ ์‹œ ์˜ค๋ž˜๋œ ๊ฒƒ๋ถ€ํ„ฐ ๋ฐ€๋ ค๋‚จ) def _skills_dir(): override = os.environ.get("SHADOW_SKILLS_DIR") if override: return override repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) return os.path.join(repo_root, ".agent", "skills") def list_vault_skills(limit: int = 40): """๋ณผํŠธ์— ์กด์žฌํ•˜๋Š” ์Šคํ‚ฌ ์ด๋ฆ„ ๋ชฉ๋ก (SKILL.md๊ฐ€ ์‹ค์žฌํ•˜๋Š” ํด๋”๋งŒ).""" try: d = _skills_dir() return sorted(n for n in os.listdir(d) if os.path.isfile(os.path.join(d, n, "SKILL.md")))[:limit] except Exception: return [] def session_skill_names(user_id: str, session_key: str): """์„ธ์…˜์— ์žฅ์ฐฉ๋œ ์Šคํ‚ฌ ์ด๋ฆ„ ๋ชฉ๋ก (์Šคํ† ์–ด ๊ธฐ๋ก ์ˆœ์„œ ์œ ์ง€).""" if not session_key: return [] try: from local_guardian_store import get_setting names = json.loads(get_setting(user_id or "anonymous", "local_taemini", f"session_skills:{session_key}", "[]") or "[]") return [str(n) for n in names] if isinstance(names, list) else [] except Exception: return [] def _equip_to_session(st, safe_name: str): """์„ธ์…˜ ์žฅ์ฐฉ ๊ธฐ๋ก ๊ณต์šฉ โ€” ์„ฑ๊ณต ์‹œ None, ์‹คํŒจ ์‹œ ์˜ค๋ฅ˜ ๋ฌธ์ž์—ด (forge/equip ๊ณต์œ ).""" try: from local_guardian_store import get_setting, set_setting key = f"session_skills:{st['session']}" uid = st.get("uid") or "anonymous" names = json.loads(get_setting(uid, "local_taemini", key, "[]") or "[]") if not isinstance(names, list): names = [] if safe_name in names: names.remove(safe_name) names.append(safe_name) names = names[-_SESSION_SKILLS_CAP:] set_setting(uid, "local_taemini", key, json.dumps(names, ensure_ascii=False)) return None except Exception as e: return str(e) def load_session_skills(user_id: str, session_key: str, max_chars_each: int = 1500): """์„ธ์…˜ ์žฅ์ฐฉ ์Šคํ‚ฌ [(name, content), ...] โ€” ๋ฆด๋ ˆ์ด๊ฐ€ ํ„ด๋งˆ๋‹ค ํ˜ธ์ถœํ•ด ํ”„๋กฌํ”„ํŠธ์— ์ฃผ์ž…. ํŒŒ์ผ์„ ๋งค๋ฒˆ ์ƒˆ๋กœ ์ฝ๋Š”๋‹ค(์ž๊ฐ€ ๊ฐฑ์‹  ์ฆ‰์‹œ ๋ฐ˜์˜ โ€” ์ง์—… ์Šคํ‚ฌ ์บ์‹œ์™€ ๋‹ฌ๋ฆฌ ๋ฌด์บ์‹œ).""" out = [] for name in session_skill_names(user_id, session_key): safe = os.path.basename(name.strip()) path = os.path.join(_skills_dir(), safe, "SKILL.md") try: with open(path, "r", encoding="utf-8") as f: text = f.read().strip() if len(text) > max_chars_each: text = text[:max_chars_each] + "\nโ€ฆ(์ดํ•˜ ์ƒ๋žต)" out.append((safe, text)) except Exception: continue return out # ๐Ÿ“ ํ”Œ๋žœ ๋ชจ๋“œ์—์„œ code_run_command ๋กœ ํ—ˆ์šฉํ•˜๋Š” '์ฝ๊ธฐ์„ฑ' ๋ช…๋ น ์ ‘๋‘ (์ƒํƒœ ๋ถˆ๋ณ€๊ฒฝ) _PLAN_SAFE_CMD_PREFIXES = ( "git status", "git diff", "git log", "git show", "git branch", "git blame", "ls", "dir", "cat ", "head ", "tail ", "grep ", "rg ", "find ", "wc ", "tree", "pwd", "file ", "stat ", "du ", "type ", "where ", "which ", "python -m py_compile", "python3 -m py_compile", ) _PLAN_BLOCK_MSG = ("๐Ÿ“ ํ”Œ๋žœ ๋ชจ๋“œ: ์ง€๊ธˆ์€ ๊ณ„ํš ์ˆ˜๋ฆฝ ๋‹จ๊ณ„๋ผ {what}์ด(๊ฐ€) ๋„๊ตฌ ๋ ˆ๋ฒจ์—์„œ " "์ฐจ๋‹จ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ์‹œ๋„๋Š” ์‹คํ–‰๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค โ€” ์ ˆ๋Œ€ '์ˆ˜์ •/์‹คํ–‰ ์™„๋ฃŒ'๋ผ๊ณ  " "๋ณด๊ณ ํ•˜์ง€ ๋งˆ์‹ญ์‹œ์˜ค(๊ฑฐ์ง“ ๋ณด๊ณ  ๊ธˆ์ง€). ๊ณ„ํš(๋‹จ๊ณ„๋ณ„ todos)๋งŒ ์ •๋ฆฌํ•ด ๋ณด๊ณ ํ•˜๊ณ , " "์‹คํ–‰์€ ๋งˆ์™•๋‹˜์ด ์ผ๋ฐ˜ ๋ชจ๋“œ๋กœ ์ „ํ™˜ํ•œ ๋’ค์— ์ง„ํ–‰ํ•ฉ๋‹ˆ๋‹ค.") def _loopback_headers(): """์ž๊ธฐ ์ž์‹ (127.0.0.1 ๋ฐ๋ชฌ)์œผ๋กœ์˜ HTTP ๋ฃจํ”„๋ฐฑ์šฉ ์ธ์ฆ ํ—ค๋” โ€” ์„ค์น˜๋ณ„ ๋กœ์ปฌ ํ‚ค. (auth_gate๊ฐ€ ๋กœ์ปฌ ์š”์ฒญ์—๋„ X-Taemini-Key๋ฅผ ์š”๊ตฌํ•˜๋Š” ๊ฐ•ํ™” ํ™˜๊ฒฝ ๋Œ€์‘ โ€” 2026-07-14 ์ „๋ฌธ๊ฐ€ ์†Œํ™˜ 401 ์‹ค์‚ฌ๊ณ , delegate_to_guardian๋„ ๋™์ผ ๊ฒฝ๋กœ)""" try: with open(os.path.join(os.path.expanduser("~"), ".taemini", "shadow_local_token"), "r", encoding="utf-8") as f: tok = f.read().strip() return {"X-Taemini-Key": tok} if tok else {} except Exception: return {} # ๊ฒ€์ƒ‰/ํƒ์ƒ‰ ์‹œ ๋ฌด์‹œํ•  ๋””๋ ‰ํ† ๋ฆฌ _SKIP_DIRS = { ".git", "node_modules", "venv", ".venv", "__pycache__", "dist", "build", ".next", ".dart_tool", "site-packages", ".pub-cache", "docker_data", } # ๋ช…๋ฐฑํžˆ ํŒŒ๊ดด์ ์ธ ๋ช…๋ น ์ฐจ๋‹จ (๋งˆ์™•๋‹˜ PC ๋ณดํ˜ธ) _BLOCKED_CMD_PATTERNS = [ r"\bformat\b", r"\brm\s+-rf\s+/", r"\bdel\s+/s\s+/q\s+[a-z]:\\\s*$", r"remove-item\s+-recurse\s+-force\s+[a-z]:\\\s*$", r"\bshutdown\b", r"\bmkfs\b", ] _TEXT_EXT_HINT = { ".py", ".dart", ".js", ".ts", ".tsx", ".jsx", ".json", ".yaml", ".yml", ".md", ".txt", ".html", ".css", ".sh", ".ps1", ".bat", ".rb", ".erb", ".sql", ".toml", ".ini", ".cfg", ".xml", ".csv", ".env", ".mjs", ".cjs", } class CodingToolkit: """ํŒŒ์ผ ํƒ์ƒ‰/์ฝ๊ธฐ/์ˆ˜์ •/๊ฒ€์ƒ‰/๋ช…๋ น ์‹คํ–‰ ๋„๊ตฌ. ๋ชจ๋“  ๊ฒฝ๋กœ๋Š” ์ž‘์—… ๋ฃจํŠธ ๊ธฐ์ค€ ์ƒ๋Œ€/์ ˆ๋Œ€ ๋‘˜ ๋‹ค ํ—ˆ์šฉ.""" def __init__(self, root: str = None): self._root = os.path.abspath(root or os.environ.get("SHADOW_CODING_ROOT", DEFAULT_ROOT)) @property def root(self) -> str: """์š”์ฒญ ์Šค๋ ˆ๋“œ์— ์˜ค๋ฒ„๋ผ์ด๋“œ(cwd)๊ฐ€ ์žˆ์œผ๋ฉด ๊ทธ ํด๋”, ์—†์œผ๋ฉด ๊ธฐ๋ณธ ๋ฃจํŠธ.""" override = getattr(_ROOT_OVERRIDE, "value", None) return override if override else self._root # โ”€โ”€ ๋‚ด๋ถ€ ํ—ฌํผ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def _resolve(self, path: str) -> str: p = (path or "").strip().strip('"') if not p or p in (".", "./"): return self.root if not os.path.isabs(p): p = os.path.join(self.root, p) p = os.path.abspath(p) if os.path.commonpath([p, self.root]) != self.root: raise ValueError(f"์ž‘์—… ๋ฃจํŠธ({self.root}) ๋ฐ”๊นฅ ๊ฒฝ๋กœ๋Š” ํ—ˆ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค: {p}") return p @staticmethod def _is_text_file(path: str) -> bool: ext = os.path.splitext(path)[1].lower() if ext in _TEXT_EXT_HINT: return True try: with open(path, "rb") as f: chunk = f.read(2048) return b"\x00" not in chunk except Exception: return False def _walk(self): for dirpath, dirnames, filenames in os.walk(self.root): dirnames[:] = [d for d in dirnames if d not in _SKIP_DIRS and not d.startswith(".")] yield dirpath, filenames # โ”€โ”€ ๋„๊ตฌ: ํƒ์ƒ‰ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def code_list_dir(self, path: str = ".") -> str: """Lists files and subdirectories at the given path (relative to the project root). Use this first to understand project structure. Args: path: Directory path relative to project root (default: root) """ try: target = self._resolve(path) if not os.path.isdir(target): return f"Error: ๋””๋ ‰ํ† ๋ฆฌ๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค: {path}" entries = sorted(os.listdir(target)) lines = [] for e in entries: full = os.path.join(target, e) if os.path.isdir(full): lines.append(f"[DIR] {e}/") else: try: size = os.path.getsize(full) except OSError: size = 0 lines.append(f"[FILE] {e} ({size:,} bytes)") rel = os.path.relpath(target, self.root) return f"# {rel} ({len(entries)} entries)\n" + "\n".join(lines[:300]) except Exception as e: return f"Error: {e}" def code_glob(self, pattern: str, max_results: int = 100) -> str: """Finds files matching a glob pattern (e.g. '**/*.py', 'portal-heimdall/lib/**/*.dart'). Returns matching paths relative to project root. Args: pattern: Glob pattern. '**' matches any directories. max_results: Maximum number of paths to return (default 100) """ try: pattern = (pattern or "").replace("\\", "/").lstrip("/") results = [] for dirpath, filenames in self._walk(): rel_dir = os.path.relpath(dirpath, self.root).replace("\\", "/") for fn in filenames: rel = fn if rel_dir == "." else f"{rel_dir}/{fn}" # '**/x' ํŒจํ„ด์ด ๋ฃจํŠธ ๋ฐ”๋กœ ์•„๋ž˜ ํŒŒ์ผ๋„ ์žก๋„๋ก ๋ณด์ • if fnmatch.fnmatch(rel, pattern) or ( pattern.startswith("**/") and fnmatch.fnmatch(rel, pattern[3:]) ): results.append(rel) if len(results) >= max_results: return "\n".join(results) + f"\n... (max {max_results} reached)" return "\n".join(results) if results else f"No files match: {pattern}" except Exception as e: return f"Error: {e}" def code_grep(self, pattern: str, file_glob: str = None, max_results: int = 50) -> str: """Searches file CONTENTS for a regex pattern across the project. Returns 'path:line: text' matches. Essential for finding where something is defined or used. Args: pattern: Regular expression to search for file_glob: Optional filename filter (e.g. '*.py', '*.dart') max_results: Maximum matching lines to return (default 50) """ try: rx = re.compile(pattern) except re.error as e: return f"Error: ์ž˜๋ชป๋œ ์ •๊ทœ์‹: {e}" results = [] try: for dirpath, filenames in self._walk(): for fn in filenames: if file_glob and not fnmatch.fnmatch(fn, file_glob): continue full = os.path.join(dirpath, fn) if not self._is_text_file(full): continue rel = os.path.relpath(full, self.root) try: with open(full, "r", encoding="utf-8", errors="ignore") as f: for i, line in enumerate(f, 1): if rx.search(line): results.append(f"{rel}:{i}: {line.rstrip()[:200]}") if len(results) >= max_results: return "\n".join(results) + f"\n... (max {max_results} reached)" except OSError: continue return "\n".join(results) if results else f"No matches for: {pattern}" except Exception as e: return f"Error: {e}" # โ”€โ”€ ๋„๊ตฌ: ์ฝ๊ธฐ/์“ฐ๊ธฐ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def code_read_file(self, path: str, offset: int = 1, limit: int = 400) -> str: """Reads a text file with line numbers. ALWAYS read a file before editing it. Args: path: File path (relative to project root or absolute) offset: 1-based line number to start from (default 1) limit: Max lines to return (default 400) """ try: full = self._resolve(path) if not os.path.isfile(full): return f"Error: ํŒŒ์ผ์ด ์—†์Šต๋‹ˆ๋‹ค: {path}" with open(full, "r", encoding="utf-8", errors="replace") as f: lines = f.readlines() st = _turn() if st is not None: st["read_files"].add(full) # read-before-edit ๊ฐ€๋“œ ํ•ด์ œ total = len(lines) start = max(int(offset or 1), 1) end = min(start - 1 + int(limit or 400), total) body = "".join( f"{i:>5}\t{lines[i - 1]}" for i in range(start, end + 1) ) return f"# {path} (lines {start}-{end} of {total})\n{body}" except Exception as e: return f"Error: {e}" def code_write_file(self, path: str, content: str) -> str: """Creates or fully overwrites a file with the given content (UTF-8). For small changes to existing files, prefer code_edit_file. Args: path: File path (relative to project root or absolute) content: Full file content to write """ try: full = self._resolve(path) st = _turn() if st is not None and st.get("plan"): return _PLAN_BLOCK_MSG.format(what="ํŒŒ์ผ ์ƒ์„ฑ/๋ฎ์–ด์“ฐ๊ธฐ(code_write_file)") existed = os.path.isfile(full) if (existed and st is not None and full not in st["read_files"] and os.path.basename(full) not in _READ_EXEMPT_FILES): return ("Error: ๊ธฐ์กด ํŒŒ์ผ์„ ์ฝ์ง€ ์•Š๊ณ  ํ†ต์งธ๋กœ ๋ฎ์–ด์“ฐ๋Š” ๊ฒƒ์€ ๊ธˆ์ง€์ž…๋‹ˆ๋‹ค. " f"๋จผ์ € code_read_file('{path}') ๋กœ ํ˜„์žฌ ๋‚ด์šฉ์„ ํ™•์ธํ•œ ๋’ค, " "๋ถ€๋ถ„ ์ˆ˜์ •์ด๋ฉด code_edit_file ์„ ์‚ฌ์šฉํ•˜์‹ญ์‹œ์˜ค.") _checkpoint_before_change(full, self.root) os.makedirs(os.path.dirname(full), exist_ok=True) with open(full, "w", encoding="utf-8", newline="") as f: f.write(content or "") if st is not None: st["read_files"].add(full) _record_change(full, self.root, "write" if existed else "create") verb = "๋ฎ์–ด์”€" if existed else "์ƒˆ ํŒŒ์ผ ์ƒ์„ฑ" return f"OK: wrote {len(content or '')} chars to {path} ({verb})" except Exception as e: return f"Error: {e}" @staticmethod def _edit_failure_hint(lines, old_string) -> str: """old_string ๋ถˆ์ผ์น˜ ์‹œ ์ž๊ฐ€๊ต์ • ํžŒํŠธ โ€” ์ฒซ ์œ ํšจ ์ค„๊ณผ ๊ฐ€์žฅ ๋น„์Šทํ•œ ์œ„์น˜์˜ ์‹ค์ œ ์›๋ฌธ(์ค„๋ฒˆํ˜ธ ํฌํ•จ)์„ ๋ณด์—ฌ์ค˜ ๋ชจ๋ธ์ด ์ •ํ™•ํ•œ ์›๋ฌธ์„ ๋‹ค์‹œ ๋ณต์‚ฌํ•˜๊ฒŒ ํ•œ๋‹ค. ์ •ํ™•/ํฌํ•จ ์ผ์น˜ โ†’ difflib ์œ ์‚ฌ๋„(โ‰ฅ0.55) ์ˆœ์œผ๋กœ ํƒ์ƒ‰ (์˜คํƒ€ยท๊ณต๋ฐฑ ์ฐจ์ด ๋ฐฉ์–ด).""" import difflib first = next((l.strip() for l in (old_string or "").splitlines() if l.strip()), "") if not first: return "" best_i, best_r = -1, 0.55 for i, line in enumerate(lines[:8000]): ls = line.strip() if not ls: continue if ls == first or (len(first) > 12 and first in line): best_i, best_r = i, 1.0 break r = difflib.SequenceMatcher(None, first, ls).ratio() if r > best_r: best_i, best_r = i, r if best_i >= 0: lo, hi = max(0, best_i - 2), min(len(lines), best_i + 7) snippet = "".join(f"{n + 1:>5}\t{lines[n]}" for n in range(lo, hi)) return ("\n๋น„์Šทํ•œ ์œ„์น˜์˜ ์‹ค์ œ ์›๋ฌธ(์ฐธ๊ณ ):\n" + snippet + "์œ„ ์›๋ฌธ์„ ๋“ค์—ฌ์“ฐ๊ธฐยท๊ณต๋ฐฑ๊นŒ์ง€ ๊ทธ๋Œ€๋กœ old_string์— ๋ณต์‚ฌํ•ด ๋‹ค์‹œ ์‹œ๋„ํ•˜์‹ญ์‹œ์˜ค.") return "\n(ํŒŒ์ผ์—์„œ ๋น„์Šทํ•œ ์ค„๋„ ์ฐพ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค โ€” code_grep ์œผ๋กœ ์œ„์น˜๋ถ€ํ„ฐ ๋‹ค์‹œ ํ™•์ธํ•˜์‹ญ์‹œ์˜ค.)" @staticmethod def _snippet_around(new_text, pos, added_lines, path) -> str: """ํŽธ์ง‘ ์ง€์  ์ฃผ๋ณ€ ๋ฏธ๋ฆฌ๋ณด๊ธฐ โ€” ๋ชจ๋ธ์ด ์žฌ์ฝ๊ธฐ ์—†์ด ๊ฒฐ๊ณผ๋ฅผ ํ™•์ธํ•˜๊ฒŒ ํ•œ๋‹ค.""" lines = new_text.splitlines(keepends=True) line_no = new_text[:pos].count("\n") # 0-based lo = max(0, line_no - 2) hi = min(len(lines), line_no + added_lines + 3) if hi - lo > 14: hi = lo + 14 return "".join(f"{n + 1:>5}\t{lines[n]}" for n in range(lo, hi)) def code_edit_file(self, path: str, old_string: str, new_string: str, replace_all: bool = False) -> str: """Edits a file by exact string replacement. old_string must match the file content EXACTLY (including indentation) and be unique unless replace_all=true. Read the file first to copy the exact text. Args: path: File path (relative to project root or absolute) old_string: Exact text to find (must be unique in the file unless replace_all) new_string: Replacement text replace_all: Replace every occurrence (default false) """ try: full = self._resolve(path) if not os.path.isfile(full): return f"Error: ํŒŒ์ผ์ด ์—†์Šต๋‹ˆ๋‹ค: {path}" st = _turn() if st is not None and st.get("plan"): return _PLAN_BLOCK_MSG.format(what="ํŒŒ์ผ ์ˆ˜์ •(code_edit_file)") if (st is not None and full not in st["read_files"] and os.path.basename(full) not in _READ_EXEMPT_FILES): return (f"Error: ์ฝ์ง€ ์•Š์€ ํŒŒ์ผ์€ ์ˆ˜์ •ํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋จผ์ € code_read_file('{path}') ๋กœ " "์ˆ˜์ •ํ•  ๋ถ€๋ถ„์˜ ์‹ค์ œ ์›๋ฌธ์„ ํ™•์ธํ•˜์‹ญ์‹œ์˜ค (์ด๋ฒˆ ํ„ด ๊ธฐ์ค€).") with open(full, "r", encoding="utf-8") as f: text = f.read() if old_string not in text: return ("Error: old_string์„ ํŒŒ์ผ์—์„œ ์ฐพ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค." + self._edit_failure_hint(text.splitlines(keepends=True), old_string)) count = text.count(old_string) if count > 1 and not replace_all: return f"Error: old_string์ด {count}๋ฒˆ ๋“ฑ์žฅํ•ฉ๋‹ˆ๋‹ค. ๋” ๊ธธ๊ณ  ๊ณ ์œ ํ•œ ๋ฌธ์ž์—ด์„ ์“ฐ๊ฑฐ๋‚˜ replace_all=true๋ฅผ ์ง€์ •ํ•˜์„ธ์š”." _checkpoint_before_change(full, self.root) pos = text.index(old_string) new_text = text.replace(old_string, new_string) if replace_all else text.replace(old_string, new_string, 1) with open(full, "w", encoding="utf-8", newline="") as f: f.write(new_text) _record_change(full, self.root, "edit") n = count if replace_all else 1 preview = self._snippet_around(new_text, pos, (new_string or "").count("\n"), path) return (f"OK: {path} โ€” {n}๊ณณ ์ˆ˜์ • ์™„๋ฃŒ\n์ˆ˜์ • ๊ฒฐ๊ณผ ๋ฏธ๋ฆฌ๋ณด๊ธฐ(์žฌ์ฝ๊ธฐ ๋ถˆํ•„์š”):\n{preview}") except Exception as e: return f"Error: {e}" # โ”€โ”€ ๋„๊ตฌ: ๋ช…๋ น ์‹คํ–‰(๊ฒ€์ฆ) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def code_run_command(self, command: str, cwd: str = None, timeout: int = 120) -> str: """Runs a shell command (PowerShell on Windows) and returns stdout/stderr/exit code. Use to verify changes: run tests, compile checks (python -m py_compile, flutter analyze), git status, etc. Args: command: The command line to execute cwd: Working directory relative to project root (default: project root) timeout: Seconds before the command is killed (default 120, max 600) """ try: low = (command or "").lower() for pat in _BLOCKED_CMD_PATTERNS: if re.search(pat, low): return f"Error: ํŒŒ๊ดด์  ๋ช…๋ น์ด ์ฐจ๋‹จ๋˜์—ˆ์Šต๋‹ˆ๋‹ค: {command}" st = _turn() if st is not None and st.get("plan"): stripped = low.strip() if not any(stripped.startswith(p) for p in _PLAN_SAFE_CMD_PREFIXES): return _PLAN_BLOCK_MSG.format(what=f"์ƒํƒœ ๋ณ€๊ฒฝ ๊ฐ€๋Šฅ ๋ช…๋ น ์‹คํ–‰({command[:60]})") workdir = self._resolve(cwd) if cwd else self.root timeout = min(max(int(timeout or 120), 5), 600) if os.name == "nt": cmd = ["powershell", "-NoProfile", "-NonInteractive", "-Command", command] else: cmd = ["bash", "-lc", command] proc = subprocess.run( cmd, cwd=workdir, capture_output=True, timeout=timeout, ) out = proc.stdout.decode("utf-8", errors="replace") err = proc.stderr.decode("utf-8", errors="replace") res = f"[exit code: {proc.returncode}]\n" if out.strip(): res += f"--- stdout ---\n{out[-6000:]}\n" if err.strip(): res += f"--- stderr ---\n{err[-3000:]}\n" return res.strip() except subprocess.TimeoutExpired: return f"Error: ๋ช…๋ น์ด {timeout}์ดˆ ์•ˆ์— ๋๋‚˜์ง€ ์•Š์•„ ์ค‘๋‹จํ–ˆ์Šต๋‹ˆ๋‹ค: {command}" except Exception as e: return f"Error: {e}" # โ”€โ”€ ๋„๊ตฌ: ๐Ÿ“š ์ž๊ฐ€ ๋ฌด์žฅ (์Šคํ‚ฌ ์ž๊ฐ€ ์ƒ์„ฑ/์žฅ์ฐฉ) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def code_forge_skill(self, name: str, content: str) -> str: """Creates or updates a reusable SKILL document in the shared skill vault. Use when the task needs domain knowledge/procedures no equipped skill covers โ€” distill the know-how (commands, pitfalls, steps), then equip it with code_equip_skill. Args: name: Skill name (Korean/English letters, digits, space, ._- up to 60 chars) content: The skill document body (markdown). Min 40 chars. """ st = _turn() if st is not None and st.get("plan"): return _PLAN_BLOCK_MSG.format(what="์Šคํ‚ฌ ์ƒ์„ฑ(code_forge_skill)") safe = (name or "").strip() # basename์œผ๋กœ ์กฐ์šฉํžˆ ์ž˜๋ผ๋‚ด์ง€ ์•Š๋Š”๋‹ค โ€” ๊ฒฝ๋กœ ๋ฌธ์ž๊ฐ€ ์„ž์ธ ์ด๋ฆ„์€ ๋ช…์‹œ์  ๊ฑฐ๋ถ€ if not safe or safe != os.path.basename(safe) or not _SKILL_NAME_RE.match(safe): return "Error: ์Šคํ‚ฌ ์ด๋ฆ„์€ ํ•œ๊ธ€/์˜๋ฌธ/์ˆซ์ž/๊ณต๋ฐฑ/._- 60์ž ์ด๋‚ด์—ฌ์•ผ ํ•ฉ๋‹ˆ๋‹ค (๊ฒฝ๋กœ ๋ฌธ์ž ๊ธˆ์ง€)." body = (content or "").strip() if len(body) < 40: return "Error: ์Šคํ‚ฌ ๋‚ด์šฉ์ด ๋„ˆ๋ฌด ์งง์Šต๋‹ˆ๋‹ค(40์ž ๋ฏธ๋งŒ) โ€” ์žฌ์‚ฌ์šฉ ๊ฐ€์น˜๊ฐ€ ์žˆ๋Š” ์ ˆ์ฐจ/์ง€์‹์„ ๋‹ด์œผ์‹ญ์‹œ์˜ค." body = body[:20000] try: d = os.path.join(_skills_dir(), safe) os.makedirs(d, exist_ok=True) with open(os.path.join(d, "SKILL.md"), "w", encoding="utf-8") as f: f.write(body + "\n") except Exception as e: return f"Error: ์Šคํ‚ฌ ์ €์žฅ ์‹คํŒจ: {e}" try: # ์ง์—… ์žฅ์ฐฉ ์บ์‹œ ๋ฌดํšจํ™” โ€” ๊ฐ™์€ ์ด๋ฆ„ ์Šคํ‚ฌ ๊ฐฑ์‹ ์ด ์ฆ‰์‹œ ๋ฐ˜์˜๋˜๊ฒŒ from services.brain_service import LOGIC_STATE b = LOGIC_STATE.get("jarvis_brain") if b is not None and hasattr(b, "_skill_cache"): b._skill_cache.pop(safe, None) except Exception: pass # โš”๏ธ ์ €์žฅ ์ฆ‰์‹œ ์ด ์„ธ์…˜์— ์ž๋™ ์žฅ์ฐฉ โ€” "๋งŒ๋“ค๊ณ  ์žฅ์ฐฉํ•˜๊ฒ ๋‹ค"๊ณ  ๋ง๋งŒ ํ•˜๊ณ  equip์„ # ์•ˆ ๋ถ€๋ฅด๋Š” ์•ฝํ•œ ๋ชจ๋ธ ์‹ค๊ด€์ธก(2026-07-13) ๋•Œ๋ฌธ์— ๋„๊ตฌ ์˜๋ฏธ๋ก ์„ forge=์ƒ์„ฑ+์žฅ์ฐฉ์œผ๋กœ. equip_err = _equip_to_session(st, safe) if (st and st.get("session")) else "์„ธ์…˜ ์—†์Œ" if equip_err: return (f"OK: ๐Ÿ“š ์Šคํ‚ฌ '{safe}' ์ €์žฅ({len(body)}์ž). " f"(์„ธ์…˜ ์žฅ์ฐฉ์€ ์•ˆ ๋จ: {equip_err} โ€” code_equip_skill ๋กœ ์žฅ์ฐฉ ๊ฐ€๋Šฅ)") return (f"OK: ๐Ÿ“š ์Šคํ‚ฌ '{safe}' ์ €์žฅ({len(body)}์ž) + ์ด ์„ธ์…˜์— ์žฅ์ฐฉ ์™„๋ฃŒ โ€” " "๋‹ค์Œ ํ„ด๋ถ€ํ„ฐ ์ž๋™ ์ฃผ์ž…๋ฉ๋‹ˆ๋‹ค.") def code_equip_skill(self, name: str) -> str: """Equips a vault skill onto THIS session โ€” its content is injected into your system context every following turn, and returned right now for immediate use. If the name doesn't match, available skills are listed. Args: name: Skill name to equip (as stored in the vault) """ st = _turn() if st is None or not st.get("session"): return "Error: ์„ธ์…˜ ์ •๋ณด๊ฐ€ ์—†์–ด ์žฅ์ฐฉํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค (ํƒœ๋ฏธ๋‹ˆ ์ฝ”๋”ฉ ์ฝ˜์†” ํ„ด์—์„œ๋งŒ ์ง€์›)." safe = os.path.basename((name or "").strip()) path = os.path.join(_skills_dir(), safe, "SKILL.md") if not os.path.isfile(path): avail = list_vault_skills(20) return ("Error: ๊ทธ๋Ÿฐ ์Šคํ‚ฌ์ด ์—†์Šต๋‹ˆ๋‹ค: " + safe + (f"\n์‚ฌ์šฉ ๊ฐ€๋Šฅ: {', '.join(avail)}" if avail else "\n(๋ณผํŠธ๊ฐ€ ๋น„์–ด ์žˆ์Šต๋‹ˆ๋‹ค โ€” code_forge_skill ๋กœ ๋งŒ๋“œ์‹ญ์‹œ์˜ค.)")) equip_err = _equip_to_session(st, safe) if equip_err: return f"Error: ์žฅ์ฐฉ ๊ธฐ๋ก ์‹คํŒจ: {equip_err}" try: with open(path, "r", encoding="utf-8") as f: text = f.read().strip()[:1500] except Exception: text = "(๋‚ด์šฉ ์ฝ๊ธฐ ์‹คํŒจ)" return (f"OK: ๐Ÿ“š '{safe}' ์žฅ์ฐฉ ์™„๋ฃŒ โ€” ๋‹ค์Œ ํ„ด๋ถ€ํ„ฐ ์ž๋™ ์ฃผ์ž…๋ฉ๋‹ˆ๋‹ค. " f"์ง€๊ธˆ ๋ฐ”๋กœ ํ™œ์šฉํ•  ๋‚ด์šฉ:\n{text}") # โ”€โ”€ ๋„๊ตฌ: ๐Ÿ”ง ์ž์ž‘ ๋„๊ตฌ (์Šคํฌ๋ฆฝํŠธ ์ œ์ž‘ โ†’ ์Šคํ‚ฌํ™”) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def code_forge_tool(self, name: str, script: str, usage: str) -> str: """Creates a self-made TOOL: a Python script saved in the skill vault, plus a SKILL doc describing exactly how to run it. Auto-equipped. Re-forge the same name to improve it (evolution). Run it later with code_run_command. Args: name: Tool name (letters/digits/space/._- up to 60 chars) script: Python source code (syntax-checked before saving) usage: How/when to use it โ€” arguments, examples, caveats """ st = _turn() if st is not None and st.get("plan"): return _PLAN_BLOCK_MSG.format(what="๋„๊ตฌ ์ƒ์„ฑ(code_forge_tool)") safe = (name or "").strip() if not safe or safe != os.path.basename(safe) or not _SKILL_NAME_RE.match(safe): return "Error: ๋„๊ตฌ ์ด๋ฆ„์€ ํ•œ๊ธ€/์˜๋ฌธ/์ˆซ์ž/๊ณต๋ฐฑ/._- 60์ž ์ด๋‚ด์—ฌ์•ผ ํ•ฉ๋‹ˆ๋‹ค (๊ฒฝ๋กœ ๋ฌธ์ž ๊ธˆ์ง€)." src = (script or "").strip() if len(src) < 40: return "Error: ์Šคํฌ๋ฆฝํŠธ๊ฐ€ ๋„ˆ๋ฌด ์งง์Šต๋‹ˆ๋‹ค(40์ž ๋ฏธ๋งŒ)." try: compile(src, f"{safe}.py", "exec") # ๋ฌธ๋ฒ• ๊ฒ€์‚ฌ โ€” ๊นจ์ง„ ๋„๊ตฌ๋ฅผ ๋ณผํŠธ์— ๋„ฃ์ง€ ์•Š๋Š”๋‹ค except SyntaxError as se: return (f"Error: ํŒŒ์ด์ฌ ๋ฌธ๋ฒ• ์˜ค๋ฅ˜(line {se.lineno}): {se.msg}\n" "์Šคํฌ๋ฆฝํŠธ๋ฅผ ๊ณ ์ณ ๊ฐ™์€ ์ด๋ฆ„์œผ๋กœ ๋‹ค์‹œ forge ํ•˜์‹ญ์‹œ์˜ค.") d = os.path.join(_skills_dir(), safe) tool_path = os.path.join(d, "tool.py") try: os.makedirs(d, exist_ok=True) with open(tool_path, "w", encoding="utf-8") as f: f.write(src[:30000] + "\n") doc = (f"# ๐Ÿ”ง ์ž์ž‘ ๋„๊ตฌ: {safe}\n\n" f"์‹คํ–‰: `python3 \"{tool_path}\" [์ธ์ž...]` (code_run_command ๋กœ ํ˜ธ์ถœ)\n\n" f"## ์‚ฌ์šฉ๋ฒ•\n{(usage or '').strip()[:3000]}\n\n" f"## ๊ฐœ์„ \n๋ถ€์ •ํ™•ํ•˜๋ฉด code_forge_tool('{safe}', ์ˆ˜์ • ์Šคํฌ๋ฆฝํŠธ, ์‚ฌ์šฉ๋ฒ•)์œผ๋กœ ๋ฎ์–ด์จ ์ง„ํ™”์‹œํ‚ฌ ๊ฒƒ.\n") with open(os.path.join(d, "SKILL.md"), "w", encoding="utf-8") as f: f.write(doc) except Exception as e: return f"Error: ๋„๊ตฌ ์ €์žฅ ์‹คํŒจ: {e}" equip_err = _equip_to_session(st, safe) if (st and st.get("session")) else "์„ธ์…˜ ์—†์Œ" tail = "" if equip_err else " + ์‚ฌ์šฉ๋ฒ• ์Šคํ‚ฌ ์žฅ์ฐฉ ์™„๋ฃŒ(๋‹ค์Œ ํ„ด๋ถ€ํ„ฐ ์ž๋™ ์ฃผ์ž…)" return (f"OK: ๐Ÿ”ง ์ž์ž‘ ๋„๊ตฌ '{safe}' ์ €์žฅ(๋ฌธ๋ฒ• ๊ฒ€์‚ฌ ํ†ต๊ณผ){tail}.\n" f"์‹คํ–‰: code_run_command(\"python3 \\\"{tool_path}\\\" ...\")") # โ”€โ”€ ๋„๊ตฌ: ๐Ÿง  ์žฅ๊ธฐ๊ธฐ์–ต (SQLite ๋ฒกํ„ฐ + ์˜ต์‹œ๋””์–ธ ๋ณผํŠธ ๋™์‹œ ๊ธฐ๋ก) โ”€โ”€ MEMORY_CONTEXT = "taemini-lessons" MEMORY_NOTE = "Knowledge/ํƒœ๋ฏธ๋‹ˆ ์žฅ๊ธฐ๊ธฐ์–ต.md" def code_remember(self, lesson: str, topic: str = "") -> str: """Engraves a reusable lesson/fact into LONG-TERM memory so future sessions recall it: SQLite vector memory (semantic recall, auto-injected as [์žฅ๊ธฐ๊ธฐ์–ต ํšŒ์ƒ]) + the local Obsidian vault note. Use for cross-project lessons; workspace facts go to TAEMINI.md instead. Args: lesson: The lesson/fact worth remembering (min 20 chars) topic: Short topic tag (optional) """ st = _turn() body = (lesson or "").strip() if len(body) < 20: return "Error: ๊ตํ›ˆ์ด ๋„ˆ๋ฌด ์งง์Šต๋‹ˆ๋‹ค(20์ž ๋ฏธ๋งŒ) โ€” ๋‹ค์Œ์—๋„ ์“ธ ๊ตฌ์ฒด์  ๋‚ด์šฉ์„ ๋‹ด์œผ์‹ญ์‹œ์˜ค." body = body[:2000] tag = (topic or "").strip()[:40] text = (f"[๊ตํ›ˆ/{tag}] " if tag else "[๊ตํ›ˆ] ") + body uid = (st or {}).get("uid") or "anonymous" stores = [] try: # โ‘  SQLite ์žฅ๊ธฐ๊ธฐ์–ต (chat_history + vec_memory ์ž„๋ฒ ๋”ฉ โ€” recall์˜ ์žฌ๋ฃŒ) import local_memory if local_memory.remember(uid, self.MEMORY_CONTEXT, "local_taemini", "assistant", text): stores.append("SQLite ๋ฒกํ„ฐ๊ธฐ์–ต") except Exception as mem_err: logger.warning(f"[Coding Memory] SQLite ๊ธฐ๋ก ์‹คํŒจ: {mem_err}") if os.environ.get("SHADOW_MEMORY_NO_OBSIDIAN") == "1": return (f"OK: ๐Ÿง  ์žฅ๊ธฐ๊ธฐ์–ต์— ์ƒˆ๊น€({' + '.join(stores)}) โ€” ์˜ต์‹œ๋””์–ธ ๊ธฐ๋ก์€ " "ํ™˜๊ฒฝ๋ณ€์ˆ˜๋กœ ๋น„ํ™œ์„ฑ(๊ฒ€์ฆ ๋ชจ๋“œ).") if stores else "Error: ์ €์žฅ ์‹คํŒจ." try: # โ‘ก ์˜ต์‹œ๋””์–ธ ๋ณผํŠธ ์ง€์‹ ๋…ธํŠธ (์‚ฌ๋žŒ์ด ์ฝ๋Š” ์ถ•์  ์žฅ๋ถ€) โ€” ๋™์ผ ๊ตํ›ˆ ์ค‘๋ณต ์ƒˆ๊น€ ๋ฐฉ์ง€ from obsidian_jobs import _vault v = _vault("local") if v is not None: try: _, _existing = v.read_note(self.MEMORY_NOTE) except Exception: _existing = "" if text in _existing: stores.append("์˜ต์‹œ๋””์–ธ ๋ณผํŠธ(์ด๋ฏธ ์žˆ์Œ)") else: import datetime as _dt entry = f"- {_dt.date.today().isoformat()} {text}\n" v.write_note(self.MEMORY_NOTE, entry, mode="append") stores.append("์˜ต์‹œ๋””์–ธ ๋ณผํŠธ") except Exception as obs_err: logger.warning(f"[Coding Memory] ์˜ต์‹œ๋””์–ธ ๊ธฐ๋ก ์‹คํŒจ: {obs_err}") if not stores: return "Error: ์žฅ๊ธฐ๊ธฐ์–ต ์ €์žฅ์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค (SQLite/์˜ต์‹œ๋””์–ธ ๋ชจ๋‘ ๋ถˆ๊ฐ€)." return (f"OK: ๐Ÿง  ์žฅ๊ธฐ๊ธฐ์–ต์— ์ƒˆ๊น€({' + '.join(stores)}) โ€” ๋‹ค์Œ ์„ธ์…˜๋ถ€ํ„ฐ ๊ด€๋ จ ์ž‘์—…์—์„œ " "์ž๋™ ํšŒ์ƒ๋ฉ๋‹ˆ๋‹ค.") # โ”€โ”€ ๋„๊ตฌ: ๐Ÿงฌ ์ž๊ฐ€ ์ง„ํ™” ์ง์—… (์—์ด์ „ํŠธ ์ „์šฉ ์ง์—…์˜ ์ง€์นจ/์žฅ์ฐฉ ์ž๊ฐ€ ๊ฐœ์ •) โ”€โ”€ SELF_JOB_ID = "taemini_self" SELF_JOB_LABEL = "์ž๊ฐ€์ง„ํ™” ํƒœ๋ฏธ๋‹ˆ" SELF_JOB_LEARNED_HEADER = "## ์Šค์Šค๋กœ ๋ฐฐ์šด ์ง€์นจ" SELF_JOB_RULE_CAP = 4000 # ์ง€์นจ ์ด๋Ÿ‰ ์ƒํ•œ โ€” ์•ฝํ•œ ๋ชจ๋ธ ์ปจํ…์ŠคํŠธ ๋ณดํ˜ธ def code_evolve_job(self, rule: str = "", add_skills: str = "") -> str: """Evolves YOUR OWN job 'taemini_self': APPENDS a learned directive (base rules are preserved, never replaced) and/or equips skills, then activates the job. Call with NO args first to see the current state. Other jobs are untouchable (owner-only). Args: rule: ONE new lesson-directive to append to your learned rules (min 20 chars). Distill what you learned about how to work well. add_skills: Comma-separated vault skill names to permanently equip on this job. """ st = _turn() try: from obsidian_jobs import get_vault_job, save_vault_job from local_guardian_store import get_local_guardian_job, set_local_guardian_job except Exception as e: return f"Error: ์ง์—… ์‹œ์Šคํ…œ ๋ชจ๋“ˆ ๋กœ๋“œ ์‹คํŒจ: {e}" uid = (st or {}).get("uid") or "anonymous" try: cur = get_vault_job(self.SELF_JOB_ID, "local") or {} except Exception as e: return f"Error: ์ง์—… ๋ณผํŠธ ์ ‘๊ทผ ์‹คํŒจ(์˜ต์‹œ๋””์–ธ Vault ๋น„ํ™œ์„ฑ?): {e}" cur_rule = str(cur.get("rule") or "").strip() cur_skills = list(cur.get("equipped_skills") or []) rule = (rule or "").strip() adds = [s.strip() for s in (add_skills or "").split(",") if s.strip()] if not rule and not adds: # ์กฐํšŒ ๋ชจ๋“œ โ€” ๊ฐœ์ • ์ „ ํ˜„์žฌ ์ƒํƒœ ํ™•์ธ(read-before-write) active = get_local_guardian_job(uid, "local_taemini") == self.SELF_JOB_ID return (f"[{self.SELF_JOB_LABEL} ํ˜„์žฌ ์ƒํƒœ] ํ™œ์„ฑ: {'์˜ˆ' if active else '์•„๋‹ˆ์˜ค'}\n" f"์žฅ์ฐฉ ์Šคํ‚ฌ: {cur_skills or '(์—†์Œ)'}\n์ง€์นจ:\n{cur_rule or '(์•„์ง ์—†์Œ)'}") if st is not None and st.get("plan"): return _PLAN_BLOCK_MSG.format(what="์ง์—… ๊ฐœ์ •(code_evolve_job)") if rule and len(rule) < 20: return "Error: ์ง€์นจ์ด ๋„ˆ๋ฌด ์งง์Šต๋‹ˆ๋‹ค(20์ž ๋ฏธ๋งŒ) โ€” ์ผํ•˜๋ฉฐ ๋ฐฐ์šด ์›์น™์„ ๊ตฌ์ฒด์ ์œผ๋กœ ์ ์œผ์‹ญ์‹œ์˜ค." # ๐Ÿงฌ ์ง€์นจ์€ '๋ˆ„์ ' โ€” ๊ธฐ๋ฐ˜ ์ˆ˜์น™(์ž๋น„์Šค๊ฐ€ ์‹ฌ์€ ์‚ฌ๊ณ ๋ฐฉ์‹)์„ ์•ฝํ•œ ๋ชจ๋ธ์˜ ์ž๊ฐ€ ๊ฐœ์ •์ด # ํ†ต์งธ๋กœ ๋Œ€์ฒดํ•ด ์ง€์›Œ๋ฒ„๋ฆฌ๋Š” ์‚ฌ๊ณ  ๋ฐฉ์ง€. ์ƒˆ ์ง€์นจ์€ '์Šค์Šค๋กœ ๋ฐฐ์šด ์ง€์นจ' ์„น์…˜์— append. new_rule = cur_rule if rule: if rule in cur_rule: return f"OK: ์ด๋ฏธ ์ง€์นจ์— ์žˆ๋Š” ๋‚ด์šฉ์ž…๋‹ˆ๋‹ค โ€” ์ค‘๋ณต ์ถ”๊ฐ€ ์ƒ๋žต.\nํ˜„์žฌ ์ง€์นจ:\n{cur_rule[-600:]}" entry = "- " + rule if self.SELF_JOB_LEARNED_HEADER in cur_rule: new_rule = cur_rule.rstrip() + "\n" + entry else: new_rule = ((cur_rule.rstrip() + "\n\n") if cur_rule else "") \ + self.SELF_JOB_LEARNED_HEADER + " (code_evolve_job์ด ๋ˆ„์ )\n" + entry if len(new_rule) > self.SELF_JOB_RULE_CAP: return ("Error: ์ง€์นจ์ด ๊ฐ€๋“ ์ฐผ์Šต๋‹ˆ๋‹ค(4000์ž) โ€” ๋งˆ์™•๋‹˜๊ป˜ ์ง์—… ๊ด€๋ฆฌ์ž์—์„œ " "์ •๋ฆฌ๋ฅผ ์š”์ฒญํ•˜๊ฑฐ๋‚˜, ์„ธ๋ถ€ ๋‚ด์šฉ์€ code_remember/์Šคํ‚ฌ๋กœ ์˜ฎ๊ธฐ์‹ญ์‹œ์˜ค.") missing = [s for s in adds if not os.path.isfile(os.path.join(_skills_dir(), s, "SKILL.md"))] if missing: return (f"Error: ๋ณผํŠธ์— ์—†๋Š” ์Šคํ‚ฌ: {missing} โ€” code_forge_skill/tool ๋กœ ๋จผ์ € ๋งŒ๋“œ์‹ญ์‹œ์˜ค. " f"์‚ฌ์šฉ ๊ฐ€๋Šฅ: {', '.join(list_vault_skills(20))}") for s in adds: if s in cur_skills: cur_skills.remove(s) cur_skills.append(s) cur_skills = cur_skills[-12:] job = { "job_id": self.SELF_JOB_ID, "label": self.SELF_JOB_LABEL, "description": "ํƒœ๋ฏธ๋‹ˆ๊ฐ€ ์Šค์Šค๋กœ ๊ฐœ์ •ํ•˜๋Š” ์ „์šฉ ์ง์—… (์ง€์นจยท์žฅ์ฐฉ ์Šคํ‚ฌ ์ž๊ฐ€ ์ง„ํ™”)", "tool_mode": "all", "equipped_skills": cur_skills, "rule": new_rule, } try: save_vault_job(job, "local") set_local_guardian_job(uid, "local_taemini", self.SELF_JOB_ID) except Exception as e: return f"Error: ์ง์—… ์ €์žฅ/์žฅ์ฐฉ ์‹คํŒจ: {e}" return (f"OK: ๐Ÿงฌ '{self.SELF_JOB_LABEL}' ๊ฐœ์ • + ํ™œ์„ฑํ™” โ€” ์ง€์นจ {len(new_rule)}์ž(๋ˆ„์ ), " f"์žฅ์ฐฉ ์Šคํ‚ฌ {cur_skills or '(์—†์Œ)'}. ๋‹ค์Œ ํ„ด๋ถ€ํ„ฐ ์ง€์นจ์ด ์ ์šฉ๋ฉ๋‹ˆ๋‹ค.") # โ”€โ”€ ๋„๊ตฌ: ๐Ÿง‘โ€๐Ÿ”ฌ ์ „๋ฌธ๊ฐ€ ์†Œํ™˜ (๋ง‰ํž˜ ๋ŒํŒŒ โ€” ์Šค์Šค๋กœ ์ „๋ฌธ๊ฐ€๋ฅผ ์ •์˜ํ•ด 2์ฐจ ์˜๊ฒฌ) โ”€โ”€ def code_consult_expert(self, specialty: str, question: str, context: str = "") -> str: """Summons an on-demand EXPERT persona (a specialist YOU define) and asks it your question โ€” a second brain configuration for when you're stuck. Pass the specialty, a self-contained question, and the relevant context you gathered. Verify its claims before adopting them. Args: specialty: Expert field, e.g. 'ํŒŒ์ด์ฌ ์„ฑ๋Šฅ ์ตœ์ ํ™”', '๋„คํŠธ์›Œํฌ ๋ณด์•ˆ' question: Self-contained question (min 10 chars) context: Relevant findings/code excerpts you already gathered """ spec = " ".join((specialty or "").split())[:60] q = (question or "").strip() if not spec or len(q) < 10: return "Error: specialty์™€ question(10์ž ์ด์ƒ)์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค." sys_i = (f"๋„ˆ๋Š” '{spec}' ๋ถ„์•ผ ์ตœ๊ณ  ์ „๋ฌธ๊ฐ€๋กœ ์†Œํ™˜๋˜์—ˆ๋‹ค. ์•„๋ž˜ ์งˆ๋ฌธ์— ๊ทธ ์ „๋ฌธ๊ฐ€๋กœ์„œ ๋‹ตํ•˜๋ผ.\n" "- ๊ฒฐ๋ก ๋ถ€ํ„ฐ, ๊ทผ๊ฑฐ์™€ ํ•จ๊ป˜ 5๋ฌธ์žฅ ์ด๋‚ด๋กœ. ํ™•์‹คํ•˜์ง€ ์•Š์€ ๋ถ€๋ถ„์€ '๋ถˆํ™•์‹ค'์ด๋ผ๊ณ  ํ‘œ๊ธฐํ•˜๋ผ.\n" "- ๋ชจ๋ฅด๋ฉด ๋ชจ๋ฅธ๋‹ค๊ณ  ๋‹ตํ•˜๋ผ. ์ง€์–ด๋‚ด๋Š” ๊ฒƒ์€ ๊ธˆ์ง€๋‹ค. ๋„๊ตฌ๋ฅผ ํ˜ธ์ถœํ•˜์ง€ ๋ง๊ณ  ์ง€์‹์œผ๋กœ ๋‹ตํ•˜๋ผ.") body = { "message": ((f"[์˜๋ขฐ ์ปจํ…์ŠคํŠธ]\n{(context or '').strip()[:4000]}\n\n" if (context or "").strip() else "") + f"[์ „๋ฌธ๊ฐ€ ์ž๋ฌธ ์งˆ๋ฌธ]\n{q[:2000]}"), "sessionKey": f"expert-{hashlib.sha1((spec + str(time.time())).encode()).hexdigest()[:8]}", "skipGrounding": True, "extraSystem": sys_i, } try: # ์œ„์ž„(delegate)๊ณผ ๋™์ผํ•œ ์ž๊ธฐ HTTP ๋ฃจํ”„๋ฐฑ โ€” ์ค‘์ฒฉ think() ์ƒํƒœ ์˜ค์—ผ ๋ฐฉ์ง€ import requests as _rq port = (os.environ.get("SHADOW_PORT") or "18700").strip() r = _rq.post(f"http://127.0.0.1:{port}/api/shadow/shadow/send", json=body, headers=_loopback_headers(), timeout=300) data = r.json() if r.headers.get("content-type", "").startswith("application/json") else {} except Exception as e: return f"Error: ์ „๋ฌธ๊ฐ€ ์†Œํ™˜ ์‹คํŒจ: {e}" if not data or data.get("status") == "ERROR": return f"Error: ์ „๋ฌธ๊ฐ€ ์‘๋‹ต ์‹คํŒจ: {(data or {}).get('message') or f'HTTP {r.status_code}'}" ans = (data.get("content") or "").strip()[:4000] if not ans: return "Error: ์ „๋ฌธ๊ฐ€ ์‘๋‹ต์ด ๋น„์—ˆ์Šต๋‹ˆ๋‹ค โ€” ์งˆ๋ฌธ์„ ๋” ๊ตฌ์ฒด์ ์œผ๋กœ ๋ฐ”๊ฟ” ์žฌ์‹œ๋„ํ•˜์‹ญ์‹œ์˜ค." return (f"[๐Ÿง‘โ€๐Ÿ”ฌ '{spec}' ์ „๋ฌธ๊ฐ€ ๋‹ต๋ณ€]\n{ans}\n" "(์ „๋ฌธ๊ฐ€ ์˜๊ฒฌ๋„ ๊ฒ€์ฆ ๋Œ€์ƒ์ด๋‹ค โ€” ์‚ฌ์‹ค ์ฃผ์žฅ์€ ๋„๊ตฌ๋กœ ํ™•์ธํ•œ ๋’ค ์ฑ„ํƒํ•˜๋ผ.)") # โ”€โ”€ OpenAI ํ˜ธํ™˜ ๋””์ŠคํŒจ์ฒ˜ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ TOOL_NAMES = ( "code_list_dir", "code_glob", "code_grep", "code_read_file", "code_write_file", "code_edit_file", "code_run_command", "code_forge_skill", "code_equip_skill", "code_forge_tool", "code_evolve_job", "code_remember", "code_consult_expert", ) def handles(self, name: str) -> bool: return name in self.TOOL_NAMES def execute(self, name: str, args: dict) -> str: if not self.handles(name): return f"Error: unknown coding tool '{name}'" try: return getattr(self, name)(**(args or {})) except TypeError as e: return f"Error: ์ž˜๋ชป๋œ ์ธ์ž: {e}" def callables(self): """Gemini AFC ๊ฒฝ๋กœ์šฉ โ€” bound method ๋ฆฌ์ŠคํŠธ.""" return [getattr(self, n) for n in self.TOOL_NAMES] def _schema(name, desc, props, required): return { "type": "function", "function": { "name": name, "description": desc, "parameters": {"type": "object", "properties": props, "required": required}, }, } OPENAI_SCHEMAS = [ _schema( "code_list_dir", "Lists files and subdirectories at a path inside the project. Use first to learn the project layout.", {"path": {"type": "string", "description": "Directory path relative to project root (default '.')"}}, [], ), _schema( "code_glob", "Finds files by glob pattern, e.g. '**/*.py' or 'portal-heimdall/lib/**/*.dart'. Returns relative paths.", { "pattern": {"type": "string", "description": "Glob pattern ('**' = any directories)"}, "max_results": {"type": "integer", "description": "Max paths (default 100)"}, }, ["pattern"], ), _schema( "code_grep", "Searches file CONTENTS with a regex across the project. Returns 'path:line: text'. Use to find where code is defined or used.", { "pattern": {"type": "string", "description": "Regular expression"}, "file_glob": {"type": "string", "description": "Filename filter, e.g. '*.py'"}, "max_results": {"type": "integer", "description": "Max matching lines (default 50)"}, }, ["pattern"], ), _schema( "code_read_file", "Reads a text file with line numbers. ALWAYS read before editing.", { "path": {"type": "string", "description": "File path (relative or absolute)"}, "offset": {"type": "integer", "description": "1-based start line (default 1)"}, "limit": {"type": "integer", "description": "Max lines (default 400)"}, }, ["path"], ), _schema( "code_write_file", "Creates or fully overwrites a file (UTF-8). Prefer code_edit_file for small changes.", { "path": {"type": "string", "description": "File path"}, "content": {"type": "string", "description": "Full file content"}, }, ["path", "content"], ), _schema( "code_edit_file", "Edits a file by EXACT string replacement. old_string must match exactly (indentation included) and be unique unless replace_all.", { "path": {"type": "string", "description": "File path"}, "old_string": {"type": "string", "description": "Exact text to find"}, "new_string": {"type": "string", "description": "Replacement text"}, "replace_all": {"type": "boolean", "description": "Replace all occurrences (default false)"}, }, ["path", "old_string", "new_string"], ), _schema( "code_run_command", "Runs a shell command (PowerShell) in the project and returns output + exit code. Use to VERIFY changes: tests, py_compile, flutter analyze, git status.", { "command": {"type": "string", "description": "Command line to run"}, "cwd": {"type": "string", "description": "Working dir relative to project root"}, "timeout": {"type": "integer", "description": "Seconds (default 120, max 600)"}, }, ["command"], ), _schema( "code_forge_skill", "Creates/updates a reusable SKILL document in the shared vault. Use when the task needs know-how no equipped skill covers โ€” distill it (steps, commands, pitfalls), then equip with code_equip_skill.", { "name": {"type": "string", "description": "Skill name (letters/digits/space/._- up to 60 chars)"}, "content": {"type": "string", "description": "Skill body markdown (min 40 chars)"}, }, ["name", "content"], ), _schema( "code_equip_skill", "Equips a vault skill onto this session โ€” injected into your context every following turn, and returned now for immediate use. Wrong name โ†’ lists available skills.", {"name": {"type": "string", "description": "Skill name to equip"}}, ["name"], ), _schema( "code_forge_tool", "Creates a self-made TOOL: a Python script (syntax-checked) saved in the vault + a usage SKILL auto-equipped. Re-forge the same name to improve it. Run it via code_run_command.", { "name": {"type": "string", "description": "Tool name"}, "script": {"type": "string", "description": "Python source code"}, "usage": {"type": "string", "description": "How/when to use โ€” args, examples, caveats"}, }, ["name", "script", "usage"], ), _schema( "code_evolve_job", "Evolves YOUR OWN job 'taemini_self' (self-authored directive + equipped skills) and activates it. Call with no args first to see current state. Other jobs are untouchable.", { "rule": {"type": "string", "description": "New standing directive (replaces old; min 20 chars)"}, "add_skills": {"type": "string", "description": "Comma-separated vault skill names to equip on the job"}, }, [], ), _schema( "code_consult_expert", "Summons an on-demand EXPERT persona you define and asks it a self-contained question โ€” a second opinion when you're stuck. Verify its claims with tools before adopting.", { "specialty": {"type": "string", "description": "Expert field, e.g. 'ํŒŒ์ด์ฌ ์„ฑ๋Šฅ ์ตœ์ ํ™”'"}, "question": {"type": "string", "description": "Self-contained question (min 10 chars)"}, "context": {"type": "string", "description": "Relevant findings you already gathered"}, }, ["specialty", "question"], ), _schema( "code_remember", "Engraves a reusable lesson/fact into LONG-TERM memory (SQLite vector recall + Obsidian vault note) so future sessions remember it. Cross-project lessons only; workspace facts go to TAEMINI.md.", { "lesson": {"type": "string", "description": "The lesson/fact worth remembering (min 20 chars)"}, "topic": {"type": "string", "description": "Short topic tag"}, }, ["lesson"], ), ] # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # ๐Ÿ—บ๏ธ [ํ”„๋กœ์ ํŠธ ์ปจํ…์ŠคํŠธ ์ž๋™ ์ˆ˜์ง‘] โ€” Claude Code์˜ env+CLAUDE.md ์ฃผ์ž… ๋“ฑ๊ฐ€. # ์ฝ”๋”ฉ ํ„ด ํ”„๋กฌํ”„ํŠธ ์•ž์— ์ž๋™ ์‚ฝ์ž…๋˜์–ด ๋ชจ๋ธ์ด ๋„๊ตฌ๋กœ ๋”๋“ฌ๊ธฐ ์ „์— ๋ฐฉํ–ฅ์„ ์žก๋Š”๋‹ค. # ์ „๋ถ€ ๋กœ์ปฌ ํŒŒ์ผ/git ๋กœ์ปฌ ๋ช…๋ น๋งŒ ์‚ฌ์šฉ(๋„คํŠธ์›Œํฌ 0) โ€” TTFT ๋ถ€๋‹ด ์ตœ์†Œ. # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ _PROJECT_TYPE_MARKERS = ( "package.json", "pubspec.yaml", "requirements.txt", "pyproject.toml", "Cargo.toml", "go.mod", "Gemfile", "CMakeLists.txt", "build.gradle", "settings.gradle", "Makefile", "pom.xml", "composer.json", "mix.exs", ) _AGENT_NOTE_FILES = ( # (ํŒŒ์ผ๋ช…, ์ตœ๋Œ€ ๋ฌธ์ž์ˆ˜) โ€” ์ˆœ์„œ = ์šฐ์„ ์ˆœ์œ„ ("TAEMINI.md", 3500), ("TAEMINI_NOTES.md", 3500), ("CLAUDE.md", 2500), ("AGENTS.md", 2500), ) # ๐Ÿงฌ [์›Œํฌ์ŠคํŽ˜์ด์Šค ์ง€์นจ์„œ] TAEMINI.md โ€” ์ด ํด๋”์—์„œ ํƒœ๋ฏธ๋‹ˆ๊ฐ€ ์ผํ•˜๋Š” ๋ฐฉ์‹์˜ ๋‹จ์ผ ์ง„์‹ค. # ์—†์œผ๋ฉด ์ฝ”๋”ฉ ํ„ด ์‹œ์ž‘ ์‹œ ์‹œ๋“œ๋ฅผ ์ž๋™ ์ƒ์„ฑํ•œ๋‹ค(๋งˆ์™•๋‹˜ ์š”๊ตฌ: "์—†์œผ๋ฉด ๋งŒ๋“ค๊ณ  ์Šค์Šค๋กœ ๊ฐœ์„ "). # ๋งค ํ„ด [ํ”„๋กœ์ ํŠธ ์ปจํ…์ŠคํŠธ]๋กœ ์ฃผ์ž…๋˜๊ณ , ๋ชจ๋ธ์ด code_edit_file๋กœ ๊ฐœ์„ ์„ ๋ˆ„์ ํ•œ๋‹ค. WORKSPACE_CHARTER = "TAEMINI.md" _CHARTER_SEED = """# ๐Ÿงฌ TAEMINI.md โ€” ์ด ์›Œํฌ์ŠคํŽ˜์ด์Šค์˜ ํƒœ๋ฏธ๋‹ˆ ์ง€์นจ์„œ (์ž๊ฐ€ ๊ฐœ์„ ) ์ด ํŒŒ์ผ์€ ํƒœ๋ฏธ๋‹ˆ(๋กœ์ปฌ ์ฝ”๋”ฉ ์—์ด์ „ํŠธ)๊ฐ€ ์ด ํ”„๋กœ์ ํŠธ์—์„œ ์ผํ•˜๋Š” ๋ฐฉ์‹์˜ ๋‹จ์ผ ์ง„์‹ค์ด๋‹ค. ํƒœ๋ฏธ๋‹ˆ๋Š” ๋งค ์ž‘์—…์—์„œ ์ด ์ง€์นจ์„ ๋”ฐ๋ฅด๊ณ , ์ž‘์—…์ด ๋๋‚˜๋ฉด ๋ฐฐ์šด ๊ฒƒ์„ ์—ฌ๊ธฐ ๋ฐ˜์˜ํ•ด ๊ฐœ์„ ํ•œ๋‹ค. ## ์ง€์นจ (์Šค์Šค๋กœ ๊ฐœ์„ ํ•  ๊ฒƒ) - ๊ฒ€์ฆ ์—†์ด ์™„๋ฃŒ ๋ณด๊ณ  ๊ธˆ์ง€. ๊ฐ™์€ ์‹คํŒจ 2ํšŒ๋ฉด ์ ‘๊ทผ์„ ๋ฐ”๊พผ๋‹ค. ## ํ”„๋กœ์ ํŠธ ์‚ฌ์‹ค (๊ตฌ์กฐยท๋นŒ๋“œยท๊ฒ€์ฆ ๋ช…๋ น โ€” ํ™•์ธ๋˜๋ฉด ๊ธฐ๋ก) - (์•„์ง ์—†์Œ) ## ํ•จ์ • (๊ฒช์€ ์‹ค์ˆ˜ โ€” ๋ฐ˜๋ณต ๊ธˆ์ง€) - (์•„์ง ์—†์Œ) ## ์ž์ž‘ ๋„๊ตฌ/์Šคํ‚ฌ (code_forge_tool/skill ๋กœ ๋งŒ๋“  ๊ฒƒ โ€” ์šฉ๋„ ๋ฉ”๋ชจ) - (์•„์ง ์—†์Œ) """ # ์ง€์นจ์„œ๋ฅ˜๋Š” ๋งค ํ„ด [ํ”„๋กœ์ ํŠธ ์ปจํ…์ŠคํŠธ]๋กœ ์ „์ฒด ์ฃผ์ž…๋˜๋ฏ€๋กœ read-before-edit ๋ฉด์ œ # (์žฌ์ฝ๊ธฐ ๊ฐ•์š”๋Š” ์ˆœ์ˆ˜ ๋งˆ์ฐฐ โ€” ๋ชจ๋ธ์ด ๊ฐœ์„ ์„ ํฌ๊ธฐํ•˜๊ณ  ๊ฑฐ์ง“ ๋ณด๊ณ ํ•˜๋Š” ์‹ค๊ด€์ธก์˜ ์›์ธ) _READ_EXEMPT_FILES = (WORKSPACE_CHARTER, "TAEMINI_NOTES.md") def ensure_workspace_charter(cwd: str) -> bool: """TAEMINI.md๊ฐ€ ์—†์œผ๋ฉด ์‹œ๋“œ ์ƒ์„ฑ(์ƒ์„ฑ ์‹œ True). ๊ตฌ๊ด€๋ก€ TAEMINI_NOTES.md๊ฐ€ ์ด๋ฏธ ์žˆ์œผ๋ฉด ๊ทธ๊ฒƒ์„ ์ง€์นจ์„œ๋กœ ์ธ์ •ํ•˜๊ณ  ์ƒˆ๋กœ ๋งŒ๋“ค์ง€ ์•Š๋Š”๋‹ค(์ด์ค‘ ์žฅ๋ถ€ ๋ฐฉ์ง€).""" try: cwd = os.path.abspath(cwd or ".") path = os.path.join(cwd, WORKSPACE_CHARTER) if os.path.isfile(path) or os.path.isfile(os.path.join(cwd, "TAEMINI_NOTES.md")): return False with open(path, "w", encoding="utf-8") as f: f.write(_CHARTER_SEED) with _PROJECT_CTX_LOCK: # ์ด๋ฒˆ ํ„ด ์ฃผ์ž…์— ๋ฐ”๋กœ ๋ฐ˜์˜๋˜๊ฒŒ ์บ์‹œ ๋ฌดํšจํ™” _PROJECT_CTX_CACHE.pop(cwd, None) return True except Exception: return False _PROJECT_CTX_CACHE = {} # cwd โ†’ (ts, text) _PROJECT_CTX_LOCK = threading.Lock() _PROJECT_CTX_TTL = 15 # ์ดˆ โ€” ์—ฐ์† ํ„ด์—์„œ ์žฌ์ˆ˜์ง‘ ์ƒ๋žต def _git_lines(cwd, args, timeout=2.0): try: p = subprocess.run(["git", "-C", cwd] + args, capture_output=True, timeout=timeout, text=True, errors="replace") if p.returncode != 0: return [] return [l for l in p.stdout.splitlines() if l.strip()] except Exception: return [] def build_project_context(cwd: str, max_chars: int = 7000) -> str: """์ž‘์—… ๋ฃจํŠธ์˜ ์˜ค๋ฆฌ์—”ํ…Œ์ด์…˜ ๋ธ”๋ก โ€” ์ตœ์ƒ์œ„ ๊ตฌ์„ฑยทํ”„๋กœ์ ํŠธ ํƒ€์ž…ยทgit ์ƒํƒœยท์—์ด์ „ํŠธ ๋…ธํŠธ.""" cwd = os.path.abspath(cwd or ".") now = time.time() with _PROJECT_CTX_LOCK: cached = _PROJECT_CTX_CACHE.get(cwd) if cached and now - cached[0] < _PROJECT_CTX_TTL: return cached[1] parts = [] try: entries = sorted(os.listdir(cwd)) dirs = [e + "/" for e in entries if os.path.isdir(os.path.join(cwd, e)) and e not in _SKIP_DIRS and not e.startswith(".")] files = [e for e in entries if os.path.isfile(os.path.join(cwd, e)) and not e.startswith(".")] top = (dirs + files)[:40] if top: parts.append("์ตœ์ƒ์œ„ ๊ตฌ์„ฑ: " + " ".join(top)) markers = [m for m in _PROJECT_TYPE_MARKERS if m in files] if markers: parts.append("ํ”„๋กœ์ ํŠธ ๋งˆ์ปค: " + ", ".join(markers)) except Exception: pass branch = _git_lines(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]) if branch: git_bits = [f"git ๋ธŒ๋žœ์น˜: {branch[0]}"] status = _git_lines(cwd, ["status", "--porcelain"]) if status: shown = status[:10] more = f" (+{len(status) - 10}๊ฑด ๋”)" if len(status) > 10 else "" git_bits.append("๋ณ€๊ฒฝ ํŒŒ์ผ:\n " + "\n ".join(shown) + more) else: git_bits.append("์ž‘์—… ํŠธ๋ฆฌ ๊นจ๋—ํ•จ") log = _git_lines(cwd, ["log", "-5", "--format=%h %s (%cr)"]) if log: git_bits.append("์ตœ๊ทผ ์ปค๋ฐ‹:\n " + "\n ".join(log)) parts.append("\n".join(git_bits)) for fname, cap in _AGENT_NOTE_FILES: fp = os.path.join(cwd, fname) try: if os.path.isfile(fp): with open(fp, "r", encoding="utf-8", errors="replace") as f: body = f.read(cap + 1) if len(body) > cap: body = body[:cap] + "\nโ€ฆ(์ดํ•˜ ์ƒ๋žต โ€” ํ•„์š” ์‹œ code_read_file๋กœ ์ „์ฒด ์—ด๋žŒ)" parts.append(f"### {fname} (ํ”„๋กœ์ ํŠธ ๋…ธํŠธ/์ง€์นจ โ€” ์ž๋™ ํฌํ•จ)\n{body.strip()}") except Exception: continue text = "\n\n".join(p for p in parts if p).strip()[:max_chars] with _PROJECT_CTX_LOCK: _PROJECT_CTX_CACHE[cwd] = (now, text) if len(_PROJECT_CTX_CACHE) > 32: # ๋ฌดํ•œ ์„ฑ์žฅ ๋ฐฉ์ง€ oldest = min(_PROJECT_CTX_CACHE, key=lambda k: _PROJECT_CTX_CACHE[k][0]) _PROJECT_CTX_CACHE.pop(oldest, None) return text # ์‹œ์Šคํ…œ ์ง€์‹œ์— ๋ง๋ถ™์ผ ์—์ด์ „ํ‹ฑ ์ฝ”๋”ฉ ์›Œํฌํ”Œ๋กœ ๊ฐ€์ด๋“œ CODING_AGENT_GUIDE = """ ## ๐Ÿ› ๏ธ ์—์ด์ „ํ‹ฑ ์ฝ”๋”ฉ ์ˆ˜์น™ (Imperial Coding Protocol) ๋„ˆ๋Š” ์ฝ”๋”ฉ ๋„๊ตฌ(code_*)๋ฅผ ๊ฐ€์ง„ ์ž์œจ ์ฝ”๋”ฉ ์—์ด์ „ํŠธ๋‹ค. ์ฝ”๋“œ ๊ด€๋ จ ์š”์ฒญ์„ ๋ฐ›์œผ๋ฉด ์ถ”์ธก์œผ๋กœ ๋‹ตํ•˜์ง€ ๋ง๊ณ  ๋ฐ˜๋“œ์‹œ ๋„๊ตฌ๋กœ ํ™•์ธํ•˜๋ผ. ์ž‘์—… ์ˆœ์„œ (๋ฐ˜๋“œ์‹œ ์ค€์ˆ˜): 1. **ํƒ์ƒ‰**: code_grep / code_glob / code_list_dir ๋กœ ๊ด€๋ จ ํŒŒ์ผ๊ณผ ์ฝ”๋“œ๋ฅผ ๋จผ์ € ์ฐพ๋Š”๋‹ค. ํŒŒ์ผ ์œ„์น˜๋ฅผ ์ถ”์ธกํ•˜์ง€ ๋งˆ๋ผ. 2. **์ฝ๊ธฐ**: code_read_file ๋กœ ์ˆ˜์ •ํ•  ๋ถ€๋ถ„์˜ ์‹ค์ œ ์ฝ”๋“œ๋ฅผ ์ฝ๋Š”๋‹ค. ์ฝ์ง€ ์•Š์€ ํŒŒ์ผ์„ ์ˆ˜์ •ํ•˜๋Š” ๊ฒƒ์€ ๊ธˆ์ง€๋‹ค. 3. **์ˆ˜์ •**: code_edit_file ๋กœ ์ •ํ™•ํ•œ ์›๋ฌธ(๋“ค์—ฌ์“ฐ๊ธฐ ํฌํ•จ)์„ ๋ณต์‚ฌํ•ด ๊ต์ฒดํ•œ๋‹ค. ์ƒˆ ํŒŒ์ผ๋งŒ code_write_file ์„ ์“ด๋‹ค. 4. **๊ฒ€์ฆ**: code_run_command ๋กœ ๊ฒ€์ฆํ•œ๋‹ค (python -m py_compile, flutter analyze, ํ…Œ์ŠคํŠธ ์‹คํ–‰ ๋“ฑ). ๊ฒ€์ฆ ์—†์ด "์™„๋ฃŒ"๋ผ๊ณ  ๋ณด๊ณ ํ•˜์ง€ ๋งˆ๋ผ. 5. **๋ฐ˜๋ณต**: ๊ฒ€์ฆ์ด ์‹คํŒจํ•˜๋ฉด ์˜ค๋ฅ˜ ๋ฉ”์‹œ์ง€๋ฅผ ์ฝ๊ณ  1๋ฒˆ๋ถ€ํ„ฐ ๋‹ค์‹œ ์ˆ˜ํ–‰ํ•œ๋‹ค. ๊ฐ™์€ ์‹คํŒจ๋ฅผ ๋ฐ˜๋ณตํ•˜๋ฉด ์ ‘๊ทผ์„ ๋ฐ”๊ฟ”๋ผ. ๊ทœ์น™: - ๋„๊ตฌ ๊ฒฐ๊ณผ(ํŒŒ์ผ ๋‚ด์šฉ, ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ)์— ๊ทผ๊ฑฐํ•ด์„œ๋งŒ ๋งํ•˜๋ผ. ์กด์žฌ๋ฅผ ํ™•์ธํ•˜์ง€ ์•Š์€ ํŒŒ์ผ/ํ•จ์ˆ˜๋ฅผ ์–ธ๊ธ‰ํ•˜์ง€ ๋งˆ๋ผ. - ์ˆ˜์ •์€ ์ตœ์†Œ ๋ฒ”์œ„๋กœ ํ•˜๊ณ , ์ฃผ๋ณ€ ์ฝ”๋“œ์˜ ์Šคํƒ€์ผ์„ ๋”ฐ๋ฅธ๋‹ค. - ์‹คํŒจํ•˜๋ฉด ์†”์งํ•˜๊ฒŒ ์‹คํŒจํ–ˆ๋‹ค๊ณ  ๋ณด๊ณ ํ•˜๊ณ  ์›์ธ๊ณผ ๋‹ค์Œ ์‹œ๋„๋ฅผ ์„ค๋ช…ํ•œ๋‹ค. """