-
Notifications
You must be signed in to change notification settings - Fork 5
feat(core): workspace lifecycle hooks system #438
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,208 @@ | ||
| """CLI workspace lifecycle hooks management. | ||
|
|
||
| Usage: | ||
| codeframe hooks show # Display configured hooks | ||
| codeframe hooks run <hook_name> # Manually trigger a hook | ||
| codeframe hooks set <name> <cmd> # Set a hook command | ||
| codeframe hooks clear <name> # Remove a hook | ||
| """ | ||
|
|
||
| from pathlib import Path | ||
| from typing import Optional | ||
|
|
||
| import typer | ||
| from rich.console import Console | ||
| from rich.table import Table | ||
|
|
||
| console = Console() | ||
|
|
||
| hooks_app = typer.Typer( | ||
| name="hooks", | ||
| help="Workspace lifecycle hooks management", | ||
| no_args_is_help=True, | ||
| ) | ||
|
|
||
| VALID_HOOK_NAMES = [ | ||
| "after_init", | ||
| "before_task", | ||
| "after_task_success", | ||
| "after_task_failure", | ||
| "before_remove", | ||
| ] | ||
|
|
||
|
|
||
| @hooks_app.command("show") | ||
| def hooks_show( | ||
| workspace_path: Optional[Path] = typer.Option( | ||
| None, "--workspace", "-w", | ||
| help="Workspace path (defaults to current directory)", | ||
| ), | ||
| ) -> None: | ||
| """Display configured hooks from .codeframe/config.yaml.""" | ||
| from codeframe.core.config import load_environment_config | ||
|
|
||
| from codeframe.core.workspace import get_workspace | ||
| path = workspace_path or Path.cwd() | ||
| try: | ||
| ws = get_workspace(path) | ||
| path = ws.repo_path | ||
| except (FileNotFoundError, ValueError): | ||
| pass # Workspace not initialized; fall back to raw path | ||
| config = load_environment_config(path) | ||
|
|
||
| if not config: | ||
| console.print("[yellow]No workspace configuration found.[/yellow]") | ||
| console.print("Run 'codeframe init .' first.") | ||
| raise typer.Exit(1) | ||
|
|
||
| table = Table(title="Workspace Hooks") | ||
| table.add_column("Hook Point", style="cyan") | ||
| table.add_column("Command", style="dim") | ||
| table.add_column("Status") | ||
|
|
||
| for hook_name in VALID_HOOK_NAMES: | ||
| command = getattr(config.hooks, hook_name, None) | ||
| if command: | ||
| table.add_row(hook_name, command, "[green]configured[/green]") | ||
| else: | ||
| table.add_row(hook_name, "-", "[dim]not set[/dim]") | ||
|
|
||
| table.add_row("", "", "") | ||
| table.add_row("hook_timeout", f"{config.hooks.hook_timeout}s", "[dim]default[/dim]") | ||
|
|
||
| console.print(table) | ||
|
|
||
|
|
||
| @hooks_app.command("run") | ||
| def hooks_run( | ||
| hook_name: str = typer.Argument(..., help="Hook name to execute"), | ||
| task_id: str = typer.Option("", "--task-id", help="Task ID for template rendering"), | ||
| task_title: str = typer.Option("", "--task-title", help="Task title for template rendering"), | ||
| workspace_path: Optional[Path] = typer.Option( | ||
| None, "--workspace", "-w", | ||
| help="Workspace path (defaults to current directory)", | ||
| ), | ||
| ) -> None: | ||
| """Manually trigger a named hook.""" | ||
| from codeframe.core.config import load_environment_config | ||
| from codeframe.core.hooks import HookContext, execute_hook | ||
|
|
||
| if hook_name not in VALID_HOOK_NAMES: | ||
| console.print(f"[red]Error:[/red] Invalid hook name '{hook_name}'") | ||
| console.print(f"Valid hooks: {', '.join(VALID_HOOK_NAMES)}") | ||
| raise typer.Exit(1) | ||
|
|
||
| from codeframe.core.workspace import get_workspace | ||
| path = workspace_path or Path.cwd() | ||
| try: | ||
| ws = get_workspace(path) | ||
| path = ws.repo_path | ||
| except (FileNotFoundError, ValueError): | ||
| pass # Workspace not initialized; fall back to raw path | ||
| config = load_environment_config(path) | ||
|
|
||
| if not config: | ||
| console.print("[yellow]No workspace configuration found.[/yellow]") | ||
| raise typer.Exit(1) | ||
|
|
||
| ctx = HookContext( | ||
| task_id=task_id, | ||
| task_title=task_title, | ||
| task_status="manual", | ||
| workspace_path=str(path), | ||
| ) | ||
|
|
||
| result = execute_hook(hook_name, config, path, ctx, abort_on_failure=False) | ||
|
|
||
| if result is None: | ||
| console.print(f"[yellow]Hook '{hook_name}' is not configured.[/yellow]") | ||
| return | ||
|
|
||
| if result.success: | ||
| console.print(f"[green]Hook '{hook_name}' succeeded[/green] ({result.duration_ms}ms)") | ||
| else: | ||
| console.print(f"[red]Hook '{hook_name}' failed[/red] ({result.duration_ms}ms)") | ||
| if result.timed_out: | ||
| console.print(" [yellow]Timed out[/yellow]") | ||
|
|
||
| if result.stdout.strip(): | ||
| console.print(f" stdout: {result.stdout.strip()[:500]}") | ||
| if result.stderr.strip(): | ||
| console.print(f" stderr: {result.stderr.strip()[:500]}") | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| if not result.success: | ||
| raise typer.Exit(1) | ||
|
|
||
|
|
||
| @hooks_app.command("set") | ||
| def hooks_set( | ||
| hook_name: str = typer.Argument(..., help="Hook name to configure"), | ||
| command: str = typer.Argument(..., help="Shell command template"), | ||
| workspace_path: Optional[Path] = typer.Option( | ||
| None, "--workspace", "-w", | ||
| help="Workspace path (defaults to current directory)", | ||
| ), | ||
| ) -> None: | ||
| """Set or update a hook command.""" | ||
| from codeframe.core.config import ( | ||
| load_environment_config, | ||
| save_environment_config, | ||
| get_default_environment_config, | ||
| ) | ||
|
|
||
| if hook_name not in VALID_HOOK_NAMES: | ||
| console.print(f"[red]Error:[/red] Invalid hook name '{hook_name}'") | ||
| console.print(f"Valid hooks: {', '.join(VALID_HOOK_NAMES)}") | ||
| raise typer.Exit(1) | ||
|
|
||
| from codeframe.core.workspace import get_workspace | ||
| path = workspace_path or Path.cwd() | ||
| try: | ||
| ws = get_workspace(path) | ||
| path = ws.repo_path | ||
| except (FileNotFoundError, ValueError): | ||
| pass # Workspace not initialized; fall back to raw path | ||
| config = load_environment_config(path) or get_default_environment_config() | ||
|
|
||
| setattr(config.hooks, hook_name, command) | ||
| save_environment_config(path, config) | ||
|
|
||
| console.print(f"[green]Hook '{hook_name}' set to:[/green] {command}") | ||
|
|
||
|
|
||
| @hooks_app.command("clear") | ||
| def hooks_clear( | ||
| hook_name: str = typer.Argument(..., help="Hook name to clear"), | ||
| workspace_path: Optional[Path] = typer.Option( | ||
| None, "--workspace", "-w", | ||
| help="Workspace path (defaults to current directory)", | ||
| ), | ||
| ) -> None: | ||
| """Remove a hook.""" | ||
| from codeframe.core.config import ( | ||
| load_environment_config, | ||
| save_environment_config, | ||
| ) | ||
|
|
||
| if hook_name not in VALID_HOOK_NAMES: | ||
| console.print(f"[red]Error:[/red] Invalid hook name '{hook_name}'") | ||
| console.print(f"Valid hooks: {', '.join(VALID_HOOK_NAMES)}") | ||
| raise typer.Exit(1) | ||
|
|
||
| from codeframe.core.workspace import get_workspace | ||
| path = workspace_path or Path.cwd() | ||
| try: | ||
| ws = get_workspace(path) | ||
| path = ws.repo_path | ||
| except (FileNotFoundError, ValueError): | ||
| pass # Workspace not initialized; fall back to raw path | ||
| config = load_environment_config(path) | ||
|
|
||
| if not config: | ||
| console.print("[yellow]No workspace configuration found.[/yellow]") | ||
| raise typer.Exit(1) | ||
|
|
||
| setattr(config.hooks, hook_name, None) | ||
| save_environment_config(path, config) | ||
|
|
||
| console.print(f"[green]Hook '{hook_name}' cleared.[/green]") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -81,6 +81,22 @@ class AgentBudgetConfig: | |
| stall_timeout_s: int = 300 | ||
|
|
||
|
|
||
| @dataclass | ||
| class HooksConfig: | ||
| """Workspace lifecycle hooks configuration. | ||
|
|
||
| Hooks are shell commands executed at specific lifecycle points. | ||
| Template variables (e.g., {{task_id}}) are rendered via Jinja2. | ||
| """ | ||
|
|
||
| after_init: Optional[str] = None | ||
| before_task: Optional[str] = None | ||
| after_task_success: Optional[str] = None | ||
| after_task_failure: Optional[str] = None | ||
| before_remove: Optional[str] = None | ||
| hook_timeout: int = 60 | ||
|
Comment on lines
+84
to
+97
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Validate
🛠️ Suggested fix `@dataclass`
class HooksConfig:
@@
after_task_failure: Optional[str] = None
before_remove: Optional[str] = None
hook_timeout: int = 60
+
+ def __post_init__(self) -> None:
+ if self.hook_timeout <= 0:
+ raise ValueError("hooks.hook_timeout must be > 0")🤖 Prompt for AI Agents |
||
|
|
||
|
|
||
| @dataclass | ||
| class EnvironmentConfig: | ||
| """v2 project environment configuration. | ||
|
|
@@ -108,6 +124,9 @@ class EnvironmentConfig: | |
| # Agent budget | ||
| agent_budget: AgentBudgetConfig = dataclass_field(default_factory=AgentBudgetConfig) | ||
|
|
||
| # Workspace lifecycle hooks | ||
| hooks: HooksConfig = dataclass_field(default_factory=HooksConfig) | ||
|
|
||
| # Execution engine | ||
| engine: str = "react" | ||
|
|
||
|
|
@@ -259,6 +278,8 @@ def from_dict(cls, data: dict[str, Any]) -> "EnvironmentConfig": | |
| data["context"] = ContextConfig(**data["context"]) | ||
| if "agent_budget" in data and isinstance(data["agent_budget"], dict): | ||
| data["agent_budget"] = AgentBudgetConfig(**data["agent_budget"]) | ||
| if "hooks" in data and isinstance(data["hooks"], dict): | ||
| data["hooks"] = HooksConfig(**data["hooks"]) | ||
| return cls(**data) | ||
|
|
||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.