pomera-ai-commander 1.2.1 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -196,7 +196,14 @@ class ToolRegistry:
196
196
  self._register_html_tool()
197
197
  self._register_list_comparator_tool()
198
198
 
199
+ # Safe Update Tool (Phase 5) - for AI-initiated updates
200
+ self._register_safe_update_tool()
201
+
202
+ # Find & Replace Diff Tool (Phase 6) - regex find/replace with diff preview and Notes backup
203
+ self._register_find_replace_diff_tool()
204
+
199
205
  self._logger.info(f"Registered {len(self._tools)} built-in MCP tools")
206
+
200
207
 
201
208
  def _register_case_tool(self) -> None:
202
209
  """Register the Case Tool."""
@@ -1844,9 +1851,14 @@ class ToolRegistry:
1844
1851
 
1845
1852
  def _get_notes_db_path(self) -> str:
1846
1853
  """Get the path to the notes database."""
1847
- import os
1848
- project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
1849
- return os.path.join(project_root, 'notes.db')
1854
+ try:
1855
+ from core.data_directory import get_database_path
1856
+ return get_database_path('notes.db')
1857
+ except ImportError:
1858
+ # Fallback to legacy behavior
1859
+ import os
1860
+ project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
1861
+ return os.path.join(project_root, 'notes.db')
1850
1862
 
1851
1863
  def _get_notes_connection(self):
1852
1864
  """Get a connection to the notes database."""
@@ -2352,9 +2364,324 @@ class ToolRegistry:
2352
2364
  result_lines.extend(in_both if in_both else ["(none)"])
2353
2365
 
2354
2366
  return "\n".join(result_lines)
2367
+
2368
+ def _register_safe_update_tool(self) -> None:
2369
+ """Register the Safe Update Tool for AI-initiated updates."""
2370
+ self.register(MCPToolAdapter(
2371
+ name="pomera_safe_update",
2372
+ description="Check update safety and get backup instructions before updating Pomera. "
2373
+ "IMPORTANT: In portable mode, npm/pip updates WILL DELETE user data. "
2374
+ "Always call this with action='check' before initiating any update.",
2375
+ input_schema={
2376
+ "type": "object",
2377
+ "properties": {
2378
+ "action": {
2379
+ "type": "string",
2380
+ "enum": ["check", "backup", "get_update_command"],
2381
+ "description": "check=analyze risks, backup=create backup to safe location, "
2382
+ "get_update_command=get recommended update command"
2383
+ },
2384
+ "backup_path": {
2385
+ "type": "string",
2386
+ "description": "For backup action: directory to save backup (default: user's Documents folder)"
2387
+ }
2388
+ },
2389
+ "required": ["action"]
2390
+ },
2391
+ handler=self._handle_safe_update
2392
+ ))
2393
+
2394
+ def _handle_safe_update(self, args: Dict[str, Any]) -> str:
2395
+ """Handle safe update tool execution."""
2396
+ import json
2397
+ import os
2398
+ import platform
2399
+ from pathlib import Path
2400
+
2401
+ action = args.get("action", "check")
2402
+
2403
+ # Determine installation mode
2404
+ try:
2405
+ from core.data_directory import is_portable_mode, get_user_data_dir, get_data_directory_info
2406
+ portable = is_portable_mode()
2407
+ data_info = get_data_directory_info()
2408
+ except ImportError:
2409
+ portable = False
2410
+ data_info = {"error": "data_directory module not available"}
2411
+
2412
+ # Get current version
2413
+ try:
2414
+ import importlib.metadata
2415
+ version = importlib.metadata.version("pomera-ai-commander")
2416
+ except Exception:
2417
+ version = "unknown"
2418
+
2419
+ # Get installation directory
2420
+ install_dir = Path(__file__).parent.parent.parent
2421
+
2422
+ # Find existing databases
2423
+ databases_found = []
2424
+ for db_name in ["settings.db", "notes.db", "settings.json"]:
2425
+ db_path = install_dir / db_name
2426
+ if db_path.exists():
2427
+ databases_found.append({
2428
+ "name": db_name,
2429
+ "path": str(db_path),
2430
+ "size_bytes": db_path.stat().st_size
2431
+ })
2432
+
2433
+ if action == "check":
2434
+ # Return risk assessment
2435
+ result = {
2436
+ "current_version": version,
2437
+ "installation_mode": "portable" if portable else "platform_dirs",
2438
+ "installation_dir": str(install_dir),
2439
+ "data_at_risk": portable and len(databases_found) > 0,
2440
+ "databases_in_install_dir": databases_found,
2441
+ "backup_required": portable and len(databases_found) > 0,
2442
+ "platform": platform.system(),
2443
+ }
2444
+
2445
+ if portable and databases_found:
2446
+ result["warning"] = (
2447
+ "CRITICAL: Portable mode detected with databases in installation directory. "
2448
+ "Running 'npm update' or 'pip install --upgrade' WILL DELETE these files! "
2449
+ "You MUST run pomera_safe_update with action='backup' before updating."
2450
+ )
2451
+ result["recommended_action"] = "backup"
2452
+ else:
2453
+ result["info"] = (
2454
+ "Safe to update. Data is stored in user data directory and will survive package updates."
2455
+ )
2456
+ result["recommended_action"] = "get_update_command"
2457
+
2458
+ return json.dumps(result, indent=2)
2459
+
2460
+ elif action == "backup":
2461
+ # Create backup to safe location
2462
+ backup_dir = args.get("backup_path")
2463
+
2464
+ if not backup_dir:
2465
+ # Default to user's Documents folder
2466
+ if platform.system() == "Windows":
2467
+ backup_dir = os.path.join(os.environ.get("USERPROFILE", ""), "Documents", "pomera-backup")
2468
+ else:
2469
+ backup_dir = os.path.join(os.path.expanduser("~"), "Documents", "pomera-backup")
2470
+
2471
+ backup_path = Path(backup_dir)
2472
+ backup_path.mkdir(parents=True, exist_ok=True)
2473
+
2474
+ import shutil
2475
+ from datetime import datetime
2476
+
2477
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
2478
+ backed_up = []
2479
+
2480
+ for db in databases_found:
2481
+ src = Path(db["path"])
2482
+ dst = backup_path / f"{src.stem}_{timestamp}{src.suffix}"
2483
+ try:
2484
+ shutil.copy2(src, dst)
2485
+ backed_up.append({"name": db["name"], "backup_path": str(dst)})
2486
+ except Exception as e:
2487
+ backed_up.append({"name": db["name"], "error": str(e)})
2488
+
2489
+ result = {
2490
+ "backup_location": str(backup_path),
2491
+ "files_backed_up": backed_up,
2492
+ "success": all("error" not in b for b in backed_up),
2493
+ "next_step": "You can now safely update Pomera. Use action='get_update_command' for the command."
2494
+ }
2495
+
2496
+ return json.dumps(result, indent=2)
2497
+
2498
+ elif action == "get_update_command":
2499
+ # Return appropriate update command
2500
+ result = {
2501
+ "npm_update": "npm update pomera-ai-commander",
2502
+ "pip_update": "pip install --upgrade pomera-ai-commander",
2503
+ "github_releases": "https://github.com/matbanik/Pomera-AI-Commander/releases",
2504
+ "note": "After updating, run the application to trigger automatic data migration."
2505
+ }
2506
+
2507
+ if portable and databases_found:
2508
+ result["warning"] = (
2509
+ "Data in installation directory detected! "
2510
+ "Ensure you have backed up (action='backup') before running update."
2511
+ )
2512
+
2513
+ return json.dumps(result, indent=2)
2514
+
2515
+ else:
2516
+ return json.dumps({"error": f"Unknown action: {action}"})
2517
+
2518
+ def _register_find_replace_diff_tool(self) -> None:
2519
+ """Register the Find & Replace Diff Tool."""
2520
+ self.register(MCPToolAdapter(
2521
+ name="pomera_find_replace_diff",
2522
+ description="Regex find/replace with diff preview and automatic backup to Notes. "
2523
+ "Designed for AI agent workflows requiring verification and rollback capability. "
2524
+ "Operations: validate (check regex), preview (show diff), execute (replace+backup), recall (retrieve previous).",
2525
+ input_schema={
2526
+ "type": "object",
2527
+ "properties": {
2528
+ "operation": {
2529
+ "type": "string",
2530
+ "enum": ["validate", "preview", "execute", "recall"],
2531
+ "description": "validate=check regex syntax, preview=show compact diff, execute=replace+backup to Notes, recall=retrieve by note_id"
2532
+ },
2533
+ "text": {
2534
+ "type": "string",
2535
+ "description": "Input text to process (for validate/preview/execute)"
2536
+ },
2537
+ "find_pattern": {
2538
+ "type": "string",
2539
+ "description": "Regex pattern to find"
2540
+ },
2541
+ "replace_pattern": {
2542
+ "type": "string",
2543
+ "description": "Replacement string (supports backreferences \\1, \\2, etc.)",
2544
+ "default": ""
2545
+ },
2546
+ "flags": {
2547
+ "type": "array",
2548
+ "items": {"type": "string", "enum": ["i", "m", "s", "x"]},
2549
+ "default": [],
2550
+ "description": "Regex flags: i=ignore case, m=multiline, s=dotall, x=verbose"
2551
+ },
2552
+ "context_lines": {
2553
+ "type": "integer",
2554
+ "default": 2,
2555
+ "minimum": 0,
2556
+ "maximum": 10,
2557
+ "description": "Lines of context in diff output (for preview)"
2558
+ },
2559
+ "save_to_notes": {
2560
+ "type": "boolean",
2561
+ "default": True,
2562
+ "description": "Save operation to Notes for rollback (for execute)"
2563
+ },
2564
+ "note_id": {
2565
+ "type": "integer",
2566
+ "description": "Note ID to recall (for recall operation)"
2567
+ }
2568
+ },
2569
+ "required": ["operation"]
2570
+ },
2571
+ handler=self._handle_find_replace_diff
2572
+ ))
2573
+
2574
+ def _handle_find_replace_diff(self, args: Dict[str, Any]) -> str:
2575
+ """Handle find/replace diff tool execution."""
2576
+ import json
2577
+ from core.mcp.find_replace_diff import validate_regex, preview_replace, execute_replace, recall_operation
2578
+
2579
+ operation = args.get("operation", "")
2580
+
2581
+ if operation == "validate":
2582
+ pattern = args.get("find_pattern", "")
2583
+ flags = args.get("flags", [])
2584
+ result = validate_regex(pattern, flags)
2585
+ return json.dumps(result, ensure_ascii=False)
2586
+
2587
+ elif operation == "preview":
2588
+ text = args.get("text", "")
2589
+ find_pattern = args.get("find_pattern", "")
2590
+ replace_pattern = args.get("replace_pattern", "")
2591
+ flags = args.get("flags", [])
2592
+ context_lines = args.get("context_lines", 2)
2593
+
2594
+ if not text:
2595
+ return json.dumps({"success": False, "error": "text is required for preview"})
2596
+ if not find_pattern:
2597
+ return json.dumps({"success": False, "error": "find_pattern is required for preview"})
2598
+
2599
+ result = preview_replace(text, find_pattern, replace_pattern, flags, context_lines)
2600
+ return json.dumps(result, ensure_ascii=False)
2601
+
2602
+ elif operation == "execute":
2603
+ text = args.get("text", "")
2604
+ find_pattern = args.get("find_pattern", "")
2605
+ replace_pattern = args.get("replace_pattern", "")
2606
+ flags = args.get("flags", [])
2607
+ save_to_notes = args.get("save_to_notes", True)
2608
+
2609
+ if not text:
2610
+ return json.dumps({"success": False, "error": "text is required for execute"})
2611
+ if not find_pattern:
2612
+ return json.dumps({"success": False, "error": "find_pattern is required for execute"})
2613
+
2614
+ # Create notes handler if saving is requested
2615
+ notes_handler = None
2616
+ if save_to_notes:
2617
+ notes_handler = self._create_notes_handler()
2618
+
2619
+ result = execute_replace(text, find_pattern, replace_pattern, flags, save_to_notes, notes_handler)
2620
+ return json.dumps(result, ensure_ascii=False)
2621
+
2622
+ elif operation == "recall":
2623
+ note_id = args.get("note_id")
2624
+ if note_id is None:
2625
+ return json.dumps({"success": False, "error": "note_id is required for recall"})
2626
+
2627
+ notes_getter = self._create_notes_getter()
2628
+ result = recall_operation(note_id, notes_getter)
2629
+ return json.dumps(result, ensure_ascii=False)
2630
+
2631
+ else:
2632
+ return json.dumps({"success": False, "error": f"Unknown operation: {operation}"})
2633
+
2634
+ def _create_notes_handler(self):
2635
+ """Create a handler function for saving to notes."""
2636
+ registry = self # Capture reference
2637
+
2638
+ def save_to_notes(title: str, input_content: str, output_content: str) -> int:
2639
+ """Save operation to notes and return note_id."""
2640
+ try:
2641
+ from datetime import datetime
2642
+ conn = registry._get_notes_connection()
2643
+ now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
2644
+ cursor = conn.execute('''
2645
+ INSERT INTO notes (Created, Modified, Title, Input, Output)
2646
+ VALUES (?, ?, ?, ?, ?)
2647
+ ''', (now, now, title, input_content, output_content))
2648
+ note_id = cursor.lastrowid
2649
+ conn.commit()
2650
+ conn.close()
2651
+ return note_id
2652
+ except Exception as e:
2653
+ registry._logger.warning(f"Failed to save to notes: {e}")
2654
+ return -1
2655
+ return save_to_notes
2656
+
2657
+ def _create_notes_getter(self):
2658
+ """Create a getter function for retrieving notes."""
2659
+ registry = self # Capture reference
2660
+
2661
+ def get_note(note_id: int) -> Dict[str, Any]:
2662
+ """Get note by ID."""
2663
+ try:
2664
+ conn = registry._get_notes_connection()
2665
+ row = conn.execute('SELECT * FROM notes WHERE id = ?', (note_id,)).fetchone()
2666
+ conn.close()
2667
+ if row:
2668
+ return {
2669
+ 'id': row[0],
2670
+ 'created': row[1],
2671
+ 'modified': row[2],
2672
+ 'title': row[3],
2673
+ 'input_content': row[4],
2674
+ 'output_content': row[5]
2675
+ }
2676
+ return None
2677
+ except Exception as e:
2678
+ registry._logger.warning(f"Failed to get note: {e}")
2679
+ return None
2680
+ return get_note
2355
2681
 
2356
2682
 
2357
2683
  # Singleton instance for convenience
2684
+
2358
2685
  _default_registry: Optional[ToolRegistry] = None
2359
2686
 
2360
2687
 
@@ -0,0 +1,275 @@
1
+ """
2
+ Memento pattern implementation for Find & Replace undo/redo functionality.
3
+
4
+ This module provides a robust undo/redo system that preserves:
5
+ - Full text content before/after operations
6
+ - Cursor position and selection
7
+ - Scroll position
8
+ - Operation metadata (find/replace patterns, timestamp)
9
+ """
10
+
11
+ from dataclasses import dataclass, field
12
+ from typing import Optional, List, Tuple
13
+ from datetime import datetime
14
+ import time
15
+
16
+
17
+ @dataclass
18
+ class TextState:
19
+ """Stores the state of a text widget for restoration."""
20
+ content: str
21
+ cursor_position: str = "1.0" # Tk index format
22
+ selection_start: Optional[str] = None
23
+ selection_end: Optional[str] = None
24
+ scroll_position: Tuple[float, float] = (0.0, 0.0) # (yview start, yview end)
25
+
26
+ def has_selection(self) -> bool:
27
+ """Check if there's a text selection."""
28
+ return self.selection_start is not None and self.selection_end is not None
29
+
30
+
31
+ @dataclass
32
+ class FindReplaceMemento:
33
+ """
34
+ Memento class storing the complete state of a Find & Replace operation.
35
+
36
+ Implements the Memento design pattern for undo/redo functionality.
37
+ """
38
+ # Before/after states
39
+ before_state: TextState
40
+ after_state: Optional[TextState] = None
41
+
42
+ # Operation details
43
+ find_pattern: str = ""
44
+ replace_pattern: str = ""
45
+ is_regex: bool = False
46
+ match_case: bool = False
47
+
48
+ # Match statistics
49
+ match_count: int = 0
50
+ replaced_count: int = 0
51
+
52
+ # Metadata
53
+ timestamp: float = field(default_factory=time.time)
54
+ description: str = ""
55
+
56
+ def get_timestamp_str(self) -> str:
57
+ """Get human-readable timestamp."""
58
+ return datetime.fromtimestamp(self.timestamp).strftime("%H:%M:%S")
59
+
60
+ def get_summary(self) -> str:
61
+ """Get a short summary of the operation."""
62
+ if self.description:
63
+ return self.description
64
+ return f"Replace '{self.find_pattern[:20]}...' → '{self.replace_pattern[:20]}...' ({self.replaced_count} changes)"
65
+
66
+
67
+ class MementoCaretaker:
68
+ """
69
+ Caretaker class that manages the undo/redo stacks.
70
+
71
+ Implements the Caretaker role in the Memento pattern.
72
+ """
73
+
74
+ def __init__(self, max_history: int = 50):
75
+ """
76
+ Initialize the caretaker.
77
+
78
+ Args:
79
+ max_history: Maximum number of operations to keep in history
80
+ """
81
+ self.max_history = max_history
82
+ self._undo_stack: List[FindReplaceMemento] = []
83
+ self._redo_stack: List[FindReplaceMemento] = []
84
+ self._change_callbacks: List[callable] = []
85
+
86
+ def add_change_callback(self, callback: callable):
87
+ """Add a callback to be notified when stacks change."""
88
+ self._change_callbacks.append(callback)
89
+
90
+ def _notify_change(self):
91
+ """Notify all callbacks of stack changes."""
92
+ for callback in self._change_callbacks:
93
+ try:
94
+ callback(self.can_undo(), self.can_redo())
95
+ except Exception:
96
+ pass # Don't let callback errors break functionality
97
+
98
+ def save(self, memento: FindReplaceMemento) -> None:
99
+ """
100
+ Save a new memento to the undo stack.
101
+
102
+ This clears the redo stack as new changes invalidate future states.
103
+
104
+ Args:
105
+ memento: The memento to save
106
+ """
107
+ self._undo_stack.append(memento)
108
+ self._redo_stack.clear() # New action invalidates redo history
109
+
110
+ # Limit stack size
111
+ if len(self._undo_stack) > self.max_history:
112
+ self._undo_stack.pop(0)
113
+
114
+ self._notify_change()
115
+
116
+ def undo(self) -> Optional[FindReplaceMemento]:
117
+ """
118
+ Pop and return the last memento from undo stack.
119
+
120
+ The memento is moved to the redo stack.
121
+
122
+ Returns:
123
+ The memento to restore, or None if stack is empty
124
+ """
125
+ if not self._undo_stack:
126
+ return None
127
+
128
+ memento = self._undo_stack.pop()
129
+ self._redo_stack.append(memento)
130
+ self._notify_change()
131
+ return memento
132
+
133
+ def redo(self) -> Optional[FindReplaceMemento]:
134
+ """
135
+ Pop and return the last memento from redo stack.
136
+
137
+ The memento is moved back to the undo stack.
138
+
139
+ Returns:
140
+ The memento to re-apply, or None if stack is empty
141
+ """
142
+ if not self._redo_stack:
143
+ return None
144
+
145
+ memento = self._redo_stack.pop()
146
+ self._undo_stack.append(memento)
147
+ self._notify_change()
148
+ return memento
149
+
150
+ def can_undo(self) -> bool:
151
+ """Check if undo is available."""
152
+ return len(self._undo_stack) > 0
153
+
154
+ def can_redo(self) -> bool:
155
+ """Check if redo is available."""
156
+ return len(self._redo_stack) > 0
157
+
158
+ def get_undo_count(self) -> int:
159
+ """Get the number of undo operations available."""
160
+ return len(self._undo_stack)
161
+
162
+ def get_redo_count(self) -> int:
163
+ """Get the number of redo operations available."""
164
+ return len(self._redo_stack)
165
+
166
+ def get_undo_history(self) -> List[str]:
167
+ """Get summaries of all undo operations (most recent first)."""
168
+ return [m.get_summary() for m in reversed(self._undo_stack)]
169
+
170
+ def get_redo_history(self) -> List[str]:
171
+ """Get summaries of all redo operations (most recent first)."""
172
+ return [m.get_summary() for m in reversed(self._redo_stack)]
173
+
174
+ def clear(self) -> None:
175
+ """Clear all undo/redo history."""
176
+ self._undo_stack.clear()
177
+ self._redo_stack.clear()
178
+ self._notify_change()
179
+
180
+ def peek_undo(self) -> Optional[FindReplaceMemento]:
181
+ """Peek at the next undo operation without removing it."""
182
+ return self._undo_stack[-1] if self._undo_stack else None
183
+
184
+ def peek_redo(self) -> Optional[FindReplaceMemento]:
185
+ """Peek at the next redo operation without removing it."""
186
+ return self._redo_stack[-1] if self._redo_stack else None
187
+
188
+
189
+ def capture_text_state(text_widget) -> TextState:
190
+ """
191
+ Capture the current state of a Tk Text widget.
192
+
193
+ Args:
194
+ text_widget: A tkinter Text widget
195
+
196
+ Returns:
197
+ TextState containing the current state
198
+ """
199
+ try:
200
+ content = text_widget.get("1.0", "end-1c")
201
+ cursor_position = text_widget.index("insert")
202
+
203
+ # Capture selection if any
204
+ try:
205
+ selection_start = text_widget.index("sel.first")
206
+ selection_end = text_widget.index("sel.last")
207
+ except Exception:
208
+ selection_start = None
209
+ selection_end = None
210
+
211
+ # Capture scroll position
212
+ try:
213
+ scroll_position = text_widget.yview()
214
+ except Exception:
215
+ scroll_position = (0.0, 0.0)
216
+
217
+ return TextState(
218
+ content=content,
219
+ cursor_position=cursor_position,
220
+ selection_start=selection_start,
221
+ selection_end=selection_end,
222
+ scroll_position=scroll_position
223
+ )
224
+ except Exception:
225
+ # Fallback for edge cases
226
+ return TextState(content="", cursor_position="1.0")
227
+
228
+
229
+ def restore_text_state(text_widget, state: TextState, restore_scroll: bool = True) -> bool:
230
+ """
231
+ Restore a text widget to a saved state.
232
+
233
+ Args:
234
+ text_widget: A tkinter Text widget
235
+ state: The TextState to restore
236
+ restore_scroll: Whether to restore scroll position
237
+
238
+ Returns:
239
+ True if restoration was successful
240
+ """
241
+ try:
242
+ # Temporarily enable widget if disabled
243
+ original_state = text_widget.cget("state")
244
+ text_widget.config(state="normal")
245
+
246
+ # Restore content
247
+ text_widget.delete("1.0", "end")
248
+ text_widget.insert("1.0", state.content)
249
+
250
+ # Restore cursor position
251
+ try:
252
+ text_widget.mark_set("insert", state.cursor_position)
253
+ except Exception:
254
+ pass
255
+
256
+ # Restore selection
257
+ if state.has_selection():
258
+ try:
259
+ text_widget.tag_add("sel", state.selection_start, state.selection_end)
260
+ except Exception:
261
+ pass
262
+
263
+ # Restore scroll position
264
+ if restore_scroll and state.scroll_position:
265
+ try:
266
+ text_widget.yview_moveto(state.scroll_position[0])
267
+ except Exception:
268
+ pass
269
+
270
+ # Restore original state
271
+ text_widget.config(state=original_state)
272
+
273
+ return True
274
+ except Exception:
275
+ return False
package/mcp.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pomera-ai-commander",
3
- "version": "1.2.1",
3
+ "version": "1.2.2",
4
4
  "description": "Text processing toolkit with 22 MCP tools including case transformation, encoding, hashing, text analysis, and notes management for AI assistants.",
5
5
  "homepage": "https://github.com/matbanik/Pomera-AI-Commander",
6
6
  "repository": "https://github.com/matbanik/Pomera-AI-Commander",