Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions .cursor/rules/go-autonomous.mdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
---
description: "Instruct Cursor to act autonomously toward the goal without prompting for confirmation."
globs:
alwaysApply: false
---

# Autonomous Execution Rule

**Purpose:** Enable Cursor IDE to take initiative on achieving a defined goal--performing analysis, refactoring, or fixes--without asking follow-up questions.

## Guidelines

1. **Immediate Action**

* Upon recognizing the goal, proceed with all detection, analysis, and corrective steps automatically.
* Do not prompt the user for intermediate approvals or clarifications.

2. **Continuous Context Usage**

* Leverage available context (task descriptions, code comments, existing rules) to make informed decisions.
* Assume sufficient knowledge; refrain from asking questions about scope or next steps.

3. **End-to-End Completion**

* Execute the full workflow: detect issues, apply minimal fixes, verify results, and summarize actions.
* Complete each phase in sequence without interruption.

4. **Concise Reporting**

* After finishing, provide a brief summary of actions taken, remaining tasks (if any), and verification outcomes.
* Avoid intermediate or verbose prompts during execution.
75 changes: 75 additions & 0 deletions .cursor/rules/go-avoid-panic.mdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
---
description: "Eliminate `panic()` calls by converting them into error returns with static error values."
globs: *.go, pkg/**/*.go
alwaysApply: true
---

# Panic-to-Error Refactoring Rule

**Problem:** Uncontrolled `panic()` calls crash applications and bypass usual error handling. We need to replace panics with returned errors to allow graceful handling.

## Rule

1. **Static Error Declarations**

* Define all error values in a shared `var` block, using `errors.New(...)` with a clear, unique message.
* Prefix error strings with the package or function name for clarity.

```go
var (
ParseConfigError = errors.New("config: parse error")
InvalidInputError = errors.New("input: invalid parameter")
)
```

2. **Convert `panic()` to Error Return**

* Remove `panic(err)` or `panic("message")` calls.
* Insert a `DebugLog` (or equivalent logger) statement to record dynamic details.
* Change the function signature to return `error` (or add `error` to returns).
* Return the appropriate static error after logging.

## Examples

### \[FAIL] Panic Usage

```go
func LoadConfig(path string) *Config {
data, err := os.ReadFile(path)
if err != nil {
panic(err)
}
// ... parse data ...
if missingField {
panic("missing required field: name")
}
return cfg
}
```

### \[OK] Error Return

```go
func LoadConfig(path string) (*Config, error) {
data, err := os.ReadFile(path)
if err != nil {
i.DebugLog("LoadConfig: failed to read file %s: %v", path, err)
return nil, ParseConfigError
}
// ... parse data ...
if missingField {
i.DebugLog("LoadConfig: missing required field 'name'")
return nil, InvalidInputError
}
return cfg, nil
}
```

## Notes

* **Preserve dynamic details** in logs, not in error strings.
* **Always return** errors instead of panicking.
* **Update callers** to handle the new `error` return value.
* **Function signatures** must include `error` if they currently do not.

*Apply this rule to all Go packages to ensure predictable error handling and avoid unexpected panics.*
11 changes: 11 additions & 0 deletions .cursor/rules/go-context.mdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
description: "Ensure that a feature branch's changes implement the intended BitNet issue"
globs: **/*.go
alwaysApply: false
---

**Purpose:** Ensure that a feature branch's changes strictly implement the intended BitNet issue and introduce no unrelated modifications.

To learn more about current context, run this command:

`./scripts/get-current-context.sh|cat`
92 changes: 92 additions & 0 deletions .cursor/rules/go-refactor.mdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
---
description: "Detect duplicated logic and refactor large functions into reusable, tested utility functions."
globs: *.go, pkg/**/*.go
alwaysApply: false
---

# Utility Extraction & Function Decomposition Rule

**Purpose:** Identify repeating patterns and overly complex functions in Go
code, extract shared logic into small, semantic utility functions, and
decompose large functions for readability and maintainability. Ensure all new
utilities have independent unit tests.

## 1. Detect Duplication & Complexity

* **Search for repeated code blocks:** Use `grep`, `git diff`, or IDE "Find
Duplicates" features to locate similar logic across files.

* **Identify large functions:** Functions exceeding \~50 lines or containing
multiple distinct responsibilities.

## 2. Extract Utility Functions

1. **Define a clear purpose:** Name utilities descriptively (e.g.,
`ParseConfigField`, `ValidateUserInput`).

2. **Move shared logic:** Extract common code into a new function in an
appropriate package (e.g., `internal/util`).

3. **Update callers:** Replace inlined code in each original location with
calls to the new utility.

```go
// Before: repeated parsing logic in multiple handlers
field, err := strconv.Atoi(params["count"])
if err != nil {
return fmt.Errorf("invalid count: %v", err)
}

// After: single utility
field, err := util.ParseIntParam(params, "count")
if err != nil {
return err
}
```

## 3. Decompose Large Functions

* **Single Responsibility:** Split functions that perform multiple tasks (e.g.,
parsing, validation, storage) into smaller helper or utility calls.

* **Maintain clear flow:** Orchestrator functions should focus on high-level
logic, delegating details to extracted utilities.

## 4. Unit Test Utilities Independently

* **Create dedicated `*_test.go` files** for each new utility.

* **Cover edge cases and error paths** using table-driven tests.

* **Use `b.ReportAllocs()`** in benchmarks for performance-sensitive utilities.

```go
func TestParseIntParam(t *testing.T) {
tests := []struct { key, want string; wantErr bool }{
{"count", "5", false},
{"missing", "", true},
{"bad", "abc", true},
}
for _, tc := range tests {
t.Run(tc.key, func(t *testing.T) {
_, err := ParseIntParam(map[string]string{tc.key: tc.want}, tc.key)
if (err != nil) != tc.wantErr {
t.Fatalf("ParseIntParam error = %v, wantErr %v", err, tc.wantErr)
}
})
}
}
```

## 5. Verify and Clean Up

* **Run coverage:** Ensure utilities are fully covered.

* **Run linters and formatters:** Maintain code style.

* **Refactor call sites:** Remove any remaining duplication and update imports.

---

*Apply this rule to improve code reuse, readability, and testability across Go
modules.*
93 changes: 93 additions & 0 deletions .cursor/rules/go-repair-tests.mdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
---
description: "Automate the detection and stepwise resolution of failing tests in pkg/bitnet, starting from the lowest-level packages."
globs: pkg/bitnet/**/*.go
alwaysApply: false
---

# Failing Test Resolution Rule

**Purpose:** Detect failing tests dynamically, order them by package dependency (leaf packages first), and guide Cursor through diagnosing and fixing each failure in turn.

## Steps

1. **Map Tests to Packages**

```bash
go test -timeout 18s -json ./pkg/bitnet/... \
| jq -r 'select(.Action=="fail" and .Test!=null) | "\(.Package):\(.Test)"' \
| sort -u > tests_by_pkg.txt
```

Captures all failed tests with their packages in one command.

2. **Order Packages**

```bash
cut -d: -f1 tests_by_pkg.txt \
| awk -F/ '{print NF, $0}' \
| sort -n \
| cut -d' ' -f2 \
| uniq > ordered_pkgs.txt
```

Sorts packages by directory depth (leaf packages first).

3. **Iterate and Fix**
For each package in `ordered_pkgs.txt`:

a. Extract its failing tests:

```bash
grep "^$pkg:" tests_by_pkg.txt | cut -d: -f2 > pkg_tests.txt
```

b. For each test in `pkg_tests.txt`:

```bash
go test -run $test -timeout 18s -v $pkg -race
```

* **Diagnose:** Identify root cause from failure output.
* **Check Docs:** Review comments in the related `.go` file and any linked issues (`gh issue view`).

* If test and docs mismatch, **update test** to align with documented behavior.
* Otherwise, **fix implementation** to satisfy both test and documentation.
* If unclear, skip this test and continue.

c. After fixes, rerun the test to confirm it passes.

4. **Report Progress**
Summarize:

* [ OK ] Tests fixed per package
* [WARN] Tests skipped due to unclear requirements

\--- **Iterate and Fix**
For each package in `ordered_pkgs.txt`:

a. Extract its failing tests:

```bash
grep "^$pkg:" tests_by_pkg.txt | cut -d: -f2 > pkg_tests.txt
```

b. For each test in `pkg_tests.txt`:

```bash
go test -run $test -timeout 18s -v $pkg -race
```

* **Diagnose:** Identify root cause from failure output.
* **Check Docs:** Review comments in the related `.go` file and any linked issues (`gh issue view`).

* If test and docs mismatch, **update test** to align with documented behavior.
* Otherwise, **fix implementation** to satisfy both test and documentation.
* If unclear, skip this test and continue.

c. After fixes, rerun the test to confirm it passes.

5. **Report Progress**
After all packages are processed, summarize:

* [ OK ] Tests fixed per package
* [WARN] Tests skipped due to unclear requirements
54 changes: 54 additions & 0 deletions .cursor/rules/go-vet.mdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
---
description: "Run `go vet` on the BitNet packages and correct all reported issues without committing changes."
globs: pkg/bitnet/**/*.go
alwaysApply: false
---

# `go vet` Enforcement Rule

**Purpose:** Identify and fix suspicious code patterns in Go files under `pkg/bitnet` using `go vet`, without automating commits.

## Steps

1. **Run the Vet Tool**

```bash
go vet ./pkg/bitnet/...
```

Review the output for issues such as:

* Incorrect struct tags
* Unhandled errors
* Unused variables or imports
* Printf-style issues

2. **Review Each Finding**
For each reported issue (`file.go:line: description`):

* Open the file at the specified line.
* Understand the root cause of the warning.

3. **Apply Minimal Fixes**

* Modify the code to address the vet warning.
* Examples:

* Remove or use unused imports/variables.
* Add error checks or handle returned errors.
* Correct struct tag formatting (e.g., `json:"name,omitempty"`).
* Use `fmt.Sprintf` placeholders correctly.

4. **Verify Fixes Locally**

* Rerun vet to confirm the issue is resolved:

```bash
go vet ./pkg/bitnet/...
```

## Best Practices

* **Granular Edits:** Only change the lines necessary to satisfy vet.
* **Manual Review:** Inspect diffs before staging to avoid unintended modifications.
* **Developer Control:** After fixes, manually commit and push as desired.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ profiles/
tensor.test

# BitNet model files
pkg/bitnet/internal/assets/models/
pkg/bitnet/assets/models/

math.test
coverage.html

*.txt
Loading