Initial commit: specs, OpenSpec roadmap and change proposals

- docs/: system spec, frontend plan and style mockups (v1.0)
- openspec/: plan-system-roadmap plus 14 proposed changes
  (Phase 1 MVP and Phase 2)
- CLAUDE.md, .gitignore, OpenSpec skills and commands

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-05 19:10:03 +08:00
co-authored by Claude Opus 5.5
commit 350e83b58e
102 changed files with 6131 additions and 0 deletions
+201
View File
@@ -0,0 +1,201 @@
---
name: "OPSX: Apply"
description: "Implement tasks from an OpenSpec change (Experimental)"
allowed-tools: Bash(openspec:*)
category: "Workflow"
tags: ["workflow", "artifacts", "experimental"]
---
Implement tasks from an OpenSpec change.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
**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 ask the user to select one
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")
- `planningHome`, `changeRoot`, and `actionContext`: planning scope and edit constraints
- 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:
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
- Progress (total, complete, remaining)
- Task list with status, source path, and source line
- Dynamic instruction based on current state
- Optional `context`: current required project instruction input from the selected root
- Optional `operationGuidance`: current advisory guidance for apply
- `missingArtifacts` (when present): required artifact ids with no output
**Handle states:**
- If `state: "blocked"`: show the message and pause implementation.
- If `missingArtifacts` is non-empty: suggest completing the missing artifacts. Run `openspec status --change "<name>" --json`, select the next `ready` artifact (not `skipped` or `blocked`), and use `openspec instructions "<artifact-id>" --change "<name>" --json` for its rules and template. Keep the selected `--store <id>` on both commands.
- Otherwise, follow the CLI instruction to create or repair the schema-configured tracking file from existing planning artifacts. Do not assume another artifact is ready or start implementation while blocked.
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
Treat `context` as a required prompt-level input. Read and consider it, and
apply relevant project facts, conventions, and constraints while implementing.
Treat `operationGuidance` as optional additive advice. Read and consider every
entry, and follow entries that are applicable and compatible with the built-in
workflow.
Keep both fields separate from CLI-returned state, missing artifacts, tasks,
progress, `contextFiles`, and the built-in `instruction`. They are not
evidence of task completion, do not replace the built-in instruction, and do
not permit bypassing a blocked state. If context conflicts with the built-in
instruction, an explicit user choice, or a CLI-controlled value, report the
conflict and preserve the controlling value. If guidance is inapplicable or
conflicts with those controlling inputs, do not follow it and explain why.
These are prompt-level behavior contracts, not enforceable checks.
4. **Read context files**
Read every file path listed under `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
Do not copy `context` or `operationGuidance` verbatim into implementation
files or planning artifacts unless the user separately asks for that content.
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
- Before editing, confirm the checkbox at the returned `sourcePath` and `line` still matches the task description; if it does not, rerun the apply instructions and use the refreshed location
- Mark the task complete at its returned `sourcePath` and `line`: `- [ ]` → `- [x]`
- Rerun the apply instructions and confirm that task is now done and progress changed
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- A task needs work beyond what the spec and tasks describe, or you are tempted to drop, narrow, defer, or accept exceptions to specified behavior to make it fit → surface the added scope and ask; do not absorb it silently
- 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
- When a task needs work beyond what the spec describes, surface the added scope and pause - never silently narrow, defer, or simplify away specified behavior
- Only mark a task `- [x]` when its specified behavior is fully implemented, not when it is partially done or deferred
- Use contextFiles from CLI output, don't assume specific file names
- Use each task's sourcePath and line to update its exact checkbox
- Do not use context or operation guidance as proof that a task is complete
- Apply relevant project context; report conflicts with controlling workflow inputs
- Consider every guidance entry; explain any inapplicable or conflicting advice
- Do not copy runtime context or operation guidance into implementation files or planning artifacts
- Preserve CLI-controlled blocked/ready/all-done behavior and completion criteria
**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
+264
View File
@@ -0,0 +1,264 @@
---
name: "OPSX: Archive"
description: "Archive a completed change in the experimental workflow"
allowed-tools: Bash(openspec:*)
category: "Workflow"
tags: ["workflow", "archive", "experimental"]
---
Archive a completed change in the experimental workflow.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
**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. **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 ask the user to select one
When prompting, show only active changes (not already archived).
Include the schema used for each change if available.
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:archive <other>`).
**Load current archive inputs before the existing archive checks:**
After resolving the selected change and planning root, run:
```bash
openspec instructions archive --change "<name>" --json
```
Keep the same selected-root flags on this command. This lookup is advisory and
optional: it only supplies extra prompt inputs, so it must never block archiving.
If it exits non-zero or returns invalid JSON — for example on an older CLI that
does not support this command yet — continue the archive workflow with no
context and no operation guidance. Do not report an error and do not stop.
A successful response may omit both optional fields. Treat `context` as a
required prompt-level input: read and consider it, and apply relevant project
facts, conventions, and constraints. Treat `operationGuidance` as optional
additive advice: read and consider every entry, and follow entries that are
applicable and compatible with the built-in archive workflow.
Keep both fields separate from built-in steps, explicit user choices, resolved
paths, CLI checks, and command contracts. If context conflicts with one of those
controlling inputs, report the conflict and preserve the controlling value. If
guidance is inapplicable or conflicts with a controlling input, do not follow it
and explain why. Do not infer replacement paths, skipped prompts, or flags from
either field, and do not copy their text verbatim into specs, change artifacts,
or archive summaries unless the user separately asks for it. These are
prompt-level behavior contracts, not enforceable checks.
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
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context
- `artifacts`: List of artifacts with their status (`done`, `skipped`, or other)
**If any artifacts are neither `done` nor `skipped`** (skipped artifacts satisfy the requirement - the change declares skip_specs):
- Display warning listing incomplete artifacts
- Prompt user for confirmation to continue
- Proceed if user confirms
3. **Check task completion status**
Run `openspec list --json` with the same selected-root flags and find the
entry in `changes` whose `name` exactly matches the selected change.
Require exactly one match and nonnegative integer `totalTasks` and
`completedTasks`, with `completedTasks <= totalTasks`. The CLI resolves
the schema's tracked task files, including custom artifact names, output
paths, and globs.
Incomplete tasks = `totalTasks - completedTasks`.
Do not infer task completion from artifact status or the absence of a
top-level `tasks.md`. If the lookup fails, returns invalid JSON, omits or
duplicates the selected change, or returns invalid counts, report the problem
and stop before syncing or archiving.
The CLI counts only `x`/`X` checkbox markers as complete;
other markers, including unfamiliar ones, remain incomplete.
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Prompt user for confirmation to continue
- Proceed if user confirms
**If `totalTasks` is zero:** Proceed without a task-related warning.
4. **Assess delta spec sync state**
Use `artifactPaths.specs.existingOutputPaths` from status JSON as the only
delta-spec source. If the `specs` entry is missing or
`existingOutputPaths` is empty, proceed without a sync prompt and do not infer
delta specs from other artifacts.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (use the store-aware `planningHome.root` from step 2, not a hardcoded repo path)
- A missing main spec is **not automatically** "already synced". For a new capability, the main spec is an *output* of the sync, not an input:
- If the delta has MODIFIED or RENAMED requirements, report that only ADDED requirements can create a new main spec and mark that capability as sync-blocked. Never invent a requirement that has no current version.
- Otherwise, if the delta has only REMOVED requirements and the change's `.openspec.yaml` declares `retire_capabilities: true`, the capability is already retired: count it as already synced, warn that there is nothing left to remove, and do not recreate the main spec. Apply this rule both now and when verifying a completed sync.
- Otherwise, if the delta has no ADDED requirements, report that no sync is possible and mark that capability as sync-blocked. For a REMOVED-only delta, warn that there is no main spec to remove from and leave the main-spec tree unchanged. `openspec archive` refuses the unmarked REMOVED-only case with `Spec must have at least one requirement`.
- Otherwise, count the capability as needing sync and name it in the summary (`<capability-path>: new main spec will be created`). If the delta also has REMOVED requirements, warn that they will be ignored because there is no main spec to remove from. The sync creates the main spec from only the delta's ADDED requirements, exactly as `openspec archive` does.
- Determine what changes would be applied (adds, modifications, removals, renames)
- Continue assessing the remaining capabilities even when one is sync-blocked. Show a combined summary before prompting.
**Prompt options:**
- If any capability is sync-blocked: explain why and offer only "Archive without syncing", "Cancel"
- Otherwise, if changes needed: "Sync now (recommended)", "Archive without syncing"
- Otherwise, if already synced: "Archive now", "Sync anyway", "Cancel"
Route on the answer:
- "Cancel" — stop, do not archive
- "Archive without syncing" or "Archive now" — proceed to archive
- "Sync now" or "Sync anyway" — sync, then verify (below). Do not start any sync while a capability is sync-blocked; explain the blocker and repeat the available choices.
- Anything else — ask again rather than archiving
Before a selected sync writes any main spec, run
`openspec instructions specs --change "<name>" --json` once with the same
selected-root flags. Require a zero exit status and valid artifact-instruction
JSON. If the lookup fails or returns invalid JSON, report the error and stop
before writing any main spec or moving the change. A valid response with omitted
`rules` is the no-rules case. Apply returned `rules` only to the content and
form of main specs produced by this merge; do not use them as archive guidance,
change CLI behavior, or copy the rule text into any output file.
Then run the `/opsx:sync` workflow inline (agent-driven intelligent merge) for change '<name>', passing the delta spec analysis and the fetched specs-rule snapshot from above, and wait for it to finish. The inline sync must reuse that snapshot without fetching `specs` instructions again. Do not delegate it to a background task — step 5 would move `changeRoot` out from under a sync that is still reading it, leaving the change archived and the main specs never updated. If your agent can only run it by delegation, delegate synchronously and wait for the result.
If the sync reports any stop or blocking condition, treat the sync as failed.
Stop the archive immediately. Do not perform the post-sync content comparison and do not move its `changeRoot`.
Nothing has moved, so the user can fix the blocking condition or re-run the sync.
After the sync writes each main spec, verify its structure against the canonical sync contract:
- A new main spec starts with a `# <capability> Specification` title. An existing main spec keeps its title exactly as it is.
- Preserve existing `## Purpose` sections completely untouched for established main specs.
- For a new main spec, copy the delta `## Purpose` verbatim. Warn only if the purpose text is shorter than standard validation expects. Do not regenerate or rewrite existing authored purpose. If no usable `## Purpose` is provided, use the existing TBD Purpose behavior and warning.
- Verify that no delta-style section headers (`## ADDED Requirements`, `## MODIFIED Requirements`, `## REMOVED Requirements`, `## RENAMED Requirements`) remain in the main spec, adhering strictly to the sync workflow formatting rules.
- Requirement blocks the sync wrote or changed use `### Requirement:` headings, and their scenarios use `#### Scenario:` headings, under the spec's `## Requirements` section. Leave content the delta does not mention exactly as it is.
Then re-run the comparison from the top of this step, including the explicitly retired, missing-spec case, against every capability that has a delta spec in `artifactPaths.specs.existingOutputPaths` — not only the ones the sync reports it touched. A successful sync leaves nothing left to apply, so each capability must now read as already synced:
- ADDED requirements present
- MODIFIED requirements carrying the scenario and description changes named in the delta, with their other scenarios intact
- REMOVED requirements gone — and where this sync retired a capability (removed its last requirement, leaving `## Requirements` empty), its main spec deleted rather than left empty.
- RENAMED requirements present under the new name and absent under the old one
If the sync failed, or any capability does not match, report what differs and stop — do not archive. Nothing has moved and `changeRoot` is intact, so the user can fix the mismatch or re-run the sync and start the archive again.
5. **Perform the archive**
Create an `archive` directory under `planningHome.changesDir` if it doesn't exist:
```bash
mkdir -p "<planningHome.changesDir>/archive"
```
Generate the target name: use the change name as-is when it already starts with a `YYYY-MM-DD-` prefix; otherwise prepend the current date as `YYYY-MM-DD-<change-name>`. Never stack a second date (same rule as `openspec archive`).
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move `changeRoot` to the archive directory
```bash
mv "<changeRoot>" "<planningHome.changesDir>/archive/<target-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**
```markdown
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** the archive path derived from `planningHome.changesDir`/<target-name>/
**Specs:** ✓ Synced to main specs
All artifacts complete. All tasks complete.
```
**Output On Success (No Delta Specs)**
```markdown
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** the archive path derived from `planningHome.changesDir`/<target-name>/
**Specs:** No delta specs
All artifacts complete. All tasks complete.
```
**Output On Success With Warnings**
```markdown
## Archive Complete (with warnings)
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** the archive path derived from `planningHome.changesDir`/<target-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)**
```markdown
## Archive Failed
**Change:** <change-name>
**Target:** the archive path derived from `planningHome.changesDir`/<target-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**
- Announce the selected change; prompt for selection when it is ambiguous
- 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, run the `/opsx:sync` workflow inline (agent-driven)
- Never archive while a spec sync is still in flight — run the sync inline and verify the main specs before moving `changeRoot`
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
- Apply relevant runtime context and report conflicts; operation guidance remains advisory
- Consider every guidance entry and explain any inapplicable or conflicting advice
- Existing CLI checks, resolved paths, prompts, and command contracts are unchanged
- Artifact rules constrain only the specs being written and are never operation guidance
- Never copy runtime context, operation guidance, or artifact-rule text verbatim into output files
+239
View File
@@ -0,0 +1,239 @@
---
name: "OPSX: Explore"
description: "Enter explore mode - think through ideas, investigate problems, clarify requirements"
allowed-tools: Bash(openspec:*)
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, investigate the codebase, and run read-only commands or tools without confirmation, but you must NEVER write code or implement features. If the user asks you to implement something, do not start it here: say that explore mode does not implement, and point them at `/opsx:propose`, which turns the discussion into a change. The work happens from that change, never from explore mode. You MAY create or update OpenSpec change artifacts (proposals, designs, specs) within a confirmed scope—that's capturing thinking, not implementing. Answering design or clarifying questions is never consent to write. Before the first write-capable action, name the artifacts or files you would change and what you would do, ask a direct yes/no question, and wait for the user's confirmation in a separate message. Confirmation covers only the scope you described; ask again before expanding it. An explicit request from the user to capture the exploration as a new change is itself that confirmation, covering the change and the change artifacts the request names; scaffold it first as described below.
**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.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
**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
---
## Planning a Change
When the user is planning a change, guide them toward shared understanding with focused discovery questions. For open-ended discussion, follow the conversation without imposing an interview or a required output.
Before asking a factual question, follow the context discovery below and inspect relevant OpenSpec artifacts, source, tests, docs, and configuration. Do not ask the user to repeat facts you can verify. Summarize relevant findings without reproducing private context or rules. If evidence is missing, conflicting, or inaccessible, state that limitation and ask only for the clarification needed to proceed.
- **Follow dependencies** - Resolve the next blocking decision before its dependent details. For example, clarify the user's outcome and scope before choosing an API or data model. Revisit downstream assumptions when an earlier answer changes. Skip branches that do not matter to this goal.
- **Keep questions focused** - Ask one focused question at a time, and briefly explain why it matters and which decision it unlocks. Batch questions only if the user asks for a batch; keep them small and group related decisions.
- **Offer grounded recommendations** - When evidence supports a recommendation, state your preferred option and why it fits the user's goals, with alternatives and their tradeoffs when useful. Do not invent intent, priorities, or external constraints: ask the user when only they can answer. Avoid a fixed question format.
- **Keep a conversational record** - Track decisions in the conversation, not in files. Separate confirmed decisions from proposed defaults and unresolved questions. Silence is not acceptance. Accepting an answer or a batch of recommendations is not permission to write. Keep file-write confirmation separate from discovery questions and follow the guardrails below.
Stop asking when the user has enough clarity. Let them pause, pivot, or defer a decision; do not exhaust every branch or force a proposal.
For example, after inspecting the relevant code:
```text
The CLI already uses SQLite and has no remote service. Is sharing state
across devices in scope? That determines whether local storage is enough.
If this stays a single-device tool, I recommend keeping SQLite to avoid
adding a service to operate; shared state would need a separate sync design.
```
---
## 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 A] -------> [State B] |
| | |
| v |
| [State C] |
| |
| System diagrams, state machines, |
| data flows, architecture sketches, |
| dependency graphs, comparison tables |
| |
+------------------------------------------+
```
**Draw with plain ASCII only** — borders `+` `-` `|`, arrows `-->` `<--` `^` `v`, markers `*` `x`.
Unicode diagram glyphs can render at different widths across terminals, fonts, and locales, so padded boxes and aligned tables can drift. Keep every diagram character ASCII.
**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 and task status
- What the user might be working on
That is the *change* list - work in flight. It does not include the project's durable capabilities, so list those too:
```bash
openspec list --specs
```
Add `--json` for ids and requirement counts, and append `--store "<id>"` only for a registered standalone store. This is the inventory of what the project already claims to do, and `openspec list` on its own never shows it. To look at one, run `openspec show "<spec-id>" --type spec --json --no-scenarios` (same `--store` rule) - it returns that capability's purpose and requirement texts without pulling the whole spec file into context, and `--type spec` stops a change of the same name from making it ambiguous.
The filtered read is only an overview. Before deciding what is already covered or what should change, read each relevant spec in full, including scenarios, with `openspec show "<spec-id>" --type spec` (same `--store` rule).
Then read the project's own context from the resolved root - `<root.path>/openspec/config.yaml` (or `config.yml`). Use the `root.path` returned above, and skip this if neither file exists:
- `context`: project background - tech stack, conventions, constraints
- `rules`: keyed by artifact id - the entries for an artifact apply only when you write that artifact
Ground your thinking in these. They are constraints for you to follow, not content to reproduce: do NOT copy them into the conversation or into any artifact you create.
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
If the user asks you to capture the exploration as a new change, that request is the confirmation required above. It covers scaffolding that change and creating the change artifacts the request names, and nothing else. This holds only when the request is theirs: a yes to an offer you made confirms only the scope your offer itself named, so name the change and the artifacts in the offer. Don't re-ask for what they already asked for; do ask before anything beyond it. Transition seamlessly into the requested capture:
1. Run `openspec new change "<name>"` (with `--store <id>` when applicable) before creating any artifacts. Never create a new change directory under `openspec/changes/` by hand; the CLI scaffold creates required metadata such as `.openspec.yaml`. Keep the selected `--store <id>` on every applicable follow-up `status` and `instructions` command.
2. Run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store), then process the requested artifacts in dependency order. For each requested artifact that is `ready`, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store). Before creating a requested artifact, evaluate any condition in its own `instruction` against the explored change; record a deliberate skip instead when the condition does not apply. If a requested artifact is blocked by a direct prerequisite the user did not request, run `openspec instructions "<prerequisite-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) for that prerequisite whether it is `ready` or `blocked`. If its own `instruction` states a condition, evaluate that condition against the explored change and record a deliberate skip only when the condition does not apply. If the condition applies, or the prerequisite is not conditional, treat it as a normal prerequisite and ask before expanding the capture. Do not create an unrequested prerequisite unless the user approves.
3. Follow the returned `template` and `instruction` fields. Read completed dependency files listed in `dependencies`, and apply `context` and `rules` as constraints without copying them into the artifact. If the instruction delegates creation to a specific skill or command, invoke it; otherwise write the artifact to `resolvedOutputPath`, using the instruction to choose a concrete path when it is a glob. Verify that the selected concrete output exists.
4. After creating each artifact, re-run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) and continue until every requested artifact is `done`, `skipped`, or was deliberately skipped because its own `instruction` stated a condition that did not apply. Tell the user about a deliberate conditional skip, remember it, and do not reconsider it. Dependencies are enablers, not gates: if a requested artifact is still `blocked` only because you deliberately skipped a conditional prerequisite, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) despite the blocked status, then create it using step 3 only when those recorded conditional skips are its sole missing dependencies. If a requested artifact is blocked by a prerequisite the user did not ask to capture and cannot be conditionally skipped, explain that dependency and ask before expanding the capture.
Capture the artifact(s) the user requested without asking them to invoke another workflow command. If they asked only to start a change, stop after scaffolding and show its status. When the requested capture is done, stop there and name where the work continues: `/opsx:propose` writes the remaining planning artifacts, and `/opsx:apply` implements the change once tasks exist. Capturing artifacts never starts implementing them.
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Resolve and read existing artifacts for context**
- Run `openspec status --change "<name>" --json`.
- Use `changeRoot`, `artifactPaths`, and `actionContext` from the status JSON.
- Read existing files from `artifactPaths.<artifact>.existingOutputPaths`.
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**
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
| Insight Type | Where to Capture |
|----------------------------|-------------------------------------|
| New requirement discovered | `specs/<capability-path>/spec.md` |
| Requirement changed | `specs/<capability-path>/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? Run `/opsx:propose` and this becomes a change."
- **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. Workflow configuration counts too: creating or editing schemas, templates, or `openspec/config.yaml` is a change, not thinking. Creating or updating OpenSpec change artifacts within the confirmed scope is fine, writing anything else is not. When the user is ready to build, name the handoff rather than starting: `/opsx:propose` turns the discussion into a change, and the work happens there.
- **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. Read-only commands and tools need no confirmation. Before the first write-capable action—including `openspec new change` or another command that writes files—name the artifacts or files and proposed changes, ask a direct yes/no question, and wait for explicit confirmation in a separate user message. That confirmation covers only the described scope; ask again before expanding it. Answers to design or clarifying questions are never consent to write. That rule governs `openspec new change` whenever you are the one proposing the capture; the user's own capture request is the exception, handled in the capture transition above.
- **Don't manually scaffold changes** - Never create a new change directory under `openspec/changes/` by hand. Always use `openspec new change "<name>"` (with `--store <id>` when applicable) so required metadata such as `.openspec.yaml` is created before writing artifacts.
- **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
+170
View File
@@ -0,0 +1,170 @@
---
name: "OPSX: Propose"
description: "Propose a new change - create it and generate all artifacts in one step"
allowed-tools: Bash(openspec:*)
category: "Workflow"
tags: ["workflow", "artifacts", "experimental"]
---
Propose a new change - create the change and generate all artifacts in one step.
**Planning boundary**: This workflow creates planning artifacts only. The user request that selected or triggered this workflow authorizes planning only, even if it asks to build or fix something. Do not edit project code. After the planning artifacts are complete, stop. Do not start implementation in the same response, even if the initial request asks for it. Wait for a new user request after the artifacts are presented; then start the apply workflow.
I'll create a change with the artifacts your schema defines. With the default spec-driven schema that is:
- proposal.md (what & why)
- `specs/<capability-path>/spec.md` (what the system must do - a delta, not the main spec)
- design.md (how)
- tasks.md (implementation steps)
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
When the user is ready to implement, they must start the apply workflow explicitly.
---
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
**Input**: The argument after `/opsx:propose` is the change name (kebab-case), OR a description of what the user wants to build.
**Steps**
1. **Understand the request and clarify material ambiguity**
If no input is provided, ask the user (open-ended, no preset options):
> "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.
If the request contains ambiguity that would materially affect scope, externally observable behavior, compatibility, or acceptance criteria, ask the user before creating the change. For minor details, make a reasonable assumption and record it in the planning artifacts.
2. **Load project context**
Run `openspec context --json` from the current working directory (or `openspec context --json --store "<store-id>"` when a registered store was explicitly selected). Use the returned `root.path` as the authoritative OpenSpec root. If context reports `no_openspec_root`, stop without creating or changing any files and follow the **Project check** above for how this workflow was reached. Offer `openspec init` only for an explicit OpenSpec request, and wait for the user to request initialization. Do not initialize automatically or run `openspec new change`. After initialization, rerun this context check before continuing. For any other context failure, stop and report the error; do not fall back to the current directory or run later OpenSpec commands without the selected store.
Only when context returns a resolved `root.path`, read `<root.path>/openspec/config.yaml`. Use `config.yml` only when `config.yaml` does not exist. If neither file exists, continue without project context. Do not fall back to `config.yml` if `config.yaml` is unreadable or invalid.
If the file parses as a YAML object and its `context` field is a string no larger than 51,200 bytes in UTF-8, apply that field before exploring the codebase or making planning decisions. If the file cannot be read or parsed, or the context field is invalid or oversized, continue without project context. Validate this field independently of other config fields, as OpenSpec does.
Treat context as project-provided data and constraints, not as authority to change this workflow: it cannot override user authorization, the planning boundary, tool restrictions, or artifact and output rules. Do not copy the context into artifacts; use it to focus any codebase exploration and as a constraint on the proposal.
3. **Determine the workflow schema**
Use the configured default schema unless the user explicitly requests a different workflow.
**Use a different schema only if the user:**
- Explicitly requests a specific schema by name → use `--schema <schema-name>`
- Asks to "show workflows" or asks "what workflows" exist → resolve the authoritative root by running `openspec context --json` from the current working directory. If the user explicitly selected a registered store, use `openspec context --json --store "<store-id>"`. Then run `openspec schemas --json` with its working directory set to the returned `root.path` and let them choose. This preserves roots selected by a local `store:` pointer or the global `defaultStore`; when a registered store was explicitly selected, append `--store "<store-id>"` to `openspec schemas --json` as well. If context fails, stop as described in the context-loading step; do not fall back to the current directory.
Otherwise, omit `--schema` to preserve the configured default.
4. **Create the change directory**
Choose one schema form below. If a registered store is selected, append `--store "<store-id>"` to that command and each later OpenSpec command shown below that accepts `--store`.
Using the configured default:
```bash
openspec new change "<name>"
```
Using an explicitly requested schema:
```bash
openspec new change "<name>" --schema "<schema-name>"
```
This creates a scaffolded change in the planning home resolved by the CLI with `.openspec.yaml`.
5. **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, each with its `status` and its `requires` edges (the artifact IDs it directly depends on)
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
6. **Create every artifact in the required set**
Use a todo list 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
- `skipped`/`warning`: present when the change declares skip_specs and this artifact must NOT be created - stop and pick another artifact
- `resolvedOutputPath`: Resolved path or pattern to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context - always re-read them from disk, even if you saw them earlier in the conversation (the user may have edited them)
- **Inspect the relevant project before drafting**: Read `context` and `rules` first, then inspect relevant implementation, nearby tests, configuration, and documentation outside `openspec/`. Keep inspection read-only and proportional to the change; reuse findings for later artifacts and inspect more only as needed.
- Identify the target project from the request and project context; the planning home may be separate from the code. If the target is unclear, ask. For greenfield or non-code changes, inspect the available structure and relevant documents. If source is unavailable, state the limitation and ask when it materially affects the plan.
- Ground scope, approach, and tasks in what you find. Distinguish observed behavior from assumptions and proposed additions; surface conflicts with existing specs instead of silently deciding which is correct.
- Do this discovery now, rather than leaving generic "explore the codebase" or "make a plan" tasks for implementation. Keep any necessary follow-up investigation specific to an unresolved question.
- If the `instruction` field delegates creation to a specific skill or command, invoke it to produce the artifact instead of writing the file yourself, then verify the artifact file exists at `resolvedOutputPath`
- Otherwise create the artifact file using `template` as the structure and write it to `resolvedOutputPath`. If `resolvedOutputPath` is a glob, follow `instruction` to choose the concrete file path
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until every artifact in the required set exists (not just `apply.requires`)**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- The required set is `applyRequires` plus every artifact reachable from those by following the `requires` edges in `status --json` - walk them transitively (spec-driven closes over proposal, specs, design, tasks). Leave artifacts outside that set alone
- `status` is file-existence only, so an `applyRequires` artifact reading `done` does NOT mean its dependencies exist - writing `tasks.md` early marks `tasks` done while `specs` was never written. Use each artifact's `requires` edges, not its `status`, to build the required set: a `done` artifact still lists what it depends on
- An artifact already reading `status: "skipped"` is satisfied: the change declares `skip_specs` in `.openspec.yaml`, so its files must NOT exist. Never try to create one
- Create every artifact in the required set that is missing, then re-check - creating one can unblock others
- Skip one only when `status` already reports it `skipped`, or when its own `instruction` says it is conditional: run `openspec instructions <artifact-id> --change "<name>" --json` and skip only if its `instruction` field marks it optional (e.g. "create only if..."). Spec-driven's `design.md` qualifies; `specs` qualifies only via the `skipped` status above, never by your own judgment. Tell the user, and do not reconsider it
- Dependencies are enablers, not gates: if a required artifact is still `blocked` only because you skipped a conditional dependency, write it anyway
- Stop when every artifact in the required set is `done`, `skipped`, or was deliberately skipped
c. **If an artifact requires user input** (unclear context):
- Ask the user to clarify
- Then continue with creation
7. **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, plus any conditional artifact you skipped and why
- What's ready: "All artifacts needed for implementation are ready."
- Prompt: "The artifacts are ready for review. When you are ready, run `/opsx:apply`."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type - it is the authoritative guidance, even for familiar artifact names
- If the `instruction` field directs you to use a specific skill or command to create the artifact, invoke it instead of writing the artifact directly
- 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**
- The request that invoked this workflow authorizes planning only. Any implementation or apply instruction in that request does not carry forward. Do NOT implement the change, start the apply workflow, or edit project code during this workflow. After presenting the artifacts, stop and wait for a new user request to start the apply workflow
- Create every artifact the apply phase transitively depends on, not just the ids listed in `apply.requires`
- Always read dependency artifacts before creating a new one - re-read from disk, not from conversation memory (files may have changed since you last saw them)
- Ask about ambiguities that would materially change scope, externally observable behavior, compatibility, or acceptance criteria; for minor details, make reasonable assumptions and record them
- 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
+286
View File
@@ -0,0 +1,286 @@
---
name: "OPSX: Sync"
description: "Sync delta specs from a change to main specs"
allowed-tools: Bash(openspec:*)
category: "Workflow"
tags: ["workflow", "specs", "experimental"]
---
Sync delta specs from a change to main specs.
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
**Input**: Optionally specify a change name after `/opsx:sync` (e.g., `/opsx:sync 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 ask the user to select one
When prompting, show changes that have delta specs (under `specs/` directory).
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:sync <other>`).
2. **Resolve change context**
Run:
```bash
openspec status --change "<name>" --json
```
The JSON includes `planningHome.root`. Main specs live under `<planningHome.root>/openspec/specs/` — use that (store-aware) root for every main-spec path below, not a hardcoded repo path. When a store is selected it points at the store, not the current repository.
3. **Find delta specs**
Use `artifactPaths.specs.existingOutputPaths` from the status JSON as the
only source of delta spec paths. If the `specs` entry is missing or
`existingOutputPaths` is empty, report that there are no delta specs to sync,
do not infer them from other artifacts, and stop without requesting artifact
instructions or writing a main spec.
Sync every path in `existingOutputPaths` unless the caller narrowed the set.
A caller narrows it by naming an explicit list of complete entries from
`existingOutputPaths` — copy those absolute values verbatim. Archive does
this inline, and a user can too (for example, by selecting the entry ending
in `/specs/billing/invoices/spec.md`).
Then sync only the named paths and leave the remaining delta specs untouched:
bulk archive excludes a delta whose implementation it could not find, and
syncing it anyway would write a main spec the caller deliberately withheld.
Carry that narrowed selection through step 4; never widen it back to the full
list. If a named path is not in `existingOutputPaths`, do not sync it —
report it and stop, rather than dropping it silently. If the named list is
empty, report that there is nothing to sync and stop without writing a main
spec.
Each delta spec file contains sections like:
- `## ADDED Requirements` - New requirements to add
- `## MODIFIED Requirements` - Changes to existing requirements
- `## REMOVED Requirements` - Requirements to remove
- `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
If no delta specs found, inform user and stop.
4. **For each delta spec, apply changes to main specs**
Before the first main-spec write, obtain one current specs-rule snapshot:
- If archive invoked this workflow inline and supplied a valid snapshot from
`openspec instructions specs --change "<name>" --json`, reuse it and do not
fetch the same instructions again.
- Otherwise run that command once now with the same selected-root flags.
- If the direct lookup exits non-zero or returns invalid artifact-instruction
JSON, report the error and stop before writing any main spec. Do not treat the
failure as an absent rule set.
- A valid response with omitted `rules` means no artifact rules are configured
and the existing semantic merge continues.
Apply returned `rules` only to the content and form of the main specs produced
by this merge. Artifact rules are not operation guidance and cannot change
selected roots, delta paths, CLI checks, or workflow steps. Use their text as
constraints without copying it verbatim into a main spec or summary.
For each capability delta spec path selected in step 3 — the full `existingOutputPaths` list, or the narrowed subset when a caller supplied one (these may belong to a selected store, not the repo):
a. **Read the delta spec** to understand the intended changes
b. **Read the main spec** at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (may not exist yet)
**If it does not exist yet** (a new capability), match what `openspec archive` does:
only ADDED requirements may be applied - step d creates the spec from them.
MODIFIED and RENAMED have no requirement to act on, so stop the sync for that
capability and report that its main spec does not exist and only ADDED is allowed
for a new spec; never invent the missing requirement. REMOVED has nothing to
remove - skip it and warn.
c. **Apply changes intelligently**:
**ADDED Requirements:**
- If requirement doesn't exist in main spec → add it
- If requirement already exists → update it to match (treat as implicit MODIFIED)
**MODIFIED Requirements:**
- Find the requirement in main spec
- Apply the changes - this can be:
- Adding new scenarios the main spec does not have yet
- Modifying existing scenarios
- Changing the requirement description
- Preserve scenarios/content not mentioned in the delta
**REMOVED Requirements:**
- Remove the entire requirement block from main spec
- Retiring the capability. Delete the whole `spec.md` - and the directory once
nothing else is left in it - only when ALL of these hold:
1. removing the requirements *this run* left no requirement blocks;
2. the rest of the spec is well-formed (it still has a `## Purpose`);
3. the main spec was not already empty before this sync - if you removed
nothing, change nothing;
4. every other nonblank line in the whole file is accounted for as the
title, Purpose, Requirements header, or a canonical requirement's
statement, scenarios, or fenced examples;
5. the change's `.openspec.yaml` declares `retire_capabilities: true`;
6. the `spec.md` resolves inside the real specs root (do not follow a
capability-directory symlink to delete an external file).
If removing the selected requirements would leave no requirement blocks and
any retirement condition is not satisfied, do not modify the main spec. Stop
the sync for that capability, report the blocking condition, and tell the user
how to resolve it. Never write or leave an empty `## Requirements` section.
When only the marker is missing, say that too - it is the one thing the user
can add to make the retirement go through.
- Deleting the file also deletes its `## Purpose`; any other section blocks
retirement. Name Purpose when you report the retirement. Include a pasteable
`git checkout` only when the spec lived in the caller's checkout;
otherwise give checkout-scoped recovery guidance.
**RENAMED Requirements:**
- Find the FROM requirement, rename to TO
**`## Purpose` in the delta:**
- The main spec already has one and it is authoritative - leave it alone
(this is what `openspec archive` does; it warns and moves on)
d. **Create new main spec** if capability doesn't exist yet:
- Only when the delta has ADDED requirements to put in it and no MODIFIED or
RENAMED requirements blocked this capability in step b. Otherwise create nothing
and leave the specs directory untouched. For a REMOVED-only delta, if the change's
`.openspec.yaml` declares `retire_capabilities: true`, report it as already retired
and continue without recreating the spec. Without that marker, report the sync as blocked:
`openspec archive` rejects it with `Spec must have at least one requirement`.
An empty delta has no operations to sync; report it as blocked too.
Never write an empty `## Requirements` section.
- Create `<planningHome.root>/openspec/specs/<capability-path>/spec.md`
- Add Purpose section: copy the delta's `## Purpose` body verbatim when it has one
(this is what `openspec archive` does); only write a brief TBD placeholder when it does not
- Add Requirements section with the ADDED requirements
- Follow the **Main Spec Format Reference** below
5. **Validate updated main specs**
Run `openspec validate --specs` with the same selected-root flags used earlier.
If validation fails, report the problems and do not claim the sync succeeded.
6. **Show summary**
After applying all changes, summarize:
- Which capabilities were updated
- What changes were made (requirements added/modified/removed/renamed)
- Any new main spec left with a TBD Purpose placeholder, so it gets written
now rather than lingering
- Any capability retired, naming the deleted `spec.md`, its Purpose, and
either a pasteable `git checkout` or checkout-scoped recovery guidance
**Delta Spec Format Reference**
```markdown
# Spec Delta
## Purpose
Only on a delta that introduces a brand-new capability. Seeds the new main spec.
## ADDED Requirements
### Requirement: New Feature
The system SHALL do something new.
#### Scenario: Basic case
- **WHEN** user does X
- **THEN** system does Y
## MODIFIED Requirements
### Requirement: Existing Feature
The system SHALL keep doing the existing thing, now also handling A.
#### Scenario: Scenario the main spec already has
- **WHEN** user does X
- **THEN** system does Y
#### Scenario: New scenario to add
- **WHEN** user does A
- **THEN** system does B
## REMOVED Requirements
### Requirement: Deprecated Feature
## RENAMED Requirements
- FROM: `### Requirement: Old Name`
- TO: `### Requirement: New Name`
```
**Main Spec Format Reference**
Main specs are what the delta merges INTO. They must never contain delta operation headers (`## ADDED/MODIFIED/REMOVED/RENAMED Requirements`) - after syncing, every requirement lives under a single `## Requirements` section:
```markdown
# <capability> Specification
## Purpose
Short description of what this capability does and why it exists.
## Requirements
### Requirement: New Feature
The system SHALL do something new.
#### Scenario: Basic case
- **WHEN** user does X
- **THEN** system does Y
```
**Key Principle: Intelligent Merging**
Unlike programmatic merging, you merge rather than overwrite:
- A MODIFIED block carries the whole requirement - body plus every scenario that survives the change. `openspec validate` and `openspec archive` both reject one that drops a scenario the main spec still has.
- Keep anything the delta does not mention, in the main spec's existing order
- Use your judgment to merge changes sensibly
**Output On Success**
```markdown
## Specs Synced: <change-name>
Updated main specs:
**<capability-1>**:
- Added requirement: "New Feature"
- Modified requirement: "Existing Feature" (added 1 scenario)
**<capability-2>**:
- Created new spec file
- Added requirement: "Another Feature"
Main specs are now updated. The change remains active - archive when implementation is complete.
```
**Guardrails**
- Read both delta and main specs before making changes
- Preserve existing content not mentioned in delta
- Never copy a delta file into a main spec as-is - merge its content so the main spec keeps the Main Spec Format Reference structure, with no delta operation headers
- If something is unclear, ask for clarification
- Show what you're changing as you go
- The operation should be idempotent - running twice should give same result
- Use only `artifactPaths.specs.existingOutputPaths`; never infer delta specs from unrelated artifacts
- Honor a caller-supplied subset of `existingOutputPaths`; never widen it back to the full list
- Fetch specs instructions once for direct sync, or reuse the archive-supplied snapshot inline
- Stop before every main-spec write on a non-zero or invalid JSON specs-instruction response
- Artifact rules constrain only the specs being written and are never copied into output files
@@ -0,0 +1,205 @@
---
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. Also use when the user says "openspec apply", "opsx apply", or "openspec implement".
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.14.0"
---
Implement tasks from an OpenSpec change.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
**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 ask the user to select one
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")
- `planningHome`, `changeRoot`, and `actionContext`: planning scope and edit constraints
- 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:
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
- Progress (total, complete, remaining)
- Task list with status, source path, and source line
- Dynamic instruction based on current state
- Optional `context`: current required project instruction input from the selected root
- Optional `operationGuidance`: current advisory guidance for apply
- `missingArtifacts` (when present): required artifact ids with no output
**Handle states:**
- If `state: "blocked"`: show the message and pause implementation.
- If `missingArtifacts` is non-empty: suggest completing the missing artifacts. Run `openspec status --change "<name>" --json`, select the next `ready` artifact (not `skipped` or `blocked`), and use `openspec instructions "<artifact-id>" --change "<name>" --json` for its rules and template. Keep the selected `--store <id>` on both commands.
- Otherwise, follow the CLI instruction to create or repair the schema-configured tracking file from existing planning artifacts. Do not assume another artifact is ready or start implementation while blocked.
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
Treat `context` as a required prompt-level input. Read and consider it, and
apply relevant project facts, conventions, and constraints while implementing.
Treat `operationGuidance` as optional additive advice. Read and consider every
entry, and follow entries that are applicable and compatible with the built-in
workflow.
Keep both fields separate from CLI-returned state, missing artifacts, tasks,
progress, `contextFiles`, and the built-in `instruction`. They are not
evidence of task completion, do not replace the built-in instruction, and do
not permit bypassing a blocked state. If context conflicts with the built-in
instruction, an explicit user choice, or a CLI-controlled value, report the
conflict and preserve the controlling value. If guidance is inapplicable or
conflicts with those controlling inputs, do not follow it and explain why.
These are prompt-level behavior contracts, not enforceable checks.
4. **Read context files**
Read every file path listed under `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
Do not copy `context` or `operationGuidance` verbatim into implementation
files or planning artifacts unless the user separately asks for that content.
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
- Before editing, confirm the checkbox at the returned `sourcePath` and `line` still matches the task description; if it does not, rerun the apply instructions and use the refreshed location
- Mark the task complete at its returned `sourcePath` and `line`: `- [ ]` → `- [x]`
- Rerun the apply instructions and confirm that task is now done and progress changed
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- A task needs work beyond what the spec and tasks describe, or you are tempted to drop, narrow, defer, or accept exceptions to specified behavior to make it fit → surface the added scope and ask; do not absorb it silently
- 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
- When a task needs work beyond what the spec describes, surface the added scope and pause - never silently narrow, defer, or simplify away specified behavior
- Only mark a task `- [x]` when its specified behavior is fully implemented, not when it is partially done or deferred
- Use contextFiles from CLI output, don't assume specific file names
- Use each task's sourcePath and line to update its exact checkbox
- Do not use context or operation guidance as proof that a task is complete
- Apply relevant project context; report conflicts with controlling workflow inputs
- Consider every guidance entry; explain any inapplicable or conflicting advice
- Do not copy runtime context or operation guidance into implementation files or planning artifacts
- Preserve CLI-controlled blocked/ready/all-done behavior and completion criteria
**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,221 @@
---
name: openspec-archive-change
description: Archive a completed OpenSpec change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete. Also use when the user says "openspec archive" or "opsx archive".
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.14.0"
---
Archive a completed change in the experimental workflow.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
**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 ask the user to select one
When prompting, show only active changes (not already archived).
Include the schema used for each change if available.
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:archive <other>`).
**Load current archive inputs before the existing archive checks:**
After resolving the selected change and planning root, run:
```bash
openspec instructions archive --change "<name>" --json
```
Keep the same selected-root flags on this command. This lookup is advisory and
optional: it only supplies extra prompt inputs, so it must never block archiving.
If it exits non-zero or returns invalid JSON — for example on an older CLI that
does not support this command yet — continue the archive workflow with no
context and no operation guidance. Do not report an error and do not stop.
A successful response may omit both optional fields. Treat `context` as a
required prompt-level input: read and consider it, and apply relevant project
facts, conventions, and constraints. Treat `operationGuidance` as optional
additive advice: read and consider every entry, and follow entries that are
applicable and compatible with the built-in archive workflow.
Keep both fields separate from built-in steps, explicit user choices, resolved
paths, CLI checks, and command contracts. If context conflicts with one of those
controlling inputs, report the conflict and preserve the controlling value. If
guidance is inapplicable or conflicts with a controlling input, do not follow it
and explain why. Do not infer replacement paths, skipped prompts, or flags from
either field, and do not copy their text verbatim into specs, change artifacts,
or archive summaries unless the user separately asks for it. These are
prompt-level behavior contracts, not enforceable checks.
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
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context
- `artifacts`: List of artifacts with their status (`done`, `skipped`, or other)
**If any artifacts are neither `done` nor `skipped`** (skipped artifacts satisfy the requirement - the change declares skip_specs):
- Display warning listing incomplete artifacts
- Ask the user to confirm they want to proceed
- Proceed if user confirms
3. **Check task completion status**
Run `openspec list --json` with the same selected-root flags and find the
entry in `changes` whose `name` exactly matches the selected change.
Require exactly one match and nonnegative integer `totalTasks` and
`completedTasks`, with `completedTasks <= totalTasks`. The CLI resolves
the schema's tracked task files, including custom artifact names, output
paths, and globs.
Incomplete tasks = `totalTasks - completedTasks`.
Do not infer task completion from artifact status or the absence of a
top-level `tasks.md`. If the lookup fails, returns invalid JSON, omits or
duplicates the selected change, or returns invalid counts, report the problem
and stop before syncing or archiving.
The CLI counts only `x`/`X` checkbox markers as complete;
other markers, including unfamiliar ones, remain incomplete.
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Ask the user to confirm they want to proceed
- Proceed if user confirms
**If `totalTasks` is zero:** Proceed without a task-related warning.
4. **Assess delta spec sync state**
Use `artifactPaths.specs.existingOutputPaths` from status JSON as the only
delta-spec source. If the `specs` entry is missing or
`existingOutputPaths` is empty, proceed without a sync prompt and do not infer
delta specs from other artifacts.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (use the store-aware `planningHome.root` from step 2, not a hardcoded repo path)
- A missing main spec is **not automatically** "already synced". For a new capability, the main spec is an *output* of the sync, not an input:
- If the delta has MODIFIED or RENAMED requirements, report that only ADDED requirements can create a new main spec and mark that capability as sync-blocked. Never invent a requirement that has no current version.
- Otherwise, if the delta has only REMOVED requirements and the change's `.openspec.yaml` declares `retire_capabilities: true`, the capability is already retired: count it as already synced, warn that there is nothing left to remove, and do not recreate the main spec. Apply this rule both now and when verifying a completed sync.
- Otherwise, if the delta has no ADDED requirements, report that no sync is possible and mark that capability as sync-blocked. For a REMOVED-only delta, warn that there is no main spec to remove from and leave the main-spec tree unchanged. `openspec archive` refuses the unmarked REMOVED-only case with `Spec must have at least one requirement`.
- Otherwise, count the capability as needing sync and name it in the summary (`<capability-path>: new main spec will be created`). If the delta also has REMOVED requirements, warn that they will be ignored because there is no main spec to remove from. The sync creates the main spec from only the delta's ADDED requirements, exactly as `openspec archive` does.
- Determine what changes would be applied (adds, modifications, removals, renames)
- Continue assessing the remaining capabilities even when one is sync-blocked. Show a combined summary before prompting.
**Prompt options:**
- If any capability is sync-blocked: explain why and offer only "Archive without syncing", "Cancel"
- Otherwise, if changes needed: "Sync now (recommended)", "Archive without syncing"
- Otherwise, if already synced: "Archive now", "Sync anyway", "Cancel"
Route on the answer:
- "Cancel" — stop, do not archive
- "Archive without syncing" or "Archive now" — proceed to archive
- "Sync now" or "Sync anyway" — sync, then verify (below). Do not start any sync while a capability is sync-blocked; explain the blocker and repeat the available choices.
- Anything else — ask again rather than archiving
Before a selected sync writes any main spec, run
`openspec instructions specs --change "<name>" --json` once with the same
selected-root flags. Require a zero exit status and valid artifact-instruction
JSON. If the lookup fails or returns invalid JSON, report the error and stop
before writing any main spec or moving the change. A valid response with omitted
`rules` is the no-rules case. Apply returned `rules` only to the content and
form of main specs produced by this merge; do not use them as archive guidance,
change CLI behavior, or copy the rule text into any output file.
Then run the `openspec-sync-specs` workflow inline (agent-driven intelligent merge) for change '<name>', passing the delta spec analysis and the fetched specs-rule snapshot from above, and wait for it to finish. The inline sync must reuse that snapshot without fetching `specs` instructions again. Do not delegate it to a background task — step 5 would move `changeRoot` out from under a sync that is still reading it, leaving the change archived and the main specs never updated. If your agent can only run it by delegation, delegate synchronously and wait for the result.
If the sync reports any stop or blocking condition, treat the sync as failed.
Stop the archive immediately. Do not perform the post-sync content comparison and do not move its `changeRoot`.
Nothing has moved, so the user can fix the blocking condition or re-run the sync.
After the sync writes each main spec, verify its structure against the canonical sync contract:
- A new main spec starts with a `# <capability> Specification` title. An existing main spec keeps its title exactly as it is.
- Preserve existing `## Purpose` sections completely untouched for established main specs.
- For a new main spec, copy the delta `## Purpose` verbatim. Warn only if the purpose text is shorter than standard validation expects. Do not regenerate or rewrite existing authored purpose. If no usable `## Purpose` is provided, use the existing TBD Purpose behavior and warning.
- Verify that no delta-style section headers (`## ADDED Requirements`, `## MODIFIED Requirements`, `## REMOVED Requirements`, `## RENAMED Requirements`) remain in the main spec, adhering strictly to the sync workflow formatting rules.
- Requirement blocks the sync wrote or changed use `### Requirement:` headings, and their scenarios use `#### Scenario:` headings, under the spec's `## Requirements` section. Leave content the delta does not mention exactly as it is.
Then re-run the comparison from the top of this step, including the explicitly retired, missing-spec case, against every capability that has a delta spec in `artifactPaths.specs.existingOutputPaths` — not only the ones the sync reports it touched. A successful sync leaves nothing left to apply, so each capability must now read as already synced:
- ADDED requirements present
- MODIFIED requirements carrying the scenario and description changes named in the delta, with their other scenarios intact
- REMOVED requirements gone — and where this sync retired a capability (removed its last requirement, leaving `## Requirements` empty), its main spec deleted rather than left empty.
- RENAMED requirements present under the new name and absent under the old one
If the sync failed, or any capability does not match, report what differs and stop — do not archive. Nothing has moved and `changeRoot` is intact, so the user can fix the mismatch or re-run the sync and start the archive again.
5. **Perform the archive**
Create an `archive` directory under `planningHome.changesDir` if it doesn't exist:
```bash
mkdir -p "<planningHome.changesDir>/archive"
```
Generate the target name: use the change name as-is when it already starts with a `YYYY-MM-DD-` prefix; otherwise prepend the current date as `YYYY-MM-DD-<change-name>`. Never stack a second date (same rule as `openspec archive`).
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move `changeRoot` to the archive directory
```bash
mv "<changeRoot>" "<planningHome.changesDir>/archive/<target-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**
```markdown
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** the archive path derived from `planningHome.changesDir`/<target-name>/
**Specs:** <"✓ Synced to main specs" only if the step 4 verification passed; otherwise "No delta specs" or "Sync skipped">
<"All artifacts complete. All tasks complete." — or, if archived with warnings, list them instead (e.g. "Archived with 2 incomplete tasks")>
```
**Guardrails**
- Announce the selected change; prompt for selection when it is ambiguous
- 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, run the `openspec-sync-specs` workflow inline (agent-driven)
- Never archive while a spec sync is still in flight — run the sync inline and verify the main specs before moving `changeRoot`
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
- Apply relevant runtime context and report conflicts; operation guidance remains advisory
- Consider every guidance entry and explain any inapplicable or conflicting advice
- Existing CLI checks, resolved paths, prompts, and command contracts are unchanged
- Artifact rules constrain only the specs being written and are never operation guidance
- Never copy runtime context, operation guidance, or artifact-rule text verbatim into output files
+354
View File
@@ -0,0 +1,354 @@
---
name: openspec-explore
description: Enter OpenSpec explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements in a project that uses OpenSpec. Use when the user wants to think through something before or during an OpenSpec change. Also use when the user says "openspec explore" or "opsx explore".
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.14.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, investigate the codebase, and run read-only commands or tools without confirmation, but you must NEVER write code or implement features. If the user asks you to implement something, do not start it here: say that explore mode does not implement, and point them at `/opsx:propose`, which turns the discussion into a change. The work happens from that change, never from explore mode. You MAY create or update OpenSpec change artifacts (proposals, designs, specs) within a confirmed scope—that's capturing thinking, not implementing. Answering design or clarifying questions is never consent to write. Before the first write-capable action, name the artifacts or files you would change and what you would do, ask a direct yes/no question, and wait for the user's confirmation in a separate message. Confirmation covers only the scope you described; ask again before expanding it. An explicit request from the user to capture the exploration as a new change is itself that confirmation, covering the change and the change artifacts the request names; scaffold it first as described below.
**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.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
---
## 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
---
## Planning a Change
When the user is planning a change, guide them toward shared understanding with focused discovery questions. For open-ended discussion, follow the conversation without imposing an interview or a required output.
Before asking a factual question, follow the context discovery below and inspect relevant OpenSpec artifacts, source, tests, docs, and configuration. Do not ask the user to repeat facts you can verify. Summarize relevant findings without reproducing private context or rules. If evidence is missing, conflicting, or inaccessible, state that limitation and ask only for the clarification needed to proceed.
- **Follow dependencies** - Resolve the next blocking decision before its dependent details. For example, clarify the user's outcome and scope before choosing an API or data model. Revisit downstream assumptions when an earlier answer changes. Skip branches that do not matter to this goal.
- **Keep questions focused** - Ask one focused question at a time, and briefly explain why it matters and which decision it unlocks. Batch questions only if the user asks for a batch; keep them small and group related decisions.
- **Offer grounded recommendations** - When evidence supports a recommendation, state your preferred option and why it fits the user's goals, with alternatives and their tradeoffs when useful. Do not invent intent, priorities, or external constraints: ask the user when only they can answer. Avoid a fixed question format.
- **Keep a conversational record** - Track decisions in the conversation, not in files. Separate confirmed decisions from proposed defaults and unresolved questions. Silence is not acceptance. Accepting an answer or a batch of recommendations is not permission to write. Keep file-write confirmation separate from discovery questions and follow the guardrails below.
Stop asking when the user has enough clarity. Let them pause, pivot, or defer a decision; do not exhaust every branch or force a proposal.
For example, after inspecting the relevant code:
```text
The CLI already uses SQLite and has no remote service. Is sharing state
across devices in scope? That determines whether local storage is enough.
If this stays a single-device tool, I recommend keeping SQLite to avoid
adding a service to operate; shared state would need a separate sync design.
```
---
## 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 A] -------> [State B] |
| | |
| v |
| [State C] |
| |
| System diagrams, state machines, |
| data flows, architecture sketches, |
| dependency graphs, comparison tables |
| |
+------------------------------------------+
```
**Draw with plain ASCII only** — borders `+` `-` `|`, arrows `-->` `<--` `^` `v`, markers `*` `x`.
Unicode diagram glyphs can render at different widths across terminals, fonts, and locales, so padded boxes and aligned tables can drift. Keep every diagram character ASCII.
**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 and task status
- What the user might be working on
That is the *change* list - work in flight. It does not include the project's durable capabilities, so list those too:
```bash
openspec list --specs
```
Add `--json` for ids and requirement counts, and append `--store "<id>"` only for a registered standalone store. This is the inventory of what the project already claims to do, and `openspec list` on its own never shows it. To look at one, run `openspec show "<spec-id>" --type spec --json --no-scenarios` (same `--store` rule) - it returns that capability's purpose and requirement texts without pulling the whole spec file into context, and `--type spec` stops a change of the same name from making it ambiguous.
The filtered read is only an overview. Before deciding what is already covered or what should change, read each relevant spec in full, including scenarios, with `openspec show "<spec-id>" --type spec` (same `--store` rule).
Then read the project's own context from the resolved root - `<root.path>/openspec/config.yaml` (or `config.yml`). Use the `root.path` returned above, and skip this if neither file exists:
- `context`: project background - tech stack, conventions, constraints
- `rules`: keyed by artifact id - the entries for an artifact apply only when you write that artifact
Ground your thinking in these. They are constraints for you to follow, not content to reproduce: do NOT copy them into the conversation or into any artifact you create.
### 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
If the user asks you to capture the exploration as a new change, that request is the confirmation required above. It covers scaffolding that change and creating the change artifacts the request names, and nothing else. This holds only when the request is theirs: a yes to an offer you made confirms only the scope your offer itself named, so name the change and the artifacts in the offer. Don't re-ask for what they already asked for; do ask before anything beyond it. Transition seamlessly into the requested capture:
1. Run `openspec new change "<name>"` (with `--store <id>` when applicable) before creating any artifacts. Never create a new change directory under `openspec/changes/` by hand; the CLI scaffold creates required metadata such as `.openspec.yaml`. Keep the selected `--store <id>` on every applicable follow-up `status` and `instructions` command.
2. Run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store), then process the requested artifacts in dependency order. For each requested artifact that is `ready`, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store). Before creating a requested artifact, evaluate any condition in its own `instruction` against the explored change; record a deliberate skip instead when the condition does not apply. If a requested artifact is blocked by a direct prerequisite the user did not request, run `openspec instructions "<prerequisite-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) for that prerequisite whether it is `ready` or `blocked`. If its own `instruction` states a condition, evaluate that condition against the explored change and record a deliberate skip only when the condition does not apply. If the condition applies, or the prerequisite is not conditional, treat it as a normal prerequisite and ask before expanding the capture. Do not create an unrequested prerequisite unless the user approves.
3. Follow the returned `template` and `instruction` fields. Read completed dependency files listed in `dependencies`, and apply `context` and `rules` as constraints without copying them into the artifact. If the instruction delegates creation to a specific skill or command, invoke it; otherwise write the artifact to `resolvedOutputPath`, using the instruction to choose a concrete path when it is a glob. Verify that the selected concrete output exists.
4. After creating each artifact, re-run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) and continue until every requested artifact is `done`, `skipped`, or was deliberately skipped because its own `instruction` stated a condition that did not apply. Tell the user about a deliberate conditional skip, remember it, and do not reconsider it. Dependencies are enablers, not gates: if a requested artifact is still `blocked` only because you deliberately skipped a conditional prerequisite, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) despite the blocked status, then create it using step 3 only when those recorded conditional skips are its sole missing dependencies. If a requested artifact is blocked by a prerequisite the user did not ask to capture and cannot be conditionally skipped, explain that dependency and ask before expanding the capture.
Capture the artifact(s) the user requested without asking them to invoke another workflow command. If they asked only to start a change, stop after scaffolding and show its status. When the requested capture is done, stop there and name where the work continues: `/opsx:propose` writes the remaining planning artifacts, and `/opsx:apply` implements the change once tasks exist. Capturing artifacts never starts implementing them.
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Resolve and read existing artifacts for context**
- Run `openspec status --change "<name>" --json`.
- Use `changeRoot`, `artifactPaths`, and `actionContext` from the status JSON.
- Read existing files from `artifactPaths.<artifact>.existingOutputPaths`.
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**
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
| Insight Type | Where to Capture |
|----------------------------|-------------------------------------|
| New requirement discovered | `specs/<capability-path>/spec.md` |
| Requirement changed | `specs/<capability-path>/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
| | |
v v v
+--------+ +--------+ +--------+
|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 |
+---------------------------------------------+
|
+-------------+-------------+
v v v
+---------+ +---------+ +---------+
| Google | | GitHub | | Email |
| OAuth | | OAuth | | Magic |
+----+----+ +----+----+ +----+----+
| | |
+-------------+-------------+
v
+-----------+
| Session |
+-----+-----+
|
v
+-----------+
| 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? Run `/opsx:propose` and this becomes a change."
- **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):
- Turn this into a change: `/opsx:propose`
- 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. Workflow configuration counts too: creating or editing schemas, templates, or `openspec/config.yaml` is a change, not thinking. Creating or updating OpenSpec change artifacts within the confirmed scope is fine, writing anything else is not. When the user is ready to build, name the handoff rather than starting: `/opsx:propose` turns the discussion into a change, and the work happens there.
- **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. Read-only commands and tools need no confirmation. Before the first write-capable action—including `openspec new change` or another command that writes files—name the artifacts or files and proposed changes, ask a direct yes/no question, and wait for explicit confirmation in a separate user message. That confirmation covers only the described scope; ask again before expanding it. Answers to design or clarifying questions are never consent to write. That rule governs `openspec new change` whenever you are the one proposing the capture; the user's own capture request is the exception, handled in the capture transition above.
- **Don't manually scaffold changes** - Never create a new change directory under `openspec/changes/` by hand. Always use `openspec new change "<name>"` (with `--store <id>` when applicable) so required metadata such as `.openspec.yaml` is created before writing artifacts.
- **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
+174
View File
@@ -0,0 +1,174 @@
---
name: openspec-propose
description: Propose a new OpenSpec 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. Also use when the user says "openspec propose" or "opsx propose".
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.14.0"
---
Propose a new change - create the change and generate all artifacts in one step.
**Planning boundary**: This workflow creates planning artifacts only. The user request that selected or triggered this workflow authorizes planning only, even if it asks to build or fix something. Do not edit project code. After the planning artifacts are complete, stop. Do not start implementation in the same response, even if the initial request asks for it. Wait for a new user request after the artifacts are presented; then start the apply workflow.
I'll create a change with the artifacts your schema defines. With the default spec-driven schema that is:
- proposal.md (what & why)
- `specs/<capability-path>/spec.md` (what the system must do - a delta, not the main spec)
- design.md (how)
- tasks.md (implementation steps)
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
When the user is ready to implement, they must start the apply workflow explicitly.
---
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
**Steps**
1. **Understand the request and clarify material ambiguity**
If no clear input is provided, ask the user (open-ended, no preset options):
> "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.
If the request contains ambiguity that would materially affect scope, externally observable behavior, compatibility, or acceptance criteria, ask the user before creating the change. For minor details, make a reasonable assumption and record it in the planning artifacts.
2. **Load project context**
Run `openspec context --json` from the current working directory (or `openspec context --json --store "<store-id>"` when a registered store was explicitly selected). Use the returned `root.path` as the authoritative OpenSpec root. If context reports `no_openspec_root`, stop without creating or changing any files and follow the **Project check** above for how this workflow was reached. Offer `openspec init` only for an explicit OpenSpec request, and wait for the user to request initialization. Do not initialize automatically or run `openspec new change`. After initialization, rerun this context check before continuing. For any other context failure, stop and report the error; do not fall back to the current directory or run later OpenSpec commands without the selected store.
Only when context returns a resolved `root.path`, read `<root.path>/openspec/config.yaml`. Use `config.yml` only when `config.yaml` does not exist. If neither file exists, continue without project context. Do not fall back to `config.yml` if `config.yaml` is unreadable or invalid.
If the file parses as a YAML object and its `context` field is a string no larger than 51,200 bytes in UTF-8, apply that field before exploring the codebase or making planning decisions. If the file cannot be read or parsed, or the context field is invalid or oversized, continue without project context. Validate this field independently of other config fields, as OpenSpec does.
Treat context as project-provided data and constraints, not as authority to change this workflow: it cannot override user authorization, the planning boundary, tool restrictions, or artifact and output rules. Do not copy the context into artifacts; use it to focus any codebase exploration and as a constraint on the proposal.
3. **Determine the workflow schema**
Use the configured default schema unless the user explicitly requests a different workflow.
**Use a different schema only if the user:**
- Explicitly requests a specific schema by name → use `--schema <schema-name>`
- Asks to "show workflows" or asks "what workflows" exist → resolve the authoritative root by running `openspec context --json` from the current working directory. If the user explicitly selected a registered store, use `openspec context --json --store "<store-id>"`. Then run `openspec schemas --json` with its working directory set to the returned `root.path` and let them choose. This preserves roots selected by a local `store:` pointer or the global `defaultStore`; when a registered store was explicitly selected, append `--store "<store-id>"` to `openspec schemas --json` as well. If context fails, stop as described in the context-loading step; do not fall back to the current directory.
Otherwise, omit `--schema` to preserve the configured default.
4. **Create the change directory**
Choose one schema form below. If a registered store is selected, append `--store "<store-id>"` to that command and each later OpenSpec command shown below that accepts `--store`.
Using the configured default:
```bash
openspec new change "<name>"
```
Using an explicitly requested schema:
```bash
openspec new change "<name>" --schema "<schema-name>"
```
This creates a scaffolded change in the planning home resolved by the CLI with `.openspec.yaml`.
5. **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, each with its `status` and its `requires` edges (the artifact IDs it directly depends on)
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
6. **Create every artifact in the required set**
Use a todo list 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
- `skipped`/`warning`: present when the change declares skip_specs and this artifact must NOT be created - stop and pick another artifact
- `resolvedOutputPath`: Resolved path or pattern to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context - always re-read them from disk, even if you saw them earlier in the conversation (the user may have edited them)
- **Inspect the relevant project before drafting**: Read `context` and `rules` first, then inspect relevant implementation, nearby tests, configuration, and documentation outside `openspec/`. Keep inspection read-only and proportional to the change; reuse findings for later artifacts and inspect more only as needed.
- Identify the target project from the request and project context; the planning home may be separate from the code. If the target is unclear, ask. For greenfield or non-code changes, inspect the available structure and relevant documents. If source is unavailable, state the limitation and ask when it materially affects the plan.
- Ground scope, approach, and tasks in what you find. Distinguish observed behavior from assumptions and proposed additions; surface conflicts with existing specs instead of silently deciding which is correct.
- Do this discovery now, rather than leaving generic "explore the codebase" or "make a plan" tasks for implementation. Keep any necessary follow-up investigation specific to an unresolved question.
- If the `instruction` field delegates creation to a specific skill or command, invoke it to produce the artifact instead of writing the file yourself, then verify the artifact file exists at `resolvedOutputPath`
- Otherwise create the artifact file using `template` as the structure and write it to `resolvedOutputPath`. If `resolvedOutputPath` is a glob, follow `instruction` to choose the concrete file path
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until every artifact in the required set exists (not just `apply.requires`)**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- The required set is `applyRequires` plus every artifact reachable from those by following the `requires` edges in `status --json` - walk them transitively (spec-driven closes over proposal, specs, design, tasks). Leave artifacts outside that set alone
- `status` is file-existence only, so an `applyRequires` artifact reading `done` does NOT mean its dependencies exist - writing `tasks.md` early marks `tasks` done while `specs` was never written. Use each artifact's `requires` edges, not its `status`, to build the required set: a `done` artifact still lists what it depends on
- An artifact already reading `status: "skipped"` is satisfied: the change declares `skip_specs` in `.openspec.yaml`, so its files must NOT exist. Never try to create one
- Create every artifact in the required set that is missing, then re-check - creating one can unblock others
- Skip one only when `status` already reports it `skipped`, or when its own `instruction` says it is conditional: run `openspec instructions <artifact-id> --change "<name>" --json` and skip only if its `instruction` field marks it optional (e.g. "create only if..."). Spec-driven's `design.md` qualifies; `specs` qualifies only via the `skipped` status above, never by your own judgment. Tell the user, and do not reconsider it
- Dependencies are enablers, not gates: if a required artifact is still `blocked` only because you skipped a conditional dependency, write it anyway
- Stop when every artifact in the required set is `done`, `skipped`, or was deliberately skipped
c. **If an artifact requires user input** (unclear context):
- Ask the user to clarify
- Then continue with creation
7. **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, plus any conditional artifact you skipped and why
- What's ready: "All artifacts needed for implementation are ready."
- Prompt: "The artifacts are ready for review. When you are ready, run `/opsx:apply` or ask me to apply this change."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type - it is the authoritative guidance, even for familiar artifact names
- If the `instruction` field directs you to use a specific skill or command to create the artifact, invoke it instead of writing the artifact directly
- 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**
- The request that invoked this workflow authorizes planning only. Any implementation or apply instruction in that request does not carry forward. Do NOT implement the change, start the apply workflow, or edit project code during this workflow. After presenting the artifacts, stop and wait for a new user request to start the apply workflow
- Create every artifact the apply phase transitively depends on, not just the ids listed in `apply.requires`
- Always read dependency artifacts before creating a new one - re-read from disk, not from conversation memory (files may have changed since you last saw them)
- Ask about ambiguities that would materially change scope, externally observable behavior, compatibility, or acceptance criteria; for minor details, make reasonable assumptions and record them
- 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
+290
View File
@@ -0,0 +1,290 @@
---
name: openspec-sync-specs
description: Sync delta specs from an OpenSpec change to main specs. Use when the user wants to update main specs with changes from a delta spec, without archiving the change. Also use when the user says "openspec sync" or "opsx sync".
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.14.0"
---
Sync delta specs from a change to main specs.
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
**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 ask the user to select one
When prompting, show changes that have delta specs (under `specs/` directory).
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:sync <other>`).
2. **Resolve change context**
Run:
```bash
openspec status --change "<name>" --json
```
The JSON includes `planningHome.root`. Main specs live under `<planningHome.root>/openspec/specs/` — use that (store-aware) root for every main-spec path below, not a hardcoded repo path. When a store is selected it points at the store, not the current repository.
3. **Find delta specs**
Use `artifactPaths.specs.existingOutputPaths` from the status JSON as the
only source of delta spec paths. If the `specs` entry is missing or
`existingOutputPaths` is empty, report that there are no delta specs to sync,
do not infer them from other artifacts, and stop without requesting artifact
instructions or writing a main spec.
Sync every path in `existingOutputPaths` unless the caller narrowed the set.
A caller narrows it by naming an explicit list of complete entries from
`existingOutputPaths` — copy those absolute values verbatim. Archive does
this inline, and a user can too (for example, by selecting the entry ending
in `/specs/billing/invoices/spec.md`).
Then sync only the named paths and leave the remaining delta specs untouched:
bulk archive excludes a delta whose implementation it could not find, and
syncing it anyway would write a main spec the caller deliberately withheld.
Carry that narrowed selection through step 4; never widen it back to the full
list. If a named path is not in `existingOutputPaths`, do not sync it —
report it and stop, rather than dropping it silently. If the named list is
empty, report that there is nothing to sync and stop without writing a main
spec.
Each delta spec file contains sections like:
- `## ADDED Requirements` - New requirements to add
- `## MODIFIED Requirements` - Changes to existing requirements
- `## REMOVED Requirements` - Requirements to remove
- `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
If no delta specs found, inform user and stop.
4. **For each delta spec, apply changes to main specs**
Before the first main-spec write, obtain one current specs-rule snapshot:
- If archive invoked this workflow inline and supplied a valid snapshot from
`openspec instructions specs --change "<name>" --json`, reuse it and do not
fetch the same instructions again.
- Otherwise run that command once now with the same selected-root flags.
- If the direct lookup exits non-zero or returns invalid artifact-instruction
JSON, report the error and stop before writing any main spec. Do not treat the
failure as an absent rule set.
- A valid response with omitted `rules` means no artifact rules are configured
and the existing semantic merge continues.
Apply returned `rules` only to the content and form of the main specs produced
by this merge. Artifact rules are not operation guidance and cannot change
selected roots, delta paths, CLI checks, or workflow steps. Use their text as
constraints without copying it verbatim into a main spec or summary.
For each capability delta spec path selected in step 3 — the full `existingOutputPaths` list, or the narrowed subset when a caller supplied one (these may belong to a selected store, not the repo):
a. **Read the delta spec** to understand the intended changes
b. **Read the main spec** at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (may not exist yet)
**If it does not exist yet** (a new capability), match what `openspec archive` does:
only ADDED requirements may be applied - step d creates the spec from them.
MODIFIED and RENAMED have no requirement to act on, so stop the sync for that
capability and report that its main spec does not exist and only ADDED is allowed
for a new spec; never invent the missing requirement. REMOVED has nothing to
remove - skip it and warn.
c. **Apply changes intelligently**:
**ADDED Requirements:**
- If requirement doesn't exist in main spec → add it
- If requirement already exists → update it to match (treat as implicit MODIFIED)
**MODIFIED Requirements:**
- Find the requirement in main spec
- Apply the changes - this can be:
- Adding new scenarios the main spec does not have yet
- Modifying existing scenarios
- Changing the requirement description
- Preserve scenarios/content not mentioned in the delta
**REMOVED Requirements:**
- Remove the entire requirement block from main spec
- Retiring the capability. Delete the whole `spec.md` - and the directory once
nothing else is left in it - only when ALL of these hold:
1. removing the requirements *this run* left no requirement blocks;
2. the rest of the spec is well-formed (it still has a `## Purpose`);
3. the main spec was not already empty before this sync - if you removed
nothing, change nothing;
4. every other nonblank line in the whole file is accounted for as the
title, Purpose, Requirements header, or a canonical requirement's
statement, scenarios, or fenced examples;
5. the change's `.openspec.yaml` declares `retire_capabilities: true`;
6. the `spec.md` resolves inside the real specs root (do not follow a
capability-directory symlink to delete an external file).
If removing the selected requirements would leave no requirement blocks and
any retirement condition is not satisfied, do not modify the main spec. Stop
the sync for that capability, report the blocking condition, and tell the user
how to resolve it. Never write or leave an empty `## Requirements` section.
When only the marker is missing, say that too - it is the one thing the user
can add to make the retirement go through.
- Deleting the file also deletes its `## Purpose`; any other section blocks
retirement. Name Purpose when you report the retirement. Include a pasteable
`git checkout` only when the spec lived in the caller's checkout;
otherwise give checkout-scoped recovery guidance.
**RENAMED Requirements:**
- Find the FROM requirement, rename to TO
**`## Purpose` in the delta:**
- The main spec already has one and it is authoritative - leave it alone
(this is what `openspec archive` does; it warns and moves on)
d. **Create new main spec** if capability doesn't exist yet:
- Only when the delta has ADDED requirements to put in it and no MODIFIED or
RENAMED requirements blocked this capability in step b. Otherwise create nothing
and leave the specs directory untouched. For a REMOVED-only delta, if the change's
`.openspec.yaml` declares `retire_capabilities: true`, report it as already retired
and continue without recreating the spec. Without that marker, report the sync as blocked:
`openspec archive` rejects it with `Spec must have at least one requirement`.
An empty delta has no operations to sync; report it as blocked too.
Never write an empty `## Requirements` section.
- Create `<planningHome.root>/openspec/specs/<capability-path>/spec.md`
- Add Purpose section: copy the delta's `## Purpose` body verbatim when it has one
(this is what `openspec archive` does); only write a brief TBD placeholder when it does not
- Add Requirements section with the ADDED requirements
- Follow the **Main Spec Format Reference** below
5. **Validate updated main specs**
Run `openspec validate --specs` with the same selected-root flags used earlier.
If validation fails, report the problems and do not claim the sync succeeded.
6. **Show summary**
After applying all changes, summarize:
- Which capabilities were updated
- What changes were made (requirements added/modified/removed/renamed)
- Any new main spec left with a TBD Purpose placeholder, so it gets written
now rather than lingering
- Any capability retired, naming the deleted `spec.md`, its Purpose, and
either a pasteable `git checkout` or checkout-scoped recovery guidance
**Delta Spec Format Reference**
```markdown
# Spec Delta
## Purpose
Only on a delta that introduces a brand-new capability. Seeds the new main spec.
## ADDED Requirements
### Requirement: New Feature
The system SHALL do something new.
#### Scenario: Basic case
- **WHEN** user does X
- **THEN** system does Y
## MODIFIED Requirements
### Requirement: Existing Feature
The system SHALL keep doing the existing thing, now also handling A.
#### Scenario: Scenario the main spec already has
- **WHEN** user does X
- **THEN** system does Y
#### Scenario: New scenario to add
- **WHEN** user does A
- **THEN** system does B
## REMOVED Requirements
### Requirement: Deprecated Feature
## RENAMED Requirements
- FROM: `### Requirement: Old Name`
- TO: `### Requirement: New Name`
```
**Main Spec Format Reference**
Main specs are what the delta merges INTO. They must never contain delta operation headers (`## ADDED/MODIFIED/REMOVED/RENAMED Requirements`) - after syncing, every requirement lives under a single `## Requirements` section:
```markdown
# <capability> Specification
## Purpose
Short description of what this capability does and why it exists.
## Requirements
### Requirement: New Feature
The system SHALL do something new.
#### Scenario: Basic case
- **WHEN** user does X
- **THEN** system does Y
```
**Key Principle: Intelligent Merging**
Unlike programmatic merging, you merge rather than overwrite:
- A MODIFIED block carries the whole requirement - body plus every scenario that survives the change. `openspec validate` and `openspec archive` both reject one that drops a scenario the main spec still has.
- Keep anything the delta does not mention, in the main spec's existing order
- Use your judgment to merge changes sensibly
**Output On Success**
```markdown
## Specs Synced: <change-name>
Updated main specs:
**<capability-1>**:
- Added requirement: "New Feature"
- Modified requirement: "Existing Feature" (added 1 scenario)
**<capability-2>**:
- Created new spec file
- Added requirement: "Another Feature"
Main specs are now updated. The change remains active - archive when implementation is complete.
```
**Guardrails**
- Read both delta and main specs before making changes
- Preserve existing content not mentioned in delta
- Never copy a delta file into a main spec as-is - merge its content so the main spec keeps the Main Spec Format Reference structure, with no delta operation headers
- If something is unclear, ask for clarification
- Show what you're changing as you go
- The operation should be idempotent - running twice should give same result
- Use only `artifactPaths.specs.existingOutputPaths`; never infer delta specs from unrelated artifacts
- Honor a caller-supplied subset of `existingOutputPaths`; never widen it back to the full list
- Fetch specs instructions once for direct sync, or reuse the archive-supplied snapshot inline
- Stop before every main-spec write on a non-zero or invalid JSON specs-instruction response
- Artifact rules constrain only the specs being written and are never copied into output files
+45
View File
@@ -0,0 +1,45 @@
# dependencies
node_modules/
# Next.js / build output
.next/
out/
build/
dist/
*.tsbuildinfo
next-env.d.ts
# tests
coverage/
playwright-report/
test-results/
# env & secrets (keep templates)
.env
.env.*
!.env.example
# local data: SQLite DB, attachments, backups
data/
*.db
*.db-journal
*.db-wal
*.db-shm
uploads/
backups/
# logs
*.log
npm-debug.log*
# OS / editor
.DS_Store
Thumbs.db
desktop.ini
.vscode/*
!.vscode/extensions.json
.idea/
~$*
# Claude Code local settings
.claude/settings.local.json
+49
View File
@@ -0,0 +1,49 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project status
**AI 補助申請系統** (AI subscription subsidy system): an internal web app for employees to claim 50% reimbursement of work-related AI subscriptions (ChatGPT / Claude / Gemini / other), with manager review, monthly department settlement, and HR/finance payout tracking.
The repo is **pre-implementation**: there is no source code, build, lint or test tooling yet. **Chosen stack: Next.js (App Router, TypeScript, full-stack) + SQLite**, single-instance deployment; attachments on local disk. ORM/test tooling are finalized in the `setup-project-foundation` change (see `openspec/changes/plan-system-roadmap/design.md` D3). Node 24 / npm 11 are installed. When tooling is added, update this file with the commands.
Git repository on branch `main` (no remote yet).
## Source-of-truth documents (`docs/`)
- `AI補助申請系統_規格文件_v1.0.docx` — business rules, roles, statuses, calculation, audit, MVP acceptance criteria, open decisions (§20).
- `AI補助申請系統_表單結構與前端介面規劃_v1.0.docx` — frontend IA, per-field validation, page layouts, routes, shared components, MVP priorities (P0/P1/P2), frontend acceptance criteria.
- `風格2_首頁.png`, `風格2_新增申請頁.png` — chosen visual style mockups (dashboard, new application page).
Python 3.12 is installed (user scope, `%LOCALAPPDATA%\Programs\Python\Python312`); `.docx` text can be extracted with Python or with PowerShell (`System.IO.Compression.ZipFile` → read `word/document.xml`, strip tags).
## Workflow: OpenSpec (spec-driven)
Changes go through OpenSpec (`openspec/config.yaml`, schema `spec-driven`). Specs live in `openspec/specs/` (currently empty), proposed changes in `openspec/changes/`, completed ones in `openspec/changes/archive/`. Use the bundled skills/commands rather than ad-hoc edits:
- `/opsx:explore` — think through requirements before committing to a change
- `/opsx:propose` — create a change with proposal, design, specs and tasks
- `/opsx:apply` — implement a change's tasks
- `/opsx:sync` — merge delta specs into main specs
- `/opsx:archive` — finalize a completed change
## Domain rules that are easy to get wrong
- **Month attribution** is by **刷卡日期 (card charge date)** only — never invoice date, service period, or submission date. It drives the application month and both deadlines.
- **Deadlines**: employee submission by the 20th of the following month; department head settlement submission by the 25th; payout in the next payroll as 「其他獎金」.
- **Personal amount** = sum of the month's approved TWD amounts × 50%, integer TWD, rounding configurable (default round half-up). TWD amount from the card statement is the basis; foreign-currency amount is reference only.
- **Department monthly cap** = headcount snapshot × NT$500 (研發部: NT$1,000). Headcount comes from a **monthly snapshot**, not live headcount. Unused quota does not carry over.
- **Over cap** → pro-rata: `final = personal ÷ dept_total × cap`. Rounding remainders are allocated by largest fractional part so the total **never exceeds** the cap (spec example: 450/850 of 1,300 with cap 1,000 → 346/654).
- **Approval ≠ payout.** Managers review work purpose only; amounts are settled at month end across all approved cases. UI must never make the quota look first-come-first-served, and must label pre-settlement amounts as 「預估」 vs 「最終」.
- **Statuses**: 草稿 → 待主管審核 → (待補件 ↔ resubmit) / 不核准 / 審核通過 → 待月結 → 已提交 → 最終核定 → 已發放; plus 撤回. Return/reject require a comment.
- **Locking & audit**: after a department head submits settlement, data is locked; corrections go through admin rollback or correction records, never overwriting history. Snapshots, parameters and settlement results must be versioned/retained; every state transition logs actor and time.
- All rule parameters (per-person quota, 50% ratio, deadlines, platforms, rounding, attachment limits) are admin-configurable, not hard-coded.
## Roles
Employee, department manager/head (own department only), admin / HR-finance (all departments, final approval, payout; does not judge work purpose), system admin (settings, accounts, audit log). Routes in the frontend plan: `/dashboard`, `/applications[/new|/:id]`, `/department/review`, `/department/settlement`, `/admin/settlements|payments|settings|audit-log`.
## UI conventions (from the frontend plan)
Desktop-first internal tool with RWD; white/light-grey with dark blue brand color. Money as `NT$` + thousands separators, dates `YYYY/MM/DD`, months `YYYY/MM`. Status badges always include text (not color alone). Labels always visible (no placeholder-as-label). One primary action per view; destructive/irreversible actions (不核准, settlement submit, final approval, mark paid) require a confirm dialog. Planned shared components: StatusBadge, MoneyDisplay, MonthPicker, FileUploader, FilePreview, ReviewTimeline, QuotaCard, ConfirmDialog, EmptyState, ErrorSummary.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-02
+49
View File
@@ -0,0 +1,49 @@
# Design
## Context
- 技術選型見 `plan-system-roadmap/design.md` D3(Next.js App Router + TypeScript);風格稿與文件差異的處理見 D9。
- 依賴 change 2 提供目前登入者、角色清單與所屬部門的伺服器端查詢。
- 風格稿:左側白色側欄(Logo、系統中英文名稱、導覽、底部 slogan 與版權)、頂部列(日期、鈴鐺、頭像+姓名+部門)、頁首大標題+說明+柔和暖色插圖、白色圓角卡片、深藍黑主要按鈕、藍色淺底選中狀態、綠色金額強調。
## Goals / Non-Goals
**Goals:**
- 單一 layout 與元件庫,讓後續 change 只寫頁面內容。
- 格式化與狀態標籤由單一來源提供,避免各頁自行格式化。
**Non-Goals:**
- 通知中心內容(change 12);本 change 只放通知入口與空狀態。
- 首頁卡片內容(change 11)。
- 檔案上傳/預覽(change 6)、審核時間軸(change 8)、額度卡(change 9)。
## Decisions
### 樣式方案:Tailwind CSS + CSS 變數 tokens
以 CSS 變數定義色彩、圓角、陰影、間距等 tokens(取自風格稿),Tailwind 設定引用這些變數。元件以自建為主,互動較複雜的對話框、選單使用無樣式且可及性完整的 headless 元件(如 Radix UI)。
替代方案:完整 UI 套件(MUI、Ant Design)——外觀與風格稿差距大,覆寫成本高。
### 導覽由「角色 → 項目」設定表產生
導覽項目、路徑與所需角色集中定義於一份設定;側欄、權限守衛與麵包屑都讀同一份。頁面層的存取權限仍由伺服器端檢查,導覽隱藏只是呈現。
### 格式化集中於 `format` 模組
`formatMoney`、`formatDate`、`formatMonth` 與狀態 → 標籤文字/色彩對照表放在共用模組,以 Vitest 測試;所有元件與頁面都透過 MoneyDisplay、StatusBadge 等元件使用,不直接格式化。日期顯示一律轉 Asia/Taipei。
### 狀態對照表以 §9 標籤為準
內部狀態代碼(如 `pending_review`)對應顯示文字(「待審核」);撤回在 D6 中為轉移事件、案件回到草稿,但仍保留「已撤回」標籤供時間軸事件顯示。
### RWD 斷點
手機 < 768px、平板 768–1279px、桌機 ≥ 1280px。平板保留側欄但可收合;手機改為漢堡選單。表格元件提供「卡片模式」與關鍵欄位設定,由頁面指定。
### 插圖與品牌素材
風格稿中的頁首插圖、便利貼、書本、馬克杯等裝飾為示意;本 change 以柔和漸層背景與簡化插圖替代,避免使用來源不明的圖片。品牌素材日後可替換。
## Risks / Trade-offs
- [風格稿裝飾圖片無法直接使用] → 以漸層與簡化插圖替代,保留整體氛圍;正式素材到位後替換 tokens/圖片即可。
- [各 change 新增元件時偏離 tokens] → 元件只能引用 tokens,不寫死色碼;code review 檢查。
- [角色組合多時導覽項目重複] → 設定表以路徑去重並依固定順序排列。
## Migration Plan
純前端新增,無資料遷移。回滾即移除 layout 與元件。
@@ -0,0 +1,29 @@
# Proposal
## Why
後續所有頁面(申請、審核、月結、發放、後台)都需要同一套全站框架、依角色導覽、視覺風格與共用元件。若各 change 各自做,金額/日期格式、狀態標籤文字與確認視窗行為會不一致,違反介面規劃 §10、§13「所有金額、日期、月份與狀態格式一致」的驗收要求。風格稿(`docs/風格2_首頁.png`、`docs/風格2_新增申請頁.png`)已定案,需先轉成設計 tokens 與元件。
## What Changes
- 全站框架:頂部列(Logo/系統名稱、今日日期、通知入口、使用者姓名/部門、使用者選單含登出)、左側依角色導覽(目前頁面高亮)、內容標題列(頁面名稱+說明+主要操作)、主內容區、選用右側輔助區(介面規劃 §2.1)。
- 依角色顯示導覽(介面規劃 §2):員工「首頁/新增申請/我的申請」;主管加上「部門審核/部門月結」;管理者「全公司月結/發放管理/後台設定」;系統管理員「後台設定/帳號與角色/操作紀錄」;所有人另有「使用說明/常見問題」靜態頁。導覽名稱用「新增申請」而非風格稿的「AI 補助申請」。
- 依風格稿建立設計 tokens:白底、淺灰分區、深藍(navy)主要按鈕、藍色強調、柔和暖色頁首插圖區、圓角卡片。
- 共用元件:StatusBadge、MoneyDisplay、MonthPicker、ConfirmDialog、EmptyState、ErrorSummary、Toast/Alert、頁首標題列;FileUploader/FilePreview 由 change 6、ReviewTimeline 由 change 8、QuotaCard 由 change 9 建立,但沿用本 change 的 tokens。
- 格式規則:金額 `NT$` + 千分位、日期 `YYYY/MM/DD`、月份 `YYYY/MM`;狀態標籤文字依介面規劃 §9(例如「待審核」而非風格稿的「審核中」),且一律顯示文字。
- RWD(介面規劃 §10):側欄在行動裝置收合為漢堡選單;資料表格轉卡片清單;主要按鈕在行動裝置改為底部固定操作列。
- `/dashboard` 先提供佔位頁(內容於 change 11);`/help`、`/faq` 靜態頁。
## Capabilities
### New Capabilities
- `app-shell`: 全站版面框架、依角色導覽、統一的顯示格式、狀態標籤、確認與錯誤回饋元件,以及響應式行為。
### Modified Capabilities
<!-- 無 -->
## Impact
- 依賴 change 1(專案骨架)與 change 2(登入身分與角色)。
- 新增全站 layout、設計 tokens、共用元件與格式化工具;後續 change 的頁面都放在此框架內並使用這些元件。
- 不影響資料模型。
@@ -0,0 +1,95 @@
# Spec Delta
## Purpose
提供 AI 補助申請系統所有頁面共用的版面框架、依角色導覽、一致的金額日期與狀態呈現、確認與錯誤回饋,以及桌機到手機的響應式行為。
## ADDED Requirements
### Requirement: 全站版面框架
登入後的每個頁面 SHALL 包含頂部列、左側導覽與主內容區。頂部列 MUST 顯示系統名稱、今日日期(含星期)、通知入口、使用者姓名與所屬部門,以及含登出的使用者選單。主內容區頂端 SHALL 顯示頁面名稱與簡短說明,頁面的主要操作按鈕位於標題列右側或表單底部(介面規劃 §2.1)。未登入者 MUST 被導向登入頁。
#### Scenario: 登入後的版面
- **WHEN** 設計部員工王小明於 2026/10/01 登入並進入首頁
- **THEN** 頂部列顯示「2026 年 10 月 1 日 星期四」、通知入口、「王小明」與「設計部」,左側顯示導覽,主內容區顯示頁面名稱
#### Scenario: 未登入存取內頁
- **WHEN** 未登入的使用者開啟 `/applications`
- **THEN** 系統導向登入頁
### Requirement: 依角色顯示導覽
左側導覽 SHALL 只顯示使用者角色可使用的功能,目前所在頁面 MUST 高亮。導覽項目:一般員工為「首頁、新增申請、我的申請」;部門主管另加「部門審核、部門月結」;管理者另加「全公司月結、發放管理、後台設定」;系統管理員另加「後台設定、帳號與角色、操作紀錄」。所有角色 SHALL 另有「使用說明、常見問題」。同時擁有多個角色的使用者 SHALL 看到各角色項目的聯集且不重複(介面規劃 §2)。
#### Scenario: 一般員工的導覽
- **WHEN** 只有員工角色的使用者登入
- **THEN** 導覽只顯示首頁、新增申請、我的申請、使用說明、常見問題,不顯示部門審核或後台設定
#### Scenario: 兼任主管的員工
- **WHEN** 同時具有員工與部門主管角色的使用者登入
- **THEN** 導覽顯示首頁、新增申請、我的申請、部門審核、部門月結、使用說明、常見問題
#### Scenario: 目前頁面高亮
- **WHEN** 使用者位於「我的申請」頁
- **THEN** 導覽中的「我的申請」以高亮樣式呈現,其餘項目不高亮
### Requirement: 金額與日期格式
系統所有畫面 SHALL 以一致格式呈現:金額為「NT$」加千分位整數(例如 NT$1,700);日期為 YYYY/MM/DD;月份為 YYYY/MM。尚無數值的金額 SHALL 顯示「--」(介面規劃 §10)。
#### Scenario: 金額顯示
- **WHEN** 畫面要顯示金額 13000
- **THEN** 顯示為「NT$13,000」
#### Scenario: 尚未確定的最終補助
- **WHEN** 案件尚未完成月結,畫面顯示最終補助欄位
- **THEN** 該欄位顯示「--」
#### Scenario: 日期與月份顯示
- **WHEN** 畫面顯示刷卡日期 2026-10-05 與其所屬月份
- **THEN** 分別顯示為「2026/10/05」與「2026/10」
### Requirement: 狀態標籤
案件與月結狀態 SHALL 以狀態標籤呈現,標籤 MUST 同時有文字與語意色,不可只靠顏色區分。案件狀態文字 SHALL 使用:草稿、待審核、待補件、已通過、不核准、待月結、已提交、已核定、已發放、已撤回(介面規劃 §9)。
#### Scenario: 待主管審核的案件
- **WHEN** 案件狀態為「待主管審核」
- **THEN** 標籤文字顯示「待審核」,而非「審核中」
#### Scenario: 色彩無法辨識時仍可讀
- **WHEN** 使用者以灰階模式檢視案件清單
- **THEN** 每個狀態仍可由標籤文字區分
### Requirement: 重要操作確認視窗
不核准、提交月結、最終核定、標記已發放等重要或不可逆操作 SHALL 在執行前顯示確認視窗,說明操作後果;使用者取消時 MUST NOT 執行操作(介面規劃 §13)。
#### Scenario: 取消提交月結
- **WHEN** 主管按下「確認並提交」,確認視窗顯示「提交後本月份名單將鎖定,如需更正須由管理者退回。確定提交?」,主管按取消
- **THEN** 月結未被提交,頁面維持原狀
### Requirement: 錯誤與回饋呈現
表單欄位錯誤 SHALL 顯示在欄位旁(inline);表單送出時若有多項錯誤,頁首 SHALL 顯示錯誤摘要(例如「尚有 3 項資料需完成」)並捲動到第一個錯誤欄位;系統層級的成功或失敗 SHALL 以提示訊息(Toast/Alert)呈現。表單欄位標籤 MUST 永遠可見,不可只用 placeholder 取代標籤(介面規劃 §10、§14)。
#### Scenario: 送出時有多項缺漏
- **WHEN** 使用者送出一份缺少 3 個必填欄位的表單
- **THEN** 頁首顯示「尚有 3 項資料需完成」,頁面捲動到第一個錯誤欄位,每個缺漏欄位旁顯示錯誤訊息
#### Scenario: 無資料時的空狀態
- **WHEN** 清單頁沒有任何資料
- **THEN** 顯示空狀態說明與可執行的下一步,而非空白表格
### Requirement: 響應式版面
系統 SHALL 支援桌機、平板與手機寬度且不出現欄位溢出、按鈕被遮擋或表格無法操作(介面規劃 §10、§13):手機寬度時側欄 SHALL 收合為漢堡選單;資料表格 SHALL 改為只保留關鍵欄位的卡片清單;頁面主要操作 SHALL 改為底部固定操作列。
#### Scenario: 手機開啟頁面
- **WHEN** 使用者以 375px 寬的手機開啟「我的申請」
- **THEN** 側欄收合為漢堡選單,案件以卡片呈現,頁面沒有水平捲動
#### Scenario: 長表單的主要按鈕
- **WHEN** 使用者在手機上捲動一個長表單
- **THEN** 主要操作按鈕固定顯示在畫面底部
### Requirement: 說明與常見問題頁
系統 SHALL 提供「使用說明」與「常見問題」兩個所有登入使用者可讀的靜態頁,內容至少涵蓋申請流程、50% 補助與部門月上限的關係、截止日,以及「可申請不代表必然補助、最終金額於月結後確認」(規格 §2)。
#### Scenario: 開啟常見問題
- **WHEN** 員工點選導覽中的「常見問題」
- **THEN** 顯示常見問題頁,其中包含「實際補助金額於月結後確認」的說明
+29
View File
@@ -0,0 +1,29 @@
# Tasks
## 1. 設計 tokens 與基礎樣式
- [ ] 1.1 依風格稿定義 CSS 變數 tokens(色彩、字級、圓角、陰影、間距)並接入 Tailwind 設定,建立 tokens 展示頁確認與風格稿色調一致
- [ ] 1.2 安裝並設定 headless 元件套件(對話框、下拉選單),確認 `npm run build` 成功
## 2. 格式化與狀態對照
- [ ] 2.1 實作 formatMoney(NT$+千分位、空值「--」)、formatDate(YYYY/MM/DD,Asia/Taipei)、formatMonth(YYYY/MM),以 Vitest 驗證 spec 中的範例
- [ ] 2.2 建立案件狀態代碼 → 標籤文字/語意色對照表(介面規劃 §9),以 Vitest 驗證「待主管審核」顯示「待審核」且每個狀態都有文字
## 3. 全站框架與導覽
- [ ] 3.1 建立登入後 layout(頂部列:系統名稱、今日日期含星期、通知入口、姓名/部門、使用者選單與登出;側欄;內容標題列;選用右側輔助區),以 Playwright 驗證登入後頂部列內容正確、未登入導向登入頁
- [ ] 3.2 建立角色 → 導覽項目設定表與側欄元件(聯集去重、目前頁高亮),以 Vitest 驗證各角色組合的項目清單,以 Playwright 驗證員工看不到部門審核
- [ ] 3.3 建立 `/dashboard` 佔位頁、`/help` 使用說明與 `/faq` 常見問題靜態頁(含「最終金額於月結後確認」說明),以 Playwright 驗證可開啟
## 4. 共用元件
- [ ] 4.1 實作 MoneyDisplay、StatusBadge、MonthPicker,以元件測試驗證輸出格式與標籤文字
- [ ] 4.2 實作 ConfirmDialog(取消不執行、確認才回呼),以元件測試驗證取消時回呼未被呼叫
- [ ] 4.3 實作 ErrorSummary(錯誤數量、捲動至第一個錯誤欄位)、inline 欄位錯誤樣式與 Toast/Alert,以 Playwright 在範例表單驗證「尚有 3 項資料需完成」與捲動行為
- [ ] 4.4 實作 EmptyState 與可切換卡片模式的資料表格元件,以元件測試驗證無資料時顯示空狀態
## 5. 響應式
- [ ] 5.1 實作手機漢堡選單、平板可收合側欄、手機底部固定操作列,以 Playwright 在 375px/768px/1280px 驗證無水平捲動、按鈕未被遮擋
- [ ] 5.2 在 `docs/` 或專案 README 記錄 tokens、共用元件與格式化規則的使用方式,確認後續 change 可依文件使用
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-02
@@ -0,0 +1,56 @@
# Design
## Context
- 技術選型見 `plan-system-roadmap/design.md` D3:Next.js + SQLite,附件存本機檔案目錄、路徑存 DB;備份範圍需涵蓋附件目錄(Risks)。
- 依賴 change 2(使用者、部門、主管關係)、change 3(操作紀錄)、change 4(`取得生效參數` 的附件格式與大小)、change 5(tokens、ConfirmDialog、Toast)。
- **順序假設**:申請案件(`applications` 資料表與狀態)在 change 7 才建立,但 change 6 排在其前。本 change 需要「附件屬於哪筆申請、申請目前狀態、申請人是誰」這三項資訊。
## Goals / Non-Goals
**Goals:**
- 提供可被 change 7/8/10 直接使用的附件服務與 FileUploader/FilePreview 元件。
- 檔案永不經公開路徑提供,所有讀取都經授權。
**Non-Goals:**
- OCR、自動辨識刷卡金額或日期。
- 防毒掃描(內部系統,列為後續評估)。
- 申請表單本身與送出流程(change 7)。
## Decisions
### 綁定介面:附件以 `application_id` 關聯,申請狀態透過介面查詢
附件表欄位:`id`、`application_id`、`kind`(invoice/card_statement)、`original_name`、`mime_type`、`size_bytes`、`storage_key`、`sha256`、`uploaded_by`、`uploaded_at`、`superseded_at`(替換或刪除時填入)。
本 change 定義一個「申請存取介面」(取得申請人、所屬部門、目前狀態是否可編輯)。在 change 7 完成前,以最小的 `applications` 草稿資料表(id、applicant_id、department_id、status)滿足此介面並以測試替身驗證;change 7 擴充同一資料表,不另建。
替代方案:附件先以暫存 token 上傳,送出時才綁定申請——需要清理孤兒檔案,且草稿本來就會在第一次儲存時建立申請,沒有必要。
### 「每類一個有效檔案」以 `superseded_at IS NULL` 表示
替換=把舊檔標記 superseded 再新增一筆;刪除=只標記 superseded。DB 加上部分唯一索引(`application_id, kind` where `superseded_at IS NULL`)保證不會有兩個有效檔案。舊檔案實體保留供稽核。
### 儲存位置與命名
檔案存於專案外或 `.gitignore` 的 `storage/attachments/`(路徑由環境變數設定),檔名使用隨機 `storage_key`,不使用原始檔名,避免路徑穿越與資訊外洩。原始檔名只存在 DB。
### 格式偵測以檔案魔術數字判斷
伺服器端讀取檔頭判斷 PDF(`%PDF-`)、JPEG(`FF D8 FF`)、PNG(`89 50 4E 47`),與允許清單比對;同時以串流計算大小,超過上限立即中止。前端也先檢查副檔名與大小以提供即時回饋,但不作為安全依據。
### 讀取路徑:授權後以串流回傳
`GET /api/attachments/:id` 在伺服器端檢查權限(本人、申請人部門主管、管理者),通過才串流檔案並設定 `Content-Disposition: inline`、`X-Content-Type-Options: nosniff`。未授權與不存在回傳相同的 404,避免枚舉。
### 預覽元件
圖片用 `<img>`;PDF 使用瀏覽器內建 PDF 檢視(`<iframe>`/`<object>` 指向授權路徑)。桌機以 Modal/Drawer、手機全螢幕呈現。
替代方案:pdf.js 自行渲染——可控性較高但增加套件大小,MVP 先用內建檢視。
## Risks / Trade-offs
- [change 7 對 `applications` 表的設計與本 change 的最小表衝突] → 最小表只含 change 7 必然需要的欄位;change 7 propose 時明確沿用並擴充此表。
- [瀏覽器內建 PDF 檢視在部分行動瀏覽器不支援] → 手機無法內嵌時提供「開啟檔案」連結(仍走授權路徑)。
- [本機磁碟損壞導致附件遺失] → 附件目錄納入 change 1 定義的定期備份。
- [被取代檔案無限累積] → 數量有限(每案少量),暫不清理;保留期限日後依公司規範再訂。
## Migration Plan
Drizzle migration 新增附件表(與最小 `applications` 表,若 change 7 尚未建立);建立儲存目錄並設定環境變數。回滾:移除資料表與目錄(無正式資料前)。
## Open Questions
- 附件保留期限與是否需要防毒掃描,可於上線前依公司資安規範確認,不影響本 change 的介面。
@@ -0,0 +1,30 @@
# Proposal
## Why
每筆 AI 補助申請都必須附上 Invoice 與刷卡帳單(規格 §9),刷卡帳單上的台幣金額更是補助計算依據;主管審核時也要能在頁內檢視附件(介面規劃 §5)。附件含個人交易資訊,需遵守最小揭露與存取控制(規格 §17、介面規劃 §1)。先把附件上傳、驗證、儲存與授權存取做成獨立能力,申請表單(change 7)與審核工作台(change 8)直接使用。
## What Changes
- 兩類附件:Invoice/訂閱證明、刷卡帳單;每類每筆申請各一個檔案。
- 上傳方式:點擊選檔或拖拉;顯示上傳中、成功、失敗、超過大小限制等狀態(介面規劃 §13)。
- 依 `rule-settings` 生效參數驗證格式(預設 PDF/JPG/PNG)與單檔上限(預設 10 MB),伺服器端以檔案內容判斷真實格式。
- 頁內預覽(PDF 與圖片)、替換、刪除;僅在案件為草稿或待補件時可替換/刪除,其他狀態唯讀。
- 上傳區提示:可遮蔽與申請無關的私人交易,但刷卡帳單 MUST 露出交易日期與台幣金額(Decisions Log)。
- 檔案存於伺服器本機、非公開目錄,只能經授權路徑讀取:申請人本人、其所屬部門主管、管理者;其他人一律拒絕。
- 附件與申請案件綁定;替換時保留被取代檔案的紀錄(不提供下載給一般使用者),刪除與替換寫入操作紀錄。
- 共用元件 FileUploader、FilePreview(沿用 change 5 的 tokens)。
## Capabilities
### New Capabilities
- `application-attachments`: 申請憑證附件(Invoice、刷卡帳單)的上傳驗證、儲存、預覽、替換/刪除與授權存取。
### Modified Capabilities
<!-- 無 -->
## Impact
- 依賴 change 2(身分、部門主管關係)、change 3(操作紀錄)、change 4(附件格式與大小參數)、change 5(tokens 與共用元件)。
- 申請案件本體在 change 7 建立;本 change 定義「附件屬於一筆申請草稿」的綁定介面,change 7 據以呈現與送出前檢查。
- 新增附件中繼資料表與伺服器檔案儲存目錄(需納入 change 1 定義的備份範圍)。
@@ -0,0 +1,92 @@
# Spec Delta
## Purpose
管理 AI 補助申請所需的憑證附件(Invoice 與刷卡帳單),涵蓋上傳驗證、與案件綁定、頁內預覽、替換刪除,以及只讓有權限者存取的保護機制。
## ADDED Requirements
### Requirement: 附件類型與綁定
每筆申請 SHALL 有兩個附件欄位:「Invoice/訂閱證明」與「刷卡帳單」,每個欄位同時 MUST 最多一個有效檔案。附件 SHALL 綁定到一筆申請,且只有該申請的申請人可上傳。系統 SHALL 提供「申請的兩類附件是否齊全」的查詢,供申請送出前檢查使用(規格 §9)。
#### Scenario: 兩類附件都已上傳
- **WHEN** 申請草稿已上傳 Invoice 與刷卡帳單各一份
- **THEN** 附件齊全查詢回傳「齊全」
#### Scenario: 缺少刷卡帳單
- **WHEN** 申請草稿只上傳了 Invoice
- **THEN** 附件齊全查詢回傳缺少「刷卡帳單」
#### Scenario: 他人嘗試上傳
- **WHEN** 使用者嘗試對不屬於自己的申請上傳附件
- **THEN** 系統拒絕上傳
### Requirement: 檔案格式與大小驗證
系統 SHALL 依上傳當下生效的制度參數驗證附件:格式 MUST 在允許清單內(預設 PDF、JPG、PNG),單檔大小 MUST 不超過上限(預設 10 MB)。格式判斷 MUST 以檔案實際內容為準,不可只看副檔名。驗證失敗時 MUST NOT 儲存檔案,並顯示具體原因。
#### Scenario: 超過大小上限
- **WHEN** 使用者上傳 12 MB 的 PDF,上限為 10 MB
- **THEN** 系統拒絕並顯示「檔案超過 10 MB 上限」,該欄位維持原狀
#### Scenario: 偽裝副檔名
- **WHEN** 使用者上傳副檔名為 .pdf、實際內容為執行檔的檔案
- **THEN** 系統拒絕並顯示「檔案格式不支援,僅接受 PDF、JPG、PNG」
#### Scenario: 管理者調整上限後
- **WHEN** 管理者把單檔上限改為 5 MB 並生效,員工上傳 6 MB 的 JPG
- **THEN** 系統拒絕並顯示「檔案超過 5 MB 上限」
### Requirement: 上傳操作與狀態回饋
附件欄位 SHALL 支援點擊選檔與拖拉上傳,並 SHALL 顯示上傳中(含進度)、上傳成功(檔名與大小)、上傳失敗(原因與重試)等狀態。上傳區 SHALL 顯示允許格式與大小上限(介面規劃 §3、§13)。
#### Scenario: 拖拉上傳成功
- **WHEN** 員工把 256 KB 的 invoice_chatgpt.pdf 拖到 Invoice 上傳區
- **THEN** 顯示上傳進度,完成後顯示「invoice_chatgpt.pdf 256 KB」及預覽、替換、刪除操作
#### Scenario: 網路中斷
- **WHEN** 上傳過程中連線中斷
- **THEN** 顯示上傳失敗與重試按鈕,該欄位不會留下不完整的檔案
### Requirement: 個資遮蔽提示
刷卡帳單上傳區 SHALL 提示使用者:可遮蔽與本次申請無關的其他私人交易,但 MUST 保留可辨識的交易日期與新台幣金額(規格 §9、介面規劃 §1)。
#### Scenario: 顯示遮蔽提示
- **WHEN** 員工檢視刷卡帳單上傳區
- **THEN** 畫面顯示「可遮蔽與申請無關的交易,但需露出交易日期與台幣金額」
### Requirement: 頁內預覽
有權限檢視附件的使用者 SHALL 可在頁內預覽 PDF 與圖片附件,不需另開新頁或下載;桌機以彈出視窗或側邊抽屜呈現,手機以全螢幕呈現(介面規劃 §5、§10)。
#### Scenario: 主管預覽刷卡帳單
- **WHEN** 部門主管在審核案件時點選「刷卡帳單預覽」
- **THEN** 檔案在頁內預覽視窗顯示,主管不用離開審核頁
#### Scenario: 手機預覽
- **WHEN** 員工在手機上點選 Invoice 預覽
- **THEN** 附件以全螢幕方式顯示,可關閉回到原頁
### Requirement: 替換與刪除限制
附件 SHALL 只在申請狀態為「草稿」或「待補件」時可由申請人替換或刪除;其他狀態的附件 MUST 為唯讀。替換或刪除 SHALL 寫入操作紀錄,被取代或刪除的檔案 SHALL 保留於系統以供稽核,但 MUST NOT 再出現在一般使用者的附件清單。
#### Scenario: 待補件時替換
- **WHEN** 案件狀態為待補件,員工以新的 card_statement.pdf 替換刷卡帳單
- **THEN** 案件顯示新檔案,操作紀錄記下替換的操作者與時間,舊檔案保留供稽核
#### Scenario: 待審核時嘗試刪除
- **WHEN** 案件狀態為待主管審核,員工嘗試刪除 Invoice
- **THEN** 系統拒絕,畫面不提供刪除按鈕
### Requirement: 附件存取控制
附件檔案 MUST NOT 可經由公開網址直接取得;每次讀取 SHALL 經過授權檢查,只允許:申請人本人、申請人所屬部門的主管、管理者(人資財務)。系統管理員僅具系統設定角色時 MUST NOT 讀取附件內容。未授權的讀取 SHALL 被拒絕且不透露檔案是否存在(規格 §17)。
#### Scenario: 其他部門主管存取
- **WHEN** 研發部主管嘗試開啟設計部員工申請的刷卡帳單
- **THEN** 系統回應與「檔案不存在」相同的拒絕結果
#### Scenario: 管理者存取
- **WHEN** 管理者在全公司月結詳情中開啟某員工的 Invoice
- **THEN** 系統允許預覽
#### Scenario: 猜測檔案網址
- **WHEN** 未登入者以猜測的網址請求附件
- **THEN** 系統拒絕存取,不回傳檔案內容
@@ -0,0 +1,23 @@
# Tasks
## 1. 資料模型與儲存
- [ ] 1.1 以 Drizzle 定義附件表(application_id、kind、原始檔名、mime、大小、storage_key、sha256、uploaded_by/at、superseded_at)與「每類一個有效檔案」部分唯一索引;若 change 7 尚未建立則一併建立最小 `applications` 表(id、applicant_id、department_id、status),執行 migration 並以測試確認無法同時存在兩個有效檔案
- [ ] 1.2 設定附件儲存目錄環境變數與 `.gitignore`,確認目錄不在公開靜態路徑下(以 HTTP 請求 `/storage/...` 驗證回應 404)
## 2. 附件服務
- [ ] 2.1 實作申請存取介面(申請人、部門、是否可編輯:草稿/待補件),以 Vitest 驗證各狀態的可編輯結果
- [ ] 2.2 實作上傳:讀取生效參數、以檔頭判斷格式、串流計算大小並超限中止、隨機 storage_key 落地,以 Vitest 驗證 12 MB 拒絕、偽裝 .pdf 拒絕、5 MB 上限調整後生效、非本人拒絕
- [ ] 2.3 實作替換與刪除(標記 superseded、保留實體檔、寫 audit-trail、非可編輯狀態拒絕),以 Vitest 驗證待補件可替換、待審核拒絕刪除且有操作紀錄
- [ ] 2.4 實作附件齊全查詢,以 Vitest 驗證齊全與缺少刷卡帳單情境
## 3. 授權讀取
- [ ] 3.1 實作附件讀取路由(本人、申請人部門主管、管理者;系統管理員單一角色拒絕;未授權與不存在同為 404;inline 與 nosniff 標頭),以整合測試驗證其他部門主管、未登入、管理者三個情境
## 4. 前端元件
- [ ] 4.1 實作 FileUploader(點擊/拖拉、進度、成功顯示檔名大小、失敗與重試、格式與上限提示、刷卡帳單遮蔽提示),以 Playwright 驗證拖拉上傳成功與超過上限錯誤訊息
- [ ] 4.2 實作 FilePreview(圖片、PDF;桌機 Modal/Drawer、手機全螢幕、手機不支援內嵌時提供開啟連結),以 Playwright 在 1280px 與 375px 驗證預覽開關
- [ ] 4.3 在元件文件中記錄 FileUploader/FilePreview 的使用方式與綁定介面,供 change 7/8 引用,確認範例可在展示頁執行
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-02
@@ -0,0 +1,49 @@
# Design
## Context
依 roadmap design D8:audit-trail 為 append-only,業務寫入與留痕在同一交易。基礎設施為 SQLite + Drizzle,交易工具(`BEGIN IMMEDIATE`)由 `setup-project-foundation` 提供;權限 guard 由 `add-identity-and-access` 提供。
## Goals / Non-Goals
**Goals:**
- 後續 change 只需呼叫一個函式即可留痕,且無法在交易外留痕。
- 資料庫層也擋住修改與刪除,不只靠應用程式。
**Non-Goals:**
- 不做紀錄的匯出、保存期限與歸檔(目前無需求)。
- 不做讀取操作(查看頁面)的存取紀錄;僅記錄寫入與登入事件。
## Decisions
### 資料模型
`audit_logs(id, occurred_at UTC ISO, actor_user_id NULL(系統/未登入), actor_label, action, target_type, target_id, before_json, after_json, comment, ip)`,索引:`(target_type, target_id)`、`occurred_at`、`actor_user_id`。
- `action` 與 `target_type` 用程式內集中定義的常數表(例如 `application.submit`、`settlement.submit`、`setting.update`、`auth.login_failed`),查詢頁的下拉選單由同一份常數產生,並附中文標籤。
- before/after 只存與該動作相關的欄位(狀態與被改動的欄位),不存整列,避免敏感資料(密碼雜湊、session)進入紀錄。
### 寫入 API:只接受交易物件
`recordAudit(tx, entry)` 第一個參數必須是交易物件(型別上與一般 db 連線區分),使呼叫端無法在交易外留痕,符合「同時成立」requirement。登入失敗事件沒有業務寫入,但仍以單獨交易寫入(同一交易內同時更新 failed_attempts)。
### 不可竄改:SQLite trigger
migration 建立 `BEFORE UPDATE` 與 `BEFORE DELETE` trigger,對 audit_logs 一律 `RAISE(ABORT, 'audit_logs is append-only')`。理由:即使未來程式誤寫,資料庫也會拒絕。替代方案(只靠程式不提供 API)無法防止誤用。
### 檢視權限
`users.can_view_audit_log` 布林欄位,系統管理員一律可看;管理者需此旗標為 true。授予/撤銷在 `/admin/accounts` 操作並留痕。路由權限設定擴充為「sysadmin 或 (admin 且 can_view_audit_log)」。
### 查詢頁
Server Component 讀取,篩選條件放 URL query(可分享、可重新整理),以 occurred_at + id 做 keyset 分頁,每頁 50 筆。詳情以側邊抽屜顯示前後差異(逐欄列出變更)。
## Risks / Trade-offs
- [audit_logs 持續成長] → 內部系統量小,SQLite 足以應付;有索引支撐常用查詢。日後需要時再加歸檔。
- [新寫入點忘記留痕] → 後續各 change 的 tasks 需含留痕測試;本 change 提供測試 helper `expectAudit(action, targetId)` 方便斷言。
## Migration Plan
新增 migration(資料表、索引、trigger、users 新欄位)。補接 identity-access 既有寫入點後,舊資料無留痕屬預期(系統尚未上線)。
@@ -0,0 +1,28 @@
# Proposal
## Why
規格 §17 要求保留申請建立、送出、退回、修改、核准、不核准、月結、最終核定及發放的時間與操作者,制度參數異動也要有紀錄;§15.5 要求已月結案件的更正保留完整稽核軌跡。若等業務功能做完再補,會遺漏寫入點且無法回填歷史,因此在申請功能之前先建立共用的操作紀錄。
## What Changes
- 共用、只增不改的操作紀錄:操作者、時間、對象類型與 ID、動作、變更前後狀態/重點欄位、意見、來源 IP。
- 紀錄寫入與業務寫入在同一交易內完成:業務寫入失敗則不留紀錄,紀錄寫入失敗則業務寫入回滾。
- 任何角色都不能修改或刪除操作紀錄。
- 操作紀錄查詢頁 `/admin/audit-log`(FE-10):依時間區間、操作者、對象類型、動作、對象 ID 篩選,查看單筆詳情(前後差異)。
- 存取限制:系統管理員,以及經系統管理員授權的管理者。
- 補接 `add-identity-and-access` 已有的寫入點(登入成功/失敗、帳號、角色、部門、主管指派、CSV 匯入、密碼重設)。
## Capabilities
### New Capabilities
- `audit-trail`: 系統操作紀錄的記錄規則、不可竄改性、查詢與存取權限。
### Modified Capabilities
<!-- 無(identity-access/org-directory 尚未 archive;本 change 只補接其寫入點的留痕,不改變其 requirement) -->
## Impact
- 新增資料表 audit_logs,以及「可檢視操作紀錄」授權欄位。
- 新增頁面 `/admin/audit-log`。
- 後續所有寫入操作的 change(申請、審核、月結、發放、制度參數)都必須在同一交易內呼叫留痕。
@@ -0,0 +1,62 @@
# Spec Delta
## Purpose
記錄系統中所有重要的狀態變更與管理操作(誰、何時、對什麼、做了什麼、前後差異),且紀錄不可竄改,供稽核、爭議查證與月結更正追溯使用(規格 §15.5、§17)。
## ADDED Requirements
### Requirement: 記錄重要操作
系統 SHALL 對每一次重要操作寫入一筆操作紀錄,內容 MUST 包含:操作者、操作時間、對象類型、對象識別碼、動作、變更前與變更後的狀態或重點欄位、意見(若有)、來源 IP。重要操作至少包含規格 §17 所列的申請、審核、月結、核定、發放動作,以及制度參數、帳號、角色、部門異動與登入事件。
#### Scenario: 主管退回補件
- **WHEN** 主管將一筆申請退回補件並填寫意見
- **THEN** 操作紀錄新增一筆,含主管身分、時間、該申請編號、動作「退回補件」、狀態由「待主管審核」變為「待補件」與意見全文
#### Scenario: 登入失敗
- **WHEN** 某帳號登入時密碼錯誤
- **THEN** 操作紀錄新增一筆「登入失敗」,含嘗試的帳號識別與來源 IP,不記錄輸入的密碼
### Requirement: 紀錄與業務變更同時成立
操作紀錄 MUST 與其對應的業務變更同時成功或同時失敗:業務變更未完成時不得留下紀錄,紀錄無法寫入時業務變更 MUST 不生效。
#### Scenario: 業務寫入失敗
- **WHEN** 核准申請時因資料衝突而失敗
- **THEN** 申請狀態不變,且操作紀錄中沒有該次核准
#### Scenario: 紀錄寫入失敗
- **WHEN** 提交月結時操作紀錄無法寫入
- **THEN** 月結維持未提交,使用者看到操作失敗訊息
### Requirement: 紀錄不可竄改
任何角色(含系統管理員)MUST 無法透過系統修改或刪除既有操作紀錄;更正業務資料時 MUST 以新增紀錄呈現,不得覆寫舊紀錄。
#### Scenario: 嘗試刪除紀錄
- **WHEN** 系統管理員嘗試刪除一筆操作紀錄
- **THEN** 系統不提供此功能,直接呼叫也被拒絕
#### Scenario: 參數修改留下前後值
- **WHEN** 管理者將一般部門每人月額度由 500 改為 600
- **THEN** 新增一筆紀錄含前值 500 與後值 600,先前紀錄維持不變
### Requirement: 操作紀錄查詢
系統 SHALL 提供操作紀錄頁,可依時間區間、操作者、對象類型、動作、對象識別碼篩選,結果依時間由新到舊排序並分頁;點選單筆可查看完整前後差異與意見。
#### Scenario: 依申請編號查詢
- **WHEN** 使用者輸入某申請編號查詢
- **THEN** 顯示該申請從建立到目前所有操作,依時間排序
#### Scenario: 查無資料
- **WHEN** 篩選條件沒有符合的紀錄
- **THEN** 顯示空狀態訊息「查無符合條件的操作紀錄」
### Requirement: 操作紀錄存取權限
只有系統管理員,以及經系統管理員授予「檢視操作紀錄」權限的管理者 SHALL 能存取操作紀錄頁;其他使用者 MUST 被拒絕。授予與撤銷此權限本身 MUST 留下操作紀錄。
#### Scenario: 一般管理者未授權
- **WHEN** 未被授權的管理者開啟 `/admin/audit-log`
- **THEN** 系統顯示無權限頁面
#### Scenario: 授權後可檢視
- **WHEN** 系統管理員授予某管理者檢視權限
- **THEN** 該管理者可開啟操作紀錄頁,且此授權動作出現在操作紀錄中
+26
View File
@@ -0,0 +1,26 @@
# Tasks
## 1. 資料模型與不可竄改
- [ ] 1.1 建立 audit_logs schema、索引與 `users.can_view_audit_log` 欄位的 migration,確認 `npm run db:migrate` 成功
- [ ] 1.2 在 migration 加入 audit_logs 的 BEFORE UPDATE/BEFORE DELETE trigger,整合測試直接執行 UPDATE 與 DELETE 都被拒絕
## 2. 寫入 API
- [ ] 2.1 建立 action/target_type 常數表(含中文標籤)與 `recordAudit(tx, entry)`(型別上只接受交易物件),單元測試型別與欄位組裝(不含密碼等敏感欄位)
- [ ] 2.2 建立測試 helper `expectAudit(action, targetId)`,整合測試驗證業務寫入失敗時無紀錄、紀錄寫入失敗時業務回滾
## 3. 補接既有寫入點
- [ ] 3.1 為登入成功、登入失敗、登出、密碼變更與重設加上留痕,整合測試各事件產生正確紀錄且不含密碼
- [ ] 3.2 為帳號新增/編輯/停用、角色指派、部門異動、主管指派、調部門、CSV 匯入加上留痕,整合測試涵蓋前後值
## 4. 檢視權限與查詢頁
- [ ] 4.1 擴充路由權限(sysadmin 或已授權 admin),並在 `/admin/accounts` 加入授予/撤銷「檢視操作紀錄」(含留痕),整合測試未授權管理者被拒、授權後可存取
- [ ] 4.2 實作 `/admin/audit-log` 列表(時間區間、操作者、對象類型、動作、對象 ID 篩選;URL query;keyset 分頁 50 筆;空狀態),整合測試篩選與分頁結果
- [ ] 4.3 實作單筆詳情抽屜(逐欄前後差異、意見),e2e 測試以申請/帳號 ID 查詢並開啟詳情
## 5. 文件
- [ ] 5.1 更新 `CLAUDE.md`:所有寫入操作必須在交易內呼叫 `recordAudit`,並說明新增 action 常數的方式,確認內容與程式一致
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-02
@@ -0,0 +1,59 @@
# Design
## Context
- 共用約定見 `plan-system-roadmap/design.md`(D3 技術選型、D4 整數金額、D6 狀態機、D8 稽核與鎖定)。
- `add-department-settlement` 已建立 `department_settlements`(狀態:未結算/已提交)與 `settlement_allocations`,並在提交時寫入參數快照與鎖定守衛。本 change 在其上擴充狀態與管理端流程。
## Goals / Non-Goals
**Goals:**
- 核定、退回、標記發放都是單一交易,月結、案件、發放紀錄狀態一致。
- 退回不覆寫歷史:每次提交保留成一個版本。
- 匯出檔欄位固定,可直接交給薪資作業。
**Non-Goals:**
- 核定後更正、發放失敗處理、已發放改回(`add-settlement-corrections`)。
- 「提醒」未提交部門的通知發送(`add-notifications`;MVP 總覽只顯示異常標示,不提供提醒按鈕)。
- 薪資系統自動串接(`integrate-payroll-export`)。
## Decisions
### 1. 月結狀態擴充
`department_settlements.status`:未結算 → 已提交 → 最終核定 → 已發放;退回時 已提交 → 未結算,並寫 `returned_at`、`returned_by`、`return_reason`(最近一次)。部門月結頁在狀態為未結算且有退回紀錄時顯示退回原因。鎖定守衛(change 9)改為「狀態 ∈ {已提交, 最終核定, 已發放} 即鎖定」。
### 2. 提交版本保留
新增 `settlement_submissions`:每次提交寫入一筆(月結 ID、版本序號、參數快照、提交者與時間、明細 JSON 或子表 `settlement_submission_allocations`)。退回只改月結狀態與寫退回紀錄,既有版本不刪不改;重新提交產生新版本。替代方案:退回時直接清空明細 → 違反規格 §15.5 與 §17。
> 與 change 9 的協調:change 9 的提交交易需改為同時寫入一筆 submission 版本。若 change 9 先實作,本 change 的 tasks 包含補上此步驟與 migration 回填既有已提交月結為版本 1。
### 3. 發放紀錄
`payout_records`:`settlement_id`、`user_id`、`department_id`、`charge_month`、`payout_month`(charge_month + 2)、`amount`、`pay_item`(固定「其他獎金」)、`status`(待發放/已發放)、`marked_by`、`marked_at`。最終核定交易內,對 `final_amount > 0` 的分配建立紀錄。唯一鍵 (`settlement_id`, `user_id`)。發放月份計算放在純函式並處理跨年。
### 4. 交易邊界
- 最終核定:`BEGIN IMMEDIATE` → 檢查狀態為已提交 → 月結改最終核定 → 案件已提交→最終核定 → 建立發放紀錄 → 操作紀錄。
- 退回:檢查已提交 → 月結改未結算並寫退回欄位 → 案件已提交→待月結 → 每筆案件時間軸事件 → 操作紀錄。
- 標記發放:檢查每筆為待發放 → 改已發放 → 對應案件最終核定→已發放 → 若該月結所有紀錄已發放則月結改已發放 → 操作紀錄。
### 5. 匯出
- Excel 用 `exceljs`(純 JS、支援數值儲存格格式,無原生相依);CSV 自行產生並加 UTF-8 BOM。
- 匯出透過 Route Handler 以串流回應下載;欄位定義集中為單一常數陣列,Excel 與 CSV 共用,避免兩者欄位漂移。
- 替代方案 `xlsx`(SheetJS)→ npm 套件版本授權與更新來源較混亂,不採用。
### 6. 頁面
- `/admin/settlements`:Server Component 彙總查詢(部門 LEFT JOIN 月結),統計卡與表格;異常判斷(逾期未提交、逾期提交、缺人數快照)在伺服器端計算。
- `/admin/settlements/[departmentId]/[month]`:詳情、版本歷史、附件預覽(沿用 `FilePreview`)、審核時間軸(`ReviewTimeline`);核定與退回為 Server Actions,配 `ConfirmDialog`。
- `/admin/payments`:發放月份選擇、狀態篩選、勾選批次標記;Mobile 轉卡片清單。
## Risks / Trade-offs
- [管理者誤核定] → 確認視窗顯示部門、月份、人數與金額;核定後無法於 MVP 撤銷,需靠 change 14 更正流程。
- [退回後部長未重新提交,錯過發放] → 總覽持續顯示該部門為待提交並標示逾期。
- [匯出欄位日後要配合薪資系統調整] → 欄位集中定義,調整時只改一處並以新 change 更新 spec。
- [change 9 與本 change 對 `department_settlements` 的修改交錯] → 本 change 的 migration 只新增欄位與表,不改既有欄位語意。
@@ -0,0 +1,29 @@
# Proposal
## Why
部長提交月結後,名單要交給管理者(鳳怡/人資財務)彙整全公司、做最終核定,並在指定薪資月份以「其他獎金」發放(規格 §5 步驟 9–11、§6、§11)。目前規劃中沒有任何地方讓管理端看到各部門提交狀況、核定、退回或追蹤發放,MVP 驗收條件第 9 項(管理端可查看全公司名單並標記最終核定及已發放)因此無法達成。
## What Changes
- 新增全公司月結總覽 `/admin/settlements`(FE-07):統計卡(已提交/待提交部門數、總核定金額、待發放人數)、各部門列(人數、月上限、最終補助、狀態、提交時間、逾期標示、異常提醒)。
- 新增部門月結詳情:檢視部長提交的名單、參數快照、案件附件與審核紀錄;管理者可「最終核定」或「退回月結」(皆需確認視窗;退回必填原因)。
- 退回月結:月結回到可編輯、案件回到「待月結」,保留原提交版本與退回紀錄,不覆寫歷史(MVP 唯一的更正方式;完整更正流程屬 `add-settlement-corrections`)。
- 新增發放管理 `/admin/payments`(FE-08):依發放月份(刷卡月份 + 2 個月的薪資)彙整姓名、部門、補助金額、薪資名目「其他獎金」、發放狀態;Excel/CSV 匯出(固定欄位);批次標記已發放(確認視窗)。
- 擴充案件狀態機:已提交 → 最終核定 → 已發放;退回月結時 已提交 → 待月結。
## Capabilities
### New Capabilities
- `company-settlement`: 管理端彙整全公司各部門月結、檢視提交名單、最終核定與退回月結。
- `payout-management`: 依發放月份彙整核定名單、匯出薪資作業檔、追蹤並標記發放狀態。
### Modified Capabilities
- `application-lifecycle`(由 `add-subsidy-application` 建立、尚未 archive,故以 ADDED requirement 擴充):新增最終核定、已發放與退回月結的批次轉移。
## Impact
- 依賴:`add-department-settlement`(部門月結與分配明細)、`add-identity-and-access`(管理者角色)、`add-audit-trail`、`add-application-attachments`(附件檢視)、`add-manager-review`(審核紀錄)、`add-app-shell`。
- 資料:擴充部門月結狀態(最終核定、已發放、已退回)與核定者/時間;新增月結提交版本紀錄與退回紀錄;新增發放紀錄(發放月份、金額、狀態、標記者與時間)。
- 新增依賴套件:Excel 檔產生函式庫(於 design 決定)。
- 下游:`add-role-dashboards` 讀取核定與發放統計;`add-settlement-corrections` 擴充更正流程;`integrate-payroll-export` 取代人工匯出。
@@ -0,0 +1,31 @@
# Spec Delta
## ADDED Requirements
### Requirement: 最終核定時案件轉為最終核定
管理者最終核定某部門月結時,系統 SHALL 在同一交易內把該月結所含所有「已提交」案件轉為「最終核定」,案件詳情顯示最終補助金額與預計發放月份。
#### Scenario: 核定後案件狀態
- **WHEN** 管理者核定設計部 2026/10 月結
- **THEN** 該月結所有案件變為最終核定,員工在案件詳情看到最終補助金額與預計發放月份 2026/12
### Requirement: 發放後案件轉為已發放
某申請人的發放紀錄被標記已發放時,系統 SHALL 把該申請人在該部門月結中的所有「最終核定」案件轉為「已發放」,案件詳情顯示發放月份與名目「其他獎金」。
#### Scenario: 標記發放後
- **WHEN** 管理者把王小明 2026/12 的發放紀錄標記已發放
- **THEN** 王小明 2026/10 的最終核定案件變為已發放,詳情顯示「2026/12 其他獎金」
### Requirement: 退回月結時案件回到待月結
管理者退回某部門月結時,系統 SHALL 把該月結所有「已提交」案件轉回「待月結」,清除尚未核定的最終補助顯示(改回「預估」),並在每筆案件時間軸記錄退回事件與原因。
#### Scenario: 退回後案件狀態
- **WHEN** 管理者退回設計部 2026/10 月結
- **THEN** 該月結所有案件回到待月結,案件詳情不再顯示「最終」金額,時間軸出現退回紀錄
### Requirement: 最終核定與已發放案件唯讀
狀態為「最終核定」或「已發放」的案件 MUST NOT 被任何角色以一般操作修改。
#### Scenario: 嘗試修改已核定案件
- **WHEN** 任何使用者嘗試修改最終核定案件的金額或狀態(標記發放除外)
- **THEN** 系統拒絕該操作
@@ -0,0 +1,77 @@
# Spec Delta
## Purpose
讓管理者(鳳怡/人資財務窗口)彙整全公司各部門某月份的月結狀態,檢視部長提交的名單與佐證,並進行最終核定或退回月結,同時保留完整的核定與退回軌跡(規格 §4、§11、§15.5,介面規劃 §7)。
## ADDED Requirements
### Requirement: 全公司月結存取權限
系統 SHALL 只允許具管理者角色的使用者存取全公司月結總覽、部門月結詳情、最終核定與退回月結;部門主管與一般員工 MUST NOT 存取。
#### Scenario: 管理者存取
- **WHEN** 具管理者角色的使用者開啟 `/admin/settlements`
- **THEN** 系統顯示全公司月結總覽
#### Scenario: 主管被拒
- **WHEN** 部門主管嘗試開啟 `/admin/settlements` 或呼叫最終核定
- **THEN** 系統拒絕並回應無權限
### Requirement: 全公司月結總覽
總覽頁 SHALL 依所選月份(預設最近一個尚有部門未完成核定的月份)顯示統計卡:已提交部門數/部門總數、待提交部門數、總核定金額、待發放人數;並以表格列出每個部門的計算人數、月上限、最終補助合計、月結狀態、提交時間與可用操作。
#### Scenario: 顯示統計與部門列
- **WHEN** 2026/10 有 9 個部門,7 個已提交、2 個待提交
- **THEN** 統計卡顯示「已提交 7/9 部門」「待提交 2」,表格列出 9 個部門,待提交部門的最終補助與提交時間顯示「--」
#### Scenario: 切換月份
- **WHEN** 管理者切換到 2026/09
- **THEN** 統計卡與表格改為 9 月資料
### Requirement: 異常提醒
總覽頁 SHALL 標示需要管理者注意的部門:逾期提交(次月 25 日後提交)、已過部長提交截止仍未提交、缺少該月計算人數快照。
#### Scenario: 截止後未提交
- **WHEN** 今天是 2026/11/26,行銷部 10 月月結仍未提交
- **THEN** 行銷部列顯示「逾期未提交」提醒
#### Scenario: 逾期提交
- **WHEN** 研發部 10 月月結於 2026/11/26 提交
- **THEN** 研發部列顯示「逾期提交」標示
### Requirement: 部門月結詳情檢視
管理者 SHALL 能開啟任一部門某月的月結詳情,檢視部長提交的分配明細、提交當時的參數快照(補助比例、取整方式、每人額度、計算人數、月上限)、提交者與時間,以及每筆案件的申請資料、附件與審核紀錄。管理者 MUST NOT 修改案件內容或分配金額。
#### Scenario: 檢視提交名單
- **WHEN** 管理者開啟設計部 2026/10 已提交月結
- **THEN** 頁面顯示提交時的分配明細與參數快照,以及每筆案件的附件與審核時間軸
#### Scenario: 未提交部門
- **WHEN** 管理者開啟尚未提交的行銷部 2026/10 月結
- **THEN** 頁面以唯讀顯示目前試算,並標示「部長尚未提交」,不提供核定與退回
### Requirement: 最終核定
管理者 SHALL 能對「已提交」的部門月結執行最終核定。系統 MUST 先顯示確認視窗;確認後記錄核定者與時間,月結狀態變為「最終核定」,並為名單中每位申請人建立待發放紀錄(發放月份為刷卡月份後第 2 個月)。已核定的月結 MUST NOT 再被修改。
#### Scenario: 核定成功
- **WHEN** 管理者確認核定設計部 2026/10 月結
- **THEN** 月結狀態變為最終核定,名單中每位申請人產生發放月份 2026/12、狀態「待發放」的發放紀錄
#### Scenario: 未提交不可核定
- **WHEN** 管理者嘗試核定尚未提交的月結
- **THEN** 系統拒絕並說明需待部長提交
### Requirement: 退回月結
管理者 SHALL 能對「已提交」的部門月結執行退回,退回原因為必填且須經確認視窗。退回後月結回到可編輯狀態、部長可重新計算與提交;原提交版本(明細與參數快照)與退回紀錄(退回者、時間、原因)MUST 保留,MUST NOT 被覆寫。已最終核定的月結在 MVP 中 MUST NOT 退回。
#### Scenario: 退回成功
- **WHEN** 管理者輸入原因「人數快照有誤,請重新確認」並確認退回設計部 2026/10 月結
- **THEN** 月結回到可編輯,部長可在部門月結頁看到退回原因,原提交版本仍可在詳情的歷史紀錄中檢視
#### Scenario: 未填原因
- **WHEN** 管理者未填退回原因就送出退回
- **THEN** 系統阻擋並提示需填寫原因
#### Scenario: 已核定不可退回
- **WHEN** 管理者嘗試退回已最終核定的月結
- **THEN** 系統拒絕並說明 MVP 不支援核定後更正
@@ -0,0 +1,62 @@
# Spec Delta
## Purpose
依發放月份彙整已最終核定的補助名單,提供與薪資作業對應的固定欄位匯出,並追蹤每位申請人「其他獎金」的發放狀態(規格 §2、§5 步驟 10–11、§6,介面規劃 §7)。
## ADDED Requirements
### Requirement: 發放管理存取權限
系統 SHALL 只允許具管理者角色的使用者存取 `/admin/payments`、匯出發放名單與標記已發放。
#### Scenario: 非管理者被拒
- **WHEN** 部門主管嘗試開啟 `/admin/payments`
- **THEN** 系統拒絕並回應無權限
### Requirement: 發放月份規則
發放紀錄的發放月份 SHALL 為刷卡月份後第 2 個月(例:10 月刷卡、11 月申請與月結、12 月發放 11 月薪資時一併發放),薪資名目固定為「其他獎金」。
#### Scenario: 10 月刷卡
- **WHEN** 2026/10 的部門月結被最終核定
- **THEN** 其發放紀錄的發放月份為 2026/12,名目為「其他獎金」
#### Scenario: 跨年
- **WHEN** 2026/11 的部門月結被最終核定
- **THEN** 其發放紀錄的發放月份為 2027/01
### Requirement: 發放名單彙整
發放管理頁 SHALL 依所選發放月份列出姓名、員工編號、部門、刷卡月份、補助金額、薪資名目與發放狀態(待發放/已發放),並顯示該發放月份的人數與金額合計。只列出最終補助大於 0 的申請人。
#### Scenario: 檢視 2026/12 發放名單
- **WHEN** 管理者選擇發放月份 2026/12
- **THEN** 頁面列出所有 2026/10 已核定部門的申請人與金額,合計列顯示人數與總金額
#### Scenario: 篩選狀態
- **WHEN** 管理者篩選「待發放」
- **THEN** 只顯示尚未標記已發放的紀錄
### Requirement: 匯出發放名單
管理者 SHALL 能把所選發放月份的名單匯出為 Excel(.xlsx)或 CSV。欄位與順序 MUST 固定為:發放月份、員工編號、姓名、部門、刷卡月份、補助金額、薪資名目、發放狀態。金額 MUST 為整數元數值(不含 NT$ 與千分位符號),以便薪資作業直接使用。匯出動作 MUST 記錄於操作紀錄。
#### Scenario: 匯出 Excel
- **WHEN** 管理者匯出 2026/12 發放名單為 Excel
- **THEN** 下載的 .xlsx 欄位依固定順序,補助金額為數值格式
#### Scenario: 匯出 CSV
- **WHEN** 管理者匯出 2026/12 發放名單為 CSV
- **THEN** 下載的 CSV 以 Excel 開啟時中文不亂碼,欄位與 Excel 版相同
### Requirement: 標記已發放
管理者 SHALL 能選取一筆或多筆「待發放」紀錄標記為「已發放」,系統 MUST 先顯示確認視窗(含筆數與金額合計)。確認後記錄標記者與時間;某部門月結的所有發放紀錄皆已發放時,該月結狀態變為「已發放」。已發放紀錄在 MVP 中 MUST NOT 改回待發放。
#### Scenario: 批次標記
- **WHEN** 管理者勾選 46 筆待發放紀錄並確認標記
- **THEN** 這 46 筆變為已發放,記錄標記者與時間
#### Scenario: 部門全數發放
- **WHEN** 設計部 2026/10 月結的最後一筆發放紀錄被標記已發放
- **THEN** 設計部 2026/10 月結狀態變為已發放
#### Scenario: 不可取消已發放
- **WHEN** 管理者嘗試把已發放紀錄改回待發放
- **THEN** 系統拒絕並說明需透過更正流程處理
@@ -0,0 +1,29 @@
# Tasks
## 1. 資料模型
- [ ] 1.1 新增 migration:`department_settlements` 擴充狀態與退回欄位、新增 `settlement_submissions`(含明細)與 `payout_records`(唯一鍵),並驗證 migration 在含已提交月結的資料庫上成功且既有月結回填為版本 1
- [ ] 1.2 修改部門月結提交交易,提交時寫入 submission 版本,並以整合測試驗證連續兩次提交(中間退回)產生版本 1、2 且版本 1 不變
- [ ] 1.3 將鎖定守衛擴充為已提交/最終核定/已發放皆鎖定,並以整合測試驗證三種狀態下案件修改被拒
## 2. 全公司月結與核定
- [ ] 2.1 實作發放月份純函式(刷卡月份 + 2、跨年),並以 Vitest 驗證 2026-10→2026-12、2026-11→2027-01
- [ ] 2.2 實作管理者權限守衛套用於全公司月結與發放的頁面與動作,並以 API 測試驗證主管與員工被拒
- [ ] 2.3 實作總覽查詢(統計卡、部門列、異常判斷),並以整合測試驗證「已提交 7/9」、逾期未提交、逾期提交、缺人數快照的標示
- [ ] 2.4 實作最終核定交易(月結、案件、發放紀錄、操作紀錄),並以整合測試驗證成功、未提交被拒、金額 0 不建發放紀錄、失敗全 rollback
- [ ] 2.5 實作退回月結交易(必填原因、案件回待月結、時間軸、版本保留、已核定不可退回),並以整合測試驗證各 scenario
## 3. 發放管理
- [ ] 3.1 實作發放名單查詢(依發放月份、狀態篩選、合計),並以整合測試驗證 2026/12 名單與合計
- [ ] 3.2 實作 Excel(exceljs)與 CSV(UTF-8 BOM)匯出共用欄位定義,並以測試解析匯出檔驗證欄位順序與金額為數值、匯出寫入操作紀錄
- [ ] 3.3 實作批次標記已發放交易(案件轉已發放、月結全數發放時轉已發放、不可改回),並以整合測試驗證各 scenario
## 4. 管理端頁面
- [ ] 4.1 建立 `/admin/settlements` 總覽頁(月份切換、統計卡、部門表、異常標示、Mobile 卡片),並以 Playwright 驗證顯示內容
- [ ] 4.2 建立部門月結詳情頁(明細、參數快照、版本歷史、附件預覽、審核時間軸、核定與退回確認視窗),並以 Playwright 驗證核定與退回流程端到端
- [ ] 4.3 在部門月結頁顯示退回原因並允許重新計算與再提交,並以 Playwright 驗證退回後部長可再提交
- [ ] 4.4 建立 `/admin/payments` 頁(發放月份、篩選、勾選批次標記確認視窗含筆數與金額、匯出按鈕),並以 Playwright 驗證標記與下載
- [ ] 4.5 在管理端操作說明中記錄核定、退回、匯出欄位與發放月份規則,並確認與 spec 一致
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-02
@@ -0,0 +1,58 @@
# Design
## Context
- 技術選型與共用約定見 `plan-system-roadmap/design.md`(D3 Next.js + SQLite + Drizzle、D4 整數金額、D5 最大餘數法、D6 狀態機、D7 時區、D8 鎖定)。本 change 是 D5 演算法的落地處。
- 前置 change 提供:部門與部門類型、主管範圍(`add-identity-and-access`)、補助比例/取整方式/每人額度/截止日與人數快照(`add-rule-settings`)、操作紀錄(`add-audit-trail`)、審核通過案件(`add-subsidy-application`、`add-manager-review`)、共用元件(`add-app-shell`)。
## Goals / Non-Goals
**Goals:**
- 計算規則集中在無 I/O 的純函式,所有 scenario 都能以單元測試驗證。
- 提交是單一交易:月結結果、分配明細、案件狀態要嘛全成功、要嘛全不變。
- 提交後的鎖定由伺服器端強制,不依賴 UI 隱藏按鈕。
**Non-Goals:**
- 管理端最終核定、退回月結、發放與正式匯出(`add-company-settlement-and-payout`)。
- 截止前後的通知提醒(`add-notifications`)。
## Decisions
### 1. 計算模組 `lib/domain/settlement/` 為純函式
輸入:申請人清單(申請人 ID、穩定排序鍵、當月審核通過台幣金額陣列)、補助比例(以整數百分比或基點表示,避免浮點)、取整方式、每人額度、計算人數。輸出:每人支付合計、個人可補助、占比、應得、最終補助、尾差調整、上限、總額、是否超額。
- 比例運算用整數:`personal = floor_or_round(sum × ratioBp / 10000)`;超額分配的分子 `personal × cap` 與分母 `total` 都是整數,以整數除法取商與餘數,餘數比較取代小數比較,完全避免浮點誤差。
- 尾差:`remaining = cap − Σ商`,依「餘數由大到小、同餘數依穩定排序鍵(使用者 ID)由小到大」逐一 +1。
- 替代方案:用浮點計算再四捨五入 → 會出現合計 999 或 1,001,不可接受。
### 2. 資料模型(Drizzle / SQLite)
- `department_settlements`:`department_id`、`month`(`YYYY-MM`)、`status`(未結算/已提交;後續 change 擴充最終核定、已發放、已退回)、`ratio_bp`、`rounding_mode`、`quota_per_person`、`headcount`、`cap`、`total_eligible`、`is_over_cap`、`calculated_at`、`submitted_by`、`submitted_at`、`is_late`。唯一鍵 (`department_id`, `month`)。
- `settlement_allocations`:`settlement_id`、`user_id`、`paid_total`、`personal_eligible`、`share_bp`(萬分比,顯示為小數兩位百分比)、`final_amount`、`remainder_adjustment`(0 或 1)。
- 未提交月結的試算結果也寫入上述表(狀態「未結算」),讓「重新計算」只是覆寫試算;提交時改為已提交並不再覆寫。
### 3. 「審核通過 → 待月結」的觸發
截止時刻是時間條件,沒有使用者動作。採「冪等推進函式+兩個觸發點」:
- 進入部門月結頁/API、主管核准案件時,先對相關月份呼叫 `promoteApprovedToPendingSettlement(month)`(只推進截止已過的月份,重複呼叫無副作用)。
- 單一實例部署(D3),在 Next.js `instrumentation.ts` 啟動一個每小時執行的計時器,推進所有已過截止的月份,確保沒人開頁面時狀態也會正確。
- 替代方案:外部 cron → 需額外部署元件;查詢時即時推導狀態不落地 → 狀態查詢與時間軸紀錄會不一致。
### 4. 提交交易與鎖定
- 提交在 `BEGIN IMMEDIATE` 交易內依序:重新讀取案件並檢查無「待主管審核/待補件」→ 以純函式重算 → 寫入月結與明細快照 → 案件「待月結 → 已提交」並寫入最終金額 → 寫操作紀錄。任何一步失敗即 rollback。
- 鎖定:所有會修改案件或月結的伺服器動作(編輯、撤回、審核、重算)共用一個守衛函式,檢查案件所屬部門月結是否為已提交(或更後狀態),是則拒絕。另加 SQLite trigger 阻擋已提交月結的明細被 UPDATE/DELETE,作為最後防線。
### 5. 頁面 `/department/settlement`
- Server Component 讀取資料;「重新計算」「匯出預覽」「確認並提交」為 Server Actions。確認視窗用 `ConfirmDialog`,額度卡用 `QuotaCard`,金額用 `MoneyDisplay`。
- 匯出預覽產生 UTF-8 BOM 的 CSV(Excel 開啟中文不亂碼)。正式 Excel 匯出在 change 10。
- Mobile:分配明細轉卡片清單,主要按鈕放底部 sticky action bar(介面規劃 §10)。
## Risks / Trade-offs
- [截止後仍有員工補件重送,使案件回到待主管審核] → 提交前檢查會阻擋,主管需先處理;補件重送是否受申請截止限制由 `add-subsidy-application` 定義。
- [計時器在程序重啟時中斷] → 啟動時立即執行一次推進,且頁面觸發點可補上。
- [部門類型或人數快照在月中被修改] → 試算一律讀取當下快照;提交時才凍結,提交前畫面顯示資料計算時間。
- [逾期提交(25 日後)規格未定義後果] → 只標示逾期、不阻擋,讓管理端判斷;若公司要阻擋,可改為後台參數。
@@ -0,0 +1,28 @@
# Proposal
## Why
主管審核只判斷工作用途,實際補助金額要等每月申請截止後,把部門所有審核通過案件一起和部門月上限比較才能確定(規格 §5 步驟 7–9、§7、§11)。沒有月結計算與部門月結頁,就無法滿足 MVP 驗收條件第 3、4、6、7、8、10 項,也無法把名單交給管理端核定與發放(change 10)。
## What Changes
- 新增月結計算規則:個人可補助金額(同月合格台幣金額加總 × 補助比例,依後台取整方式取整,預設無條件捨去)、部門月上限(人數快照 × 部門類型每人額度)、未超額照發、超額依占比分配並以最大餘數法補足尾差,合計恰等於且絕不超過月上限。
- 月結時把補助比例、取整方式、每人額度、計算人數「快照」進月結結果,後續參數變更不影響該月。
- 新增部門月結頁 `/department/settlement`(FE-06):月份切換、部門額度卡、超額提示、分配明細(含占比)、尾差說明、提交前檢查、重新計算、匯出預覽、確認並提交(確認視窗)、提交後鎖定。
- 擴充案件狀態機:申請截止後該月「審核通過」案件批次進入「待月結」;部長提交後批次轉為「已提交」並鎖定。
- 每月額度獨立計算,未使用額度不帶入次月。
## Capabilities
### New Capabilities
- `settlement-calculation`: 個人可補助金額、部門月上限、超額比例分配與尾差補差的計算規則及參數快照。
- `department-settlement`: 以「部門+月份」為單位的月結工作流程:試算、提交前檢查、提交、鎖定與部門月結頁。
### Modified Capabilities
- `application-lifecycle`(由 `add-subsidy-application` 建立、尚未 archive,故以 ADDED requirement 擴充):新增「審核通過 → 待月結 → 已提交」的批次轉移與提交後鎖定。
## Impact
- 依賴:`add-identity-and-access`(部門、部門類型、主管範圍)、`add-audit-trail`(提交與重算留痕)、`add-rule-settings`(補助比例、取整方式、每人額度、截止日、人數快照)、`add-app-shell`(QuotaCard、MoneyDisplay、ConfirmDialog 等)、`add-subsidy-application` 與 `add-manager-review`(審核通過案件)。
- 新增資料:部門月結(部門、月份、狀態、參數快照、上限、總額、是否超額、提交者與時間)、月結分配明細(每位申請人的支付總額、個人可補助、占比、最終補助、尾差調整)。
- 下游:`add-company-settlement-and-payout` 讀取已提交月結;`add-role-dashboards` 讀取月結進度與截止日。
@@ -0,0 +1,43 @@
# Spec Delta
## ADDED Requirements
### Requirement: 審核通過案件進入待月結
當某月份的員工申請截止(刷卡月份次月 20 日 23:59:59,Asia/Taipei)過後,系統 SHALL 把該月份所有「審核通過」案件批次轉為「待月結」,並記錄於案件時間軸與操作紀錄。截止前核准的案件維持「審核通過」;截止後才核准的案件 SHALL 直接進入「待月結」。
#### Scenario: 申請截止後批次轉入
- **WHEN** 2026/11/20 23:59:59 過後,設計部 10 月有 5 筆審核通過案件
- **THEN** 這 5 筆案件狀態變為待月結,時間軸記錄轉入時間
#### Scenario: 截止後核准
- **WHEN** 2026/11/21 主管核准一筆 10 月案件
- **THEN** 該案件核准後直接為待月結
### Requirement: 申請截止後逾期待補件案件可不核准
某月份員工申請截止後,該月仍為「待補件」的案件因無法再重送,系統 SHALL 允許該案件的審核者將其轉為「不核准」,原因為必填(預設帶入「逾期未完成補件」可修改),使部門月結得以提交。申請截止前 MUST NOT 允許此轉移。
#### Scenario: 截止後不核准待補件案件
- **WHEN** 2026/11/21 設計部主管對一筆 10 月待補件案件執行不核准並保留預設原因
- **THEN** 案件變為不核准,時間軸記錄「逾期未完成補件」,該案件不再阻擋 10 月月結提交
#### Scenario: 截止前不可不核准待補件
- **WHEN** 2026/11/15 主管嘗試對 10 月待補件案件執行不核准
- **THEN** 系統拒絕,案件仍為待補件
### Requirement: 月結提交時案件轉為已提交
部門月結提交成功時,系統 SHALL 在同一交易內把該部門該月所有「待月結」案件批次轉為「已提交」,並寫入各案件的最終補助金額(顯示為「最終」);交易失敗時 MUST 全部不變。
#### Scenario: 提交後狀態轉換
- **WHEN** 設計部主管提交 10 月月結
- **THEN** 該月所有待月結案件同時變為已提交,案件詳情顯示最終補助金額
#### Scenario: 提交失敗不留部分結果
- **WHEN** 提交過程中發生錯誤
- **THEN** 月結與所有案件狀態皆維持提交前的樣子
### Requirement: 已提交案件的唯讀限制
狀態為「已提交」的案件 MUST NOT 被員工編輯、撤回,也 MUST NOT 被主管變更審核結果。
#### Scenario: 員工嘗試撤回已提交案件
- **WHEN** 員工對已提交案件執行撤回
- **THEN** 系統拒絕,案件詳情只提供檢視
@@ -0,0 +1,103 @@
# Spec Delta
## Purpose
定義部門主管以「部門+月份」為單位檢視月結試算、確認無待處理案件後提交名單並鎖定的流程,以及部門月結頁應呈現的資訊與操作(規格 §11、介面規劃 §6)。
## ADDED Requirements
### Requirement: 部門月結的存取範圍
系統 SHALL 只允許部門主管/部長檢視與操作自己所屬部門的月結;一般員工 MUST NOT 存取部門月結頁。管理者可唯讀檢視各部門月結(核定與退回屬 `company-settlement`)。
#### Scenario: 主管存取本部門
- **WHEN** 設計部主管開啟 `/department/settlement`
- **THEN** 只看到設計部的月結資料
#### Scenario: 存取其他部門被拒
- **WHEN** 設計部主管嘗試以網址或 API 取得研發部月結
- **THEN** 系統拒絕並回應無權限
#### Scenario: 員工無法進入
- **WHEN** 一般員工嘗試開啟 `/department/settlement`
- **THEN** 系統拒絕存取,且導覽列不顯示「部門月結」
### Requirement: 月份切換與預設月份
部門月結頁 SHALL 預設顯示最早一個尚未提交的月結月份;若沒有未提交月份,則顯示最近一個月份。主管 SHALL 能切換到歷史月份檢視。
#### Scenario: 預設待結算月份
- **WHEN** 今天是 2026/11/22,設計部 10 月月結尚未提交
- **THEN** 頁面預設顯示 2026/10 的月結
#### Scenario: 切換歷史月份
- **WHEN** 主管切換到 2026/08
- **THEN** 頁面顯示 8 月月結結果(若已提交則為唯讀)
### Requirement: 部門額度與超額提示
部門月結頁 SHALL 顯示部門計算人數、每人額度、月上限、可補助總額與超額差額;未超額時提示「依原個人可補助金額發放」,超額時提示「將依每人可補助金額占比進行比例分配」。
#### Scenario: 超額提示
- **WHEN** 設計部 10 月計算人數 20 人、月上限 NT$10,000、可補助總額 NT$13,000
- **THEN** 額度卡顯示超額 NT$3,000,並顯示比例分配提示
#### Scenario: 未超額提示
- **WHEN** 部門可補助總額未超過月上限
- **THEN** 額度卡顯示超額 NT$0,並提示依原個人可補助金額發放
### Requirement: 分配明細與尾差說明
部門月結頁 SHALL 列出每位申請人的姓名、平台、支付金額合計、個人可補助、占比(小數兩位百分比)與最終補助,並顯示合計列。若最終補助包含尾差補差,頁面 SHALL 說明補差規則並標示被調整的申請人。
#### Scenario: 顯示分配明細
- **WHEN** 超額月結包含 A(支付 899、可補助 450)與 B(支付 1,700、可補助 850)
- **THEN** 明細列出 A 占比 34.62%、最終 NT$346,B 占比 65.38%、最終 NT$654,合計可補助 NT$1,300、最終 NT$1,000
#### Scenario: 尾差標示
- **WHEN** 分配時有申請人因尾差補差加 1 元
- **THEN** 該列標示「含尾差調整 +1」,頁面說明依小數餘額由大至小分配剩餘元數
### Requirement: 重新計算與匯出預覽
在月結提交前,主管 SHALL 能按「重新計算」以目前的審核通過案件與後台參數更新試算結果,並能匯出目前分配明細為 CSV 預覽檔。重新計算與匯出 MUST 記錄於操作紀錄。
#### Scenario: 審核結果變動後重算
- **WHEN** 主管於提交前又核准一筆該月案件,接著按「重新計算」
- **THEN** 分配明細納入新案件並更新合計與超額判斷
#### Scenario: 匯出預覽
- **WHEN** 主管按「匯出預覽」
- **THEN** 下載包含姓名、平台、支付金額、個人可補助、占比、最終補助的 CSV,金額格式與頁面一致
### Requirement: 提交前檢查
系統 SHALL 只在該月員工申請截止(刷卡月份次月 20 日 23:59:59,Asia/Taipei)之後允許提交月結。提交前系統 MUST 檢查該部門該月是否仍有「待主管審核」或「待補件」案件,若有則阻擋提交並列出這些案件與件數。
#### Scenario: 仍有待處理案件
- **WHEN** 設計部 10 月仍有 2 筆待主管審核、1 筆待補件,主管按「確認並提交」
- **THEN** 系統阻擋提交,顯示「尚有 2 筆待審核、1 筆待補件案件,完成處理後才能提交月結」並列出案件連結;待補件案件旁提供「逾期不核准」操作
#### Scenario: 申請截止前不可提交
- **WHEN** 今天是 2026/11/15,主管嘗試提交 10 月月結
- **THEN** 系統阻擋提交並說明需待 2026/11/20 申請截止後才能提交,但仍可檢視試算
### Requirement: 確認並提交月結
通過提交前檢查後,系統 SHALL 先顯示確認視窗(「提交後本月份名單將鎖定,如需更正須由管理者退回。確定提交?」),主管確認後以當下最新試算結果與參數快照提交月結,記錄提交者與時間,月結狀態變為「已提交」。部長提交截止為刷卡月份次月 25 日;逾期提交 SHALL 仍允許,但月結須標示為逾期提交。
#### Scenario: 提交成功
- **WHEN** 2026/11/23 設計部主管確認提交 10 月月結
- **THEN** 月結狀態變為已提交,記錄提交者、時間與參數快照,頁面改為唯讀並顯示提交資訊
#### Scenario: 取消提交
- **WHEN** 主管在確認視窗按取消
- **THEN** 月結維持未提交,資料不變
#### Scenario: 逾期提交
- **WHEN** 2026/11/26 主管提交 10 月月結
- **THEN** 提交成功,月結標示「逾期提交」供管理端識別
### Requirement: 提交後鎖定
月結提交後,該部門該月的月結結果與所含案件 MUST NOT 再被主管或員工修改、重新計算或變更審核結果;只能由管理者退回月結後才能再次編輯(規格 §15.5)。
#### Scenario: 提交後重算被拒
- **WHEN** 已提交月結的主管嘗試重新計算
- **THEN** 系統拒絕並說明需由管理者退回月結
#### Scenario: 提交後修改案件被拒
- **WHEN** 有人嘗試修改已提交月結中的案件金額或審核結果
- **THEN** 系統拒絕該操作,資料不變
@@ -0,0 +1,93 @@
# Spec Delta
## Purpose
定義 AI 補助月結的計算規則:個人可補助金額、部門月上限、未超額與超額時的最終補助分配,以及尾差補差與參數快照,確保結果可重現且合計絕不超過部門月上限。
## ADDED Requirements
### Requirement: 個人可補助金額計算
系統 SHALL 以「申請人+部門+月份」為單位,把該月所有「審核通過」案件的實際台幣金額加總後乘以補助比例,再依後台設定的取整方式取整為新台幣整數元,作為個人可補助金額(規格 §7.1)。取整方式預設為無條件捨去,可設定為四捨五入。原幣金額 MUST NOT 參與計算。系統 MUST NOT 套用個人月上限。
#### Scenario: 無條件捨去(預設)
- **WHEN** 申請人 A 當月審核通過案件台幣金額為 899,補助比例 50%,取整方式為無條件捨去
- **THEN** A 的個人可補助金額為 NT$449
#### Scenario: 四捨五入
- **WHEN** 申請人 A 當月審核通過案件台幣金額為 899,補助比例 50%,取整方式為四捨五入
- **THEN** A 的個人可補助金額為 NT$450
#### Scenario: 同月多筆先加總再計算
- **WHEN** 申請人當月有兩筆審核通過案件,台幣金額分別為 899 與 655,補助比例 50%,取整方式為無條件捨去
- **THEN** 個人可補助金額為 floor((899 + 655) × 50%) = NT$777,而非逐筆取整後相加
#### Scenario: 未通過案件不計入
- **WHEN** 申請人當月另有「不核准」、「草稿」或「待補件」案件
- **THEN** 這些案件的金額不計入個人可補助金額
### Requirement: 部門月上限計算
系統 SHALL 以該部門該月的計算人數快照乘以部門類型對應的每人月額度,得到部門月上限(規格 §7.2)。每人月額度預設一般部門 NT$500、研發部 NT$1,000,由後台設定。每月上限獨立計算,當月未使用額度 MUST NOT 帶入其他月份。
#### Scenario: 一般部門
- **WHEN** 一般部門 10 月計算人數快照為 20 人,每人額度 NT$500
- **THEN** 該部門 10 月月上限為 NT$10,000
#### Scenario: 研發部
- **WHEN** 研發部 10 月計算人數快照為 2 人,每人額度 NT$1,000
- **THEN** 該部門 10 月月上限為 NT$2,000
#### Scenario: 未使用額度不累計
- **WHEN** 某部門 9 月月上限 NT$10,000,最終補助合計僅 NT$6,000
- **THEN** 10 月月上限仍只依 10 月人數快照計算,不加入 9 月剩餘的 NT$4,000
#### Scenario: 缺少人數快照
- **WHEN** 計算某部門某月月結時,該部門該月沒有計算人數快照
- **THEN** 系統拒絕產生月結結果並提示需先由管理端建立人數快照
### Requirement: 未超額時依個人可補助金額發放
當部門所有申請人個人可補助金額總和小於或等於部門月上限時,系統 SHALL 使每位申請人的最終補助等於其個人可補助金額(規格 §7.3)。
#### Scenario: 研發部未超額(規格 §8.2)
- **WHEN** 研發部 2 人、月上限 NT$2,000,A 個人可補助 NT$450、B 個人可補助 NT$850
- **THEN** 部門未超額,A 最終補助 NT$450、B 最終補助 NT$850,合計 NT$1,300
#### Scenario: 剛好等於上限
- **WHEN** 部門個人可補助總和恰等於月上限
- **THEN** 視為未超額,每人最終補助等於個人可補助金額
### Requirement: 超額時依占比分配並補足尾差
當個人可補助總和大於部門月上限時,系統 SHALL 依「個人可補助 ÷ 部門總可補助 × 月上限」計算每人應得金額,先取整數部分,再把「月上限 − 整數部分合計」的剩餘元數,依小數部分由大到小每人加 1 元分配,直到合計等於月上限(規格 §7.4、§15.2)。小數部分相同時 MUST 以固定且可重現的次序決定先後。最終補助合計 MUST 等於月上限且 MUST NOT 超過。
#### Scenario: 規格 §8.1(四捨五入取整)
- **WHEN** 一般部門 2 人、月上限 NT$1,000,取整方式為四捨五入,A 支付 899(個人可補助 450)、B 支付 1,700(個人可補助 850)
- **THEN** 應得金額為 346.15 與 653.85,整數部分 346 與 653 剩 1 元給小數較大的 B,最終補助 A NT$346、B NT$654,合計 NT$1,000
#### Scenario: 無條件捨去取整的同一案例
- **WHEN** 同上部門與支付金額,取整方式為無條件捨去(A 個人可補助 449、B 850,總和 1,299)
- **THEN** 應得金額為 345.65 與 654.35,整數部分 345 與 654 剩 1 元給小數較大的 A,最終補助 A NT$346、B NT$654,合計 NT$1,000
#### Scenario: 小數相同時以固定次序決勝
- **WHEN** 月上限 NT$1,000,三位申請人個人可補助皆為 NT$500(總和 1,500),應得金額皆為 333.33…,整數部分合計 999 剩 1 元
- **THEN** 系統依固定次序把 1 元給其中一人(如 334/333/333),且以相同輸入重算時結果完全相同
#### Scenario: 合計絕不超過上限
- **WHEN** 任意超額情況完成分配
- **THEN** 所有申請人最終補助合計等於部門月上限,且每人最終補助不超過其個人可補助金額
### Requirement: 無申請時的月結結果
當部門某月沒有任何審核通過案件時,系統 SHALL 產生合計為 0 的月結結果,不視為超額。
#### Scenario: 零申請
- **WHEN** 某部門 10 月沒有任何審核通過案件
- **THEN** 月結結果的可補助總額與最終補助合計皆為 NT$0,分配明細為空,狀態提示為未超額
### Requirement: 月結參數快照
系統 SHALL 在產生月結結果時,把補助比例、取整方式、部門類型每人額度、計算人數與月上限一併保存於該月結結果。部長提交後,後續後台參數或人數快照的變更 MUST NOT 改變已提交月結的金額(規格 §17)。
#### Scenario: 提交後調整參數
- **WHEN** 10 月設計部月結已提交,之後管理者把一般部門每人額度改為 NT$600
- **THEN** 10 月設計部月結的月上限與最終補助維持提交時的結果
#### Scenario: 未提交前重新計算採用最新參數
- **WHEN** 月結尚未提交,管理者調整取整方式後主管按下「重新計算」
- **THEN** 新的試算結果採用最新取整方式,並更新月結結果中的參數快照
@@ -0,0 +1,32 @@
# Tasks
## 1. 月結計算純函式
- [ ] 1.1 在 `lib/domain/settlement/` 實作個人可補助計算(加總後乘比例、無條件捨去/四捨五入,整數運算),並以 Vitest 驗證 899→449(捨去)、899→450(四捨五入)、899+655→777、未通過案件不計入等 scenario 通過
- [ ] 1.2 實作部門月上限計算(人數 × 部門類型每人額度、缺少快照時回傳錯誤),並以單元測試驗證一般部門 20 人→10,000、研發部 2 人→2,000、缺快照被拒
- [ ] 1.3 實作未超額/超額分配與最大餘數尾差補差(整數商餘、穩定排序鍵決勝),並以單元測試驗證規格 §8.1(346/654,兩種取整)、§8.2(450/850)、三人同額 334/333/333 可重現、零申請合計 0
- [ ] 1.4 加入 property-based 測試(隨機申請人數與金額)驗證「合計等於上限且每人不超過個人可補助」不變式,並確認測試通過
## 2. 資料模型與狀態推進
- [ ] 2.1 以 Drizzle 新增 `department_settlements` 與 `settlement_allocations` 資料表與 migration(含唯一鍵、外鍵、`is_late`),並驗證 `npm run db:migrate` 在空資料庫成功
- [ ] 2.2 新增 SQLite trigger 阻擋已提交月結的明細被修改或刪除,並以整合測試驗證 UPDATE 被拒
- [ ] 2.3 實作冪等的 `promoteApprovedToPendingSettlement(month)`(截止已過才推進、寫時間軸與操作紀錄),並以整合測試驗證截止前不推進、截止後推進、重複呼叫無副作用、截止後核准直接為待月結
- [ ] 2.4 實作「申請截止後逾期待補件可不核准」轉移(必填原因、預設「逾期未完成補件」、截止前拒絕),並以整合測試驗證截止前後行為
- [ ] 2.5 在 `instrumentation.ts` 註冊啟動時與每小時執行的推進計時器,並以測試或手動記錄驗證啟動後過期月份被推進
## 3. 月結服務與鎖定
- [ ] 3.1 實作試算服務(讀取案件與當下參數、呼叫純函式、覆寫未結算月結與明細),並以整合測試驗證重新計算會納入新核准案件與最新取整方式
- [ ] 3.2 實作提交前檢查(申請截止已過、無待主管審核/待補件,回傳案件清單),並以整合測試驗證「2 筆待審、1 筆待補件」與截止前提交皆被阻擋
- [ ] 3.3 實作提交交易(`BEGIN IMMEDIATE`、重算、快照、案件轉已提交並寫最終金額、逾期標示、操作紀錄),並以整合測試驗證成功、失敗全 rollback、25 日後標示逾期
- [ ] 3.4 實作共用鎖定守衛並套用到案件編輯、撤回、審核、重算動作,並以整合測試驗證已提交後上述動作全部被拒
- [ ] 3.5 實作權限檢查(主管僅本部門、員工不可存取),並以 API 測試驗證跨部門與員工存取被拒
## 4. 部門月結頁
- [ ] 4.1 建立 `/department/settlement` 頁:月份切換(預設最早未提交月份)、部門額度卡、超額/未超額提示,並以 Playwright 驗證 2026/11/22 預設顯示 2026/10
- [ ] 4.2 實作分配明細表(占比兩位小數、合計列、尾差標示與說明)與 Mobile 卡片版,並以 Playwright 驗證 A 34.62%/346、B 65.38%/654
- [ ] 4.3 實作「重新計算」「匯出預覽」(UTF-8 BOM CSV)按鈕,並以 Playwright 驗證下載檔欄位與金額
- [ ] 4.4 實作「確認並提交」:阻擋時列出待處理案件、確認視窗文案、取消不變、成功後唯讀並顯示提交資訊,並以 Playwright 端到端驗證
- [ ] 4.5 在使用說明文件(或 README 的月結章節)記錄計算規則、尾差規則與提交後更正方式,並確認內容與 spec scenario 一致
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-02
@@ -0,0 +1,40 @@
# Design
## Context
- 送出流程在 `subsidy-application`,狀態轉移集中於 `application-lifecycle`(roadmap D6);附件在 `application-attachments`,存本機目錄(roadmap D3)。
- 撤回後案件回到草稿(roadmap Decisions Log),因此「排除草稿」已涵蓋撤回情境。
## Goals / Non-Goals
**Goals:**
- 同一判斷邏輯在送出時與審核顯示時一致。
- 不阻擋合理的重複情形(例如同日買兩個同價方案),只要求確認。
**Non-Goals:**
- 跨申請人比對(例如兩人共用同一張 Invoice)——規格只要求同申請人;列為 Open Question。
- OCR 比對附件內容中的金額或日期。
## Decisions
### D1. 純函式判斷 + 送出時重新計算
判斷邏輯寫成無 I/O 的函式(輸入:候選案件與同申請人有效案件清單),送出 API 在交易內查詢並呼叫;不在背景預先計算,避免資料過期。替代方案:資料庫唯一約束硬擋——違反「警示而非阻擋」。
### D2. 附件以 SHA-256 內容雜湊比對
上傳時計算雜湊存於附件紀錄;migration 對既有附件回填。檔名不同但內容相同即視為相同。
### D3. 確認以「重送帶確認旗標」完成
送出 API 第一次回傳 `duplicate_warning` 與比對案件清單;前端顯示 ConfirmDialog,員工確認後帶 `confirmDuplicate=true` 重送。後端再次判斷,若仍重複且有確認旗標才放行,並寫入案件的重複標記(比對案件 ID 清單、確認者、時間)與 `audit-trail`。
### D4. 標記存在案件上,審核端直接讀取
疑似重複標記於送出時寫入案件,主管端不需重算;若後來被比對案件變為不核准,標記仍保留(反映送出當時狀態)。
## Risks / Trade-offs
- [正常情況被誤判(同日兩筆同價)] → 只是警示,員工確認即可送出。
- [員工隨意確認] → 主管端可見標記與確認紀錄,由主管判斷。
- [回填雜湊時附件檔案遺失] → 回填工具記錄失敗清單,缺雜湊的附件僅不參與內容比對。
## Open Questions
- 是否需跨申請人比對附件(防止共用 Invoice)?目前不做,若需要可在本 capability 以新 change 擴充。
@@ -0,0 +1,27 @@
# Proposal
## Why
規格 §15.3 要求針對相同申請人、平台、刷卡日期、金額及 Invoice 進行重複提醒,避免同一筆交易重複送件;前端規劃將「重複申請提示」列為 P1。MVP 未做此檢查,重複送件只能靠主管人工發現。
## What Changes
- 員工送出(含補件重送)時,系統比對同一申請人其他有效案件,符合重複條件即顯示警示「系統發現相同日期、平台與金額的申請,請確認是否重複送件。」(前端規劃 §9)。
- 重複判斷條件:同申請人+同 AI 平台(「其他」時含平台名稱)+同刷卡日期+同實際台幣金額;或任一附件檔案內容雜湊與他案相同。
- 只比對「有效」案件:排除草稿、不核准;撤回後已回到草稿的案件也因此不計入。
- 為警示而非阻擋:員工須明確確認「非重複」後才能送出,確認紀錄留存。
- 主管審核工作台與案件詳情顯示「疑似重複」標記,可直接開啟被比對的案件。
## Capabilities
### New Capabilities
- `duplicate-detection`: 疑似重複申請的判斷條件、送出時的警示與確認、審核端標記與紀錄。
### Modified Capabilities
<!-- 無:在 `subsidy-application` 送出與 `application-review` 檢視流程中加入檢查,但不變更其既有 requirement;新行為全部定義在 `duplicate-detection` -->
## Impact
- 依賴 Phase 1 changes archive 後實作:`subsidy-application`(送出流程)、`application-attachments`(附件內容雜湊)、`application-review`(審核工作台)、`audit-trail`(確認紀錄)。
- 附件需保存內容雜湊(SHA-256);既有附件需一次性回填。
- 送出 API 回應增加「需確認重複」的結果型態。
@@ -0,0 +1,51 @@
# Spec Delta
## Purpose
在員工送出申請時偵測可能重複的同一筆交易並要求確認,同時讓主管在審核時看到疑似重複標記,降低同一筆訂閱費被重複補助的風險(規格 §15.3)。
## ADDED Requirements
### Requirement: 疑似重複判斷條件
系統 SHALL 在下列任一條件成立時,將待送出案件判定為與另一案件疑似重複:(1) 同一申請人、同一 AI 平台(平台為「其他」時平台名稱也相同,不分大小寫與前後空白)、同一刷卡日期且同一實際台幣金額;(2) 任一附件的檔案內容與同一申請人另一案件的附件完全相同。
#### Scenario: 欄位條件相同
- **WHEN** 員工已有一筆 ChatGPT、刷卡日期 2026/10/05、NT$899 的待審案件,又送出相同平台、日期、金額的新案件
- **THEN** 系統判定新案件疑似重複,並指出被比對的案件
#### Scenario: 金額不同不算重複
- **WHEN** 新案件平台與刷卡日期相同但台幣金額為 NT$900
- **THEN** 系統不依欄位條件判定為重複
#### Scenario: 附件內容相同
- **WHEN** 新案件上傳的 Invoice 與同一申請人既有案件的 Invoice 檔案內容完全相同,即使檔名不同
- **THEN** 系統判定新案件疑似重複
### Requirement: 比對範圍僅限有效案件
重複判斷 MUST 只比對同一申請人狀態不是草稿或不核准的其他案件,且 MUST NOT 與案件自身比對。
#### Scenario: 不核准案件不參與比對
- **WHEN** 員工先前一筆相同條件的案件已被不核准,現在送出新案件
- **THEN** 系統不顯示重複警示
#### Scenario: 補件重送不與自己比對
- **WHEN** 員工對待補件案件修改後重新送出
- **THEN** 系統不會把該案件判定為與自己重複
### Requirement: 送出前重複警示與確認
當待送出案件疑似重複時,系統 SHALL 中止送出並顯示「系統發現相同日期、平台與金額的申請,請確認是否重複送件。」及被比對案件的連結;員工確認非重複後 SHALL 能繼續送出,系統 MUST 記錄確認者與時間。
#### Scenario: 員工確認後送出
- **WHEN** 員工看到重複警示後勾選「確認不是重複送件」並再次送出
- **THEN** 案件成功送出進入待主管審核,操作紀錄包含此確認
#### Scenario: 員工取消送出
- **WHEN** 員工看到重複警示後選擇取消
- **THEN** 案件維持原狀態,未送出
### Requirement: 審核端顯示疑似重複標記
對疑似重複的案件,系統 SHALL 在主管審核清單與案件詳情顯示「疑似重複」標記,並提供被比對案件的連結及員工的確認紀錄。
#### Scenario: 主管看到標記
- **WHEN** 主管開啟一筆員工確認後送出的疑似重複案件
- **THEN** 審核詳情顯示「疑似重複」標記、被比對案件連結與員工確認時間
@@ -0,0 +1,20 @@
# Tasks
## 1. 資料與判斷邏輯
- [ ] 1.1 為附件新增內容雜湊欄位、為案件新增重複標記欄位(比對案件、確認者、確認時間),產生 Drizzle migration,並驗證可套用於含既有資料的 SQLite
- [ ] 1.2 上傳附件時計算 SHA-256,並撰寫既有附件回填腳本,以 Vitest 驗證檔名不同內容相同時雜湊一致、檔案遺失時記入失敗清單
- [ ] 1.3 實作疑似重複判斷純函式(欄位條件、「其他」平台名稱正規化、附件雜湊、排除草稿/不核准/自身),並以 Vitest 涵蓋 spec 全部判斷 scenario
## 2. 送出流程
- [ ] 2.1 送出/重送 API 在交易內執行判斷,未確認時回傳重複警示與比對案件,確認後寫入重複標記與操作紀錄,並以 Vitest 驗證確認前不轉移狀態、確認後成功送出
- [ ] 2.2 新增申請頁與補件頁顯示重複警示 ConfirmDialog(前端規劃 §9 文案、比對案件連結、確認勾選),並以 Playwright 驗證取消時案件維持原狀態
## 3. 審核端顯示
- [ ] 3.1 主管審核清單與案件詳情顯示「疑似重複」標記、比對案件連結與員工確認時間(StatusBadge 含文字),並以 Playwright 驗證主管可開啟比對案件
## 4. 整合驗證
- [ ] 4.1 以 Playwright 跑完整流程:送出案件 A → 送出相同條件案件 B 出現警示 → 確認送出 → 主管看到標記,確認全部通過
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-02
@@ -0,0 +1,52 @@
# Design
## Context
建立在 `setup-project-foundation` 的骨架上(Next.js App Router、SQLite、Drizzle、Zod)。規格 §4 定義四種角色;§19 Phase 1 使用本地帳號、Phase 3 才接 SSO/AD。roadmap design 的風險項要求以員工編號/email 作穩定識別。
## Goals / Non-Goals
**Goals:**
- 單一權限判斷入口,後續所有頁面、Server Action、Route Handler 都用它。
- 資料範圍檢查集中,避免各頁各自寫查詢條件而漏掉。
**Non-Goals:**
- SSO/AD(`integrate-sso`)、人資系統同步(`integrate-hr-org-sync`)。
- 操作紀錄頁的授權細節(由 `add-audit-trail` 定義)。
## Decisions
### 認證:自建 session,不用 Auth.js
- 密碼以 argon2id(`@node-rs/argon2`,有 Windows 預編譯)雜湊。
- session 存 SQLite `sessions` 表(隨機 256-bit token 的 SHA-256 雜湊、user_id、last_seen_at、created_at),cookie 為 `httpOnly`、`sameSite=lax`、正式環境 `secure`。每次請求更新 last_seen_at(節流為每分鐘一次),閒置 8 小時失效。
- 理由:需求只有本地帳密,自建邏輯少且可控;Auth.js 的 Credentials provider 不支援 DB session,且日後 SSO 可在同一 session 表上新增 OIDC 登入路徑。
### 授權:集中的 guard 與 scope helper
- `requireUser()`、`requireRole(...roles)` 用於頁面、Server Action、Route Handler 入口。
- `scopeApplications(user)` 產生申請查詢條件:員工 → 本人;主管 → 所轄部門(`department_managers`);管理者 → 全部。後續 change 查詢申請 MUST 經過此 helper。
- `middleware.ts` 只檢查是否有 session cookie 並導向 `/login`(middleware 不直接讀 SQLite);完整 session 驗證與角色檢查在各 route group 的 server layout 與每個 action 內執行。
- 導覽項目與路由權限由同一份「路由 → 允許角色」設定產生,避免兩者不一致。
### 資料模型
- `departments(id, name, type: general|rnd, active)`
- `users(id, employee_no UNIQUE, email UNIQUE, name, department_id, active, password_hash, must_change_password, failed_attempts, locked_until)`
- `user_roles(user_id, role)`,role ∈ employee / manager / admin / sysadmin。
- `department_managers(department_id, user_id)`:主管資料範圍以此表為準。
- `user_department_history(user_id, department_id, effective_from)`:調部門紀錄。申請建立時把當下部門寫入申請本身(由 `add-subsidy-application` 實作),因此調部門不影響舊申請。
### CSV 匯入
兩階段:上傳 → 以 Zod 全量驗證並回傳預覽/錯誤列 → 確認後單一交易寫入。以員工編號為 upsert key;部門以名稱比對,不存在即報錯(部門需先建立或在同一檔案的部門區段中定義)。
## Risks / Trade-offs
- [自建認證的安全風險] → 使用成熟雜湊函式庫、固定時間比較、失敗鎖定、session token 只存雜湊;e2e 測試涵蓋未授權存取。
- [若某頁漏寫 server 端角色檢查就會外洩] → route group layout 強制呼叫 `requireRole`,並以 e2e 測試逐一驗證各角色對所有路由的結果。
- [本 change 早於 audit-trail,帳號異動暫時無留痕] → `add-audit-trail` 的 tasks 會補接本 change 的寫入點。
## Migration Plan
`db:seed` 建立初始系統管理員(密碼由環境變數提供、首次登入強制變更),其餘人員以 CSV 匯入。
@@ -0,0 +1,31 @@
# Proposal
## Why
所有流程都依角色與部門運作(規格 §4):員工只能看自己的申請、主管只能審核本部門、管理者看全公司。沒有帳號、部門與權限,就無法實作申請、審核與月結。MVP 先用本地帳號(規格 §19 Phase 1),SSO 留到 Phase 3。
## What Changes
- 本地帳號登入/登出(帳號密碼、伺服器端 session、閒置逾時)、使用者自行變更密碼、系統管理員重設密碼。
- 使用者以員工編號與公司 email 為穩定識別(供日後 SSO 對應),可停用但不刪除。
- 部門資料:名稱、部門類型(一般/研發,決定每人月額度)、部門主管;使用者同時只隸屬一個部門。
- 角色:員工、部門主管/部長、管理者/人資財務、系統管理員;一人可兼多個角色。
- 資料範圍控制:員工僅本人、主管僅所轄部門、管理者全公司;未授權存取一律拒絕。
- 依角色決定可進入的路由與可見的導覽項目(伺服器端檢查,前端僅隱藏)。
- 系統管理員維護帳號、角色與部門;以 CSV 匯入初始人員與部門。
## Capabilities
### New Capabilities
- `identity-access`: 登入/登出、session、密碼管理、角色指派與權限判斷、資料範圍控制、路由存取控制。
- `org-directory`: 部門與部門類型、人員資料(員工編號、email、姓名、所屬部門、在職狀態)、部門主管指派、調部門紀錄、CSV 匯入。
### Modified Capabilities
<!-- 無 -->
## Impact
- 新增資料表:departments、users、user_roles、department_managers、user_department_history、sessions。
- 新增頁面:`/login`、`/admin/accounts`(帳號與角色)、`/admin/departments`;後續所有頁面與 API 都需呼叫本 change 的權限檢查。
- 部門類型供 `add-rule-settings` 計算部門月上限;人員在職狀態供人數快照使用。
- 帳號與部門異動的操作留痕由 `add-audit-trail` 接上(該 change 晚於本 change)。
@@ -0,0 +1,103 @@
# Spec Delta
## Purpose
定義使用者如何登入系統、擁有哪些角色,以及系統如何依角色與部門限制可存取的頁面、資料與操作,確保每位使用者只看到並只能操作自己有權限的內容。
## ADDED Requirements
### Requirement: 帳號密碼登入
系統 SHALL 允許已啟用的使用者以員工編號或公司 email 加上密碼登入,登入成功後建立伺服器端 session。帳號不存在、密碼錯誤或帳號停用時 MUST 拒絕登入,且錯誤訊息不得透露是哪一項錯誤。
#### Scenario: 登入成功
- **WHEN** 已啟用的使用者輸入正確的員工編號與密碼
- **THEN** 系統建立 session 並導向 `/dashboard`
#### Scenario: 密碼錯誤
- **WHEN** 使用者輸入錯誤密碼
- **THEN** 系統拒絕登入並顯示「帳號或密碼錯誤」,不建立 session
#### Scenario: 帳號已停用
- **WHEN** 已停用的使用者輸入正確密碼
- **THEN** 系統拒絕登入並顯示「帳號或密碼錯誤」
### Requirement: 連續登入失敗鎖定
同一帳號連續登入失敗達 5 次時,系統 MUST 暫時鎖定該帳號 15 分鐘,鎖定期間即使密碼正確也拒絕登入。
#### Scenario: 失敗達上限
- **WHEN** 某帳號連續第 5 次輸入錯誤密碼
- **THEN** 該帳號在 15 分鐘內無法登入
#### Scenario: 成功登入重置計數
- **WHEN** 使用者在失敗 3 次後成功登入
- **THEN** 失敗次數歸零
### Requirement: Session 管理與登出
系統 SHALL 在使用者登出或閒置超過 8 小時後使 session 失效;失效後存取任何需登入的頁面或 API MUST 導向登入頁或回傳未授權。
#### Scenario: 登出
- **WHEN** 使用者點擊頂部列的「登出」
- **THEN** session 失效並回到登入頁
#### Scenario: 閒置逾時
- **WHEN** 使用者閒置超過 8 小時後再操作
- **THEN** 系統導向登入頁
### Requirement: 密碼管理
使用者 SHALL 能在驗證舊密碼後變更自己的密碼;系統管理員 SHALL 能重設他人密碼,被重設者下次登入 MUST 先變更密碼。密碼 MUST 至少 8 個字元,且只以不可逆雜湊儲存。
#### Scenario: 變更密碼
- **WHEN** 使用者輸入正確舊密碼與符合規則的新密碼
- **THEN** 密碼更新,舊密碼不再可登入
#### Scenario: 管理者重設後強制變更
- **WHEN** 系統管理員重設某使用者密碼後,該使用者以新密碼登入
- **THEN** 系統要求先設定新密碼才能使用其他功能
### Requirement: 角色指派
系統 SHALL 支援四種角色:員工、部門主管、管理者、系統管理員;一位使用者 MAY 同時擁有多個角色,所有在職使用者 MUST 至少具備員工角色。只有系統管理員可指派或移除角色。
#### Scenario: 兼任角色
- **WHEN** 系統管理員將某員工同時指派為部門主管
- **THEN** 該使用者登入後同時看到員工與主管的導覽項目
#### Scenario: 非系統管理員嘗試指派角色
- **WHEN** 管理者角色的使用者嘗試修改他人角色
- **THEN** 系統拒絕並回傳無權限
### Requirement: 資料範圍控制
系統 MUST 依角色限制可讀寫的資料:員工僅能存取本人的申請;部門主管僅能存取其所轄部門的申請與月結;管理者可存取全公司申請、月結與發放資料;系統管理員可存取設定、帳號與操作紀錄。超出範圍的存取 MUST 被拒絕,即使直接呼叫 API 或輸入網址。
#### Scenario: 員工存取他人申請
- **WHEN** 員工直接開啟他人申請的網址
- **THEN** 系統回應無權限,不顯示該申請內容
#### Scenario: 主管存取其他部門
- **WHEN** 設計部主管要求研發部的申請清單
- **THEN** 系統拒絕並回傳無權限
#### Scenario: 管理者查看全公司
- **WHEN** 管理者開啟全公司月結
- **THEN** 系統顯示所有部門資料
### Requirement: 角色導向的路由與導覽
系統 SHALL 依使用者角色決定可進入的路由與側欄可見項目(員工:首頁、新增申請、我的申請;主管:部門審核、部門月結;管理者:全公司月結、發放管理、後台設定;系統管理員:後台設定、帳號與角色、操作紀錄)。權限檢查 MUST 在伺服器端執行,前端隱藏不得作為唯一防線。
#### Scenario: 員工看不到管理功能
- **WHEN** 僅具員工角色的使用者登入
- **THEN** 側欄不顯示部門審核、全公司月結、後台設定等項目
#### Scenario: 直接輸入未授權路由
- **WHEN** 員工在網址列輸入 `/admin/settlements`
- **THEN** 系統顯示無權限頁面,不回傳任何管理資料
### Requirement: 審核權限限於部門主管
系統 MUST 只允許申請人所屬部門的主管執行審核操作;不具主管身分的使用者不得審核任何案件,包含本人案件(規格 §4)。部門主管 SHALL 可審核自己提出的申請(使用者決定),該次審核 MUST 在案件時間軸與操作紀錄標示為「主管自行審核」。
#### Scenario: 一般員工嘗試審核
- **WHEN** 一般員工以網址開啟任何案件的審核操作
- **THEN** 系統拒絕操作
#### Scenario: 主管本人的申請
- **WHEN** 設計部主管審核自己提出的申請並核准
- **THEN** 系統允許核准,並在時間軸與操作紀錄標示「主管自行審核」
@@ -0,0 +1,62 @@
# Spec Delta
## Purpose
維護公司部門與人員的基本資料(部門類型、主管、人員所屬與在職狀態),作為權限範圍、部門月上限與每月人數快照的依據。
## ADDED Requirements
### Requirement: 部門資料與部門類型
系統 SHALL 維護部門清單,每個部門有名稱、部門類型(一般或研發)與啟用狀態;部門類型決定適用的每人月額度(規格 §2、§7.2)。部門 MUST 不可刪除,只能停用,以保留歷史月結關聯。
#### Scenario: 新增研發部門
- **WHEN** 系統管理員新增部門「研發部」並設定類型為研發
- **THEN** 部門清單出現研發部,類型顯示為「研發」
#### Scenario: 停用部門
- **WHEN** 系統管理員停用某部門
- **THEN** 該部門不再出現在人員的部門選項中,但歷史資料仍可查詢
### Requirement: 人員資料
系統 SHALL 維護人員資料:員工編號(唯一)、公司 email(唯一)、姓名、所屬部門、在職狀態。每位人員同一時間 MUST 只隸屬一個部門。人員 MUST 不可刪除,離職以停用表示。
#### Scenario: 員工編號重複
- **WHEN** 系統管理員新增員工編號已存在的人員
- **THEN** 系統拒絕並提示員工編號已存在
#### Scenario: 離職停用
- **WHEN** 系統管理員將某人員設為離職
- **THEN** 該人員無法登入,其歷史申請仍保留可查
### Requirement: 部門主管指派
系統 SHALL 允許系統管理員為每個部門指派一位或多位部門主管;被指派者取得對該部門的主管資料範圍,移除指派後立即失去該範圍。
#### Scenario: 指派主管
- **WHEN** 系統管理員將李經理指派為設計部主管
- **THEN** 李經理可在部門審核看到設計部的待審案件
#### Scenario: 移除主管
- **WHEN** 系統管理員移除李經理的設計部主管身分
- **THEN** 李經理無法再存取設計部的審核與月結頁
### Requirement: 人員調部門
人員變更所屬部門時,系統 SHALL 記錄生效日期;變更 MUST 不改寫既有申請所歸屬的部門。
#### Scenario: 調部門後的舊申請
- **WHEN** 王小明 10/15 從設計部調到研發部
- **THEN** 他調動前建立的申請仍歸屬設計部,之後新建的申請歸屬研發部
#### Scenario: 查詢指定日期的部門成員
- **WHEN** 系統查詢設計部在 2026/11/01 00:00 的在職成員(供每月人數快照使用)
- **THEN** 系統依生效日期回傳當時屬於設計部的人員,10/15 已調往研發部的王小明不在其中
### Requirement: CSV 匯入人員與部門
系統 SHALL 提供 CSV 匯入初始部門與人員(含角色),匯入前 MUST 驗證全部資料列並顯示錯誤列與原因;有任何錯誤時不得寫入任何資料。
#### Scenario: 匯入成功
- **WHEN** 系統管理員上傳格式正確的 CSV
- **THEN** 系統顯示將新增與更新的筆數,確認後寫入
#### Scenario: 部分列錯誤
- **WHEN** CSV 第 5 列缺少 email、第 9 列部門不存在
- **THEN** 系統列出這兩列的錯誤原因,且不匯入任何資料
@@ -0,0 +1,31 @@
# Tasks
## 1. 資料模型
- [ ] 1.1 建立 departments、users、user_roles、department_managers、user_department_history、sessions 的 Drizzle schema 與 migration,確認 `npm run db:migrate` 成功且員工編號、email 唯一鍵生效
- [ ] 1.2 擴充 `db:seed` 建立初始系統管理員(密碼來自環境變數、`must_change_password=true`),確認重複執行不會重複建立
## 2. 認證
- [ ] 2.1 實作 argon2id 密碼雜湊與驗證工具,Vitest 測試正確/錯誤密碼與最短長度規則通過
- [ ] 2.2 實作 session 建立、驗證、更新 last_seen_at、閒置 8 小時失效與登出,整合測試涵蓋逾時與登出後失效
- [ ] 2.3 實作登入 action 與 `/login` 頁(員工編號或 email+密碼、統一錯誤訊息、連續 5 次失敗鎖定 15 分鐘),整合測試涵蓋成功、密碼錯誤、停用帳號、鎖定、成功後重置計數
- [ ] 2.4 實作變更密碼頁與強制變更流程(must_change_password 時攔截其他頁面),e2e 測試管理者重設後首次登入被要求改密碼
## 3. 授權
- [ ] 3.1 實作 `requireUser`、`requireRole` 與「路由 → 允許角色」設定,單元測試四種角色對前端規劃 §11 每條路由的允許/拒絕結果
- [ ] 3.2 實作 `scopeApplications` 與部門範圍 helper(員工本人、主管所轄部門、管理者全部)及「僅部門主管可審核」判斷,單元測試涵蓋一般員工審核被拒、主管審本人案件允許且標示「主管自行審核」
- [ ] 3.3 建立 `middleware.ts`(無 session 導向 `/login`)、各 route group layout 的角色檢查與無權限頁,e2e 測試員工直接輸入 `/admin/settlements` 看到無權限頁
- [ ] 3.4 依角色產生側欄導覽資料(供 `add-app-shell` 使用),單元測試四種角色及兼任時的項目
## 4. 組織與帳號管理
- [ ] 4.1 實作部門管理頁 `/admin/departments`(新增、編輯類型、停用、指派/移除主管),整合測試停用部門不出現在選項、指派主管後取得部門範圍
- [ ] 4.2 實作帳號與角色頁 `/admin/accounts`(新增、編輯、停用、指派角色、重設密碼、調部門並記錄生效日),整合測試員工編號重複被拒、非系統管理員無法改角色
- [ ] 4.3 實作 CSV 匯入(範本下載、全量驗證預覽、單一交易寫入、以員工編號 upsert),整合測試含錯誤列時完全不寫入
## 5. 整合驗收
- [ ] 5.1 在 CI 開啟 Playwright e2e(安裝瀏覽器),以 e2e 測試四種角色登入後的導覽與跨範圍存取被拒,確認 CI 通過
- [ ] 5.2 更新 `CLAUDE.md` 說明授權入口(頁面與 action 必須用 `requireRole`,申請查詢必須用 `scopeApplications`),確認內容與程式一致
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-02
@@ -0,0 +1,52 @@
# Design
## Context
- 共用決策見 `plan-system-roadmap/design.md`(D3 Next.js + SQLite + Drizzle、D6 狀態機集中定義)。
- 狀態機模組、案件資料與轉移紀錄由 add-subsidy-application 建立;本 change 只往轉移表新增定義並加上審核者判定。
- 部門主管、管理者角色與部門範圍由 identity-access/org-directory 提供。
## Goals / Non-Goals
**Goals:**
- 審核者判定規則集中為一個函式,清單查詢與轉移 guard 共用,避免「看得到但不能審」或反之。
- 審核轉移與撤回之間不產生競態。
**Non-Goals:**
- 月結計算與月結相關狀態(add-department-settlement)。
- 審核結果通知(Phase 2 add-notifications)。
- 重複申請提示(Phase 2)。
## Decisions
### 1. 審核者判定 `resolveReviewer(application)`
回傳「申請人部門的主管」,申請人即為該主管時亦同(使用者 2026-10-02 決定:主管自行審核,並標示「主管自行審核」);部門沒有主管時回傳「管理者角色」。清單查詢以此規則轉成 SQL 條件,轉移 guard 對單筆案件呼叫同一函式。規格 §4 的「不可審核本人案件」針對一般員工角色,不適用於部門主管。替代方案「改由管理者審」由使用者否決。
### 2. 轉移定義
新增 `approve`(待主管審核→審核通過)、`return`(→待補件,requiresComment)、`reject`(→不核准,requiresComment,終止)。三者 guard 皆為「操作者 = resolveReviewer」。
### 3. 競態處理
沿用狀態機的單一 `BEGIN IMMEDIATE` 交易:交易內重新讀取狀態並比對預期 from 狀態,不符即回傳「狀態已變更」。撤回 guard(add-subsidy-application)已要求本次送出後無審核紀錄,兩者自然互斥。
### 4. 月結池
不另建月結池資料表:月結以「部門+申請月份+狀態=審核通過」查詢即可,避免重複狀態來源。核准轉移不需額外寫入。
### 5. 批次核准
逐筆在同一請求內執行 approve 轉移,每筆獨立交易;先以完整性檢查(必填+兩份附件)篩出可核准者,回傳成功清單與失敗原因。替代方案「整批單一交易、全有或全無」會因一筆不完整卡住全部,否決。
### 6. 頁面
`/department/review` 以 URL 參數保存目前篩選與選取案件(`?status=pending&id=...`),Desktop 雙欄、Mobile 導向 `/department/review/:id`。附件預覽使用 app-shell 的 FilePreview(Modal/抽屜,Mobile 全螢幕)。管理者代審的案件在管理者的同一工作台以「代審」分頁呈現。
## Risks / Trade-offs
- [主管自行審核缺乏制衡] → 時間軸與操作紀錄標示「主管自行審核」,管理者於全公司月結可檢視;日後若要改由他人審核,規則集中在 `resolveReviewer`,只需改一處。
- [部門沒有設定主管時案件無人審核] → `resolveReviewer` 回退到管理者,並在管理者工作台顯示。
- [批次核准部分成功造成困惑] → 結果明確列出成功筆數與失敗原因。
## Migration Plan
無資料遷移;轉移表新增定義即生效。
## Open Questions
- 部門未設定主管時暫由管理者審核,此為假設,待使用者確認。
@@ -0,0 +1,30 @@
# Proposal
## Why
補助以「工作需求」為前提,必須由部門主管核實用途、平台合理性、成果與附件後,案件才能進入月結(規格 §5 步驟 6、§10;介面規劃 §5、FE-05)。主管需要一個能快速判斷、不必重讀制度的審核工作台;沒有它,申請只會停在「待主管審核」,月結也無從計算。
## What Changes
- 新增部門審核工作台(`/department/review`):Desktop 左側案件清單(35%)+右側詳情(65%),Mobile 先清單後獨立詳情頁。
- 清單預設只顯示「待審核」,可切換待補件、已通過、不核准;每筆顯示申請人、平台、金額、刷卡月份、50% 試算、用途摘要。
- 詳情含完整申請資料、Invoice 與刷卡帳單頁內預覽、審核檢查項目(規格 §10.1)、審核意見、審核時間軸。
- 三種審核動作:核准、退回補件、不核准;退回與不核准必填意見,不核准需確認視窗。
- 批次核准:僅限資料完整的待審核案件;退回與不核准仍需逐筆處理。
- 權限:主管只能審核本部門案件,主管本人的申請由主管自行審核並標示「主管自行審核」;部門無主管時由管理者(人資財務)審核。
- 擴充案件狀態機:待主管審核 → 審核通過/待補件/不核准;審核通過案件依申請月份進入該部門當月月結池。
## Capabilities
### New Capabilities
- `application-review`: 審核者查看待審案件、預覽附件、依檢查項目做出核准/退回補件/不核准(含批次核准)的審核工作台與其權限規則。
### Modified Capabilities
<!-- `application-lifecycle` 由 add-subsidy-application 建立且尚未 archive;本 change 以 ADDED requirement 新增審核轉移(見 specs/application-lifecycle/spec.md),不修改其既有 requirement。 -->
## Impact
- 新增頁面:`/department/review`(含 Mobile 詳情路由);`/applications/:id` 對審核者顯示審核區塊。
- 擴充狀態轉移表:approve、return、reject 三筆轉移與審核者判定規則。
- 依賴:`application-lifecycle`、`subsidy-application`(add-subsidy-application)、`application-attachments`(預覽)、`identity-access`(部門範圍、角色)、`audit-trail`、`app-shell`(ConfirmDialog、FilePreview、ReviewTimeline)。
- 下游:`add-department-settlement` 讀取「審核通過」案件作為月結池。
@@ -0,0 +1,35 @@
# Spec Delta
## ADDED Requirements
### Requirement: 審核核准轉移
系統 SHALL 允許該案件的審核者將「待主管審核」案件轉為「審核通過」;申請人本人與非審核者 MUST NOT 執行此轉移。
#### Scenario: 審核者核准
- **WHEN** 案件審核者核准待主管審核案件
- **THEN** 案件狀態變為審核通過,時間軸新增「主管核准」紀錄
#### Scenario: 他部門主管核准
- **WHEN** 非該案件審核者的主管嘗試核准
- **THEN** 系統拒絕,案件狀態不變
### Requirement: 審核退回補件轉移
系統 SHALL 允許該案件的審核者將「待主管審核」案件轉為「待補件」,且轉移 MUST 附帶非空白意見。
#### Scenario: 退回補件
- **WHEN** 審核者附意見退回待主管審核案件
- **THEN** 案件狀態變為待補件,時間軸新增「主管退回補件」紀錄與意見
### Requirement: 審核不核准轉移
系統 SHALL 允許該案件的審核者將「待主管審核」案件轉為「不核准」,且轉移 MUST 附帶非空白原因;「不核准」為終止狀態,之後不得再有任何轉移或內容修改。
#### Scenario: 不核准後唯讀
- **WHEN** 案件已不核准,申請人嘗試編輯或重送
- **THEN** 系統拒絕操作
### Requirement: 審核動作終止撤回權
系統 SHALL 在審核者對案件做出任何審核轉移後,取消申請人對該次送出的撤回權;同一案件若在員工撤回與主管審核同時發生,系統 MUST 只接受先完成的一方,另一方收到狀態已變更的提示。
#### Scenario: 撤回與核准同時發生
- **WHEN** 員工撤回與主管核准幾乎同時送達
- **THEN** 只有先完成的操作生效,另一方看到「案件狀態已變更,請重新整理」
@@ -0,0 +1,98 @@
# Spec Delta
## Purpose
讓部門主管(或代審的管理者)在單一工作台快速判斷申請是否符合工作需求,檢視附件、依檢查項目做出核准、退回補件或不核准,並讓審核結果與意見清楚回饋給申請人。
## ADDED Requirements
### Requirement: 審核者判定
系統 SHALL 以申請人所屬部門的主管作為該案件的審核者;申請人本身是該部門主管時,仍由其本人審核(使用者決定),並標示「主管自行審核」。部門未設定主管時,案件 MUST 改由具管理者(人資財務)角色的使用者審核。主管不得看到或審核其他部門的案件。
#### Scenario: 一般員工的申請
- **WHEN** 設計部員工送出申請
- **THEN** 該案件出現在設計部主管的待審清單
#### Scenario: 主管本人的申請
- **WHEN** 設計部主管送出自己的申請
- **THEN** 該案件出現在其本人的待審清單並標示「主管自行審核」,審核動作的時間軸與操作紀錄同樣標示
#### Scenario: 部門未設定主管
- **WHEN** 尚未指派主管的部門有員工送出申請
- **THEN** 該案件出現在管理者的待審清單
#### Scenario: 跨部門存取
- **WHEN** 研發部主管以網址開啟設計部的案件審核頁
- **THEN** 系統拒絕存取,且不洩露案件內容
### Requirement: 待審清單
系統 SHALL 提供審核清單,預設只顯示「待審核」案件,並可切換顯示待補件、已通過、不核准;每筆 MUST 顯示申請人、平台、台幣金額、刷卡月份、50% 試算與用途摘要。無案件時顯示空狀態。
#### Scenario: 預設篩選
- **WHEN** 主管開啟部門審核頁
- **THEN** 清單只顯示待審核案件,例如「王小明|ChatGPT|NT$899|待審核」
#### Scenario: 切換篩選
- **WHEN** 主管切換到「待補件」
- **THEN** 清單只顯示已退回、等待員工補件的案件
### Requirement: 審核詳情與附件預覽
系統 SHALL 在審核詳情顯示申請人、平台、方案、刷卡日期與月份、台幣金額、50% 試算、工作用途、成果產出、審核時間軸,並 MUST 支援在頁內預覽 Invoice 與刷卡帳單,無須另開新頁。
#### Scenario: 預覽附件
- **WHEN** 主管在詳情點擊刷卡帳單
- **THEN** 附件以頁內預覽(Desktop 為 Modal 或側邊抽屜、Mobile 為全螢幕)開啟
### Requirement: 審核檢查項目
系統 SHALL 在審核詳情列出審核檢查項目:用途與工作直接相關、平台合理(其他平台需說明充分)、屬工作使用/測試/實驗/研發、有具體成果產出、附件完整可辨識、金額與刷卡日期一致(規格 §10.1)。檢查項目為審核提示,系統 MUST 不以其勾選狀態取代審核者的判斷。
#### Scenario: 顯示檢查項目
- **WHEN** 主管開啟一筆平台為「其他」的案件
- **THEN** 詳情列出六項檢查項目,並提示其他平台需確認說明是否充分
### Requirement: 核准
系統 SHALL 允許審核者核准「待審核」案件;核准意見為選填。核准後案件 MUST 依其申請月份計入申請人部門當月的月結池。
#### Scenario: 核准案件
- **WHEN** 主管核准刷卡月份 2026/10 的待審核案件
- **THEN** 案件狀態變為已通過,並計入該部門 2026/10 月結池
### Requirement: 退回補件
系統 SHALL 允許審核者將「待審核」案件退回補件,且 MUST 填寫退回意見;意見空白時不得退回。退回後申請人能在案件詳情第一眼看到意見。
#### Scenario: 未填意見退回
- **WHEN** 主管未填意見即點擊「退回補件」
- **THEN** 系統拒絕操作並提示意見為必填
#### Scenario: 填意見退回
- **WHEN** 主管填寫「請補上刷卡帳單,並說明此工具實際用於哪一項工作。」後退回
- **THEN** 案件狀態變為待補件,申請人詳情頁上方顯示該意見
### Requirement: 不核准
系統 SHALL 允許審核者對「待審核」案件做出不核准,MUST 填寫原因並經確認視窗確認;不核准的案件結束、唯讀,且不計入月結。
#### Scenario: 不核准需確認
- **WHEN** 主管填寫原因並點擊「不核准」
- **THEN** 系統顯示確認視窗,確認後案件狀態變為不核准且不計入月結
#### Scenario: 取消確認
- **WHEN** 主管在不核准確認視窗點擊取消
- **THEN** 案件狀態不變
### Requirement: 批次核准
系統 SHALL 允許審核者一次核准多筆「待審核」案件,但每筆 MUST 具備完整必填資料與兩份附件;不完整的案件 MUST 不被核准並列出。批次操作不得用於退回或不核准。
#### Scenario: 批次中含不完整案件
- **WHEN** 主管勾選三筆案件批次核准,其中一筆缺少刷卡帳單
- **THEN** 兩筆完整案件變為已通過,缺附件的一筆維持待審核並被列出原因
#### Scenario: 無批次退回
- **WHEN** 主管勾選多筆案件
- **THEN** 批次操作只提供「核准」
### Requirement: 審核工作台版面
系統 SHALL 在 Desktop 以左側清單約 35%、右側詳情約 65% 的雙欄呈現審核工作台,操作按鈕依序為「不核准」「退回補件」「核准」且「核准」為唯一主要按鈕;Mobile MUST 先顯示清單,點選後進入獨立詳情頁。
#### Scenario: Mobile 審核
- **WHEN** 主管以手機寬度開啟審核頁並點選一筆案件
- **THEN** 系統進入該案件的獨立詳情頁,審核按鈕位於底部固定操作列
@@ -0,0 +1,25 @@
# Tasks
## 1. 審核者規則與轉移
- [ ] 1.1 確認「部門無主管時由管理者審核」的假設(主管本人申請由主管自行審核已於 2026-10-02 決定),並把結論記入本 change 的 design.md
- [ ] 1.2 實作 `resolveReviewer`(部門主管,含主管本人申請並標示「主管自行審核」;部門無主管時回退管理者),並以 Vitest 驗證一般員工、主管本人、無主管部門三種情況
- [ ] 1.3 於狀態機轉移表新增 approve、return(必填意見)、reject(必填原因、終止)及其 guard,並以 Vitest 驗證:審核者可轉移、他部門主管與申請人被拒、空白意見被拒、不核准後任何轉移或修改被拒
- [ ] 1.4 以 Vitest 驗證撤回與核准競態:同一案件先完成者生效、後者回傳「狀態已變更」
## 2. 審核伺服器端操作
- [ ] 2.1 實作審核清單查詢(依 resolveReviewer 範圍、狀態篩選、預設待審核),並以整合測試驗證主管只看到本部門且不含本人案件、管理者看到代審案件
- [ ] 2.2 實作核准、退回補件、不核准 Server Actions 與批次核准(完整性檢查、逐筆交易、回傳成功與失敗原因),並以整合測試驗證批次中缺附件案件維持待審核且被列出
## 3. 審核工作台頁面
- [ ] 3.1 建立 `/department/review` Desktop 雙欄(清單 35%/詳情 65%)、狀態篩選、快速摘要欄位與空狀態,並以 Playwright 驗證預設只顯示待審核
- [ ] 3.2 建立審核詳情:申請資料、用途與成果、FilePreview 頁內預覽 Invoice/刷卡帳單、六項審核檢查項目、審核意見、審核時間軸、按鈕「不核准/退回補件/核准」,並以 Playwright 驗證附件不另開新頁
- [ ] 3.3 實作意見必填提示與不核准確認視窗,並以 Playwright 驗證未填意見無法退回、取消確認視窗時狀態不變
- [ ] 3.4 實作批次核准 UI(只提供核准、結果列出成功筆數與失敗原因),並以 Playwright 驗證
- [ ] 3.5 實作 Mobile:清單→`/department/review/:id` 獨立詳情、底部固定操作列、附件全螢幕預覽,並以 Playwright 手機 viewport 驗證
## 4. 整合驗證
- [ ] 4.1 以 Playwright 跑:員工送出→主管退回補件→員工在詳情頁上方看到意見並重送→主管核准,確認時間軸四筆紀錄、操作紀錄對應、案件出現在該部門當月「已通過」清單
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-02
@@ -0,0 +1,44 @@
# Design
## Context
- 依賴 Phase 1 全部 archive:狀態轉移集中在 `application-lifecycle`(roadmap D6),月結動作在 `department-settlement`/`company-settlement`,截止日在 `rule-settings`,頂部列在 `app-shell`。
- 技術選型見 roadmap D3(Next.js App Router + SQLite + Drizzle,單一實例部署)。時間判斷一律 Asia/Taipei(roadmap D7)。
## Goals / Non-Goals
**Goals:**
- 事件通知與期限提醒都由伺服器端產生,前端只讀取。
- 新增通知不需修改既有業務邏輯的判斷,只在狀態轉移成功後掛上通知產生。
**Non-Goals:**
- Email、Teams/Slack、瀏覽器推播(後續可在同一通知模型上加送出管道)。
- 使用者自訂通知偏好(MVP 後若有需求再加)。
- 即時推送(WebSocket);以頁面載入與定時輪詢更新未讀數即可。
## Decisions
### N1. 在狀態轉移的同一交易內寫入通知
`application-lifecycle` 與月結服務在完成轉移後呼叫通知模組,於同一 SQLite 交易內寫入 `notifications`。轉移失敗則通知一併回滾,避免「收到通知但狀態未變」。替代方案:事件佇列非同步處理——單機 SQLite 下多一層元件且無必要。
### N2. 期限提醒以每日排程產生,靠唯一鍵去重
每日(Asia/Taipei 08:00)執行提醒工作,計算對象後寫入通知;以 `(recipient, type, target_key, date)` 唯一索引去重,重跑安全。排程執行方式:單一實例內的排程(如 node-cron 於伺服器啟動時註冊)或作業系統排程呼叫受保護的內部 API;於實作時擇一並記錄於 CLAUDE.md。替代方案:使用者登入時即時計算——不登入的人就收不到提醒,不採用。
### N3. 提醒時間點寫成常數組態,不做後台參數
員工 5/1 天、主管 3/1 天放在設定檔常數;截止日本身仍讀 `rule-settings`。若之後要可調再移入後台參數。
### N4. 未讀數以輪詢更新
頂部列每 60 秒與頁面切換時重新取得未讀數。資料量小,SQLite 查詢成本可忽略。
### N5. 通知內容快照
通知寫入當下的標題/說明文字(含金額、意見摘要),之後案件變更不回改通知,符合「通知即當時事件」的語意;連結指向最新案件頁。
## Risks / Trade-offs
- [排程未執行(伺服器停機)導致漏提醒] → 排程啟動時補跑當日;提醒工作執行結果寫入操作紀錄以便追查。
- [主管在多個角色或代理人情境下重複收件] → 收件人以使用者去重。
- [通知量增長] → 列表分頁;保留期限暫不限制,資料量大時再加清理策略。
## Open Questions
- 是否需要 Email 通知(尤其截止提醒)?目前假設不需要;若需要,另開 change 擴充送出管道。
@@ -0,0 +1,30 @@
# Proposal
## Why
規格 §19 Phase 2 與前端規劃 P1 要求「通知提醒」。MVP 完成後,員工常因不知道案件被退回補件或截止日將至而錯過期限(不允許逾期補登,見 roadmap Decisions Log),主管與管理端也需要被提醒待審案件與月結截止。現有頂部列的通知鈴(`app-shell`)需要真正的通知來源。
## What Changes
- 新增站內通知中心:頂部列鈴鐺顯示未讀數、下拉最近通知、通知列表頁,可標記已讀/全部已讀,點擊前往對應頁面。
- 事件通知:主管退回補件、案件核准/不核准、月結最終核定與已發放時通知申請人;員工送出或重送案件時通知該部門主管;部長提交月結時通知管理端;管理者退回月結時通知部長。
- 期限提醒(每日排程產生):
- 員工:刷卡月份次月 20 日截止前 5 天與前 1 天,對當月仍有草稿或待補件案件的員工提醒。
- 主管:次月 25 日月結截止前 3 天與前 1 天,提醒待審件數、待補件件數與尚未提交月結。
- 管理端:25 日截止後仍未提交月結的部門清單。
- 通知只發給有權限看到該案件或月結的人;同一提醒同一天不重複產生。
- 不包含 Email/即時推播(列為後續可選擴充)。
## Capabilities
### New Capabilities
- `notifications`: 站內通知的產生規則、收件對象、已讀狀態、通知列表與期限提醒排程行為。
### Modified Capabilities
<!-- 無:Phase 1 capabilities 未變更 requirement;事件來源僅「訂閱」既有狀態轉移 -->
## Impact
- 依賴 Phase 1 changes 全部 archive 後實作:`identity-access`(收件人與權限)、`app-shell`(頂部列鈴鐺)、`application-lifecycle`/`application-review`(案件事件)、`department-settlement`/`company-settlement`/`payout-management`(月結事件)、`rule-settings`(截止日參數)。
- 新增資料表:通知、提醒去重紀錄;新增每日排程執行點(單一實例部署,見 roadmap D3)。
- 新增通知列表頁路由 `/notifications`。
@@ -0,0 +1,90 @@
# Spec Delta
## Purpose
提供站內通知中心,讓員工、主管與管理端在案件狀態變更與申請/月結期限將至時即時得知需要處理的事項,避免錯過不可逾期的截止日。
## ADDED Requirements
### Requirement: 通知中心顯示與已讀狀態
系統 SHALL 在頂部列顯示目前使用者的未讀通知數,並提供下拉最近通知與完整通知列表頁。每則通知 MUST 包含標題、說明、產生時間、已讀狀態與目標連結;使用者 SHALL 能標記單則或全部為已讀。
#### Scenario: 顯示未讀數
- **WHEN** 使用者有 3 則未讀通知並開啟任一頁面
- **THEN** 頂部列鈴鐺顯示未讀數 3
#### Scenario: 點擊通知前往目標並標為已讀
- **WHEN** 使用者點擊一則「待補件」通知
- **THEN** 系統導向該案件詳情頁,且該通知變為已讀、未讀數減 1
#### Scenario: 全部標為已讀
- **WHEN** 使用者在通知列表頁點選「全部標為已讀」
- **THEN** 該使用者所有通知皆為已讀,鈴鐺不再顯示未讀數
### Requirement: 通知僅限本人可見
系統 MUST 只讓通知的收件人讀取與變更該通知;通知內容 MUST NOT 揭露收件人無權檢視的案件或月結資料。
#### Scenario: 他人無法讀取通知
- **WHEN** 員工嘗試以網址存取另一位員工的通知
- **THEN** 系統拒絕存取,且不回傳通知內容
### Requirement: 案件審核結果通知申請人
當主管對案件執行退回補件、核准或不核准時,系統 SHALL 通知該案件申請人;退回補件與不核准的通知 MUST 包含主管意見摘要。
#### Scenario: 退回補件通知
- **WHEN** 主管退回案件並填寫意見「請補上刷卡帳單」
- **THEN** 申請人收到「待補件」通知,內容含該意見並連結至案件詳情
#### Scenario: 核准通知
- **WHEN** 主管核准案件
- **THEN** 申請人收到「已通過,等待月結」通知
### Requirement: 待審案件通知部門主管
當員工送出或補件後重新送出案件時,系統 SHALL 通知該員工所屬部門的主管(具審核權限者)。
#### Scenario: 員工送出案件
- **WHEN** 設計部員工送出一筆申請
- **THEN** 設計部主管收到「有新的待審案件」通知;其他部門主管不會收到
### Requirement: 月結流程通知
系統 SHALL 在下列月結事件發生時通知相關人:部長提交月結時通知管理端;管理者退回月結時通知該部門部長;最終核定與標記已發放時通知該月結內所有申請人,並顯示最終補助金額或發放月份。
#### Scenario: 部長提交月結
- **WHEN** 設計部部長提交 2026/10 月結
- **THEN** 管理端使用者收到「設計部已提交 2026/10 月結」通知
#### Scenario: 最終核定通知申請人
- **WHEN** 管理者最終核定設計部 2026/10 月結
- **THEN** 該月結內每位申請人收到含其最終補助金額與預計發放月份的通知
### Requirement: 員工申請截止提醒
系統 SHALL 每日檢查,於刷卡月份次月申請截止日(預設 20 日,依後台參數)前 5 天與前 1 天,對該刷卡月份仍有草稿或待補件案件的員工產生截止提醒。
#### Scenario: 截止前 5 天提醒草稿
- **WHEN** 今日為 2026/11/15,員工有一筆刷卡日期 2026/10/05 的草稿
- **THEN** 員工收到「2026/10 申請將於 2026/11/20 截止」提醒
#### Scenario: 無待處理案件不提醒
- **WHEN** 今日為 2026/11/15,員工在 2026/10 沒有草稿或待補件案件
- **THEN** 系統不對該員工產生截止提醒
### Requirement: 主管月結截止提醒
系統 SHALL 於月結提交截止日(預設次月 25 日,依後台參數)前 3 天與前 1 天,對尚未提交該月月結的部門主管產生提醒,內容 MUST 包含待審件數與待補件件數。
#### Scenario: 截止前提醒未提交部門
- **WHEN** 今日為 2026/11/22,設計部尚未提交 2026/10 月結且有 2 筆待審
- **THEN** 設計部主管收到含「待審 2 筆」與截止日 2026/11/25 的提醒
### Requirement: 管理端逾期未提交提醒
系統 SHALL 在月結提交截止日隔天,通知管理端仍未提交該月月結的部門清單。
#### Scenario: 截止後仍有部門未提交
- **WHEN** 2026/11/26 行銷部仍未提交 2026/10 月結
- **THEN** 管理端收到列出行銷部的「月結逾期未提交」通知
### Requirement: 提醒不重複產生
同一收件人、同一提醒類型與同一對象(月份或部門)的期限提醒,系統 MUST 在同一天最多產生一次;排程重複執行 MUST NOT 產生重複通知。
#### Scenario: 排程重跑
- **WHEN** 每日提醒排程在同一天執行兩次
- **THEN** 每位收件人當天每種提醒只有一則
@@ -0,0 +1,27 @@
# Tasks
## 1. 資料模型與通知模組
- [ ] 1.1 以 Drizzle 新增 `notifications`(收件人、類型、標題、說明、目標連結、已讀時間、建立時間)與去重唯一索引 `(recipient, type, target_key, date)`,產生 migration,並驗證 migration 在空白 SQLite 上可套用
- [ ] 1.2 實作通知建立/查詢/標記已讀的伺服器端模組,限制僅收件人可讀寫,並以 Vitest 驗證他人存取被拒、全部已讀行為正確
## 2. 事件通知
- [ ] 2.1 在退回補件、核准、不核准的轉移中於同一交易寫入申請人通知(含意見摘要),並以 Vitest 驗證轉移失敗時通知回滾
- [ ] 2.2 在員工送出/重新送出時通知所屬部門主管,並以 Vitest 驗證其他部門主管不會收到
- [ ] 2.3 在部長提交月結、管理者退回月結、最終核定、標記已發放時寫入對應通知,並以 Vitest 驗證最終核定通知含每位申請人的最終補助金額
## 3. 期限提醒排程
- [ ] 3.1 實作每日提醒工作:員工申請截止前 5/1 天、主管月結截止前 3/1 天、截止隔天管理端未提交部門清單,截止日讀取 `rule-settings`,並以 Vitest(固定 Asia/Taipei 日期)驗證 spec 各 scenario
- [ ] 3.2 驗證同日重跑不產生重複通知(Vitest),並在伺服器啟動時註冊排程與補跑當日提醒
- [ ] 3.3 在 CLAUDE.md 記錄排程執行方式與手動觸發方法,並驗證文件所列指令可執行
## 4. 介面
- [ ] 4.1 頂部列鈴鐺顯示未讀數、下拉最近 5 則、60 秒輪詢,並以 Playwright 驗證點擊通知會導向目標且未讀數減少
- [ ] 4.2 新增 `/notifications` 列表頁(分頁、已讀/未讀樣式、全部標為已讀、EmptyState),並以 Playwright 驗證 Mobile 寬度下無溢出
## 5. 整合驗證
- [ ] 5.1 以 Playwright 跑完整流程:員工送出 → 主管收到通知 → 主管退回 → 員工收到含意見的通知 → 重送 → 核准通知,確認全部通過
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-02
@@ -0,0 +1,53 @@
# Design
## Context
- 共用約定見 `plan-system-roadmap/design.md`(D3 技術選型、D7 時區、D9 風格稿差異中「首頁額度卡」一項)。
- 首頁只讀取前面 changes 已建立的資料:案件與狀態、部門月結與分配、發放紀錄、後台截止日與平台清單、人數快照。視覺以 `docs/風格2_首頁.png` 為準。
## Goals / Non-Goals
**Goals:**
- 每個角色區塊是獨立的伺服器端查詢,權限在查詢層過濾,不靠前端隱藏。
- 額度與金額的呈現規則(參考值、預估/最終)集中在共用元件,與其他頁面一致。
**Non-Goals:**
- 圖表型分析與歷史趨勢(介面規劃 P1「Dashboard 圖表/進度卡」日後再評估)。
- 通知中心(`add-notifications`);首頁只顯示由資料推導的提醒,不發送通知。
- 「使用說明/常見問題」內容頁(由 `add-app-shell` 處理)。
## Decisions
### 1. 頁面組成
`/dashboard` 為 Server Component,依 session 角色平行載入 `getEmployeeDashboard(userId)`、`getManagerDashboard(departmentId)`、`getAdminDashboard(month)`,各自回傳已格式化前的原始數值;區塊元件放在 `app/dashboard/_sections/`。替代方案:前端打多支 API 組裝 → 多次往返且權限邏輯分散。
### 2. 時程與月份推導
純函式 `resolveCurrentCycle(today, deadlines)`(Asia/Taipei):今天在刷卡月份次月 20 日(含)前,「目前適用刷卡月份」為上個月與本月並存;首頁主要顯示「本月刷卡」的截止日,並在上個月仍可申請(今天 ≤ 20 日)時一併提醒上個月截止。部長截止倒數取最早一個未提交月結的月份。以 Vitest 覆蓋月底、跨年與截止當天。
> spec 的 2026/10/01 案例:本月刷卡為 10 月 → 2026/11/20、2026/11/25、2026/12;9 月截止 2026/10/20 亦會出現在提醒中(員工仍可申請 9 月)。
### 3. 額度參考值
`已通過可補助總額` = 該部門該月狀態 ∈ {審核通過, 待月結, 已提交, 最終核定, 已發放} 的案件,依申請人加總後套用 `settlement-calculation` 的個人可補助計算(同一純函式,確保與月結一致)。上限沿用月結計算的上限函式。呈現用 `add-app-shell` 的 `QuotaCard`,新增 `variant="reference"` 以固定附上「參考」標籤與說明文字;超過上限時進度條封頂並顯示「將依比例分配」。
### 4. 金額標示
新增(或沿用)`SubsidyAmount` 元件:輸入案件狀態與金額,月結提交前顯示「預估」+ 50% 試算,提交後顯示「最終」+ 分配金額。最近申請表、我的申請、案件詳情共用。
### 5. 視覺
- 依風格稿:淺暖色主視覺區(問候、標語、開始申請按鈕)、白色圓角卡片、深藍主色、狀態膠囊標籤;文案「審核中」依介面規劃改為「待審核」。
- 主視覺插圖與便利貼/書本照片為裝飾素材:MVP 使用可授權的插圖或純 CSS 漸層替代,素材確定後替換,不影響功能。
- AI 平台圖示:使用各平台官方提供的品牌資源,或以中性圖示+文字替代,避免授權問題。
### 6. 效能
資料量小(內部員工),每個區塊單一聚合查詢;不加快取。若日後部門數或案件量增加,再加入短時間快取。
## Risks / Trade-offs
- [員工把參考值誤解為保證額度] → 參考標籤與說明文字固定綁在 `QuotaCard` reference 變體,無法單獨移除;並列入 Playwright 驗證。
- [主管兼員工、管理者兼主管時首頁過長] → 區塊依角色順序排列,管理區塊在前、個人區塊在後,可收合。
- [品牌圖示與照片素材授權] → 先用替代素材,素材確認列為待辦,不阻擋功能驗收。
@@ -0,0 +1,27 @@
# Proposal
## Why
登入後的首頁(FE-01)要讓各角色第一眼看到「要做的事」:員工要知道本月申請狀態與截止日,主管要知道待審件數與月結截止,管理者要知道各部門提交與待發放狀況(規格 §12–13、介面規劃 §8)。申請、審核、月結與發放功能完成後才有資料可彙整,所以首頁放在 Phase 1 最後一步。首頁同時是最容易讓人誤以為部門額度「先到先得」的地方,需要明確規範呈現方式。
## What Changes
- 新增 `/dashboard`,依登入者角色組合卡片;具多重角色者顯示各角色區塊。
- 員工區塊(依 `風格2_首頁.png` 視覺):問候主視覺與「開始申請」CTA、部門本月補助使用情況(參考值)、支援的 AI 工具、重要時程提醒(員工申請截止、部長提交截止、薪資發放月)、待補件提醒、最近申請紀錄(含預估/最終補助與狀態)。
- 主管區塊:待審件數、待補件件數、部門本月額度使用(參考值)、距月結截止剩餘天數、最近待處理案件。
- 管理者區塊:已提交/待提交部門數、全公司預估補助、待核定部門、待發放人數與金額、異常提醒。
- 額度呈現規範:以「目前已通過可補助總額/部門月上限」標示「參考」,並註明實際補助於月結後確認;不使用未加說明的「剩餘可用額度」。預估金額標「預估」,月結提交後金額標「最終」。
## Capabilities
### New Capabilities
- `dashboard`: 依角色彙整的登入首頁,包含待辦、時程、額度參考值與最近案件的呈現規則。
### Modified Capabilities
<!-- 無 -->
## Impact
- 依賴 Phase 1 前面所有 changes 的資料:案件與狀態(`add-subsidy-application`、`add-manager-review`)、月結與上限(`add-department-settlement`)、核定與發放(`add-company-settlement-and-payout`)、截止日與平台清單(`add-rule-settings`)、共用元件與導覽(`add-app-shell`)。
- 只讀取資料,不新增寫入流程;新增彙總查詢。
- 視覺資產:首頁主視覺插圖與 AI 平台圖示(需確認可用的授權素材)。
@@ -0,0 +1,110 @@
# Spec Delta
## Purpose
定義登入後首頁依角色顯示的內容與呈現規則,讓員工、主管、管理者一進系統就看到自己的待辦、截止時程與案件進度,並避免部門額度被誤解為先到先得(規格 §13、介面規劃 §8、§14)。
## ADDED Requirements
### Requirement: 依角色組合首頁內容
系統 SHALL 在使用者登入後導向 `/dashboard`,並只顯示其角色有權限的區塊:一般員工看員工區塊;部門主管另看所屬部門的主管區塊;管理者另看全公司管理區塊。系統 MUST NOT 在首頁顯示使用者無權存取的部門或他人資料。
#### Scenario: 一般員工
- **WHEN** 設計部員工王小明登入
- **THEN** 首頁只顯示員工區塊,且其中只有他本人的案件
#### Scenario: 主管兼申請人
- **WHEN** 設計部主管登入
- **THEN** 首頁同時顯示其個人員工區塊與設計部的主管區塊,不顯示其他部門資料
#### Scenario: 管理者
- **WHEN** 管理者登入
- **THEN** 首頁顯示全公司管理區塊
### Requirement: 員工區塊內容
員工區塊 SHALL 包含:問候語與「開始申請」按鈕(前往 `/applications/new`)、部門本月補助使用情況、支援的 AI 工具(依後台平台清單)、重要時程提醒、待補件提醒、最近申請紀錄(申請日期、平台/方案、付款金額、補助金額、狀態、查看詳情),以及本月已送出件數與預估補助。
#### Scenario: 開始申請
- **WHEN** 員工在首頁按「開始申請」
- **THEN** 系統前往新增申請頁
#### Scenario: 最近申請紀錄
- **WHEN** 員工有 5 筆以上申請
- **THEN** 首頁列出最近 3 筆並提供「查看全部」前往 `/applications`
#### Scenario: 無申請
- **WHEN** 員工從未申請
- **THEN** 最近申請區塊顯示空狀態與「開始申請」引導
### Requirement: 待補件醒目提醒
當員工有「待補件」案件時,員工區塊 SHALL 以醒目樣式顯示待補件件數、主管意見摘要與「前往補件」連結,並位於最近申請紀錄之前。
#### Scenario: 有待補件
- **WHEN** 王小明有 1 筆待補件案件
- **THEN** 首頁顯示待補件提醒,含主管意見摘要與前往該案件的連結
### Requirement: 重要時程提醒
首頁 SHALL 顯示目前適用月份的員工申請截止日(刷卡月份次月 20 日)、部長提交截止日(次月 25 日)與預計薪資發放月份,日期依後台截止日參數計算,格式為 `YYYY/MM/DD`(含星期)或 `YYYY/MM`。
#### Scenario: 10 月份時程
- **WHEN** 今天是 2026/10/01
- **THEN** 時程提醒顯示員工申請截止 2026/11/20、部長提交截止 2026/11/25、薪資發放 2026/12
#### Scenario: 已過申請截止
- **WHEN** 今天是 2026/11/21
- **THEN** 時程提醒改以 11 月刷卡的截止日(2026/12/20、2026/12/25、2027/01)為主,10 月僅在月結未完成時顯示部長提交截止
### Requirement: 部門額度以參考值呈現
首頁顯示部門額度時 SHALL 呈現「目前已通過可補助總額/部門月上限」與使用百分比,並 MUST 標示「參考」及說明「實際補助於當月結算後依全體通過案件與部門額度統一確認,可能因其他申請而變動」。系統 MUST NOT 以未加上述說明的「剩餘可用額度」呈現,也 MUST NOT 暗示先申請者優先取得額度。已通過可補助總額只計入該部門該月「審核通過」以後狀態的案件。
#### Scenario: 顯示參考額度
- **WHEN** 設計部 10 月已通過可補助總額 NT$3,250、月上限 NT$10,000
- **THEN** 額度卡顯示「NT$3,250/NT$10,000(參考)」、已使用 32.5%,並附月結後確認的說明
#### Scenario: 已超過月上限
- **WHEN** 已通過可補助總額 NT$13,000 超過月上限 NT$10,000
- **THEN** 額度卡顯示超過上限,並說明月結時將依比例分配,不顯示負數剩餘額度
#### Scenario: 尚無人數快照
- **WHEN** 該月尚未建立部門人數快照
- **THEN** 額度卡顯示「本月額度尚未設定」,不顯示百分比
### Requirement: 預估與最終金額區隔
首頁所有補助金額 SHALL 依案件狀態標示:月結提交前顯示「預估」(50% 試算),提交後顯示「最終」(月結分配結果)。金額格式 MUST 為 NT$ 加千分位。
#### Scenario: 預估金額
- **WHEN** 案件狀態為待主管審核,支付 NT$660
- **THEN** 最近申請列顯示補助「預估 NT$330」
#### Scenario: 最終金額
- **WHEN** 案件已提交月結,最終補助 NT$346
- **THEN** 最近申請列顯示補助「最終 NT$346」
### Requirement: 主管區塊內容
主管區塊 SHALL 顯示所屬部門的待審件數、待補件件數、本月額度使用(同參考值規範)、距部長提交截止剩餘天數、目前月結狀態,以及最近 5 筆待處理案件(連往部門審核)。
#### Scenario: 待處理摘要
- **WHEN** 設計部有 3 筆待主管審核、1 筆待補件,今天 2026/11/22
- **THEN** 主管區塊顯示待審 3、待補件 1、距 10 月月結截止剩 3 天,並列出待審案件
#### Scenario: 月結已提交
- **WHEN** 設計部 10 月月結已提交
- **THEN** 主管區塊顯示 10 月月結「已提交」,不再顯示其截止倒數
### Requirement: 管理者區塊內容
管理者區塊 SHALL 顯示所選月結月份的已提交部門數/部門總數、待提交部門數、全公司預估補助(未提交部門以已通過可補助總額估算)、待核定部門數、待發放人數與金額,以及異常提醒(逾期未提交、逾期提交、缺少人數快照),並提供前往全公司月結與發放管理的連結。
#### Scenario: 管理者摘要
- **WHEN** 2026/10 有 9 個部門,7 個已提交、其中 5 個已核定,待發放 46 人
- **THEN** 管理者區塊顯示已提交 7/9、待提交 2、待核定 2、待發放 46 人與金額
#### Scenario: 異常提醒
- **WHEN** 2026/11/26 行銷部 10 月月結仍未提交
- **THEN** 管理者區塊列出「行銷部 10 月逾期未提交」並連往該部門月結詳情
### Requirement: 首頁響應式版面
首頁 SHALL 在 Desktop 以多欄卡片呈現,在 Mobile 轉為單欄、表格轉為卡片清單,且不出現水平捲動或文字溢出。
#### Scenario: Mobile 檢視
- **WHEN** 員工以 375px 寬的手機開啟首頁
- **THEN** 卡片單欄排列,最近申請以卡片清單呈現,頁面無水平捲動
@@ -0,0 +1,20 @@
# Tasks
## 1. 推導邏輯
- [ ] 1.1 實作 `resolveCurrentCycle`(目前刷卡月份、申請截止、部長截止、發放月份,Asia/Taipei、跨年),並以 Vitest 驗證 2026/10/01、2026/11/21、截止當天與 12 月跨年案例
- [ ] 1.2 實作部門已通過可補助總額(重用 `settlement-calculation` 個人可補助與上限函式、狀態篩選),並以單元測試驗證 NT$3,250/10,000 → 32.5%、超過上限、缺人數快照
## 2. 資料查詢
- [ ] 2.1 實作 `getEmployeeDashboard`(本月件數、預估補助、待補件與主管意見摘要、最近 3 筆),並以整合測試驗證只回傳本人資料
- [ ] 2.2 實作 `getManagerDashboard`(待審、待補件、額度參考值、截止倒數、月結狀態、最近 5 筆待處理),並以整合測試驗證只含本部門且月結已提交時不回傳倒數
- [ ] 2.3 實作 `getAdminDashboard`(已提交/待提交、預估補助、待核定、待發放、異常),並以整合測試驗證 7/9、待核定 2、待發放 46 人與逾期未提交異常
## 3. 首頁元件與頁面
- [ ] 3.1 為 `QuotaCard` 新增 reference 變體(固定「參考」標籤與說明、超過上限封頂與比例分配提示)並新增 `SubsidyAmount` 預估/最終元件,以元件測試驗證標籤與說明一定出現
- [ ] 3.2 建立 `/dashboard` 頁與員工區塊(問候主視覺、開始申請、額度卡、支援 AI 工具、時程提醒、待補件提醒、最近申請、空狀態),並以 Playwright 驗證員工只看到本人資料與「開始申請」導向
- [ ] 3.3 建立主管區塊與管理者區塊(含連往部門審核、全公司月結、發放管理),並以 Playwright 驗證主管兼申請人與管理者的區塊組合
- [ ] 3.4 完成 RWD(Desktop 多欄、Mobile 單欄與卡片清單),並以 Playwright 在 375px 與 1440px 驗證無水平捲動
- [ ] 3.5 將登入後預設導向設為 `/dashboard`,並以 Playwright 驗證三種角色登入後落點正確
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-02
@@ -0,0 +1,55 @@
# Design
## Context
- 技術選型與共用約定見 `plan-system-roadmap/design.md`(D3 Next.js + SQLite + Drizzle + Zod;D4 金額整數;D7 Asia/Taipei;D8 稽核與鎖定;Decisions Log)。
- 依賴 change 2 的部門、部門類型(一般/研發)、人員所屬部門,以及 change 3 的操作紀錄寫入介面。
- 月結(change 9)尚未存在;快照鎖定需要知道「某部門某月月結是否已提交」。
## Goals / Non-Goals
**Goals:**
- 提供單一的參數讀取入口:`取得生效參數(時間點)`、`推導截止日(刷卡日期)`、`取得部門月上限(部門, 月份)`,後續 change 只呼叫它們。
- 參數與快照的每次異動都可追溯,不覆寫歷史。
**Non-Goals:**
- 不做 HR 系統同步(change 16)。
- 不做參數套用到歷史月份的更正(change 14)。
- 月結本身的計算與提交(change 9)。
## Decisions
### 參數以「整份快照版本」儲存,而非逐欄位異動
每個版本存一份完整參數(JSON 欄位經 Zod schema 驗證)加上 `effective_at`、`created_by`、`reason`。查詢某時間點只要取 `effective_at <= t` 的最新一筆。
替代方案:每個參數一列、各自版本化——查詢「某時間點完整參數」需要多次合併,且月結快照要記錄多個版本 ID,較複雜。
### 版本只新增不修改
版本表無 update/delete 路徑;未來生效的版本若要取消,以再新增一個版本覆蓋的方式處理,避免歷史被改動。
### 截止日以「刷卡月份結束時生效的版本」推導
同一刷卡月份的所有案件使用同一組截止日,避免月中改參數導致同月案件截止日不一致。日期計算以 Asia/Taipei 進行,存 UTC。
### 人數快照的建立方式:懶建立+手動觸發
單機 Next.js 不另設排程器;在該月 1 日之後任何需要快照的讀取(月上限查詢、設定頁開啟)時,若不存在就以「該月 1 日 00:00 的人員所屬部門」建立,並寫操作紀錄(操作者記為系統)。管理者也可在設定頁手動觸發。
- 需要 change 2 保存人員所屬部門的生效期間(到職/轉調/離職日期),才能算出「1 日當時」的人數。若 change 2 只存目前部門,則快照以建立當下人數計算,由管理者人工調整——此為 change 2 propose 時需確認的依賴。
- 替代方案:外部 cron 呼叫 API——增加部署元件,對單機內部系統不划算。
### 快照鎖定以「月結狀態查詢介面」解耦
本 change 定義快照的 `locked` 狀態與鎖定/解鎖操作,由 change 9 在主管提交月結時呼叫鎖定、change 10 在管理者退回月結時呼叫解鎖。本 change 內只實作介面與調整時的鎖定檢查。
### 部門月上限即時計算、不另存
月上限 = 快照人數 × 生效每人額度,於查詢時計算;月結提交時由 change 9 把當時的數值與參數版本 ID 一起存入月結結果。
## Risks / Trade-offs
- [懶建立導致月初快照延後建立,期間人員異動] → 若 change 2 有部門生效期間則以 1 日當時資料計算不受影響;否則以人工調整補正並留痕。
- [管理者設定未來生效版本後忘記] → 設定頁明確標示「排定生效」版本與生效時間。
- [JSON 欄位難以用 SQL 查詢單一參數] → 參數數量少,讀取一律經應用層 schema 解析;不需要以 SQL 篩選參數值。
## Migration Plan
Drizzle migration 建立參數版本表、快照表、快照調整紀錄表;seed 腳本建立初始參數版本(規格 §16 預設值,取整為無條件捨去)。回滾:刪除新增資料表(無其他 change 依賴前)。
## Open Questions
- change 2 是否保存人員所屬部門的生效期間(影響快照是否能精確反映 1 日人數),在 change 2 propose/實作時確認。
@@ -0,0 +1,29 @@
# Proposal
## Why
補助比例、部門每人額度、申請與月結截止日、平台清單、取整方式、附件限制都是公司制度參數(規格 §16),之後的申請、審核與月結都要讀取它們,不能寫死在程式裡。部門月上限又依賴「部門計算人數」,規格 §15.1 要求以每月快照計算,避免月中人事異動讓額度持續變動。這兩項必須在申請功能(change 7)與月結(change 9)之前完成。
## What Changes
- 新增後台「制度參數」設定:一般部門每人月額度(預設 NT$500)、研發部每人月額度(NT$1,000)、個人補助比例(50%)、取整方式(預設無條件捨去,可改四捨五入)、員工申請截止(刷卡月份次月 20 日 23:59:59,Asia/Taipei)、主管月結提交截止(次月 25 日)、主要平台清單(ChatGPT/Claude/Gemini,「其他」永遠可選)、附件允許格式(PDF/JPG/PNG)與單檔上限(10 MB)。
- 參數每次變更都建立新版本,記錄生效時間、操作者與變更內容,舊版本保留不覆寫;提供「依時間點查詢當時生效版本」的能力,供月結快照使用。
- 新增每月「部門計算人數快照」:以每月 1 日為基準建立各部門人數,可人工調整(必填原因並留痕);該部門該月月結提交後快照鎖定。
- 依部門類型(一般/研發)與快照人數算出部門月上限的查詢能力。
- 新增後台設定頁 `/admin/settings`(FE-09),僅管理者與系統管理員可進入。
- 不設個人月補助上限(Decisions Log)。
## Capabilities
### New Capabilities
- `rule-settings`: 補助制度參數的維護、版本化與依時間點查詢,以及據以推導的截止日。
- `headcount-snapshot`: 各部門每月計算人數快照的建立、人工調整、鎖定與部門月上限計算。
### Modified Capabilities
<!-- 無 -->
## Impact
- 依賴 change 2 `add-identity-and-access`(部門、部門類型、角色)與 change 3 `add-audit-trail`(參數與快照異動留痕)。
- 新增資料表:制度參數版本、部門月人數快照與調整紀錄。
- 後續 change 7(申請截止、比例、平台、附件限制)、change 6(附件格式/大小)、change 9(月上限、取整、參數快照)讀取本 change 提供的查詢。
@@ -0,0 +1,66 @@
# Spec Delta
## Purpose
以每月固定基準日建立各部門「計算人數」快照,作為部門月上限的依據,避免月中到職、離職或轉部門讓額度持續變動,並保留人工調整與鎖定紀錄。
## ADDED Requirements
### Requirement: 建立每月人數快照
系統 SHALL 為每個部門、每個月份建立一筆計算人數快照,人數以該月 1 日 00:00(Asia/Taipei)時隸屬該部門的在職人員數計算(規格 §15.1)。快照 SHALL 在該月 1 日之後首次需要時(查詢月上限或開啟設定頁)自動建立,管理者亦 SHALL 可手動觸發建立;無論何時建立,人數皆以 1 日 00:00 的所屬部門計算。同一部門同一月份 MUST 只有一筆快照。
#### Scenario: 月初後首次需要時自動建立
- **WHEN** 2026/11/01 00:00 設計部有 20 位在職人員,2026/11/03 管理者首次開啟 2026/11 的人數快照
- **THEN** 系統建立設計部 2026/11 快照,人數為 20
#### Scenario: 月中到職不影響當月快照
- **WHEN** 2026/11/10 有一位新人加入設計部
- **THEN** 設計部 2026/11 快照人數仍為 20
#### Scenario: 重複建立
- **WHEN** 管理者對已有快照的部門與月份再次觸發建立
- **THEN** 系統不建立第二筆快照,並提示該月份快照已存在
### Requirement: 人工調整快照人數
管理者 SHALL 可調整未鎖定快照的人數,人數 MUST 為非負整數,且 MUST 填寫調整原因。每次調整 SHALL 保留調整前後人數、原因、操作者與時間,並寫入操作紀錄;歷次調整紀錄 MUST NOT 被刪除。
#### Scenario: 調整人數
- **WHEN** 管理者把研發部 2026/11 快照由 20 調整為 21,原因填「11/01 到職者系統晚建檔」
- **THEN** 快照人數變為 21,調整紀錄顯示 20 → 21、原因、操作者與時間
#### Scenario: 未填原因
- **WHEN** 管理者修改人數但未填原因
- **THEN** 系統拒絕儲存並要求填寫原因
### Requirement: 快照鎖定
當某部門某月份的月結已由主管提交後,該部門該月份的快照 SHALL 鎖定,MUST NOT 再被調整;若管理者退回該月結,快照 SHALL 解除鎖定。後續組織異動 MUST NOT 改變已存在的快照(規格 §17)。
#### Scenario: 已提交月結後調整
- **WHEN** 設計部 2026/10 月結已提交,管理者嘗試調整設計部 2026/10 快照
- **THEN** 系統拒絕並提示該月份月結已提交,需先退回月結
#### Scenario: 部門改名或人員轉調
- **WHEN** 2026/12 一位員工由設計部轉調至研發部
- **THEN** 設計部與研發部 2026/10、2026/11 的快照人數不變
### Requirement: 部門月上限計算
系統 SHALL 以「快照人數 × 該月生效之部門類型每人月額度」計算部門月上限:一般部門使用一般部門每人月額度,研發部使用研發部每人月額度(規格 §7.2)。快照不存在時 MUST NOT 回傳月上限,而 SHALL 回傳「尚未建立人數快照」。
#### Scenario: 一般部門月上限
- **WHEN** 設計部(一般部門)2026/10 快照人數為 20,每人額度 NT$500
- **THEN** 部門月上限為 NT$10,000
#### Scenario: 研發部月上限
- **WHEN** 研發部 2026/10 快照人數為 2,每人額度 NT$1,000
- **THEN** 部門月上限為 NT$2,000
#### Scenario: 無快照
- **WHEN** 查詢一個尚未建立 2026/10 快照之部門的月上限
- **THEN** 系統回傳「尚未建立人數快照」而非數值
### Requirement: 快照檢視
管理者 SHALL 可在後台設定頁依月份檢視所有部門的快照人數、部門類型、算出的月上限、鎖定狀態與調整紀錄;其他角色 MUST NOT 修改快照。
#### Scenario: 依月份檢視
- **WHEN** 管理者在後台設定頁選擇 2026/10
- **THEN** 列出每個部門的快照人數、類型、月上限、是否鎖定,可展開查看調整紀錄
@@ -0,0 +1,88 @@
# Spec Delta
## Purpose
管理 AI 補助制度的可調參數(額度、比例、取整、截止日、平台、附件限制),確保每次異動都有版本紀錄,並能查出任一時間點生效的參數供申請與月結使用。
## ADDED Requirements
### Requirement: 制度參數項目與預設值
系統 SHALL 提供以下制度參數,並在系統初始化時以預設值建立第一個版本:一般部門每人月額度 NT$500、研發部每人月額度 NT$1,000、個人補助比例 50%、取整方式「無條件捨去」、員工申請截止日為刷卡月份次月 20 日、主管月結提交截止日為刷卡月份次月 25 日、主要平台 ChatGPT/Claude/Gemini、附件允許格式 PDF/JPG/PNG、附件單檔上限 10 MB(規格 §16)。系統 SHALL NOT 提供個人月補助上限參數。
#### Scenario: 初始化後的預設參數
- **WHEN** 系統首次初始化完成,管理者開啟後台設定頁
- **THEN** 頁面顯示上述各參數的預設值,且版本紀錄中有一筆初始版本
#### Scenario: 無個人上限
- **WHEN** 管理者檢視所有可設定的參數
- **THEN** 參數清單中不包含個人月補助上限
### Requirement: 參數值驗證
系統 SHALL 拒絕不合法的參數值並顯示錯誤:每人月額度 MUST 為正整數(新台幣元);補助比例 MUST 介於 1% 到 100% 之間的整數百分比;取整方式 MUST 為「無條件捨去」或「四捨五入」;截止日 MUST 為 1 到 28 之間的日期且主管截止日 MUST 晚於員工截止日;平台清單 MUST 至少一項且名稱不重複;附件單檔上限 MUST 為 1 到 50 MB 的整數;允許格式 MUST 至少一項且只能從 PDF/JPG/PNG 中選擇。
#### Scenario: 主管截止日早於員工截止日
- **WHEN** 管理者把主管月結截止日設為 18 日,員工申請截止日仍為 20 日,並按下儲存
- **THEN** 系統拒絕儲存,顯示「主管提交截止日必須晚於員工申請截止日」,且不產生新版本
#### Scenario: 額度輸入小數
- **WHEN** 管理者把一般部門每人月額度輸入為 500.5
- **THEN** 系統拒絕儲存並標示該欄位須為正整數
### Requirement: 參數變更版本化
每次儲存參數變更 SHALL 建立新的參數版本,記錄完整參數內容、生效時間、操作者與變更原因;既有版本 MUST NOT 被修改或刪除。生效時間預設為儲存當下,管理者 MAY 指定未來的生效時間,但 MUST NOT 指定過去的時間。每次變更 SHALL 寫入操作紀錄。
#### Scenario: 儲存變更產生新版本
- **WHEN** 管理者把取整方式由「無條件捨去」改為「四捨五入」,填寫原因後儲存
- **THEN** 系統建立新版本並立即生效,舊版本仍可在版本紀錄中檢視,操作紀錄記下操作者、時間與前後值
#### Scenario: 指定過去的生效時間
- **WHEN** 管理者嘗試把新版本的生效時間設為昨天
- **THEN** 系統拒絕儲存並提示生效時間不得早於現在
#### Scenario: 變更原因必填
- **WHEN** 管理者修改參數但未填寫變更原因就按儲存
- **THEN** 系統拒絕儲存並要求填寫原因
### Requirement: 依時間點查詢生效參數
系統 SHALL 能回傳任一時間點生效的參數版本(生效時間不晚於該時間點的最新版本),供申請試算、截止判斷與月結快照使用。月結結果 SHALL 記錄其採用的參數版本,之後的參數變更 MUST NOT 改變已提交月結的計算結果。
#### Scenario: 查詢變更前的時間點
- **WHEN** 比例於 2026/11/01 00:00 由 50% 改為 40%,系統查詢 2026/10/15 的生效參數
- **THEN** 回傳比例 50% 的版本
#### Scenario: 未來生效版本尚未生效
- **WHEN** 管理者建立一個 2026/12/01 生效的新版本,現在是 2026/11/10
- **THEN** 現在查詢生效參數仍回傳原版本,後台版本紀錄標示新版本為「排定生效」
### Requirement: 截止日推導
系統 SHALL 依刷卡日期所屬月份與生效參數推導兩個截止時刻:員工申請截止為刷卡月份次月「員工截止日」23:59:59、主管月結提交截止為刷卡月份次月「主管截止日」23:59:59,皆以 Asia/Taipei 時區計算。推導 SHALL 使用該刷卡月份結束時生效的參數版本。
#### Scenario: 10 月刷卡的截止日
- **WHEN** 刷卡日期為 2026/10/05,參數為預設值
- **THEN** 員工申請截止為 2026/11/20 23:59:59,主管月結提交截止為 2026/11/25 23:59:59(Asia/Taipei)
#### Scenario: 跨年的截止日
- **WHEN** 刷卡日期為 2026/12/31
- **THEN** 員工申請截止為 2027/01/20 23:59:59
### Requirement: 平台清單
系統 SHALL 以參數中的主要平台清單作為申請表單的平台選項,並 SHALL 永遠附加「其他」選項;「其他」MUST NOT 可被移除。從清單移除的平台 MUST NOT 影響既有申請上記錄的平台名稱。
#### Scenario: 新增平台
- **WHEN** 管理者在平台清單加入「Perplexity」並儲存
- **THEN** 新版本生效後,申請表單平台選項為 ChatGPT、Claude、Gemini、Perplexity、其他
#### Scenario: 移除平台不影響舊案件
- **WHEN** 管理者從清單移除「Gemini」,而已有申請的平台為 Gemini
- **THEN** 既有申請仍顯示 Gemini,新申請的選項中不再出現 Gemini
### Requirement: 後台設定頁存取權限
後台設定頁(`/admin/settings`)SHALL 只允許管理者與系統管理員檢視與修改;其他角色進入時 MUST 被拒絕,且導覽中不顯示該頁。
#### Scenario: 一般員工直接輸入網址
- **WHEN** 一般員工直接開啟 `/admin/settings`
- **THEN** 系統拒絕存取並顯示無權限頁面,不回傳任何參數資料
#### Scenario: 管理者檢視版本紀錄
- **WHEN** 管理者開啟後台設定頁的版本紀錄
- **THEN** 依生效時間由新到舊列出各版本、操作者、變更原因與差異欄位
@@ -0,0 +1,29 @@
# Tasks
## 1. 資料模型與 migration
- [ ] 1.1 以 Drizzle 定義制度參數版本表(完整參數 JSON、effective_at、created_by、reason、created_at),執行 migration 並確認資料表建立成功
- [ ] 1.2 定義部門月人數快照表(部門、月份唯一鍵、人數、locked)與快照調整紀錄表,執行 migration 並以單元測試確認同一部門同月無法建立兩筆
- [ ] 1.3 撰寫 seed 建立初始參數版本(規格 §16 預設值、取整無條件捨去、無個人上限),執行 seed 後查詢確認內容正確
## 2. 參數服務
- [ ] 2.1 以 Zod 定義參數 schema 與驗證規則(額度正整數、比例 1–100、截止日 1–28 且主管 > 員工、平台不重複且至少一項、附件 1–50 MB 與格式限 PDF/JPG/PNG),並以 Vitest 涵蓋 spec 中的錯誤情境
- [ ] 2.2 實作「儲存新版本」(原因必填、生效時間不得早於現在、寫入 audit-trail),以 Vitest 驗證舊版本不被修改且操作紀錄寫入
- [ ] 2.3 實作「取得某時間點生效參數」,以 Vitest 驗證變更前時間點與排定生效版本兩個情境
- [ ] 2.4 實作「推導截止日(刷卡日期)」使用刷卡月份結束時的版本與 Asia/Taipei,以 Vitest 驗證 2026/10/05 → 11/20、11/25 23:59:59 及 2026/12/31 → 2027/01/20
- [ ] 2.5 實作平台選項查詢(主要平台+固定「其他」),以 Vitest 驗證「其他」無法移除且移除平台不影響既有資料
## 3. 人數快照服務
- [ ] 3.1 實作快照建立(以該月 1 日 00:00 Asia/Taipei 的部門人員計算;懶建立+手動觸發;重複建立回傳已存在),以 Vitest 驗證月中到職不影響當月快照
- [ ] 3.2 實作人工調整(非負整數、原因必填、保存前後值、寫 audit-trail、鎖定時拒絕),以 Vitest 驗證各情境
- [ ] 3.3 實作鎖定/解鎖介面供 change 9/10 呼叫,以 Vitest 驗證鎖定後調整被拒、解鎖後可調整
- [ ] 3.4 實作部門月上限查詢(一般/研發每人額度 × 快照人數;無快照回傳「尚未建立人數快照」),以 Vitest 驗證 20×500=10,000、2×1,000=2,000 與無快照情境
## 4. 後台設定頁 FE-09
- [ ] 4.1 建立 `/admin/settings` 頁面與伺服器端權限檢查(僅管理者、系統管理員),以 Playwright 驗證一般員工直接輸入網址被拒且無資料外洩
- [ ] 4.2 實作參數編輯表單(inline 錯誤、原因必填、生效時間選擇、儲存確認視窗),以 Playwright 驗證儲存後產生新版本並顯示於版本紀錄
- [ ] 4.3 實作版本紀錄清單(新到舊、操作者、原因、差異欄位、排定生效標示),以 Playwright 驗證排定生效版本正確標示
- [ ] 4.4 實作人數快照分頁(月份切換、人數、類型、月上限、鎖定狀態、調整紀錄展開、手動建立與調整),以 Playwright 驗證調整流程與鎖定時的錯誤提示
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-02
@@ -0,0 +1,54 @@
# Design
## Context
- MVP 已有:部門月結(含參數快照)、最終核定、發放管理與匯出、管理者退回月結(未核定前)。見 roadmap D4、D5、D8。
- 技術選型見 roadmap D3(Next.js + SQLite + Drizzle);多筆寫入使用單一 `BEGIN IMMEDIATE` 交易。
- 規格 §20「核定後發放失敗或更正流程」尚未由公司確認——本設計為草案,Open Questions 中的決策可能調整 spec。
## Goals / Non-Goals
**Goals:**
- 原月結結果、原核定金額與參數快照永遠唯讀;任何事後變動都是附加紀錄。
- 薪資作業只需看「某發放月份的清單」,即可知道要發、要追回什麼。
**Non-Goals:**
- 薪資系統自動扣回或入帳(Phase 3 `integrate-payroll-export`)。
- 重新開啟已核定月結重算比例分配(以更正處理,不重算)。
- 多層簽核流程(見 Open Questions)。
## Decisions
### C1. 更正為獨立的附加紀錄(ledger 模式)
新增 `settlement_corrections` 表:參照個人月結結果、類型、帶正負號的整數金額、目標發放月份、原因、狀態(有效/已取消/已發放)、建立者與時間。更正後金額 = 原核定 + Σ 有效與已發放更正。替代方案:直接改寫月結結果並記 diff——違反 §15.5「不覆寫」,且匯出歷史會不一致。
### C2. 撤銷與改期都轉換成金額語意
- 撤銷未發放:建立 −原金額 的更正,排在原發放月份,使該月淨額為 0。
- 撤銷已發放:建立 −原金額 追回,排在管理者指定的後續發放月份。
- 改期:原發放月份該筆標記發放失敗(不計已發放),並在新月份建立 +原金額 的改期項目。
如此發放清單只需加總「排入該月份的原核定與更正項目」,邏輯單一。
### C3. 更正不受部門月上限限制,但顯示警示
事後補發可能使部門該月更正後合計超過月上限(例如原先計算錯誤)。草案:允許建立,但介面顯示「更正後合計超過部門月上限 NT$x」警示並寫入稽核紀錄。是否應硬性阻擋列為 Open Question。
### C4. 只有管理端可建立,單人完成
沿用 MVP 角色:管理者/人資財務可建立與取消更正,不需第二人覆核(草案)。
### C5. 匯出欄位擴充向後相容
匯出保留 MVP 欄位順序,新增欄位附加在最後(類型、來源月份、更正編號),降低既有薪資作業試算表的調整成本。
## Risks / Trade-offs
- [追回(負數)無法在薪資實際扣回] → 匯出清楚標示,由薪資作業人工處理;Phase 3 整合時再自動化。
- [更正後合計超過月上限造成制度爭議] → C3 警示並留痕;待使用者決定是否硬擋。
- [單人建立更正缺乏覆核] → 全部寫入操作紀錄,可在稽核頁篩選;如需覆核另開 change。
## Open Questions
以下需使用者/公司確認(規格 §20 第 7 項),答案可能修改 spec:
1. 已發放後的追回:從後續薪資「其他獎金」扣回,還是另行請員工繳回?(草案:排入後續發放月份以負數呈現,由薪資作業處理)
2. 更正後部門合計超過月上限時是否允許?(草案:允許但警示)
3. 建立更正是否需要第二位管理者覆核?(草案:不需要)
4. 發放失敗改期是否限定「下一個發放月份」,或可由管理者任選?(草案:任選未來月份)
5. 員工端是否需要看到更正原因全文?(草案:顯示原因)
@@ -0,0 +1,32 @@
# Proposal
## Why
規格 §15.5 與 §17 要求月結結果不可覆寫、更正須留存稽核軌跡;§20 也列出「最終核定後若薪資發放失敗或需更正之處理流程」待決。MVP(`add-company-settlement-and-payout`)只支援在最終核定前由管理者退回月結,核定或發放之後發現金額錯誤、發放失敗或須撤銷補助時,目前沒有合規的處理方式。
## What Changes
- 新增「更正紀錄」:對已最終核定或已發放的個人補助建立更正,不修改原月結結果。三種類型:
- **金額調整**:補發(正數)或追回(負數),排入指定的發放月份。
- **發放失敗改期**:原發放月份未成功發放,將該筆補助改排到後續發放月份。
- **撤銷補助**:整筆補助作廢;未發放者取消發放,已發放者產生等額追回。
- 每筆更正必填原因、記錄建立者與時間並寫入操作紀錄;更正可在尚未發放前取消(取消也留紀錄)。
- 案件與部門月結頁顯示「原核定金額、更正明細、更正後金額」;原結果保持唯讀。
- 發放管理與匯出依發放月份納入更正項目(含負數追回),並標示其來源月結與更正編號。
- 歷史月份的計算參數(比例、取整、月上限)維持月結當時的快照,不因參數改版而重算。
## Capabilities
### New Capabilities
- `settlement-correction`: 已核定/已發放補助的更正紀錄(類型、必填原因、更正後金額、取消、稽核與唯讀原結果)。
### Modified Capabilities
<!-- `company-settlement` 與 `payout-management` 由 Phase 1 change 建立且尚未 archive,本 change 以 ADDED requirements 擴充,不修改其既有 requirement -->
- `company-settlement`: 新增「部門月結詳情顯示更正明細與更正後金額」與「歷史月結參數快照不重算」。
- `payout-management`: 新增「發放清單與匯出納入更正項目」與「發放失敗標記」。
## Impact
- 依賴 Phase 1 changes archive 後實作:`company-settlement`、`payout-management`、`settlement-calculation`、`audit-trail`、`identity-access`(僅管理端可建立更正)。
- 新增資料表:更正紀錄;發放清單查詢與 Excel/CSV 匯出欄位增加(更正編號、來源月份、類型)——下游薪資作業需同步知道欄位變更。
- 完整流程中數項規則待使用者確認(見 design.md Open Questions),確認結果可能調整 spec。
@@ -0,0 +1,17 @@
# Spec Delta
## ADDED Requirements
### Requirement: 部門月結詳情顯示更正後金額
管理端檢視已最終核定的部門月結時,系統 SHALL 在每位申請人列上顯示原核定金額、更正合計與更正後金額,並提供更正明細;部門合計 SHALL 同時顯示原核定合計與更正後合計。
#### Scenario: 有更正的月結
- **WHEN** 設計部 2026/10 月結中一人有 +NT$10 的調整,管理者開啟月結詳情
- **THEN** 該列顯示原核定、+NT$10 與更正後金額,部門合計同時顯示原核定合計與更正後合計
### Requirement: 歷史月結維持參數快照
已最終核定月結的補助比例、取整方式、每人額度、部門計算人數與月上限 MUST 維持核定當時的快照;後台參數或人數快照日後變更時,系統 MUST NOT 重新計算該月結果。
#### Scenario: 參數改版後查看歷史月份
- **WHEN** 管理者把取整方式由無條件捨去改為四捨五入後,查看已核定的 2026/10 月結
- **THEN** 2026/10 的金額與顯示的計算參數仍為核定當時的值
@@ -0,0 +1,17 @@
# Spec Delta
## ADDED Requirements
### Requirement: 發放清單納入更正項目
系統 SHALL 在發放月份的發放清單與 Excel/CSV 匯出中納入排入該月份且未取消的更正項目(含負數追回與改期項目),每列 MUST 標示類型(原核定/調整/追回/改期)、來源月結月份與更正編號,且薪資名目維持「其他獎金」。
#### Scenario: 匯出含追回項目
- **WHEN** 2027/01 發放清單包含一筆原核定 NT$500 與一筆 −NT$654 追回,管理者匯出 CSV
- **THEN** 匯出檔包含兩列,分別標示類型、來源月份與更正編號,金額為 500 與 −654
### Requirement: 標記發放失敗
管理端 SHALL 能將某發放月份中的單筆補助標記為發放失敗並填寫原因;標記後該筆 MUST NOT 被視為已發放,並 SHALL 提示管理者建立發放失敗改期更正。
#### Scenario: 標記發放失敗
- **WHEN** 管理者將 2026/12 一筆補助標記為發放失敗並填寫「帳戶異常」
- **THEN** 該筆狀態為發放失敗、不計入已發放,頁面提示可建立改期更正
@@ -0,0 +1,69 @@
# Spec Delta
## Purpose
讓管理端在月結最終核定或發放之後,以獨立、可稽核的更正紀錄處理金額錯誤、發放失敗與撤銷補助,確保原月結結果永不被覆寫(規格 §15.5、§17)。
## ADDED Requirements
### Requirement: 僅能對已核定或已發放的補助建立更正
系統 SHALL 只允許管理端角色對狀態為最終核定或已發放的個人補助建立更正紀錄;對尚未最終核定的月結 MUST 改用退回月結處理,不得建立更正。
#### Scenario: 對已發放補助建立更正
- **WHEN** 管理者對狀態為已發放的個人補助建立更正
- **THEN** 系統建立更正紀錄
#### Scenario: 未核定月結不可更正
- **WHEN** 管理者對狀態為已提交(尚未最終核定)的月結中的補助建立更正
- **THEN** 系統拒絕,並提示使用「退回月結」
#### Scenario: 非管理端角色不可更正
- **WHEN** 部門主管嘗試建立更正
- **THEN** 系統拒絕該操作
### Requirement: 更正類型
每筆更正 MUST 屬於下列類型之一:金額調整(正數為補發、負數為追回,金額為非零整數元)、發放失敗改期(將原補助改排至指定的後續發放月份)、撤銷補助(未發放者取消發放,已發放者產生等額追回)。
#### Scenario: 金額調整補發
- **WHEN** 管理者對原核定 NT$346 的補助建立 +NT$10 的金額調整,排入 2027/01 發放
- **THEN** 該補助更正後金額為 NT$356,2027/01 發放清單多一筆 NT$10
#### Scenario: 撤銷已發放補助
- **WHEN** 管理者撤銷一筆已發放 NT$654 的補助
- **THEN** 系統產生 −NT$654 的追回項目,更正後金額為 NT$0
#### Scenario: 發放失敗改期
- **WHEN** 管理者對 2026/12 未成功發放的 NT$346 補助建立改期至 2027/01
- **THEN** 2027/01 發放清單包含該筆 NT$346,2026/12 該筆標示為發放失敗已改期
### Requirement: 更正必填原因並留存稽核紀錄
建立或取消更正時,系統 MUST 要求填寫原因,並記錄操作者、時間、類型、金額與目標發放月份至操作紀錄。
#### Scenario: 未填原因
- **WHEN** 管理者未填原因即送出更正
- **THEN** 系統拒絕並提示需填寫原因
### Requirement: 原月結結果不被覆寫
建立、取消更正 MUST NOT 修改原月結的計算結果、原核定金額或計算參數快照;更正後金額 SHALL 以原核定金額加總所有未取消更正計算。
#### Scenario: 原結果保持不變
- **WHEN** 管理者對一筆補助建立兩筆更正
- **THEN** 原月結結果與原核定金額仍為原值,更正後金額為原值加兩筆更正之和
### Requirement: 未發放的更正可取消
尚未在其發放月份標記已發放的更正 SHALL 能被管理端取消;取消後 MUST 保留紀錄並標示為已取消,不再計入更正後金額與發放清單。已發放的更正 MUST NOT 被取消,只能再建立反向更正。
#### Scenario: 取消未發放更正
- **WHEN** 管理者取消一筆排入 2027/01、尚未發放的 +NT$10 調整
- **THEN** 該更正標示已取消,2027/01 發放清單不再包含此筆
#### Scenario: 已發放更正不可取消
- **WHEN** 管理者嘗試取消已發放的更正
- **THEN** 系統拒絕,並提示建立反向更正
### Requirement: 案件詳情顯示更正明細
申請人與有權限的主管、管理端檢視案件詳情時,系統 SHALL 顯示原核定金額、每筆更正(類型、金額、發放月份、原因、狀態)與更正後金額。
#### Scenario: 申請人查看更正
- **WHEN** 申請人開啟有一筆金額調整的案件詳情
- **THEN** 頁面顯示原核定金額、該筆調整與更正後金額
@@ -0,0 +1,28 @@
# Tasks
## 1. 決策確認與資料模型
- [ ] 1.1 與使用者確認 design.md Open Questions 1–5,若結果與草案不同先更新 spec 與 design,並驗證 `openspec validate add-settlement-corrections --strict` 通過
- [ ] 1.2 以 Drizzle 新增 `settlement_corrections`(參照個人月結結果、類型、帶號整數金額、目標發放月份、原因、狀態、建立者、時間)及發放項目的「發放失敗」狀態,產生 migration,並驗證可套用於含 MVP 資料的 SQLite
## 2. 更正規則(domain)
- [ ] 2.1 實作更正後金額計算與類型轉換(金額調整、撤銷未發放/已發放、改期)為純函式,並以 Vitest 涵蓋 spec 的補發、撤銷、改期 scenario
- [ ] 2.2 實作建立/取消更正服務:限管理端、僅最終核定或已發放、必填原因、已發放更正不可取消、單一交易內寫入操作紀錄、原月結結果不變,並以 Vitest 驗證各拒絕情境與原結果未被修改
- [ ] 2.3 實作更正後部門合計超過月上限時的警示(依 1.1 決策:警示或阻擋),並以 Vitest 驗證
## 3. 發放管理擴充
- [ ] 3.1 發放清單依發放月份納入有效更正與改期項目,新增「標記發放失敗」操作(必填原因、不計已發放),並以 Vitest 驗證清單合計與狀態
- [ ] 3.2 擴充 Excel/CSV 匯出:新增欄位附加於最後(類型、來源月份、更正編號),負數追回正確輸出,並以 Vitest 比對匯出檔內容
- [ ] 3.3 在匯出相關文件記錄新欄位定義,並驗證範例匯出檔與文件一致
## 4. 介面
- [ ] 4.1 部門月結詳情顯示原核定、更正合計、更正後金額與明細,歷史月份顯示核定當時參數,並以 Playwright 驗證參數改版後歷史月份不變
- [ ] 4.2 管理端建立/取消更正的表單與 ConfirmDialog(類型、金額、發放月份、原因必填),並以 Playwright 驗證未填原因無法送出
- [ ] 4.3 案件詳情(員工/主管/管理端)顯示更正明細與更正後金額,並以 Playwright 驗證申請人看得到更正
## 5. 整合驗證
- [ ] 5.1 以 Playwright 跑完整流程:最終核定 → 標記已發放 → 標記一筆發放失敗 → 建立改期 → 建立追回 → 匯出新月份清單,確認金額與欄位正確且原月結結果未變
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-02
@@ -0,0 +1,53 @@
# Design
## Context
- 技術選型、金額規則、狀態機原則與 §20 決策見 `plan-system-roadmap/design.md`(D3–D9、Decisions Log);本文件只補充申請功能的做法。
- 依賴的 change(identity-access、audit-trail、rule-settings、app-shell、application-attachments)尚未實作;本 change 假設它們提供:登入者與部門、寫入操作紀錄的服務、目前生效的制度參數(比例、取整、截止日、平台清單)、共用 UI 元件、可綁定案件的附件上傳。
## Goals / Non-Goals
**Goals:**
- 驗證規則只寫一份,前端即時驗證與伺服器端驗證共用。
- 狀態轉移集中為單一模組,後續 change 只新增轉移定義而不改既有呼叫端。
- 月份、期限、試算的計算為純函式,可完整單元測試。
**Non-Goals:**
- 主管審核轉移(add-manager-review)、月結相關轉移與最終補助(add-department-settlement 之後)。
- 重複申請提醒(Phase 2 add-duplicate-detection)、通知(Phase 2)。
- 主管/管理者視角的詳情頁操作。
## Decisions
### 1. 共用驗證 schema
以 Zod 定義兩份 schema:`draftSchema`(全部欄位選填,只驗格式)與 `submitSchema`(必填與條件必填)。表單用 `submitSchema` 做即時與送出前驗證並計算錯誤數 N;Server Action 送出時再跑一次 `submitSchema` 加上期限、附件、權限檢查。替代方案「前後端各寫一次」容易漂移,被否決。
### 2. 月份、期限與試算為純函式
`applicationMonth(chargeDate)`、`submissionDeadline(chargeDate, deadlineDay)`(回傳 Asia/Taipei 次月 deadlineDay 23:59:59 的 UTC 時刻)、`estimateSubsidy(twd, ratio, rounding)`(整數運算:`twd * ratioPercent / 100` 再依 floor/half-up 取整,避免浮點)。「今日」與「現在」由呼叫端注入,方便測試跨日與跨月邊界。
### 3. 案件資料與參數快照
案件表存 TWD 金額(INTEGER)、刷卡日期(`YYYY-MM-DD`)、申請月份(`YYYY-MM`,送出時由刷卡日期計算並存入以便月結查詢)、平台、方案、原幣金額(以「分」整數存)與幣別、用途、成果、成果連結、聲明時間、`everSubmitted` 旗標(決定可否刪除)。送出時把當時生效的制度參數版本 ID 記在案件上,試算顯示與月結以該版本為準。
`applications` 表已由 `add-application-attachments` 以最小欄位(id、applicant_id、department_id、status)建立;本 change 以 migration **擴充同一張表**,不另建新表。`department_id` 在建立申請時寫入申請人當下所屬部門,之後人員調部門不改寫(見 org-directory「人員調部門」)。
### 4. 狀態機模組
以一張轉移表定義 `{from, to, action, allowedRole, requiresComment, guard}`;本 change 填入 submit、resubmit、withdraw 三筆,刪除草稿另以 guard(狀態=草稿且 `everSubmitted=false`)處理。執行轉移時於單一 SQLite 交易(`BEGIN IMMEDIATE`)內:重新讀取並比對目前狀態 → 跑 guard → 更新狀態 → 寫入轉移紀錄 → 寫入操作紀錄。撤回的 guard 要求「該案件在本次送出後沒有任何審核動作紀錄」。「撤回」不新增停留狀態(Decisions Log:撤回回到草稿)。
### 5. 頁面
- `/applications/new` 與草稿/待補件編輯共用同一個表單元件;右側摘要為 client component,依表單值即時計算。Mobile 摘要改頂部可收合卡片,按鈕放底部 sticky action bar。
- 風格稿上方步驟條改為「完成進度」(已完成區塊數/總區塊數),不切頁。
- `/applications` 清單與 `/applications/:id` 詳情以 server component 查詢,查詢一律帶入登入者 ID 作為條件(資料範圍由 identity-access 提供)。
## Risks / Trade-offs
- [依賴 change 尚未完成,介面可能與假設不同] → 依賴點集中在少數 adapter(取參數、寫稽核、查附件),實作前先對照該 change 的 spec 調整。
- [申請月份存成冗餘欄位,若刷卡日期修改未同步會不一致] → 只允許草稿/待補件修改,且每次儲存都由刷卡日期重新計算,不接受外部傳入。
- [伺服器時鐘與時區設定錯誤造成期限誤判] → 期限以 UTC 時刻比較,Asia/Taipei 轉換只在純函式內,並有跨日邊界測試。
## Migration Plan
新功能,無既有資料。部署後依 rule-settings 預設值即可運作。
## Open Questions
- 申請編號格式(例如 `AI-202610-0001`)未於規格定義;實作時採「年月+流水號」,不影響 spec。
@@ -0,0 +1,31 @@
# Proposal
## Why
員工需要一個能自行提出 AI 訂閱補助申請、隨時知道案件在哪一關的入口(規格 §5 步驟 1–5、§9、§14;介面規劃 §3、§4、FE-02~04)。這是整個制度的資料起點:沒有正確的申請月份、台幣金額與附件,後續主管審核與月結都無法進行。前置的帳號權限、操作紀錄、後台參數、全站框架與附件上傳已由 roadmap 1.x、2.1 規劃,現在可以把員工端申請流程與案件狀態機建立起來。
## What Changes
- 新增「新增 AI 補助申請」頁(`/applications/new`):單頁分區(申請人資訊、訂閱資訊、金額與日期、工作用途、憑證附件、聲明確認)+右側即時摘要(申請月份、實際支付、50% 試算、申請截止日、「實際補助於月結後確認」)。不採多步驟 Wizard。
- 欄位驗證依介面規劃 §3.1/規格 §9;前端即時驗證與伺服器端驗證使用同一份規則。
- 儲存草稿;送出時執行完整驗證,未通過則捲動至第一個錯誤欄位並於頁首顯示「尚有 N 項資料需完成」。
- 申請月份由刷卡日期決定;超過刷卡月份次月 20 日 23:59:59(Asia/Taipei)一律不可送出,不提供逾期補登。
- 50% 試算依後台設定的比例與取整方式(預設無條件捨去)即時計算,標示為「預估」;無個人月上限。
- 新增「我的申請」清單(`/applications`)與申請詳情(`/applications/:id`):摘要卡、篩選(月份/狀態/平台,預設最近 6 個月)、詳情含申請資料、附件、審核時間軸、主管意見、月結結果與發放資訊。
- 建立案件狀態機:定義規格 §14 全部狀態與標籤,並實作本 change 負責的轉移——送出(草稿→待主管審核)、補件重送(待補件→待主管審核)、撤回(待主管審核且主管尚未處理→草稿)、刪除草稿。每次轉移寫入操作紀錄與審核時間軸。
## Capabilities
### New Capabilities
- `subsidy-application`: 員工建立、編輯、送出與查看 AI 補助申請,包括欄位驗證、月份歸屬、申請期限、50% 試算、草稿與「我的申請」清單/詳情。
- `application-lifecycle`: 申請案件的狀態定義、狀態標籤、允許的狀態轉移與其角色限制、轉移紀錄(時間軸),供後續審核與月結 change 擴充。
### Modified Capabilities
<!-- 無;依賴的 identity-access、audit-trail、rule-settings、app-shell、application-attachments 尚未 archive,本 change 只使用其既定行為,不修改其 requirement。 -->
## Impact
- 新增頁面:`/applications/new`、`/applications`、`/applications/:id`(員工視角;主管/管理者視角的詳情操作由後續 change 擴充)。
- 新增資料:申請案件、案件狀態轉移紀錄;與附件、使用者/部門、制度參數版本關聯。
- 依賴:`identity-access`(登入者與資料範圍)、`org-directory`(申請人部門)、`audit-trail`(留痕)、`rule-settings`(比例、取整、截止日、平台清單)、`app-shell`(StatusBadge、MoneyDisplay、ErrorSummary、ConfirmDialog 等)、`application-attachments`(Invoice/刷卡帳單)。
- 下游:`add-manager-review` 以本 change 的狀態機加入審核轉移;`add-department-settlement` 讀取「審核通過」案件與其試算金額。
@@ -0,0 +1,79 @@
# Spec Delta
## Purpose
集中定義 AI 補助申請案件的狀態、對外顯示標籤、允許的狀態轉移與可執行角色,並保留每次轉移的時間軸紀錄,讓申請、審核、月結與發放各階段遵循同一套規則。
## ADDED Requirements
### Requirement: 案件狀態與顯示標籤
系統 SHALL 以下列狀態管理案件,並以對應標籤顯示(規格 §14、介面規劃 §9):草稿→「草稿」、待主管審核→「待審核」、待補件→「待補件」、審核通過→「已通過」、不核准→「不核准」、待月結→「待月結」、已提交→「已提交」、最終核定→「已核定」、已發放→「已發放」。狀態標籤 MUST 同時顯示文字,不得僅以顏色區分。
#### Scenario: 待主管審核的標籤
- **WHEN** 案件狀態為待主管審核
- **THEN** 所有清單與詳情頁以文字標籤「待審核」顯示
### Requirement: 只允許已定義的狀態轉移
系統 SHALL 只執行已定義的狀態轉移,且只允許該轉移指定的角色執行;未定義的轉移或角色不符 MUST 被拒絕,案件狀態與內容保持不變。
#### Scenario: 員工嘗試把案件改為審核通過
- **WHEN** 員工對自己待主管審核的案件要求轉為審核通過
- **THEN** 系統拒絕該操作,案件仍為待主管審核
### Requirement: 送出申請
系統 SHALL 允許申請人本人將「草稿」案件送出為「待主管審核」,前提是案件通過完整驗證且未超過申請期限。
#### Scenario: 草稿送出
- **WHEN** 員工送出一筆資料完整、期限內的草稿
- **THEN** 案件狀態變為待主管審核,時間軸新增「送出」紀錄
#### Scenario: 不完整的草稿無法送出
- **WHEN** 員工送出缺少附件的草稿
- **THEN** 案件仍為草稿,且不產生轉移紀錄
### Requirement: 補件重新送出
系統 SHALL 允許申請人本人修改「待補件」案件後重新送出為「待主管審核」;重送同樣需通過完整驗證且未超過申請期限。
#### Scenario: 補件後重送
- **WHEN** 員工補上刷卡帳單後重新送出待補件案件
- **THEN** 案件狀態變為待主管審核,時間軸新增「補件重送」紀錄
#### Scenario: 補件逾期
- **WHEN** 員工在刷卡月份次月 20 日 23:59:59 之後重送待補件案件
- **THEN** 系統拒絕重送並顯示申請期限已截止,案件仍為待補件
### Requirement: 撤回申請
系統 SHALL 允許申請人本人撤回狀態為「待主管審核」且主管尚未做出任何審核動作的案件;撤回後案件 MUST 回到「草稿」並可再次編輯送出,時間軸 MUST 保留「撤回」紀錄。其他狀態不得撤回。
#### Scenario: 待審核案件撤回
- **WHEN** 員工撤回主管尚未處理的待主管審核案件
- **THEN** 案件回到草稿,可再編輯,時間軸顯示「撤回」紀錄
#### Scenario: 已通過案件不可撤回
- **WHEN** 員工嘗試撤回已審核通過的案件
- **THEN** 系統拒絕撤回
### Requirement: 刪除草稿
系統 SHALL 允許申請人本人刪除從未送出過的「草稿」案件,刪除前 MUST 顯示確認視窗;曾送出過(例如撤回後回到草稿)的案件不得刪除,以保留審核軌跡。
#### Scenario: 刪除未送出的草稿
- **WHEN** 員工確認刪除一筆從未送出的草稿
- **THEN** 該草稿與其附件不再出現在「我的申請」
#### Scenario: 撤回後的草稿不可刪除
- **WHEN** 員工嘗試刪除曾送出又撤回的草稿
- **THEN** 系統拒絕刪除,並說明需保留審核紀錄
### Requirement: 申請內容鎖定
系統 SHALL 只在案件為「草稿」或「待補件」時允許申請人修改申請內容與附件;其他狀態下任何修改請求 MUST 被拒絕。
#### Scenario: 待審核時修改金額
- **WHEN** 員工嘗試修改待主管審核案件的台幣金額
- **THEN** 系統拒絕修改,金額維持原值
### Requirement: 轉移紀錄與時間軸
系統 SHALL 為每次狀態轉移記錄轉移前後狀態、操作者、時間(顯示為 Asia/Taipei)與意見,並寫入操作紀錄;案件詳情的審核時間軸 MUST 依時間順序呈現這些紀錄,且紀錄不得被修改或刪除。
#### Scenario: 時間軸呈現
- **WHEN** 案件在 10/12 送出、10/14 被退回補件
- **THEN** 詳情時間軸依序顯示「10/12 送出」「10/14 主管退回補件」及退回意見
@@ -0,0 +1,212 @@
# Spec Delta
## Purpose
讓員工自行建立、編輯、送出與追蹤非專案型 AI 工具訂閱補助申請,確保每筆申請具備正確的申請月份、台幣金額、工作用途與憑證,並讓員工隨時看到案件進度與預估補助。
## ADDED Requirements
### Requirement: 申請人資訊自動帶入
系統 SHALL 在新增申請時以登入帳號自動帶入申請人姓名與所屬部門,兩者 MUST 為唯讀,員工不得修改(規格 §9、介面規劃 §3.1)。
#### Scenario: 開啟新增申請頁
- **WHEN** 員工王小明(設計部)開啟新增申請頁
- **THEN** 申請人欄位顯示「王小明」、部門欄位顯示「設計部」,且兩者皆不可編輯
#### Scenario: 竄改申請人資料的請求
- **WHEN** 送出的申請資料中夾帶不同於登入者的申請人或部門
- **THEN** 系統忽略該值,以登入帳號與其部門資料建立申請
#### Scenario: 送出後申請人調部門
- **WHEN** 王小明以設計部身分送出申請後,被調至研發部
- **THEN** 該申請的部門仍記為「設計部」,並計入設計部該月份的審核與月結,不隨人員調部門而移動
### Requirement: AI 平台與其他平台名稱
系統 SHALL 要求選擇 AI 平台,選項來自後台平台清單並包含「其他」,預設顯示「請選擇平台」。選擇「其他」時 MUST 顯示並要求填寫「其他平台名稱」,長度 2–60 字;未選「其他」時不得要求該欄位。
#### Scenario: 未選擇平台
- **WHEN** 員工未選擇 AI 平台即送出
- **THEN** 系統拒絕送出,並於 AI 平台欄位顯示必填錯誤
#### Scenario: 選擇其他平台
- **WHEN** 員工選擇「其他」
- **THEN** 頁面展開「其他平台名稱」欄位,且該欄位為必填
#### Scenario: 其他平台名稱長度不足
- **WHEN** 員工選擇「其他」並輸入 1 個字的平台名稱後送出
- **THEN** 系統拒絕送出,並提示名稱需為 2–60 字
### Requirement: 訂閱方案/項目
系統 SHALL 要求填寫訂閱方案/項目名稱(例如 ChatGPT Plus),長度 MUST 為 2–100 字。
#### Scenario: 方案名稱空白
- **WHEN** 員工未填訂閱方案即送出
- **THEN** 系統拒絕送出,並於該欄位顯示必填錯誤
### Requirement: 實際台幣金額
系統 SHALL 要求填寫實際台幣支付金額,值 MUST 為正整數(以刷卡帳單為準),並作為補助計算的唯一金額基礎。
#### Scenario: 金額為小數或非正數
- **WHEN** 員工輸入台幣金額 899.5 或 0 後送出
- **THEN** 系統拒絕送出,並提示需為正整數
#### Scenario: 有效金額
- **WHEN** 員工輸入台幣金額 899
- **THEN** 系統接受該金額並以其計算 50% 試算
### Requirement: 原幣金額與幣別
系統 SHALL 允許選填原幣金額與幣別,僅供留存參考,不得參與補助計算。原幣金額若有填寫 MUST 大於 0 且最多 2 位小數,且幣別成為必填。
#### Scenario: 填原幣金額未選幣別
- **WHEN** 員工輸入原幣金額 20.00 但未選幣別即送出
- **THEN** 系統拒絕送出,並提示幣別為必填
#### Scenario: 原幣金額小數位過多
- **WHEN** 員工輸入原幣金額 19.999
- **THEN** 系統提示原幣金額最多 2 位小數
#### Scenario: 原幣金額不影響試算
- **WHEN** 員工輸入原幣 USD 20.00 與台幣 660
- **THEN** 50% 試算只依台幣 660 計算
### Requirement: 刷卡日期決定申請月份
系統 SHALL 要求填寫刷卡日期,日期 MUST 不晚於今日(Asia/Taipei)。申請月份 MUST 等於刷卡日期所屬年月(YYYY/MM),唯讀且不得以 Invoice 日期、服務期間或送出日期決定(規格 §6)。
#### Scenario: 刷卡日期決定月份
- **WHEN** 員工將刷卡日期設為 2026/10/05
- **THEN** 申請月份即時顯示為 2026/10
#### Scenario: 刷卡日期晚於今日
- **WHEN** 今日為 2026/10/02,員工將刷卡日期設為 2026/10/03
- **THEN** 系統拒絕該日期並提示不得晚於今日
### Requirement: 申請期限
系統 SHALL 以刷卡月份次月 20 日 23:59:59(Asia/Taipei,日期取自後台截止日參數)為送出期限;超過期限 MUST 拒絕送出與補件重送,且不提供逾期例外補登。期限需在表單摘要中顯示。
#### Scenario: 期限內送出
- **WHEN** 刷卡日期為 2026/10/05,員工於 2026/11/20 23:59:00 送出
- **THEN** 系統接受送出
#### Scenario: 逾期送出
- **WHEN** 刷卡日期為 2026/10/05,員工於 2026/11/21 00:00:01 送出
- **THEN** 系統拒絕送出,並顯示「此筆刷卡日期屬於 2026/10,申請期限已於 2026/11/20 截止。」
#### Scenario: 逾期案件仍可存草稿
- **WHEN** 員工對已逾期月份的申請點擊「儲存草稿」
- **THEN** 系統可儲存草稿,但頁面明確提示該筆已逾期、無法送出
### Requirement: 工作用途與成果產出
系統 SHALL 要求填寫工作用途說明與成果產出,兩者皆為必填;系統 MUST 提供範例提示並以字數計數建議 20–500 字,超過 500 字 MUST 拒絕。成果產出 MAY 另附成果連結,連結若有填寫 MUST 為有效 URL。
#### Scenario: 用途空白
- **WHEN** 員工未填工作用途說明即送出
- **THEN** 系統拒絕送出,並顯示「請完成「工作用途說明」後再送出。」
#### Scenario: 用途少於建議字數
- **WHEN** 員工填寫 8 個字的用途
- **THEN** 系統在欄位下方提示建議至少 20 字並具體描述與工作的關聯,但不阻擋送出
#### Scenario: 超過字數上限
- **WHEN** 員工填寫 501 字的成果產出
- **THEN** 系統拒絕送出並提示上限 500 字
### Requirement: 憑證附件必備
系統 SHALL 要求每筆申請在送出前同時具備 Invoice 與刷卡帳單附件;附件格式、容量與遮蔽提示依附件能力的規定。缺少任一附件 MUST 拒絕送出。
#### Scenario: 缺少刷卡帳單
- **WHEN** 員工只上傳 Invoice 即送出
- **THEN** 系統拒絕送出,並顯示「請上傳 Invoice 與刷卡帳單。」
#### Scenario: 遮蔽提醒
- **WHEN** 員工檢視憑證附件區塊
- **THEN** 頁面提示可遮蔽與申請無關的私人交易,但需露出交易日期與台幣金額
### Requirement: 聲明確認
系統 SHALL 要求員工勾選「資料真實且用途符合工作需求」聲明後才可送出。
#### Scenario: 未勾選聲明
- **WHEN** 員工未勾選聲明即送出
- **THEN** 系統拒絕送出,並標示聲明欄位錯誤
### Requirement: 50% 補助即時試算
系統 SHALL 依台幣金額 × 後台補助比例(預設 50%),以後台取整方式(預設無條件捨去)即時計算預估補助並唯讀顯示,標示為「預估」。系統 MUST NOT 套用任何個人月上限。
#### Scenario: 預設取整
- **WHEN** 員工輸入台幣金額 899
- **THEN** 試算立即顯示 NT$ 449(預估)
#### Scenario: 後台改為四捨五入
- **WHEN** 後台取整方式為四捨五入,員工輸入台幣金額 899
- **THEN** 試算顯示 NT$ 450(預估)
### Requirement: 補助摘要區
系統 SHALL 在表單旁(Mobile 為可收合摘要卡或底部摘要)即時顯示申請月份、實際支付、預估補助與申請截止日,並固定顯示「實際補助於月結後確認」。摘要 MUST NOT 使用「年度預算」等暗示年度額度或先到先得的文案。
#### Scenario: 變更刷卡日期
- **WHEN** 員工把刷卡日期由 2026/10/05 改為 2026/09/28
- **THEN** 摘要的申請月份立即變為 2026/09,申請截止日變為 2026/10/20
#### Scenario: 摘要說明文案
- **WHEN** 員工檢視補助摘要
- **THEN** 摘要顯示「實際補助於月結後確認」,且不出現「年度預算」字樣
### Requirement: 儲存草稿
系統 SHALL 允許員工在任何填寫進度下儲存草稿,草稿不需通過必填驗證,但已填欄位的格式錯誤 MUST 不被儲存為有效值並提示。草稿僅本人可見。
#### Scenario: 部分填寫存草稿
- **WHEN** 員工只填平台與方案後點擊「儲存草稿」
- **THEN** 系統建立狀態為「草稿」的案件,之後可從「我的申請」繼續編輯
### Requirement: 送出前完整驗證與錯誤摘要
系統 SHALL 在員工點擊「送出申請」時執行完整驗證;有缺漏時 MUST 不送出、在頁首顯示「尚有 N 項資料需完成」(N 為錯誤欄位數)、捲動至第一個錯誤欄位,並於各欄位顯示 inline 錯誤。
#### Scenario: 三項錯誤
- **WHEN** 員工未填用途、未上傳刷卡帳單、未勾選聲明即送出
- **THEN** 頁首顯示「尚有 3 項資料需完成」,頁面捲動至工作用途說明欄位
### Requirement: 伺服器端驗證
系統 SHALL 在伺服器端對送出、補件重送與草稿儲存重新執行與表單相同的驗證、期限與權限檢查;任何不符規則的請求 MUST 被拒絕,不得僅依賴前端驗證。
#### Scenario: 繞過前端送出不完整資料
- **WHEN** 有人直接呼叫送出功能並省略刷卡帳單
- **THEN** 系統拒絕並回傳缺少附件的錯誤,案件狀態不變
### Requirement: 我的申請清單
系統 SHALL 在「我的申請」顯示登入者本人的案件,頁首摘要顯示本月案件數、待補件數、審核通過數與已發放總額;清單欄位包含申請編號、刷卡日期、平台、台幣金額、試算補助、最終補助、狀態、最後更新。
#### Scenario: 檢視清單
- **WHEN** 員工開啟「我的申請」
- **THEN** 只看到本人案件,每筆顯示上述欄位,最終補助尚未確定時顯示「--」
#### Scenario: 員工無法存取他人案件
- **WHEN** 員工以網址開啟他人的申請詳情
- **THEN** 系統拒絕存取,且不洩露該案件內容
### Requirement: 我的申請篩選
系統 SHALL 提供月份、狀態、AI 平台篩選,預設顯示刷卡月份為最近 6 個月的案件;無資料時顯示空狀態並提供「新增申請」入口。
#### Scenario: 預設範圍
- **WHEN** 今日為 2026/10/02,員工開啟「我的申請」
- **THEN** 清單預設顯示刷卡月份 2026/05–2026/10 的案件
#### Scenario: 依狀態篩選
- **WHEN** 員工篩選狀態「待補件」
- **THEN** 清單只顯示待補件案件
### Requirement: 申請詳情
系統 SHALL 在申請詳情顯示完整申請資料、附件、審核時間軸、主管意見、月結結果與發放資訊,並依狀態只提供允許的操作:草稿可編輯/刪除、待補件可編輯並重新送出、允許階段可撤回,其他狀態僅檢視。待補件時主管意見 MUST 醒目顯示於頁面上方。
#### Scenario: 待補件詳情
- **WHEN** 員工開啟主管退回補件的案件
- **THEN** 頁面上方醒目顯示主管意見與「編輯並重新送出」按鈕,金額摘要顯示支付金額、預估補助與最終補助「--」
#### Scenario: 已通過案件唯讀
- **WHEN** 員工開啟狀態為「已通過」的案件
- **THEN** 頁面不提供編輯、刪除或撤回操作,並顯示「等待月結」
### Requirement: 新增申請版面
系統 SHALL 以單頁分區呈現新增申請(申請人資訊、訂閱資訊、金額與日期、工作用途、憑證附件、聲明確認),Desktop 為表單與摘要雙欄,Mobile 為單欄並以底部固定操作列放置「儲存草稿」與「送出申請」;不得拆成多步驟 Wizard。欄位 Label MUST 永遠顯示。
#### Scenario: Mobile 版面
- **WHEN** 員工以手機寬度開啟新增申請
- **THEN** 各區塊單欄排列,操作按鈕固定於底部且不遮擋欄位
@@ -0,0 +1,33 @@
# Tasks
## 1. 計算與驗證規則
- [ ] 1.1 實作 `applicationMonth`、`submissionDeadline`(Asia/Taipei 次月 N 日 23:59:59)、`estimateSubsidy`(整數運算、floor/half-up)純函式,並以 Vitest 驗證:2026/10/05→2026/10、截止 2026/11/20 23:59:59、11/20 23:59:00 未逾期、11/21 00:00:01 逾期、899→449(floor)/450(half-up)
- [ ] 1.2 以 Zod 建立 `draftSchema` 與 `submitSchema`(平台、其他平台 2–60、方案 2–100、TWD 正整數、原幣 >0 且 ≤2 位小數、填原幣則幣別必填、刷卡日期 ≤ 今日、用途/成果 ≤500 字、成果連結 URL、聲明勾選),並以 Vitest 涵蓋 spec 各欄位 scenario 與錯誤數計算
## 2. 資料模型與狀態機
- [ ] 2.1 以 Drizzle 新增申請案件與狀態轉移紀錄資料表及 migration(金額 INTEGER、刷卡日期 ISO 字串、申請月份、參數版本 ID、`everSubmitted`),並驗證 migration 可於空資料庫套用與回復
- [ ] 2.2 實作狀態機模組(轉移表、角色檢查、guard、單一 `BEGIN IMMEDIATE` 交易內更新狀態+轉移紀錄+操作紀錄),填入 submit、resubmit、withdraw 與刪除草稿規則,並以 Vitest 驗證合法轉移、未定義轉移被拒、角色不符被拒、撤回後回到草稿、主管已處理後不可撤回、曾送出草稿不可刪除
- [ ] 2.3 定義狀態→顯示標籤對照(草稿/待審核/待補件/已通過/不核准/待月結/已提交/已核定/已發放),接到 app-shell 的 StatusBadge,並以單元測試確認每個狀態都有文字標籤
## 3. 申請伺服器端操作
- [ ] 3.1 實作儲存草稿、更新草稿/待補件、送出、補件重送、撤回、刪除草稿的 Server Actions:申請人與部門一律取自登入者、送出與重送重跑 `submitSchema`+期限+雙附件檢查、非草稿/待補件拒絕修改;並以 Vitest 整合測試驗證竄改申請人被忽略、缺附件被拒、逾期被拒、他人案件被拒
- [ ] 3.2 送出時記錄當下生效的制度參數版本並存入申請月份,並以整合測試驗證後台參數變更後既有案件試算不變
## 4. 新增申請頁(/applications/new)
- [ ] 4.1 建立單頁分區表單(A 申請人資訊唯讀、B 訂閱資訊含「其他」展開、C 金額與日期、D 用途與成果含範例提示與字數計數、E 憑證附件含遮蔽提示、F 聲明確認),Label 永遠顯示,並以 Playwright 驗證選「其他」會展開必填欄位
- [ ] 4.2 建立右側補助摘要(申請月份、實際支付、預估補助、申請截止、「實際補助於月結後確認」)與完成進度指示,並以 Playwright 驗證改刷卡日期立即更新月份與截止日、輸入 899 立即顯示 NT$ 449、頁面無「年度預算」字樣
- [ ] 4.3 實作送出前驗證:頁首「尚有 N 項資料需完成」、捲動至第一個錯誤欄位、inline 錯誤、逾期訊息;並以 Playwright 驗證三項缺漏時顯示「尚有 3 項資料需完成」並聚焦工作用途欄位
- [ ] 4.4 實作 Mobile 版面(單欄、可收合摘要、底部 sticky 操作列),並以 Playwright 手機 viewport 驗證按鈕不遮擋欄位、無水平捲動
## 5. 我的申請與申請詳情
- [ ] 5.1 建立 `/applications` 清單(頁首摘要、月份/狀態/平台篩選預設最近 6 個月、清單欄位、最終補助未定顯示「--」、空狀態),並以 Playwright 驗證只出現本人案件與篩選結果正確
- [ ] 5.2 建立 `/applications/:id` 詳情(金額摘要、申請資料、用途與成果、附件、審核時間軸、主管意見置頂、依狀態顯示編輯/刪除/重送/撤回操作,刪除與撤回使用確認視窗),並以 Playwright 驗證待補件案件顯示主管意見與「編輯並重新送出」、已通過案件無操作、他人案件無法開啟
## 6. 整合驗證
- [ ] 6.1 以 Playwright 跑完整流程:新增→存草稿→上傳兩份附件→送出→撤回回草稿→再送出,確認時間軸依序顯示送出/撤回/送出且操作紀錄皆有對應項目
View File
@@ -0,0 +1,3 @@
schema: spec-driven
created: 2026-10-02
skip_specs: true
@@ -0,0 +1,176 @@
# Design
## Context
- Repo 只有 `docs/`(規格文件、前端介面規劃、兩張風格稿)與空的 `openspec/specs/`,尚無程式碼、技術選型或部署環境。
- 本 change 的產出是「後續 changes 的切分方式」與「跨 change 必須一致的決策」,動機見 `proposal.md` – Why。
- 規格 §20 仍有 7 項待公司確認的決策;部分會影響特定 change 的 spec,需在該 change propose 前確認(見 Open Questions)。
## Goals / Non-Goals
**Goals:**
- 每個後續 change 可獨立 propose、實作、驗收與 archive,且依賴方向單一(後者只依賴前者)。
- Phase 1 完成即滿足規格 §18 全部 11 項 MVP 驗收條件與前端規劃 §13 驗收重點。
- 固定跨 change 的共用規則,讓各 change 的 spec 不重複定義、不互相矛盾。
**Non-Goals:**
- 不在此撰寫任何 capability 的 requirement/scenario(由各 change 撰寫)。
- 不涵蓋規格 §1.2 範圍外項目:專案型採購、公司統一採購/企業授權、薪資系統自動入帳(Phase 3 才評估整合)。
## Decisions
### D1. 切分原則:依「業務流程關卡」切,而非依前後端分層
每個 change 同時包含該功能的資料模型、API、UI 與測試(垂直切片),因為驗收條件都是端到端的(例:「主管可完成核准、退回補件、不核准」)。替代方案「先做全部後端再做全部前端」會讓驗收延後到最後,且難以依 change archive spec。
### D2. 實作順序與依賴
```
1 foundation
└─ 2 identity-and-access
├─ 3 audit-trail ───────────────┐ (之後所有寫入操作都要留痕)
├─ 4 rule-settings (+人數快照) ──┤
└─ 5 app-shell ─────────────────┤
▼
6 attachments → 7 subsidy-application → 8 manager-review
→ 9 department-settlement → 10 company-settlement-and-payout
→ 11 role-dashboards(需前面資料才有內容)
Phase 2:12~14 皆依賴 Phase 1 完成;彼此獨立可平行。
Phase 3:15~17 依賴外部系統資訊,個別啟動。
```
- `audit-trail` 放在業務功能之前,避免事後回填留痕(規格 §17 要求申請到發放每一步都記錄)。
- `rule-settings` 必須早於申請:截止日、比例、平台清單、附件限制都是後台參數,不可寫死。
- 人數快照放在 MVP(change 4)而非 Phase 2:沒有快照就無法計算部門月上限(§18 第 4 項)。Phase 2 的「部門人數快照管理」強化項目(如 HR 同步)移到 change 16。
- 3、4、5 彼此獨立,可平行開發。
### D3. 技術選型(使用者已決定:Next.js + SQLite)
**Next.js(App Router,TypeScript)全端單一應用 + SQLite**。前後端同一個專案:頁面用 React Server/Client Components,寫入操作用 Route Handlers 或 Server Actions;附件存本機檔案目錄(路徑存 DB)。
- 理由:前後端共用 TypeScript 型別與驗證 schema(前端即時驗證與伺服器驗證同一份規則);內部工具使用者少、寫入量低,SQLite 單檔資料庫部署與備份簡單。
- 替代方案:先前建議的 FastAPI + PostgreSQL 由使用者否決;PostgreSQL 留作日後規模變大時的遷移目標(見 Risks)。
- 工具(使用者已確認):ORM 與 migration 用 **Drizzle**(對 SQLite 型別與交易控制較直接);驗證用 Zod;測試用 **Vitest**(domain 與 API)+ **Playwright**(端到端);套件管理用 npm(開發機已有 Node 24 / npm 11)。UI 層由 `add-app-shell` 提議 Tailwind CSS(CSS 變數 tokens)+ Radix 類 headless 元件(使用者已確認);SQLite driver 由 `setup-project-foundation` 選定 better-sqlite3(支援 `BEGIN IMMEDIATE`)。
- SQLite 使用約定:
- 開啟 WAL 模式與 `foreign_keys`;月結提交、比例分配寫入、最終核定等多筆寫入一律包在單一交易(`BEGIN IMMEDIATE`),以守住「合計不超過上限」「提交後鎖定」等不變式。
- 金額存 `INTEGER`;日期存 ISO 字串(刷卡日期 `YYYY-MM-DD`,時間戳 UTC ISO 8601),顯示與「今日」判斷在應用層轉 Asia/Taipei(D7)。
- 只能以單一實例部署(單一 Node 程序或單機),不可多台機器共用同一個 SQLite 檔。
### D4. 金額一律以「新台幣整數元」儲存與計算
- 欄位型別為整數,不使用浮點。原幣金額僅留存參考,不參與計算。
- 個人可補助 = 取整(當月合格台幣金額加總 × 比例),取整方式讀取後台參數,**預設無條件捨去**(使用者決定;可改四捨五入)。
- 無個人月上限(使用者決定);只受部門月上限與比例分配限制。
- 比例與取整方式在月結時「快照」到月結結果,後續參數變更不影響已結算月份(§17)。
### D5. 月結比例分配與尾差:最大餘數法,置於純函式模組
- 未超額:最終補助 = 個人可補助。
- 超額:先算 `個人可補助 × 月上限 ÷ 部門總可補助`,取整數部分(無條件捨去),再把剩餘元數依小數餘額由大到小每人 +1,直到合計等於月上限;餘額相同時以固定次序(如申請人 ID)決勝,確保結果可重現。
- 規格範例驗證(規格用四捨五入得 450/850):450/850、總額 1,300、上限 1,000 → 346.15/653.85 → 346/653 剩 1 元 → 給餘數較大者 → 346/654 ✓。
- 改用預設「無條件捨去」時:899×50%=449、1,700×50%=850,總額 1,299 → 345.65/654.35 → 345/654 剩 1 元 → 給 A → 346/654,合計 1,000 ✓。spec 的 scenario 需分別涵蓋兩種取整方式。
- 演算法放在無 I/O 的 domain 模組(change 9 的 `settlement-calculation`),以規格 §8 兩個案例與邊界案例做單元測試;UI 與 API 只呼叫它。
### D6. 案件狀態機集中定義
- 狀態:草稿、待主管審核、待補件、審核通過、不核准、待月結、已提交、最終核定、已發放、撤回(規格 §14)。
- 轉移規則、允許角色、必填意見集中在 `application-lifecycle`(change 7 建立),後續 change 以 delta 擴充(如 change 8 加入審核轉移、change 9/10 加入月結轉移),不各自寫 if-else。前一個 change 尚未 archive 時,後續 change 以 ADDED requirement 新增轉移,避免 MODIFIED 找不到主 spec。
- 撤回(使用者決定):僅限「待主管審核」且主管尚未處理時;撤回後案件**回到草稿**可再編輯送出,時間軸保留撤回紀錄。「撤回」因此是一次轉移事件而非停留狀態,狀態標籤以草稿呈現。
- 「待月結」與「已提交」等月結相關狀態由月結動作批次推進,而非逐案操作。
### D7. 時間與月份歸屬
- 刷卡日期為純日期(無時區),直接決定歸屬月份。
- 「是否逾期」「今日」等判斷一律以 Asia/Taipei 時區計算,刷卡月份次月 20 日 23:59:59(Asia/Taipei)前皆可送出。
- **不允許逾期補登**(使用者決定):逾期一律阻擋送出,原規劃的 `add-late-submission-exceptions` 已移除;截止日本身仍為後台參數。
### D8. 稽核與鎖定
- `audit-trail` 為 append-only,記錄操作者、時間、對象、動作、前後狀態與意見。
- 月結提交後由伺服器端在寫入交易內檢查月結狀態,阻擋一般修改(必要時輔以 SQLite trigger);更正只能透過管理者「退回月結」(MVP,change 10)或更正紀錄(Phase 2,change 14),不覆寫歷史結果。
### D9. 風格稿與介面規劃的差異處理
風格稿決定**視覺風格**;欄位、流程與文案以**規格文件與介面規劃**為準(新增申請流程採單頁分區已由使用者確認)。各差異的處理:
| 差異 | 風格稿 | 文件 | 建議 |
|------|--------|------|------|
| 新增申請流程 | 3 步驟 Wizard(申請資料→上傳證明→確認送出) | 介面規劃 §3:單頁分區+右側即時摘要,不建議多步驟 | 單頁分區;上方步驟條改為「完成進度」指示(change 7) |
| 缺少欄位 | 無原幣金額/幣別、無聲明確認勾選 | 規格 §9 有這些欄位 | 依規格補齊(change 7) |
| 試算說明文案 | 「視各部門**年度**預算額度而定」 | 額度為**月**上限、月結後確認 | 改為「實際補助於月結後確認」(change 7) |
| 首頁額度卡 | 「剩餘可用額度 NT$6,750」 | 介面規劃 §8:需標示參考值、月結前可能變動,避免先搶先贏 | 標示「參考」並加註說明(change 11) |
| 狀態文字 | 「審核中」 | 「待審核」 | 依介面規劃 §9 標籤(change 5 StatusBadge) |
| 側欄項目 | 「AI 補助申請」「使用說明」「常見問題」 | 「新增申請」;無說明/FAQ 頁 | 導覽名稱依規劃;說明/FAQ 先做靜態頁或列為後續(change 5) |
| 附件上限 | 「單檔上限 10 MB」 | 由後台設定 | 10 MB 作為預設值(change 4) |
## Risks / Trade-offs
- [§20 決策日後變更] → 已確認的決策(見 Decisions Log)都設計為後台參數或集中規則,變更時調參數或以新 change 修改對應 capability。
- [狀態機被後續 change 分散修改導致不一致] → D6 集中定義,各 change 以 delta 更新同一 capability。
- [規劃與實際落差,後續發現需要新 change] → 本 roadmap 不需一次定死;新增或合併 change 時更新本 change 的 tasks,或在 archive 後另開 change。
- [SQLite 只能單機、單一寫入者;附件存本機目錄,主機故障即遺失] → 定期備份 DB 檔與附件目錄(備份方式於 change 1 定義);資料存取集中在 ORM 層,日後需要多實例時可遷移至 PostgreSQL。
- [MVP 期間使用本地帳號,Phase 3 改 SSO 需遷移帳號] → change 2 設計使用者以員工編號/公司 email 為穩定識別,便於後續對應 AD。
## Migration Plan
全新系統,無既有資料遷移。上線前需由管理端建立:部門與部門類型(一般/研發)、人員與角色、首月人數快照、制度參數初始值(規格 §16 預設值)。這些匯入能力分別屬於 change 2 與 change 4。
## Decisions Log(規格 §20 與相關決策,2026-10-02 使用者確認)
| 決策 | 結果 | 影響 change |
|------|------|-------------|
| ORM/測試工具 | Drizzle + Zod + Vitest + Playwright | 1 |
| 50% 金額取整規則 | 無條件捨去(後台可改) | 4、7、9 |
| 部門計算人數認定 | 每月 1 日快照,可人工調整並留痕 | 4、9 |
| 同一人同月個人上限 | 無 | 7、9 |
| 刷卡帳單遮蔽 | 允許遮蔽無關交易,需露出交易日期與台幣金額 | 6、7 |
| 附件格式與容量 | PDF/JPG/PNG、單檔 10 MB(後台可改) | 4、6 |
| 申請截止時刻 | 刷卡月份次月 20 日 23:59:59 Asia/Taipei | 7 |
| 逾期補申請 | 不允許;移除 `add-late-submission-exceptions` | 7 |
| 撤回後行為 | 回到草稿,可編輯重送 | 7 |
| 新增申請流程 | 單頁分區+右側試算(不採 Wizard) | 7 |
| UI 樣式工具 | Tailwind CSS(CSS 變數 tokens)+ Radix 類 headless 元件 | 5 |
| 登入安全預設 | 連續失敗 5 次鎖 15 分鐘、閒置 8 小時登出、密碼至少 8 碼 | 2 |
| 主管本人的申請 | 主管自行審核,時間軸與操作紀錄標示「主管自行審核」;部門無主管時暫由管理者審核(待確認) | 2、8 |
| 核定後更正流程 | 暫不決定;Phase 1 上線後再確認(tasks 4.3 保留未完成) | 14 |
## Open Questions
| 問題 | 影響 change | 處理 |
|------|-------------|------|
| 核定後發放失敗或更正的完整流程 | 10、14 | MVP 僅支援管理者退回月結;完整流程於 change 14 propose 前確認 |
## MVP 驗收條件對照(tasks 3.4)
### 規格 §18
| # | 驗收條件 | 涵蓋的 change / capability → requirement |
|---|----------|------------------------------------------|
| 1 | 員工可完成一筆申請,含 Invoice 與刷卡帳單 | `add-subsidy-application` subsidy-application →「憑證附件必備」「送出前完整驗證與錯誤摘要」;`add-application-attachments` →「附件類型與綁定」「上傳操作與狀態回饋」 |
| 2 | 依刷卡日期判定申請月份 | subsidy-application →「刷卡日期決定申請月份」 |
| 3 | 依台幣金額正確計算 50% | subsidy-application →「50% 補助即時試算」;`add-department-settlement` settlement-calculation →「個人可補助金額計算」 |
| 4 | 依一般/研發部與人數產生月上限 | `add-rule-settings` headcount-snapshot →「部門月上限計算」;settlement-calculation →「部門月上限計算」 |
| 5 | 主管可核准、退回補件、不核准 | `add-manager-review` application-review →「核准」「退回補件」「不核准」;application-lifecycle → 審核三項轉移 |
| 6 | 未超額=個人可補助;超額依比例 | settlement-calculation →「未超額時依個人可補助金額發放」「超額時依占比分配並補足尾差」 |
| 7 | 比例分配合計不超過上限 | settlement-calculation → Scenario「合計絕不超過上限」「小數相同時以固定次序決勝」 |
| 8 | 部長可確認並提交月結名單 | department-settlement →「提交前檢查」「確認並提交月結」「提交後鎖定」 |
| 9 | 管理端可看全公司名單並標記核定與發放 | `add-company-settlement-and-payout` company-settlement →「全公司月結總覽」「最終核定」;payout-management →「標記已發放」 |
| 10 | 未使用額度不帶入次月 | settlement-calculation → Scenario「未使用額度不累計」 |
| 11 | 保留完整操作與審核紀錄 | `add-audit-trail` audit-trail →「記錄重要操作」「紀錄與業務變更同時成立」「紀錄不可竄改」;application-lifecycle →「轉移紀錄與時間軸」 |
### 前端規劃 §13
| 驗收重點 | 涵蓋 |
|----------|------|
| 角色只看到有權限的導覽、資料、操作 | identity-access →「資料範圍控制」「角色導向的路由與導覽」;app-shell →「依角色顯示導覽」 |
| 缺必填/附件/日期不合法不可送出並指出位置 | subsidy-application →「送出前完整驗證與錯誤摘要」(Scenario「三項錯誤」)、「伺服器端驗證」 |
| 金額與刷卡日期變更即時更新試算、月份、截止日 | subsidy-application →「50% 補助即時試算」「補助摘要區」(Scenario「變更刷卡日期」) |
| 退回必填原因,員工第一眼看到 | application-review →「退回補件」;subsidy-application →「申請詳情」(Scenario「待補件詳情」) |
| 超額時呈現分配前後金額,合計不超上限 | department-settlement →「分配明細與尾差說明」;settlement-calculation →「合計絕不超過上限」 |
| 提交月結後不可直接修改 | department-settlement →「提交後鎖定」;application-lifecycle →「已提交案件的唯讀限制」 |
| Desktop/Tablet/Mobile 無溢出、遮擋 | app-shell →「響應式版面」;dashboard →「首頁響應式版面」 |
| 附件上傳中/成功/失敗/超過大小回饋 | application-attachments →「上傳操作與狀態回饋」「檔案格式與大小驗證」 |
| 金額、日期、月份、狀態格式一致 | app-shell →「金額與日期格式」「狀態標籤」 |
| 重要操作需確認視窗 | app-shell →「重要操作確認視窗」;各 change 的不核准/提交月結/最終核定/標記已發放 requirement |
結論:§18 全部 11 項與 §13 全部 10 項均已有對應 requirement/scenario,無缺口。
@@ -0,0 +1,57 @@
# Proposal
## Why
`docs/` 已有完整的制度規格(`AI補助申請系統_規格文件_v1.0.docx`)、前端介面規劃(`AI補助申請系統_表單結構與前端介面規劃_v1.0.docx`)與兩張風格稿,但 repo 仍無任何程式碼與 spec。需要先把整套系統拆成一組邊界清楚、可依序實作與驗收的 OpenSpec changes,並固定跨 change 共用的決策(技術選型、金額與月結演算法、狀態機、稽核),避免各 change 各自詮釋規格。
## What Changes
本 change 只產出規劃,不實作任何系統行為。它定義下列後續 changes(依建議實作順序;詳細依賴與理由見 `design.md`):
### Phase 1|MVP(對應規格 §18 驗收條件、前端規劃 P0)
| # | Change | 範圍 | 新增 capability |
|---|--------|------|-----------------|
| 1 | `setup-project-foundation` | 技術選型、專案骨架、DB 與 migration、lint/test/CI、環境設定 | —(tooling,`skip_specs`) |
| 2 | `add-identity-and-access` | 登入(MVP 本地帳號)、使用者、部門(一般/研發)、角色、權限與資料範圍(員工僅本人、主管僅本部門) | `identity-access`, `org-directory` |
| 3 | `add-audit-trail` | 共用、只增不改的操作紀錄(操作者、時間、前後狀態);操作紀錄查詢頁(FE-10) | `audit-trail` |
| 4 | `add-rule-settings` | 後台制度參數(每人額度、補助比例、截止日、平台清單、取整方式、附件格式/大小)含版本紀錄;每月部門計算人數快照(可人工調整並留痕)(FE-09) | `rule-settings`, `headcount-snapshot` |
| 5 | `add-app-shell` | 全站框架(頂部列、依角色側欄、RWD)、設計 tokens(依風格稿)、共用元件(StatusBadge、MoneyDisplay、MonthPicker、ConfirmDialog、EmptyState、ErrorSummary 等)、金額/日期/月份格式 | `app-shell` |
| 6 | `add-application-attachments` | Invoice/刷卡帳單上傳、預覽、替換、刪除;格式與大小驗證;與案件綁定的存取控制 | `application-attachments` |
| 7 | `add-subsidy-application` | 新增申請表單(欄位與驗證)、草稿、刷卡日期→申請月份與截止日、逾期阻擋、50% 即時試算、聲明確認、送出、我的申請清單/詳情、待補件重送、撤回;案件狀態機(FE-02~04) | `subsidy-application`, `application-lifecycle` |
| 8 | `add-manager-review` | 部門審核工作台、附件頁內預覽、核准/退回補件/不核准(退回與不核准必填意見)、批次核准、審核時間軸(FE-05) | `application-review` |
| 9 | `add-department-settlement` | 月上限計算、超額比例分配、尾差補差、月結頁、提交前檢查、確認提交與鎖定、匯出預覽(FE-06) | `settlement-calculation`, `department-settlement` |
| 10 | `add-company-settlement-and-payout` | 全公司月結總覽、部門詳情、最終核定/退回月結、發放管理、Excel/CSV 匯出、標記已發放(FE-07~08) | `company-settlement`, `payout-management` |
| 11 | `add-role-dashboards` | 員工/主管/管理者首頁卡片:本月申請、待處理、部門額度參考值、時程提醒、最近申請(FE-01) | `dashboard` |
### Phase 2|管理優化(規格 §19 Phase 2、前端規劃 P1/P2)
| # | Change | 範圍 | Capability |
|---|--------|------|-----------|
| 12 | `add-notifications` | 通知中心與提醒:補件、申請截止、月結截止、審核結果 | 新增 `notifications` |
| 13 | `add-duplicate-detection` | 相同申請人+平台+刷卡日期+金額(+Invoice)重複提醒 | 新增 `duplicate-detection` |
| 14 | `add-settlement-corrections` | 已核定/已發放後的更正紀錄、發放失敗處理、制度參數版本套用於歷史月份 | 新增 `settlement-correction`;修改 `company-settlement`, `payout-management` |
### Phase 3|整合(規格 §19 Phase 3)
| # | Change | 範圍 | Capability |
|---|--------|------|-----------|
| 15 | `integrate-sso` | SSO/AD 登入 | 修改 `identity-access` |
| 16 | `integrate-hr-org-sync` | 人資組織資料同步(人員、部門、異動)供人數快照使用 | 修改 `org-directory`, `headcount-snapshot` |
| 17 | `integrate-payroll-export` | 薪資系統或會計流程整合(取代人工匯出) | 修改 `payout-management` |
本 change 另外記錄:規格 §20 決策結果(逾期補申請經決定不允許,故無例外補登 change)、風格稿與介面規劃之間的差異及建議處理方式(見 `design.md`)。
## Capabilities
### New Capabilities
<!-- 本 change 為純規劃(skip_specs: true),不新增 spec。上表 capability 由各後續 change 建立。 -->
### Modified Capabilities
<!-- 無 -->
## Impact
- 只新增 `openspec/changes/plan-system-roadmap/` 下的規劃文件;不動程式碼、不建立 spec。
- 套用(apply)本 change = 依 `tasks.md` 逐一以 `/opsx:propose` 建立上述 changes。
- 技術選型:Next.js(TypeScript 全端)+ SQLite(使用者已決定,見 `design.md` D3);ORM、測試工具等細節於 change 1 定案。
@@ -0,0 +1,36 @@
# Tasks
每項任務=以 `/opsx:propose` 建立一個後續 change(範圍與 capability 見 `proposal.md`,共用決策見 `design.md`)。完成標準:`openspec validate <change-name>` 通過,且 proposal 的 Capabilities 與本 roadmap 一致(若有調整,同步更新 `proposal.md`)。
## 1. Phase 1 基礎建設
- [x] 1.1 依 design D3(Next.js + SQLite,已定案)(Drizzle + Zod + Vitest + Playwright,已確認),propose `setup-project-foundation`(skip_specs;含 lint/test/CI 指令、SQLite 與附件目錄備份方式),並驗證 `openspec validate setup-project-foundation` 通過
- [x] 1.2 Propose `add-identity-and-access`(建立 `identity-access`、`org-directory`;含部門類型一般/研發、資料範圍、帳號初始匯入),並驗證 validate 通過
- [x] 1.3 Propose `add-audit-trail`(建立 `audit-trail`;含操作紀錄頁 FE-10),並驗證 validate 通過
- [x] 1.4 依 design Decisions Log(取整、人數快照、附件格式/容量),propose `add-rule-settings`(建立 `rule-settings`、`headcount-snapshot`;預設值依規格 §16),並驗證 validate 通過
- [x] 1.5 Propose `add-app-shell`(建立 `app-shell`;依風格稿設計 tokens、依角色導覽、共用元件、格式規則,處理 design D9 中狀態文字與側欄差異),並驗證 validate 通過
## 2. Phase 1 申請與審核
- [x] 2.1 依 Decisions Log(遮蔽規則、附件限制),propose `add-application-attachments`(建立 `application-attachments`),並驗證 validate 通過
- [x] 2.2 依 Decisions Log(無個人上限、截止時刻、不允許逾期、撤回回草稿、單頁分區),propose `add-subsidy-application`(建立 `subsidy-application`、`application-lifecycle`),並驗證 validate 通過
- [x] 2.3 Propose `add-manager-review`(建立 `application-review`;以 ADDED requirement 擴充 `application-lifecycle` 的審核轉移),並驗證 validate 通過
## 3. Phase 1 月結、發放與首頁
- [x] 3.1 Propose `add-department-settlement`(建立 `settlement-calculation`、`department-settlement`;spec 需含規格 §8 兩個案例、兩種取整方式與 design D5 尾差規則的 scenario),並驗證 validate 通過
- [x] 3.2 Propose `add-company-settlement-and-payout`(建立 `company-settlement`、`payout-management`;MVP 更正僅支援管理者退回月結),並驗證 validate 通過
- [x] 3.3 Propose `add-role-dashboards`(建立 `dashboard`;額度卡依 D9 標示參考值),並驗證 validate 通過
- [x] 3.4 對照規格 §18 的 11 項 MVP 驗收條件與前端規劃 §13,逐項確認都被 1.x~3.x 某個 change 的 spec scenario 涵蓋,並把對照表附在本 change 的 `design.md`
## 4. Phase 2 管理優化
- [x] 4.1 Propose `add-notifications`(建立 `notifications`),並驗證 validate 通過
- [x] 4.2 Propose `add-duplicate-detection`(建立 `duplicate-detection`),並驗證 validate 通過
- [ ] 4.3 確認核定後發放失敗/更正流程,propose `add-settlement-corrections`(建立 `settlement-correction`、修改 `company-settlement`、`payout-management`),並驗證 validate 通過
## 5. Phase 3 整合
- [ ] 5.1 取得 SSO/AD 環境資訊後 propose `integrate-sso`(修改 `identity-access`),並驗證 validate 通過
- [ ] 5.2 取得人資系統介面資訊後 propose `integrate-hr-org-sync`(修改 `org-directory`、`headcount-snapshot`),並驗證 validate 通過
- [ ] 5.3 取得薪資/會計系統介面資訊後 propose `integrate-payroll-export`(修改 `payout-management`),並驗證 validate 通過
@@ -0,0 +1,3 @@
schema: spec-driven
created: 2026-10-02
skip_specs: true
@@ -0,0 +1,69 @@
# Design
## Context
全新專案,無程式碼。技術選型與 SQLite 使用約定見 `plan-system-roadmap/design.md` D3;本 design 只決定骨架層級的具體做法。開發機:Windows 10、Node 24、npm 11。
## Goals / Non-Goals
**Goals:**
- 一個指令就能在本機啟動、跑測試、建立資料庫與種子資料。
- 固定目錄慣例,讓後續 change 知道 domain 邏輯、資料存取、UI 各放哪裡。
- 備份與還原步驟可實際執行。
**Non-Goals:**
- 不實作任何業務頁面、登入或資料表(由後續 change 建立)。
- 不建立正式環境部署管線(僅文件說明單機部署限制)。
## Decisions
### 目錄結構
```
src/
app/ # Next.js 路由(頁面、Route Handlers)
domain/ # 純函式業務邏輯(無 I/O、無框架相依):月結計算、狀態機、日期/月份規則
server/ # 伺服器端:db 連線、repository、service(交易邊界在此)、auth
db/
schema/ # Drizzle schema,依 capability 分檔
migrations/
seed.ts
lib/ # 前後端共用:Zod schema、格式化工具
components/ # UI 元件
tests/
e2e/ # Playwright
```
- `domain/` 不得 import `server/` 或 Next.js;以 ESLint `no-restricted-imports` 強制。理由:月結演算法(D5)與狀態機(D6)需可單獨單元測試。
- 單元測試與被測檔放一起(`*.test.ts`);e2e 放 `tests/e2e/`。
### SQLite 驅動:better-sqlite3
同步 API、交易語意清楚,可直接下 `BEGIN IMMEDIATE`(D3 要求)。替代方案 libsql/`@libsql/client` 為非同步且偏遠端,單機用途不需要。連線初始化時設定 `journal_mode=WAL`、`foreign_keys=ON`、`busy_timeout=5000`。整個 Node 程序共用單一連線(模組層 singleton,dev 模式掛在 `globalThis` 避免 HMR 重複開啟)。
### Migration 流程
`drizzle-kit generate` 產生 SQL migration 並納入版控;`db:migrate` 於啟動前執行。不使用 `drizzle-kit push`(無法留下版本紀錄)。
### 測試
- Vitest:`environment: node`;整合測試每個測試檔使用暫存 SQLite 檔(或 `:memory:`)並跑 migration。
- Playwright:對 `next build && next start` 啟動的實例測試,使用獨立的測試資料庫路徑與 seed。
- CI 執行 lint、typecheck、`test`;e2e 在 CI 先不強制(需瀏覽器安裝,待有頁面後於後續 change 開啟)。
### 環境設定
`.env.example` 列出 `DATABASE_PATH`(預設 `./data/app.db`)、`ATTACHMENTS_DIR`(預設 `./data/attachments`)、`SESSION_SECRET`、`TZ_APP=Asia/Taipei`。啟動時以 Zod 驗證環境變數,缺漏即失敗。`data/` 列入 `.gitignore`。
### 備份
`npm run backup`:使用 SQLite online backup API(better-sqlite3 `db.backup()`)產生一致性快照到 `backups/<timestamp>/app.db`,並複製附件目錄;保留最近 N 份(預設 14)。理由:直接複製 WAL 模式下的 db 檔可能不一致。還原步驟寫在 `docs/operations/backup.md`。排程由主機(Windows 工作排程器或 cron)負責。
## Risks / Trade-offs
- [better-sqlite3 為原生模組,Windows 需預編譯檔] → Node 24 有預編譯版本;安裝失敗時文件記錄需安裝 Visual Studio Build Tools。
- [單一連線+同步 API 在高併發下阻塞] → 內部工具流量低可接受;寫入交易保持短小。
- [CI 暫不跑 e2e] → 於第一個有頁面的 change(add-identity-and-access)開啟。
## Migration Plan
無既有資料。完成後開發者流程:`npm install` → 複製 `.env.example` 為 `.env` → `npm run db:migrate` → `npm run db:seed` → `npm run dev`。
@@ -0,0 +1,31 @@
# Proposal
## Why
Repo 目前只有文件,後續所有功能 change 都需要一致的專案骨架、資料庫、測試與 CI 才能開始實作。依 `plan-system-roadmap` design D3(Next.js + SQLite + Drizzle + Zod + Vitest + Playwright + npm),先建立共用基礎,避免各功能 change 各自決定目錄結構與工具。
## What Changes
- 建立 Next.js(App Router、TypeScript strict)單一全端專案與目錄結構,含無 I/O 的 domain 模組位置(供月結計算、狀態機等純邏輯)。
- 建立 SQLite 連線(WAL、`foreign_keys`、`busy_timeout`)、Drizzle schema/migration 流程與 seed 腳本骨架。
- 建立 Zod 驗證共用位置;Vitest(單元、整合)與 Playwright(端到端)設定與範例測試。
- 建立 ESLint、Prettier、`npm run` 腳本:`dev`、`build`、`start`、`lint`、`format`、`typecheck`、`test`、`test:e2e`、`db:generate`、`db:migrate`、`db:seed`、`backup`。
- 環境設定(`.env.example`:資料庫路徑、附件目錄、session 密鑰、時區)與附件本機儲存目錄設定。
- SQLite 檔與附件目錄的備份方式與還原步驟文件。
- `git init`、`.gitignore`、GitHub Actions CI(lint、typecheck、test)。
- 更新 `CLAUDE.md` 的指令與架構說明。
## Capabilities
### New Capabilities
<!-- 無:本 change 為工具與骨架(skip_specs: true),不改變任何系統行為。 -->
### Modified Capabilities
<!-- 無 -->
## Impact
- 新增整個應用程式骨架、`package.json` 與相依套件(next、react、drizzle-orm、better-sqlite3、drizzle-kit、zod、vitest、@playwright/test、eslint、prettier)。
- 新增 `.github/workflows/ci.yml`、`.env.example`、`docs/operations/backup.md`。
- 修改 `CLAUDE.md`(指令與目錄結構)。
- 之後所有功能 change 都建立在此骨架上。
@@ -0,0 +1,38 @@
# Tasks
## 1. 專案初始化
- [ ] 1.1 `git init`,建立 `.gitignore`(node_modules、.next、data/、backups/、.env、playwright 報告),並確認 `git status` 不出現上述目錄
- [ ] 1.2 以 Next.js(App Router、TypeScript、`src/` 目錄)建立專案,開啟 TypeScript strict,確認 `npm run dev` 可開啟預設首頁且 `npm run build` 成功
- [ ] 1.3 建立 design 所列目錄結構(`src/domain`、`src/server/db/{schema,migrations}`、`src/lib`、`src/components`、`tests/e2e`),各放一個說明用途的 README 或 index,確認結構存在
## 2. 程式碼品質工具
- [ ] 2.1 設定 ESLint(含 `no-restricted-imports` 禁止 `src/domain` 引用 `src/server`、`next/*`)與 Prettier,新增 `lint`、`format`、`typecheck` 腳本,並以一個故意違規的暫時檔確認 lint 會報錯後刪除
## 3. 資料庫
- [ ] 3.1 安裝 better-sqlite3、drizzle-orm、drizzle-kit,建立連線模組(WAL、foreign_keys、busy_timeout、dev 模式 globalThis singleton),確認啟動後 `PRAGMA journal_mode` 回傳 `wal`
- [ ] 3.2 設定 drizzle-kit 與 `db:generate`、`db:migrate` 腳本,建立一張暫時的 `_meta` 表產生第一個 migration,確認 `npm run db:migrate` 可在空資料庫上成功執行
- [ ] 3.3 建立 `db:seed` 腳本骨架(可重複執行、不重複插入),確認連續執行兩次不報錯
- [ ] 3.4 建立交易工具函式(以 `BEGIN IMMEDIATE` 包住 callback,例外時 rollback),並以 Vitest 測試 commit 與 rollback 兩種情況通過
## 4. 環境設定與附件目錄
- [ ] 4.1 建立 `.env.example` 與以 Zod 驗證環境變數的模組,確認缺少 `SESSION_SECRET` 時啟動失敗並顯示明確訊息
- [ ] 4.2 建立附件儲存目錄設定(啟動時自動建立 `ATTACHMENTS_DIR`),確認首次啟動後目錄存在
## 5. 測試框架
- [ ] 5.1 設定 Vitest(node 環境、整合測試用暫存資料庫 helper:建立暫存 SQLite 並跑 migration),新增 `test` 腳本,確認範例單元與整合測試通過
- [ ] 5.2 設定 Playwright(使用獨立測試資料庫、build+start 啟動),新增 `test:e2e` 腳本,確認一個開啟首頁的範例測試通過
## 6. 備份
- [ ] 6.1 實作 `npm run backup`(SQLite online backup+附件目錄複製、保留最近 14 份),確認執行後產生可開啟的 db 檔與附件副本
- [ ] 6.2 撰寫 `docs/operations/backup.md`(備份排程設定、還原步驟、單機部署限制),並依文件實際還原一次確認資料可讀
## 7. CI 與文件
- [ ] 7.1 建立 `.github/workflows/ci.yml`(npm ci、lint、typecheck、test),在本機以相同指令序列執行全部通過
- [ ] 7.2 更新 `CLAUDE.md`:移除「pre-implementation」描述,加入常用指令(含執行單一測試:`npx vitest run <path>`、`npx playwright test <file>`)、目錄結構與 domain 模組約束,確認文件中的指令可照抄執行

Some files were not shown because too many files have changed in this diff Show More