refactor: code standards, automated enforcement, agent directives, and docs overhaul #10
No reviewers
Labels
No labels
blocked
bug
enhancement
high-priority
low-priority
needs-info
needs-triage
ready-for-agent
ready-for-human
referenced
research
wontfix
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
gabogg/hikcentral!10
Loading…
Reference in a new issue
No description provided.
Delete branch "refactor/code-standards-enforcement-and-docs"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
📌 Overview & Scope
This draft PR lays out the complete architectural cleanup, code standard specification, automated quality enforcement, agent guideline overhaul, and documentation restructuring for the HikCentral Professional Integration platform.
🧹 1. Branch Maintenance & Pruning
All 9 previously merged and superseded feature branches were closed and pruned both locally and on the remote Forgejo repository:
audit/i18n-localizationfeat/admin-data-visualization-and-calibrationfeat/api-docs-and-swagger-explorerfeat/empirical-door-trackingfeat/occupancy-calibration-bleed-and-analyticsfeat/occupancy-calibration-model-redesignfeat/people-counting-and-occupancy-trackingfix/calibration-daemon-and-business-cycle-chartsrefactor/architecture-and-code-designOnly
masterand the new working branchrefactor/code-standards-enforcement-and-docsremain active.📐 2. Code Standards Specification
Documented in
docs/standards/code-standards.md:app/controllers/) handle HTTP routing, parameter validation (Pydantic v2), and RBAC.app/services/) encapsulate complex domain logic (proportional calibration, business cycles, WebSocket streaming).app/db/) isolate all SQLite WAL operations.app/clients/) manage upstream network authentication (Artemis HMAC-SHA256 and Bumblebee ISAPI).{"detail": str, "error_code": str}.pytestandpytest-asyncio.⚙️ 3. Automated Enforcement Infrastructure
pyproject.toml: Single source of truth forrufflinting/formatting rules andpytestconfiguration..pre-commit-config.yaml: Pre-commit hooks running:ruff check --fixruff formatcheck-yaml,check-json,trailing-whitespace,end-of-file-fixerpytestpass gate.forgejo/workflows/ci.yml: Continuous Integration workflow executing Ruff linting, formatting checks, and full test suite on push and PRs.requirements-dev.txt: Consolidated development toolchain (ruff,pre-commit,pytest,pytest-asyncio).scripts/lint.sh: One-command developer script with.venvauto-detection.⚡ 4. Retroactive Code Compliance
ruff check --fixandruff formatacross allapp/andtests/modules (730+ auto-fixes applied, un-sorted imports organized, trailing whitespace cleaned).B904) and ambiguous variables (E741).🤖 5. Agent Directives & Domain Context Synchronization
AGENTS.md: Created following agent-authoring best practices:WIP:draft conventions).CONTEXT.md: Synchronized domain glossary with all PR #1 through #9 additions:CameraEntry,DirectionType, zones).CALIBRATION_MODEL_PROPORTIONAL,kmultiplier, baseline offset, nocturnal quiet hours, anomaly quarantine).CalibrationDaemon).door_classifier).ADMIN,OPERATOR,AUDITOR).📚 6. Documentation Restructuring (
docs/)Reorganized the previously cluttered
docs/tree into a structured, indexed hierarchy:🔍 7. Dynamic Swagger & API Explorer Sync
app/docs/build_catalog.pyto parse docx guides directly from the repo directory (docs/OpenAPI Developer Guide/*.docx) instead of relying on an external machine-specific zip file.app/docs/artemis_catalog.json(189 APIs)app/docs/artemis_openapi.json(OpenAPI 3.0.3)app/docs/bumblebee_catalog.json/docs,/redoc,/api-docs).✅ Review Checklist
pyproject.toml,.pre-commit-config.yaml, and CI workflow configured.ruff.AGENTS.mdandCONTEXT.mdup to date.docs/reorganized with masterREADME.md.WIP: Code Standards, Automated Enforcement, Agent Directives & Documentation Overhaulto Code Standards, Automated Enforcement, Agent Directives & Documentation Overhaul📋 Code Review — PR #10
Fixed point:
master(36d38618e43fe8898dc7262f23c25a1c335c61b0), comparisongit diff master...HEAD.Commit:
b84fb0c(refactor: enforce code standards, automated pre-commit, agent directives, and docs overhaul).📐 Standards
Hard Violations (Documented Standards)
docs/standards/code-standards.md§1.1 &AGENTS.md§1):app/services/occupancy_service.py:649,1034andapp/services/analytics_service.py:81,114execute raw inline SQL (SELECT,DELETE,UPDATE) directly viaget_async_db(), violating the rule: "All SQL strings must reside within repository classes; no inline SQL in services or controllers."docs/standards/code-standards.md§2):app/docs/build_catalog.py:20definesdef _parse_single_docx(docx_file, category: str)leavingdocx_fileunannotated. Inapp/controllers/analytics_controller.py:31, route handlers (get_hourly_timeseries,get_calibration_status) omit return type annotations.docs/standards/code-standards.md§3.1 &AGENTS.md§2):app/controllers/video_controller.py:139,157andapp/controllers/analytics_controller.py:185,276raiseHTTPExceptionwithout standardizedheaders={"X-Error-Code": "..."}.pyproject.tomlvsdocs/standards/code-standards.md§2.2):The standards doc mandates
typing.Optional/typing.List, butpyproject.tomlenablesUP(pyupgrade), enforcingT | None/list[T].Baseline Code Smells (Judgement Calls)
Incomplete linter variable removals left orphaned evaluation statements with no effect:
app/services/door_service.py:1052:app/services/door_classifier.py:51:app/services/analytics_service.py:527-595:get_*_telemetry_asyncandget_calibration_history_asyncpass arguments straight through to repositories without added logic.app/services/analytics_service.py:425-485: 12 filtering parameters (start_epoch,end_epoch,camera_index_code,direction,status,search,state_key,page, etc.) travel together repeatedly across export and generator signatures without a unified filter schema.🎯 Spec
(a) Missing or Partial Requirements
(b) Scope Creep (Unasked-For Behavior)
(c) Faulty Implementations
📌 Summary
app/services/door_service.py:1052andapp/services/door_classifier.py:51from incomplete linter fixes).pytest.inishadowingpyproject.tomland invalidating the single-source-of-truth claim).✅ Review Corrections Applied (Commit
aba102c)Thank you for the thorough code review. All findings have been addressed and verified:
1. Hard Standards Violations Resolved
OccupancyRepositoryinapp/db/occupancy_repository.py:get_hourly_flow_distribution_async(...)quarantine_and_deduplicate_calibration_logs_async()get_calibration_log_for_cycle_async(...)get_bucketed_cycle_flow_async(...)upsert_retroactive_audit_log_async(...)get_async_db()calls and inline SQL from bothapp/services/occupancy_service.pyandapp/services/analytics_service.py.docx_file: Path | io.BytesIO | strin_parse_single_docx(app/docs/build_catalog.py).-> dict[str, Any]/-> StreamingResponse) to all route handlers inapp/controllers/analytics_controller.py.headers={"X-Error-Code": "..."}to allHTTPExceptionraises inapp/controllers/video_controller.py(HLS_PROXY_ERROR,SEGMENT_PROXY_ERROR) andapp/controllers/analytics_controller.py(INVALID_TELEMETRY_TYPE,INVALID_EXPORT_FORMAT,EXPORT_RANGE_EXCEEDED,CALIBRATION_LOG_NOT_FOUND).docs/standards/code-standards.md§2.2 to mandate modern Python 3.11+ built-in syntax (list[T],dict[K, V],T | None) as enforced by Ruffpyupgrade(UP).2. Code Smells Cleared
d.get("is_closed", False) and not is_offlineinapp/services/door_service.py.current_time or time.time()inapp/services/door_classifier.py.3. Spec & Documentation Alignment
CONTEXT.mdfordoor_classifier,DirectionType,CalibrationDaemon, andDual Gateway API.app/docs/build_catalog.pywith door status query, door control, and alert stream endpoints. Regenerated and committedapp/docs/bumblebee_catalog.json.pytest.ini. Pytest now runs exclusively againstpyproject.toml([tool.pytest.ini_options]) without shadowing warnings.docs/standards/code-standards.md§4.2 to documentpyproject.tomlas the single source of truth.check-added-large-filesfrom.pre-commit-config.yamlto maintain strictly specified hooks.4. Verification
./scripts/lint.sh:ruff check .oAll checks passed!ruff format --check .o109 files already formattedpytesto98 passed in 8.99s (100% green)Code Standards, Automated Enforcement, Agent Directives & Documentation Overhaulto WIP: Code Standards, Automated Enforcement, Agent Directives & Documentation Overhaul✅ PR #10 Verification & Resolution Summary
All initial review findings (Standards & Spec) have been addressed and validated across commits
aba102cand99bb28a.🔍 Verification Breakdown
occupancy_service.pyandanalytics_service.pywere relocated into dedicated repository methods onOccupancyRepository(quarantine_and_deduplicate_calibration_logs_async,upsert_retroactive_audit_log_async,get_hourly_flow_distribution_async,get_calibration_log_for_cycle_async,get_bucketed_cycle_flow_async). Direct imports ofget_async_dbin service layers were removed.docx_file: Path | io.BytesIO | strinapp/docs/build_catalog.py, and added return types across all endpoints inapp/controllers/analytics_controller.py.X-Error-Codeheaders to exceptions invideo_controller.pyandanalytics_controller.py.door_service.pyanddoor_classifier.py.pytest.ini.pyproject.tomlis now the exclusive configuration source. Updateddocs/standards/code-standards.mdto reflect Python 3.11+ union syntax and the single config source.door_classifier,DirectionType,CalibrationDaemon, andDual Gateway APItoCONTEXT.md.build_catalog.pyand regeneratedbumblebee_catalog.json.check-added-large-fileshook, updatedruff-pre-committo match repo runtimev0.16.6, and applied hook formatting cleanly across the codebase.🧪 Test & Lint Status
trailing-whitespace,end-of-file-fixer,check-yaml,check-json,ruff,ruff-format,pytest).Ready for merge!
WIP: Code Standards, Automated Enforcement, Agent Directives & Documentation Overhaulto refactor: code standards, automated enforcement, agent directives, and docs overhaul