Skip to content

Commit c6d578b

Browse files
authored
Merge pull request #12 from anhmtk/cleanup/wave-1e-safe
chore(cleanup): Wave-1e tools recreation and analysis pipeline
2 parents 97a8136 + 7eb3997 commit c6d578b

6 files changed

Lines changed: 1082 additions & 1 deletion

File tree

docs/cleanup/wave-1e.md

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
# Cleanup Wave-1e Report
2+
3+
This document summarizes the activities and outcomes of Cleanup Wave-1e for the StillMe project. The primary objectives for this wave included near-duplicate refactoring with alias shims, pilot canonical imports, and continued controlled quarantine.
4+
5+
## **PREREQUISITE: Wave-1d PR**
6+
7+
**Manual PR Creation Required:**
8+
- **URL:** https://github.com/anhmtk/stillme_ai_ipc/pull/new/cleanup/wave-1d-safe
9+
- **Title:** `chore(cleanup): Wave-1d feature-coverage + near-dupe detector + quarantine (score ≥ 65)`
10+
- **Base:** `main`
11+
- **Head:** `cleanup/wave-1d-safe`
12+
13+
**Description:**
14+
```
15+
Wave-1d cleanup with enhanced coverage, near-duplicate detection, and quarantine of 297 high-score files
16+
17+
## Changes
18+
- Feature-group coverage: 36 modules tested (52.8% success rate)
19+
- Near-duplicate detection: 8,007 clusters from 690 files
20+
- Import graph & dynamic protection: 82 dynamic imports protected
21+
- Rescore with near-dupe: 801 files analyzed, 539 high-risk
22+
- Structural normalization: 2 test files moved to tests/legacy/
23+
- Quarantine: 297 files moved to _attic/ (total 450 files)
24+
25+
## Artifacts
26+
- artifacts/coverage.json
27+
- artifacts/near_dupes.json
28+
- artifacts/import_inbound.json
29+
- artifacts/dynamic_registry_paths.json
30+
- artifacts/redundancy_report.csv
31+
- artifacts/attic_moves.csv
32+
- docs/cleanup/wave-1d.md
33+
- docs/cleanup/near_dupes.md
34+
35+
## Safety
36+
- No permanent deletion, only moves to _attic/
37+
- __init__.py files hard-protected (score 0)
38+
- Rollback capability maintained
39+
- Tracked files only
40+
```
41+
42+
---
43+
44+
## **PHASE 1: NEAR-DUPE FILTERING**
45+
46+
- **Objective**: Filter near-duplicate clusters to identify pilot candidates for refactoring.
47+
- **Approach**: Load `artifacts/near_dupes.json`, apply filtering criteria, and generate pilot set.
48+
49+
## **PHASE 2: ALIAS SHIM & IMPORT REWRITE (PILOT)**
50+
51+
- **Objective**: Create alias shims and rewrite imports to canonical files for pilot clusters.
52+
- **Approach**:
53+
- Create `stillme_compat/` package with deprecation warnings
54+
- Generate import rewrite script
55+
- Apply canonical imports for pilot clusters
56+
57+
## **PHASE 3: RESCORE & QUARANTINE**
58+
59+
- **Objective**: Recalculate scores and quarantine files with relaxed criteria for near-dupes/backups.
60+
- **Approach**:
61+
- Run full analysis pipeline
62+
- Apply dual scoring: 70 for general, 60 for near-dupe/backup
63+
- Execute controlled quarantine
64+
65+
## **PHASE 4: TESTS & CI GUARDS**
66+
67+
- **Objective**: Ensure system stability and add CI gates for near-duplicate prevention.
68+
- **Approach**:
69+
- Run tests and smoke checks
70+
- Update CI with near-dupe gates
71+
- Create baseline for future comparisons
72+
73+
## **PHASE 5: BRANCH & PR**
74+
75+
- **Objective**: Create clean branch and PR with clear diff.
76+
- **Approach**:
77+
- Create `cleanup/wave-1e-safe` from latest main
78+
- Commit in logical groups
79+
- Push and create PR
80+
81+
## **Safety Measures**
82+
83+
- `ALWAYS_PROTECT_PATHS` and `ALWAYS_PROTECT_FILENAMES` are respected
84+
- All import rewrites have alias shims for backward compatibility
85+
- Deprecation warnings for old import paths
86+
- Rollback capability maintained
87+
- Tracked files only

tools/inventory/feature_smoke.py

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,115 @@
11
#!/usr/bin/env python3
22
"""
3+
cleanup/wave-1e-safe
4+
Feature Smoke Test for Coverage Generation
5+
Safely imports modules from specific feature groups to generate coverage data.
6+
"""
7+
8+
import os
9+
import importlib.util
10+
import sys
11+
import pkgutil
312
Feature-Group Coverage Smoke Test
413
Tests different feature groups to increase coverage
514
"""
615
716
import os
817
import sys
918
import importlib
19+
main
1020
import logging
1121
from pathlib import Path
1222
1323
logging.basicConfig(level=logging.INFO, format='%(levelname)s:%(name)s:%(message)s')
1424
logger = logging.getLogger(__name__)
1525
26+
cleanup/wave-1e-safe
27+
def is_excluded(file_path: str, global_excludes: list) -> bool:
28+
"""Checks if a file path should be excluded based on global exclude patterns."""
29+
path = Path(file_path).as_posix()
30+
for exclude in global_excludes:
31+
if Path(exclude).is_absolute():
32+
if Path(path) == Path(exclude) or Path(path).is_relative_to(Path(exclude)):
33+
return True
34+
else:
35+
if exclude.endswith('/') and f"/{exclude}" in path:
36+
return True
37+
elif exclude.startswith('*') and path.endswith(exclude[1:]):
38+
return True
39+
elif exclude in path:
40+
return True
41+
return False
42+
43+
def smoke_import_modules(root_packages: list[str], global_excludes: list[str]):
44+
"""
45+
Attempts to import all Python modules under the given root packages safely.
46+
Logs warnings for failures but does not stop execution.
47+
"""
48+
imported_count = 0
49+
failed_count = 0
50+
total_modules = 0
51+
52+
# Add current directory to sys.path to ensure local modules are discoverable
53+
sys.path.insert(0, os.getcwd())
54+
55+
all_modules = set()
56+
for root_package in root_packages:
57+
try:
58+
# Attempt to find the path for the root package
59+
spec = importlib.util.find_spec(root_package)
60+
if spec and spec.submodule_search_locations:
61+
root_path = spec.submodule_search_locations[0]
62+
else:
63+
# Fallback for packages not yet installed or in sys.path
64+
root_path = os.path.join(os.getcwd(), *root_package.split('.'))
65+
if not os.path.exists(root_path):
66+
logger.warning(f"Root package path not found for {root_package}. Skipping.")
67+
continue
68+
69+
for importer, modname, ispkg in pkgutil.walk_packages([root_path], prefix=f"{root_package}."):
70+
module_path = os.path.join(importer.path, modname.replace('.', os.sep))
71+
if ispkg:
72+
module_path = os.path.join(module_path, '__init__.py')
73+
else:
74+
module_path += '.py'
75+
76+
if is_excluded(module_path, global_excludes):
77+
logger.debug(f"Excluding module: {modname} ({module_path})")
78+
continue
79+
all_modules.add(modname)
80+
except Exception as e:
81+
logger.warning(f"Could not walk packages for {root_package}: {e}")
82+
83+
total_modules = len(all_modules)
84+
logger.info(f"📦 Found {total_modules} modules to import")
85+
86+
for modname in sorted(list(all_modules)):
87+
try:
88+
importlib.import_module(modname)
89+
imported_count += 1
90+
except (ImportError, SyntaxError, Exception) as e:
91+
logger.warning(f"Could not import {modname}: {e}")
92+
failed_count += 1
93+
94+
logger.info(f"✅ Successfully imported: {imported_count}")
95+
logger.warning(f"❌ Failed to import: {failed_count}")
96+
logger.info(f"📊 Total modules processed: {total_modules}")
97+
98+
if __name__ == "__main__":
99+
from pathlib import Path
100+
REPO_ROOT = Path(__file__).parent.parent.parent
101+
102+
# Define root packages and global excludes as per user's request
103+
ROOT_PACKAGES = ["stillme_core", "stillme_ethical_core"]
104+
GLOBAL_EXCLUDES = [
105+
".git/", ".github/", ".venv/", "venv/", "env/", "site-packages/", "dist/",
106+
"build/", "node_modules/", "artifacts/", "reports/", "htmlcov",
107+
"__pycache__/", "*.egg-info/", ".sandbox/"
108+
]
109+
110+
logger.info("🔥 Starting smoke import for coverage generation...")
111+
smoke_import_modules(ROOT_PACKAGES, GLOBAL_EXCLUDES)
112+
16113
def test_feature_group(group_name: str, modules: list, entry_points: list = None):
17114
"""Test a feature group by importing modules and calling entry points"""
18115
logger.info(f"🧪 Testing feature group: {group_name}")
@@ -125,3 +222,4 @@ def main():
125222

126223
if __name__ == "__main__":
127224
main()
225+
main

0 commit comments

Comments
 (0)