invar-tools 1.14.0__py3-none-any.whl → 1.15.1__py3-none-any.whl

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.
@@ -23,6 +23,7 @@ from invar.shell.mcp_config import (
23
23
  get_recommended_method,
24
24
  )
25
25
  from invar.shell.pi_hooks import install_pi_hooks
26
+ from invar.shell.pi_tools import install_pi_tools
26
27
  from invar.shell.templates import (
27
28
  add_config,
28
29
  create_directories,
@@ -60,6 +61,7 @@ FILE_CATEGORIES: dict[str, list[tuple[str, str]]] = {
60
61
  ("CLAUDE.md", "Agent instructions (Pi compatible)"),
61
62
  (".claude/skills/", "Workflow automation (Pi compatible)"),
62
63
  (".pi/hooks/", "Pi-specific hooks"),
64
+ (".pi/tools/", "Pi custom tools (invar_guard, invar_sig, invar_map)"),
63
65
  ],
64
66
  }
65
67
 
@@ -153,29 +155,43 @@ def _get_prompt_style():
153
155
 
154
156
  # @shell_complexity: Interactive prompt with cursor selection
155
157
  def _prompt_agent_selection() -> list[str]:
156
- """Prompt user to select code agent using cursor navigation."""
158
+ """Prompt user to select agent(s) using checkbox (DX-81: multi-agent support)."""
157
159
  import questionary
158
160
 
159
- console.print("\n[bold]Select code agent:[/bold]")
160
- console.print("[dim]Use arrow keys to move, enter to select[/dim]\n")
161
+ console.print("\n[bold]Select agent(s) to configure:[/bold]")
162
+ console.print("[dim]Space to toggle, Enter to confirm (can select multiple)[/dim]\n")
161
163
 
162
164
  choices = [
163
- questionary.Choice("Claude Code (recommended)", value="claude"),
164
- questionary.Choice("Pi Coding Agent", value="pi"),
165
- questionary.Choice("Other (AGENT.md)", value="generic"),
165
+ questionary.Choice(
166
+ "Claude Code (recommended)",
167
+ value="claude",
168
+ checked=True # Default selection
169
+ ),
170
+ questionary.Choice(
171
+ "Pi Coding Agent",
172
+ value="pi",
173
+ checked=False
174
+ ),
175
+ questionary.Choice(
176
+ "Other (AGENT.md)",
177
+ value="generic",
178
+ checked=False
179
+ ),
166
180
  ]
167
181
 
168
- selected = questionary.select(
182
+ selected = questionary.checkbox(
169
183
  "",
170
184
  choices=choices,
171
185
  instruction="",
172
186
  style=_get_prompt_style(),
173
187
  ).ask()
174
188
 
175
- # Handle Ctrl+C
189
+ # Handle Ctrl+C or empty selection
176
190
  if not selected:
177
- return ["claude"] # Default to Claude Code
178
- return [selected]
191
+ console.print("[yellow]No agents selected, using Claude Code as default.[/yellow]")
192
+ return ["claude"]
193
+
194
+ return selected
179
195
 
180
196
 
181
197
  # @shell_complexity: Interactive file selection with cursor navigation
@@ -205,9 +221,10 @@ def _prompt_file_selection(agents: list[str]) -> dict[str, bool]:
205
221
  console.print()
206
222
  console.print("[dim]Use arrow keys to move, space to toggle, enter to confirm[/dim]\n")
207
223
 
208
- # Build choices with categories as separators
224
+ # Build choices with categories as separators (DX-81: deduplicate shared files)
209
225
  choices: list[questionary.Choice | questionary.Separator] = []
210
226
  file_list: list[str] = []
227
+ seen_files: set[str] = set()
211
228
 
212
229
  for category, files in available.items():
213
230
  if category == "required":
@@ -217,12 +234,19 @@ def _prompt_file_selection(agents: list[str]) -> dict[str, bool]:
217
234
  category_name = "Claude Code"
218
235
  elif category == "pi":
219
236
  category_name = "Pi Coding Agent"
220
- choices.append(questionary.Separator(f"── {category_name} ──"))
221
- for file, desc in files:
222
- choices.append(
223
- questionary.Choice(f"{file:28} {desc}", value=file, checked=True)
224
- )
225
- file_list.append(file)
237
+
238
+ # Filter out files already seen (shared between categories)
239
+ unique_files = [(f, d) for f, d in files if f not in seen_files]
240
+
241
+ # Only add separator if there are unique files to show
242
+ if unique_files:
243
+ choices.append(questionary.Separator(f"── {category_name} ──"))
244
+ for file, desc in unique_files:
245
+ choices.append(
246
+ questionary.Choice(f"{file:28} {desc}", value=file, checked=True)
247
+ )
248
+ file_list.append(file)
249
+ seen_files.add(file)
226
250
 
227
251
  selected = questionary.checkbox(
228
252
  "Select files to install:",
@@ -390,10 +414,7 @@ def init(
390
414
  """
391
415
  from invar import __version__
392
416
 
393
- # Mutual exclusivity check
394
- if claude and pi:
395
- console.print("[red]Error:[/red] Cannot use --claude and --pi together.")
396
- raise typer.Exit(1)
417
+ # DX-81: Multi-agent support - removed mutual exclusivity check
397
418
 
398
419
  if mcp_only and (claude or pi):
399
420
  console.print("[red]Error:[/red] --mcp-only cannot be combined with --claude or --pi.")
@@ -458,8 +479,10 @@ def init(
458
479
  console.print(f"[red]Error:[/red] Invalid language '{language}'. Must be one of: {valid}")
459
480
  raise typer.Exit(1)
460
481
 
461
- # Header
462
- if claude:
482
+ # Header (DX-81: Support multi-agent display)
483
+ if claude and pi:
484
+ console.print(f"\n[bold]Invar v{__version__} - Quick Setup (Claude Code + Pi)[/bold]")
485
+ elif claude:
463
486
  console.print(f"\n[bold]Invar v{__version__} - Quick Setup (Claude Code)[/bold]")
464
487
  elif pi:
465
488
  console.print(f"\n[bold]Invar v{__version__} - Quick Setup (Pi)[/bold]")
@@ -468,27 +491,30 @@ def init(
468
491
  console.print("=" * 45)
469
492
  console.print(f"[dim]Language: {language} | Existing files will be MERGED.[/dim]")
470
493
 
471
- # Determine agents and files
472
- if claude:
473
- # Quick mode: Claude Code defaults
474
- agents = ["claude"]
494
+ # DX-81: Determine agents and files (multi-agent support)
495
+ if claude or pi:
496
+ # Quick mode: Build agent list from flags
497
+ agents = []
498
+ if claude:
499
+ agents.append("claude")
500
+ if pi:
501
+ agents.append("pi")
502
+
503
+ # Build selected_files from all agents' categories
475
504
  selected_files: dict[str, bool] = {}
476
- for category in ["optional", "claude"]:
477
- for file, _ in FILE_CATEGORIES.get(category, []):
478
- selected_files[file] = True
479
- # DX-79: Default feedback enabled for quick mode
480
- feedback_enabled = True
481
- console.print("\n[dim]📊 Feedback collection enabled by default (stored locally in .invar/feedback/)[/dim]")
482
- console.print("[dim] To disable: Set feedback.enabled=false in .claude/settings.local.json[/dim]")
483
- elif pi:
484
- # Quick mode: Pi defaults
485
- agents = ["pi"]
486
- selected_files = {}
487
- for category in ["optional", "pi"]:
505
+ for agent in agents:
506
+ category = AGENT_CONFIGS[agent]["category"]
488
507
  for file, _ in FILE_CATEGORIES.get(category, []):
489
508
  selected_files[file] = True
509
+
510
+ # Add optional files
511
+ for file, _ in FILE_CATEGORIES["optional"]:
512
+ selected_files[file] = True
513
+
490
514
  # DX-79: Default feedback enabled for quick mode
491
515
  feedback_enabled = True
516
+ if len(agents) > 1:
517
+ console.print(f"\n[dim]📊 Configuring for {len(agents)} agents: {', '.join(agents)}[/dim]")
492
518
  console.print("\n[dim]📊 Feedback collection enabled by default (stored locally in .invar/feedback/)[/dim]")
493
519
  console.print("[dim] To disable: Set feedback.enabled=false in .claude/settings.local.json[/dim]")
494
520
  else:
@@ -598,6 +624,10 @@ def init(
598
624
  if "pi" in agents and selected_files.get(".pi/hooks/", True):
599
625
  install_pi_hooks(path, console)
600
626
 
627
+ # Install Pi custom tools if selected
628
+ if "pi" in agents and selected_files.get(".pi/tools/", True):
629
+ install_pi_tools(path, console)
630
+
601
631
  # Add feedback configuration (DX-79 Phase C)
602
632
  if "claude" in agents or "pi" in agents:
603
633
  feedback_result = add_feedback_config(path, feedback_enabled, console)
@@ -622,7 +652,7 @@ def init(
622
652
  # Completion message
623
653
  console.print(f"\n[bold green]✓ Initialized Invar v{__version__}[/bold green]")
624
654
 
625
- # Show agent-specific tips
655
+ # Show agent-specific tips (DX-81: show all relevant tips)
626
656
  if "claude" in agents:
627
657
  console.print()
628
658
  console.print(
@@ -633,7 +663,7 @@ def init(
633
663
  border_style="dim",
634
664
  )
635
665
  )
636
- elif "pi" in agents:
666
+ if "pi" in agents:
637
667
  console.print()
638
668
  console.print(
639
669
  Panel(
@@ -0,0 +1,127 @@
1
+ """
2
+ Pi Coding Agent custom tools for Invar.
3
+
4
+ Provides Invar CLI commands as Pi custom tools for better LLM integration.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import shutil
10
+ from pathlib import Path
11
+ from typing import TYPE_CHECKING
12
+
13
+ from returns.result import Failure, Result, Success
14
+
15
+ if TYPE_CHECKING:
16
+ from rich.console import Console
17
+
18
+ # Pi tools directory
19
+ PI_TOOLS_DIR = ".pi/tools/invar"
20
+
21
+
22
+ def get_pi_tools_template_path() -> Path:
23
+ """Get the path to Pi tools template."""
24
+ return Path(__file__).parent.parent / "templates" / "pi-tools" / "invar"
25
+
26
+
27
+ def install_pi_tools(
28
+ project_path: Path,
29
+ console: Console,
30
+ ) -> Result[list[str], str]:
31
+ """
32
+ Install Pi custom tools for Invar.
33
+
34
+ Creates .pi/tools/invar/index.ts with:
35
+ - invar_guard: Wrapper for invar guard command
36
+ - invar_sig: Wrapper for invar sig command
37
+ - invar_map: Wrapper for invar map command
38
+ - invar_doc_toc: Extract document structure
39
+ - invar_doc_read: Read specific section
40
+ - invar_doc_find: Find sections by pattern
41
+ - invar_doc_replace: Replace section content
42
+ - invar_doc_insert: Insert content relative to section
43
+ - invar_doc_delete: Delete section
44
+ """
45
+ tools_dir = project_path / PI_TOOLS_DIR
46
+ tools_dir.mkdir(parents=True, exist_ok=True)
47
+
48
+ console.print("\n[bold]Installing Pi custom tools...[/bold]")
49
+ console.print(" Tools provide:")
50
+ console.print(" ✓ invar_guard - Smart verification (static + doctests + symbolic)")
51
+ console.print(" ✓ invar_sig - Show function signatures and contracts")
52
+ console.print(" ✓ invar_map - Symbol map with reference counts")
53
+ console.print(" ✓ 6 doc tools - Structured markdown editing (toc, read, find, replace, insert, delete)")
54
+ console.print("")
55
+
56
+ template_path = get_pi_tools_template_path()
57
+ tool_file = template_path / "index.ts"
58
+
59
+ if not tool_file.exists():
60
+ return Failure(f"Template not found: {tool_file}")
61
+
62
+ try:
63
+ # Copy the template file
64
+ dest_file = tools_dir / "index.ts"
65
+ shutil.copy2(tool_file, dest_file)
66
+
67
+ console.print(f" [green]Created[/green] {PI_TOOLS_DIR}/index.ts")
68
+ console.print("\n [bold green]✓ Pi custom tools installed[/bold green]")
69
+ console.print(" [dim]Pi will auto-discover tools in .pi/tools/[/dim]")
70
+ console.print(" [yellow]⚠ Restart Pi session for tools to take effect[/yellow]")
71
+
72
+ return Success(["index.ts"])
73
+ except Exception as e:
74
+ return Failure(f"Failed to install Pi tools: {e}")
75
+
76
+
77
+ def remove_pi_tools(
78
+ project_path: Path,
79
+ console: Console,
80
+ ) -> Result[None, str]:
81
+ """Remove Pi custom tools."""
82
+ tools_dir = project_path / PI_TOOLS_DIR
83
+ tool_file = tools_dir / "index.ts"
84
+
85
+ if tool_file.exists():
86
+ tool_file.unlink()
87
+ console.print(f" [red]Removed[/red] {PI_TOOLS_DIR}/index.ts")
88
+
89
+ # Remove directory if empty
90
+ try:
91
+ tools_dir.rmdir()
92
+ console.print(f" [red]Removed[/red] {PI_TOOLS_DIR}/")
93
+ except OSError:
94
+ pass # Directory not empty, keep it
95
+
96
+ console.print("[bold green]✓ Pi custom tools removed[/bold green]")
97
+ else:
98
+ console.print("[dim]No Pi custom tools installed[/dim]")
99
+
100
+ return Success(None)
101
+
102
+
103
+ def pi_tools_status(
104
+ project_path: Path,
105
+ console: Console,
106
+ ) -> Result[dict[str, str], str]:
107
+ """Check status of Pi custom tools."""
108
+ tools_dir = project_path / PI_TOOLS_DIR
109
+ tool_file = tools_dir / "index.ts"
110
+
111
+ status: dict[str, str] = {}
112
+
113
+ if not tool_file.exists():
114
+ console.print("[dim]No Pi custom tools installed[/dim]")
115
+ return Success({"status": "not_installed"})
116
+
117
+ status["status"] = "installed"
118
+
119
+ # Try to check file size (basic validation)
120
+ try:
121
+ size = tool_file.stat().st_size
122
+ status["size"] = f"{size} bytes"
123
+ console.print(f"[green]✓ Pi custom tools installed[/green] ({size} bytes)")
124
+ except OSError:
125
+ console.print("[green]✓ Pi custom tools installed[/green]")
126
+
127
+ return Success(status)
@@ -2,6 +2,7 @@
2
2
  # Invar UserPromptSubmit Hook
3
3
  # Protocol: v{{ protocol_version }} | Generated: {{ generated_date }}
4
4
  # DX-57: Protocol refresh with full INVAR.md injection
5
+ # DX-79: Automatic feedback trigger via message count
5
6
 
6
7
  USER_MESSAGE="$1"
7
8
 
@@ -82,3 +83,33 @@ if [[ $COUNT -ge 25 && $((COUNT % 10)) -eq 0 ]]; then
82
83
  INVAR_EOF
83
84
  echo "</system-reminder>"
84
85
  fi
86
+
87
+ # ============================================
88
+ # DX-79: Feedback trigger at threshold
89
+ # ============================================
90
+
91
+ # Read feedback configuration
92
+ FEEDBACK_ENABLED=true
93
+ MIN_MESSAGES=30
94
+
95
+ if [[ -f ".claude/settings.local.json" ]]; then
96
+ # Try to parse with jq if available, otherwise use defaults
97
+ if command -v jq &> /dev/null; then
98
+ FEEDBACK_ENABLED=$(jq -r '.feedback.enabled // true' .claude/settings.local.json 2>/dev/null)
99
+ MIN_MESSAGES=$(jq -r '.feedback.min_messages // 30' .claude/settings.local.json 2>/dev/null)
100
+ fi
101
+ fi
102
+
103
+ # Trigger feedback prompt at threshold
104
+ if [[ "$FEEDBACK_ENABLED" == "true" && $COUNT -eq $MIN_MESSAGES ]]; then
105
+ echo "<system-reminder>"
106
+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
107
+ echo "📊 Invar: Auto-triggering usage feedback ($COUNT messages)"
108
+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
109
+ echo ""
110
+ echo "Session has reached $COUNT messages. Consider running /invar-reflect"
111
+ echo "to generate usage feedback."
112
+ echo ""
113
+ echo "To disable: Set feedback.enabled=false in .claude/settings.local.json"
114
+ echo "</system-reminder>"
115
+ fi
@@ -2,13 +2,16 @@
2
2
  * Invar Pi Hook
3
3
  * Protocol: v{{ protocol_version }} | Generated: {{ generated_date }}
4
4
  * LX-04: Full feature parity with Claude Code hooks
5
+ * DX-79: Automatic feedback trigger via message count
5
6
  *
6
7
  * Features:
7
8
  * - pytest/crosshair blocking via tool_call
8
9
  * - Protocol injection via pi.send() for long conversations
10
+ * - Automatic /invar-reflect trigger at message threshold
9
11
  */
10
12
 
11
13
  import type { HookAPI } from "@mariozechner/pi-coding-agent/hooks";
14
+ import * as fs from "fs";
12
15
 
13
16
  // Blocked commands (same as Claude Code)
14
17
  {% if language == "python" -%}
@@ -22,6 +25,21 @@ const ALLOWED_FLAGS = [/--inspect/, /--coverage/, /--debug/];
22
25
  // Protocol content for injection (escaped for JS)
23
26
  const INVAR_PROTOCOL = `{{ invar_protocol_escaped }}`;
24
27
 
28
+ // DX-79: Helper to read feedback configuration
29
+ function readFeedbackConfig() {
30
+ try {
31
+ const settingsPath = ".claude/settings.local.json";
32
+ const settings = JSON.parse(fs.readFileSync(settingsPath, "utf-8"));
33
+ return {
34
+ enabled: settings.feedback?.enabled ?? true,
35
+ min_messages: settings.feedback?.min_messages ?? 30,
36
+ };
37
+ } catch {
38
+ // File doesn't exist or other error, use defaults
39
+ }
40
+ return { enabled: true, min_messages: 30 };
41
+ }
42
+
25
43
  export default function (pi: HookAPI) {
26
44
  let msgCount = 0;
27
45
 
@@ -53,6 +71,21 @@ export default function (pi: HookAPI) {
53
71
  pi.send(`<system-reminder>
54
72
  === Protocol Refresh (message ${msgCount}) ===
55
73
  ${INVAR_PROTOCOL}
74
+ </system-reminder>`);
75
+ }
76
+
77
+ // DX-79: Feedback trigger at threshold
78
+ const feedbackConfig = readFeedbackConfig();
79
+ if (msgCount === feedbackConfig.min_messages && feedbackConfig.enabled) {
80
+ pi.send(`<system-reminder>
81
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
82
+ 📊 Invar: Auto-triggering usage feedback (${msgCount} messages)
83
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
84
+
85
+ Session has reached ${msgCount} messages. Consider running /invar-reflect
86
+ to generate usage feedback.
87
+
88
+ To disable: Set feedback.enabled=false in .claude/settings.local.json
56
89
  </system-reminder>`);
57
90
  }
58
91
  });
@@ -62,7 +95,8 @@ ${INVAR_PROTOCOL}
62
95
  // ============================================
63
96
  pi.on("tool_call", async (event) => {
64
97
  if (event.toolName !== "bash") return;
65
- const cmd = ((event.input as Record<string, unknown>).command as string || "").trim();
98
+ const input = event.input as Record<string, unknown>;
99
+ const cmd = (typeof input?.command === "string" ? input.command : "").trim();
66
100
 
67
101
  // Skip if not a blocked command
68
102
  if (!BLOCKED_CMDS.some((p) => p.test(cmd))) return;