hive-gpu 0.1.7

High-performance GPU acceleration for vector operations with Device Info API (Metal, CUDA, ROCm)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
<!-- RULEBOOK:START -->
# Project Rules

Generated by @hivellm/rulebook
Generated at: 2025-11-03T01:49:55.258Z

<!-- QUALITY_ENFORCEMENT:START -->

# Quality Enforcement Rules


**CRITICAL**: These rules are NON-NEGOTIABLE and MUST be followed without exception.

## Absolute Prohibitions


### Test Bypassing - STRICTLY FORBIDDEN

- NEVER use .skip(), .only(), or .todo() to bypass failing tests
- NEVER comment out failing tests
- NEVER use @ts-ignore, @ts-expect-error, or similar to hide test errors
- NEVER mock/stub functionality just to make tests pass without fixing root cause
- FIX the actual problem causing test failures

### Git Hook Bypassing - STRICTLY FORBIDDEN  

- NEVER use --no-verify flag on git commit
- NEVER use --no-verify flag on git push
- NEVER disable or skip pre-commit hooks
- NEVER disable or skip pre-push hooks
- FIX the issues that hooks are detecting

### Test Implementation - STRICTLY FORBIDDEN

- NEVER create boilerplate tests that don't actually test behavior
- NEVER write tests that always pass regardless of implementation
- NEVER write tests without assertions
- NEVER mock everything to avoid testing real behavior
- WRITE meaningful tests that verify actual functionality

### Problem Solving Approach - REQUIRED

- DO NOT seek the simplest bypass or workaround
- DO NOT be creative with shortcuts that compromise quality
- DO solve problems properly following best practices
- DO use proven, established solutions from decades of experience
- DO fix root causes, not symptoms

## Enforcement


These rules apply to ALL implementations:
- Bug fixes
- New features  
- Refactoring
- Documentation changes
- Any code modifications

**Violation = Implementation Rejected**

<!-- QUALITY_ENFORCEMENT:END -->


## Documentation Standards

**CRITICAL**: Minimize Markdown files. Keep documentation organized.

### Allowed Root-Level Documentation
Only these files are allowed in the project root:
- `README.md` - Project overview and quick start
-`CHANGELOG.md` - Version history and release notes
-`AGENTS.md` - This file (AI assistant instructions)
-`LICENSE` - Project license
-`CONTRIBUTING.md` - Contribution guidelines
-`CODE_OF_CONDUCT.md` - Code of conduct
-`SECURITY.md` - Security policy

### All Other Documentation
**ALL other documentation MUST go in `/docs` directory**:
- `/docs/ARCHITECTURE.md` - System architecture
- `/docs/DEVELOPMENT.md` - Development guide
- `/docs/ROADMAP.md` - Project roadmap
- `/docs/DAG.md` - Component dependencies (DAG)
- `/docs/specs/` - Feature specifications
- `/docs/sdks/` - SDK documentation
- `/docs/protocols/` - Protocol specifications
- `/docs/guides/` - Developer guides
- `/docs/diagrams/` - Architecture diagrams
- `/docs/benchmarks/` - Performance benchmarks
- `/docs/versions/` - Version release reports

## Testing Requirements

**CRITICAL**: All features must have comprehensive tests.

- **Minimum Coverage**: 95%
- **Test Location**: `/tests` directory in project root
- **Test Execution**: 100% of tests MUST pass before moving to next task
- **Test First**: Write tests based on specifications before implementation

## Feature Development Workflow

**CRITICAL**: Follow this workflow for all feature development.

1. **Check Specifications First**:
   - Read `/docs/specs/` for feature specifications
   - Review `/docs/ARCHITECTURE.md` for system design
   - Check `/docs/ROADMAP.md` for implementation timeline
   - Review `/docs/DAG.md` for component dependencies

2. **Implement with Tests**:
   - Write tests in `/tests` directory first
   - Implement feature following specifications
   - Ensure tests pass and meet coverage threshold

3. **Quality Checks**:
   - Run code formatter
   - Run linter (must pass with no warnings)
   - Run all tests (must be 100% passing)
   - Verify coverage meets threshold

4. **Update Documentation**:
   - Update `/docs/ROADMAP.md` progress
   - Update feature specs if implementation differs
   - Document any deviations with justification

## Rules Configuration

Rules can be selectively disabled using `.rulesignore` file in project root.

Example `.rulesignore`:
```
# Ignore coverage requirement
coverage-threshold
# Ignore specific language rules
rust/edition-2024
# Ignore all TypeScript rules
typescript/*
```

<!-- RULEBOOK:END -->


<!-- RUST:START -->

# Rust Project Rules


## Agent Automation Commands


**CRITICAL**: Execute these commands after EVERY implementation (see AGENT_AUTOMATION module for full workflow).

```bash
# Complete quality check sequence:

cargo fmt --all -- --check           # Format check
cargo clippy --workspace --all-targets --all-features -- -D warnings  # Lint
cargo test --workspace --all-features  # All tests (100% pass)
cargo build --release                # Build verification
cargo llvm-cov --all                 # Coverage (95%+ required)

# Security audit:

cargo audit                          # Vulnerability scan
cargo outdated                       # Check outdated deps
```

## Rust Edition and Toolchain


**CRITICAL**: Always use Rust Edition 2024 with nightly toolchain.

- **Edition**: 2024
- **Toolchain**: nightly 1.85+
- **Update**: Run `rustup update nightly` regularly

### Formatting


- Use `rustfmt` with nightly toolchain
- Configuration in `rustfmt.toml` or `.rustfmt.toml`
- Always format before committing: `cargo +nightly fmt --all`
- CI must check formatting: `cargo +nightly fmt --all -- --check`

### Linting


- Use `clippy` with `-D warnings` (warnings as errors)
- Fix all clippy warnings before committing
- Acceptable exceptions must be documented with `#[allow(clippy::...)]` and justification
- CI must enforce clippy: `cargo clippy --workspace -- -D warnings`

### Testing


- **Location**: Tests in `/tests` directory for integration tests
- **Unit Tests**: In same file as implementation with `#[cfg(test)]`
- **Coverage**: Must meet project threshold (default 95%)
- **Tools**: Use `cargo-nextest` for faster test execution
- **Async**: Use `tokio::test` for async tests with Tokio runtime

Example test structure:
```rust
#[cfg(test)]

mod tests {
    use super::*;

    #[test]
    fn test_feature() {
        // Test implementation
    }

    #[tokio::test]
    async fn test_async_feature() {
        // Async test implementation
    }
}
```

## Async Programming


**CRITICAL**: Follow Tokio best practices for async code.

- **Runtime**: Use Tokio for async runtime
- **Blocking**: Never block in async context - use `spawn_blocking` for CPU-intensive tasks
- **Channels**: Use `tokio::sync::mpsc` or `tokio::sync::broadcast` for async communication
- **Timeouts**: Always set timeouts for network operations: `tokio::time::timeout`

Example:
```rust
use tokio::time::{timeout, Duration};

async fn fetch_data() -> Result<Data, Error> {
    timeout(Duration::from_secs(30), async {
        // Network operation
    }).await?
}
```

## Dependency Management


**CRITICAL**: Always verify latest versions before adding dependencies.

### Before Adding Any Dependency


1. **Check Context7 for latest version**:
   - Use MCP Context7 tool if available
   - Search for the crate documentation
   - Verify the latest stable version
   - Review breaking changes and migration guides

2. **Example Workflow**:
   ```
   Adding tokio → Check crates.io and docs.rs
   Adding serde → Verify latest version with security updates
   Adding axum → Check for breaking changes in latest version
   ```

3. **Document Version Choice**:
   - Note why specific version chosen in `Cargo.toml` comments
   - Document any compatibility constraints
   - Update CHANGELOG.md with new dependencies

### Dependency Guidelines


- ✅ Use latest stable versions
- ✅ Check for security advisories: `cargo audit`
- ✅ Prefer well-maintained crates (active development, good documentation)
- ✅ Minimize dependency count
- ✅ Use workspace dependencies for monorepos
- ❌ Don't use outdated versions without justification
- ❌ Don't add dependencies without checking latest version

## Codespell Configuration


**CRITICAL**: Use codespell to catch typos in code and documentation.

Install: `pip install 'codespell[toml]'`

Configuration in `pyproject.toml`:
```toml
[tool.codespell]
skip = "*.lock,*.json,target,node_modules,.git"
ignore-words-list = "crate,ser,deser"
```

Or run with flags:
```bash
codespell \
  --skip="*.lock,*.json,target,node_modules,.git" \
  --ignore-words-list="crate,ser,deser"
```

## Error Handling


- Use `Result<T, E>` for recoverable errors
- Use `thiserror` for custom error types
- Use `anyhow` for application-level error handling
- Document error conditions in function docs
- Never use `unwrap()` or `expect()` in production code without justification

Example:
```rust
use thiserror::Error;

#[derive(Error, Debug)]

pub enum MyError {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    
    #[error("Invalid input: {0}")]
    InvalidInput(String),
}

pub fn process_data(input: &str) -> Result<Data, MyError> {
    // Implementation
}
```

## Documentation


- **Public APIs**: Must have doc comments (`///`)
- **Examples**: Include examples in doc comments
- **Modules**: Document module purpose with `//!`
- **Unsafe**: Always document safety requirements for `unsafe` code
- **Run doctests**: `cargo test --doc`

Example:
```rust
/// Processes the input data and returns a result.
///
/// # Arguments
///
/// * `input` - The input string to process
///
/// # Examples
///
/// ```
/// use mylib::process;
/// let result = process("hello");
/// assert_eq!(result, "HELLO");
/// ```
///
/// # Errors
///
/// Returns `MyError::InvalidInput` if input is empty.
pub fn process(input: &str) -> Result<String, MyError> {
    // Implementation
}
```

## Project Structure


```
project/
├── Cargo.toml          # Package manifest
├── Cargo.lock          # Dependency lock file (commit this)
├── README.md           # Project overview (allowed in root)
├── CHANGELOG.md        # Version history (allowed in root)
├── AGENTS.md          # AI assistant rules (allowed in root)
├── LICENSE            # Project license (allowed in root)
├── CONTRIBUTING.md    # Contribution guidelines (allowed in root)
├── CODE_OF_CONDUCT.md # Code of conduct (allowed in root)
├── SECURITY.md        # Security policy (allowed in root)
├── src/
│   ├── lib.rs          # Library root (for libraries)
│   ├── main.rs         # Binary root (for applications)
│   └── ...
├── tests/              # Integration tests
├── examples/           # Example code
├── benches/            # Benchmarks
└── docs/               # Project documentation
```

## CI/CD Requirements


Must include GitHub Actions workflows for:

1. **Testing** (`rust-test.yml`):
   - Test on ubuntu-latest, windows-latest, macos-latest
   - Use `cargo-nextest` for fast test execution
   - Upload test results

2. **Linting** (`rust-lint.yml`):
   - Format check: `cargo +nightly fmt --all -- --check`
   - Clippy: `cargo clippy --workspace -- -D warnings`
   - All targets: `cargo clippy --workspace --all-targets -- -D warnings`

3. **Codespell** (`codespell.yml`):
   - Check for typos in code and documentation
   - Fail on errors

## Crate Publication


### Publishing to crates.io


**Prerequisites:**
1. Create account at https://crates.io
2. Generate API token: `cargo login`
3. Add `CARGO_TOKEN` to GitHub repository secrets

**Cargo.toml Configuration:**

```toml
[package]
name = "your-crate-name"
version = "1.0.0"
edition = "2024"
authors = ["Your Name <your.email@example.com>"]
license = "MIT OR Apache-2.0"
description = "A short description of your crate"
documentation = "https://docs.rs/your-crate-name"
homepage = "https://github.com/your-org/your-crate-name"
repository = "https://github.com/your-org/your-crate-name"
readme = "README.md"
keywords = ["your", "keywords", "here"]
categories = ["category"]
exclude = [
    ".github/",
    "tests/",
    "benches/",
    "examples/",
    "*.sh",
]

[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
```

**Publishing Workflow:**

1. Update version in Cargo.toml
2. Update CHANGELOG.md
3. Run quality checks:
   ```bash
   cargo fmt --all

   cargo clippy --workspace --all-targets -- -D warnings

   cargo test --all-features

   cargo doc --no-deps --all-features

   ```
4. Create git tag: `git tag v1.0.0 && git push --tags`
5. GitHub Actions automatically publishes to crates.io
6. Or manual publish: `cargo publish`

**Publishing Checklist:**

- ✅ All tests passing (`cargo test --all-features`)
- ✅ No clippy warnings (`cargo clippy -- -D warnings`)
- ✅ Code formatted (`cargo fmt --all -- --check`)
- ✅ Documentation builds (`cargo doc --no-deps`)
- ✅ Version updated in Cargo.toml
- ✅ CHANGELOG.md updated
- ✅ README.md up to date
- ✅ LICENSE file present
- ✅ Package size < 10MB (check with `cargo package --list`)
- ✅ Verify with `cargo publish --dry-run`

**Semantic Versioning:**

Follow [SemVer](https://semver.org/) strictly:
- **MAJOR**: Breaking API changes
- **MINOR**: New features (backwards compatible)
- **PATCH**: Bug fixes (backwards compatible)

**Documentation:**

- Use `///` for public API documentation
- Include examples in doc comments
- Use `#![deny(missing_docs)]` for libraries
- Test documentation examples with `cargo test --doc`

```rust
/// Processes the input data and returns a result.
///
/// # Arguments
///
/// * `input` - The input string to process
///
/// # Examples
///
/// ```
/// use your_crate::process;
///
/// let result = process("hello");
/// assert_eq!(result, "HELLO");
/// ```
///
/// # Errors
///
/// Returns an error if the input is empty.
pub fn process(input: &str) -> Result<String, Error> {
    // Implementation
}
```

<!-- RUST:END -->




<!-- AGENT_AUTOMATION:START -->

# Agent Automation Rules


**CRITICAL**: Mandatory workflow that AI agents MUST execute after EVERY implementation.

## Workflow Overview


After completing ANY feature, bug fix, or code change, execute this workflow in order:

### Step 1: Quality Checks (MANDATORY)


Run these checks in order - ALL must pass:

```bash
1. Type check (if applicable)
2. Lint (MUST pass with ZERO warnings)
3. Format code
4. Run ALL tests (MUST pass 100%)
5. Verify coverage meets threshold (default 95%)
```

**Language-specific commands**: See your language template (TYPESCRIPT, RUST, PYTHON, etc.) for exact commands.

**IF ANY CHECK FAILS:**
- ❌ STOP immediately
- ❌ DO NOT proceed
- ❌ DO NOT commit
- ✅ Fix the issue first
- ✅ Re-run ALL checks

### Step 2: Security & Dependency Audits

```bash
# Check for vulnerabilities (language-specific)
# Check for outdated dependencies (informational)
# Find unused dependencies (optional)
```

**Language-specific commands**: See your language template for audit commands.

**IF VULNERABILITIES FOUND:**
- ✅ Attempt automatic fix
- ✅ Document if auto-fix fails
- ✅ Include in Step 5 report
- ❌ Never ignore critical/high vulnerabilities without user approval

### Step 3: Update OpenSpec Tasks


If `openspec/` directory exists:

```bash
# Mark completed tasks as [DONE]

# Update in-progress tasks

# Add new tasks if discovered

# Update progress percentages

# Document deviations or blockers

```

### Step 4: Update Documentation


```bash
# Update ROADMAP.md (if feature is milestone)

# Update CHANGELOG.md (conventional commits format)

# Update feature specs (if implementation differs)

# Update README.md (if public API changed)

```

### Step 5: Git Commit


**ONLY after ALL above steps pass:**

```bash
git add .
git commit -m "<type>(<scope>): <description>

- Detailed change 1
- Detailed change 2
- Tests: [describe coverage]
- Coverage: X% (threshold: 95%)

Closes #<issue> (if applicable)"
```

**Commit Types**: `feat`, `fix`, `docs`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`

### Step 6: Report to User


```
✅ Implementation Complete

📝 Changes:
- [List main changes]

🧪 Quality Checks:
- ✅ Type check: Passed
- ✅ Linting: Passed (0 warnings)
- ✅ Formatting: Applied
- ✅ Tests: X/X passed (100%)
- ✅ Coverage: X% (threshold: 95%)

🔒 Security:
- ✅ No vulnerabilities

📊 OpenSpec:
- ✅ Tasks updated
- ✅ Progress: X% → Y%

📚 Documentation:
- ✅ CHANGELOG.md updated
- ✅ [other docs updated]

💾 Git:
- ✅ Committed: <commit message>
- ✅ Hash: <commit hash>

📋 Next Steps:
- [ ] Review changes
- [ ] Push to remote (if ready)
```

## Automation Exceptions

Skip steps ONLY when:

1. **Exploratory Code**: User says "experimental", "draft", "try"
   - Still run quality checks
   - Don't commit

2. **User Explicitly Requests**: User says "skip tests", "no commit"
   - Only skip requested step
   - Warn about skipped steps

3. **Emergency Hotfix**: Critical production bug
   - Run minimal checks
   - Document technical debt

**In ALL other cases: Execute complete workflow**

## Error Recovery

If workflow fails 3+ times:

```bash
1. Create backup branch
2. Reset to last stable commit
3. Report to user with error details
4. Request guidance or try alternative approach
```

## Best Practices


### DO's ✅

- ALWAYS run complete workflow
- ALWAYS update OpenSpec and documentation
- ALWAYS use conventional commits
- ALWAYS report summary to user
- ASK before skipping steps

### DON'Ts ❌

- NEVER skip quality checks without permission
- NEVER commit failing tests
- NEVER commit linting errors
- NEVER skip documentation updates
- NEVER assume user wants to skip automation
- NEVER commit debug code or secrets

## Summary


**Complete workflow after EVERY implementation:**

1. ✅ Quality checks (type, lint, format, test, coverage)
2. ✅ Security audit
3. ✅ Update OpenSpec tasks
4. ✅ Update documentation
5. ✅ Git commit (conventional format)
6. ✅ Report summary to user

**Only skip with explicit user permission and document why.**

<!-- AGENT_AUTOMATION:END -->



<!-- VECTORIZER:START -->

# Vectorizer Instructions


**CRITICAL**: Use MCP Vectorizer as primary data source for project information instead of file reading.

## Core Functions


### Search

```
mcp_vectorizer_search - Multiple strategies:
  - intelligent: AI-powered with query expansion
  - semantic: Advanced with reranking  
  - contextual: Context-aware with filtering
  - multi_collection: Cross-project search
  - batch: Parallel queries
  - by_file_type: Filter by extension (.rs, .ts, .py)
```

### File Operations
```
get_content - Retrieve file without disk I/O
list_files - List indexed files with metadata
get_summary - File summaries (extractive/structural)
get_chunks - Progressive reading of large files
get_outline - Project structure overview
get_related - Find semantically related files
```

### Discovery
```
full_pipeline - Complete discovery with scoring
broad_discovery - Multi-query with deduplication
semantic_focus - Deep semantic search
expand_queries - Generate query variations
```

## When to Use

| Task | Tool |
|------|------|
| Explore unfamiliar code | intelligent search |
| Read file | get_content |
| Understand structure | get_outline |
| Find related files | get_related |
| Read large file | get_chunks |
| Complex question | full_pipeline |

## Best Practices

✅ **DO:**
- Start with intelligent search for exploration
- Use file_operations to avoid disk I/O
- Batch queries for related items
- Set similarity thresholds (0.6-0.8)
- Use specific collections when known

❌ **DON'T:**
- Read files from disk when available in vectorizer
- Use sequential searches (batch instead)
- Skip similarity thresholds
- Search entire codebase when collection is known

<!-- VECTORIZER:END -->


<!-- OPENSPEC:START -->
# OpenSpec Instructions

**CRITICAL**: Use OpenSpec for spec-driven development of new features and breaking changes.

## When to Use

Create proposal for:
- ✅ New features/capabilities
- ✅ Breaking changes
- ✅ Architecture changes  
- ✅ Performance/security work

Skip for:
- ❌ Bug fixes (restore intended behavior)
- ❌ Typos, formatting, comments
- ❌ Dependency updates (non-breaking)

## Task Creation Guidelines

**CRITICAL**: Before creating ANY OpenSpec task, you MUST:

1. **Check Context7 MCP** (if available):
   - Use Context7 to review documentation and best practices for the technology/library involved
   - Verify the correct task format and structure
   - Review existing task examples from official documentation
   - Most AIs create tasks in the wrong format - Context7 helps prevent this

2. **Validate Format Requirements**:
   - Ensure scenario format uses `#### Scenario:` (4 hashtags)
   - Follow SHALL/MUST conventions for requirements
   - Include proper WHEN/THEN structure

**Why This Matters:**
Many AI assistants create OpenSpec tasks in incorrect formats, causing validation failures and rework. Using Context7 to review proper task structures BEFORE creation saves time and ensures consistency.

## Quick Start

```bash
# 1. Check existing
openspec list --specs
openspec list

# 2. Create change
CHANGE=add-your-feature
mkdir -p openspec/changes/$CHANGE/specs/capability-name

# 3. Create files
# - proposal.md (why, what, impact)
# - tasks.md (implementation checklist)
# - specs/capability-name/spec.md (deltas)

# 4. Validate
openspec validate $CHANGE --strict
```

## Spec Format


**CRITICAL**: Scenario format MUST be exact:

```markdown
## ADDED Requirements

### Requirement: Feature Name

The system SHALL provide...

#### Scenario: Success case

- **WHEN** user performs action
- **THEN** expected result occurs
```

❌ **WRONG:**
```markdown
- **Scenario: Login**      # NO - bullet
**Scenario**: Login        # NO - bold
### Scenario: Login        # NO - 3 hashtags
```

✅ **CORRECT:**
```markdown
#### Scenario: User login   # YES - 4 hashtags

```

## Three-Stage Workflow


### Stage 1: Create

1. Read `openspec/project.md`
2. Choose verb-led `change-id` (e.g., `add-auth`, `update-api`)
3. Create `proposal.md`, `tasks.md`, delta specs
4. Validate: `openspec validate [id] --strict`
5. Get approval

### Stage 2: Implement  

1. Read `proposal.md`, `tasks.md`
2. Implement tasks
3. Run AGENT_AUTOMATION workflow
4. Update tasks as complete
5. Document commit hash in tasks.md

### Stage 3: Archive

After deployment:
```bash
openspec archive [change] --yes
```

## Commands


```bash
openspec list                    # Active changes
openspec list --specs            # All capabilities
openspec show [item]             # View details
openspec validate [change] --strict  # Validate
openspec diff [change]           # Show changes
openspec archive [change] --yes  # Complete
```

## Best Practices


✅ **DO:**
- **Check Context7 MCP before creating tasks** (prevents format errors)
- One requirement per concern
- At least one scenario per requirement
- Use SHALL/MUST for normative requirements
- Validate before committing
- Keep changes focused and small

❌ **DON'T:**
- Create tasks without checking Context7 MCP first
- Mix multiple features in one change
- Skip scenario definitions
- Use wrong scenario format
- Start implementation before approval

## Integration with AGENT_AUTOMATION


OpenSpec drives implementation. AGENT_AUTOMATION enforces quality:

```
1. Create spec → Validate → Approve
2. Implement → Run AGENT_AUTOMATION
3. Update tasks.md with commit hash
4. Archive when deployed
```

<!-- OPENSPEC:END -->



<!-- CONTEXT7:START -->
# Context7 Instructions

**CRITICAL**: Use MCP Context7 to access up-to-date library documentation before adding dependencies.

## Core Functions

### 1. resolve-library-id
Resolve a package name to Context7-compatible library ID:
```
resolve-library-id("tokio") → "/tokio-rs/tokio"
resolve-library-id("react") → "/facebook/react"
```

### 2. get-library-docs
Fetch documentation with optional topic filter:
```
get-library-docs("/tokio-rs/tokio", topic="async")
```

## Workflow

**Before adding ANY dependency:**
```
1. resolve-library-id(library_name)
2. get-library-docs(library_id) 
3. Check latest version and security
4. Add dependency with correct version
5. Document choice in commit
```

**Before updating major version:**
```
1. get-library-docs for current version
2. get-library-docs for target version
3. Review breaking changes
4. Plan migration
```

## Best Practices

✅ **DO:**
- Always check Context7 before adding dependencies
- Use topic parameter for specific info
- Document version choices
- Review security advisories

❌ **DON'T:**
- Add dependencies without checking latest version
- Skip migration guides on major updates
- Ignore security warnings

<!-- CONTEXT7:END -->



<!-- GIT:START -->

**AI Assistant Git Push Mode**: MANUAL

**CRITICAL**: Never execute `git push` commands automatically.
Always provide push commands for manual execution by the user.

Example:
```
✋ MANUAL ACTION REQUIRED:
Run these commands manually (SSH password may be required):
  git push origin main
  git push origin v1.0.0
```

# Git Workflow Rules

**CRITICAL**: Specific rules and patterns for Git version control workflow.

## Git Workflow Overview

This project follows a strict Git workflow to ensure code quality and proper version control.

**NEVER commit code without tests passing. NEVER create tags without full quality checks.**

## Initial Repository Setup

### New Project Initialization

**⚠️ CRITICAL**: Only run initialization commands if `.git` directory does NOT exist!

```bash
# Check if Git repository already exists
if [ -d .git ]; then
  echo "❌ Git repository already initialized. Skipping git init."
  echo "Current status:"
  git status
  git remote -v
  exit 0
fi

# If no .git directory exists, initialize:

# Initialize Git repository
git init

# Add all files
git add .

# Initial commit
git commit -m "chore: Initial project setup"

# Rename default branch to main (GitHub standard)
git branch -M main

# Add remote (if applicable)
git remote add origin <repository-url>
```

**AI Assistant Behavior:**

```
BEFORE running any Git initialization commands:

1. Check if .git directory exists
2. If exists:
   ✅ Repository already configured
   ❌ DO NOT run: git init
   ❌ DO NOT run: git branch -M main
   ✅ Check status: git status
   ✅ Show remotes: git remote -v
   
3. If not exists:
   ✅ Safe to initialize
   ✅ Run full initialization sequence
```

## AI Assistant Git Checks

**CRITICAL**: AI assistants MUST perform these checks before Git operations:

### Automatic Checks

```bash
# 1. Check if Git repository exists
if [ ! -d .git ]; then
  echo "No Git repository found."
  # Ask user if they want to initialize
fi

# 2. Check if there are unstaged changes
git status --short

# 3. Check current branch
CURRENT_BRANCH=$(git branch --show-current)
echo "On branch: $CURRENT_BRANCH"

# 4. Check if remote exists
git remote -v

# 5. Check for unpushed commits
git log origin/main..HEAD --oneline 2>/dev/null
```

### Before Git Commands


**NEVER execute if `.git` directory exists:**
- `git init` - Repository already initialized
-`git branch -M main` - Branch may already be configured
-`git remote add origin` - Remote may already exist (check first with `git remote -v`)
-`git config user.name/email` - User configuration is personal
- ❌ Reconfiguration commands - Repository is already set up

**ALWAYS safe to execute:**
- `git status` - Check repository state
-`git add` - Stage changes
-`git commit` - Create commits (after quality checks)
-`git log` - View history
-`git diff` - View changes
-`git branch` - List branches
-`git tag` - Create tags (after quality checks)

**Execute with caution (check first):**
- ⚠️ `git push` - Follow push mode configuration
- ⚠️ `git pull` - May cause merge conflicts
- ⚠️ `git merge` - May cause conflicts
- ⚠️ `git rebase` - Can rewrite history
- ⚠️ `git reset --hard` - Destructive, only for rollback
- ⚠️ `git push --force` - NEVER on main/master

### Repository Detection


**AI Assistant MUST check:**

```bash
# Before ANY Git operation:


# 1. Does .git exist?

if [ -d .git ]; then
  echo "✅ Git repository exists"
  
  # 2. Check current state
  git status
  
  # 3. Check branch
  BRANCH=$(git branch --show-current)
  echo "On branch: $BRANCH"
  
  # 4. Check remote
  REMOTE=$(git remote -v)
  if [ -z "$REMOTE" ]; then
    echo "⚠️  No remote configured"
  else
    echo "Remote: $REMOTE"
  fi
  
  # 5. Proceed with normal Git operations
else
  echo "⚠️  No Git repository found"
  echo "Ask user if they want to initialize Git"
fi
```

## Daily Development Workflow


### 1. Before Making Changes


**CRITICAL**: Always check current state:

```bash
# Check current branch and status

git status

# Ensure you're on the correct branch

git branch

# Pull latest changes if working with team (use --ff-only for safety)

git pull --ff-only origin main
```

**Git Safety**: Use `--ff-only` to prevent unexpected merge commits and maintain linear history.

### 2. Making Changes


**CRITICAL**: Commit after every important implementation:

```bash
# After implementing a feature/fix:


# 1. Run ALL quality checks FIRST

npm run lint           # or equivalent for your language
npm run type-check     # TypeScript/typed languages
npm test              # ALL tests must pass
npm run build         # Ensure build succeeds

# 2. If ALL checks pass, stage changes

git add .

# 3. Commit with conventional commit message

git commit -m "feat: Add user authentication

- Implement login/logout functionality
- Add JWT token management
- Include comprehensive tests (95%+ coverage)
- Update documentation"

# Alternative for smaller changes:

git commit -m "fix: Correct validation logic in user form"

# For signed commits (recommended for production):

git commit -S -m "feat: Add feature"
```

## Advanced Git Safeguards


### Safe Push Operations


```bash
# NEVER use git push --force on main/master branches

# Instead, use --force-with-lease which prevents overwriting others' work:


# Force push with safety check (only updates if no one else pushed)

git push --force-with-lease origin feature-branch

# Regular push is always safest

git push origin main
```

### Commit Signing


```bash
# Sign commits with GPG for verified commits

# Set GPG key: git config --global user.signingkey <KEY_ID>

git commit -S -m "feat: Signed commit"

# Configure to always sign commits

git config --global commit.gpgsign true
```

### Branch Protection (Recommended Settings)


For GitHub/GitLab repositories, configure branch protection rules:

**For main/master branch:**
- Require pull request reviews
- Require status checks to pass
- Require branches to be up to date
- Do not allow force pushes
- Do not allow deletions
- Require signed commits (optional but recommended)

### Destructive Operation Warnings


**NEVER run these on main/master:**
- `git push --force` - Use `--force-with-lease` instead
-`git reset --hard` - Destructive, use only on feature branches
-`git rebase` main into feature - Causes rewriting of main history

### Pre-Push Checklist


Before pushing any changes, verify:

```bash
✅ Checklist before push:
- [ ] All quality checks passed locally
- [ ] Tests pass with 100% success rate
- [ ] Coverage meets threshold (95%+)
- [ ] Linting passes with 0 warnings
- [ ] Build succeeds without errors
- [ ] No security vulnerabilities in dependencies
- [ ] Documentation updated if API changed
- [ ] OpenSpec tasks marked complete if applicable
- [ ] Conventional commit format used
- [ ] Commit hash verified: git rev-parse HEAD
- [ ] Similar changes passed CI before
- [ ] No console.log or debug code
- [ ] No credentials or secrets in code
```

**Only provide push command if ALL items checked.**

### 3. Pushing Changes

**⚠️ IMPORTANT**: Pushing is OPTIONAL and depends on your setup.

```bash
# IF you have passwordless SSH or want to push:
git push origin main

# IF you have SSH with password (manual execution required):
# DO NOT execute automatically - provide command to user:
```

**For users with SSH password authentication:**
```
✋ MANUAL ACTION REQUIRED:

Run this command manually (requires SSH password):
git push origin main
```

**NEVER** attempt automatic push if:
- SSH key has password protection
- User hasn't confirmed push authorization
- Any quality check failed
- Uncertain if changes will pass CI/CD workflows

## Conventional Commits


**MUST** follow conventional commit format:

```bash
# Format: <type>(<scope>): <subject>

#
# <body>

#
# <footer>


# Types:

feat:     # New feature
fix:      # Bug fix
docs:     # Documentation only
style:    # Code style (formatting, missing semi-colons, etc)
refactor: # Code refactoring
perf:     # Performance improvement
test:     # Adding tests
build:    # Build system changes
ci:       # CI/CD changes
chore:    # Maintenance tasks

# Examples:

git commit -m "feat(auth): Add OAuth2 login support"
git commit -m "fix(api): Handle null response in user endpoint"
git commit -m "docs: Update README with installation steps"
git commit -m "test: Add integration tests for payment flow"
git commit -m "chore: Update dependencies to latest versions"
```

## Version Management


### Creating New Version


**CRITICAL**: Full quality gate required before versioning!

```bash
# 1. MANDATORY: Run complete quality suite

npm run lint          # Must pass with no warnings
npm test             # Must pass 100%
npm run type-check   # Must pass (if applicable)
npm run build        # Must succeed
npx codespell        # Must pass (if configured)

# 2. Update version in package.json/Cargo.toml/etc

# Use semantic versioning:

# - MAJOR: Breaking changes (1.0.0 -> 2.0.0)

# - MINOR: New features, backwards compatible (1.0.0 -> 1.1.0)

# - PATCH: Bug fixes (1.0.0 -> 1.0.1)


# 3. Update CHANGELOG.md

# Document all changes in this version:

## [1.2.0] - 2024-01-15

### Added

- New feature X
- New feature Y

### Fixed

- Bug in component Z

### Changed

- Refactored module A

# 4. Commit version changes

git add .
git commit -m "chore: Release version 1.2.0

- Updated version to 1.2.0
- Updated CHANGELOG.md with release notes"

# 5. Create annotated tag

git tag -a v1.2.0 -m "Release version 1.2.0

Major changes:
- Feature X
- Feature Y
- Bug fix Z

All tests passing ✅
Coverage: 95%+ ✅
Linting: Clean ✅
Build: Success ✅"

# 6. OPTIONAL: Push tag (manual if SSH password)

# Only if you're CERTAIN it will pass CI/CD workflows!

```

**For users requiring manual push:**
```
✋ MANUAL ACTIONS REQUIRED:

1. Verify all quality checks passed locally
2. Push commits:
   git push origin main

3. Push tag:
   git push origin v1.2.0

Note: Tag push will trigger CI/CD workflows and may create GitHub release.
Only push if you're confident all checks will pass.
```

## Quality Gate Enforcement


**CRITICAL**: Pre-commit checks MUST match GitHub Actions workflow commands to prevent CI/CD failures.

### Language-Specific Pre-Commit Commands


**The commands you run locally MUST be identical to those in your GitHub Actions workflows.**

#### TypeScript/JavaScript Projects


```bash
# These commands MUST match .github/workflows/*.yml

# 1. Type check (matches workflow)

npm run type-check        # Must match workflow exactly

# 2. Lint (matches workflow)

npm run lint              # Must match workflow exactly

# 3. Format check (matches workflow)

npx prettier --check 'src/**/*.ts' 'tests/**/*.ts'  # Must match workflow

# 4. Tests (matches workflow)

npm test                  # Must match workflow exactly

# 5. Build (matches workflow)

npm run build             # Must match workflow exactly

# If ANY fails: ❌ DO NOT COMMIT - Fix first!

```

#### Rust Projects


```bash
# These commands MUST match .github/workflows/*.yml

# 1. Format check (matches workflow)

cargo fmt --all -- --check

# 2. Clippy (matches workflow)

cargo clippy --all-targets --all-features -- -D warnings

# 3. Tests (matches workflow)

cargo test --all-features

# 4. Build (matches workflow)

cargo build --release

# If ANY fails: ❌ DO NOT COMMIT - Fix first!

```

#### Python Projects


```bash
# These commands MUST match .github/workflows/*.yml

# 1. Format check (matches workflow)

black --check .

# 2. Lint (matches workflow)

ruff check .

# 3. Type check (matches workflow)

mypy .

# 4. Tests (matches workflow)

pytest

# If ANY fails: ❌ DO NOT COMMIT - Fix first!

```

### Before ANY Commit


**MANDATORY CHECKS**:

```bash
# Checklist - ALL must pass:

☐ Code formatted
☐ Linter passes (no warnings)
☐ Type check passes
☐ ALL tests pass (100%)
☐ Coverage meets threshold (95%+)
☐ Build succeeds
☐ No console errors/warnings

# Run quality check script:

npm run quality-check  # or equivalent

# If ANY check fails:

# ❌ DO NOT COMMIT

# ❌ FIX THE ISSUES FIRST

```

### Before Tag Creation


**MANDATORY CHECKS** (even stricter):

```bash
# Extended checklist - ALL must pass:

☐ All pre-commit checks passed
☐ Codespell passes (no typos)
☐ Security audit clean
☐ Dependencies up to date
☐ Documentation updated
☐ CHANGELOG.md updated
☐ Version bumped correctly
☐ All workflows would pass

# Run comprehensive check:

npm run lint
npm test
npm run type-check
npm run build
npx codespell
npm audit

# Only create tag if everything is green!

```

## Error Recovery & Rollback


### When Implementation Is Failing


If the AI is making repeated mistakes and user is frustrated:

```bash
# 1. Identify last stable commit

git log --oneline -10

# 2. Create backup branch of current work

git branch backup-failed-attempt

# 3. Hard reset to last stable version

git reset --hard <last-stable-commit-hash>

# 4. Verify stability

npm test
npm run build

# 5. Reimplement from scratch using DIFFERENT approach

# ⚠️ DO NOT repeat the same techniques that failed before

# ⚠️ Review AGENTS.md for alternative patterns

# ⚠️ Consider different architecture/design


# 6. After successful reimplementation

git branch -D backup-failed-attempt  # Delete backup if no longer needed
```

### Undo Last Commit (Not Pushed)


```bash
# Keep changes, undo commit

git reset --soft HEAD~1

# Discard changes completely

git reset --hard HEAD~1
```

### Revert Pushed Commit


```bash
# Create revert commit

git revert <commit-hash>

# Then push (manual if SSH password)

```

## Branch Strategy


### Feature Branches


```bash
# Create feature branch

git checkout -b feature/user-authentication

# Work on feature...

# Commit regularly with quality checks


# When feature complete and tested:

git checkout main
git merge feature/user-authentication

# Delete feature branch

git branch -d feature/user-authentication
```

### Hotfix Workflow


```bash
# Critical bug in production

git checkout -b hotfix/critical-security-fix

# Fix the bug

# MUST include tests

# MUST pass all quality checks


git commit -m "fix: Critical security vulnerability in auth

- Patch authentication bypass
- Add regression tests
- Update security documentation"

# Merge to main

git checkout main
git merge hotfix/critical-security-fix

# Tag immediately if production fix

git tag -a v1.2.1 -m "Hotfix: Security patch"

# Manual push if required

```

## CRITICAL RESTRICTIONS - HUMAN AUTHORIZATION REQUIRED


**⚠️ IMPERATIVE RULES - THESE ARE NON-NEGOTIABLE ⚠️**

### Destructive Git Operations


**ABSOLUTELY FORBIDDEN without explicit human authorization:**

```
❌ NEVER execute: git checkout
   ✋ ALWAYS ask user: "Do you want to checkout [branch/commit]? [Y/n]"
   ✅ Only execute after explicit user confirmation
   
❌ NEVER execute: git reset
   ✋ ALWAYS ask user: "Do you want to reset to [commit]? This may lose changes. [Y/n]"
   ✅ Only execute after explicit user confirmation
   ⚠️  Explain consequences before executing
```

**Rationale**: These commands can cause data loss. Human oversight is mandatory.

### Merge Conflict Resolution


**When merge conflicts occur:**

```
❌ NEVER attempt to resolve conflicts by editing files automatically
❌ NEVER commit merged files without human review
✅ ALWAYS stop and request human assistance
✅ ALWAYS provide conflict locations and context
✅ ALWAYS wait for human to resolve manually

Message to user:
"⚠️ Merge conflict detected in the following files:
- [list of conflicted files]

Please resolve these conflicts manually. I cannot auto-resolve merge conflicts.

To resolve:
1. Open the conflicted files
2. Look for conflict markers (<<<<<<<, =======, >>>>>>>)
3. Choose the correct version or merge manually
4. Remove conflict markers
5. Run: git add <resolved-files>
6. Run: git commit

Let me know when you're done, and I can help with the next steps."
```

**Rationale**: Merge conflicts require human judgment about which code to keep.

### Commit Frequency Management


**⚠️ IMPORTANT: Reduce excessive commits**

```
❌ DO NOT commit after every small change
❌ DO NOT create multiple commits for the same logical feature
✅ COMMIT only when:
   - A complete feature is implemented and tested
   - A significant bug fix is completed
   - A major refactoring is done
   - Before creating a version tag
   - User explicitly requests a commit
   
✅ GROUP related changes into meaningful commits
✅ USE conventional commit messages that describe the full scope

Example of GOOD commit frequency:
- Implement entire authentication system → 1 commit
- Add login, logout, and session management → 1 commit
- Complete feature with tests and docs → 1 commit

Example of BAD commit frequency (AVOID):
- Add login function → commit
- Add logout function → commit  
- Add session check → commit
- Fix typo → commit
- Update comment → commit
```

**Rationale**: Too many commits pollute git history and make it harder to track meaningful changes.

### Feature Branch Strategy

**BEFORE starting ANY new task or feature:**

```
✋ ALWAYS ask user FIRST:
"Should I create a separate branch for this feature/task? [Y/n]

Options:
1. Create feature branch: git checkout -b feature/[name]
2. Work directly on current branch
3. Create hotfix branch: git checkout -b hotfix/[name]

What would you prefer?"

✅ Wait for user decision
✅ Respect user's branching strategy
❌ NEVER assume to work on main without asking
❌ NEVER create branches without permission

If user says YES to branch:
  → Create branch with descriptive name
  → Work on that branch
  → Ask before merging back to main
  
If user says NO to branch:
  → Proceed on current branch
  → Be extra careful with commits
```

**Rationale**: Branching strategy varies by team and project. Always confirm with the human first.

## Critical AI Assistant Rules


### Repository Initialization


**BEFORE any `git init` or setup commands:**

```
1. Check for .git directory existence
2. If .git exists:
   - ❌ STOP - Repository already configured
   - ❌ DO NOT run git init
   - ❌ DO NOT run git config
   - ❌ DO NOT run git branch -M
   - ❌ DO NOT reconfigure anything
   - ✅ Use existing repository as-is
   
3. If .git does NOT exist:
   - ✅ Ask user if they want Git initialization
   - ✅ Run initialization sequence if approved
```

### Push Command Behavior

**Based on configured push mode:**

```
Manual Mode (DEFAULT):
  ❌ NEVER execute: git push
  ✅ ALWAYS provide: "Run manually: git push origin main"
  
Prompt Mode:
  ⚠️  ALWAYS ask first: "Ready to push. Proceed? [Y/n]"
  ✅ Execute only if user confirms
  
Auto Mode:
  ⚠️  Check quality first
  ⚠️  Only if 100% confident
  ✅ Execute if all checks passed
```

### Quality Gate Enforcement


**MANDATORY checks before commit:**

```bash
# Run in this exact order:

1. npm run lint          # or language equivalent
2. npm run type-check    # if applicable
3. npm test             # ALL tests must pass
4. npm run build        # must succeed

# If ANY fails:

❌ STOP - DO NOT commit
❌ Fix issues first
❌ Re-run all checks

# If ALL pass:

✅ Safe to commit
✅ Proceed with git add and commit
```

**MANDATORY checks before tag:**

```bash
# Extended checks for version tags:

1. All commit checks above +
2. npx codespell        # no typos
3. npm audit            # no vulnerabilities
4. CHANGELOG.md updated
5. Version bumped correctly
6. Documentation current

# If ANY fails:

❌ STOP - DO NOT create tag
❌ Fix issues
❌ Re-verify everything

# Only create tag if 100% green!

```

## Best Practices


### DO's ✅


- **ALWAYS** check if .git exists before init commands
- **ALWAYS** run tests before commit
- **ALWAYS** use conventional commit messages
- **ALWAYS** update CHANGELOG for versions
- **ALWAYS** ask before executing `git checkout`
- **ALWAYS** ask before executing `git reset`
- **ALWAYS** ask user if a feature branch should be created before starting tasks
- **ALWAYS** request human assistance when merge conflicts occur
- **COMMIT** only when complete features/fixes are done (not for every small change)
- **TAG** releases with semantic versions
- **VERIFY** quality gates before tagging
- **DOCUMENT** breaking changes clearly
- **REVERT** when implementation is failing repeatedly
- **ASK** user before automatic push
- **PROVIDE** manual commands for SSH password users
- **CHECK** repository state before operations
- **RESPECT** existing Git configuration
- **GROUP** related changes into meaningful commits

### DON'Ts ❌


- **NEVER** run `git init` if .git exists
- **NEVER** run `git config` (user-specific)
- **NEVER** run `git checkout` without explicit user authorization
- **NEVER** run `git reset` without explicit user authorization
- **NEVER** auto-resolve merge conflicts by editing files
- **NEVER** commit merged files without human review
- **NEVER** create excessive commits for small changes
- **NEVER** assume branching strategy - always ask user first
- **NEVER** reconfigure existing repository
- **NEVER** commit without passing tests
- **NEVER** commit with linting errors
- **NEVER** commit with build failures
- **NEVER** create tag without quality checks
- **NEVER** push automatically with SSH password
- **NEVER** push if uncertain about CI/CD success
- **NEVER** commit console.log/debug code
- **NEVER** commit credentials or secrets
- **NEVER** force push to main/master
- **NEVER** rewrite published history
- **NEVER** skip hooks (--no-verify)
- **NEVER** assume repository configuration

## SSH Configuration


### For Users with SSH Password


If your SSH key has password protection:

**Configuration in AGENTS.md or project settings:**

```yaml
git_workflow:
  auto_push: false
  push_mode: "manual"
  reason: "SSH key has password protection"
```

**AI Assistant Behavior:**
- ✅ Provide push commands in chat
- ✅ Wait for user manual execution
- ❌ Never attempt automatic push
- ❌ Never execute git push commands

### For Users with Passwordless SSH


```yaml
git_workflow:
  auto_push: true  # or prompt each time
  push_mode: "auto"
```

## Git Hooks


### Pre-commit Hook


Create `.git/hooks/pre-commit`:

```bash
#!/bin/sh


echo "Running pre-commit checks..."

# Run linter

npm run lint
if [ $? -ne 0 ]; then
  echo "❌ Linting failed. Commit aborted."
  exit 1
fi

# Run tests

npm test
if [ $? -ne 0 ]; then
  echo "❌ Tests failed. Commit aborted."
  exit 1
fi

# Run type check (if applicable)

if command -v tsc &> /dev/null; then
  npm run type-check
  if [ $? -ne 0 ]; then
    echo "❌ Type check failed. Commit aborted."
    exit 1
  fi
fi

echo "✅ All pre-commit checks passed!"
exit 0
```

### Pre-push Hook


Create `.git/hooks/pre-push`:

```bash
#!/bin/sh


echo "Running pre-push checks..."

# Run full test suite

npm test
if [ $? -ne 0 ]; then
  echo "❌ Tests failed. Push aborted."
  exit 1
fi

# Run build

npm run build
if [ $? -ne 0 ]; then
  echo "❌ Build failed. Push aborted."
  exit 1
fi

echo "✅ All pre-push checks passed!"
exit 0
```

Make hooks executable:
```bash
chmod +x .git/hooks/pre-commit
chmod +x .git/hooks/pre-push
```

## CI/CD Integration


### Before Providing Push Commands


**CRITICAL**: Only suggest push if confident about CI/CD success:

```
✅ Provide push command if:
- All local tests passed
- All linting passed
- Build succeeded
- Coverage meets threshold
- No warnings or errors
- Code follows AGENTS.md standards
- Similar changes passed CI/CD before

❌ DO NOT provide push command if:
- ANY quality check failed
- Uncertain about CI/CD requirements
- Making experimental changes
- First time working with this codebase
- User seems uncertain

Instead say:
"I recommend running the full CI/CD pipeline locally first to ensure 
the changes will pass. Once confirmed, you can push manually."
```

## GitHub MCP Server Integration


**If GitHub MCP Server is available**, use it for automated workflow monitoring.

### Workflow Validation After Push


```
After every git push (manual or auto):

1. Wait 5-10 seconds for workflows to trigger

2. Check workflow status via GitHub MCP:
   - List workflow runs for latest commit
   - Check status of each workflow

3. If workflows are RUNNING:
   ⏳ Report: "CI/CD workflows in progress..."
   ✅ Continue with other tasks
   ✅ Check again in next user interaction
   
4. If workflows COMPLETED:
   - All passed: ✅ Report success
   - Some failed: ❌ Fetch errors and fix

5. If workflows FAILED:
   a. Fetch complete error logs via GitHub MCP
   b. Display errors to user
   c. Analyze against AGENTS.md standards
   d. Propose specific fixes
   e. Implement fixes
   f. Run local quality checks
   g. Commit fixes
   h. Provide push command for retry
```

### Next Interaction Check

```
On every user message after a push:

if (github_mcp_available && last_push_timestamp) {
  // Check workflow status
  const status = await checkWorkflows();
  
  if (status.running) {
    console.log('⏳ CI/CD still running, will check later');
  } else if (status.failed) {
    console.log('❌ CI/CD failures detected!');
    await analyzeAndFixErrors(status.errors);
  } else {
    console.log('✅ All CI/CD workflows passed!');
  }
}
```

### Error Analysis Flow


```
When workflow fails:

1. Fetch error via GitHub MCP:
   - Workflow name
   - Job name  
   - Failed step
   - Error output
   - Full logs

2. Categorize error:
   - Test failure → Fix test or implementation
   - Lint error → Format/fix code style
   - Build error → Fix compilation issues
   - Type error → Fix type definitions
   - Coverage error → Add more tests

3. Fix following AGENTS.md:
   - Apply correct pattern from AGENTS.md
   - Add tests if needed
   - Verify locally before committing

4. Commit fix:
   git commit -m "fix: Resolve CI/CD failure - [specific issue]"

5. Provide push command:
   "Ready to retry. Run: git push origin main"

6. After next push:
   - Monitor again
   - Verify fix worked
```

### CI/CD Confidence Check

**Before suggesting push:**

```
Assess confidence in CI/CD success:

HIGH confidence (safe to push):
✅ All local checks passed
✅ Similar changes passed CI before
✅ No experimental changes
✅ Follows AGENTS.md exactly
✅ Comprehensive tests
✅ No unusual patterns

MEDIUM confidence (verify first):
⚠️ First time with this pattern
⚠️ Modified build configuration
⚠️ Changed dependencies
⚠️ Cross-platform concerns
→ Suggest: "Let's verify locally first"

LOW confidence (don't push yet):
❌ Experimental implementation
❌ Skipped some tests
❌ Uncertain about compatibility
❌ Modified CI/CD files
→ Say: "Let's run additional checks first"
```

## Troubleshooting


### Merge Conflicts


```bash
# View conflicts

git status

# Edit conflicted files (marked with <<<<<<<, =======, >>>>>>>)


# After resolving:

git add <resolved-files>
git commit -m "fix: Resolve merge conflicts"
```

### Accidental Commit


```bash
# Undo last commit, keep changes

git reset --soft HEAD~1

# Make corrections

# Re-commit properly

```

### Lost Commits


```bash
# View all actions

git reflog

# Recover lost commit

git checkout <commit-hash>
git checkout -b recovery-branch
```

<!-- GIT:END -->