ltcai 6.1.0 → 6.3.0

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.
Files changed (70) hide show
  1. package/README.md +36 -38
  2. package/docs/CHANGELOG.md +75 -1
  3. package/frontend/src/App.tsx +3 -1286
  4. package/frontend/src/components/LanguageSwitcher.tsx +23 -0
  5. package/frontend/src/components/ProductFlow.tsx +32 -669
  6. package/frontend/src/components/onboarding/AnalysisScreen.tsx +127 -0
  7. package/frontend/src/components/onboarding/DownloadConsentPanel.tsx +29 -0
  8. package/frontend/src/components/onboarding/InstallScreen.tsx +208 -0
  9. package/frontend/src/components/onboarding/LanguageChooser.tsx +23 -0
  10. package/frontend/src/components/onboarding/LoginScreen.tsx +131 -0
  11. package/frontend/src/components/onboarding/ProductFlowScreens.tsx +13 -0
  12. package/frontend/src/components/onboarding/RecommendationScreen.tsx +59 -0
  13. package/frontend/src/components/onboarding/recommendationModel.ts +132 -0
  14. package/frontend/src/features/admin/AdminConsole.tsx +294 -0
  15. package/frontend/src/features/brain/BrainCarePanel.tsx +254 -0
  16. package/frontend/src/features/brain/BrainComposer.tsx +66 -0
  17. package/frontend/src/features/brain/BrainConversation.tsx +131 -0
  18. package/frontend/src/features/brain/BrainGraphLayer.tsx +132 -0
  19. package/frontend/src/features/brain/BrainHome.tsx +232 -0
  20. package/frontend/src/features/brain/BrainMemoryLayer.tsx +38 -0
  21. package/frontend/src/features/brain/BrainOverviewPanel.tsx +74 -0
  22. package/frontend/src/features/brain/BrainRelationshipLayer.tsx +43 -0
  23. package/frontend/src/features/brain/DepthEmergence.tsx +53 -0
  24. package/frontend/src/features/brain/brainData.ts +98 -0
  25. package/frontend/src/features/brain/graphLayout.ts +26 -0
  26. package/frontend/src/features/brain/types.ts +44 -0
  27. package/frontend/src/features/review/ReviewCard.tsx +3 -1
  28. package/frontend/src/features/review/ReviewInbox.tsx +11 -1
  29. package/frontend/src/i18n.ts +290 -0
  30. package/frontend/src/pages/Brain.tsx +63 -5
  31. package/frontend/src/pages/Capture.tsx +102 -13
  32. package/frontend/src/pages/Library.tsx +72 -6
  33. package/frontend/src/styles.css +220 -0
  34. package/lattice_brain/__init__.py +1 -1
  35. package/lattice_brain/runtime/multi_agent.py +1 -1
  36. package/latticeai/__init__.py +1 -1
  37. package/latticeai/api/tools.py +50 -23
  38. package/latticeai/app_factory.py +59 -76
  39. package/latticeai/cli/entrypoint.py +283 -0
  40. package/latticeai/core/marketplace.py +1 -1
  41. package/latticeai/core/workspace_os.py +1 -1
  42. package/latticeai/integrations/__init__.py +0 -0
  43. package/latticeai/integrations/telegram_bot.py +1009 -0
  44. package/latticeai/runtime/chat_wiring.py +119 -0
  45. package/latticeai/runtime/lifespan_runtime.py +1 -1
  46. package/latticeai/runtime/model_wiring.py +40 -0
  47. package/latticeai/runtime/platform_runtime_wiring.py +86 -0
  48. package/latticeai/runtime/review_wiring.py +37 -0
  49. package/latticeai/runtime/router_registration.py +49 -30
  50. package/latticeai/runtime/tail_wiring.py +21 -0
  51. package/latticeai/services/p_reinforce.py +258 -0
  52. package/latticeai/services/router_context.py +52 -0
  53. package/ltcai_cli.py +7 -279
  54. package/p_reinforce.py +4 -255
  55. package/package.json +3 -2
  56. package/scripts/check_i18n_literals.mjs +52 -0
  57. package/scripts/release_smoke.py +133 -0
  58. package/scripts/wheel_smoke.py +4 -0
  59. package/src-tauri/Cargo.lock +1 -1
  60. package/src-tauri/Cargo.toml +1 -1
  61. package/src-tauri/tauri.conf.json +1 -1
  62. package/static/app/asset-manifest.json +5 -5
  63. package/static/app/assets/index-D76dWuQk.js +16 -0
  64. package/static/app/assets/index-D76dWuQk.js.map +1 -0
  65. package/static/app/assets/index-Div5vMlq.css +2 -0
  66. package/static/app/index.html +2 -2
  67. package/telegram_bot.py +9 -1002
  68. package/static/app/assets/index-B744yblP.css +0 -2
  69. package/static/app/assets/index-DYaUKNfl.js +0 -16
  70. package/static/app/assets/index-DYaUKNfl.js.map +0 -1
@@ -0,0 +1,119 @@
1
+ """Chat and interaction wiring seam for ``latticeai.app_factory``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Optional
6
+
7
+ from latticeai.services.router_context import InteractionRouterContext, ToolRouterContext
8
+
9
+
10
+ def build_chat_agent_runtime_from_context(
11
+ *,
12
+ build_agent_runtime: Any,
13
+ model_router: Any,
14
+ execute_tool: Any,
15
+ recent_chat_context: Any,
16
+ clear_history: Any,
17
+ knowledge_save: Any,
18
+ audit: Any,
19
+ hooks: Any,
20
+ brain_memory: Any,
21
+ ) -> Any:
22
+ return build_agent_runtime(
23
+ model_router=model_router,
24
+ execute_tool=execute_tool,
25
+ recent_chat_context=recent_chat_context,
26
+ clear_history=clear_history,
27
+ knowledge_save=knowledge_save,
28
+ audit=audit,
29
+ hooks=hooks,
30
+ brain_memory=brain_memory,
31
+ )
32
+
33
+
34
+ def build_interaction_contexts(
35
+ *,
36
+ config: Any,
37
+ ingestion_pipeline: Any,
38
+ data_dir: Any,
39
+ static_dir: Any,
40
+ model_router: Any,
41
+ require_user: Any,
42
+ require_admin: Any,
43
+ get_current_user: Any,
44
+ clear_history: Any,
45
+ append_audit_event: Any,
46
+ enforce_rate_limit: Any,
47
+ bytes_match_extension: Any,
48
+ classify_sensitive_message: Any,
49
+ save_to_history: Any,
50
+ enable_graph: bool,
51
+ knowledge_graph: Any,
52
+ require_graph: Any,
53
+ local_kg_watcher: Any,
54
+ load_mcp_installs: Any,
55
+ recommend_mcps: Any,
56
+ install_mcp: Any,
57
+ mcp_public_item: Any,
58
+ hooks: Any,
59
+ chat_context: Any,
60
+ search_service: Any,
61
+ allowed_workspaces_for: Any,
62
+ embedding_info: Any,
63
+ agent_registry: Any,
64
+ memory_service: Any,
65
+ platform: Any,
66
+ ) -> tuple[ToolRouterContext, InteractionRouterContext]:
67
+ tool_router_context = ToolRouterContext(
68
+ config=config,
69
+ ingestion_pipeline=ingestion_pipeline,
70
+ data_dir=data_dir,
71
+ static_dir=static_dir,
72
+ model_router=model_router,
73
+ require_user=require_user,
74
+ require_admin=require_admin,
75
+ get_current_user=get_current_user,
76
+ clear_history=clear_history,
77
+ append_audit_event=append_audit_event,
78
+ enforce_rate_limit=enforce_rate_limit,
79
+ bytes_match_extension=bytes_match_extension,
80
+ classify_sensitive_message=classify_sensitive_message,
81
+ save_to_history=save_to_history,
82
+ enable_graph=enable_graph,
83
+ knowledge_graph=knowledge_graph,
84
+ require_graph=require_graph,
85
+ local_kg_watcher=local_kg_watcher,
86
+ load_mcp_installs=load_mcp_installs,
87
+ recommend_mcps=recommend_mcps,
88
+ install_mcp=install_mcp,
89
+ mcp_public_item=mcp_public_item,
90
+ hooks=hooks,
91
+ )
92
+ interaction_router_context = InteractionRouterContext(
93
+ chat_context=chat_context,
94
+ search_service=search_service,
95
+ allowed_workspaces_for=allowed_workspaces_for,
96
+ require_user=require_user,
97
+ embedding_info=embedding_info,
98
+ tool_context=tool_router_context,
99
+ hooks=hooks,
100
+ agent_registry=agent_registry,
101
+ memory_service=memory_service,
102
+ platform=platform,
103
+ )
104
+ return tool_router_context, interaction_router_context
105
+
106
+
107
+ def maybe_build_telegram_chat_mirror(
108
+ *,
109
+ enable_telegram: bool,
110
+ spawn: Any,
111
+ ) -> Optional[Any]:
112
+ if not enable_telegram:
113
+ return None
114
+
115
+ def telegram_chat_mirror(role: str, text: str, source: Optional[str] = None) -> None:
116
+ from latticeai.integrations.telegram_bot import broadcast_web_chat
117
+ spawn(broadcast_web_chat(role, text), name="telegram_broadcast")
118
+
119
+ return telegram_chat_mirror
@@ -102,7 +102,7 @@ def build_lifespan_runtime(
102
102
  try:
103
103
  print(f"🧭 Lattice AI mode: {app_mode}")
104
104
  if enable_telegram:
105
- from telegram_bot import run_bot
105
+ from latticeai.integrations.telegram_bot import run_bot
106
106
 
107
107
  spawn(run_bot(), name="telegram_bot")
108
108
  print("🚀 Telegram Bot Bridge activated!")
@@ -0,0 +1,40 @@
1
+ """Model/runtime wiring seam for ``latticeai.app_factory``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from latticeai.runtime.platform_services_runtime import build_model_service
8
+
9
+
10
+ def configure_model_runtime_from_context(**kwargs: Any) -> None:
11
+ configure_model_runtime = kwargs.pop("configure_model_runtime")
12
+ configure_model_runtime(**kwargs)
13
+
14
+
15
+ def register_model_runtime_routers(
16
+ *,
17
+ app: Any,
18
+ create_health_router: Any,
19
+ create_models_router: Any,
20
+ register_health_and_model_routers: Any,
21
+ model_router: Any,
22
+ runtime_features: Any,
23
+ is_public_mode: bool,
24
+ **kwargs: Any,
25
+ ) -> Any:
26
+ model_service = build_model_service(
27
+ model_router=model_router,
28
+ runtime_features=runtime_features,
29
+ is_public=is_public_mode,
30
+ )
31
+ register_health_and_model_routers(
32
+ app,
33
+ create_health_router=create_health_router,
34
+ model_service=model_service,
35
+ create_models_router=create_models_router,
36
+ model_router=model_router,
37
+ is_public_mode=is_public_mode,
38
+ **kwargs,
39
+ )
40
+ return model_service
@@ -0,0 +1,86 @@
1
+ """Platform and automation wiring for the application factory.
2
+
3
+ This module owns the cross-subsystem runtime assembly that used to live inline
4
+ inside ``app_factory._build``. Keeping it here reduces the app factory's global
5
+ surface without changing router order or the legacy exported runtime names.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any, Callable, Dict
11
+
12
+
13
+ def build_platform_automation_runtime(
14
+ *,
15
+ model_router: Any,
16
+ workspace_store: Any,
17
+ workspace_service: Any,
18
+ plugin_registry: Any,
19
+ get_current_user: Callable[..., Any],
20
+ workspace_graph: Callable[[], Any],
21
+ workspace_scope_from_request: Callable[..., Any],
22
+ get_tool_permission: Callable[..., Any],
23
+ hooks: Any,
24
+ agent_registry: Any,
25
+ data_dir: Any,
26
+ append_audit_event: Callable[..., Any],
27
+ ) -> Dict[str, Any]:
28
+ """Build platform services, automation services, and hook bindings.
29
+
30
+ The returned names intentionally match the historical local variables in
31
+ ``app_factory._build`` so ``dict(locals())`` continues to expose the legacy
32
+ ``server_app`` compatibility surface.
33
+ """
34
+ from latticeai.runtime.automation_runtime import build_automation_runtime
35
+ from latticeai.services.platform_runtime import PlatformRuntime
36
+
37
+ def _llm_generate_sync(
38
+ message: str,
39
+ context: str = "",
40
+ max_tokens: int = 1024,
41
+ temperature: float = 0.1,
42
+ ) -> str:
43
+ # Synchronous model bridge for the orchestrator's role runner. Safe
44
+ # because the agents run endpoint executes start() in a worker thread
45
+ # (asyncio.to_thread), where no event loop is running.
46
+ import asyncio as _asyncio
47
+
48
+ return str(_asyncio.run(model_router.generate(
49
+ message,
50
+ context=context,
51
+ max_tokens=max_tokens,
52
+ temperature=temperature,
53
+ )))
54
+
55
+ platform = PlatformRuntime(
56
+ store=workspace_store,
57
+ workspace_service=workspace_service,
58
+ plugin_registry=plugin_registry,
59
+ get_current_user=get_current_user,
60
+ workspace_graph=workspace_graph,
61
+ workspace_scope_from_request=workspace_scope_from_request,
62
+ get_tool_permission=get_tool_permission,
63
+ hooks=hooks,
64
+ llm_generate=_llm_generate_sync,
65
+ llm_available=lambda: bool(getattr(model_router, "current_model_id", None)),
66
+ agent_registry=agent_registry,
67
+ )
68
+
69
+ automation_runtime = build_automation_runtime(
70
+ store=workspace_store,
71
+ platform=platform,
72
+ data_dir=data_dir,
73
+ workspace_graph=workspace_graph,
74
+ append_audit_event=append_audit_event,
75
+ hooks=hooks,
76
+ )
77
+
78
+ return {
79
+ "_llm_generate_sync": _llm_generate_sync,
80
+ "PLATFORM": platform,
81
+ "_automation_runtime": automation_runtime,
82
+ "REVIEW_QUEUE": automation_runtime["REVIEW_QUEUE"],
83
+ "TRIGGER_SERVICE": automation_runtime["TRIGGER_SERVICE"],
84
+ "AGENT_RUNTIME": automation_runtime["AGENT_RUNTIME"],
85
+ "RUN_EXECUTOR": automation_runtime["RUN_EXECUTOR"],
86
+ }
@@ -0,0 +1,37 @@
1
+ """Review Center runtime wiring helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Callable, Dict, Optional
6
+
7
+
8
+ def build_review_run_now_runner(platform: Any, http_exception: type[Exception]) -> Callable[..., Any]:
9
+ """Build the Review Center run-now runner used by the API router.
10
+
11
+ The runner preserves the public contract: "Run now" previews/regenerates the
12
+ source workflow, records a fresh run id, and leaves approval status unchanged.
13
+ """
14
+
15
+ def run_review_item(
16
+ item: Dict[str, Any],
17
+ *,
18
+ user_email: Optional[str],
19
+ scope: Optional[str],
20
+ ) -> Any:
21
+ payload = item.get("payload") or {}
22
+ provenance = item.get("provenance") or {}
23
+ workflow_id = payload.get("workflow_id") or provenance.get("workflow_id")
24
+ if not workflow_id:
25
+ raise http_exception(status_code=409, detail="review item has no workflow to run")
26
+ return platform.run_workflow_by_id(
27
+ workflow_id,
28
+ user_email,
29
+ scope,
30
+ with_agent=False,
31
+ inputs={"__review_item__": item.get("id")},
32
+ )
33
+
34
+ return run_review_item
35
+
36
+
37
+ __all__ = ["build_review_run_now_runner"]
@@ -10,6 +10,8 @@ from __future__ import annotations
10
10
 
11
11
  from typing import Any
12
12
 
13
+ from latticeai.services.router_context import InteractionRouterContext
14
+
13
15
 
14
16
  def build_static_routes_bundle(
15
17
  *,
@@ -412,45 +414,61 @@ def register_health_and_model_routers(
412
414
  def register_interaction_routers(
413
415
  app: Any,
414
416
  *,
417
+ interaction_context: InteractionRouterContext | None = None,
415
418
  create_chat_router: Any,
416
- context: Any,
419
+ context: Any = None,
417
420
  create_search_router: Any,
418
- search_service: Any,
419
- allowed_workspaces_for: Any,
420
- require_user: Any,
421
- embedding_info: Any,
421
+ search_service: Any = None,
422
+ allowed_workspaces_for: Any = None,
423
+ require_user: Any = None,
424
+ embedding_info: Any = None,
422
425
  create_tools_router: Any,
423
- ingestion_pipeline: Any,
424
- config: Any,
425
- data_dir: Any,
426
- static_dir: Any,
427
- model_router: Any,
428
- require_admin: Any,
429
- get_current_user: Any,
430
- clear_history: Any,
431
- append_audit_event: Any,
432
- enforce_rate_limit: Any,
433
- bytes_match_extension: Any,
434
- classify_sensitive_message: Any,
435
- save_to_history: Any,
436
- enable_graph: bool,
437
- knowledge_graph: Any,
438
- require_graph: Any,
439
- local_kg_watcher: Any,
440
- load_mcp_installs: Any,
441
- recommend_mcps: Any,
442
- install_mcp: Any,
443
- mcp_public_item: Any,
444
- hooks: Any,
426
+ ingestion_pipeline: Any = None,
427
+ config: Any = None,
428
+ data_dir: Any = None,
429
+ static_dir: Any = None,
430
+ model_router: Any = None,
431
+ require_admin: Any = None,
432
+ get_current_user: Any = None,
433
+ clear_history: Any = None,
434
+ append_audit_event: Any = None,
435
+ enforce_rate_limit: Any = None,
436
+ bytes_match_extension: Any = None,
437
+ classify_sensitive_message: Any = None,
438
+ save_to_history: Any = None,
439
+ enable_graph: bool | None = None,
440
+ knowledge_graph: Any = None,
441
+ require_graph: Any = None,
442
+ local_kg_watcher: Any = None,
443
+ load_mcp_installs: Any = None,
444
+ recommend_mcps: Any = None,
445
+ install_mcp: Any = None,
446
+ mcp_public_item: Any = None,
447
+ hooks: Any = None,
445
448
  create_hooks_router: Any,
446
449
  create_agent_registry_router: Any,
447
- agent_registry: Any,
450
+ agent_registry: Any = None,
448
451
  create_memory_router: Any,
449
- memory_service: Any,
450
- platform: Any,
452
+ memory_service: Any = None,
453
+ platform: Any = None,
451
454
  ) -> tuple[Any, ...]:
452
455
  """Register chat/search/tools/hooks/registry/memory routes in order."""
453
456
 
457
+ tool_context = None
458
+ if interaction_context is not None:
459
+ context = interaction_context.chat_context
460
+ search_service = interaction_context.search_service
461
+ allowed_workspaces_for = interaction_context.allowed_workspaces_for
462
+ require_user = interaction_context.require_user
463
+ embedding_info = interaction_context.embedding_info
464
+ tool_context = interaction_context.tool_context
465
+ get_current_user = tool_context.get_current_user
466
+ append_audit_event = tool_context.append_audit_event
467
+ hooks = interaction_context.hooks
468
+ agent_registry = interaction_context.agent_registry
469
+ memory_service = interaction_context.memory_service
470
+ platform = interaction_context.platform
471
+
454
472
  return register_routers(
455
473
  app,
456
474
  create_chat_router(context),
@@ -461,6 +479,7 @@ def register_interaction_routers(
461
479
  embedding_info=embedding_info,
462
480
  ),
463
481
  create_tools_router(
482
+ tool_context=tool_context,
464
483
  ingestion_pipeline=ingestion_pipeline,
465
484
  config=config,
466
485
  data_dir=data_dir,
@@ -0,0 +1,21 @@
1
+ """Review, browser, portability, network, garden, and setup tail wiring."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+
8
+ def register_tail_runtime_routers(
9
+ *,
10
+ app: Any,
11
+ create_review_queue_router: Any,
12
+ register_review_and_brain_tail_routers: Any,
13
+ build_brain_network: Any,
14
+ **kwargs: Any,
15
+ ) -> Any:
16
+ return register_review_and_brain_tail_routers(
17
+ app,
18
+ create_review_queue_router=create_review_queue_router,
19
+ build_brain_network=build_brain_network,
20
+ **kwargs,
21
+ )
@@ -0,0 +1,258 @@
1
+ """
2
+ P-Reinforce Knowledge Gardener — notes capture with a brain-backed memory.
3
+
4
+ v4 (T4.3 garden absorption): the markdown vault is no longer a second brain.
5
+ The vault stays as the user-owned, Obsidian-compatible *mirror* (capability
6
+ preserved), but the Knowledge Graph is authoritative: notes created through
7
+ the API are ingested through the unified pipeline (provenance + hooks), the
8
+ existing vault is imported idempotently, and chat context comes from brain
9
+ queries instead of an O(n) vault scan per message.
10
+ """
11
+
12
+ import logging
13
+ import os
14
+ import re
15
+ import shutil
16
+ from datetime import datetime
17
+ from pathlib import Path
18
+ from typing import Any, Optional
19
+
20
+ BRAIN_DIR = Path(
21
+ os.getenv("LATTICEAI_OBSIDIAN_VAULT_DIR")
22
+ or os.getenv("LATTICEAI_BRAIN_DIR")
23
+ or Path.home() / ".ltcai-brain"
24
+ )
25
+
26
+ STRUCTURE = {
27
+ "10_Wiki": "검증된 지식, 개념 설명, 레퍼런스",
28
+ "00_Raw": "정제되지 않은 원시 데이터, 아이디어 메모",
29
+ "20_Skills": "재사용 가능한 코드 스니펫, 프롬프트, 워크플로",
30
+ "30_Projects": "프로젝트별 컨텍스트, 진행 상황",
31
+ "40_Log": "날짜별 작업 로그",
32
+ }
33
+
34
+
35
+ class PReinforceGardener:
36
+ def __init__(self, ingestion_pipeline: Any = None, knowledge_graph: Any = None):
37
+ self._pipeline = ingestion_pipeline
38
+ self._kg = knowledge_graph
39
+ self._ensure_structure()
40
+
41
+ def _ensure_structure(self):
42
+ for folder in STRUCTURE:
43
+ (BRAIN_DIR / folder).mkdir(parents=True, exist_ok=True)
44
+ # 인덱스 파일
45
+ index_path = BRAIN_DIR / "INDEX.md"
46
+ if not index_path.exists():
47
+ index_path.write_text(self._render_index())
48
+
49
+ def _render_index(self) -> str:
50
+ lines = ["# 🧠 Lattice AI Brain — P-Reinforce Index\n"]
51
+ lines.append(f"*Generated: {datetime.now().strftime('%Y-%m-%d %H:%M')}*\n")
52
+ lines.append("\nThis folder is an Obsidian-compatible Markdown vault.\n")
53
+ lines.append("\nThe Knowledge Graph is the authoritative store; this vault is the\nuser-owned markdown mirror of garden notes.\n")
54
+ for folder, desc in STRUCTURE.items():
55
+ lines.append(f"## [{folder}](./{folder}/)\n_{desc}_\n")
56
+ lines.append("## Connector Status\n")
57
+ lines.append(f"- OCR engine: `{'tesseract' if shutil.which('tesseract') else 'not installed'}`\n")
58
+ return "\n".join(lines)
59
+
60
+ # ── Classify ──────────────────────────────────────────────────────────────
61
+
62
+ def _classify(self, text: str) -> str:
63
+ """간단한 규칙 기반 분류 (LLM 없이도 동작)"""
64
+ text_lower = text.lower()
65
+
66
+ code_signals = ["def ", "class ", "import ", "```", "function ", "const ", "let ", "var "]
67
+ if any(s in text for s in code_signals):
68
+ return "20_Skills"
69
+
70
+ wiki_signals = ["개념", "원리", "이란", "what is", "how does", "definition", "explanation"]
71
+ if any(s in text_lower for s in wiki_signals):
72
+ return "10_Wiki"
73
+
74
+ project_signals = ["project", "프로젝트", "todo", "task", "작업", "기능", "feature"]
75
+ if any(s in text_lower for s in project_signals):
76
+ return "30_Projects"
77
+
78
+ return "00_Raw"
79
+
80
+ # ── File Naming ───────────────────────────────────────────────────────────
81
+
82
+ def _make_filename(self, text: str, folder: str) -> str:
83
+ # 첫 줄을 제목으로
84
+ first_line = text.strip().split("\n")[0][:60]
85
+ # 파일명 안전하게
86
+ safe = re.sub(r"[^\w\s-]", "", first_line).strip()
87
+ safe = re.sub(r"\s+", "_", safe)
88
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
89
+ return f"{timestamp}_{safe or 'note'}.md"
90
+
91
+ # ── Process ───────────────────────────────────────────────────────────────
92
+
93
+ async def process(self, raw_data: str, category: Optional[str] = None) -> dict:
94
+ folder = category if category in STRUCTURE else self._classify(raw_data)
95
+ filename = self._make_filename(raw_data, folder)
96
+ filepath = BRAIN_DIR / folder / filename
97
+
98
+ # 마크다운 미러 (사용자 소유 Obsidian 호환 아티팩트)
99
+ content = self._wrap_markdown(raw_data, folder)
100
+ filepath.write_text(content, encoding="utf-8")
101
+
102
+ # 오늘 로그에도 기록
103
+ self._append_log(raw_data[:200], folder, filename)
104
+
105
+ result = {
106
+ "status": "saved",
107
+ "folder": folder,
108
+ "filename": filename,
109
+ "path": str(filepath),
110
+ "classified_as": folder,
111
+ "description": STRUCTURE[folder],
112
+ }
113
+ # 두뇌(Knowledge Graph)가 정식 저장소: 통합 수집 파이프라인으로 ingest.
114
+ result.update(self._ingest_note(raw_data, source_uri=str(filepath), folder=folder))
115
+ return result
116
+
117
+ def _ingest_note(self, text: str, *, source_uri: str, folder: str, title: Optional[str] = None) -> dict:
118
+ if self._pipeline is None:
119
+ return {"graph": "unavailable", "graph_detail": "ingestion pipeline not wired"}
120
+ try:
121
+ from lattice_brain.ingestion import IngestionItem
122
+
123
+ ingest = self._pipeline.ingest(
124
+ IngestionItem(
125
+ source_type="note",
126
+ title=title or text.strip().split("\n")[0][:80],
127
+ text=text,
128
+ source_uri=source_uri,
129
+ metadata={"garden_folder": folder, "pipeline": "p-reinforce"},
130
+ )
131
+ )
132
+ if ingest.status != "ok":
133
+ return {"graph": ingest.status, "graph_detail": ingest.detail}
134
+ return {
135
+ "graph": "ok",
136
+ "graph_node_id": ingest.node_id,
137
+ "provenance_id": ingest.provenance_id,
138
+ "duplicate": ingest.duplicate,
139
+ }
140
+ except Exception as exc:
141
+ logging.warning("garden note ingest failed: %s", exc)
142
+ return {"graph": "failed", "graph_detail": str(exc)}
143
+
144
+ def import_vault(self) -> dict:
145
+ """Idempotent import of every existing vault note into the brain.
146
+
147
+ Content-hash dedup in the store makes re-runs safe; vault files are
148
+ never modified or deleted. INDEX.md and the daily logs are skipped.
149
+ """
150
+ if self._pipeline is None:
151
+ return {"status": "unavailable", "imported": 0}
152
+ imported = duplicates = failed = 0
153
+ for file_path in sorted(BRAIN_DIR.rglob("*.md")):
154
+ if file_path.name == "INDEX.md" or "40_Log" in file_path.parts:
155
+ continue
156
+ try:
157
+ text = file_path.read_text(encoding="utf-8")
158
+ except Exception:
159
+ failed += 1
160
+ continue
161
+ folder = file_path.parent.name if file_path.parent != BRAIN_DIR else "00_Raw"
162
+ outcome = self._ingest_note(
163
+ text, source_uri=str(file_path), folder=folder, title=file_path.stem
164
+ )
165
+ if outcome.get("graph") == "ok":
166
+ if outcome.get("duplicate"):
167
+ duplicates += 1
168
+ else:
169
+ imported += 1
170
+ else:
171
+ failed += 1
172
+ if imported:
173
+ logging.info("garden: imported %d vault notes into the brain (%d already known)", imported, duplicates)
174
+ return {"status": "ok", "imported": imported, "duplicates": duplicates, "failed": failed}
175
+
176
+ def _wrap_markdown(self, raw: str, folder: str) -> str:
177
+ now = datetime.now().strftime("%Y-%m-%d %H:%M")
178
+ first_line = raw.strip().split("\n")[0][:80]
179
+ lines = [
180
+ f"# {first_line}",
181
+ f"\n> 📁 `{folder}` | 🕐 {now} | Lattice AI MLX\n",
182
+ "---\n",
183
+ raw,
184
+ "\n\n---",
185
+ "*Auto-organized by P-Reinforce Gardener*",
186
+ ]
187
+ return "\n".join(lines)
188
+
189
+ def _append_log(self, preview: str, folder: str, filename: str):
190
+ today = datetime.now().strftime("%Y-%m-%d")
191
+ log_path = BRAIN_DIR / "40_Log" / f"{today}.md"
192
+ entry = f"\n- [{datetime.now().strftime('%H:%M')}] → `{folder}/{filename}`\n > {preview[:100]}\n"
193
+ with open(log_path, "a", encoding="utf-8") as f:
194
+ if log_path.stat().st_size == 0 if log_path.exists() else True:
195
+ f.write(f"# 📅 Log — {today}\n")
196
+ f.write(entry)
197
+
198
+ # ── Tree ──────────────────────────────────────────────────────────────────
199
+
200
+ def get_tree(self) -> dict:
201
+ """지식 정원 파일트리 (마크다운 미러 기준)."""
202
+ folders = []
203
+ for folder, desc in STRUCTURE.items():
204
+ folder_path = BRAIN_DIR / folder
205
+ files = []
206
+ if folder_path.exists():
207
+ for file_path in sorted(folder_path.glob("*.md")):
208
+ try:
209
+ stat = file_path.stat()
210
+ files.append({
211
+ "name": file_path.name,
212
+ "size_bytes": stat.st_size,
213
+ "modified_at": datetime.fromtimestamp(stat.st_mtime).isoformat(timespec="seconds"),
214
+ })
215
+ except OSError:
216
+ continue
217
+ folders.append({"name": folder, "description": desc, "files": files, "count": len(files)})
218
+ return {"root": str(BRAIN_DIR), "folders": folders}
219
+
220
+ def get_relevant_context(self, query: str, limit: int = 3) -> str:
221
+ """질문과 관련된 정원 노트를 두뇌에서 검색해 컨텍스트로 반환.
222
+
223
+ v4: 채팅마다 vault 전체를 rglob 하던 O(n) 스캔을 브레인 검색으로
224
+ 대체. 그래프가 없으면(비활성) 기존 파일 스캔으로 정직하게 폴백.
225
+ """
226
+ if self._kg is not None:
227
+ try:
228
+ matches = self._kg.search(query, max(limit * 4, 8)).get("matches", [])
229
+ results = []
230
+ for match in matches:
231
+ meta = match.get("metadata") or {}
232
+ if not (meta.get("garden_folder") or meta.get("pipeline") == "p-reinforce"):
233
+ continue
234
+ title = match.get("title") or "note"
235
+ body = match.get("summary") or ""
236
+ results.append(f"--- Document: {title} ---\n{body[:800]}")
237
+ if len(results) >= limit:
238
+ break
239
+ return "\n\n".join(results)
240
+ except Exception as exc:
241
+ logging.debug("garden brain context failed, falling back to vault scan: %s", exc)
242
+ return self._scan_vault_context(query, limit)
243
+
244
+ def _scan_vault_context(self, query: str, limit: int = 3) -> str:
245
+ results = []
246
+ for file_path in BRAIN_DIR.rglob("*.md"):
247
+ if file_path.name == "INDEX.md" or "40_Log" in str(file_path):
248
+ continue
249
+ try:
250
+ content = file_path.read_text(encoding="utf-8")
251
+ keywords = [k for k in re.split(r"\s+", query) if len(k) > 1]
252
+ if any(k.lower() in content.lower() for k in keywords):
253
+ results.append(f"--- Document: {file_path.name} ---\n{content[:800]}")
254
+ if len(results) >= limit:
255
+ break
256
+ except Exception:
257
+ continue
258
+ return "\n\n".join(results)