feat(cmd/gf): add gendao fileNameCase and ai coding stuffs (#4764)

This pull request introduces new and updated prompt and instruction
documents for the experimental OPSX workflow system, providing detailed,
step-by-step guidance for proposing, applying, archiving, and exploring
changes using OpenSpec. The changes standardize workflow guardrails,
clarify user interactions, and ensure consistent artifact handling
across all major workflow operations.

**OPSX Workflow Prompt Additions and Enhancements:**

* **Propose Workflow**
- Adds `.agents/prompts/opsx/propose.md` outlining how to propose a new
change, including artifact creation order, dependency handling, and user
input requirements. Emphasizes using schema-defined instructions and
templates, and clarifies that context/rules are for internal guidance
only.

* **Apply Workflow**
- Introduces `.agents/prompts/opsx/apply.md` detailing the process for
implementing tasks from an OpenSpec change. Covers change selection,
context reading, task loop execution, state handling, and output
formatting. Includes guardrails for ambiguity, blockers, and minimal
change scope.

* **Archive Workflow**
- Adds `.agents/prompts/opsx/archive.md` specifying the process for
archiving completed changes, including artifact/task completion checks,
delta spec sync assessment, user prompts for incomplete work, and
summary output. Ensures robust handling of archive naming conflicts and
user confirmations.

* **Explore Mode**
- Adds `.agents/prompts/opsx/explore.md` describing "explore mode" for
non-implementation discovery, problem investigation, and requirements
clarification. Outlines stance, behaviors, and guardrails for thinking
and artifact capture without code changes.

**Documentation Standardization:**

* **Markdown Formatting Standards**
- Adds `.agents/instructions/markdown-format.instructions.md` to
standardize markdown document formatting, including heading levels, code
block usage, list formatting, and language-specific punctuation rules
for improved clarity and consistency.
This commit is contained in:
John Guo
2026-04-25 17:47:05 +08:00
committed by GitHub
parent cb7cfa58ab
commit 94623a19d1
33 changed files with 2205 additions and 36 deletions

View File

@ -0,0 +1,21 @@
---
name: "Standardize markdown document formatting"
description: "Standardize the formatting of all markdown documents to keep structure clear, content readable, and the overall quality and user experience consistent. This document explains requirements for heading levels, paragraph formatting, code block usage, list formatting, and image and link insertion so authors can follow a unified style that is easier to read and maintain."
applyTo: "*.{md,MD}"
---
# Primary Formatting Requirements
- Keywords or specialized terms in the document must be formatted with inline code, for example `RuntimeClass`, `containerd`, `GPU`, and `AI`.
- In Chinese text, do not add spaces around inline code.
- For technical articles, review the generated content before finalizing it to ensure the material is technically accurate and contains no incorrect technical descriptions.
- When the generated content is too large, split it into multiple tasks to avoid exceeding model output limits and causing the workflow to fail.
# Detailed Content Requirements
- When documenting parameters or configuration items for a component or project, prefer tables when practical, and keep tables short enough to avoid horizontal scrolling during normal reading.
- In Chinese paragraphs, use full-width punctuation rather than half-width punctuation, for example `` instead of `,` and `` instead of `;`.
- Use `mermaid` for architecture diagrams, flowcharts, and similar visuals. If you need line breaks inside `mermaid`, use `<br/>` instead of `\n`.
- If a code block is not a `mermaid` diagram and instead uses box-drawing characters such as `┌─`, `┐`, `┤`, or `│`, keep the content in English so the layout stays aligned.
- Do not use `---` as a separator between paragraphs.

View File

@ -0,0 +1,152 @@
---
name: "OPSX: Apply"
description: Implement tasks from an OpenSpec change (Experimental)
category: Workflow
tags: [workflow, artifacts, experimental]
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name (e.g., `/opsx:apply add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- Context file paths (varies by schema)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using `/opsx:continue`
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read the files listed in `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! You can archive this change with `/opsx:archive`.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly

View File

@ -0,0 +1,157 @@
---
name: "OPSX: Archive"
description: Archive a completed change in the experimental workflow
category: Workflow
tags: [workflow, archive, experimental]
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name after `/opsx:archive` (e.g., `/opsx:archive add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `artifacts`: List of artifacts with their status (`done` or other)
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Prompt user for confirmation to continue
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Prompt user for confirmation to continue
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Spec sync status (synced / sync skipped / no delta specs)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs
All artifacts complete. All tasks complete.
```
**Output On Success (No Delta Specs)**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** No delta specs
All artifacts complete. All tasks complete.
```
**Output On Success With Warnings**
```
## Archive Complete (with warnings)
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** Sync skipped (user chose to skip)
**Warnings:**
- Archived with 2 incomplete artifacts
- Archived with 3 incomplete tasks
- Delta spec sync was skipped (user chose to skip)
Review the archive if this was not intentional.
```
**Output On Error (Archive Exists)**
```
## Archive Failed
**Change:** <change-name>
**Target:** openspec/changes/archive/YYYY-MM-DD-<name>/
Target archive directory already exists.
**Options:**
1. Rename the existing archive
2. Delete the existing archive if it's a duplicate
3. Wait until a different date to archive
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use the Skill tool to invoke `openspec-sync-specs` (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

View File

@ -0,0 +1,173 @@
---
name: "OPSX: Explore"
description: "Enter explore mode - think through ideas, investigate problems, clarify requirements"
category: Workflow
tags: [workflow, explore, experimental, thinking]
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
**Input**: The argument after `/opsx:explore` is whatever the user wants to think about. Could be:
- A vague idea: "real-time collaboration"
- A specific problem: "the auth system is getting unwieldy"
- A change name: "add-dark-mode" (to explore in context of that change)
- A comparison: "postgres vs sqlite for this"
- Nothing (just enter explore mode)
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
If the user mentioned a specific change name, read its artifacts for context.
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|--------------|------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When things crystallize, you might offer a summary - but it's optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

View File

@ -0,0 +1,106 @@
---
name: "OPSX: Propose"
description: Propose a new change - create it and generate all artifacts in one step
category: Workflow
tags: [workflow, artifacts, experimental]
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx:apply
---
**Input**: The argument after `/opsx:propose` is the change name (kebab-case), OR a description of what the user wants to build.
**Steps**
1. **If no input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx:apply` to start implementing."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

View File

@ -0,0 +1,280 @@
---
name: gf-feedback
description: >-
Track, fix, verify, and test any bugs, improvements, or gaps reported against an OpenSpec change.
MUST use this skill whenever user reports problems, defects, issues, bugs, or gaps related to
existing implementations, even if they don't explicitly say "feedback" or mention OpenSpec.
compatibility: Requires openspec CLI, Go toolchain, and gf-review skill.
---
# Feedback: Structured Fix, Verification & Test Coverage Loop
When users discover bugs or improvement points after implementation, this skill captures those issues, organizes them into a traceable task list in `tasks.md`, systematically fixes and verifies each one, and ensures every behavior-changing fix is covered by focused unit tests.
**Core principles:**
1. **Spec is the source of truth** — Spec-level changes require spec update before task recording
2. **Write it down first, then fix it** — Every issue gets recorded before any code change
3. **Every fix deserves a test** — Behavior-changing code changes require unit test coverage in the affected package
---
## Workflow
### 1. Identify Target Change
**CRITICAL:**
1. Always append to existing active changes. Only create new change when none exist.
2. An **active change** is any change directory that still exists directly under `openspec/changes/` and has **not** been moved into `openspec/changes/archive/`. Do **not** treat `status: complete`, all tasks checked off, or similar completion signals as "inactive" until archive actually happens.
3. Regardless of whether the feedback content is related to the main functionality of the current active iteration, it MUST be appended to the current active iteration. This ensures all changes are tracked in a single change record for unified management and archiving.
```bash
openspec list --json
# Or: ls openspec/changes/ | grep -v archive
```
When the two signals disagree, prefer the filesystem rule:
- If a change directory still exists under `openspec/changes/` and is not inside `archive/`, it is active.
- `openspec list --json` may still report such a change as `status: complete`; that only means implementation tasks are done, **not** that the change is inactive.
- Only archived changes under `openspec/changes/archive/` are inactive.
| Active Changes | Action |
|----------------|--------|
| None | Create new change (see below) |
| One | Auto-select it, announce and proceed |
| Multiple | Ask user to select from list |
**When multiple active changes exist:**
```
Multiple active changes detected. Which change should this feedback be appended to?
1. config-management — System config CRUD management
2. user-auth — User authentication enhancement
Please select 1 or 2:
```
**When no active change exists:**
1. Derive kebab-case name from feedback (e.g., "fix-menu-circular-ref")
2. If name exists, append suffix ("-2")
3. Create: `openspec new change "<name>"`
4. Generate minimal `proposal.md` (one paragraph summarizing context)
5. Skip `design.md` for pure bug fixes unless architectural changes needed
Announce: "Applying feedback fixes to change: **<name>**"
---
### 2. Read Current Context
| File | Purpose |
|------|---------|
| `tasks.md` | Task structure, naming conventions, numbering |
| `design.md` | Architectural context |
| `proposal.md` | Feature scope and intent |
| `specs/` | Delta spec definitions |
```bash
# Locate existing unit tests in the impacted package before adding a new one
rg --files <pkg-dir> | rg '_test\\.go$'
```
---
### 3. Analyze and Organize Issues
For each reported issue:
**Classify by type:**
- **bug** — Incorrect behavior, code doesn't match spec
- **missing** — Feature incomplete, gaps in implementation
- **ux** — UX improvement, no spec change needed
- **test-gap** — Missing test coverage only
**Classify by spec impact:**
| Level | Definition | Action |
|-------|------------|--------|
| **implementation** | Spec is correct, code is wrong | Fix code only |
| **spec-level** | Requirement missing/incomplete/changed | Update spec first, then fix |
| **internal** | No user-observable change | Fix code, test optional |
**Group related issues** — Same root cause → single task with multiple verification points.
---
### 4. Update Delta Specs (for Spec-Level Issues Only)
For spec-level issues, update specs **before** recording tasks:
1. Identify affected capability: `specs/<capability>/spec.md`
2. Apply delta operation:
```markdown
<!-- ADDED: New requirement -->
### Requirement: Parent Selector Circular Prevention
The system SHALL disable the current menu and all its descendants in the parent selector
to prevent circular references.
#### Scenario: Edit menu with children
WHEN user edits a menu that has child menus
THEN the parent selector SHALL disable the current menu and all descendant menus
<!-- MODIFIED: Changed requirement (include full original block) -->
### Requirement: Import Error Handling
The system SHALL display error messages when import fails.
**MODIFIED:** Error messages SHALL include row number, field name, and validation failure reason.
<!-- REMOVED: Deprecated requirement -->
### Requirement: Legacy Import Format
The system SHALL support legacy CSV format.
**REMOVED:** This format is no longer supported.
**Migration:** Use the new CSV format with header row.
```
---
### 5. Write Task List to tasks.md
Append a **Feedback section** to `tasks.md`:
```markdown
## Feedback
- [ ] **FB-1**: Parent selector allows circular references in menu edit
- [ ] **FB-2**: Import error messages lack row and field details
- [ ] **FB-3**: No test coverage for reset password feature
```
**Numbering:** Sequential `FB-1`, `FB-2`, etc. Continue from last number if section exists.
**One line per task** — No sub-fields. Analysis happens during fix phase.
**Confirm with user** before writing to file.
**Test coverage planning (internal):**
- Behavior-changing code change → Unit test required
- Internal-only optimization → Unit test optional unless logic risk increased
- Prefer extending the nearest `*_z_unit*_test.go` or `*_test.go` in the same package
---
### 6. Execute Fixes (Loop)
For each task:
**a. Announce:** `## Fixing FB-X: <issue title>`
**b. Investigate** — Read source files, confirm root cause
**c. Implement** — Minimal, focused fix following existing patterns
**d. Write/update unit tests** — Prefer the affected package's existing `*_z_unit*_test.go` or `*_test.go` files and keep assertions focused on the changed logic
**e. Assess Impact Scope (MANDATORY)**
After implementing, identify regression risk:
| Change Type | Map To Tests |
|-------------|--------------|
| Package-level logic | Targeted test for changed function/method + package regression tests |
| Shared utility | Utility package unit tests + highest-value dependent package tests already covering reuse |
| DB/DAO logic | DAO/model package unit tests with focused fixtures, mocks, or test helpers |
| Public API validation | Handler/service package unit tests that assert the changed validation path |
| Refactor without behavior change | Existing package tests that prove behavior parity |
```bash
# Example: Find unit tests related to a changed symbol or package
rg -l "GenDao|gdao" . -g '*_test.go'
```
Announce:
```
### Impact Analysis for FB-X
- Modified: cmd/gf/internal/cmd/gendao/gendao.go
- Affected package: cmd/gf/internal/cmd/gendao
- Unit tests: cmd/gf/internal/cmd/gendao/gendao_test.go
- Regression command: go test ./cmd/gf/internal/cmd/gendao -run 'TestGenDao'
```
**f. Verify (MANDATORY before marking complete)**
1. Run new/updated unit tests for this task → **must pass**
2. Run ALL identified package-level regression tests → **must pass**
3. Only then: mark task `[x]` in tasks.md
If regression fails:
- Fix inline if related to current change
- Add as new FB task if separate issue
**g. Run review** — Invoke `gf-review` skill after completion
---
### 7. Comprehensive Verification
After all fixes:
1. Aggregate regression tests from all tasks
2. Run full set in single pass
3. Report:
```
### Comprehensive Verification Results
- Total tests: N
- Passed: N
- Failed: N (list with details)
- Regression tests: all passed ✓ / X failures
```
If failures → add new FB tasks, loop to Step 6.
---
### 8. Report Completion
```markdown
## Feedback Complete
**Change:** <name>
**Issues reported:** X
**Issues fixed:** Y/X
**Tests added:** Z unit tests / focused assertions
**Regression tests run:** R tests across N packages
**Verification:** all passed / N issues remaining
### Fixed This Session
- [x] FB-1: <title> ✓ (unit test: TestGenDao_FiltersInvalidTables | package: ./cmd/gf/internal/cmd/gendao ✓)
- [x] FB-2: <title> ✓ (unit test: existing package coverage extended | package: ./cmd/gf/internal/cmd ✓)
### Remaining (if any)
- [ ] FB-3: <title> — blocked by <reason>
```
---
## Edge Cases
| Situation | Handling |
|-----------|----------|
| Single issue | Still follow full workflow |
| Missing test cases only | Classify as test-gap, implement tests |
| Fix reveals more issues | Add as new FB tasks |
| "Bug" is actually feature request | Re-classify as spec-level, update specs first |
| Unit test not feasible (docs/spec only) | Note reason explicitly and skip only when no runtime code changes exist |
| Multiple feedback rounds | All tasks in single Feedback section, sequential numbering |
---
## Guardrails
- **Append to active change if exists** — Never create new change when active ones exist
- **Specs before tasks for spec-level issues** — Update delta specs first
- **Write tasks before fixing** — Never code without recording
- **Confirm task list with user** — User validates analysis
- **Minimal fixes** — No refactoring beyond issue scope
- **Behavior-changing fix needs unit test** — No exceptions unless the change is docs/spec only
- **No green check without green unit tests** — Mark `[x]` only after tests pass
- **Impact analysis mandatory** — Every fix requires package-level regression test identification
- **Regression failures block completion** — Must resolve before marking done
- **Update tasks.md in real time** — Mark complete immediately after verification
- **Match file language** — Use same language as existing content in target file

View File

@ -0,0 +1,168 @@
---
name: gf-review
description: >-
Code and specification review for OpenSpec workflow. Triggers automatically after /opsx:apply
task completion, after /gf-feedback task completion, and before /opsx:archive. Use when
user requests code review, spec compliance check, or when explicitly invoked via /gf-review.
compatibility: Requires OpenSpec CLI and GoFrame v2 skill.
---
# GF Review
Structured code and specification review for the OpenSpec development workflow.
**Spec Source**: `CLAUDE.md` is the single source of truth for all review criteria.
---
## When This Skill Activates
**Automatic triggers:**
- After completing each task in `/opsx:apply`
- After completing each task in `/gf-feedback`
- Before executing `/opsx:archive`
**Manual trigger:**
- User explicitly requests: "review this code", "check spec compliance", "/gf-review"
---
## Review Workflow
### 1. Identify Scope
Determine what needs to be reviewed:
1. **After task completion** — Review files modified/created by the completed task
2. **Before archive** — Review all changes in the current OpenSpec change
3. **Manual invocation** — Ask user to specify scope or use current change
**Mandatory scope collection rules:**
1. Start with repository status, not `git diff` alone:
```bash
git status --short
git ls-files --others --exclude-standard
```
2. Treat **all tracked and untracked changes** as review candidates, including:
- staged files
- unstaged files
- untracked files shown as `??`
- untracked directories shown as `?? path/`
3. When `git status --short` reports an untracked directory, expand it to concrete files before review:
```bash
find <path> -type f
# Or prefer:
rg --files <path>
```
4. If the task ran generators such as `make ctrl`, `make dao`, codegen scripts, or produced new test files, explicitly include the generated untracked files in review scope even if they do not appear in `git diff`.
5. `git diff` may be used only as a secondary narrowing aid after status collection. It is **never sufficient by itself** for review scope definition.
Run `openspec status --change "<name>" --json` to understand the current change state.
### 2. Load Specifications
Read `CLAUDE.md` to load all specifications. This is the single source of truth.
### 3. Backend Code Review
**Trigger**: Changes to files under `apps/lina-core` directory
1. Invoke `goframe-v2` skill for GoFrame framework conventions
2. Check against `CLAUDE.md` backend code specifications
### 4. RESTful API Review
**Trigger**: Any API endpoint changes
Check against `CLAUDE.md` API design specifications.
### 5. Project Specification Review
**Trigger**: Any implementation changes
Check against `CLAUDE.md` architecture design specifications and code development specifications.
### 6. SQL Review
**Trigger**: New or modified files under `apps/lina-core/manifest/sql/`、`apps/lina-core/manifest/sql/mock-data/`、`apps/lina-plugins/**/manifest/sql/` or SQL snippets embedded in related delivery docs
Check against `CLAUDE.md` SQL file management specifications, at minimum covering:
1. File naming, versioning, and single-iteration single-file rules
2. Seed DML vs mock data separation
3. **Idempotent execution safety** — SQL must be safe to run multiple times without duplicate-object errors or duplicate seed data; verify use of `IF [NOT] EXISTS`, `IF EXISTS`, `INSERT IGNORE`, or equivalent safe re-entry patterns
4. **Seed write style compliance** — delivered SQL must reject `INSERT ... ON DUPLICATE KEY UPDATE` and reject explicit writes to `AUTO_INCREMENT` `id` columns in seed/mock/install data
5. Whether schema/data changes still match the current change scope and deployment path
### 7. Unit Test Review
**Trigger**: New or modified Go implementation files, or new/modified Go unit test files matching `*_test.go`
Check at minimum:
1. Behavior-changing Go code includes focused unit coverage in the same package, preferably by extending existing `*_z_unit*_test.go` or `*_test.go`
2. Tests assert the changed logic directly instead of relying on broad workflow-level coverage when a package-level test is sufficient
3. Verification uses targeted `go test ./path/to/pkg -run TestName` during development and package-level `go test ./path/to/pkg` for regression
### 8. Generate Review Report
```markdown
## GF Review Report
**Change:** <change-name>
**Scope:** <task-specific / full change>
**Files Reviewed:** <count>
**Scope Source:** `git status --short` + `git ls-files --others --exclude-standard` + task/change context
### Backend Code Review
✓ All checks passed / ⚠ N issues found
### RESTful API Review
✓ All endpoints compliant / ⚠ N violations found
### Project Spec Review
✓ Compliant with CLAUDE.md / ⚠ N violations found
### SQL Review
✓ No SQL changes / ✓ SQL changes compliant / ⚠ N SQL issues found
### Unit Test Review
✓ Unit tests are focused and sufficient / ⚠ N issues found
### Summary
- **Critical:** N (must fix before archive)
- **Warnings:** N (recommended to fix)
### Recommended Actions
1. [Specific action with CLAUDE.md reference]
```
---
## Issue Severity
| Level | Behavior |
|-------|----------|
| **Critical** | Block archive, must fix |
| **Warning** | Show but allow proceed |
---
## Integration Points
| Workflow Step | Behavior |
|---------------|----------|
| `/opsx:apply` task done | Review, offer to fix issues before next task |
| `/gf-feedback` task done | Review, fix before marking complete |
| `/opsx:archive` | Review all changes, block on critical issues |
---
## Guardrails
- **CLAUDE.md is the single source of truth** — All spec references point to it
- Only check categories relevant to changed files
- Scope identification MUST include untracked files and expanded untracked directories; never rely on `git diff` alone
- Behavior-changing Go code without focused unit tests is a review finding unless the author documents why tests are not applicable
- Don't block on warnings — only critical issues block archive
- Include file paths and line numbers in issue reports
- Offer to fix issues automatically when straightforward

View File

@ -0,0 +1,148 @@
---
name: git-commit-push
description: Review the current git working tree, generate a commit message from the actual diff using the repository's commit or PR-title convention, commit all current changes on the active branch, and push that branch to `origin`. Use this whenever the user asks to "commit", "push", "commit and push", "generate a commit message", "commit the current changes", or wants the current branch changes sent upstream without hand-writing the git commands.
---
# Git Commit Push
Inspect the current repository changes, derive a concise commit subject that matches the repository convention, commit every current modification on the active branch, and push that branch to `origin`.
This skill is for execution, not just advice. When it triggers, actually run the git workflow unless the repository state makes that unsafe or impossible.
## When To Use
- The user asks you to commit the current changes, with or without asking for push
- The user wants you to write the commit message from the diff instead of inventing one up front
- The user mentions the repo's PR or commit naming convention and wants you to follow it
- The user says things like "commit the current branch", "help me commit", "commit and push", "generate a commit message and push", or "send these changes to origin"
## Core Behavior
1. Confirm you are inside a Git repository and detect the active branch with `git branch --show-current`.
2. Inspect the working tree before committing:
- `git status --short --branch`
- `git diff --stat`
- `git diff --cached --stat`
- `git diff -- . ':(exclude)package-lock.json'` or narrower path filters only when needed for readability
3. If the repository contains `.github/PULL_REQUEST_TEMPLATE.MD`, read it and treat its PR-title rules as the default commit-subject convention.
4. Generate a commit subject from the actual changed files and diff content, not from the user prompt alone.
5. Stage every current modification on the branch with `git add -A`.
6. Commit once with the generated message.
7. Push the current branch to `origin` with `git push origin <current-branch>`.
## Commit Message Rules
The commit message is formatted as follows: `<type>[optional scope]: <description>` For example, `fix(os/gtime): fix time zone issue`
+ `<type>` is mandatory and can be one of `fix`, `feat`, `build`, `ci`, `docs`, `style`, `refactor`, `perf`, `test`, `chore`
+ `fix`: Used when a bug has been fixed.
+ `feat`: Used when a new feature has been added.
+ `build`: Used for modifications to the project build system, such as changes to dependencies, external interfaces, or upgrading Node version.
+ `ci`: Used for modifications to continuous integration processes, such as changes to Travis, Jenkins workflow configurations.
+ `docs`: Used for modifications to documentation, such as changes to README files, API documentation, etc.
+ `style`: Used for changes to code style, such as adjustments to indentation, spaces, blank lines, etc.
+ `refactor`: Used for code refactoring, such as changes to code structure, variable names, function names, without altering functionality.
+ `perf`: Used for performance optimization, such as improving code performance, reducing memory usage, etc.
+ `test`: Used for modifications to test cases, such as adding, deleting, or modifying test cases for code.
+ `chore`: Used for modifications to non-business-related code, such as changes to build processes or tool configurations.
+ After `<type>`, specify the affected package name or scope in parentheses, for example, `(os/gtime)`.
+ The part after the colon uses the verb tense + phrase that completes the blank in
+ Lowercase verb after the colon
+ No trailing period
+ Keep the title as short as possible. ideally under 76 characters or shorter
+ If there is a corresponding issue, add either `fixes #1234` (the latter if this is not a complete fix) to this comment
### Examples
#### Commit message with description and breaking change footer
```
feat: allow provided config object to extend other configs
BREAKING CHANGE: `extends` key in config file is now used for extending other config files
```
#### Commit message with ! to draw attention to breaking change
```
feat!: send an email to the customer when a product is shipped
```
#### Commit message with scope and ! to draw attention to breaking change
```
feat(api)!: send an email to the customer when a product is shipped
```
#### Commit message with both ! and BREAKING CHANGE footer
```
feat!: drop support for Node 6
BREAKING CHANGE: use JavaScript features not available in Node 6.
```
#### Commit message with no body
```
docs: correct spelling of CHANGELOG
```
#### Commit message with scope
```
feat(lang): add Polish language
```
#### Commit message with multi-paragraph body and multiple footers
```
fix: prevent racing of requests
Introduce a request id and a reference to latest request. Dismiss
incoming responses other than from latest request.
Remove timeouts which were used to mitigate the racing issue but are
obsolete now.
Reviewed-by: Z
Refs: #123
```
## Execution Rules
- Commit all current tracked and untracked changes in the working tree, because this skill is for "commit the current state" requests
- If there are no changes, say so clearly and stop before commit or push
- If `git branch --show-current` is empty, explain that `HEAD` is detached and stop unless the user explicitly asks you to commit from detached `HEAD`
- Never use `--force`, `--force-with-lease`, or history-rewriting commands unless the user explicitly asks
- If push fails because the remote branch moved, report the exact failure and stop instead of auto-rebasing or auto-merging
- Do not silently drop files from the commit unless the user asked to exclude them
## Suggested Command Flow
```bash
git status --short --branch
git diff --stat
git diff --cached --stat
test -f .github/PULL_REQUEST_TEMPLATE.MD && sed -n '1,220p' .github/PULL_REQUEST_TEMPLATE.MD
branch_name=$(git branch --show-current)
git add -A
git commit -m "<generated-subject>"
git push origin "$branch_name"
```
Inspect `git diff --cached` again after staging if the pre-stage diff was noisy or if untracked files materially change the scope.
## Output Contract
When you use this skill:
- Tell the user which branch you committed
- Provide the final commit subject you used
- Mention that you staged all current changes
- Report the push target as `origin/<branch>`
- If commit or push did not happen, explain exactly why
## Example
User request:
```text
Generate a commit message that follows this repository's convention, then commit and push the current branch
```
Expected behavior:
- Inspect the repo status and diff
- Generate a conventional subject from the real changes
- Run one commit for the whole current working tree
- Push the active branch to `origin`

View File

@ -0,0 +1,142 @@
---
name: git-worktree
description: Create and actively use an isolated git worktree for the user's task, then continue the task inside that new directory. Use this whenever the user asks for a separate worktree, isolated checkout, clean branch directory, safer parallel changes, or a fresh workspace to avoid unrelated local edits.
---
# Git Worktree
Create a dedicated `git worktree` for the current task, then keep working inside that new directory instead of the original checkout.
This skill is about execution, not just advice. When it triggers, actually create the worktree unless the repository state makes that impossible.
Do not introduce helper scripts for this skill. Use direct `git` and shell commands inline.
## When To Use
- The user explicitly asks for a new `git worktree`, independent branch directory, or isolated workspace
- The current checkout contains unrelated local changes and isolation is the safest way forward
- The user wants parallel work on multiple tasks without stashing or disturbing the original worktree
- The user says things like "create a separate branch folder", "open a fresh worktree", "use a clean checkout", or "work in an isolated workspace"
## Core Rule
After creating the worktree, treat the new path as the active working directory for the rest of the task.
In any agent environment, "enter the directory" means:
- Run subsequent commands against the new worktree path
- Apply all edits under that worktree path
- Do not keep using the original checkout by accident
- Confirm the handoff by running at least one follow-up command in the new worktree
Never claim you "switched" unless your subsequent actions actually target the new `worktree_path`.
If your environment supports a per-command working directory, use it for every later command. If it does not, prefix later commands with an explicit `cd <worktree_path> && ...`.
## Name Derivation
- Derive a short ASCII kebab-case task slug from the user's real task, such as `login-timeout-fix` or `user-export`
- Do not use generic names like `git-worktree`, `new-worktree`, or `task` unless the request is too vague
- If the request is mostly non-ASCII or no good slug is obvious, fall back to `task-$(date +%Y%m%d-%H%M%S)`
- Default branch prefix is `worktree/`
- Default worktree directory is a sibling of the repository root, named `<repo-name>-<slug>`
## Default Workflow
1. Inspect the repository context from the current checkout:
- `git rev-parse --show-toplevel`
- `git branch --show-current`
- `git status --short`
- `git worktree list --porcelain`
2. Decide a task slug yourself using the rules above
3. Build branch and path names inline, then create the worktree with direct shell commands like:
```bash
repo_root=$(git rev-parse --show-toplevel)
repo_name=$(basename "$repo_root")
parent_dir=$(dirname "$repo_root")
source_branch=$(git -C "$repo_root" branch --show-current)
if [ -n "$source_branch" ]; then
source_ref="$source_branch"
else
source_ref="HEAD@$(git -C "$repo_root" rev-parse --short HEAD)"
fi
slug="<task-slug>"
base_branch="worktree/$slug"
branch_name="$base_branch"
base_path="$parent_dir/$repo_name-$slug"
worktree_path="$base_path"
index=2
while git -C "$repo_root" show-ref --verify --quiet "refs/heads/$branch_name" || [ -e "$worktree_path" ]; do
branch_name="${base_branch}-$index"
worktree_path="${base_path}-$index"
index=$((index + 1))
done
git -C "$repo_root" worktree add -b "$branch_name" "$worktree_path" HEAD
```
4. Immediately verify the handoff inside the new worktree, for example:
```bash
pwd
git status --short --branch
```
These verification commands must run against `worktree_path`.
5. Announce the new active path briefly, then continue the main task there
6. For the remainder of the task, use `worktree_path` as the working directory for every relevant command or edit operation
## Behavior Rules
- Default base ref is `HEAD` from the current checkout so uncommitted local changes are not dragged into the new worktree
- If a branch name or path already exists, auto-increment it instead of failing
- If you are already inside a non-default worktree and the user still wants another isolated workspace, create a new one from the current `HEAD`
- If the directory is not a Git repository, explain that clearly and do not pretend a worktree was created
- If worktree creation succeeds, continue the user's actual task instead of stopping at setup
- If worktree creation fails because of filesystem permissions, request the minimal approval needed and retry
## Uncommitted Change Policy
The safe default is isolation from uncommitted changes.
- If the source checkout is dirty, still create the new worktree from `HEAD` unless the user explicitly asks to carry local edits over
- Do not silently stash, reset, or move the user's existing changes
- If the user wants local edits copied into the new worktree, use an explicit flow such as a temporary commit, patch, or cherry-pick, and say what you are doing
## Output Contract
When you use this skill:
- Tell the user which branch and directory were created
- Make it clear that subsequent work is now happening inside that path
- Mention the source ref and whether the original checkout was dirty when that context matters
- Do not stop after setup if the user asked for additional work; continue the task in the new worktree
## Example
User request:
```text
Create a separate worktree for this task and then start implementing it.
```
Expected behavior:
- Inspect current repo status
- Create a new `worktree/...` branch and sibling directory with direct `git worktree` commands
- Switch all following commands to that directory
- Continue the requested implementation there
## Cleanup
Only remove a worktree when the user asks or when cleanup is clearly part of the task.
Before cleanup:
- Check status in the worktree you created
- Make sure you are removing the correct path
- Never remove the user's original checkout

View File

@ -0,0 +1,288 @@
---
name: openspec-explore
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|--------------|------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Handling Different Entry Points
**User brings a vague idea:**
```
User: I'm thinking about adding real-time collaboration
You: Real-time collab is a big space. Let me think about this...
COLLABORATION SPECTRUM
════════════════════════════════════════════
Awareness Coordination Sync
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│Presence│ │Cursors │ │ CRDT │
│ "3 │ │ Multi │ │Conflict│
│online" │ │ select │ │ free │
└────────┘ └────────┘ └────────┘
│ │ │
trivial moderate complex
Where's your head at?
```
**User brings a specific problem:**
```
User: The auth system is a mess
You: [reads codebase]
┌─────────────────────────────────────────────┐
│ CURRENT AUTH FLOW │
└─────────────────────────────────────────────┘
┌─────────────┼─────────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Google │ │ GitHub │ │ Email │
│ OAuth │ │ OAuth │ │ Magic │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
└─────────────┼─────────────┘
┌───────────┐
│ Session │
└─────┬─────┘
┌───────────┐
│ Perms │
└───────────┘
I see three tangles. Which one's burning?
```
**User is stuck mid-implementation:**
```
User: /opsx:explore add-auth-system
The OAuth integration is more complex than expected
You: [reads change artifacts]
You're on task 4: "Implement OAuth flow"
Let me trace what's involved...
[draws diagram, explores options, suggests paths]
Want to update the design to reflect this?
Or add a spike task to investigate?
```
**User wants to compare options:**
```
User: Should we use Postgres or SQLite?
You: Generic answer is boring. What's the context?
User: A CLI tool that tracks local dev environments
You: That changes everything.
┌─────────────────────────────────────────────────┐
│ CLI TOOL DATA STORAGE │
└─────────────────────────────────────────────────┘
Key constraints:
• No daemon running
• Must work offline
• Single user
SQLite Postgres
Deployment embedded ✓ needs server ✗
Offline yes ✓ no ✗
Single file yes ✓ no ✗
SQLite. Not even close.
Unless... is there a sync component?
```
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When it feels like things are crystallizing, you might summarize:
```
## What We Figured Out
**The problem**: [crystallized understanding]
**The approach**: [if one emerged]
**Open questions**: [if any remain]
**Next steps** (if ready):
- Create a change proposal
- Keep exploring: just keep talking
```
But this summary is optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

View File

@ -0,0 +1,110 @@
---
name: openspec-propose
description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx:apply
---
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
**Steps**
1. **If no clear input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx:apply` or ask me to implement to start working on the tasks."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

1
.claude/commands Symbolic link
View File

@ -0,0 +1 @@
../.agents/prompts

1
.claude/skills Symbolic link
View File

@ -0,0 +1 @@
../.agents/skills

5
.codex/config.toml Normal file
View File

@ -0,0 +1,5 @@
approval_policy = "never"
sandbox_mode = "danger-full-access"
[sandbox_workspace_write]
network_access = true

1
AGENTS.md Symbolic link
View File

@ -0,0 +1 @@
CLAUDE.md

211
CLAUDE.md Normal file
View File

@ -0,0 +1,211 @@
# Repository Overview
This is the [GoFrame](https://goframe.org) framework (`github.com/gogf/gf/v2`) — a modular Go application framework. The repository is a **multi-module monorepo**: the root module hosts the core framework, while `cmd/gf` and every directory under `contrib/` are independent Go modules with their own `go.mod`.
- Root module: `github.com/gogf/gf/v2` (Go 1.23+)
- Tooling module: `cmd/gf` (CLI: `gf` command, separate `go.work`)
- Plugin modules under `contrib/`: `config/*`, `drivers/*` (mysql, pgsql, mssql, oracle, sqlite, clickhouse, dm, gaussdb, mariadb, oceanbase, tidb, sqlitecgo), `metric/*`, `nosql/*`, `registry/*`, `rpc/grpcx`, `sdk/*`, `trace/*`. Each is published as its own module so users only pull what they need.
The root framework intentionally has **minimal external dependencies** (see `go.mod`). Anything requiring a heavy third-party dep (a DB driver, a registry client, an RPC stack) lives in `contrib/`.
## Top-level package map
| Path | Purpose |
| --- | --- |
| `frame/g`, `frame/gins` | Convenience facade (`g.Server()`, `g.DB()`, `g.Cfg()`) and the singleton/instance container |
| `net/` | `ghttp` (HTTP server/router), `gclient` (HTTP client), `gtcp`, `gudp`, `gsel` (load balancing), `gsvc` (service discovery), `gtrace`, `goai` (OpenAPI) |
| `os/` | OS abstractions: `gcfg` (config), `gcmd` (CLI), `gcron`, `glog`, `gfile`, `gres` (resource embedding), `gview` (templating), `gcache`, `gsession`, `gctx`, `gtimer`, `gproc`, `gmetric`, `gfsnotify`, `gstructs` |
| `database/` | `gdb` (ORM/query builder, driver-agnostic core), `gredis` (Redis client core) |
| `container/` | Concurrent-safe data structures: `garray`, `gmap`, `gset`, `gtree`, `glist`, `gqueue`, `gring`, `gpool`, `gtype`, `gvar` |
| `encoding/` | Codecs for JSON/XML/YAML/TOML/INI/Properties, base64, charsets, compression, hashes, HTML, URL |
| `text/` | `gstr`, `gregex` |
| `util/` | `gconv` (universal conversion — heavily used), `gvalid` (validation), `gutil`, `grand`, `guid`, `gtag`, `gmeta`, `gpage`, `gmode` |
| `crypto/` | `gaes`, `gdes`, `grsa`, `gmd5`, `gsha*`, `gcrc32` |
| `errors/` | `gerror` (stack-aware errors), `gcode` (error code registry) |
| `internal/` | Framework-internal helpers (do not import from outside the root module) |
| `test/gtest` | The framework's own testing helpers — used throughout the test suite |
Concrete database drivers and Redis adapters live under `contrib/drivers/` and `contrib/nosql/`; the `database/gdb` and `database/gredis` packages define the abstract layer.
# Common Commands
All commands run from the repository root unless noted.
## Build / lint / tidy
```bash
# Tidy every go.mod in the repo (root, cmd/gf, contrib/*) — strips // indirect and toolchain lines
make tidy
# Run the project's golangci-lint config (.golangci.yml)
make lint
# Equivalent: golangci-lint run -c .golangci.yml
```
`make tidy` invokes `.make_tidy.sh`, which `cd`s into every directory containing a `go.mod` (skipping `testdata/` and `examples/`) and runs `go mod tidy`. After editing imports in any module, run this from the repo root.
## Tests
Each Go module must be tested from inside its own directory because they are separate modules. The CI script (`.github/workflows/scripts/ci-main.sh`) iterates every `go.mod`:
```bash
# Build + race-enabled tests for the root module
go build ./...
go test ./... -count=1 -race
# Coverage (matches CI 'coverage' mode)
go test ./... -count=1 -race -coverprofile=coverage.out -covermode=atomic \
-coverpkg=./...,github.com/gogf/gf/...
# Run a single package's tests
go test -count=1 -race ./os/gcfg/...
# Run a single test by name
go test -count=1 -race -run TestCfg_Get ./os/gcfg/
# Test a contrib module — must cd in first (separate go.mod)
cd contrib/drivers/mysql && go test ./... -count=1 -race
```
Many tests (database drivers, registry clients, redis cluster, apollo/nacos config) require backing services. CI starts them via docker-compose files under `.github/workflows/{redis,apollo,nacos,consul}/`. Locally, use:
```bash
make docker # start the default local stack
make docker cmd=start svc=mysql # start a specific service
make docker cmd=stop svc=mysql
```
## CLI tool
```bash
cd cmd/gf && go run . <subcommand> # iterate on the gf CLI itself
```
# Architecture Notes Worth Knowing Up Front
- **The `frame/g` package is a facade, not a library.** It re-exports types and provides singleton accessors (`g.DB()`, `g.Server()`, `g.Cfg()`, `g.Log()`) backed by `frame/gins`. Examples in docs use `g.*` heavily; framework-internal code generally imports the underlying packages directly.
- **`util/gconv` is foundational.** Most public APIs accept `any` and use `gconv` for type coercion. When changing argument handling, search for `gconv.` usage to understand the conversion contract.
- **`gdb` is driver-agnostic.** The core in `database/gdb` exposes interfaces; concrete drivers (`contrib/drivers/mysql`, etc.) register themselves via `init()` when imported. The same model pattern applies to `gredis`, `gcfg` (apollo/nacos/polaris adapters), and `gsvc` (etcd/consul/nacos/polaris/zookeeper registries).
- **`internal/` is private.** Sub-packages (`intlog`, `instance`, `reflection`, `utils`, `json`, `command`) are not part of the public API surface — do not import them from outside the root module, and avoid leaking their types in exported signatures.
- **Tests use `gtest`, not stdlib `testing` directly.** `test/gtest` provides `gtest.C(t, func(t *gtest.T){...})` blocks, fluent assertions (`t.Assert`, `t.AssertNE`, `t.AssertNil`), and is the project-wide convention. Match this style when adding tests.
- **CI matrix.** Tests run on Go 1.23, 1.24, 1.25 across 386 and amd64. `contrib/*` only runs on the latest Go version (`LATEST_GO_VERSION` in `.github/workflows/ci-main.yml`). Code that requires the latest stdlib should live in `contrib/` or be guarded.
- **Lint config matters.** `.golangci.yml` enforces a 380-char line limit, function length up to 340 lines, custom import grouping (`gci` with `prefix(github.com/gogf/gf/v2)` ahead of `cmd`/`contrib`/`example`), `gofmt -s` with rewrites (`interface{}``any`, `ioutil.*``io`/`os`, `reflect.Ptr``reflect.Pointer`). Run `make lint` before pushing.
- **OpenSpec changes live under `openspec/changes/`** and drive every non-trivial change through the workflow defined below. The active iteration directory must be checked before starting work — see the Development Workflow Rules section.
# Karpathy Guidelines
**Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment.
## 1. Think Before Coding
**Don't assume. Don't hide confusion. Surface tradeoffs.**
Before implementing:
- State your assumptions explicitly. If uncertain, ask.
- If multiple interpretations exist, present them - don't pick silently.
- If a simpler approach exists, say so. Push back when warranted.
- If something is unclear, stop. Name what's confusing. Ask.
## 2. Simplicity First
**Minimum code that solves the problem. Nothing speculative.**
- No features beyond what was asked.
- No abstractions for single-use code.
- No "flexibility" or "configurability" that wasn't requested.
- No error handling for impossible scenarios.
- If you write 200 lines and it could be 50, rewrite it.
Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify.
## 3. Surgical Changes
**Touch only what you must. Clean up only your own mess.**
When editing existing code:
- Don't "improve" adjacent code, comments, or formatting.
- Don't refactor things that aren't broken.
- Match existing style, even if you'd do it differently.
- If you notice unrelated dead code, mention it - don't delete it.
When your changes create orphans:
- Remove imports/variables/functions that YOUR changes made unused.
- Don't remove pre-existing dead code unless asked.
The test: Every changed line should trace directly to the user's request.
## 4. Goal-Driven Execution
**Define success criteria. Loop until verified.**
Transform tasks into verifiable goals:
- "Add validation" → "Write tests for invalid inputs, then make them pass"
- "Fix the bug" → "Write a test that reproduces it, then make it pass"
- "Refactor X" → "Ensure tests pass before and after"
For multi-step tasks, state a brief plan:
```
1. [Step] → verify: [check]
2. [Step] → verify: [check]
3. [Step] → verify: [check]
```
Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification.
# Documentation Writing Rules
Technical documentation such as `README.md` must follow `.agents/instructions/markdown-format.instructions.md`.
- All directory-level primary documentation files in the repository must use the English `README.md` and provide a matching Chinese mirror in `README.zh_CN.md`.
- When adding a new directory documentation file, create both `README.md` and `README.zh_CN.md` in the same change. Maintaining only one language version is not allowed.
# Development Workflow Rules
This project follows `SDD` and uses the `OpenSpec` tool to drive implementation. Change records are stored under `openspec/changes/`. Each change includes `proposal.md`, `design.md`, `specs/`, and `tasks.md`.
**Execution workflow**:
1. Use the `/opsx:explore` slash command at `.agents/prompts/opsx/explore.md` to conduct an exploratory discussion based on the requirement description, analyze the problem, design the solution, and assess risks.
2. Once the exploratory discussion finishes and the solution is clear, use the `/opsx:propose` slash command at `.agents/prompts/opsx/propose.md` to turn it into a formal `OpenSpec` change proposal. The command format is `/opsx:propose feature-name`, where `feature-name` is a descriptive name for the current change in `kebab-case`, such as `user-auth` or `data-export`. A new change directory will then be generated automatically under `openspec/changes`, containing incremental spec documents (`spec/`), the technical implementation plan (`design.md`), the proposal and rationale (`proposal.md`), and the implementation task list (`tasks.md`).
3. Then run the `/opsx:apply` slash command at `.agents/prompts/opsx/apply.md` to execute the items in `tasks.md` one by one, completing code changes, tests, and documentation updates. After the work is done, the `/gf-review` skill must be invoked for code and spec review.
4. When users report issues or improvement requests, the `/gf-feedback` skill must be used to fix and verify them, and the related `OpenSpec` documents must be updated. After the work is done, the `/gf-review` skill must be invoked for review.
5. After the user confirms that the current iteration is complete and has no remaining issues, run the `/opsx:archive` slash command at `.agents/prompts/opsx/archive.md` to archive the change. Before archiving, the `/gf-review` skill must be used for a full change review to ensure code quality and compliance with the spec.
**Key rules**:
- **An `OpenSpec` change is considered active until it is archived**: any change directory that still exists directly under `openspec/changes/` and has **not been moved to** `openspec/changes/archive/` is an active change. **Even if the change has completed all tasks and `openspec list --json` shows `status: complete`, it must still be treated as active until the archive step has been executed.**
- When a user reports a bug, defect, or improvement request in either Chinese or English, and there is an active `OpenSpec` change in the project, the `gf-feedback` skill must be used. **Unless the user explicitly asks to create a new change, the feedback must always be appended to the current active iteration, even if it is unrelated to the main feature of that iteration**, so that everything can be managed and archived together.
- The `/gf-review` review skill is triggered automatically after `/opsx:apply` completes, after `/opsx:feedback` completes, and before `/opsx:archive`.
- During development tasks executed with tools such as `Claude Code` or `Codex CLI`, if the work can be parallelized effectively with `SubAgent` and doing so would clearly improve efficiency, that option must be evaluated first and adopted whenever appropriate. Only skip `SubAgent` when the task is strongly dependent on serial context, the split cost is too high, or it introduces obvious collaboration risk.
- When creating new iteration documents, the content of `proposal.md`, `design.md`, `tasks.md`, and the incremental specs must be written in English.
# Code Development Rules
- All source code must include comments, such as package comments, file comments, method comments for both public and private methods, constant comments, variable comments, and comments for key logic.
- **All submitted code changes must include unit tests**: every submitted code change must add or update focused unit tests that directly cover the affected logic and expected behavior of the changed code path, and the coverage for newly added code must stay at or above 80%; 90% or above is the preferred target when feasible.
- **Do not hardcode string literals with enum semantics in backend implementation code**: values that represent statuses, types, stages, actions, execution modes, sort directions, filter operators, or any other enum-like semantics must be managed through Go named types and constants. Writing raw string literals directly in business branching, comparisons, assignments, or persistence logic is forbidden.
- **Do not ignore any `error` return value**: every call that may return an `error` must be handled explicitly. Do not use patterns such as `_ = someFunc()`, `_, _ = someFunc()`, or direct calls that discard returned errors. In business flows, errors should be returned explicitly or converted before returning; in initialization, startup, or other critical non-recoverable paths, they should `panic`; in tests and cleanup paths, they must still be asserted, logged, or otherwise handled explicitly rather than silently ignored.
- **Do not use stand-alone assignments like `_ = var` to mask unused parameters or local variables**: this placeholder pattern has no business meaning and creates misleading signals about whether the variable was supposed to participate in the logic. Prefer deleting unused variables. If a parameter must be kept to satisfy an interface signature or callback contract, use the blank identifier directly in the function signature, such as `func(ctx context.Context, _ gdb.TX) error`, or omit an unused receiver name instead of adding one-line statements like `_ = tx`, `_ = req`, or `_ = ctx` in the function body.
- **File header comment rules**:
- Every `Go` source file must include a file-purpose comment at the top of the file. Component-level comments should appear in the component's main file, meaning the file with the same name as the component, such as `plugin.go`, `config.go`, or `file.go`.
- In a main file, the component comment must be placed immediately before the `package xxx` declaration with no blank line in between. For example:
```go
// Package plugin implements plugin manifest discovery, lifecycle orchestration,
// governance metadata synchronization, and host integration for LinaPro plugins.
package plugin
```
- Other implementation files must keep only file comments that describe the responsibility of the current file, such as `plugin_xxx.go` or `config_xxx.go`. There must be one blank line between the file comment and `package xxx`, and non-main files must not duplicate component-level descriptions.
- **Variable Declarations**: When defining multiple variables, use a `var` block to group them for better alignment and readability:
```go
// Good - aligned and clean
var (
authSvc *auth.Service
bizCtxSvc *bizctx.Service
k8sSvc *svcK8s.Service
notebookSvc *notebook.Service
middlewareSvc *middleware.Service
)
// Avoid - scattered declarations
authSvc := auth.New()
bizCtxSvc := bizctx.New()
k8sSvc := svcK8s.New()
```
Apply this pattern when you have 3 or more related variable declarations in the same scope.

View File

@ -412,3 +412,60 @@ func Test_Gen_Dao_Sqlite3(t *testing.T) {
}
})
}
func Test_Gen_Dao_FileNameCaseSnakeFirstUpper(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
err error
db = testDB
table = "sys_i18n_message"
sqlContent = fmt.Sprintf(
gtest.DataContent(`gendao`, `user.tpl.sql`),
table,
)
)
dropTableWithDb(db, table)
array := gstr.SplitAndTrim(sqlContent, ";")
for _, v := range array {
if _, err = db.Exec(ctx, v); err != nil {
t.AssertNil(err)
}
}
defer dropTableWithDb(db, table)
var (
path = gfile.Temp(guid.S())
in = gendao.CGenDaoInput{
Path: path,
Link: link,
Group: "test",
Tables: table,
FileNameCase: "SnakeFirstUpper",
}
)
err = gutil.FillStructWithDefault(&in)
t.AssertNil(err)
err = gfile.Mkdir(path)
t.AssertNil(err)
defer gfile.Remove(path)
err = gfile.Copy(
gtest.DataPath("gendao", "go.mod.txt"),
gfile.Join(path, "go.mod"),
)
t.AssertNil(err)
_, err = gendao.CGenDao{}.Dao(ctx, in)
t.AssertNil(err)
files, err := gfile.ScanDir(path, "*.go", true)
t.AssertNil(err)
t.Assert(files, []string{
filepath.FromSlash(path + "/dao/internal/sys_i18n_message.go"),
filepath.FromSlash(path + "/dao/sys_i18n_message.go"),
filepath.FromSlash(path + "/model/do/sys_i18n_message.go"),
filepath.FromSlash(path + "/model/entity/sys_i18n_message.go"),
})
})
}

View File

@ -46,6 +46,7 @@ type (
RemovePrefix string `name:"removePrefix" short:"r" brief:"{CGenDaoBriefRemovePrefix}"`
RemoveFieldPrefix string `name:"removeFieldPrefix" short:"rf" brief:"{CGenDaoBriefRemoveFieldPrefix}"`
JsonCase string `name:"jsonCase" short:"j" brief:"{CGenDaoBriefJsonCase}" d:"CamelLower"`
FileNameCase string `name:"fileNameCase" short:"fc" brief:"{CGenDaoBriefFileNameCase}" d:"Snake"`
ImportPrefix string `name:"importPrefix" short:"i" brief:"{CGenDaoBriefImportPrefix}"`
DaoPath string `name:"daoPath" short:"d" brief:"{CGenDaoBriefDaoPath}" d:"dao"`
TablePath string `name:"tablePath" short:"tp" brief:"{CGenDaoBriefTablePath}" d:"table"`

View File

@ -69,7 +69,7 @@ func generateDaoSingle(ctx context.Context, in generateDaoSingleInput) {
var (
tableNameCamelCase = formatFieldName(in.NewTableName, FieldNameCaseCamel)
tableNameCamelLowerCase = formatFieldName(in.NewTableName, FieldNameCaseCamelLower)
tableNameSnakeCase = gstr.CaseSnake(in.NewTableName)
fileName = formatFileName(in.NewTableName, in.FileNameCase)
importPrefix = in.ImportPrefix
)
if importPrefix == "" {
@ -78,13 +78,6 @@ func generateDaoSingle(ctx context.Context, in generateDaoSingleInput) {
importPrefix = gstr.Join(g.SliceStr{importPrefix, in.DaoPath}, "/")
}
fileName := gstr.Trim(tableNameSnakeCase, "-_.")
if len(fileName) > 5 && fileName[len(fileName)-5:] == "_test" {
// Add suffix to avoid the table name which contains "_test",
// which would make the go file a testing file.
fileName += "_table"
}
// dao - index
generateDaoIndex(generateDaoIndexInput{
generateDaoSingleInput: in,

View File

@ -36,7 +36,7 @@ func generateDo(ctx context.Context, in CGenDaoInternalInput) {
}
var (
newTableName = in.NewTableNames[i]
doFilePath = gfile.Join(dirPathDo, gstr.CaseSnake(newTableName)+".go")
doFilePath = gfile.Join(dirPathDo, formatFileName(newTableName, in.FileNameCase)+".go")
structDefinition, _ = generateStructDefinition(ctx, generateStructDefinitionInput{
CGenDaoInternalInput: in,
TableName: tableName,

View File

@ -13,7 +13,6 @@ import (
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gview"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/cmd/gf/v2/internal/consts"
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
@ -32,7 +31,7 @@ func generateEntity(ctx context.Context, in CGenDaoInternalInput) {
var (
newTableName = in.NewTableNames[i]
entityFilePath = filepath.FromSlash(gfile.Join(dirPathEntity, gstr.CaseSnake(newTableName)+".go"))
entityFilePath = filepath.FromSlash(gfile.Join(dirPathEntity, formatFileName(newTableName, in.FileNameCase)+".go"))
structDefinition, appendImports = generateStructDefinition(ctx, generateStructDefinitionInput{
CGenDaoInternalInput: in,
TableName: tableName,

View File

@ -208,6 +208,28 @@ func formatFieldName(fieldName string, nameCase FieldNameCase) string {
}
}
// formatFileName formats and returns a new file name for generated source files.
func formatFileName(fileName, nameCase string) string {
if nameCase == "" {
nameCase = string(gstr.Snake)
}
fileName = normalizeNameForCaseConvert(fileName)
fileName = gstr.Trim(gstr.CaseConvert(fileName, gstr.CaseTypeMatch(nameCase)), "-_.")
if len(fileName) > 5 && fileName[len(fileName)-5:] == "_test" {
// Add suffix to avoid the table name which contains "_test",
// which would make the go file a testing file.
fileName += "_table"
}
return fileName
}
func normalizeNameForCaseConvert(name string) string {
if isAllUpper(name) {
return strings.ToLower(name)
}
return name
}
// isAllUpper checks and returns whether given `fieldName` all letters are upper case.
func isAllUpper(fieldName string) bool {
for _, b := range fieldName {

View File

@ -17,7 +17,6 @@ import (
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gview"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
"github.com/gogf/gf/cmd/gf/v2/internal/consts"
@ -67,13 +66,7 @@ func generateTableSingle(ctx context.Context, in generateTableSingleInput) {
mlog.Fatalf(`fetching tables fields failed for table "%s": %+v`, in.TableName, err)
}
tableNameSnakeCase := gstr.CaseSnake(in.NewTableName)
fileName := gstr.Trim(tableNameSnakeCase, "-_.")
if len(fileName) > 5 && fileName[len(fileName)-5:] == "_test" {
// Add suffix to avoid the table name which contains "_test",
// which would make the go file a testing file.
fileName += "_table"
}
fileName := formatFileName(in.NewTableName, in.FileNameCase)
path := filepath.FromSlash(gfile.Join(in.DirPathTable, fileName+".go"))
in.genItems.AppendGeneratedFilePath(path)
if in.OverwriteDao || !gfile.Exists(path) {

View File

@ -58,6 +58,13 @@ CONFIGURATION SUPPORT
CGenDaoBriefStdTime = `use time.Time from stdlib instead of gtime.Time for generated time/date fields of tables`
CGenDaoBriefWithTime = `add created time for auto produced go files`
CGenDaoBriefGJsonSupport = `use gJsonSupport to use *gjson.Json instead of string for generated json fields of tables`
CGenDaoBriefFileNameCase = `
generated go file name case for dao/table/do/entity files, cases are as follows:
| Case | Example |
|---------------- |--------------------|
| Snake | any_kind_of_string | default
| SnakeFirstUpper | rgb_code_md5 |
`
CGenDaoBriefImportPrefix = `custom import prefix for generated go files`
CGenDaoBriefDaoPath = `directory path for storing generated dao files under path`
CGenDaoBriefTablePath = `directory path for storing generated table files under path`
@ -128,6 +135,7 @@ func init() {
`CGenDaoBriefRemoveFieldPrefix`: CGenDaoBriefRemoveFieldPrefix,
`CGenDaoBriefStdTime`: CGenDaoBriefStdTime,
`CGenDaoBriefWithTime`: CGenDaoBriefWithTime,
`CGenDaoBriefFileNameCase`: CGenDaoBriefFileNameCase,
`CGenDaoBriefDaoPath`: CGenDaoBriefDaoPath,
`CGenDaoBriefTablePath`: CGenDaoBriefTablePath,
`CGenDaoBriefDoPath`: CGenDaoBriefDoPath,

View File

@ -10,6 +10,7 @@ import (
"testing"
"github.com/gogf/gf/v2/test/gtest"
"github.com/gogf/gf/v2/text/gstr"
)
// Test containsWildcard function.
@ -180,3 +181,12 @@ func Test_filterTablesByPatterns_NonExistent(t *testing.T) {
t.AssertNI("nonexistent", result)
})
}
func Test_formatFileName(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
t.Assert(formatFileName("sys_i18n_message", ""), "sys_i_18_n_message")
t.Assert(formatFileName("sys_i18n_message", string(gstr.SnakeFirstUpper)), "sys_i18n_message")
t.Assert(formatFileName("SYS_I18N_MESSAGE", string(gstr.SnakeFirstUpper)), "sys_i18n_message")
t.Assert(formatFileName("user_test", string(gstr.SnakeFirstUpper)), "user_test_table")
})
}

View File

@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-04-24

View File

@ -0,0 +1,3 @@
# add-unit-test-coverage-requirements
Require unit tests for submitted code changes and enforce minimum coverage targets for new code.

View File

@ -0,0 +1,28 @@
## Context
`CLAUDE.md` and `AGENTS.md` currently act as the canonical project rule documents used during implementation and review. The requested change is documentation-only, but the wording must clearly separate the hard minimum quality bar from the preferred target so contributors and reviewers apply the same standard.
## Goals / Non-Goals
**Goals:**
- Add an explicit rule that submitted code changes must include unit tests.
- Add an explicit rule that newly added code must reach at least 80% coverage.
- Preserve a stronger preferred target of 90% or above when feasible.
- Keep the change limited to the canonical rule documents and OpenSpec artifacts.
**Non-Goals:**
- Adding CI automation or coverage tooling in this change.
- Defining repository-wide historical coverage requirements.
- Changing unrelated contribution or coding rules.
## Decisions
- Update both `CLAUDE.md` and `AGENTS.md` so the duplicated project rule documents remain aligned.
- Place the new requirement under `Code Development Rules`, where existing mandatory engineering requirements already live.
- Use 80% as the hard minimum for newly added code and describe 90% or above as the preferred target when feasible.
- Keep the wording focused on unit tests and coverage expectations rather than implementation details about how coverage is measured.
## Risks / Trade-offs
- [Documentation-only enforcement] -> The rule depends on reviewer and contributor discipline until tooling is added; placing it in the canonical rule documents keeps the expectation visible during development and review.
- [Coverage interpretation] -> Different packages may measure coverage differently; using a clear minimum plus a preferred target reduces ambiguity without over-specifying tooling.

View File

@ -0,0 +1,23 @@
## Why
The project rules currently encourage tests, but they do not define a clear mandatory standard for submitted code changes or a minimum coverage threshold for newly added code. Adding an explicit rule makes review expectations consistent and gives contributors a concrete quality bar.
## What Changes
- Add a project rule requiring submitted code changes to include focused unit tests for the introduced or modified behavior.
- Add a project rule requiring newly added code to maintain at least 80% test coverage, with 90% or above treated as the preferred target when feasible.
- Record the requirement in the active OpenSpec change so the new quality gate is traceable.
## Capabilities
### New Capabilities
- `code-quality-gates`: Defines mandatory unit-test and coverage expectations for submitted code changes.
### Modified Capabilities
- None.
## Impact
- `CLAUDE.md`
- `AGENTS.md`
- Review expectations for future code submissions

View File

@ -0,0 +1,23 @@
## ADDED Requirements
### Requirement: Submitted code changes include unit tests
The project SHALL require every submitted code change to include unit tests that directly cover the affected logic and expected behavior of the changed code path in the affected package.
#### Scenario: Behavior-changing code is submitted
- **WHEN** a contribution adds or changes code in the repository
- **THEN** the submission SHALL include unit tests that exercise the affected logic or preserve the expected behavior of the changed code path before the change is considered complete
### Requirement: Newly added code meets the coverage baseline
The project SHALL require the newly added code in a submission to maintain unit-test coverage of at least 80%, and reviews SHALL treat 90% or above as the preferred target when that level is feasible without artificial or low-value tests.
#### Scenario: Coverage falls below the minimum
- **WHEN** the newly added code in a submission is covered below 80%
- **THEN** the change SHALL not satisfy the project quality requirement
#### Scenario: Coverage meets the minimum baseline
- **WHEN** the newly added code in a submission reaches 80% or higher coverage
- **THEN** the change SHALL satisfy the minimum coverage requirement
#### Scenario: Coverage reaches the preferred target
- **WHEN** the newly added code in a submission reaches 90% or higher coverage
- **THEN** the change SHALL satisfy the preferred coverage target for the project

View File

@ -0,0 +1,8 @@
## 1. Document the quality gate
- [x] 1.1 Create the OpenSpec proposal, design, and spec artifacts for the unit-test and coverage requirement
- [x] 1.2 Update the canonical project rule documents with the new unit-test and coverage requirement
## 2. Verify the documentation change
- [x] 2.1 Verify the updated rule documents mention mandatory unit tests and the 80% minimum / 90% preferred coverage targets

8
openspec/config.yaml Normal file
View File

@ -0,0 +1,8 @@
schema: spec-driven
# Project context (optional)
# This is shown to AI when creating artifacts.
# Add your tech stack, conventions, style guides, domain knowledge, etc.
# Example:
context: |
Generate all OpenSpec artifacts in English.

View File

@ -0,0 +1,27 @@
# code-quality-gates Specification
## Purpose
TBD - created by archiving change add-unit-test-coverage-requirements. Update Purpose after archive.
## Requirements
### Requirement: Submitted code changes include unit tests
The project SHALL require every submitted code change to include unit tests that directly cover the affected logic and expected behavior of the changed code path in the affected package.
#### Scenario: Behavior-changing code is submitted
- **WHEN** a contribution adds or changes code in the repository
- **THEN** the submission SHALL include unit tests that exercise the affected logic or preserve the expected behavior of the changed code path before the change is considered complete
### Requirement: Newly added code meets the coverage baseline
The project SHALL require the newly added code in a submission to maintain unit-test coverage of at least 80%, and reviews SHALL treat 90% or above as the preferred target when that level is feasible without artificial or low-value tests.
#### Scenario: Coverage falls below the minimum
- **WHEN** the newly added code in a submission is covered below 80%
- **THEN** the change SHALL not satisfy the project quality requirement
#### Scenario: Coverage meets the minimum baseline
- **WHEN** the newly added code in a submission reaches 80% or higher coverage
- **THEN** the change SHALL satisfy the minimum coverage requirement
#### Scenario: Coverage reaches the preferred target
- **WHEN** the newly added code in a submission reaches 90% or higher coverage
- **THEN** the change SHALL satisfy the preferred coverage target for the project