From d8d7b8036e43081969e13169edb798c12d43a3b5 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 24 Dec 2025 00:44:59 +0000 Subject: [PATCH 1/4] Initial plan From 2112bd6f0e22d21c904b2660dac5c02d9832a8fe Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 24 Dec 2025 00:48:55 +0000 Subject: [PATCH 2/4] Initial plan for adding clear and concise logging Co-authored-by: alexec <1142830+alexec@users.noreply.github.com> --- .../commands/example-command-no-expansion.md | 11 +++ examples/.agents/commands/setup-database.md | 22 +++++ .../rules/example-rule-no-expansion.md | 11 +++ .../.agents/rules/go-implementation-cursor.md | 29 +++++++ examples/.agents/rules/implementation-go.md | 49 +++++++++++ examples/.agents/rules/planning.md | 42 ++++++++++ examples/.agents/rules/testing.md | 47 +++++++++++ examples/.agents/tasks/code-review.md | 63 +++++++++++++++ .../tasks/example-mcp-arbitrary-fields.md | 81 +++++++++++++++++++ .../.agents/tasks/example-no-expansion.md | 31 +++++++ .../tasks/example-with-standard-fields.md | 56 +++++++++++++ examples/.agents/tasks/fix-bug-resume.md | 45 +++++++++++ examples/.agents/tasks/fix-bug.md | 56 +++++++++++++ .../.agents/tasks/implement-go-feature.md | 55 +++++++++++++ examples/.agents/tasks/plan-feature.md | 51 ++++++++++++ examples/.agents/tasks/refactor-code.md | 57 +++++++++++++ examples/.agents/tasks/write-tests.md | 52 ++++++++++++ 17 files changed, 758 insertions(+) create mode 100644 examples/.agents/commands/example-command-no-expansion.md create mode 100644 examples/.agents/commands/setup-database.md create mode 100644 examples/.agents/rules/example-rule-no-expansion.md create mode 100644 examples/.agents/rules/go-implementation-cursor.md create mode 100644 examples/.agents/rules/implementation-go.md create mode 100644 examples/.agents/rules/planning.md create mode 100644 examples/.agents/rules/testing.md create mode 100644 examples/.agents/tasks/code-review.md create mode 100644 examples/.agents/tasks/example-mcp-arbitrary-fields.md create mode 100644 examples/.agents/tasks/example-no-expansion.md create mode 100644 examples/.agents/tasks/example-with-standard-fields.md create mode 100644 examples/.agents/tasks/fix-bug-resume.md create mode 100644 examples/.agents/tasks/fix-bug.md create mode 100644 examples/.agents/tasks/implement-go-feature.md create mode 100644 examples/.agents/tasks/plan-feature.md create mode 100644 examples/.agents/tasks/refactor-code.md create mode 100644 examples/.agents/tasks/write-tests.md diff --git a/examples/.agents/commands/example-command-no-expansion.md b/examples/.agents/commands/example-command-no-expansion.md new file mode 100644 index 0000000..f601eb5 --- /dev/null +++ b/examples/.agents/commands/example-command-no-expansion.md @@ -0,0 +1,11 @@ +--- +expand: false +--- + +# Example Command Without Parameter Expansion + +This command content will not have parameters expanded. + +Placeholders like ${project_name}, ${version}, and ${environment} will be preserved as-is. + +Use this when you want the command's output to contain template variables for later processing. diff --git a/examples/.agents/commands/setup-database.md b/examples/.agents/commands/setup-database.md new file mode 100644 index 0000000..6198f72 --- /dev/null +++ b/examples/.agents/commands/setup-database.md @@ -0,0 +1,22 @@ +--- +selectors: + database: postgres + feature: auth +--- + +# Database Setup Instructions + +This command provides database setup instructions. When this command is used in a task, +it will automatically include rules that are tagged with `database: postgres` and +`feature: auth` in their frontmatter. + +## PostgreSQL Configuration + +Connect to PostgreSQL: +```bash +psql -U ${db_user} -d ${db_name} +``` + +## Authentication Setup + +Configure authentication tables and initial data. diff --git a/examples/.agents/rules/example-rule-no-expansion.md b/examples/.agents/rules/example-rule-no-expansion.md new file mode 100644 index 0000000..176184b --- /dev/null +++ b/examples/.agents/rules/example-rule-no-expansion.md @@ -0,0 +1,11 @@ +--- +expand: false +--- + +# Example Rule Without Parameter Expansion + +This rule demonstrates disabling parameter expansion at the rule level. + +Template variables: ${variable1}, ${variable2}, ${variable3} + +This is useful when rules contain template syntax that should be preserved for the AI agent to process. diff --git a/examples/.agents/rules/go-implementation-cursor.md b/examples/.agents/rules/go-implementation-cursor.md new file mode 100644 index 0000000..711a201 --- /dev/null +++ b/examples/.agents/rules/go-implementation-cursor.md @@ -0,0 +1,29 @@ +--- +task_name: implement-feature +language: go +agent: cursor +--- + +# Go Implementation Standards for Feature Development + +This rule demonstrates standard frontmatter fields for rules: + +- **task_name**: `implement-feature` - This rule only applies to the `implement-feature` task +- **language**: `go` - This rule only applies when the language is go +- **agent**: `cursor` - This rule is optimized for the Cursor AI agent + +## When This Rule Is Included + +This rule will be included when: +1. The task being run is `implement-feature` (or has `task_name: implement-feature` selector) +2. AND the task has `language: go` (or `-s language=go` is specified) +3. AND the task has `agent: cursor` (or `-a cursor` is specified) + +## Go-Specific Implementation Guidelines + +When implementing features in Go: +- Follow Go idioms and conventions +- Use table-driven tests +- Handle errors explicitly +- Keep functions small and focused +- Use interfaces for abstraction diff --git a/examples/.agents/rules/implementation-go.md b/examples/.agents/rules/implementation-go.md new file mode 100644 index 0000000..91bf76a --- /dev/null +++ b/examples/.agents/rules/implementation-go.md @@ -0,0 +1,49 @@ +--- +stage: implementation +language: go +--- + +# Go Implementation Standards + +## Code Style + +- Follow Go standard formatting (use `gofmt`) +- Use meaningful variable and function names +- Keep functions focused and small +- Comment exported functions and types +- Use Go idioms and patterns + +## Error Handling + +- Always check and handle errors explicitly +- Wrap errors with context using `fmt.Errorf` +- Return errors rather than panicking +- Use custom error types when appropriate + +## Testing + +- Write unit tests for all functions +- Use table-driven tests for multiple scenarios +- Aim for high test coverage (>80%) +- Use meaningful test names that describe the scenario + +## Concurrency + +- Use channels for communication between goroutines +- Use sync package primitives appropriately +- Avoid shared state when possible +- Document goroutine lifecycle + +## Dependencies + +- Minimize external dependencies +- Use standard library when possible +- Vendor dependencies for reproducible builds +- Keep dependencies up to date + +## Performance + +- Profile before optimizing +- Avoid premature optimization +- Use benchmarks to measure performance +- Consider memory allocations diff --git a/examples/.agents/rules/planning.md b/examples/.agents/rules/planning.md new file mode 100644 index 0000000..fe0b53d --- /dev/null +++ b/examples/.agents/rules/planning.md @@ -0,0 +1,42 @@ +--- +stage: planning +--- + +# Feature Planning Guidelines + +When planning new features, follow these principles: + +## Architecture First + +- Consider how the feature fits into existing architecture +- Identify dependencies and affected components +- Plan for backwards compatibility +- Consider scalability and performance implications + +## Design Patterns + +- Use established design patterns from the codebase +- Maintain consistency with existing code structure +- Follow SOLID principles +- Plan for testability from the start + +## Breaking Down Work + +- Decompose features into manageable units +- Identify critical path vs. nice-to-have elements +- Plan incremental delivery when possible +- Consider feature flags for gradual rollout + +## Risk Assessment + +- Identify technical risks and mitigation strategies +- Consider security implications +- Plan for error handling and edge cases +- Document assumptions and constraints + +## Documentation Planning + +- Plan what documentation will be needed +- Consider API documentation requirements +- Plan for user-facing documentation +- Identify training or onboarding needs diff --git a/examples/.agents/rules/testing.md b/examples/.agents/rules/testing.md new file mode 100644 index 0000000..062e908 --- /dev/null +++ b/examples/.agents/rules/testing.md @@ -0,0 +1,47 @@ +--- +stage: testing +--- + +# Testing Standards + +## Test Coverage + +- Write tests for all public APIs +- Test edge cases and error conditions +- Aim for >80% code coverage +- Write integration tests for critical paths + +## Test Organization + +- Group related tests in test files +- Use descriptive test names +- Follow AAA pattern: Arrange, Act, Assert +- Keep tests independent and isolated + +## Test Data + +- Use fixtures for complex test data +- Avoid hardcoding test data in tests +- Clean up test data after tests +- Use realistic test scenarios + +## Mocking and Stubbing + +- Mock external dependencies +- Use interfaces for testability +- Avoid over-mocking +- Test real integrations when possible + +## Performance Testing + +- Write benchmarks for performance-critical code +- Set performance baselines +- Monitor performance over time +- Load test under realistic conditions + +## Test Automation + +- All tests must run in CI/CD +- Tests should be fast (<5 minutes total) +- Flaky tests should be fixed or removed +- Failed tests should block deployment diff --git a/examples/.agents/tasks/code-review.md b/examples/.agents/tasks/code-review.md new file mode 100644 index 0000000..fab4584 --- /dev/null +++ b/examples/.agents/tasks/code-review.md @@ -0,0 +1,63 @@ +--- +task_name: code-review +--- + +# Code Review Task + +You are an expert code reviewer analyzing a pull request. + +## Pull Request Information + +- **PR Number**: #${pr_number} +- **Title**: ${pr_title} +- **URL**: ${pr_url} +- **Base Branch**: ${base_branch} +- **Head Branch**: ${head_branch} + +## Your Task + +Perform a thorough code review covering: + +1. **Code Quality** + - Readability and maintainability + - Adherence to coding standards + - Proper naming conventions + - Code organization + +2. **Correctness** + - Logic errors or bugs + - Edge case handling + - Error handling completeness + - Type safety + +3. **Testing** + - Test coverage adequacy + - Test quality and relevance + - Missing test scenarios + - Test maintainability + +4. **Security** + - Security vulnerabilities + - Input validation + - Authentication/authorization + - Sensitive data handling + +5. **Performance** + - Performance implications + - Resource usage + - Scalability concerns + - Optimization opportunities + +6. **Documentation** + - Code comments where needed + - API documentation + - README updates if needed + - Migration guides if applicable + +## Output Format + +Provide your review as: +- Overall summary +- Specific inline comments for issues +- Recommendations for improvement +- Approval status (approve, request changes, comment) diff --git a/examples/.agents/tasks/example-mcp-arbitrary-fields.md b/examples/.agents/tasks/example-mcp-arbitrary-fields.md new file mode 100644 index 0000000..bb504be --- /dev/null +++ b/examples/.agents/tasks/example-mcp-arbitrary-fields.md @@ -0,0 +1,81 @@ +--- +task_name: example-mcp-arbitrary-fields +agent: cursor +--- + +# Example Rule with MCP Server Configuration + +This example demonstrates how rules can specify MCP server configuration with arbitrary custom fields. + +Note: MCP servers are specified in rules, not in tasks. Tasks can select which rules (and thus which MCP servers) to use via selectors. + +## The `mcp_server` Field in Rules + +Rules can specify a single MCP server configuration with both standard and arbitrary custom fields. + +The `mcp_server` field, when present in a rule, specifies that rule's single MCP server configuration with both standard and arbitrary custom fields. Tasks cannot define MCP servers directly. + +**Standard fields:** +- `command`: The executable to run (e.g., "python", "npx", "docker") +- `args`: Array of command-line arguments +- `env`: Environment variables for the server process +- `type`: Connection protocol ("stdio", "http", "sse") - optional, defaults to stdio +- `url`: Endpoint URL for HTTP/SSE types +- `headers`: Custom HTTP headers for HTTP/SSE types + +## Example Rule with MCP Server + +```yaml +--- +rule_name: python-mcp-server +mcp_server: + command: python + args: ["-m", "server"] + env: + PYTHON_PATH: /usr/bin/python3 + custom_config: + host: localhost + port: 5432 + ssl: true + pool: + min: 2 + max: 10 + monitoring: + enabled: true + metrics_port: 9090 +--- + +# Python MCP Server Rule + +This rule provides the Python MCP server configuration. +``` + +## Why Arbitrary Fields? + +Different MCP servers may need different configuration options beyond the standard fields. Arbitrary fields allow you to: + +1. **Add custom metadata**: Version info, regions, endpoints, etc. +2. **Configure behavior**: Caching, retry policies, timeouts, rate limits +3. **Include nested config**: Complex configuration objects specific to your server +4. **Future-proof**: Add new fields without changing the schema + +## How It Works + +The `MCPServerConfig` struct includes a `Content` field that captures all fields from YAML/JSON: + +```go +type MCPServerConfig struct { + // Standard fields + Type TransportType + Command string + Args []string + Env map[string]string + URL string + Headers map[string]string + + // Arbitrary fields via inline map + Content map[string]any `yaml:",inline"` +} +``` + +All fields (both standard and custom) are preserved when the configuration is parsed and can be accessed via the struct fields or the `Content` map. diff --git a/examples/.agents/tasks/example-no-expansion.md b/examples/.agents/tasks/example-no-expansion.md new file mode 100644 index 0000000..90cd4f6 --- /dev/null +++ b/examples/.agents/tasks/example-no-expansion.md @@ -0,0 +1,31 @@ +--- +task_name: example-no-expansion +expand: false +--- + +# Example Task Without Parameter Expansion + +This task demonstrates how to disable parameter expansion using the `expand: false` frontmatter field. + +## Usage + +When `expand` is set to `false`, parameter placeholders are preserved as-is: + +- Issue Number: ${issue_number} +- Issue Title: ${issue_title} +- Repository: ${repo} +- Branch: ${branch} + +This is useful when: +1. You want to pass parameters directly to an AI agent that will handle its own substitution +2. You're using template syntax that conflicts with the parameter expansion syntax +3. You want to preserve the template for later processing + +## Example + +```bash +coding-context -p issue_number=123 -p issue_title="Bug Fix" example-no-expansion +``` + +Even though parameters are passed on the command line, they won't be expanded in the output. +The placeholders `${issue_number}` and `${issue_title}` will remain unchanged. diff --git a/examples/.agents/tasks/example-with-standard-fields.md b/examples/.agents/tasks/example-with-standard-fields.md new file mode 100644 index 0000000..ec38f96 --- /dev/null +++ b/examples/.agents/tasks/example-with-standard-fields.md @@ -0,0 +1,56 @@ +--- +task_name: example-with-standard-fields +agent: cursor +language: go +model: anthropic.claude-sonnet-4-20250514-v1-0 +single_shot: false +timeout: 10m +selectors: + stage: implementation +--- + +# Example Task with Standard Frontmatter Fields + +This task demonstrates all standard frontmatter fields supported by the coding-context CLI. + +## Standard Fields (Default Selectors) + +These fields automatically filter rules when present in task frontmatter: + +- **agent**: `cursor` - Only includes rules with `agent: cursor` (or no agent field) +- **language**: `go` - Only includes rules with `language: go` (or no language field) + +## Standard Fields (Metadata Only) + +These fields are stored in frontmatter and passed through to output, but do NOT filter rules: + +- **model**: `anthropic.claude-sonnet-4-20250514-v1-0` - AI model to use for this task +- **single_shot**: `false` - Task can be run multiple times +- **timeout**: `10m` - Task timeout as time.Duration (10 minutes) + +## Custom Selectors + +Additional filtering criteria beyond the standard fields: + +- **selectors.stage**: `implementation` - Only includes rules with `stage: implementation` + +## How Filtering Works + +When this task runs, rules are included if they match ALL of the following: +1. `agent: cursor` OR no agent field +2. `language: go` OR no language field +3. `stage: implementation` OR no stage field +4. `task_name: example-with-standard-fields` OR no task_name field + +Rules without any selectors are always included (generic rules). + +## Usage + +```bash +coding-context-cli example-with-standard-fields +``` + +The output will include: +1. Task frontmatter with all standard fields +2. Only rules matching the selectors +3. The task content diff --git a/examples/.agents/tasks/fix-bug-resume.md b/examples/.agents/tasks/fix-bug-resume.md new file mode 100644 index 0000000..c47bd01 --- /dev/null +++ b/examples/.agents/tasks/fix-bug-resume.md @@ -0,0 +1,45 @@ +--- +task_name: fix-bug +resume: true +--- + +# Bug Fix Task - Resume + +You are continuing work on a bug fix from a previous session. + +## Context + +You've already been provided with the coding standards and project guidelines. +Continue from where you left off. + +## Issue Information + +- **Issue Number**: #${issue_number} +- **Title**: ${issue_title} +- **URL**: ${issue_url} + +## Your Task + +Review your previous work and: + +1. **Complete Implementation** + - Finish any incomplete code changes + - Address any edge cases identified + - Ensure consistency with existing patterns + +2. **Finalize Tests** + - Complete test coverage + - Verify all tests pass + - Add any missing test cases + +3. **Code Review Preparation** + - Review your changes for quality + - Update documentation as needed + - Ensure commit messages are clear + +## Next Steps + +- Complete any outstanding tasks +- Run all tests one final time +- Prepare for code review +- Update the PR description if needed diff --git a/examples/.agents/tasks/fix-bug.md b/examples/.agents/tasks/fix-bug.md new file mode 100644 index 0000000..96770ea --- /dev/null +++ b/examples/.agents/tasks/fix-bug.md @@ -0,0 +1,56 @@ +--- +task_name: fix-bug +resume: false +--- + +# Bug Fix Task + +You are an expert software developer tasked with fixing a bug. + +## Issue Information + +- **Issue Number**: #${issue_number} +- **Title**: ${issue_title} +- **URL**: ${issue_url} +- **Description**: +${issue_body} + +## Your Task + +1. **Analyze the Issue** + - Understand the reported problem + - Identify the root cause + - Determine affected components + +2. **Implement the Fix** + - Write minimal code changes to fix the bug + - Follow existing code patterns + - Ensure backwards compatibility + - Handle edge cases + +3. **Add Tests** + - Write regression tests + - Verify the fix works + - Test edge cases + - Ensure no new bugs introduced + +4. **Document Changes** + - Update relevant documentation + - Add code comments if needed + - Document any behavior changes + +## Guidelines + +- Make minimal changes - only fix the specific issue +- Don't refactor unrelated code +- Ensure all existing tests still pass +- Add clear commit messages +- Consider if this bug might exist elsewhere + +## Output + +Provide: +- Root cause analysis +- The fix implementation +- Test cases +- Any documentation updates diff --git a/examples/.agents/tasks/implement-go-feature.md b/examples/.agents/tasks/implement-go-feature.md new file mode 100644 index 0000000..e8ae840 --- /dev/null +++ b/examples/.agents/tasks/implement-go-feature.md @@ -0,0 +1,55 @@ +--- +task_name: implement-feature +selectors: + language: go + stage: implementation +--- + +# Implement Feature in Go + +You are an expert Go developer implementing a new feature. + +## Feature Information + +- **Name**: ${feature_name} +- **Description**: ${feature_description} + +## Your Task + +1. **Design the Implementation** + - Follow Go idioms and best practices + - Use existing patterns in the codebase + - Keep functions small and focused + - Use interfaces for flexibility + +2. **Write the Code** + - Implement the feature with clean, readable Go code + - Add proper error handling + - Include necessary comments + - Follow the project's code style + +3. **Add Tests** + - Write table-driven tests (project standard) + - Test happy paths and error cases + - Aim for >80% code coverage + - Use meaningful test names + +4. **Update Documentation** + - Add godoc comments for exported functions + - Update README if needed + - Document any new behavior + +## Guidelines + +This task automatically includes: +- Go-specific coding rules (via language=Go selector) +- Implementation-stage guidelines (via stage=implementation selector) + +Follow all included rules and best practices. + +## Output + +Provide: +- The implementation code +- Comprehensive tests +- Documentation updates diff --git a/examples/.agents/tasks/plan-feature.md b/examples/.agents/tasks/plan-feature.md new file mode 100644 index 0000000..7091e37 --- /dev/null +++ b/examples/.agents/tasks/plan-feature.md @@ -0,0 +1,51 @@ +--- +task_name: plan-feature +stage: planning +--- + +# Feature Planning Task + +You are an expert software architect planning a new feature for this project. + +## Feature Information + +- **Name**: ${feature_name} +- **Description**: ${feature_description} +- **Priority**: ${priority} + +## Your Task + +Create a comprehensive feature plan that includes: + +1. **Architecture Design** + - How the feature fits into the existing system + - Required components and modules + - Data models and schemas + - API endpoints or interfaces + +2. **Implementation Approach** + - Step-by-step implementation plan + - Technology choices and rationale + - Integration points with existing code + - Potential challenges and solutions + +3. **Testing Strategy** + - Unit testing requirements + - Integration testing approach + - Edge cases to consider + - Performance testing needs + +4. **Timeline Estimate** + - Break down into tasks + - Estimate complexity for each task + - Identify dependencies + - Suggest milestones + +5. **Risks and Mitigation** + - Technical risks + - Resource constraints + - Mitigation strategies + +## Output Format + +Provide your plan in Markdown format with clear sections and actionable details. diff --git a/examples/.agents/tasks/refactor-code.md b/examples/.agents/tasks/refactor-code.md new file mode 100644 index 0000000..34712f4 --- /dev/null +++ b/examples/.agents/tasks/refactor-code.md @@ -0,0 +1,57 @@ +--- +task_name: refactor-code +selectors: + language: [go, python, javascript] + stage: refactoring +--- + +# Refactor Code + +You are an expert developer tasked with refactoring code to improve quality, maintainability, and performance. + +## Refactoring Target + +- **Component**: ${component_name} +- **Files**: ${files_to_refactor} +- **Goal**: ${refactoring_goal} + +## Your Task + +1. **Analyze Current Code** + - Identify code smells + - Find duplicated code + - Locate overly complex functions + - Review naming and structure + +2. **Plan the Refactoring** + - Define clear refactoring goals + - Identify potential risks + - Plan incremental changes + - Consider backwards compatibility + +3. **Implement Changes** + - Make small, focused changes + - Extract functions/methods for clarity + - Improve naming and readability + - Reduce complexity + - Remove duplication + +4. **Ensure Tests Pass** + - Run existing tests after each change + - Add tests if coverage is lacking + - Verify no behavior changes + - Use tests to guide refactoring + +## Guidelines + +This task automatically includes refactoring-stage rules for Go, Python, OR JavaScript (via array selector). + +The selector `language: [go, python, javascript]` means rules matching ANY of these languages will be included, along with rules for stage=refactoring. + +## Output + +Provide: +- Analysis of current code issues +- Refactored code +- Explanation of improvements made +- Test results showing no regressions diff --git a/examples/.agents/tasks/write-tests.md b/examples/.agents/tasks/write-tests.md new file mode 100644 index 0000000..35cef91 --- /dev/null +++ b/examples/.agents/tasks/write-tests.md @@ -0,0 +1,52 @@ +--- +task_name: write-tests +selectors: + stage: testing +--- + +# Write Comprehensive Tests + +You are an expert developer tasked with writing comprehensive tests. + +## Test Requirements + +- **Component**: ${component_name} +- **File(s)**: ${files_to_test} + +## Your Task + +1. **Analyze the Code** + - Understand the functionality being tested + - Identify all code paths + - Find edge cases and boundary conditions + - Review existing tests for patterns + +2. **Write Test Cases** + - Cover all happy paths + - Test error conditions + - Test edge cases and boundary values + - Test concurrent operations if applicable + +3. **Follow Language Conventions** + - Use meaningful test names that describe what's being tested + - Keep tests isolated and independent + - Follow the testing patterns in the codebase + +4. **Verify Coverage** + - Run tests to ensure they pass + - Check code coverage metrics + - Aim for >80% coverage + - Ensure all critical paths are tested + +## Guidelines + +This task automatically includes testing-stage guidelines (via stage=testing selector). + +Use `-s language=go` or similar if you need language-specific rules. + +## Output + +Provide: +- Well-structured test code +- Test coverage report +- Any testing utilities or fixtures needed From 2fca625b371c2fb73932df7fb0955f5cdd010050 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 24 Dec 2025 00:57:59 +0000 Subject: [PATCH 3/4] Implement clear and concise logging with -v flag - Add -v/--verbose flag to control logging verbosity - Update usage output to use fmt.Fprintf instead of logger - Update error messages to be clean without slog formatting - Update log messages to be more concise and user-friendly - Default mode (no -v): only errors shown, no timestamps - Verbose mode (-v): INFO level logs with timestamps - Clean output suitable for piping to AI agents Co-authored-by: alexec <1142830+alexec@users.noreply.github.com> --- main.go | 57 +++++++++++++++++++++--------------- pkg/codingcontext/context.go | 14 ++++----- 2 files changed, 41 insertions(+), 30 deletions(-) diff --git a/main.go b/main.go index 5fbfc04..1c02fc8 100644 --- a/main.go +++ b/main.go @@ -21,11 +21,10 @@ func main() { ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer cancel() - logger := slog.New(slog.NewTextHandler(os.Stderr, nil)) - var workDir string var resume bool var writeRules bool + var verbose bool var agent codingcontext.Agent params := make(taskparser.Params) includes := make(selectors.Selectors) @@ -35,6 +34,7 @@ func main() { flag.StringVar(&workDir, "C", ".", "Change to directory before doing anything.") flag.BoolVar(&resume, "r", false, "Resume mode: skip outputting rules and select task with 'resume: true' in frontmatter.") flag.BoolVar(&writeRules, "w", false, "Write rules to the agent's user rules path and only print the prompt to stdout. Requires agent (via task 'agent' field or -a flag).") + flag.BoolVar(&verbose, "v", false, "Enable verbose logging to stderr.") flag.Var(&agent, "a", "Target agent to use. Required when using -w to write rules to the agent's user rules path. Supported agents: cursor, opencode, copilot, claude, gemini, augment, windsurf, codex.") flag.Var(¶ms, "p", "Parameter to substitute in the prompt. Can be specified multiple times as key=value.") flag.Var(&includes, "s", "Include rules with matching frontmatter. Can be specified multiple times as key=value.") @@ -45,24 +45,33 @@ func main() { flag.StringVar(&manifestURL, "m", "", "Go Getter URL to a manifest file containing search paths (one per line). Every line is included as-is.") flag.Usage = func() { - logger.Info("Usage:") - logger.Info(" coding-context [options] [user-prompt]") - logger.Info("") - logger.Info("The task-name is the name of a task file to look up in task search paths (.agents/tasks).") - logger.Info("The user-prompt is optional text to append to the task. It can contain slash commands") - logger.Info("(e.g., '/command-name') which will be expanded, and parameter substitution (${param}).") - logger.Info("") - logger.Info("Task content can contain slash commands (e.g., '/command-name arg') which reference") - logger.Info("command files in command search paths (.cursor/commands, .agents/commands, etc.).") - logger.Info("") - logger.Info("Options:") + fmt.Fprintln(os.Stderr, "Usage:") + fmt.Fprintln(os.Stderr, " coding-context [options] [user-prompt]") + fmt.Fprintln(os.Stderr, "") + fmt.Fprintln(os.Stderr, "The task-name is the name of a task file to look up in task search paths (.agents/tasks).") + fmt.Fprintln(os.Stderr, "The user-prompt is optional text to append to the task. It can contain slash commands") + fmt.Fprintln(os.Stderr, "(e.g., '/command-name') which will be expanded, and parameter substitution (${param}).") + fmt.Fprintln(os.Stderr, "") + fmt.Fprintln(os.Stderr, "Task content can contain slash commands (e.g., '/command-name arg') which reference") + fmt.Fprintln(os.Stderr, "command files in command search paths (.cursor/commands, .agents/commands, etc.).") + fmt.Fprintln(os.Stderr, "") + fmt.Fprintln(os.Stderr, "Options:") flag.PrintDefaults() } flag.Parse() + // Create logger with appropriate level based on verbose flag + logLevel := slog.LevelError + if verbose { + logLevel = slog.LevelInfo + } + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ + Level: logLevel, + })) + args := flag.Args() if len(args) < 1 || len(args) > 2 { - logger.Error("Error", "error", fmt.Errorf("invalid usage: expected one task name argument and optional user-prompt")) + fmt.Fprintf(os.Stderr, "Error: invalid usage: expected one task name argument and optional user-prompt\n") flag.Usage() os.Exit(1) } @@ -75,7 +84,7 @@ func main() { homeDir, err := os.UserHomeDir() if err != nil { - logger.Error("Error", "error", fmt.Errorf("failed to get user home directory: %w", err)) + fmt.Fprintf(os.Stderr, "Error: failed to get user home directory: %v\n", err) os.Exit(1) } @@ -95,7 +104,7 @@ func main() { result, err := cc.Run(ctx, taskName) if err != nil { - logger.Error("Error", "error", err) + fmt.Fprintf(os.Stderr, "Error: %v\n", err) flag.Usage() os.Exit(1) } @@ -104,7 +113,7 @@ func main() { if writeRules { // Get the user rule path from the agent (could be from task or -a flag) if !result.Agent.IsSet() { - logger.Error("Error", "error", fmt.Errorf("-w flag requires an agent to be specified (via task 'agent' field or -a flag)")) + fmt.Fprintf(os.Stderr, "Error: -w flag requires an agent to be specified (via task 'agent' field or -a flag)\n") os.Exit(1) } @@ -112,7 +121,7 @@ func main() { if !resume { relativePath := result.Agent.UserRulePath() if relativePath == "" { - logger.Error("Error", "error", fmt.Errorf("no user rule path available for agent")) + fmt.Fprintf(os.Stderr, "Error: no user rule path available for agent\n") os.Exit(1) } @@ -122,7 +131,7 @@ func main() { // Create directory if it doesn't exist if err := os.MkdirAll(rulesDir, 0o755); err != nil { - logger.Error("Error", "error", fmt.Errorf("failed to create rules directory %s: %w", rulesDir, err)) + fmt.Fprintf(os.Stderr, "Error: failed to create rules directory %s: %v\n", rulesDir, err) os.Exit(1) } @@ -137,18 +146,20 @@ func main() { rulesContent.WriteString("\n") if err := os.WriteFile(rulesFile, []byte(rulesContent.String()), 0o644); err != nil { - logger.Error("Error", "error", fmt.Errorf("failed to write rules to %s: %w", rulesFile, err)) + fmt.Fprintf(os.Stderr, "Error: failed to write rules to %s: %v\n", rulesFile, err) os.Exit(1) } - logger.Info("Rules written", "path", rulesFile) + if verbose { + logger.Info("Rules written", "path", rulesFile) + } } // Output only task frontmatter and content if taskContent := result.Task.FrontMatter.Content; taskContent != nil { fmt.Println("---") if err := yaml.NewEncoder(os.Stdout).Encode(taskContent); err != nil { - logger.Error("Failed to encode task frontmatter", "error", err) + fmt.Fprintf(os.Stderr, "Error: failed to encode task frontmatter: %v\n", err) os.Exit(1) } fmt.Println("---") @@ -160,7 +171,7 @@ func main() { if taskContent := result.Task.FrontMatter.Content; taskContent != nil { fmt.Println("---") if err := yaml.NewEncoder(os.Stdout).Encode(taskContent); err != nil { - logger.Error("Failed to encode task frontmatter", "error", err) + fmt.Fprintf(os.Stderr, "Error: failed to encode task frontmatter: %v\n", err) os.Exit(1) } fmt.Println("---") diff --git a/pkg/codingcontext/context.go b/pkg/codingcontext/context.go index e83dc4e..406719b 100644 --- a/pkg/codingcontext/context.go +++ b/pkg/codingcontext/context.go @@ -146,7 +146,7 @@ func (cc *Context) findTask(taskName string) error { taskContent += "\n" } taskContent += "---\n" + cc.userPrompt - cc.logger.Info("Appended user_prompt to task", "user_prompt_length", len(cc.userPrompt)) + cc.logger.Info("Appended user prompt to task", "length", len(cc.userPrompt)) } // Parse the task content (including user_prompt) to separate text blocks from slash commands @@ -187,7 +187,7 @@ func (cc *Context) findTask(taskName string) error { } cc.totalTokens += cc.task.Tokens - cc.logger.Info("Including task", "tokens", cc.task.Tokens) + cc.logger.Info("Task loaded", "tokens", cc.task.Tokens) return nil }) @@ -326,7 +326,7 @@ func (cc *Context) Run(ctx context.Context, taskName string) (*Result, error) { } // Estimate tokens for task - cc.logger.Info("Total estimated tokens", "tokens", cc.totalTokens) + cc.logger.Info("Context assembled", "total_tokens", cc.totalTokens, "rules", len(cc.rules)) // Build the combined prompt from all rules and task content var promptBuilder strings.Builder @@ -421,7 +421,7 @@ func (cc *Context) parseManifestFile(ctx context.Context) ([]string, error) { return nil, fmt.Errorf("failed to read manifest file: %w", err) } - cc.logger.Info("Parsed manifest file", "url", cc.manifestURL, "paths", len(paths)) + cc.logger.Info("Parsed manifest file", "url", cc.manifestURL, "paths_found", len(paths)) return paths, nil } @@ -437,12 +437,12 @@ func (cc *Context) downloadRemoteDirectories(ctx context.Context) error { } // Download remote directories - cc.logger.Info("Downloading remote directory", "path", path) + cc.logger.Info("Downloading", "url", path) dst := downloadDir(path) if _, err := getter.Get(ctx, dst, path); err != nil { return fmt.Errorf("failed to download remote directory %s: %w", path, err) } - cc.logger.Info("Downloaded to", "path", dst) + cc.logger.Info("Downloaded", "destination", dst) cc.downloadedPaths = append(cc.downloadedPaths, dst) } @@ -498,7 +498,7 @@ func (cc *Context) findExecuteRuleFiles(ctx context.Context, homeDir string) err cc.totalTokens += tokens - cc.logger.Info("Including rule file", "path", path, "tokens", tokens) + cc.logger.Info("Rule loaded", "path", filepath.Base(path), "tokens", tokens) if err := cc.runBootstrapScript(ctx, path); err != nil { return fmt.Errorf("failed to run bootstrap script: %w", err) From c9e56df6764cd6836e262511205658e114fb9bbd Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 24 Dec 2025 01:00:18 +0000 Subject: [PATCH 4/4] Remove unnecessary verbose check - logger handles level filtering Co-authored-by: alexec <1142830+alexec@users.noreply.github.com> --- main.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/main.go b/main.go index 1c02fc8..e328a20 100644 --- a/main.go +++ b/main.go @@ -150,9 +150,7 @@ func main() { os.Exit(1) } - if verbose { - logger.Info("Rules written", "path", rulesFile) - } + logger.Info("Rules written", "path", rulesFile) } // Output only task frontmatter and content