cli-usereq 0.68.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. cli_usereq-0.68.0.dist-info/METADATA +1134 -0
  2. cli_usereq-0.68.0.dist-info/RECORD +37 -0
  3. cli_usereq-0.68.0.dist-info/WHEEL +5 -0
  4. cli_usereq-0.68.0.dist-info/entry_points.txt +4 -0
  5. cli_usereq-0.68.0.dist-info/licenses/LICENSE +674 -0
  6. cli_usereq-0.68.0.dist-info/top_level.txt +1 -0
  7. usereq/__init__.py +62 -0
  8. usereq/__main__.py +17 -0
  9. usereq/cli.py +4963 -0
  10. usereq/compress.py +393 -0
  11. usereq/compress_files.py +134 -0
  12. usereq/doxygen_parser.py +172 -0
  13. usereq/find_constructs.py +394 -0
  14. usereq/generate_markdown.py +158 -0
  15. usereq/resources/docs/Document_Source_Code_in_Doxygen_Style.md +130 -0
  16. usereq/resources/docs/HDT_Test_Authoring_Guide.md +318 -0
  17. usereq/resources/docs/Requirements_Template.md +78 -0
  18. usereq/resources/prompts/analyze.md +191 -0
  19. usereq/resources/prompts/change.md +279 -0
  20. usereq/resources/prompts/check.md +190 -0
  21. usereq/resources/prompts/cover.md +271 -0
  22. usereq/resources/prompts/create.md +134 -0
  23. usereq/resources/prompts/fix.md +273 -0
  24. usereq/resources/prompts/flowchart.md +272 -0
  25. usereq/resources/prompts/implement.md +194 -0
  26. usereq/resources/prompts/new.md +278 -0
  27. usereq/resources/prompts/readme.md +234 -0
  28. usereq/resources/prompts/recreate.md +265 -0
  29. usereq/resources/prompts/refactor.md +265 -0
  30. usereq/resources/prompts/references.md +131 -0
  31. usereq/resources/prompts/renumber.md +150 -0
  32. usereq/resources/prompts/workflow.md +254 -0
  33. usereq/resources/prompts/write.md +129 -0
  34. usereq/resources/prompts-version.txt +1 -0
  35. usereq/source_analyzer.py +2280 -0
  36. usereq/static_check.py +812 -0
  37. usereq/token_counter.py +123 -0
@@ -0,0 +1,158 @@
1
+ #!/usr/bin/env python3
2
+ """!
3
+ @file generate_markdown.py
4
+ @brief Generate concatenated markdown from arbitrary source files.
5
+ @details Analyzes each input file with source_analyzer and produces a single markdown output concatenating all results. Prints pack summary to stderr.
6
+ @author GitHub Copilot
7
+ @version 0.0.70
8
+ """
9
+
10
+ import os
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ from .source_analyzer import SourceAnalyzer, format_markdown
15
+
16
+ # Map file extensions to languages
17
+ EXT_LANG_MAP = {
18
+ ".py": "python",
19
+ ".js": "javascript",
20
+ ".mjs": "javascript",
21
+ ".ts": "typescript",
22
+ ".rs": "rust",
23
+ ".go": "go",
24
+ ".c": "c",
25
+ ".cpp": "cpp",
26
+ ".h": "c",
27
+ ".hpp": "cpp",
28
+ ".java": "java",
29
+ ".rb": "ruby",
30
+ ".php": "php",
31
+ ".swift": "swift",
32
+ ".kt": "kotlin",
33
+ ".scala": "scala",
34
+ ".lua": "lua",
35
+ ".sh": "shell",
36
+ ".pl": "perl",
37
+ ".hs": "haskell",
38
+ ".zig": "zig",
39
+ ".ex": "elixir",
40
+ ".cs": "csharp",
41
+ }
42
+ """! @brief Extension-to-language normalization map for markdown generation."""
43
+
44
+
45
+ def detect_language(filepath: str) -> str | None:
46
+ """! @brief Detect language from file extension.
47
+ @param filepath Path to the source file.
48
+ @return Language identifier string or None if unknown.
49
+ @details Uses EXT_LANG_MAP for extension lookup (case-insensitive).
50
+ """
51
+ _, ext = os.path.splitext(filepath)
52
+ return EXT_LANG_MAP.get(ext.lower())
53
+
54
+
55
+ def _format_output_path(filepath: str, output_base: Path | None) -> str:
56
+ """!
57
+ @brief Build the markdown-visible path for one source file.
58
+ @param filepath Absolute or relative source file path.
59
+ @param output_base Project-home base used to relativize output paths.
60
+ @return Original filepath when output_base is None; otherwise POSIX relative path from output_base.
61
+ @details Implements the _format_output_path function behavior with deterministic control flow.
62
+ """
63
+ if output_base is None:
64
+ return filepath
65
+ absolute_path = Path(filepath).resolve()
66
+ return Path(os.path.relpath(absolute_path, output_base)).as_posix()
67
+
68
+
69
+ def generate_markdown(
70
+ filepaths: list[str],
71
+ verbose: bool = False,
72
+ output_base: Path | None = None,
73
+ ) -> str:
74
+ """! @brief Analyze source files and return concatenated markdown.
75
+ @param filepaths List of source file paths to analyze.
76
+ @param verbose If True, emits progress status messages on stderr.
77
+ @param output_base Project-home base used to render file paths in markdown as relative paths.
78
+ @return Concatenated markdown string with all file analyses.
79
+ @throws ValueError If no valid source files are found.
80
+ @details Iterates through files, detecting language, analyzing constructs, and formatting output. Disables legacy comment/exit annotation traces in rendered markdown, emitting only construct references plus Doxygen field bullets when available.
81
+ """
82
+ analyzer = SourceAnalyzer()
83
+ md_parts = []
84
+ ok_count = 0
85
+ fail_count = 0
86
+ resolved_output_base = output_base.resolve() if output_base is not None else None
87
+
88
+ for fpath in filepaths:
89
+ if not os.path.isfile(fpath):
90
+ if verbose:
91
+ print(f" SKIP {fpath} (file not found)", file=sys.stderr)
92
+ continue
93
+
94
+ lang = detect_language(fpath)
95
+ if not lang:
96
+ if verbose:
97
+ print(f" SKIP {fpath} (unsupported extension)", file=sys.stderr)
98
+ continue
99
+
100
+ try:
101
+ elements = analyzer.analyze(fpath, lang)
102
+ lang_key = lang.lower().strip().lstrip(".")
103
+ spec = analyzer.specs[lang_key]
104
+ analyzer.enrich(elements, lang_key, filepath=fpath)
105
+
106
+ with open(fpath, "r", encoding="utf-8", errors="replace") as f:
107
+ total_lines = sum(1 for _ in f)
108
+
109
+ md_output = format_markdown(
110
+ elements,
111
+ _format_output_path(fpath, resolved_output_base),
112
+ lang_key,
113
+ spec.name,
114
+ total_lines,
115
+ include_legacy_annotations=False,
116
+ )
117
+
118
+ md_parts.append(md_output)
119
+ ok_count += 1
120
+ if verbose:
121
+ print(f" OK {fpath}", file=sys.stderr)
122
+
123
+ except Exception as e:
124
+ if verbose:
125
+ print(f" FAIL {fpath} ({e})", file=sys.stderr)
126
+ fail_count += 1
127
+
128
+ if not md_parts:
129
+ raise ValueError("No valid source files processed")
130
+
131
+ if verbose:
132
+ print(f"\n Processed: {ok_count} ok, {fail_count} failed",
133
+ file=sys.stderr)
134
+
135
+ return "\n\n---\n\n".join(md_parts)
136
+
137
+
138
+ def main():
139
+ """!
140
+ @brief Execute the standalone markdown generation CLI command.
141
+ @details Expects file paths as command-line arguments. Prints generated markdown to stdout.
142
+ @return {None} Function return value.
143
+ """
144
+ if len(sys.argv) < 2:
145
+ print("Usage: python generate_markdown.py file1 [file2 ...]",
146
+ file=sys.stderr)
147
+ sys.exit(1)
148
+
149
+ try:
150
+ md = generate_markdown(sys.argv[1:])
151
+ print(md)
152
+ except ValueError as e:
153
+ print(f"Error: {e}", file=sys.stderr)
154
+ sys.exit(1)
155
+
156
+
157
+ if __name__ == "__main__":
158
+ main()
@@ -0,0 +1,130 @@
1
+ # Role: AI Code Documentation Specialist & QA Enforcer
2
+
3
+ ## 1) Primary Objective
4
+ You are the definitive authority on generating, regenerating, updating, and maintaining source-code documentation. Your output is consumed exclusively by **Doxygen parsers** and **downstream LLM Agents**, never by humans.
5
+
6
+ All documentation and comments inside source code MUST:
7
+ - Document **ALL** code components (functions, classes, objects, structures, modules, variables).
8
+ - Strictly adhere to the **Tag Taxonomy** defined in Section 4.
9
+ - Use **Atomic Syntax** designed for machine logic inference.
10
+ - Be formatted using standard Doxygen syntax (`/** ... */` for C/C++ or `""" ... """` for Python) leveraging Markdown within the comments.
11
+
12
+ ## 2) Language & Format Constraints
13
+ * **Format:** Standard Doxygen with Markdown support.
14
+ * **Language:** English (Strict US English).
15
+ * **Target Audience:** LLM Agents, Automated Parsers, Static Analysis Tools.
16
+
17
+ ## 3) "LLM-Native" Documentation Strategy
18
+ **CRITICAL:** Formulate all new or edited requirements and all source code information using a highly structured, machine-interpretable format (Markdown within Doxygen) with unambiguous, atomic syntax to ensure maximum reliability for downstream LLM agentic reasoning.
19
+ * **Avoid:** Conversational filler, subjective adjectives, ambiguity, flowery prose.
20
+ * **Enforce:** High semantic density, logical causality, explicit constraints.
21
+ * **Goal:** Optimize context to enable an LLM to perform future refactoring, extension, or test generation without analyzing the function body.
22
+
23
+ ## 4) Tag Taxonomy & Content Standards
24
+ You must strictly adhere to the following classification of Doxygen tags. Missing a **Mandatory** tag is a critical failure.
25
+
26
+ ### A. MANDATORY TAGS (Must appear in every functional block)
27
+ These tags define the core interface contract.
28
+ * **`@brief`**: Mandatory, a short single-line technical description of its specific action.
29
+ * *Ex:* `@brief Initializes sensor array.`
30
+ * **`@details`**: Mandatory, detailed logical description. Must provide a high-density technical summary detailing critical algorithmic logic, complexity and side effects. Write description for other LLM **Agents**, NOT humans. Must be optimized for machine comprehension. Do not write flowery prose. Use high semantic density, optimized to contextually enable an **LLM Agent** to perform future refactoring or extension.
31
+ * **`@param`**: Mandatory if params are defined, input definition. Must include type constraints if the language is dynamic.
32
+ * *Ex:* `@param[in] id Unique identifier (UUIDv4 format).`
33
+ * **`@return`** (or **`@retval`**): Mandatory, output definition. Describe the data structure returned in a single block or list specific return values.
34
+ * *Ex:* `@return {bool} True if connection established; structure {x,y} otherwise.`
35
+
36
+ ### B. CONTEXT-MANDATORY TAGS (Required based on logic)
37
+ You must analyze the code logic. If these conditions exist, the tag is **Mandatory**.
38
+ * **`@param[out]`**: MANDATORY if a reference/pointer argument is mutated inside the function (C/C++).
39
+ * **`@exception`** (or **`@throws`**): MANDATORY if the function can raise an exception or error state. List specific error classes.
40
+ * **`@satisfies`**: If applicable, link to requirements (e.g., @satisfies REQ-026, REQ-045).
41
+
42
+ ### C. OPTIONAL TAGS (Semantic Enrichment)
43
+ Use these to increase context window efficiency for future agents.
44
+ * **`@pre`**: Pre-conditions. What must be true *before* calling. Use logical notation.
45
+ * **`@post`**: Post-conditions. System state *after* execution.
46
+ * **`@warning`**: Critical usage hazards (e.g., non-thread-safe).
47
+ * **`@note`**: Vital implementation details not fitting in `@details`.
48
+ * **`@see`** (or **`@sa`**): Links to related functions/classes for context linkage.
49
+ * **`@deprecated`**: If applicable, link to the replacement API.
50
+
51
+
52
+ ## 5) Operational Rules
53
+
54
+ ### Rule A: The "Update" Imperative
55
+ If you modify code, you must **immediately** verify and update the associated documentation. Stale documentation is a hallucination trigger and is strictly forbidden.
56
+
57
+ ### Rule B: 100% Coverage
58
+ Every exportable symbol must be documented. New code does not exist until it is documented according to the **Tag Taxonomy**.
59
+
60
+ ### Rule C: Content Heuristics (LLM-Optimized)
61
+ 1. **Type Precision:** If Python/JS, explicit types are mandatory in `@param` (e.g., `Dict[str, Any]`).
62
+ 2. **Complexity:** In `@details`, state Time/Space complexity (e.g., `O(n log n)`).
63
+ 3. **Side Effects:** Explicitly state mutations in `@details` or `@post` (e.g., "Resets global timer").
64
+
65
+ ## 6) Examples of Expected Output
66
+
67
+ ### Example A: C++ (BAD - Human Readable - AVOID)
68
+ ```cpp
69
+ /**
70
+ * This function basically checks if the user is valid.
71
+ * It connects to the db and returns true/false.
72
+ * Be careful not to pass a null user!
73
+ */
74
+ bool check_user(User u);
75
+ ```
76
+
77
+ ### Example B: C++ (GOOD - LLM Optimized)
78
+ ```cpp
79
+ /**
80
+ * @brief Validates User credentials against local cache.
81
+ * @details Performs SHA-256 hash comparison. Short-circuits on empty fields.
82
+ * Implementation uses constant-time comparison to prevent timing attacks.
83
+ * @pre Input User object must be initialized.
84
+ * @param[in] u {UserStruct} target_user - Entity to validate. Must contain non-null 'password_hash'.
85
+ * @return {bool} True if credentials match; False if invalid or cache miss.
86
+ * @throws {AuthError} If internal hashing service is unreachable.
87
+ * @note Complexity: O(1) - Constant time lookup.
88
+ * @warning Thread-Safety: Read-only, safe for concurrent calls.
89
+ * @see User::login
90
+ */
91
+ bool check_user(User u);
92
+ ```
93
+
94
+ ### Example C: Python (BAD - Human Readable - AVOID)
95
+
96
+ ```python
97
+ def process_telemetry(data, threshold=10):
98
+ """
99
+ Takes some data and cleans it up.
100
+ Removes the old keys and returns a list of numbers.
101
+ Might crash if data is bad.
102
+ """
103
+ # ...
104
+ ```
105
+
106
+ ### Example D: Python (GOOD - LLM Optimized)
107
+
108
+ ```python
109
+ def process_telemetry(data: Dict[str, Any], threshold: int = 10) -> List[float]:
110
+ """
111
+ @brief Filters and normalizes input telemetry stream.
112
+ @details Applies Z-score normalization. Drops keys matching 'legacy_*' pattern.
113
+ Uses list comprehension for memory efficiency.
114
+ @pre 'data' dictionary must not be empty.
115
+ @param data {Dict[str, Any]} Raw JSON payload from sensor.
116
+ @param threshold {int} Noise cutoff value. Defaults to 10.
117
+ @return {List[float]} Normalized value sequence in range [0.0, 1.0].
118
+ @throws {ValueError} If calculated standard deviation is zero.
119
+ @complexity O(N) where N is the number of keys in 'data'.
120
+ @side_effect Logs warning if >50% of data is filtered out.
121
+ """
122
+ # Implementation...
123
+ ```
124
+
125
+ ## 7) Minimal Agent-Focused Reference
126
+
127
+ - Keep this guide strictly parser-first and policy-focused.
128
+ - Include only repository-relevant Doxygen rules, tags, and compact examples.
129
+ - Exclude generic Doxygen handbook/tutorial material that does not change repository behavior.
130
+ - Prefer atomic constraints and deterministic examples over narrative explanations.
@@ -0,0 +1,318 @@
1
+ # HDT Unit Test Authoring Guide (for LLM Agents)
2
+ **Version:** 1.0
3
+ **Audience:** LLM agents that *author or modify* unit tests in the HDT style
4
+ **Source Prompt Cards:** Generator + Refactorer modes
5
+
6
+ ---
7
+
8
+ ## 1) Purpose and Non‑Negotiables
9
+ When you decide you must **write new unit tests** or **modify existing tests**, this document is the single reference for *how* to do so.
10
+
11
+ All HDT unit tests MUST be:
12
+
13
+ - **Deterministic**: 100% reproducible across runs and environments.
14
+ - **Isolated**: no real network / filesystem / database / clock / unseeded randomness.
15
+ - **Dependency‑aware**: tests are organized and executed by **levels** (Level 0 → Level N) derived from the call graph.
16
+ - **Framework‑native**: no custom gating logic embedded in test bodies.
17
+ - **CI‑gated**: higher levels are blocked if lower levels fail (via CI stages, not `if/return` in tests).
18
+ - **Signal‑rich for developers**: support dev runs that collect multiple failures when useful.
19
+
20
+ Guiding principle: **maximize diagnostic value and maintainability without proceduralizing the suite.**
21
+
22
+ ---
23
+
24
+ ## 2) Choose the Mode: Generator vs Refactorer
25
+ You MUST explicitly choose one of these modes before authoring.
26
+
27
+ ### Mode A — **Generator** (Create New Tests)
28
+ Use **Generator** when:
29
+ - No tests exist for the target scope, OR
30
+ - You are adding coverage for **new units** / **new behavior**, OR
31
+ - You are building a suite from source code (or a new module) and need a baseline.
32
+
33
+ Primary deliverable shape:
34
+ 1) Static analysis (UUTs + call graph + levels + deps)
35
+ 2) Test matrix (happy/boundary/error)
36
+ 3) New test code (level‑ordered)
37
+ 4) Execution plan (CI gating + dev signal)
38
+ 5) Quality checklist
39
+
40
+ ### Mode B — **Refactorer** (Improve Existing Tests)
41
+ Use **Refactorer** when:
42
+ - A test suite already exists, and you must **fix flakiness**, **reduce brittleness**, **restructure levels**, or **improve coverage**.
43
+ - You are modifying tests to align with HDT rules (determinism, isolation, leveling, CI gating).
44
+
45
+ Primary deliverable shape:
46
+ 1) Audit (what’s wrong & why)
47
+ 2) Static analysis (UUTs + call graph + levels + deps)
48
+ 3) Refactor plan (stepwise)
49
+ 4) Updated test matrix
50
+ 5) Refactored test code (or patches)
51
+ 6) Execution plan (CI gating + dev signal)
52
+ 7) Quality checklist
53
+
54
+ ---
55
+
56
+ ## 3) Mode Selection Heuristic (Decision Checklist)
57
+ If ANY of the following is true, pick **Refactorer**:
58
+ - Tests exist for the scope.
59
+ - Failures are flaky/intermittent.
60
+ - Tests touch real I/O or time.
61
+ - Tests rely on order or shared state.
62
+ - Assertions are brittle (implementation details, snapshots that break frequently).
63
+
64
+ Pick **Generator** only when you are genuinely producing **new tests** from source (or for uncovered code).
65
+
66
+ If ambiguous, default to **Refactorer** (changing existing suites is higher risk; start by auditing).
67
+
68
+ ---
69
+
70
+ ## 4) Universal HDT Test Principles (apply in BOTH modes)
71
+
72
+ ### 4.1 Determinism Requirements
73
+ Tests MUST NOT depend on:
74
+ - Real wall clock time (use time freezing, dependency injection, or fakes)
75
+ - Unseeded randomness (seed or inject deterministic generators)
76
+ - Unordered collection iteration (normalize or compare as sets where appropriate)
77
+ - Locale/timezone/environment (explicitly set or normalize)
78
+ - Global mutable state shared across tests
79
+
80
+ ### 4.2 Isolation Requirements
81
+ You MUST isolate:
82
+ - **Network** calls (mock/stub)
83
+ - **Filesystem** access (use temp fakes or mock; never touch real user paths)
84
+ - **Databases** (use in‑memory fakes or mocks; never real DB)
85
+ - **External services** (always mock)
86
+ - **OS / process** state (env vars, cwd, etc.) where relevant
87
+
88
+ No test may rely on state left behind by another test.
89
+
90
+ ### 4.3 Behavior over Implementation
91
+ - Prefer **behavioral assertions** (inputs → outputs / observable effects).
92
+ - Avoid asserting internal calls unless that is the behavior contract.
93
+ - Avoid brittle snapshot asserts unless the snapshot is *truly* a stable contract.
94
+ - Prefer explicit expected values/exceptions.
95
+
96
+ ### 4.4 AAA Structure
97
+ Use **Arrange – Act – Assert** in every test. Make the Act step obvious.
98
+
99
+ ### 4.5 Explicit Expected Outcomes
100
+ Every test MUST declare either:
101
+ - `expected_output`, OR
102
+ - `expected_exception` (type; message only if stable and intentional)
103
+
104
+ ---
105
+
106
+ ## 5) Dependency Awareness: Levels and the Call Graph
107
+ HDT uses levels to ensure fast, reliable diagnosis and CI gating.
108
+
109
+ ### 5.1 Definitions
110
+ - **UUT (Unit Under Test):** a function/class/module boundary you are testing.
111
+ - **Level 0 (Atomic):** leaf units with no internal dependencies (or only trivial pure helpers).
112
+ - **Level 1..N (Composed):** units that depend on lower-level units (directly or indirectly).
113
+
114
+ ### 5.2 Required Static Analysis Artifact
115
+ Before writing or refactoring tests, you MUST produce:
116
+ 1) **UUT list**
117
+ 2) **Call graph** (approximate is acceptable; must be explicit)
118
+ 3) **Level classification table**
119
+ 4) **External dependencies to isolate**
120
+
121
+ ### 5.3 Leveling Rules of Thumb
122
+ - If a unit calls another project unit: it is *higher level* than the callee.
123
+ - If a unit calls an external dependency: it is higher level, and that dependency must be isolated.
124
+ - Keep Level 0 tests small and precise; they are your CI gate.
125
+
126
+ ---
127
+
128
+ ## 6) Repo Layout and Naming Conventions
129
+ ### 6.1 Recommended Layout
130
+ ```
131
+ tests/
132
+ unit/
133
+ atomic/
134
+ composed/
135
+ module/ # optional; only if your project meaningfully benefits
136
+ ```
137
+
138
+ ### 6.2 Naming Convention
139
+ Use clear test names:
140
+ - `test_<scenario>_<expected_behavior>`
141
+ - Prefer descriptive scenario labels (happy/boundary/error).
142
+
143
+ ---
144
+
145
+ ## 7) Generator Mode: Required Workflow and Output Contract
146
+ When in **Generator** mode, you MUST deliver the following artifacts **in this exact order**.
147
+
148
+ ### 7.1 Static Analysis Artifact
149
+ Include:
150
+ - UUT list
151
+ - Call graph
152
+ - Levels table
153
+ - External deps to isolate
154
+
155
+ ### 7.2 Test Matrix Artifact (minimum cases per UUT)
156
+ For each UUT, define at least:
157
+ - **Happy path**
158
+ - **Boundary case(s)**
159
+ - **Error case(s)** (if applicable)
160
+
161
+ Matrix columns SHOULD include:
162
+ - UUT, Level, Scenario, Arrange (inputs), Act, Assert (expected), Mocks
163
+
164
+ ### 7.3 Test Code (Framework‑Native)
165
+ - Write tests starting from **Level 0**, then Level 1..N.
166
+ - Use AAA.
167
+ - No real I/O.
168
+ - Explicit expected outcomes.
169
+ - Use per-framework best practices (fixtures, parametrization, setup/teardown) *without* creating cross-test coupling.
170
+
171
+ ### 7.4 Execution Plan
172
+ Provide:
173
+ - **CI plan**: staged gating (atomic → composed → module)
174
+ - **Dev plan**: how to run signal‑rich (collect multiple failures)
175
+
176
+ ### 7.5 Quality Checklist
177
+ At minimum:
178
+ - Deterministic
179
+ - Isolated
180
+ - Explicit expected outcomes
181
+ - Correct levels (atomic first)
182
+ - Happy + boundary + error coverage
183
+ - Non‑brittle asserts
184
+ - Clear naming
185
+
186
+ ---
187
+
188
+ ## 8) Refactorer Mode: Required Workflow and Output Contract
189
+ When in **Refactorer** mode, you MUST deliver the following artifacts **in this exact order**.
190
+
191
+ ### 8.1 Audit Artifact (what’s wrong & why)
192
+ Identify:
193
+ 1) **Flakiness sources** (time, random, I/O, shared state, order dependence)
194
+ 2) **Brittleness sources** (over-mocking, impl-detail asserts, fragile snapshots)
195
+ 3) **Dependency structure gaps** (missing leaf tests, misleveled tests)
196
+ 4) **Coverage gaps** (missing happy/boundary/error)
197
+
198
+ ### 8.2 Static Analysis Artifact
199
+ Same requirements as Generator:
200
+ - UUT list
201
+ - Call graph
202
+ - Levels table
203
+ - External deps to isolate
204
+
205
+ ### 8.3 Refactor Plan (stepwise)
206
+ Provide a numbered plan that:
207
+ - Stabilizes determinism (freeze time, seed random, inject deps, fakes)
208
+ - Removes real I/O
209
+ - Re-levels tests and reorganizes files
210
+ - Replaces brittle asserts with behavioral asserts
211
+ - Adds missing cases minimally
212
+
213
+ ### 8.4 Updated Test Matrix Artifact
214
+ Refresh the matrix to ensure:
215
+ - Each UUT has happy + boundary + error (if applicable)
216
+ - Correct level assignment
217
+ - Mocking strategy is explicit and minimal
218
+
219
+ ### 8.5 Refactored Test Code
220
+ - Provide updated files (or patches) in separate fenced blocks per file.
221
+ - Preserve original behavioral intent unless it is clearly incorrect; if you change behavior, document why.
222
+
223
+ ### 8.6 Execution Plan
224
+ - CI (gated fail-fast by stage)
225
+ - Dev (signal‑rich, optionally include framework-native triage commands)
226
+
227
+ ### 8.7 Quality Checklist (Refactor‑specific additions)
228
+ Also confirm:
229
+ - No sleeps/retries to hide flakes
230
+ - No hidden cross-test dependencies
231
+ - Brittle mocks removed where a fake is simpler
232
+
233
+ ---
234
+
235
+ ## 9) CI Gating vs Test Logic (Critical Rule)
236
+ **Gating belongs to CI**, not to test bodies.
237
+
238
+ ### 9.1 CI (Strict Gated Fail‑Fast)
239
+ Run stages and block next stage if previous fails. Example:
240
+ - Stage 1: `tests/unit/atomic` (fail-fast)
241
+ - Stage 2: `tests/unit/composed` (fail-fast; only if Stage 1 green)
242
+ - Stage 3: `tests/unit/module` (optional; only if Stage 2 green)
243
+
244
+ ### 9.2 Dev (Signal‑Rich)
245
+ - Run full suite without fail-fast to gather multiple failures.
246
+ - Use fail-fast only for focused debugging.
247
+
248
+ ---
249
+
250
+ ## 10) Assumptions You MUST Actively Challenge (Pre‑Flight)
251
+ Before writing or changing tests, challenge these common failure modes:
252
+
253
+ 1) **Leaf identification:** Did you misread the call graph or miss a dependency?
254
+ 2) **Expected errors:** Is the exception type correct? Is message stable enough to assert?
255
+ 3) **Boundaries:** Null/empty, max size, negative, overflow, encoding, and type errors.
256
+ 4) **Determinism risks:** timestamps, UUIDs, randomness, unordered structures.
257
+ 5) **Coupling:** Are you asserting behavior, or implementation details?
258
+
259
+ If uncertain:
260
+ - State the uncertainty explicitly in your artifacts.
261
+ - Choose robust techniques (freeze time, seed random, normalize outputs).
262
+ - Avoid overly specific assertions until justified.
263
+
264
+ ---
265
+
266
+ ## 11) Fine‑Grained Test Dependencies (Rare Exception)
267
+ Avoid “Test B depends on Test A”.
268
+
269
+ Only if truly necessary:
270
+ - Make dependency explicit and documented.
271
+ - Prefer framework support (markers/plugins) or CI staging.
272
+ - Justify why level-based staging is insufficient.
273
+ - Avoid long chains; improve leaf tests instead.
274
+
275
+ ---
276
+
277
+ ## 12) Operational Templates (Copy/Paste Prompts)
278
+
279
+ ### 12.1 Generator Mode Prompt Template
280
+ **Task:** Create HDT unit tests (Generator mode)
281
+ **Lang/Framework:** `{{LANG}} / {{TEST_FRAMEWORK}}`
282
+ **Scope:** `{{TARGET_SCOPE}}`
283
+ **Constraints:** `{{CONSTRAINTS}}`
284
+ **Source Code:**
285
+ ```text
286
+ {{SOURCE_CODE}}
287
+ ```
288
+ **Required output:** Follow the Generator workflow and artifact order in Sections 7 and 5.
289
+
290
+ ### 12.2 Refactorer Mode Prompt Template
291
+ **Task:** Refactor HDT unit tests (Refactorer mode)
292
+ **Lang/Framework:** `{{LANG}} / {{TEST_FRAMEWORK}}`
293
+ **Scope:** `{{TARGET_SCOPE}}`
294
+ **Constraints:** `{{CONSTRAINTS}}`
295
+ **Source Code:**
296
+ ```text
297
+ {{SOURCE_CODE}}
298
+ ```
299
+ **Existing Tests:**
300
+ ```text
301
+ {{EXISTING_TESTS}}
302
+ ```
303
+ **Required output:** Follow the Refactorer workflow and artifact order in Sections 8 and 5.
304
+
305
+ ---
306
+
307
+ ## 13) Final Self‑Check (Mandatory)
308
+ Before outputting test code, verify:
309
+
310
+ - [ ] Mode correctly chosen (Generator vs Refactorer)
311
+ - [ ] Static analysis completed (UUTs, call graph, levels, external deps)
312
+ - [ ] Tests are deterministic (no time/random/env nondeterminism)
313
+ - [ ] Tests are isolated (no real I/O)
314
+ - [ ] Level 0 exists and runs first
315
+ - [ ] Each UUT has happy + boundary + error (if applicable)
316
+ - [ ] Assertions are behavioral and explicit
317
+ - [ ] CI gating is described outside of test bodies
318
+ - [ ] Repo layout and naming are consistent
@@ -0,0 +1,78 @@
1
+ ---
2
+ title: "{{project name}} Requirements"
3
+ description: Software requirements specification
4
+ version: "{{version}}"
5
+ date: "{{date_modified}}"
6
+ author: "{{author}}"
7
+ scope:
8
+ paths:
9
+ - "**/*.py"
10
+ - "**/*.ipynb"
11
+ - "**/*.c"
12
+ - "**/*.h"
13
+ - "**/*.cpp"
14
+ excludes:
15
+ - ".*/**"
16
+ visibility: "draft"
17
+ tags: ["markdown", "requirements", "example"]
18
+ ---
19
+
20
+ # {{project name}} Requirements
21
+ <!-- Metadata is in the YAML front matter; do not duplicate it in the body. -->
22
+
23
+ <!-- Optional: omit a Table of Contents to reduce token footprint for LLM agents. If a TOC is included, it MUST be auto-generated and kept minimal. -->
24
+
25
+ ## 1. Introduction
26
+ <!-- Overview of the SRS: purpose, scope, audience, and document organization. Avoid detailed requirements here. -->
27
+
28
+ ### 1.1 Document Rules
29
+ This document MUST follow these authoring rules (LLM-first, normative SRS):
30
+ - This document MUST be written and maintained in English.
31
+ - Use RFC 2119 keywords exclusively (MUST, MUST NOT, SHOULD, SHOULD NOT, MAY). Do not use "shall".
32
+ - In requirements sections, every bullet MUST be a requirement and MUST start with a unique, stable Requirement ID (e.g., **REQ-001**).
33
+ - Requirement IDs MUST be stable: never renumber, reuse, or repurpose an ID. Only the dedicated reorganization workflow may renumber and it MUST emit an old→new ID mapping.
34
+ - Requirement ID prefixes MUST be consistent; if additional prefixes are needed beyond PRJ/CTN/DES/REQ/TST, they MUST be defined once in this section before first use.
35
+ - Each requirement MUST be atomic, single-sentence, and testable; target <= 35 words per requirement; split any compound behavior into separate IDs.
36
+ - Write for other LLM Agents and automated parsers (high semantic density; no filler).
37
+ - On every change to this document:
38
+ - Update `date` and `version` in the YAML front matter only (avoid duplicating metadata in the body).
39
+ - Do NOT maintain an in-document revision history; use git history / CHANGELOG.md for change tracking.
40
+
41
+ ### 1.2 Project Scope
42
+ <!-- The project (name/version), primary purpose, key capabilities, and boundaries. Keep brief and focus on the "what" and "why", not the "how". Avoid detailed requirements here. -->
43
+
44
+ ## 2. Project Requirements
45
+ <!-- Background and context that shape the project's requirements. Avoid detailed requirements here. -->
46
+
47
+ ### 2.1 Project Functions
48
+ <!-- Major functional areas or features of the project -->
49
+ - **PRJ-001**: MUST <single-sentence project function (<= 35 words)>.
50
+ - **PRJ-002**: Requirement description of project function 2
51
+ <!-- add here other project function requirements -->
52
+
53
+ ### 2.2 Project Constraints
54
+ <!-- Design and implementation constraints that affect the solution of the project -->
55
+ - **CTN-001**: MUST <single-sentence constraint (<= 35 words)>.
56
+ - **CTN-002**: Requirement description of project constraint 2
57
+ <!-- add here other project constraint requirements -->
58
+
59
+ ## 3. Requirements
60
+ <!-- Identifiable, verifiable, and testable requirements. Avoid implementation details. -->
61
+
62
+ ### 3.1 Design and Implementation
63
+ <!-- Constraints and mandates on design, deployment, and maintenance -->
64
+ - **DES-001**: Requirement description of design constraint 1
65
+ - **DES-002**: MUST <single-sentence design constraint (<= 35 words)>.
66
+ <!-- add here other design constraint requirements -->
67
+ ### 3.2 Functions
68
+ <!-- Externally observable behaviors organized by feature or use case -->
69
+ - **REQ-001**: MUST <single observable behavior with explicit trigger and expected outcome>.
70
+ - **REQ-002**: Requirement description of function 2
71
+ <!-- add here other function requirements -->
72
+
73
+ ## 4. Test Requirements
74
+ <!-- Define the test requirements linked to functional/non-functional requirements (or to a verification context) and specify a clear, reproducible test procedure with explicit pass/fail criteria. -->
75
+
76
+ - **TST-001**: MUST verify <requirement-id> using <reproducible procedure> with explicit pass/fail criteria.
77
+
78
+ <!-- Do not add a revision history section here; use git history / CHANGELOG.md instead. -->