Rework Admin UI #6

Merged
MasterMito merged 18 commits from epic/admin_rework_second_try into main 2026-03-20 11:55:38 +01:00
37 changed files with 4385 additions and 201 deletions
+149
View File
@@ -0,0 +1,149 @@
---
description: Implement tasks from an OpenSpec change (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
+154
View File
@@ -0,0 +1,154 @@
---
description: Archive a completed change in the experimental workflow
---
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
+170
View File
@@ -0,0 +1,170 @@
---
description: Enter explore mode - think through ideas, investigate problems, clarify requirements
---
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
+103
View File
@@ -0,0 +1,103 @@
---
description: Propose a new change - create it and generate all artifacts in one step
---
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
@@ -0,0 +1,156 @@
---
name: openspec-apply-change
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name. 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 - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
- 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 openspec-continue-change
- 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! Ready to archive this change.
```
**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
@@ -0,0 +1,114 @@
---
name: openspec-archive-change
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name. 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
- Use **AskUserQuestion tool** to confirm user wants to proceed
- 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
- Use **AskUserQuestion tool** to confirm user wants to proceed
- 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
- Whether specs were synced (if applicable)
- 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 (or "No delta specs" or "Sync skipped")
All artifacts complete. All tasks complete.
```
**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 openspec-sync-specs approach (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
+288
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
+110
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
@@ -54,6 +54,37 @@ public class ClubRoleClaimsTransformation : IClaimsTransformation
return Task.FromResult(principal); return Task.FromResult(principal);
} }
// --- NEW: Skip DB role lookup if user is a global admin ---
var realmAccess = principal.FindFirst("realm_access")?.Value;
if (!string.IsNullOrEmpty(realmAccess) && IsAdminUser(realmAccess))
{
return Task.FromResult(principal);
}
// ---------------------------------------------------------
static bool IsAdminUser(string realmAccess)
{
try
{
using var doc = System.Text.Json.JsonDocument.Parse(realmAccess);
if (doc.RootElement.TryGetProperty("roles", out var rolesElement) &&
rolesElement.ValueKind == System.Text.Json.JsonValueKind.Array)
{
foreach (var role in rolesElement.EnumerateArray())
{
if (role.GetString()?.Equals("admin", StringComparison.OrdinalIgnoreCase) == true)
return true;
}
}
}
catch
{
// If JSON parsing fails, fallback to string contains check
return realmAccess.Contains("admin", StringComparison.OrdinalIgnoreCase);
}
return false;
}
// Look up the user's role in the database for the requested tenant // Look up the user's role in the database for the requested tenant
_httpContextAccessor.HttpContext!.Items["TenantId"] = tenantId; _httpContextAccessor.HttpContext!.Items["TenantId"] = tenantId;
var memberRole = GetMemberRole(userIdClaim, tenantId); var memberRole = GetMemberRole(userIdClaim, tenantId);
@@ -22,14 +22,16 @@ public class TenantValidationMiddleware
return; return;
} }
// Exempt bootstrap and admin endpoints from tenant validation // Exempt bootstrap, admin, debug, and Keycloak OIDC endpoints from tenant validation
if (context.Request.Path.StartsWithSegments("/api/clubs/me") || if (context.Request.Path.StartsWithSegments("/api/clubs/me") ||
context.Request.Path.StartsWithSegments("/api/admin")) context.Request.Path.StartsWithSegments("/api/admin") ||
{ context.Request.Path.StartsWithSegments("/api/debug") ||
_logger.LogInformation("TenantValidationMiddleware: Exempting {Path} from tenant validation", context.Request.Path); context.Request.Path.StartsWithSegments("/realms"))
await _next(context); {
return; _logger.LogInformation("TenantValidationMiddleware: Exempting {Path} from tenant validation", context.Request.Path);
} await _next(context);
return;
}
if (!context.Request.Headers.TryGetValue("X-Tenant-Id", out var tenantIdHeader) || if (!context.Request.Headers.TryGetValue("X-Tenant-Id", out var tenantIdHeader) ||
string.IsNullOrWhiteSpace(tenantIdHeader)) string.IsNullOrWhiteSpace(tenantIdHeader))
@@ -44,6 +46,37 @@ public class TenantValidationMiddleware
if (string.IsNullOrEmpty(clubsClaim)) if (string.IsNullOrEmpty(clubsClaim))
{ {
// NEW: Skip check if user is a global admin
var realmAccess = context.User.FindFirst("realm_access")?.Value;
if (!string.IsNullOrEmpty(realmAccess) && IsAdminUser(realmAccess))
{
await _next(context);
return;
}
static bool IsAdminUser(string realmAccess)
{
try
{
using var doc = System.Text.Json.JsonDocument.Parse(realmAccess);
if (doc.RootElement.TryGetProperty("roles", out var rolesElement) &&
rolesElement.ValueKind == System.Text.Json.JsonValueKind.Array)
{
foreach (var role in rolesElement.EnumerateArray())
{
if (role.GetString()?.Equals("admin", StringComparison.OrdinalIgnoreCase) == true)
return true;
}
}
}
catch
{
// If JSON parsing fails, fallback to string contains check
return realmAccess.Contains("admin", StringComparison.OrdinalIgnoreCase);
}
return false;
}
context.Response.StatusCode = StatusCodes.Status403Forbidden; context.Response.StatusCode = StatusCodes.Status403Forbidden;
await context.Response.WriteAsJsonAsync(new { error = "User does not have clubs claim" }); await context.Response.WriteAsJsonAsync(new { error = "User does not have clubs claim" });
return; return;
+129 -6
View File
@@ -31,6 +31,18 @@ builder.Services.AddScoped<MemberSyncService>();
builder.Services.AddScoped<TenantDbTransactionInterceptor>(); builder.Services.AddScoped<TenantDbTransactionInterceptor>();
builder.Services.AddSingleton<SaveChangesTenantInterceptor>(); builder.Services.AddSingleton<SaveChangesTenantInterceptor>();
// Add CORS to allow frontend requests
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowFrontend", policy =>
{
policy.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => .AddJwtBearer(options =>
{ {
@@ -38,12 +50,75 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
options.Audience = builder.Configuration["Keycloak:Audience"]; options.Audience = builder.Configuration["Keycloak:Audience"];
options.RequireHttpsMetadata = false; options.RequireHttpsMetadata = false;
options.MapInboundClaims = false; options.MapInboundClaims = false;
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
// For Docker internal communication, configure metadata and signing key resolution
// to bypass the hostname mismatch in Keycloak's discovery endpoint
var keycloakAuthority = builder.Configuration["Keycloak:Authority"];
var keycloakInternalUrl = "http://keycloak:8081";
if (keycloakAuthority?.Contains("keycloak:") == true)
{ {
ValidateIssuer = false, // Disabled for local dev - external clients use localhost:8080, internal use keycloak:8080 // Set metadata address to internal Keycloak URL
ValidateAudience = true, options.MetadataAddress = $"{keycloakAuthority}/.well-known/openid-configuration";
ValidateLifetime = true,
ValidateIssuerSigningKey = true // Configure custom signing key resolver to fetch from internal Keycloak URL
// This overrides the URLs returned in the discovery document
var httpClient = new HttpClient();
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKeyResolver = (token, securityToken, kid, validationParameters) =>
{
// Fetch JWKS from internal Keycloak URL
var jwksUrl = $"{keycloakInternalUrl}/realms/workclub/protocol/openid-connect/certs";
try
{
var response = httpClient.GetStringAsync(jwksUrl).GetAwaiter().GetResult();
var jwks = new Microsoft.IdentityModel.Tokens.JsonWebKeySet(response);
return jwks.Keys;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to fetch JWKS from {jwksUrl}: {ex.Message}");
return Array.Empty<Microsoft.IdentityModel.Tokens.SecurityKey>();
}
}
};
}
else
{
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true
};
}
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
Console.WriteLine($"JWT Authentication Failed: {context.Exception.Message}");
if (context.Exception.InnerException != null)
{
Console.WriteLine($"Inner Exception: {context.Exception.InnerException.Message}");
}
return Task.CompletedTask;
},
OnTokenValidated = context =>
{
Console.WriteLine($"JWT Token Validated for user: {context.Principal?.Identity?.Name ?? "unknown"}");
return Task.CompletedTask;
},
OnChallenge = context =>
{
Console.WriteLine($"JWT Challenge: {context.Error}");
return Task.CompletedTask;
}
}; };
}); });
@@ -53,7 +128,29 @@ builder.Services.AddAuthorizationBuilder()
.AddPolicy("RequireGlobalAdmin", policy => policy.RequireAssertion(context => .AddPolicy("RequireGlobalAdmin", policy => policy.RequireAssertion(context =>
{ {
var realmAccess = context.User.FindFirst("realm_access")?.Value; var realmAccess = context.User.FindFirst("realm_access")?.Value;
return realmAccess != null && realmAccess.Contains("\"admin\""); if (string.IsNullOrEmpty(realmAccess))
return false;
try
{
using var doc = System.Text.Json.JsonDocument.Parse(realmAccess);
if (doc.RootElement.TryGetProperty("roles", out var rolesElement) &&
rolesElement.ValueKind == System.Text.Json.JsonValueKind.Array)
{
foreach (var role in rolesElement.EnumerateArray())
{
if (role.GetString() == "admin")
return true;
}
}
}
catch
{
// If JSON parsing fails, fallback to string contains check
return realmAccess.Contains("admin", StringComparison.OrdinalIgnoreCase);
}
return false;
})) }))
.AddPolicy("RequireManager", policy => policy.RequireRole("Manager")) .AddPolicy("RequireManager", policy => policy.RequireRole("Manager"))
.AddPolicy("RequireMember", policy => policy.RequireRole("Manager", "Member")) .AddPolicy("RequireMember", policy => policy.RequireRole("Manager", "Member"))
@@ -89,6 +186,11 @@ if (app.Environment.IsDevelopment())
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseCors("AllowFrontend");
// IMPORTANT: Order matters!
// 1. Authentication must come before tenant validation so JWT middleware can fetch JWKS
// 2. Tenant validation should come after auth but before endpoints
app.UseAuthentication(); app.UseAuthentication();
app.UseMiddleware<TenantValidationMiddleware>(); app.UseMiddleware<TenantValidationMiddleware>();
app.UseAuthorization(); app.UseAuthorization();
@@ -121,9 +223,30 @@ app.MapGet("/weatherforecast", () =>
}) })
.WithName("GetWeatherForecast"); .WithName("GetWeatherForecast");
// Simple test endpoint for middleware validation tests
app.MapGet("/api/test", () => Results.Ok(new { message = "Test endpoint" })) app.MapGet("/api/test", () => Results.Ok(new { message = "Test endpoint" }))
.RequireAuthorization(); .RequireAuthorization();
app.MapGet("/api/debug/claims", (HttpContext context) =>
{
var claims = context.User.Claims.Select(c => new { c.Type, c.Value }).ToList();
var realmAccess = context.User.FindFirst("realm_access")?.Value;
// Check if the authorization header is present
var authHeader = context.Request.Headers["Authorization"].FirstOrDefault();
return Results.Ok(new
{
isAuthenticated = context.User.Identity?.IsAuthenticated ?? false,
authenticationType = context.User.Identity?.AuthenticationType,
claimCount = claims.Count,
claims = claims,
realmAccess = realmAccess,
hasAuthHeader = !string.IsNullOrEmpty(authHeader),
authHeaderPrefix = authHeader?.Substring(0, Math.Min(20, authHeader?.Length ?? 0))
});
});
app.MapTaskEndpoints(); app.MapTaskEndpoints();
app.MapShiftEndpoints(); app.MapShiftEndpoints();
app.MapClubEndpoints(); app.MapClubEndpoints();
@@ -9,10 +9,12 @@ namespace WorkClub.Api.Services;
public class AdminClubService public class AdminClubService
{ {
private readonly AppDbContext _context; private readonly AppDbContext _context;
private readonly IHttpContextAccessor _httpContextAccessor;
public AdminClubService(AppDbContext context) public AdminClubService(AppDbContext context, IHttpContextAccessor httpContextAccessor)
{ {
_context = context; _context = context;
_httpContextAccessor = httpContextAccessor;
} }
public async Task<List<ClubDetailDto>> GetAllClubsAsync() public async Task<List<ClubDetailDto>> GetAllClubsAsync()
@@ -33,7 +35,15 @@ public class AdminClubService
public async Task<ClubDetailDto> CreateClubAsync(CreateClubRequest request) public async Task<ClubDetailDto> CreateClubAsync(CreateClubRequest request)
{ {
var tenantId = Guid.NewGuid().ToString(); var tenantId = "club-" + Guid.NewGuid().ToString().Substring(0, 8);
// Ensure interceptors can see the new tenantId
var httpContext = _httpContextAccessor.HttpContext;
if (httpContext != null)
{
httpContext.Items["TenantId"] = tenantId;
}
var club = new Club var club = new Club
{ {
Id = Guid.NewGuid(), Id = Guid.NewGuid(),
+32 -30
View File
@@ -76,26 +76,27 @@ public class ShiftService
{ {
var shift = await _context.Shifts.FindAsync(id); var shift = await _context.Shifts.FindAsync(id);
if (shift == null) if (shift == null)
return null; return null;
var signups = await (from ss in _context.ShiftSignups var signups = await (from ss in _context.ShiftSignups
where ss.ShiftId == id where ss.ShiftId == id
join m in _context.Members on ss.MemberId equals m.Id join m in _context.Members on ss.MemberId equals m.Id
orderby ss.SignedUpAt orderby ss.SignedUpAt
select new { ss.Id, ss.MemberId, m.ExternalUserId, ss.SignedUpAt }) select new { ss.Id, ss.MemberId, m.DisplayName, m.ExternalUserId, ss.SignedUpAt })
.ToListAsync(); .ToListAsync();
var signupDtos = signups.Select(ss => new ShiftSignupDto( var signupDtos = signups.Select(ss => new ShiftSignupDto(
ss.Id, ss.Id,
ss.MemberId, ss.MemberId,
ss.ExternalUserId, ss.DisplayName,
ss.SignedUpAt ss.ExternalUserId,
)).ToList(); ss.SignedUpAt
)).ToList();
var isSignedUp = currentExternalUserId != null && signupDtos.Any(s => s.ExternalUserId == currentExternalUserId); var isSignedUp = currentExternalUserId != null && signupDtos.Any(s => s.ExternalUserId == currentExternalUserId);
return new ShiftDetailDto( return new ShiftDetailDto(
shift.Id, shift.Id,
shift.Title, shift.Title,
shift.Description, shift.Description,
@@ -190,23 +191,24 @@ public class ShiftService
return (null, "Shift was modified by another user. Please refresh and try again.", true); return (null, "Shift was modified by another user. Please refresh and try again.", true);
} }
var signups = await (from ss in _context.ShiftSignups var signups = await (from ss in _context.ShiftSignups
where ss.ShiftId == id where ss.ShiftId == id
join m in _context.Members on ss.MemberId equals m.Id join m in _context.Members on ss.MemberId equals m.Id
orderby ss.SignedUpAt orderby ss.SignedUpAt
select new { ss.Id, ss.MemberId, m.ExternalUserId, ss.SignedUpAt }) select new { ss.Id, ss.MemberId, m.DisplayName, m.ExternalUserId, ss.SignedUpAt })
.ToListAsync(); .ToListAsync();
var signupDtos = signups.Select(ss => new ShiftSignupDto( var signupDtos = signups.Select(ss => new ShiftSignupDto(
ss.Id, ss.Id,
ss.MemberId, ss.MemberId,
ss.ExternalUserId, ss.DisplayName,
ss.SignedUpAt ss.ExternalUserId,
)).ToList(); ss.SignedUpAt
)).ToList();
var isSignedUp = currentExternalUserId != null && signupDtos.Any(s => s.ExternalUserId == currentExternalUserId); var isSignedUp = currentExternalUserId != null && signupDtos.Any(s => s.ExternalUserId == currentExternalUserId);
var dto = new ShiftDetailDto( var dto = new ShiftDetailDto(
shift.Id, shift.Id,
shift.Title, shift.Title,
shift.Description, shift.Description,
+139 -93
View File
@@ -30,67 +30,89 @@ public class TaskService
} }
} }
var total = await query.CountAsync(); var total = await query.CountAsync();
var items = await query var items = await query
.OrderBy(w => w.CreatedAt) .OrderBy(w => w.CreatedAt)
.Skip((page - 1) * pageSize) .Skip((page - 1) * pageSize)
.Take(pageSize) .Take(pageSize)
.ToListAsync(); .ToListAsync();
Guid? memberId = null; // Get current member ID for IsAssignedToMe check
if (currentExternalUserId != null) Guid? currentMemberId = null;
{ if (currentExternalUserId != null)
var tenantId = _tenantProvider.GetTenantId(); {
memberId = await _context.Members var tenantId = _tenantProvider.GetTenantId();
.Where(m => m.ExternalUserId == currentExternalUserId && m.TenantId == tenantId) currentMemberId = await _context.Members
.Select(m => m.Id) .Where(m => m.ExternalUserId == currentExternalUserId && m.TenantId == tenantId)
.FirstOrDefaultAsync(); .Select(m => m.Id)
} .FirstOrDefaultAsync();
}
var itemDtos = items.Select(w => new TaskListItemDto( // Get all assignee IDs to fetch their names in bulk
w.Id, var assigneeIds = items.Where(w => w.AssigneeId.HasValue).Select(w => w.AssigneeId!.Value).Distinct().ToList();
w.Title, var assigneeNames = await _context.Members
w.Status.ToString(), .Where(m => assigneeIds.Contains(m.Id))
w.AssigneeId, .Select(m => new { m.Id, m.DisplayName })
w.CreatedAt, .ToDictionaryAsync(m => m.Id, m => m.DisplayName);
memberId != null && w.AssigneeId == memberId
)).ToList();
return new TaskListDto(itemDtos, total, page, pageSize); var itemDtos = items.Select(w => new TaskListItemDto(
} w.Id,
w.Title,
w.Status.ToString(),
w.AssigneeId,
w.AssigneeId.HasValue && assigneeNames.TryGetValue(w.AssigneeId.Value, out var name) ? name : null,
w.CreatedAt,
currentMemberId != null && w.AssigneeId == currentMemberId
)).ToList();
public async Task<TaskDetailDto?> GetTaskByIdAsync(Guid id, string? currentExternalUserId = null) return new TaskListDto(itemDtos, total, page, pageSize);
{ }
var workItem = await _context.WorkItems.FindAsync(id);
if (workItem == null) public async Task<TaskDetailDto?> GetTaskByIdAsync(Guid id, string? currentExternalUserId = null)
return null; {
var workItem = await _context.WorkItems.FindAsync(id);
Guid? memberId = null; if (workItem == null)
if (currentExternalUserId != null) return null;
{
var tenantId = _tenantProvider.GetTenantId();
memberId = await _context.Members
.Where(m => m.ExternalUserId == currentExternalUserId && m.TenantId == tenantId)
.Select(m => m.Id)
.FirstOrDefaultAsync();
}
return new TaskDetailDto( // Get current member ID for IsAssignedToMe check
workItem.Id, Guid? currentMemberId = null;
workItem.Title, if (currentExternalUserId != null)
workItem.Description, {
workItem.Status.ToString(), var tenantId = _tenantProvider.GetTenantId();
workItem.AssigneeId, currentMemberId = await _context.Members
workItem.CreatedById, .Where(m => m.ExternalUserId == currentExternalUserId && m.TenantId == tenantId)
workItem.ClubId, .Select(m => m.Id)
workItem.DueDate, .FirstOrDefaultAsync();
workItem.CreatedAt, }
workItem.UpdatedAt,
memberId != null && workItem.AssigneeId == memberId // Fetch assignee and creator names
); var memberIds = new List<Guid>();
} if (workItem.AssigneeId.HasValue) memberIds.Add(workItem.AssigneeId.Value);
memberIds.Add(workItem.CreatedById);
var memberNames = await _context.Members
.Where(m => memberIds.Contains(m.Id))
.Select(m => new { m.Id, m.DisplayName })
.ToDictionaryAsync(m => m.Id, m => m.DisplayName);
return new TaskDetailDto(
workItem.Id,
workItem.Title,
workItem.Description,
workItem.Status.ToString(),
workItem.AssigneeId,
workItem.AssigneeId.HasValue && memberNames.TryGetValue(workItem.AssigneeId.Value, out var assigneeName) ? assigneeName : null,
workItem.CreatedById,
memberNames.TryGetValue(workItem.CreatedById, out var createdByName) ? createdByName : null,
workItem.ClubId,
workItem.DueDate,
workItem.CreatedAt,
workItem.UpdatedAt,
currentMemberId != null && workItem.AssigneeId == currentMemberId
);
}
public async Task<(TaskDetailDto? task, string? error)> CreateTaskAsync(CreateTaskRequest request, Guid createdById) public async Task<(TaskDetailDto? task, string? error)> CreateTaskAsync(CreateTaskRequest request, Guid createdById)
{ {
@@ -111,24 +133,35 @@ public class TaskService
UpdatedAt = DateTimeOffset.UtcNow UpdatedAt = DateTimeOffset.UtcNow
}; };
_context.WorkItems.Add(workItem); _context.WorkItems.Add(workItem);
await _context.SaveChangesAsync(); await _context.SaveChangesAsync();
var dto = new TaskDetailDto( // Fetch creator and assignee names
workItem.Id, var memberIds = new List<Guid> { createdById };
workItem.Title, if (workItem.AssigneeId.HasValue) memberIds.Add(workItem.AssigneeId.Value);
workItem.Description,
workItem.Status.ToString(),
workItem.AssigneeId,
workItem.CreatedById,
workItem.ClubId,
workItem.DueDate,
workItem.CreatedAt,
workItem.UpdatedAt,
false
);
return (dto, null); var memberNames = await _context.Members
.Where(m => memberIds.Contains(m.Id))
.Select(m => new { m.Id, m.DisplayName })
.ToDictionaryAsync(m => m.Id, m => m.DisplayName);
var dto = new TaskDetailDto(
workItem.Id,
workItem.Title,
workItem.Description,
workItem.Status.ToString(),
workItem.AssigneeId,
workItem.AssigneeId.HasValue && memberNames.TryGetValue(workItem.AssigneeId.Value, out var assigneeName) ? assigneeName : null,
workItem.CreatedById,
memberNames.TryGetValue(workItem.CreatedById, out var createdByName) ? createdByName : null,
workItem.ClubId,
workItem.DueDate,
workItem.CreatedAt,
workItem.UpdatedAt,
false
);
return (dto, null);
} }
public async Task<(TaskDetailDto? task, string? error, bool isConflict)> UpdateTaskAsync(Guid id, UpdateTaskRequest request, string? currentExternalUserId = null) public async Task<(TaskDetailDto? task, string? error, bool isConflict)> UpdateTaskAsync(Guid id, UpdateTaskRequest request, string? currentExternalUserId = null)
@@ -176,32 +209,45 @@ public class TaskService
return (null, "Task was modified by another user. Please refresh and try again.", true); return (null, "Task was modified by another user. Please refresh and try again.", true);
} }
Guid? memberId = null; // Get current member ID for IsAssignedToMe check
if (currentExternalUserId != null) Guid? currentMemberId = null;
{ if (currentExternalUserId != null)
var tenantId = _tenantProvider.GetTenantId(); {
memberId = await _context.Members var tenantId = _tenantProvider.GetTenantId();
.Where(m => m.ExternalUserId == currentExternalUserId && m.TenantId == tenantId) currentMemberId = await _context.Members
.Select(m => m.Id) .Where(m => m.ExternalUserId == currentExternalUserId && m.TenantId == tenantId)
.FirstOrDefaultAsync(); .Select(m => m.Id)
} .FirstOrDefaultAsync();
}
var dto = new TaskDetailDto( // Fetch assignee and creator names
workItem.Id, var memberIds = new List<Guid>();
workItem.Title, if (workItem.AssigneeId.HasValue) memberIds.Add(workItem.AssigneeId.Value);
workItem.Description, memberIds.Add(workItem.CreatedById);
workItem.Status.ToString(),
workItem.AssigneeId,
workItem.CreatedById,
workItem.ClubId,
workItem.DueDate,
workItem.CreatedAt,
workItem.UpdatedAt,
memberId != null && workItem.AssigneeId == memberId
);
return (dto, null, false); var memberNames = await _context.Members
} .Where(m => memberIds.Contains(m.Id))
.Select(m => new { m.Id, m.DisplayName })
.ToDictionaryAsync(m => m.Id, m => m.DisplayName);
var dto = new TaskDetailDto(
workItem.Id,
workItem.Title,
workItem.Description,
workItem.Status.ToString(),
workItem.AssigneeId,
workItem.AssigneeId.HasValue && memberNames.TryGetValue(workItem.AssigneeId.Value, out var assigneeName) ? assigneeName : null,
workItem.CreatedById,
memberNames.TryGetValue(workItem.CreatedById, out var createdByName) ? createdByName : null,
workItem.ClubId,
workItem.DueDate,
workItem.CreatedAt,
workItem.UpdatedAt,
currentMemberId != null && workItem.AssigneeId == currentMemberId
);
return (dto, null, false);
}
public async Task<bool> DeleteTaskAsync(Guid id) public async Task<bool> DeleteTaskAsync(Guid id)
{ {
@@ -17,7 +17,9 @@ public record ShiftDetailDto(
); );
public record ShiftSignupDto( public record ShiftSignupDto(
Guid Id, Guid Id,
Guid MemberId, string? ExternalUserId, Guid MemberId,
DateTimeOffset SignedUpAt string? MemberName,
string? ExternalUserId,
DateTimeOffset SignedUpAt
); );
@@ -1,15 +1,17 @@
namespace WorkClub.Application.Tasks.DTOs; namespace WorkClub.Application.Tasks.DTOs;
public record TaskDetailDto( public record TaskDetailDto(
Guid Id, Guid Id,
string Title, string Title,
string? Description, string? Description,
string Status, string Status,
Guid? AssigneeId, Guid? AssigneeId,
Guid CreatedById, string? AssigneeName,
Guid ClubId, Guid CreatedById,
DateTimeOffset? DueDate, string? CreatedByName,
DateTimeOffset CreatedAt, Guid ClubId,
DateTimeOffset UpdatedAt, DateTimeOffset? DueDate,
bool IsAssignedToMe DateTimeOffset CreatedAt,
DateTimeOffset UpdatedAt,
bool IsAssignedToMe
); );
@@ -8,10 +8,11 @@ public record TaskListDto(
); );
public record TaskListItemDto( public record TaskListItemDto(
Guid Id, Guid Id,
string Title, string Title,
string Status, string Status,
Guid? AssigneeId, Guid? AssigneeId,
DateTimeOffset CreatedAt, string? AssigneeName,
bool IsAssignedToMe DateTimeOffset CreatedAt,
bool IsAssignedToMe
); );
@@ -185,11 +185,6 @@ public class TenantDbTransactionInterceptor : DbCommandInterceptor, IDbTransacti
{ {
var tenantId = _httpContextAccessor.HttpContext?.Items["TenantId"] as string; var tenantId = _httpContextAccessor.HttpContext?.Items["TenantId"] as string;
if (string.IsNullOrWhiteSpace(tenantId)) return null; if (string.IsNullOrWhiteSpace(tenantId)) return null;
if (!Guid.TryParse(tenantId, out _))
{
_logger.LogWarning("Invalid tenant ID format: {TenantId}", tenantId);
return null;
}
return tenantId; return tenantId;
} }
@@ -0,0 +1,57 @@
using System.Net;
using System.Net.Http.Json;
using System.Security.Claims;
using System.Text.Json;
using WorkClub.Domain.Enums;
using WorkClub.Application.Clubs.DTOs;
using WorkClub.Tests.Integration.Infrastructure;
using Xunit;
namespace WorkClub.Tests.Integration.Clubs;
public class AdminClubEndpointsTests : IntegrationTestBase
{
public AdminClubEndpointsTests(CustomWebApplicationFactory<Program> factory) : base(factory)
{
}
[Fact]
public async Task CreateClub_WithAdminRole_ReturnsCreated()
{
AuthenticateAsAdmin();
var request = new CreateClubRequest("New Admin Club", SportType.Tennis, "Desc");
var response = await Client.PostAsJsonAsync("/api/admin/clubs", request);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
}
[Fact]
public async Task CreateClub_WithoutAdminRole_ReturnsForbidden()
{
AuthenticateAsNonAdmin();
var request = new CreateClubRequest("New Club", SportType.Tennis, "Desc");
var response = await Client.PostAsJsonAsync("/api/admin/clubs", request);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
private void AuthenticateAsAdmin()
{
Client.DefaultRequestHeaders.Remove("X-Test-Email");
Client.DefaultRequestHeaders.Add("X-Test-Email", "admin@workclub.com");
Client.DefaultRequestHeaders.Remove("X-Test-Realm-Access");
Client.DefaultRequestHeaders.Add("X-Test-Realm-Access", "{\"roles\":[\"admin\"]}");
}
private void AuthenticateAsNonAdmin()
{
Client.DefaultRequestHeaders.Remove("X-Test-Email");
Client.DefaultRequestHeaders.Add("X-Test-Email", "user@workclub.com");
Client.DefaultRequestHeaders.Remove("X-Test-Realm-Access");
Client.DefaultRequestHeaders.Add("X-Test-Realm-Access", "{\"roles\":[\"user\"]}");
}
}
@@ -184,18 +184,34 @@ public class ClubEndpointsTests : IntegrationTestBase
Assert.Equal("Cycling", club.SportType); Assert.Equal("Cycling", club.SportType);
} }
[Fact] [Fact]
public async Task GetClubsCurrent_NoTenantContext_ReturnsBadRequest() public async Task GetClubsCurrent_NoTenantContext_ReturnsBadRequest()
{
AuthenticateAs("admin@test.com", new Dictionary<string, string>
{ {
AuthenticateAs("admin@test.com", new Dictionary<string, string> [Tenant1Id] = "Admin"
{ }, userId: "admin-user-id");
[Tenant1Id] = "Admin"
}, userId: "admin-user-id");
var response = await Client.GetAsync("/api/clubs/current"); var response = await Client.GetAsync("/api/clubs/current");
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
} }
[Fact]
public async Task GetClubsCurrent_InvalidTenant_ReturnsForbidden()
{
AuthenticateAs("admin@test.com", new Dictionary<string, string>
{
[Tenant1Id] = "Admin"
}, userId: "admin-user-id");
// Set tenant that user is not a member of
SetTenant("invalid-tenant-id");
var response = await Client.GetAsync("/api/clubs/current");
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact] [Fact]
public async Task GetClubsMe_Unauthenticated_ReturnsUnauthorized() public async Task GetClubsMe_Unauthenticated_ReturnsUnauthorized()
@@ -57,20 +57,38 @@ public class CustomWebApplicationFactory<TProgram> : WebApplicationFactory<TProg
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>(); var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
db.Database.Migrate(); db.Database.Migrate();
using var conn = new Npgsql.NpgsqlConnection(_postgresContainer.GetConnectionString()); using var conn = new Npgsql.NpgsqlConnection(_postgresContainer.GetConnectionString());
conn.Open(); conn.Open();
using var cmd = conn.CreateCommand(); using var cmd = conn.CreateCommand();
cmd.CommandText = @" cmd.CommandText = @"
DO $$ BEGIN DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'rls_test_user') THEN -- Create test user for RLS
CREATE USER rls_test_user WITH PASSWORD 'rlspass'; IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'rls_test_user') THEN
GRANT CONNECT ON DATABASE workclub_test TO rls_test_user; CREATE USER rls_test_user WITH PASSWORD 'rlspass';
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO rls_test_user; END IF;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO rls_test_user;
END IF; -- Grant basic permissions to test user
END $$; GRANT CONNECT ON DATABASE workclub_test TO rls_test_user;
"; GRANT USAGE ON SCHEMA public TO rls_test_user;
cmd.ExecuteNonQuery(); GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO rls_test_user;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO rls_test_user;
-- Create app_admin role for bypassing RLS
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'app_admin') THEN
CREATE ROLE app_admin WITH BYPASSRLS;
END IF;
-- Grant app_admin full access to tables
GRANT CONNECT ON DATABASE workclub_test TO app_admin;
GRANT USAGE ON SCHEMA public TO app_admin;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO app_admin;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO app_admin;
-- Allow rls_test_user to assume app_admin role
GRANT app_admin TO rls_test_user;
END $$;
";
cmd.ExecuteNonQuery();
}); });
builder.UseEnvironment("Test"); builder.UseEnvironment("Test");
@@ -30,9 +30,10 @@ public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions
var emailClaim = Context.Request.Headers["X-Test-Email"].ToString(); var emailClaim = Context.Request.Headers["X-Test-Email"].ToString();
var userIdClaim = Context.Request.Headers["X-Test-UserId"].ToString(); var userIdClaim = Context.Request.Headers["X-Test-UserId"].ToString();
var clubRolesJson = Context.Request.Headers["X-Test-ClubRoles"].ToString(); var clubRolesJson = Context.Request.Headers["X-Test-ClubRoles"].ToString();
var realmAccessClaim = Context.Request.Headers["X-Test-Realm-Access"].ToString();
// If no test auth headers are present, return NoResult (unauthenticated) // If no test auth headers are present, return NoResult (unauthenticated)
if (string.IsNullOrEmpty(emailClaim) && string.IsNullOrEmpty(userIdClaim) && string.IsNullOrEmpty(clubsClaim)) if (string.IsNullOrEmpty(emailClaim) && string.IsNullOrEmpty(userIdClaim) && string.IsNullOrEmpty(clubsClaim) && string.IsNullOrEmpty(realmAccessClaim))
{ {
return Task.FromResult(AuthenticateResult.NoResult()); return Task.FromResult(AuthenticateResult.NoResult());
} }
@@ -47,6 +48,11 @@ public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions
new Claim("preferred_username", resolvedEmail), new Claim("preferred_username", resolvedEmail),
}; };
if (!string.IsNullOrEmpty(realmAccessClaim))
{
claims.Add(new Claim("realm_access", realmAccessClaim, ClaimValueTypes.String));
}
if (!string.IsNullOrEmpty(clubsClaim)) if (!string.IsNullOrEmpty(clubsClaim))
{ {
claims.Add(new Claim("clubs", clubsClaim)); claims.Add(new Claim("clubs", clubsClaim));
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+17 -5
View File
@@ -39,8 +39,15 @@ services:
KC_DB_PASSWORD: keycloakpass KC_DB_PASSWORD: keycloakpass
KC_HEALTH_ENABLED: "true" KC_HEALTH_ENABLED: "true"
KC_LOG_LEVEL: INFO KC_LOG_LEVEL: INFO
KC_HOSTNAME: "http://localhost:8080"
KC_HOSTNAME_STRICT: "false"
KC_PROXY: "edge"
KC_HTTP_PORT: "8081"
# Additional hostname for internal Docker communication
KC_HOSTNAME_ADMIN: "http://keycloak:8081"
KC_SPI_HOSTNAME_DEFAULT_ADMIN: "keycloak:8081"
ports: ports:
- "8080:8080" - "8080:8081"
volumes: volumes:
- ./infra/keycloak:/opt/keycloak/data/import - ./infra/keycloak:/opt/keycloak/data/import
depends_on: depends_on:
@@ -59,18 +66,22 @@ services:
container_name: workclub_api container_name: workclub_api
environment: environment:
ASPNETCORE_ENVIRONMENT: Development ASPNETCORE_ENVIRONMENT: Development
ASPNETCORE_URLS: "http://+:8080"
ConnectionStrings__DefaultConnection: "Host=postgres;Port=5432;Database=workclub;Username=workclub;Password=dev_password_change_in_production" ConnectionStrings__DefaultConnection: "Host=postgres;Port=5432;Database=workclub;Username=workclub;Password=dev_password_change_in_production"
Keycloak__Authority: "http://keycloak:8080/realms/workclub" Keycloak__Authority: "http://keycloak:8081/realms/workclub"
Keycloak__Audience: "workclub-api" Keycloak__Audience: "workclub-api"
Keycloak__TokenValidationParameters__ValidateIssuer: "false" Keycloak__TokenValidationParameters__ValidateIssuer: "false"
ports: ports:
- "5001:8080" - "5001:8080"
extra_hosts:
- "localhost:172.18.0.1"
- "127.0.0.1:172.18.0.1"
working_dir: /app
volumes: volumes:
- ./backend:/app:cached - ./backend:/app:cached
depends_on: depends_on:
postgres: postgres:
condition: service_healthy condition: service_healthy
command: watch run WorkClub.Api/WorkClub.Api.csproj
networks: networks:
- app-network - app-network
@@ -84,12 +95,13 @@ services:
environment: environment:
NEXT_PUBLIC_API_URL: "http://localhost:5001" NEXT_PUBLIC_API_URL: "http://localhost:5001"
API_INTERNAL_URL: "http://dotnet-api:8080" API_INTERNAL_URL: "http://dotnet-api:8080"
NEXTAUTH_URL: "http://localhost:3000"
NEXTAUTH_SECRET: "dev-secret-change-in-production-use-openssl-rand-base64-32" NEXTAUTH_SECRET: "dev-secret-change-in-production-use-openssl-rand-base64-32"
AUTH_SECRET: "dev-secret-change-in-production-use-openssl-rand-base64-32"
AUTH_TRUST_HOST: "true"
KEYCLOAK_CLIENT_ID: "workclub-app" KEYCLOAK_CLIENT_ID: "workclub-app"
KEYCLOAK_CLIENT_SECRET: "dev-secret-workclub-api-change-in-production" KEYCLOAK_CLIENT_SECRET: "dev-secret-workclub-api-change-in-production"
KEYCLOAK_ISSUER: "http://localhost:8080/realms/workclub" KEYCLOAK_ISSUER: "http://localhost:8080/realms/workclub"
KEYCLOAK_ISSUER_INTERNAL: "http://keycloak:8080/realms/workclub" KEYCLOAK_ISSUER_INTERNAL: "http://keycloak:8081/realms/workclub"
NEXT_PUBLIC_KEYCLOAK_ISSUER: "http://localhost:8080/realms/workclub" NEXT_PUBLIC_KEYCLOAK_ISSUER: "http://localhost:8080/realms/workclub"
ports: ports:
- "3000:3000" - "3000:3000"
@@ -67,9 +67,9 @@ export default function ShiftDetailPage({ params }: { params: Promise<{ id: stri
<p className="text-sm text-muted-foreground">No sign-ups yet</p> <p className="text-sm text-muted-foreground">No sign-ups yet</p>
) : ( ) : (
<ul className="list-disc list-inside text-sm"> <ul className="list-disc list-inside text-sm">
{shift.signups.map((signup) => ( {shift.signups.map((signup) => (
<li key={signup.id}>Member ID: {signup.memberId}</li> <li key={signup.id}>{signup.memberName || signup.memberId}</li>
))} ))}
</ul> </ul>
)} )}
</div> </div>
@@ -85,11 +85,11 @@ export default function TaskDetailPage({ params }: { params: Promise<{ id: strin
<div className="grid grid-cols-2 gap-4"> <div className="grid grid-cols-2 gap-4">
<div> <div>
<p className="text-sm font-medium text-muted-foreground">Assignee</p> <p className="text-sm font-medium text-muted-foreground">Assignee</p>
<p className="mt-1">{task.assigneeId || 'Unassigned'}</p> <p className="mt-1">{task.assigneeName || 'Unassigned'}</p>
</div> </div>
<div> <div>
<p className="text-sm font-medium text-muted-foreground">Created By</p> <p className="text-sm font-medium text-muted-foreground">Created By</p>
<p className="mt-1">{task.createdById}</p> <p className="mt-1">{task.createdByName || task.createdById}</p>
</div> </div>
<div> <div>
<p className="text-sm font-medium text-muted-foreground">Created At</p> <p className="text-sm font-medium text-muted-foreground">Created At</p>
+1 -1
View File
@@ -89,7 +89,7 @@ export default function TaskListPage() {
{task.status} {task.status}
</Badge> </Badge>
</TableCell> </TableCell>
<TableCell>{task.assigneeId || 'Unassigned'}</TableCell> <TableCell>{task.assigneeName || 'Unassigned'}</TableCell>
<TableCell>{new Date(task.createdAt).toLocaleDateString()}</TableCell> <TableCell>{new Date(task.createdAt).toLocaleDateString()}</TableCell>
<TableCell className="text-right"> <TableCell className="text-right">
<Button variant="outline" size="sm" asChild> <Button variant="outline" size="sm" asChild>
+24 -2
View File
@@ -27,13 +27,12 @@ declare module "next-auth" {
const issuerPublic = process.env.KEYCLOAK_ISSUER! const issuerPublic = process.env.KEYCLOAK_ISSUER!
const issuerInternal = process.env.KEYCLOAK_ISSUER_INTERNAL || issuerPublic const issuerInternal = process.env.KEYCLOAK_ISSUER_INTERNAL || issuerPublic
const oidcPublic = `${issuerPublic}/protocol/openid-connect` const oidcPublic = `${issuerPublic}/protocol/openid-connect`
const oidcInternal = `${issuerInternal}/protocol/openid-connect` const oidcInternal = `${issuerInternal.replace(':8080', ':8081')}/protocol/openid-connect`
export const { handlers, signIn, signOut, auth } = NextAuth({ export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [ providers: [
KeycloakProvider({ KeycloakProvider({
clientId: process.env.KEYCLOAK_CLIENT_ID!, clientId: process.env.KEYCLOAK_CLIENT_ID!,
clientSecret: process.env.KEYCLOAK_CLIENT_SECRET!,
issuer: issuerPublic, issuer: issuerPublic,
authorization: { authorization: {
url: `${oidcPublic}/auth`, url: `${oidcPublic}/auth`,
@@ -41,8 +40,31 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
}, },
token: `${oidcInternal}/token`, token: `${oidcInternal}/token`,
userinfo: `${oidcInternal}/userinfo`, userinfo: `${oidcInternal}/userinfo`,
jwks_endpoint: `${oidcInternal}/certs`,
}) })
], ],
trustHost: true,
cookies: {
pkceCodeVerifier: {
name: "authjs.pkce.code_verifier",
options: {
httpOnly: true,
sameSite: "lax",
path: "/",
secure: false,
},
},
state: {
name: "authjs.state",
options: {
httpOnly: true,
sameSite: "lax",
path: "/",
secure: false,
},
},
},
debug: true,
callbacks: { callbacks: {
async jwt({ token, account }) { async jwt({ token, account }) {
if (account && account.access_token) { if (account && account.access_token) {
+1
View File
@@ -38,6 +38,7 @@ export interface ShiftDetailDto {
export interface ShiftSignupDto { export interface ShiftSignupDto {
id: string; id: string;
memberId: string; memberId: string;
memberName?: string;
externalUserId?: string; externalUserId?: string;
signedUpAt: string; signedUpAt: string;
} }
+3
View File
@@ -14,6 +14,7 @@ export interface TaskListItemDto {
title: string; title: string;
status: string; status: string;
assigneeId: string | null; assigneeId: string | null;
assigneeName?: string;
createdAt: string; createdAt: string;
isAssignedToMe: boolean; isAssignedToMe: boolean;
} }
@@ -24,7 +25,9 @@ export interface TaskDetailDto {
description: string | null; description: string | null;
status: string; status: string;
assigneeId: string | null; assigneeId: string | null;
assigneeName?: string;
createdById: string; createdById: string;
createdByName?: string;
clubId: string; clubId: string;
dueDate: string | null; dueDate: string | null;
createdAt: string; createdAt: string;
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-03-18
@@ -0,0 +1,99 @@
## Context
Currently, the frontend displays raw UUIDs for user references:
- Task list shows `assigneeId` (e.g., "a1b2c3d4-e5f6...") or "Unassigned"
- Task detail shows `assigneeId` and `createdById`
- Shift detail shows `memberId` for each signup
The backend already stores `DisplayName` in the `Member` entity but the API DTOs don't expose it. The `ShiftService` already demonstrates the pattern of joining with Members (lines 82-87), which we can replicate for Tasks.
## Goals / Non-Goals
**Goals:**
- Add member name fields to backend DTOs
- Update TaskService to query and include member names
- Update ShiftService to include member name in ShiftSignupDto
- Update frontend TypeScript interfaces
- Replace UUID displays with names in task/shift UIs
**Non-Goals:**
- No database schema changes
- No changes to authentication or authorization
- No changes to how tasks/shifts are created or updated
- No caching layer for member names
## Decisions
### 1. Add names to existing DTOs vs create new DTOs
**Decision:** Add optional fields to existing DTOs
**Rationale:**
- Keeps API surface simple
- Backward compatible - existing clients ignore new fields
- No breaking changes to existing integrations
**Alternative considered:** Create new DTO versions (e.g., `TaskDetailDtoV2`)
- Rejected: Unnecessary complexity for a simple additive change
### 2. Fetch member names via JOIN vs separate query
**Decision:** Use JOIN in TaskService methods
**Rationale:**
- More efficient - single query per endpoint
- Pattern already exists in ShiftService
- Avoids N+1 query problem
**Alternative considered:** Query members separately and build lookup dictionary
- Rejected: Adds complexity and extra database round-trips
### 3. Handle missing members (orphaned IDs)
**Decision:** Return null for name when member not found
**Rationale:**
- Data integrity issue should surface visibly
- Frontend can display fallback like "Unknown" or keep showing ID
- Logging can track data inconsistencies
### 4. Frontend handling of null names
**Decision:** Frontend shows fallback text when name is null
**Implementation:**
```typescript
// Task list
task.assigneeName || 'Unassigned'
// Task detail
task.assigneeName || 'Unassigned'
task.createdByName || 'Unknown'
// Shift signups
signup.memberName || 'Unknown Member'
```
## Risks / Trade-offs
| Risk | Mitigation |
|------|-----------|
| JOIN adds query complexity | Keep JOINs simple, only on indexed columns (Member.Id) |
| Larger API response payloads | Minimal impact - names are small strings |
| Member names become stale | Acceptable - names rarely change; eventual consistency |
| Database performance degradation | Monitor query execution plans; add caching if needed |
| Partial data on member deletion | Show "Unknown" fallback; log orphaned references |
## Migration Plan
1. **Backend DTO changes** - Add new optional fields
2. **Backend service changes** - Update queries to include names
3. **Frontend type updates** - Add name fields to interfaces
4. **Frontend UI updates** - Replace ID displays with names
**Rollback:**
- DTO changes are backward compatible
- Frontend can revert to showing IDs by changing display logic
- No database changes required
## Open Questions
- Should we include `externalUserId` in the signup display? (Currently available in ShiftSignupDto)
- Do we need to include member email for any display purposes?
- Should we add name fields to shift list items (showing creator name)?
@@ -0,0 +1,34 @@
## Why
Currently, the frontend displays raw UUIDs for user references (assignee, creator, members) which creates a poor user experience. Users should see meaningful names like "Alice Smith" instead of "a1b2c3d4-e5f6-7890-abcd-ef1234567890". The backend already stores display names in the Member entity, but the API DTOs don't expose them.
## What Changes
- **Backend DTOs**: Add name fields to task and shift DTOs
- `TaskListItemDto`: Add `string? AssigneeName`
- `TaskDetailDto`: Add `string? AssigneeName` and `string CreatedByName`
- `ShiftSignupDto`: Add `string MemberName`
- **Backend Services**: Update TaskService and ShiftService to query and populate member names
- Join with Members table to fetch display names
- Include names in DTO construction
- **Frontend Types**: Update TypeScript interfaces to include new name fields
- `TaskListItemDto`, `TaskDetailDto`, `ShiftSignupDto` interfaces
- **Frontend UI**: Replace UUID displays with names
- Task list: show assignee name instead of ID
- Task detail: show assignee and creator names
- Shift detail: show member names in signup list
## Capabilities
### New Capabilities
- `member-name-enrichment`: API DTOs include human-readable member names alongside IDs
### Modified Capabilities
- None (this is purely an enhancement to existing capabilities)
## Impact
- **Backend**: TaskService.cs, ShiftService.cs, and DTOs in WorkClub.Application
- **Frontend**: Tasks pages, Shifts pages, and React hooks (useTasks.ts, useShifts.ts)
- **Database**: Additional JOIN queries on Members table (no schema changes)
- **API Response**: New optional fields in existing endpoints (backward compatible)
@@ -0,0 +1,43 @@
## ADDED Requirements
### Requirement: Task list items include assignee name
The API SHALL return the assignee's display name in TaskListItemDto.
#### Scenario: Task with assignee
- **WHEN** a task is assigned to a member
- **THEN** the TaskListItemDto SHALL include the assignee's DisplayName as `assigneeName`
#### Scenario: Task without assignee
- **WHEN** a task has no assignee
- **THEN** the TaskListItemDto SHALL have `assigneeName` set to null
### Requirement: Task details include creator and assignee names
The API SHALL return the display names of both the creator and assignee in TaskDetailDto.
#### Scenario: Viewing task details
- **WHEN** a user requests task details
- **THEN** the TaskDetailDto SHALL include `createdByName` (the creator's DisplayName)
- **AND** the TaskDetailDto SHALL include `assigneeName` (the assignee's DisplayName, or null if unassigned)
### Requirement: Shift signup includes member name
The API SHALL return the member's display name in ShiftSignupDto.
#### Scenario: Viewing shift signups
- **WHEN** a user views shift details with signups
- **THEN** each ShiftSignupDto SHALL include `memberName` (the member's DisplayName)
### Requirement: Frontend displays names instead of UUIDs
The frontend SHALL render member names instead of UUIDs wherever user references appear.
#### Scenario: Task list view
- **WHEN** viewing the task list
- **THEN** the Assignee column SHALL display the assignee's name (or "Unassigned")
#### Scenario: Task detail view
- **WHEN** viewing a task detail page
- **THEN** the Assignee field SHALL display the assignee's name (or "Unassigned")
- **AND** the Created By field SHALL display the creator's name
#### Scenario: Shift detail view
- **WHEN** viewing a shift detail page with signups
- **THEN** the member list SHALL display each member's name instead of their ID
@@ -0,0 +1,41 @@
## 1. Backend DTO Updates
- [x] 1.1 Update TaskListItemDto.cs to add `string? AssigneeName` field
- [x] 1.2 Update TaskDetailDto.cs to add `string? AssigneeName` and `string? CreatedByName` fields
- [x] 1.3 Update ShiftSignupDto.cs to add `string? MemberName` field
## 2. Backend Service Updates - Tasks
- [x] 2.1 Update TaskService.GetTasksAsync() to join with Members and populate assigneeName
- [x] 2.2 Update TaskService.GetTaskByIdAsync() to join with Members for assignee and creator names
- [x] 2.3 Update TaskService.CreateTaskAsync() to fetch and include creator name in response
- [x] 2.4 Update TaskService.UpdateTaskAsync() to join with Members for assignee and creator names
## 3. Backend Service Updates - Shifts
- [x] 3.1 Update ShiftService.GetShiftByIdAsync() to include member display name in ShiftSignupDto
- [x] 3.2 Update ShiftService.UpdateShiftAsync() to include member display name in ShiftSignupDto
## 4. Frontend Type Updates
- [x] 4.1 Update TaskListItemDto interface in useTasks.ts to add `assigneeName?: string`
- [x] 4.2 Update TaskDetailDto interface in useTasks.ts to add `assigneeName?: string` and `createdByName?: string`
- [x] 4.3 Update ShiftSignupDto interface in useShifts.ts to add `memberName?: string`
## 5. Frontend UI Updates - Tasks
- [x] 5.1 Update tasks/page.tsx to display assigneeName instead of assigneeId
- [x] 5.2 Update tasks/[id]/page.tsx to display assigneeName instead of assigneeId
- [x] 5.3 Update tasks/[id]/page.tsx to display createdByName instead of createdById
## 6. Frontend UI Updates - Shifts
- [x] 6.1 Update shifts/[id]/page.tsx to display memberName instead of memberId in signup list
## 7. Testing & Verification
- [x] 7.1 Run backend build to verify C# compilation succeeds
- [x] 7.2 Run frontend build to verify TypeScript compilation succeeds
- [x] 7.3 Verify task list shows member names correctly
- [x] 7.4 Verify task detail shows assignee and creator names
- [x] 7.5 Verify shift detail shows member names in signup list
+20
View File
@@ -0,0 +1,20 @@
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: |
# Tech stack: TypeScript, React, Node.js
# We use conventional commits
# Domain: e-commerce platform
# Per-artifact rules (optional)
# Add custom rules for specific artifacts.
# Example:
# rules:
# proposal:
# - Keep proposals under 500 words
# - Always include a "Non-goals" section
# tasks:
# - Break tasks into chunks of max 2 hours