formular lesen (binär) und openspec für codex

This commit is contained in:
2026-09-05 08:36:40 +02:00
parent 05837cd846
commit 1cb6ae8fd9
34 changed files with 2211 additions and 149 deletions

View File

@@ -0,0 +1 @@
agents

View File

@@ -0,0 +1,188 @@
---
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.
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.12.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.
**Input**: Optionally specify a change name (e.g., `/openspec-apply-change 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., `/openspec-apply-change <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
- Dynamic instruction based on current state
- Optional `context`: current required project instruction input from the selected root
- Optional `operationGuidance`: current advisory guidance for apply
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using `/openspec-continue-change` (if it is not installed, run `openspec status --change "<name>" --json` to see the next artifact and `openspec instructions <artifact-id> --change "<name>" --json` for how to create it)
- 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
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- 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 `/openspec-archive-change`.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- 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
- 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

View File

@@ -0,0 +1,182 @@
---
name: openspec-archive-change
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.12.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.
`<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., `/openspec-archive-change <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**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Ask the user to confirm they want to proceed
- Proceed if user confirms
**If no tasks file exists:** Proceed without 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)
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
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)
- 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.
Then re-run the comparison from the top of this step 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; a spec the sync deliberately kept and reported is also a match
- 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

View File

@@ -0,0 +1,335 @@
---
name: openspec-explore
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.12.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, remind them to exit explore mode first and create a change proposal. 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. For a new change, 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.
---
## 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, schemas, and status
- What the user might be working on
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, 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 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: /openspec-explore add-auth-system
The OAuth integration is more complex than expected
You: [reads change artifacts]
You're on task 4: "Implement OAuth flow"
Let me trace what's involved...
[draws diagram, explores options, suggests paths]
Want to update the design to reflect this?
Or add a spike task to investigate?
```
**User wants to compare options:**
```
User: Should we use Postgres or SQLite?
You: Generic answer is boring. What's the context?
User: A CLI tool that tracks local dev environments
You: That changes everything.
+-------------------------------------------------+
| CLI TOOL DATA STORAGE |
+-------------------------------------------------+
Key constraints:
- No daemon running
- Must work offline
- Single user
SQLite Postgres
Deployment embedded needs server
Offline yes no
Single file yes no
SQLite. Not even close.
Unless... is there a sync component?
```
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When it feels like things are crystallizing, you might summarize:
```
## What We Figured Out
**The problem**: [crystallized understanding]
**The approach**: [if one emerged]
**Open questions**: [if any remain]
**Next steps** (if ready):
- Create a change proposal
- Keep exploring: just keep talking
```
But this summary is optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. 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.
- **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.
- **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

View File

@@ -0,0 +1,153 @@
---
name: openspec-propose
description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.12.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.
**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. **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 reports only `no_openspec_root`, run `openspec schemas --json` from the current working directory instead. Do not use this fallback for invalid or unavailable stores.
Otherwise, omit `--schema` to preserve the configured default.
3. **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`.
4. **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.
5. **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
6. **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 `/openspec-apply-change` 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

View File

@@ -0,0 +1,262 @@
---
name: openspec-sync-specs
description: Sync delta specs from a change to main specs. Use when the user wants to update main specs with changes from a delta spec, without archiving the change.
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.12.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.
`<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., `/openspec-sync-specs <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)
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:
- 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
## 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

View File

@@ -0,0 +1,91 @@
---
name: openspec-update-change
description: Update an OpenSpec change by revising its existing planning artifacts and keeping them coherent with one another. Use when the user wants to revise a change's plan, fold new decisions into it, or reconcile its artifacts after an edit. Never edits code.
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.12.0"
---
Revise a change's existing planning artifacts and keep them coherent. Never edit code.
**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.
**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.
`/openspec-continue-change` is an optional workflow and may not be installed. Before suggesting it anywhere below, verify that it is available. If it is unavailable, `openspec status --change "<name>" --json` shows the next artifact and `openspec instructions "<artifact-id>" --change "<name>" --json` explains how to create it.
**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 sorted by most recently modified, and ask the user to select one
When prompting, present the top 3-4 most recently modified changes as options, showing:
- Change name
- Schema (from `schema` field if present, otherwise "spec-driven")
- Status (e.g., "0/5 tasks", "complete", "no tasks")
- How recently it was modified (from `lastModified` field)
Mark the most recently modified change as "(Recommended)" since it's likely what the user wants to update.
Always announce: "Using change: <name>" and how to override (e.g., `/openspec-update-change <other>`).
2. **Get the change's artifacts**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand current state. The response includes:
- `schemaName`: The workflow schema being used (e.g., "spec-driven")
- `artifacts`: Array of artifacts with their status ("done", "skipped", "ready", "blocked")
- `isPlanningComplete`: Boolean indicating if all planning artifacts are complete. Older CLI versions expose the same value as `isComplete`.
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
The artifact ids and paths come from the active schema - do NOT assume them, and do NOT branch on hardcoded artifact names. Custom schemas must work unchanged.
The files to edit are `artifactPaths.<id>.existingOutputPaths` - the concrete files that exist on disk, already glob-expanded for glob artifacts (e.g. `specs/**/*.md`). Do NOT write to `resolvedOutputPath`: for a glob artifact it is still the glob pattern, not a real file.
3. **Understand the request**
- If the user asked for a specific revision ("the design now uses X"), that is the starting edit.
- If they only said "update" / "make this coherent", treat it as a coherence review: read the existing artifacts and check them against each other for contradictions, gaps, and duplication.
4. **Read and reconcile**
- Read the artifact(s) the request touches and the change's other existing artifacts.
- Apply the requested edit. Then check every other existing artifact against it - in ANY direction: an edit to a later artifact may require revising an earlier one, not only the other way around. Build order is a useful reading order, not a constraint on which artifacts may be revised.
- Note everything that is now inconsistent, missing, or contradictory.
- Revise only files that already exist (`existingOutputPaths`). Do NOT create artifacts that don't exist yet, and do NOT invent new files under a glob artifact - note them and point the user to `/openspec-continue-change` to create them.
- If the change is already coherent, say so and make no edits.
5. **Confirm and apply, one artifact at a time**
- Show each proposed revision and why. Write only after the user confirms.
- If the user rejects a revision, do not write it - leave that artifact unchanged.
- When a substantial rewrite is needed, get that artifact's rules and template first:
```bash
openspec instructions "<artifact-id>" --change "<name>" --json
```
6. **Point to the next step (guidance only - NEVER act on it)**
- Artifacts still missing -> suggest `/openspec-continue-change` to create them.
- Change already implemented (tasks checked off / already applied) -> the code may no longer match the revised plan; suggest `/openspec-apply-change` to carry the delta into code.
- Everything done and implemented -> suggest `/openspec-archive-change`.
**Output**
After each invocation, show:
- Which artifacts were revised (and which proposed revisions were rejected)
- Anything deferred to `/openspec-continue-change` (not-yet-created artifacts or files)
- Where the change stands and the recommended next command
**Guardrails**
- Planning artifacts only - NEVER edit implementation code. If the revised plan implies code changes, stop and point to `/openspec-apply-change`.
- Use the artifact ids and paths reported by `openspec status`; never branch on hardcoded artifact names.
- Edit only the concrete files in `existingOutputPaths`; never write to a glob `resolvedOutputPath`.
- Do not advance the build frontier: no new artifacts, no new files under glob artifacts - that is `/openspec-continue-change`'s job.
- Confirm every edit with the user before writing.
- If the request changes the change's *intent* rather than refining it, first verify whether the optional `/openspec-new-change` workflow is available. If it is, recommend starting fresh with `/openspec-new-change` (the "Update vs. Start Fresh" heuristic). If it is unavailable, ask for a distinct unused change name and recommend `openspec new change "<new-change-name>"` instead.

View File

@@ -0,0 +1,175 @@
---
name: openspec-verify-change
description: Verify implementation matches change artifacts. Use when the user wants to validate that implementation is complete, correct, and coherent before archiving.
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.12.0"
---
Verify that an implementation matches the change artifacts (specs, tasks, design).
**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.
**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 implementation tasks (tasks artifact exists).
Include the schema used for each change if available.
Mark changes with incomplete tasks as "(In Progress)".
Always announce: "Using change: <name>" and how to override (e.g., `/openspec-verify-change <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`, `artifactPaths`, and `actionContext`: path and scope context
- Which artifacts exist for this change
3. **Get planning context and load artifacts**
```bash
openspec instructions apply --change "<name>" --json
```
This returns the change directory and `contextFiles` (artifact ID -> array of concrete file paths). Read all available artifacts from `contextFiles`.
4. **Initialize verification report structure**
Create a report structure with three dimensions:
- **Completeness**: Track tasks and spec coverage
- **Correctness**: Track requirement implementation and scenario coverage
- **Coherence**: Track design adherence and pattern consistency
Each dimension can have CRITICAL, WARNING, or SUGGESTION issues.
5. **Verify Completeness**
**Task Completion**:
- If `contextFiles.tasks` exists, read every file path in it
- Parse checkboxes: `- [ ]` (incomplete) vs `- [x]` (complete)
- Count complete vs total tasks
- If incomplete tasks exist:
- Add CRITICAL issue for each incomplete task
- Recommendation: "Complete task: <description>" or "Mark as done if already implemented"
**Spec Coverage**:
- If delta specs exist in `contextFiles.specs`:
- Extract all requirements (marked with "### Requirement:")
- For each requirement:
- Search codebase for keywords related to the requirement
- Assess if implementation likely exists
- If requirements appear unimplemented:
- Add CRITICAL issue: "Requirement not found: <requirement name>"
- Recommendation: "Implement requirement X: <description>"
6. **Verify Correctness**
**Requirement Implementation Mapping**:
- For each requirement from delta specs:
- Search codebase for implementation evidence
- If found, note file paths and line ranges
- Assess if implementation matches requirement intent
- If divergence detected:
- Add WARNING: "Implementation may diverge from spec: <details>"
- Recommendation: "Review <file>:<lines> against requirement X"
**Scenario Coverage**:
- For each scenario in delta specs (marked with "#### Scenario:"):
- Check if conditions are handled in code
- Check if tests exist covering the scenario
- If scenario appears uncovered:
- Add WARNING: "Scenario not covered: <scenario name>"
- Recommendation: "Add test or implementation for scenario: <description>"
7. **Verify Coherence**
**Design Adherence**:
- If `contextFiles.design` exists:
- Extract key decisions (look for sections like "Decision:", "Approach:", "Architecture:")
- Verify implementation follows those decisions
- If contradiction detected:
- Add WARNING: "Design decision not followed: <decision>"
- Recommendation: "Update implementation or revise design.md to match reality"
- If no design.md: Skip design adherence check, note "No design.md to verify against"
**Code Pattern Consistency**:
- Review new code for consistency with project patterns
- Check file naming, directory structure, coding style
- If significant deviations found:
- Add SUGGESTION: "Code pattern deviation: <details>"
- Recommendation: "Consider following project pattern: <example>"
8. **Generate Verification Report**
**Summary Scorecard**:
```markdown
## Verification Report: <change-name>
### Summary
| Dimension | Status |
|--------------|------------------|
| Completeness | X/Y tasks, N reqs|
| Correctness | M/N reqs covered |
| Coherence | Followed/Issues |
```
**Issues by Priority**:
1. **CRITICAL** (Must fix before archive):
- Incomplete tasks
- Missing requirement implementations
- Each with specific, actionable recommendation
2. **WARNING** (Should fix):
- Spec/design divergences
- Missing scenario coverage
- Each with specific recommendation
3. **SUGGESTION** (Nice to fix):
- Pattern inconsistencies
- Minor improvements
- Each with specific recommendation
**Final Assessment**:
- If CRITICAL issues: "X critical issue(s) found. Fix before archiving."
- If only warnings: "No critical issues. Y warning(s) to consider. Ready for archive (with noted improvements)."
- If all clear: "All checks passed. Ready for archive."
**Verification Heuristics**
- **Completeness**: Focus on objective checklist items (checkboxes, requirements list)
- **Correctness**: Use keyword search, file path analysis, reasonable inference - don't require perfect certainty
- **Coherence**: Look for glaring inconsistencies, don't nitpick style
- **False Positives**: When uncertain, prefer SUGGESTION over WARNING, WARNING over CRITICAL
- **Actionability**: Every issue must have a specific recommendation with file/line references where applicable
**Graceful Degradation**
- If only tasks.md exists: verify task completion only, skip spec/design checks
- If tasks + specs exist: verify completeness and correctness, skip design
- If full artifacts: verify all three dimensions
- Always note which checks were skipped and why
**Output Format**
Use clear markdown with:
- Table for summary scorecard
- Grouped lists for issues (CRITICAL/WARNING/SUGGESTION)
- Code references in format: `file.ts:123`
- Specific, actionable recommendations
- No vague suggestions like "consider reviewing"

View File

@@ -520,10 +520,7 @@ fn fehlende_groessenangabe_wird_abgewiesen() {
std::fs::write(&f, "PRINT 1\n").unwrap();
let r = std::panic::catch_unwind(|| run_corpus_file(&f, None));
let e = r.expect_err("Datei ohne Größenangabe muss abgewiesen werden");
let m = e
.downcast_ref::<String>()
.cloned()
.unwrap_or_default();
let m = e.downcast_ref::<String>().cloned().unwrap_or_default();
assert!(m.contains("keine Bildschirmgröße deklariert"), "{m}");
let _ = std::fs::remove_dir_all(&dir);
}

View File

@@ -6,8 +6,8 @@
//! nach `LOCATE`, `CLS` oder einem Umbruch am rechten Rand überein.
use crate::errors::RuntimeError;
use crate::format::format_print;
use crate::fileio::Dateien;
use crate::format::format_print;
use crate::screen::TextScreen;
use crate::value::Value;

View File

@@ -264,7 +264,10 @@ mod tests {
// In einer Zone mit Sommerzeit unterscheiden sie sich um genau
// die Umstellungsspanne, sonst gar nicht.
let d = (a - b).abs();
assert!(d == 0 || (1800..=7200).contains(&d), "Spanne {d} unplausibel");
assert!(
d == 0 || (1800..=7200).contains(&d),
"Spanne {d} unplausibel"
);
}
}

View File

@@ -84,12 +84,14 @@ impl Datei {
}
let datei = opt.open(pfad).map_err(fehler_aus_io)?;
let leser = match modus {
Modus::Input => Some(BufReader::new(
File::open(pfad).map_err(fehler_aus_io)?,
)),
Modus::Input => Some(BufReader::new(File::open(pfad).map_err(fehler_aus_io)?)),
_ => None,
};
let reclen = if modus == Modus::Random { reclen.max(1) } else { 1 };
let reclen = if modus == Modus::Random {
reclen.max(1)
} else {
1
};
Ok(Datei {
modus,
pfad: pfad.to_path_buf(),
@@ -104,7 +106,10 @@ impl Datei {
/// Dateigröße in Bytes.
pub fn laenge(&self) -> Result<u64, RuntimeError> {
self.datei.metadata().map(|m| m.len()).map_err(fehler_aus_io)
self.datei
.metadata()
.map(|m| m.len())
.map_err(fehler_aus_io)
}
/// `EOF` — bei sequenziellem Lesen: nichts mehr im Puffer; sonst:
@@ -127,9 +132,7 @@ impl Datei {
if !matches!(self.modus, Modus::Output | Modus::Append) {
return Err(RuntimeError(54)); // Bad file mode
}
self.datei
.write_all(text.as_bytes())
.map_err(fehler_aus_io)
self.datei.write_all(text.as_bytes()).map_err(fehler_aus_io)
}
/// Eine Zeile lesen (ohne Zeilenende); `None` = Dateiende.
@@ -243,7 +246,8 @@ impl Dateien {
if modus == Modus::Input && !p.exists() {
return Err(RuntimeError(53)); // File not found
}
self.offen.insert(nummer, Datei::oeffnen(&p, modus, reclen)?);
self.offen
.insert(nummer, Datei::oeffnen(&p, modus, reclen)?);
Ok(())
}
@@ -403,7 +407,10 @@ pub fn wert_schreiben(
feld_setzen(puffer, offset, *len as usize, s, false)
}
(TypeInit::Udt(i), Value::Rec(r)) => {
let felder = &layouts.get(*i as usize).ok_or(RuntimeError::TYPE_MISMATCH)?.fields;
let felder = &layouts
.get(*i as usize)
.ok_or(RuntimeError::TYPE_MISMATCH)?
.fields;
let rec = r.borrow();
let mut off = offset;
for (ft, fv) in felder.iter().zip(rec.fields.iter()) {
@@ -433,11 +440,14 @@ pub fn wert_lesen(
TypeInit::Sng => Value::Sng(f32::from_le_bytes([b[0], b[1], b[2], b[3]])),
TypeInit::Dbl => Value::Dbl(f64::from_le_bytes(b[..8].try_into().unwrap())),
TypeInit::Cur => Value::Cur(i64::from_le_bytes(b[..8].try_into().unwrap())),
TypeInit::FixedStr(len) => {
Value::Str(std::rc::Rc::from(feld_lesen(puffer, offset, *len as usize).as_str()))
}
TypeInit::FixedStr(len) => Value::Str(std::rc::Rc::from(
feld_lesen(puffer, offset, *len as usize).as_str(),
)),
TypeInit::Udt(i) => {
let felder = &layouts.get(*i as usize).ok_or(RuntimeError::TYPE_MISMATCH)?.fields;
let felder = &layouts
.get(*i as usize)
.ok_or(RuntimeError::TYPE_MISMATCH)?
.fields;
let mut off = offset;
let mut werte = Vec::with_capacity(felder.len());
for ft in felder {
@@ -468,10 +478,10 @@ pub fn pfad_normieren(p: &str) -> PathBuf {
fn fehler_aus_io(e: std::io::Error) -> RuntimeError {
use std::io::ErrorKind::*;
match e.kind() {
NotFound => RuntimeError(53), // File not found
NotFound => RuntimeError(53), // File not found
PermissionDenied => RuntimeError(70), // Permission denied
AlreadyExists => RuntimeError(58), // File already exists
_ => RuntimeError(57), // Device I/O error
AlreadyExists => RuntimeError(58), // File already exists
_ => RuntimeError(57), // Device I/O error
}
}
@@ -495,7 +505,9 @@ pub fn umbenennen(alt: &str, neu: &str) -> Result<(), RuntimeError> {
/// `MKDIR` / `RMDIR` / `CHDIR`.
pub fn verzeichnis_anlegen(pfad: &str) -> Result<(), RuntimeError> {
let p = pfad_normieren(pfad);
if p.parent().is_some_and(|e| !e.as_os_str().is_empty() && !e.exists()) {
if p.parent()
.is_some_and(|e| !e.as_os_str().is_empty() && !e.exists())
{
return Err(RuntimeError(76)); // Path not found
}
std::fs::create_dir(p).map_err(fehler_aus_io)
@@ -558,11 +570,7 @@ pub fn passt(name: &str, muster: &str) -> bool {
None => n.is_empty(),
Some('*') => rek(n, &m[1..]) || (!n.is_empty() && rek(&n[1..], m)),
Some('?') => !n.is_empty() && rek(&n[1..], &m[1..]),
Some(c) => {
!n.is_empty()
&& n[0].eq_ignore_ascii_case(c)
&& rek(&n[1..], &m[1..])
}
Some(c) => !n.is_empty() && n[0].eq_ignore_ascii_case(c) && rek(&n[1..], &m[1..]),
}
}
rek(&n, &m)

View File

@@ -86,14 +86,7 @@ pub fn nper(zins: f64, zahlung: f64, barwert: f64, endwert: f64, faellig: f64) -
}
/// `IPmt#` — Zinsanteil der Periode `periode` (1-basiert).
pub fn ipmt(
zins: f64,
periode: f64,
perioden: f64,
barwert: f64,
endwert: f64,
faellig: f64,
) -> R {
pub fn ipmt(zins: f64, periode: f64, perioden: f64, barwert: f64, endwert: f64, faellig: f64) -> R {
if periode < 1.0 || periode > perioden {
return Err(ungueltig());
}
@@ -111,14 +104,7 @@ pub fn ipmt(
}
/// `PPmt#` — Tilgungsanteil der Periode.
pub fn ppmt(
zins: f64,
periode: f64,
perioden: f64,
barwert: f64,
endwert: f64,
faellig: f64,
) -> R {
pub fn ppmt(zins: f64, periode: f64, perioden: f64, barwert: f64, endwert: f64, faellig: f64) -> R {
let zahlung = pmt(zins, perioden, barwert, endwert, faellig)?;
let zinsanteil = ipmt(zins, periode, perioden, barwert, endwert, faellig)?;
Ok(zahlung - zinsanteil)
@@ -144,7 +130,11 @@ pub fn rate(
Some(barwert * faktor(r, perioden) + zahlung * rentenfaktor(r, perioden, faellig) + endwert)
};
let mut r0 = schaetzung;
let mut r1 = if schaetzung == 0.0 { 0.1 } else { schaetzung * 1.1 };
let mut r1 = if schaetzung == 0.0 {
0.1
} else {
schaetzung * 1.1
};
let (mut f0, mut f1) = match (f(r0), f(r1)) {
(Some(a), Some(b)) => (a, b),
_ => return Err(ungueltig()),
@@ -206,7 +196,11 @@ pub fn irr(werte: &[f64], schaetzung: f64) -> R {
Some(summe)
};
let mut r0 = schaetzung;
let mut r1 = if schaetzung == 0.0 { 0.1 } else { schaetzung * 1.1 };
let mut r1 = if schaetzung == 0.0 {
0.1
} else {
schaetzung * 1.1
};
let (mut f0, mut f1) = match (f(r0), f(r1)) {
(Some(a), Some(b)) => (a, b),
_ => return Err(ungueltig()),
@@ -246,7 +240,8 @@ pub fn mirr(werte: &[f64], finanzierungszins: f64, wiederanlagezins: f64) -> R {
return Err(ungueltig());
}
let n = n as f64;
let verhaeltnis = -bw_pos * (1.0 + wiederanlagezins).powf(n) / (bw_neg * (1.0 + finanzierungszins));
let verhaeltnis =
-bw_pos * (1.0 + wiederanlagezins).powf(n) / (bw_neg * (1.0 + finanzierungszins));
if verhaeltnis <= 0.0 {
return Err(ungueltig());
}
@@ -266,8 +261,10 @@ pub fn syd(anschaffung: f64, restwert: f64, nutzungsdauer: f64, periode: f64) ->
if nutzungsdauer <= 0.0 || periode < 1.0 || periode > nutzungsdauer {
return Err(ungueltig());
}
Ok((anschaffung - restwert) * (nutzungsdauer - periode + 1.0) * 2.0
/ (nutzungsdauer * (nutzungsdauer + 1.0)))
Ok(
(anschaffung - restwert) * (nutzungsdauer - periode + 1.0) * 2.0
/ (nutzungsdauer * (nutzungsdauer + 1.0)),
)
}
/// `DDB#` — geometrisch-degressive Abschreibung (doppelter linearer Satz).
@@ -353,7 +350,9 @@ mod tests {
fn abschreibungen() {
nah(sln(1000.0, 100.0, 10.0).unwrap(), 90.0);
// SYD: Summe über alle Perioden = Abschreibungsvolumen.
let summe: f64 = (1..=10).map(|p| syd(1000.0, 100.0, 10.0, p as f64).unwrap()).sum();
let summe: f64 = (1..=10)
.map(|p| syd(1000.0, 100.0, 10.0, p as f64).unwrap())
.sum();
nah(summe, 900.0);
nah(syd(1000.0, 100.0, 10.0, 1.0).unwrap(), 163.636363);
nah(ddb(1000.0, 100.0, 10.0, 1.0).unwrap(), 200.0);

View File

@@ -69,7 +69,11 @@ fn fmt_float(x: f64, sig: usize, expch: char) -> String {
return "NaN".to_string();
}
if x.is_infinite() {
return if x < 0.0 { "-1E+38".into() } else { "1E+38".into() };
return if x < 0.0 {
"-1E+38".into()
} else {
"1E+38".into()
};
}
let neg = x < 0.0;
let ax = x.abs();
@@ -92,7 +96,11 @@ fn fmt_float(x: f64, sig: usize, expch: char) -> String {
m.push('.');
m.push_str(&digits[1..]);
}
format!("{m}{expch}{}{:02}", if exp < 0 { '-' } else { '+' }, exp.abs())
format!(
"{m}{expch}{}{:02}",
if exp < 0 { '-' } else { '+' },
exp.abs()
)
} else if exp >= 0 {
let e = exp as usize;
if (e + 1) >= digits.len() {
@@ -128,7 +136,10 @@ pub fn val(s: &str) -> f64 {
return i64::from_str_radix(&hex, 16).unwrap_or(0) as f64;
}
if let Some(rest) = t.strip_prefix("&O").or_else(|| t.strip_prefix("&o")) {
let oct: String = rest.chars().take_while(|c| ('0'..='7').contains(c)).collect();
let oct: String = rest
.chars()
.take_while(|c| ('0'..='7').contains(c))
.collect();
return i64::from_str_radix(&oct, 8).unwrap_or(0) as f64;
}
let bytes: Vec<char> = t.chars().collect();

View File

@@ -154,10 +154,19 @@ struct Bindung {
#[derive(Debug, Clone)]
enum Undo {
/// Der Satz wurde eingefügt — Rücknahme entfernt ihn wieder.
Eingefuegt { pfad: PathBuf, tabelle: String, id: u64 },
Eingefuegt {
pfad: PathBuf,
tabelle: String,
id: u64,
},
/// Der Satz wurde geändert oder gelöscht — Rücknahme stellt die
/// alten Bytes wieder her.
Vorher { pfad: PathBuf, tabelle: String, id: u64, bytes: Vec<u8> },
Vorher {
pfad: PathBuf,
tabelle: String,
id: u64,
bytes: Vec<u8>,
},
}
impl Undo {
@@ -294,7 +303,11 @@ fn schluessel_anhaengen(out: &mut Vec<u8>, wert: &Value, typ: &TypeInit, absteig
}
TypeInit::Sng => {
let bits = (crate::value::as_f64(wert) as f32).to_bits();
let k = if bits & 0x8000_0000 != 0 { !bits } else { bits | 0x8000_0000 };
let k = if bits & 0x8000_0000 != 0 {
!bits
} else {
bits | 0x8000_0000
};
out.extend_from_slice(&k.to_be_bytes());
}
TypeInit::Dbl => {
@@ -538,11 +551,7 @@ impl Isam {
return Err(RuntimeError::TYPE_MISMATCH);
}
let layout = Layout {
spalten: namen
.iter()
.map(|n| n.to_string())
.zip(felder)
.collect(),
spalten: namen.iter().map(|n| n.to_string()).zip(felder).collect(),
};
let pfad = fileio::pfad_normieren(datenbank);
@@ -616,9 +625,7 @@ impl Isam {
}
}
Some(_) => return Err(INKONSISTENT),
None if neu => {
meta_schreiben(&txn, "version", &FORMATVERSION.to_le_bytes())?
}
None if neu => meta_schreiben(&txn, "version", &FORMATVERSION.to_le_bytes())?,
// Bestehende Datei ohne Versionsmarke: keine Datenbank
// dieses Formats.
None => return Err(INKONSISTENT),
@@ -760,7 +767,11 @@ impl Isam {
if spalten.is_empty() {
return Err(SPALTE_UNGUELTIG);
}
let mut def = Indexdef { name: name.to_string(), eindeutig, spalten: Vec::new() };
let mut def = Indexdef {
name: name.to_string(),
eindeutig,
spalten: Vec::new(),
};
for s in spalten {
let (absteigend, sname) = match s.strip_prefix('-') {
Some(r) => (true, r),
@@ -930,7 +941,11 @@ impl Isam {
let id = self.schreiben(&pfad, move |txn, log| {
let id = naechste_id(txn, &tabelle)?;
satz_schreiben(txn, &tabelle, &layout, &udts, id, Some(&bytes), None)?;
log.push(Undo::Eingefuegt { pfad: fuer_log, tabelle: tabelle.clone(), id });
log.push(Undo::Eingefuegt {
pfad: fuer_log,
tabelle: tabelle.clone(),
id,
});
Ok(id)
})?;
self.belegt += bytes_von(&self.trans);
@@ -1132,7 +1147,9 @@ impl Isam {
praefix.clone()
};
let mut bereich = t.range(von.as_slice()..).map_err(|_| INKONSISTENT)?;
let Some(e) = bereich.next() else { return Ok(None) };
let Some(e) = bereich.next() else {
return Ok(None);
};
let (k, v) = e.map_err(|_| INKONSISTENT)?;
if art == Suchart::Gleich && !k.value().starts_with(&praefix) {
return Ok(None);
@@ -1215,7 +1232,10 @@ impl Isam {
/// `SAVEPOINT` — liefert die Kennung des gesetzten Sicherungspunkts.
pub fn sicherungspunkt(&mut self) -> Result<i16, RuntimeError> {
let t = self.trans.as_mut().ok_or(RuntimeError::ILLEGAL_FUNCTION_CALL)?;
let t = self
.trans
.as_mut()
.ok_or(RuntimeError::ILLEGAL_FUNCTION_CALL)?;
let kennung = t.naechste_kennung;
t.naechste_kennung = t.naechste_kennung.saturating_add(1);
let pos = t.log.len();
@@ -1283,18 +1303,15 @@ impl Isam {
let layout = self.layout_von(&pfad, &tabelle)?;
self.schreiben(&pfad, move |txn, _| {
let alt = satz_bytes_lesen(txn, &tabelle, id)?;
satz_schreiben(
txn,
&tabelle,
&layout,
&udts,
id,
None,
alt.as_deref(),
)
satz_schreiben(txn, &tabelle, &layout, &udts, id, None, alt.as_deref())
})?;
}
Undo::Vorher { pfad, tabelle, id, bytes } => {
Undo::Vorher {
pfad,
tabelle,
id,
bytes,
} => {
let layout = self.layout_von(&pfad, &tabelle)?;
self.schreiben(&pfad, move |txn, _| {
let alt = satz_bytes_lesen(txn, &tabelle, id)?;
@@ -1372,7 +1389,10 @@ fn satz_bytes_lesen(
let name = satz_def(tabelle);
let def: SatzTab = TableDefinition::new(&name);
let t = txn.open_table(def).map_err(|_| INKONSISTENT)?;
let gefunden = t.get(id).map_err(|_| INKONSISTENT)?.map(|v| v.value().to_vec());
let gefunden = t
.get(id)
.map_err(|_| INKONSISTENT)?
.map(|v| v.value().to_vec());
Ok(gefunden)
}

View File

@@ -38,8 +38,11 @@ fn kodierung_erhaelt_die_ordnung_bei_zufallspaaren() {
let a = r.next() as i16;
let b = r.next() as i16;
assert_eq!(
kodiere(&Value::Int(a), &TypeInit::Int, false)
.cmp(&kodiere(&Value::Int(b), &TypeInit::Int, false)),
kodiere(&Value::Int(a), &TypeInit::Int, false).cmp(&kodiere(
&Value::Int(b),
&TypeInit::Int,
false
)),
a.cmp(&b),
"INTEGER {a} vs {b}"
);
@@ -48,8 +51,11 @@ fn kodierung_erhaelt_die_ordnung_bei_zufallspaaren() {
let a = r.next() as i32;
let b = r.next() as i32;
assert_eq!(
kodiere(&Value::Lng(a), &TypeInit::Lng, false)
.cmp(&kodiere(&Value::Lng(b), &TypeInit::Lng, false)),
kodiere(&Value::Lng(a), &TypeInit::Lng, false).cmp(&kodiere(
&Value::Lng(b),
&TypeInit::Lng,
false
)),
a.cmp(&b),
"LONG {a} vs {b}"
);
@@ -58,8 +64,11 @@ fn kodierung_erhaelt_die_ordnung_bei_zufallspaaren() {
let a = r.next() as i32 as i64;
let b = r.next() as i32 as i64;
assert_eq!(
kodiere(&Value::Cur(a), &TypeInit::Cur, false)
.cmp(&kodiere(&Value::Cur(b), &TypeInit::Cur, false)),
kodiere(&Value::Cur(a), &TypeInit::Cur, false).cmp(&kodiere(
&Value::Cur(b),
&TypeInit::Cur,
false
)),
a.cmp(&b),
"CURRENCY {a} vs {b}"
);
@@ -68,8 +77,11 @@ fn kodierung_erhaelt_die_ordnung_bei_zufallspaaren() {
let a = (r.next() as i32 as f64) / 1024.0;
let b = (r.next() as i32 as f64) / 1024.0;
assert_eq!(
kodiere(&Value::Dbl(a), &TypeInit::Dbl, false)
.cmp(&kodiere(&Value::Dbl(b), &TypeInit::Dbl, false)),
kodiere(&Value::Dbl(a), &TypeInit::Dbl, false).cmp(&kodiere(
&Value::Dbl(b),
&TypeInit::Dbl,
false
)),
a.partial_cmp(&b).unwrap(),
"DOUBLE {a} vs {b}"
);
@@ -78,8 +90,11 @@ fn kodierung_erhaelt_die_ordnung_bei_zufallspaaren() {
let a = (r.next() as i32 as f32) / 64.0;
let b = (r.next() as i32 as f32) / 64.0;
assert_eq!(
kodiere(&Value::Sng(a), &TypeInit::Sng, false)
.cmp(&kodiere(&Value::Sng(b), &TypeInit::Sng, false)),
kodiere(&Value::Sng(a), &TypeInit::Sng, false).cmp(&kodiere(
&Value::Sng(b),
&TypeInit::Sng,
false
)),
a.partial_cmp(&b).unwrap(),
"SINGLE {a} vs {b}"
);
@@ -88,14 +103,19 @@ fn kodierung_erhaelt_die_ordnung_bei_zufallspaaren() {
// Dialekts, der auf UTF-8-Bytes vergleicht (interp::CmpStr).
let mach = |x: u32| -> String {
let zeichen = ['a', 'b', 'z', 'A', 'Z', 'ä', 'ß', '€'];
(0..4).map(|i| zeichen[((x >> (i * 3)) & 7) as usize]).collect()
(0..4)
.map(|i| zeichen[((x >> (i * 3)) & 7) as usize])
.collect()
};
let sa = mach(r.next());
let sb = mach(r.next());
let t = TypeInit::FixedStr(4);
assert_eq!(
kodiere(&Value::Str(Rc::from(sa.as_str())), &t, false)
.cmp(&kodiere(&Value::Str(Rc::from(sb.as_str())), &t, false)),
kodiere(&Value::Str(Rc::from(sa.as_str())), &t, false).cmp(&kodiere(
&Value::Str(Rc::from(sb.as_str())),
&t,
false
)),
sa.as_bytes().cmp(sb.as_bytes()),
"TEXT {sa:?} vs {sb:?}"
);
@@ -181,7 +201,10 @@ impl Drop for TempDb {
}
fn isam_mit_tabelle(db: &str) -> Isam {
let mut i = Isam { udts: test_udts(), ..Default::default() };
let mut i = Isam {
udts: test_udts(),
..Default::default()
};
i.oeffnen(1, db, "Kunden", "Nummer,Name", 0).unwrap();
i
}
@@ -203,9 +226,15 @@ fn hoehere_formatversion_wird_abgewiesen() {
meta_schreiben(&txn, "version", &(FORMATVERSION + 1).to_le_bytes()).unwrap();
txn.commit().unwrap();
}
let mut i = Isam { udts: test_udts(), ..Default::default() };
let mut i = Isam {
udts: test_udts(),
..Default::default()
};
let e = i.oeffnen(1, &pfad, "Kunden", "Nummer,Name", 0).unwrap_err();
assert_eq!(e, INKONSISTENT, "höhere Formatversion muss benannt scheitern");
assert_eq!(
e, INKONSISTENT,
"höhere Formatversion muss benannt scheitern"
);
}
#[test]
@@ -213,7 +242,10 @@ fn beschaedigte_datei_meldet_fehler_88() {
let t = TempDb::neu("kaputt");
let pfad = t.pfad("kaputt.isam");
std::fs::write(&pfad, b"das ist keine Datenbankdatei").unwrap();
let mut i = Isam { udts: test_udts(), ..Default::default() };
let mut i = Isam {
udts: test_udts(),
..Default::default()
};
let e = i.oeffnen(1, &pfad, "Kunden", "Nummer,Name", 0).unwrap_err();
assert_eq!(e, RuntimeError(88));
}
@@ -229,7 +261,10 @@ fn geloeschte_satz_id_wird_nicht_neu_vergeben() {
i.satz_loeschen(1).unwrap();
i.einfuegen(1, &satz(2, "zwei")).unwrap();
let zweite = i.satznummer(1).unwrap();
assert_ne!(erste, zweite, "eine gelöschte ID darf nicht neu vergeben werden");
assert_ne!(
erste, zweite,
"eine gelöschte ID darf nicht neu vergeben werden"
);
assert!(zweite > erste);
}
@@ -249,8 +284,12 @@ fn satz_roundtrip_ueber_alle_feldtypen() {
TypeInit::FixedStr(5),
],
}];
let mut i = Isam { udts, ..Default::default() };
i.oeffnen(1, &t.pfad("db.isam"), "Alles", "A,B,C,D,E,F", 0).unwrap();
let mut i = Isam {
udts,
..Default::default()
};
i.oeffnen(1, &t.pfad("db.isam"), "Alles", "A,B,C,D,E,F", 0)
.unwrap();
let original = Value::Rec(Rc::new(RefCell::new(RecordObj {
fields: vec![
Value::Int(-7),
@@ -262,7 +301,9 @@ fn satz_roundtrip_ueber_alle_feldtypen() {
],
})));
i.einfuegen(1, &original).unwrap();
let Value::Rec(gelesen) = i.satz_lesen(1).unwrap() else { panic!("kein Record") };
let Value::Rec(gelesen) = i.satz_lesen(1).unwrap() else {
panic!("kein Record")
};
let f = &gelesen.borrow().fields;
assert!(matches!(f[0], Value::Int(-7)));
assert!(matches!(f[1], Value::Lng(123456)));
@@ -279,7 +320,8 @@ fn satz_roundtrip_ueber_alle_feldtypen() {
fn indexeintraege_stehen_in_schluesselreihenfolge() {
let t = TempDb::neu("indexordnung");
let mut i = isam_mit_tabelle(&t.pfad("db.isam"));
i.index_anlegen(1, "NachName", false, &["Name".into()]).unwrap();
i.index_anlegen(1, "NachName", false, &["Name".into()])
.unwrap();
for (n, name) in [(3, "Cäsar"), (1, "Anton"), (2, "Berta")] {
i.einfuegen(1, &satz(n, name)).unwrap();
}
@@ -287,8 +329,12 @@ fn indexeintraege_stehen_in_schluesselreihenfolge() {
let mut namen = Vec::new();
i.bewegen(1, Richtung::Erster).unwrap();
while !i.eof(1) {
let Value::Rec(r) = i.satz_lesen(1).unwrap() else { panic!() };
let Value::Str(s) = r.borrow().fields[1].clone() else { panic!() };
let Value::Rec(r) = i.satz_lesen(1).unwrap() else {
panic!()
};
let Value::Str(s) = r.borrow().fields[1].clone() else {
panic!()
};
namen.push(s.trim_end().to_string());
i.bewegen(1, Richtung::Naechster).unwrap();
}
@@ -303,7 +349,8 @@ fn indexeintraege_stehen_in_schluesselreihenfolge() {
fn cursor_ueberlebt_eine_satzaenderung() {
let t = TempDb::neu("cursor");
let mut i = isam_mit_tabelle(&t.pfad("db.isam"));
i.index_anlegen(1, "NachName", false, &["Name".into()]).unwrap();
i.index_anlegen(1, "NachName", false, &["Name".into()])
.unwrap();
for (n, name) in [(1, "Anton"), (2, "Berta"), (3, "Cäsar")] {
i.einfuegen(1, &satz(n, name)).unwrap();
}
@@ -313,18 +360,31 @@ fn cursor_ueberlebt_eine_satzaenderung() {
let vorher = i.satznummer(1).unwrap();
// Über eine zweite Bindung einen anderen Satz einfügen.
i.oeffnen(2, &t.pfad("db.isam"), "Kunden", "Nummer,Name", 0).unwrap();
i.oeffnen(2, &t.pfad("db.isam"), "Kunden", "Nummer,Name", 0)
.unwrap();
i.einfuegen(2, &satz(4, "Anna")).unwrap();
assert_eq!(i.satznummer(1).unwrap(), vorher, "Cursor darf nicht wandern");
let Value::Rec(r) = i.satz_lesen(1).unwrap() else { panic!() };
let Value::Str(s) = r.borrow().fields[1].clone() else { panic!() };
assert_eq!(
i.satznummer(1).unwrap(),
vorher,
"Cursor darf nicht wandern"
);
let Value::Rec(r) = i.satz_lesen(1).unwrap() else {
panic!()
};
let Value::Str(s) = r.borrow().fields[1].clone() else {
panic!()
};
assert_eq!(s.trim_end(), "Berta");
// Und er bewegt sich weiter in der neuen Ordnung.
i.bewegen(1, Richtung::Naechster).unwrap();
let Value::Rec(r) = i.satz_lesen(1).unwrap() else { panic!() };
let Value::Str(s) = r.borrow().fields[1].clone() else { panic!() };
let Value::Rec(r) = i.satz_lesen(1).unwrap() else {
panic!()
};
let Value::Str(s) = r.borrow().fields[1].clone() else {
panic!()
};
assert_eq!(s.trim_end(), "Cäsar");
}
@@ -383,12 +443,16 @@ fn ungueltige_namen_werden_abgewiesen() {
fn close_beendet_keine_transaktion() {
let t = TempDb::neu("close_trans");
let mut i = isam_mit_tabelle(&t.pfad("db.isam"));
i.oeffnen(2, &t.pfad("db.isam"), "Kunden", "Nummer,Name", 0).unwrap();
i.oeffnen(2, &t.pfad("db.isam"), "Kunden", "Nummer,Name", 0)
.unwrap();
i.trans_beginn().unwrap();
i.einfuegen(1, &satz(1, "eins")).unwrap();
i.schliessen(2).unwrap();
assert!(i.trans.is_some(), "CLOSE darf die Transaktion nicht beenden");
assert!(
i.trans.is_some(),
"CLOSE darf die Transaktion nicht beenden"
);
// Die Rücknahme wirkt danach noch auf die Änderung an #1.
i.ruecknahme(ROLLBACK_ALL).unwrap();
@@ -407,7 +471,10 @@ fn nicht_festgeschriebene_transaktion_verfaellt() {
i.einfuegen(1, &satz(1, "eins")).unwrap();
i.alles_schliessen();
}
let mut i = Isam { udts: test_udts(), ..Default::default() };
let mut i = Isam {
udts: test_udts(),
..Default::default()
};
i.oeffnen(1, &pfad, "Kunden", "Nummer,Name", 0).unwrap();
assert_eq!(
i.satzzahl(1).unwrap(),
@@ -427,7 +494,9 @@ fn gescheitertes_createindex_hinterlaesst_keinen_index() {
i.einfuegen(1, &satz(2, "gleich")).unwrap();
i.trans_beginn().unwrap();
let e = i.index_anlegen(1, "Eindeutig", true, &["Name".into()]).unwrap_err();
let e = i
.index_anlegen(1, "Eindeutig", true, &["Name".into()])
.unwrap_err();
assert_eq!(e, DOPPELTER_SCHLUESSEL);
i.trans_festschreiben().unwrap();

View File

@@ -39,7 +39,12 @@ pub struct Cell {
impl Default for Cell {
fn default() -> Self {
Cell { ch: ' ', fg: 7, bg: 0, fortsetzung: false }
Cell {
ch: ' ',
fg: 7,
bg: 0,
fortsetzung: false,
}
}
}
@@ -125,8 +130,15 @@ impl TextScreen {
if cols == self.cols && rows == self.rows {
return;
}
let mut cells =
vec![Cell { ch: ' ', fg: self.fg, bg: self.bg, fortsetzung: false }; cols * rows];
let mut cells = vec![
Cell {
ch: ' ',
fg: self.fg,
bg: self.bg,
fortsetzung: false
};
cols * rows
];
for row in 0..self.rows.min(rows) {
for col in 0..self.cols.min(cols) {
cells[row * cols + col] = self.cells[row * self.cols + col];
@@ -158,7 +170,12 @@ impl TextScreen {
/// Cursor an den Anfang des Bereichs.
pub fn cls(&mut self) {
self.veraendert = true;
let blank = Cell { ch: ' ', fg: self.fg, bg: self.bg, fortsetzung: false };
let blank = Cell {
ch: ' ',
fg: self.fg,
bg: self.bg,
fortsetzung: false,
};
for row in self.view_top..=self.view_bottom {
self.cells[row * self.cols..(row + 1) * self.cols].fill(blank);
}
@@ -190,7 +207,11 @@ impl TextScreen {
/// Breite der belegten Zeile `z` (1-basiert); 0 für unberührte Zeilen.
pub fn belegte_breite(&self, z: usize) -> usize {
self.belegt.get(z - 1).copied().flatten().map_or(0, |c| c + 1)
self.belegt
.get(z - 1)
.copied()
.flatten()
.map_or(0, |c| c + 1)
}
/// `COLOR vg, hg` (vg 031, hg 07). Blinkende Vordergrundfarben
@@ -273,10 +294,19 @@ impl TextScreen {
let attr = (self.fg, self.bg);
let start = self.cur_row * self.cols + self.cur_col;
self.haelften_freimachen(self.cur_col, breite);
self.cells[start] = Cell { ch, fg: attr.0, bg: attr.1, fortsetzung: false };
self.cells[start] = Cell {
ch,
fg: attr.0,
bg: attr.1,
fortsetzung: false,
};
for i in 1..breite {
self.cells[start + i] =
Cell { ch: ' ', fg: attr.0, bg: attr.1, fortsetzung: true };
self.cells[start + i] = Cell {
ch: ' ',
fg: attr.0,
bg: attr.1,
fortsetzung: true,
};
}
let letzte = self.cur_col + breite - 1;
let b = &mut self.belegt[self.cur_row];
@@ -293,7 +323,12 @@ impl TextScreen {
/// dessen Fortsetzung geleert. Sonst blieben Geisterzeichen stehen.
fn haelften_freimachen(&mut self, col: usize, breite: usize) {
let zeilenanfang = self.cur_row * self.cols;
let leer = Cell { ch: ' ', fg: self.fg, bg: self.bg, fortsetzung: false };
let leer = Cell {
ch: ' ',
fg: self.fg,
bg: self.bg,
fortsetzung: false,
};
if col > 0 && self.cells[zeilenanfang + col].fortsetzung {
self.cells[zeilenanfang + col - 1] = leer;
}
@@ -323,12 +358,20 @@ impl TextScreen {
self.cur_col -= 1;
// War das gelöschte eine Fortsetzung, gehört die Hälfte davor dazu.
if self.cells[self.cur_row * self.cols + self.cur_col].fortsetzung && self.cur_col > 0 {
self.cells[self.cur_row * self.cols + self.cur_col] =
Cell { ch: ' ', fg: self.fg, bg: self.bg, fortsetzung: false };
self.cells[self.cur_row * self.cols + self.cur_col] = Cell {
ch: ' ',
fg: self.fg,
bg: self.bg,
fortsetzung: false,
};
self.cur_col -= 1;
}
self.cells[self.cur_row * self.cols + self.cur_col] =
Cell { ch: ' ', fg: self.fg, bg: self.bg, fortsetzung: false };
self.cells[self.cur_row * self.cols + self.cur_col] = Cell {
ch: ' ',
fg: self.fg,
bg: self.bg,
fortsetzung: false,
};
// Die gelöschte Zelle gilt nicht mehr als belegt.
let b = &mut self.belegt[self.cur_row];
*b = match (self.cur_col, *b) {
@@ -342,13 +385,17 @@ impl TextScreen {
/// Scrollbereich um eine Zeile nach oben schieben; unterste Zeile leeren.
pub fn scroll_up(&mut self) {
self.veraendert = true;
let blank = Cell { ch: ' ', fg: self.fg, bg: self.bg, fortsetzung: false };
let blank = Cell {
ch: ' ',
fg: self.fg,
bg: self.bg,
fortsetzung: false,
};
for row in self.view_top..self.view_bottom {
let (a, b) = self.cells.split_at_mut((row + 1) * self.cols);
a[row * self.cols..].copy_from_slice(&b[..self.cols]);
}
self.cells[self.view_bottom * self.cols..(self.view_bottom + 1) * self.cols]
.fill(blank);
self.cells[self.view_bottom * self.cols..(self.view_bottom + 1) * self.cols].fill(blank);
for row in self.view_top..self.view_bottom {
self.belegt[row] = self.belegt[row + 1];
}
@@ -553,5 +600,4 @@ mod tests {
assert_eq!(s.cell(39, 1).ch, 'a');
assert_eq!(s.cell(40, 1).ch, 'b');
}
}

View File

@@ -59,7 +59,9 @@ pub struct Waehrung {
impl Default for Waehrung {
fn default() -> Self {
Waehrung { zeichen: "$".into() }
Waehrung {
zeichen: "$".into(),
}
}
}
@@ -216,7 +218,9 @@ fn zahl_formatieren(f: &NumFeld, wert: f64, waehrung: &Waehrung) -> String {
let b = gerundet - gerundet.trunc();
let s = format!("{:.*}", f.nach, b);
// "0.25" → "25"
s.split_once('.').map(|(_, r)| r.to_string()).unwrap_or_default()
s.split_once('.')
.map(|(_, r)| r.to_string())
.unwrap_or_default()
} else {
String::new()
};
@@ -231,11 +235,23 @@ fn zahl_formatieren(f: &NumFeld, wert: f64, waehrung: &Waehrung) -> String {
// neben dem Zahlenfeld, nicht darin. Ohne Vorzeichenangabe teilt sich ein
// `-` die Ziffernstellen.
let (vorz_vorn, vorz_hinten, minus_im_feld) = if f.plus_vorn {
(if negativ { "-" } else { "+" }.to_string(), String::new(), false)
(
if negativ { "-" } else { "+" }.to_string(),
String::new(),
false,
)
} else if f.plus_hinten {
(String::new(), if negativ { "-" } else { "+" }.to_string(), false)
(
String::new(),
if negativ { "-" } else { "+" }.to_string(),
false,
)
} else if f.minus_hinten {
(String::new(), if negativ { "-" } else { " " }.to_string(), false)
(
String::new(),
if negativ { "-" } else { " " }.to_string(),
false,
)
} else {
(String::new(), String::new(), negativ)
};
@@ -358,7 +374,7 @@ pub fn using(fmt: &str, werte: &[Value], waehrung: &Waehrung) -> Result<String,
let mut out = String::new();
let mut i = 0usize; // Index im Teile-Vektor
let mut w = 0usize; // Index im Wertevektor
// Schutz gegen Endlosläufe bei Formaten ohne Fortschritt.
// Schutz gegen Endlosläufe bei Formaten ohne Fortschritt.
let mut runden = 0usize;
while w < werte.len() {

View File

@@ -5,7 +5,9 @@
//! Getippte Zeichen erscheinen im Eingabebereich; Sondertasten und
//! Mausereignisse werden in der Statuszeile angezeigt.
use crossterm::event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind};
use crossterm::event::{
self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind,
};
use crossterm::execute;
use std::io::stdout;
use std::time::Duration;
@@ -13,7 +15,10 @@ use tb_ui::screen::{ScreenWidget, TextScreen};
fn testbild(s: &mut TextScreen) {
s.set_color(15, 1);
s.print(&format!("{:^80}", "Terminal Basic — Phase-0-Spike (Esc beendet)"));
s.print(&format!(
"{:^80}",
"Terminal Basic — Phase-0-Spike (Esc beendet)"
));
// Farbraster: alle Vordergrundfarben auf allen Hintergründen
for bg in 0u8..8 {
@@ -70,15 +75,26 @@ fn main() -> anyhow::Result<()> {
KeyCode::Esc => break,
KeyCode::Char(c) => {
screen.print(&c.to_string());
status(&mut screen, &format!("Taste: {:?} Modifier: {:?}", k.code, k.modifiers));
status(
&mut screen,
&format!("Taste: {:?} Modifier: {:?}", k.code, k.modifiers),
);
}
KeyCode::Enter => screen.print("\n"),
other => status(&mut screen, &format!("Sondertaste: {other:?} Modifier: {:?}", k.modifiers)),
other => status(
&mut screen,
&format!("Sondertaste: {other:?} Modifier: {:?}", k.modifiers),
),
},
Event::Mouse(m) => {
status(
&mut screen,
&format!("Maus: {:?} bei Spalte {}, Zeile {}", m.kind, m.column + 1, m.row + 1),
&format!(
"Maus: {:?} bei Spalte {}, Zeile {}",
m.kind,
m.column + 1,
m.row + 1
),
);
}
Event::Resize(w, h) => {

View File

@@ -50,19 +50,21 @@ impl Widget for ScreenWidget<'_> {
let mut s = String::new();
s.push(c.ch);
cell.set_symbol(&s);
cell.set_style(
Style::default().fg(basic_color(c.fg)).bg(basic_color(c.bg)),
);
cell.set_style(Style::default().fg(basic_color(c.fg)).bg(basic_color(c.bg)));
}
}
}
// Cursor als invertierte Zelle darstellen (Terminal-Cursor wird in
// der Forms-/Runtime-Schicht später gezielt gesteuert).
if self.0.cursor_visible && self.0.csrlin() <= rows && self.0.pos() <= cols {
let (cx, cy) = (area.x + (self.0.pos() - 1) as u16, area.y + (self.0.csrlin() - 1) as u16);
let (cx, cy) = (
area.x + (self.0.pos() - 1) as u16,
area.y + (self.0.csrlin() - 1) as u16,
);
if let Some(cell) = buf.cell_mut((cx, cy)) {
cell.set_style(
cell.style().add_modifier(ratatui::style::Modifier::REVERSED),
cell.style()
.add_modifier(ratatui::style::Modifier::REVERSED),
);
}
}

View File

@@ -74,7 +74,11 @@ fn main() {
println!(
" Einzelmodul: {single_lines} Zeilen in {:.2} ms (Budget 50 ms) {}",
best_single * 1000.0,
if best_single < 0.050 { "OK" } else { "VERFEHLT" }
if best_single < 0.050 {
"OK"
} else {
"VERFEHLT"
}
);
println!(
" Projekt: {project_lines} Zeilen in {:.0} ms (Budget 1000 ms) {}{instrs} Instruktionen",

View File

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

View File

@@ -0,0 +1,114 @@
# Design — Steuerelemente, Menüs, Dialoge
## Context
Siehe proposal.md — Why. Dieser Change setzt auf drei fertigen Stücken
auf: dem Zellenpuffer aus Phase 3, der Ereignisschleife samt Mausquelle
(`phase-4-ereignisschleife`) und dem Objektmodell
(`phase-4-objektmodell`). Er ist der breiteste Change der Phase — 15
Klassen, Menüs, Dialoge —, aber der mit den wenigsten offenen
Architekturfragen.
Die Forms-Referenz lässt drei Detailfragen offen, die hier beantwortet
werden müssen: die Optik je Zustand, die Z-Reihenfolge bei Überlappung
und die Reihenfolge gleichzeitig fälliger Timer.
## Goals / Non-Goals
**Goals:**
- Eine Darstellung, die im Zellenpuffer entsteht und deshalb mit dem
bestehenden Snapshot-Vergleich prüfbar ist.
- Eingabebehandlung, die je Klasse an einer Stelle steht, statt über
Sonderfälle in der Schleife verteilt zu sein.
**Non-Goals:**
- Pixelgenaue Nachbildung der Originaloptik; maßgeblich sind Aufbau und
Zeichen, nicht der Farbton eines Schattens.
- Ein Layoutalgorithmus. Steuerelemente stehen, wo ihre Koordinaten sie
hinstellen.
## Decisions
### D1 — Zeichnen ist eine Funktion des Zustands, kein Nebeneffekt
Jede Klasse zeichnet sich vollständig aus ihren Eigenschaften in den
Zellenpuffer. Es gibt keinen inkrementellen Zeichenpfad und kein
Merken zuvor gezeichneter Bereiche.
| Alternative | Warum nicht |
|---|---|
| Nur veränderte Bereiche neu zeichnen | Bei 80×25 Zellen ist das Neuzeichnen ohnehin billig; der Zustandsabgleich wäre die zweite Quelle der Wahrheit neben den Eigenschaften |
Neu gezeichnet wird an den Zustellpunkten der Ereignisschleife, wenn
eine Eigenschaft sich geändert hat — dieselbe Bedingung, die der
Bildschirmpuffer heute schon für `present` nutzt.
### D2 — Eingabe geht durch eine Kette, nicht durch eine Fallunterscheidung
Ein Tastenereignis läuft: Menü (wenn offen) → modaler Dialog (wenn
offen) → Access-Key des Formulars → fokussiertes Steuerelement →
`Default`/`Cancel`-Schaltfläche → Formular. Jede Station nimmt das
Ereignis an oder gibt es weiter. Für die Maus entsprechend: Menü →
Dialog → Trefferprüfung über die Z-Reihenfolge → Formular.
Die Kette ist die einzige Stelle, an der Vorrang entschieden wird; die
Klassen selbst wissen nichts über einander.
### D3 — Antworten auf die offenen Detailfragen der Forms-Referenz
- **Optik je Zustand**: aus den Original-Screenshots abgeleitet und je
Klasse in der Forms-Referenz als Zeichenbild festgehalten, bevor
gezeichnet wird — sonst legt der erste Implementierungsversuch sie
stillschweigend fest.
- **Z-Reihenfolge**: Reihenfolge der Erzeugung, später Erzeugtes liegt
oben; Steuerelement-Arrays nach Index. Das ist die Regel, die aus einer
`.FRM` reproduzierbar folgt.
- **Gleichzeitig fällige Timer**: in aufsteigender Reihenfolge ihres
Namens im Formular, damit die Ausgabe eines Korpusprogramms nicht von
einer Hashreihenfolge abhängt.
Alle drei werden in `docs/forms-referenz.md` als unsere Festlegung
gekennzeichnet, nicht als Referenzverhalten ausgegeben.
### D4 — Dialoge sind Formulare, keine Sonderfälle
`MSGBOX` und `INPUTBOX$` bauen ein Formular mit Label und Schaltflächen
und zeigen es modal über den Weg aus `phase-4-objektmodell` (Frame-Marke,
D4 dort). Damit gelten Fokus, Access-Keys und Esc ohne Sonderbehandlung,
und die Dialoge sind mit demselben Snapshot-Vergleich prüfbar wie jedes
andere Formular.
### D5 — Menü hält die Ereigniszustellung an
Die Forms-Referenz nennt es für das Vorbild: Zeitereignisse und Trapping
ruhen, solange ein Menü den Fokus hat. Umgesetzt wird das über den
`STOP`-Zustand der Ereignissteuerung — kein neuer Mechanismus, sondern
der vorhandene, vom Menü gesetzt und beim Schließen zurückgenommen.
### D6 — Dateisystem-Steuerelemente werden plattformneutral abgebildet
DriveListBox zeigt keine Laufwerksbuchstaben, sondern die Wurzeln bzw.
Einhängepunkte der Plattform; DirListBox und FileListBox arbeiten auf
Pfaden. `Pattern` bleibt das Muster des Vorbilds. Die Abweichung wird in
der Sprachreferenz festgehalten.
## Risks / Trade-offs
- **Breite statt Tiefe** → 15 Klassen sind viel Fläche für Flüchtigkeit;
jede Klasse bekommt ihren eigenen Korpusnachweis, nicht nur einen
gemeinsamen Sammeltest.
- **Vollständiges Neuzeichnen bei großen Terminals** → bei 200×60 sind es
12 000 Zellen je Anzeige; falls das messbar stört, greift die
Bedingung „nur bei Änderung" bereits heute, und ein Ausbau bleibt
möglich, ohne die Klassen anzufassen.
- **Fremdprogramme scheitern aus unerwartetem Grund** → jeder Befund wird
festgehalten statt umgangen; er ist das eigentliche Ergebnis des
Kompatibilitätstests.
## Open Questions
- Ob die PictureBox als Container für OptionButton-Gruppen dieselbe
Fokuslogik wie der Frame braucht, zeigt der erste Korpusnachweis mit
gruppierten Optionsfeldern.

View File

@@ -0,0 +1,80 @@
# Phase 4 (Abschluss) — Steuerelemente, Menüs, Dialoge
## Why
Das Objektmodell (`phase-4-objektmodell`) macht Formulare und
Steuerelemente ansprechbar, zeigt aber nichts an und nimmt nichts
entgegen. Dieser Change füllt die Klassen mit Verhalten: Darstellung im
Zellenpuffer, Fokus- und Tabreihenfolge, Access-Keys, Maussteuerung,
Menüsystem und die drei vordefinierten Dialoge. Damit schließt Phase 4.
Die drei Dialoge (`MSGBOX` als Anweisung **und** als Funktion,
`INPUTBOX$`) sind die letzten drei offenen Inventareinträge der Phase.
Sie stehen in keiner Steuerelementliste und fielen deshalb bisher
zwischen die Aufgaben.
## What Changes
- **Steuerelementklassen mit Verhalten**: CommandButton, TextBox,
ListBox, ComboBox, CheckBox, OptionButton, Frame, Label, HScrollBar,
VScrollBar, PictureBox, Timer sowie die Dateisystem-Steuerelemente
DirListBox, DriveListBox und FileListBox — je mit Darstellung,
Zuständen (normal, fokussiert, deaktiviert) und ihren Methoden.
- **Darstellung im Zellenpuffer**: Steuerelemente zeichnen in den
vorhandenen Textbildschirm; es entsteht keine zweite Zeichenschicht.
Die höhenabhängige Darstellung des CommandButton (1 Zeile `<Text>`,
2 Zeilen Rahmen, ab 3 Zeilen Kasten) und die Rahmenarten der übrigen
Klassen folgen der Forms-Referenz.
- **Fokus, Tabreihenfolge, Access-Keys**: `TabIndex`/`TabStop`,
Weiterschalten mit Tab und Umschalt-Tab, `&` im Text als Access-Key,
`Default`- und `Cancel`-Schaltfläche für Enter und Esc, `SETFOCUS`,
`GotFocus`/`LostFocus`.
- **Maussteuerung**: Die Mausereignisse aus `phase-4-ereignisschleife`
werden auf Steuerelemente abgebildet — Trefferprüfung über die
Z-Reihenfolge, Klick, Doppelklick, `MouseDown`/`MouseMove`/`MouseUp`
sowie Ziehen und Ablegen (`DragMode`, `DRAG`, `DragDrop`, `DragOver`).
- **Menüsystem**: Menüleiste je Formular, bis zu sechs Ebenen,
Access-Keys, Shortcuts, `Checked`/`Enabled`/`Visible`/`Separator`,
Menü-Steuerelement-Arrays. Während ein Menü den Fokus hält, ruhen
Zeitereignisse und Traps.
- **Vordefinierte Dialoge** (3 Inventareinträge): `MSGBOX` als Anweisung
und als Funktion mit den Schaltflächengruppen und Rückgabewerten der
Sprachreferenz, `INPUTBOX$` mit fester Größe 46×16 Zeichen und
Positionierung in Zeichen.
- **Timer als Steuerelement**: `Interval` 065 535 ms auf der Zeitquelle
der Ereignisschleife, Ereignis `Timer`.
**Non-Goals:** Der Formular-Designer und die Projektverwaltung (Phase 5);
native Erweiterungssteuerelemente (Stufe 2); grafische Ausgabe in der
PictureBox — sie ist eine Textzeichenfläche.
## Capabilities
### New Capabilities
- `forms-steuerelemente`: Verhalten und Darstellung der
Steuerelementklassen, Fokus- und Tabreihenfolge, Access-Keys,
Maussteuerung mit Ziehen und Ablegen, Menüsystem und die
vordefinierten Dialoge.
### Modified Capabilities
- `kompat-testkorpus`: Der Korpus SHALL Formularprogramme mit
Bildschirm-Sollausgabe und deterministischer Ereignisfolge führen.
## Impact
- `crates/tb-ui`: Darstellung und Eingabebehandlung je Klasse, Menüs,
Dialoge, Trefferprüfung, Fokusverwaltung.
- `crates/tb-runtime`: Fehler 260480 des Forms-Bereichs als Auslöser;
`MSGBOX`/`INPUTBOX$` als Sprachelemente.
- `crates/tb-frontend`: Signaturen von `MSGBOX` (Anweisung und Funktion)
und `INPUTBOX$`; die `Unsupported`-Absenkung von `MSGBOX` entfällt.
- `tests/compat`: Formularprogramme mit Sollausgabe; die Programme aus
`github.com/cout/vbdos` als Kompatibilitätsnachweis.
- `docs/`: `forms-referenz.md` — die offenen Detailfragen (Optik je
Zustand, Z-Reihenfolge, Reihenfolge gleichzeitig fälliger Timer)
werden beantwortet; `inventar.md` setzt die Einträge dieses Changes
auf `implementiert`.
- PLAN.md: Punkte „Steuerelemente", „Menüsystem", „Fokus-/Tab-Reihenfolge",
„Vordefinierte Dialoge" und die beiden Meilensteine der Phase 4.

View File

@@ -0,0 +1,138 @@
## Purpose
Die Steuerelemente machen ein Formular bedienbar: sie stellen sich im
Textbildschirm dar, nehmen Tastatur und Maus entgegen, führen Fokus und
Tabreihenfolge, tragen die Menüleiste und stellen die vordefinierten
Dialoge bereit.
## ADDED Requirements
### Requirement: Darstellung im Zellenpuffer
Steuerelemente SHALL sich im vorhandenen Textbildschirm darstellen; es
MUST NOT eine zweite Zeichenschicht neben ihm entstehen. Jede Klasse
SHALL die in der Forms-Referenz festgelegte Optik für die Zustände
normal, fokussiert und deaktiviert zeigen. Der CommandButton SHALL seine
Darstellung nach der Höhe wählen: eine Zeile als `<Text>`, zwei Zeilen
mit einzeiligem Rahmen, ab drei Zeilen als Kasten. Überlappen
Steuerelemente, SHALL die festgelegte Z-Reihenfolge entscheiden, welches
sichtbar ist.
#### Scenario: Schaltfläche nach Höhe
- **WHEN** ein CommandButton mit `Height = 1` und `Caption = "OK"` gezeichnet wird
- **THEN** erscheint im Zellenpuffer `<OK>`
#### Scenario: Deaktivierter Zustand
- **WHEN** ein Steuerelement `Enabled = 0` trägt
- **THEN** unterscheidet sich seine Darstellung sichtbar vom aktiven Zustand und es nimmt keinen Fokus an
### Requirement: Fokus, Tabreihenfolge und Access-Keys
Der Fokus SHALL mit Tab in aufsteigender `TabIndex`-Folge und mit
Umschalt-Tab rückwärts wechseln; Elemente mit `TabStop = 0` oder
`Enabled = 0` MUST übersprungen werden. Ein `&` im Text SHALL den
folgenden Buchstaben zum Access-Key machen, der mit Alt das Element
auslöst oder ihm den Fokus gibt. Enter SHALL die `Default`-Schaltfläche
auslösen, Esc die `Cancel`-Schaltfläche. Fokuswechsel MUST `LostFocus`
am alten und `GotFocus` am neuen Element auslösen, in dieser Reihenfolge.
#### Scenario: Tab überspringt
- **WHEN** das mittlere von drei Elementen `TabStop = 0` trägt und Tab gedrückt wird
- **THEN** erhält das dritte Element den Fokus
#### Scenario: Access-Key
- **WHEN** eine Schaltfläche `Caption = "&OK"` trägt und Alt+O gedrückt wird
- **THEN** wird ihr `Click`-Ereignis ausgelöst
#### Scenario: Reihenfolge der Fokusereignisse
- **WHEN** der Fokus von `Text1` auf `Text2` wechselt
- **THEN** läuft erst `Text1_LostFocus`, danach `Text2_GotFocus`
### Requirement: Maussteuerung mit Trefferprüfung
Ein Mausereignis SHALL dem obersten Steuerelement an seiner Position
zugestellt werden; liegt dort keines, dem Formular. Klick, Doppelklick
sowie `MouseDown`, `MouseMove` und `MouseUp` SHALL mit Taste,
Umschaltzustand und Position in Zellen zugestellt werden. Bei
`DragMode = 1` SHALL das Ziehen automatisch beginnen; `DRAG action%`
SHALL es manuell beginnen, ablegen oder abbrechen, mit `DragOver` und
`DragDrop` am Ziel.
#### Scenario: Treffer nach Z-Reihenfolge
- **WHEN** zwei Steuerelemente überlappen und in den gemeinsamen Bereich geklickt wird
- **THEN** erhält das obere das Ereignis
#### Scenario: Klick ohne Steuerelement
- **WHEN** auf eine freie Stelle des Formulars geklickt wird
- **THEN** erhält das Formular das Ereignis
#### Scenario: Ziehen und Ablegen
- **WHEN** ein Element mit `DragMode = 1` auf ein anderes gezogen und dort losgelassen wird
- **THEN** läuft am Ziel `DragOver` mit dem Zustand Over und danach `DragDrop` mit der Quelle als Argument
### Requirement: Steuerelemente mit Listeninhalt
ListBox und ComboBox SHALL `ADDITEM` und `REMOVEITEM` unterstützen und
`List`, `ListCount`, `ListIndex` und `Text` konsistent führen; bei
`Sorted = -1` SHALL die Einfügereihenfolge der Sortierung folgen.
`ListIndex = -1` SHALL „keine Auswahl" bedeuten. Die ComboBox SHALL die
drei Stilarten (Dropdown, Simple, Dropdown List) darstellen.
#### Scenario: Element hinzufügen
- **WHEN** `List1.ADDITEM "b"` und `List1.ADDITEM "a"` bei `Sorted = -1` ausgeführt werden
- **THEN** liefert `List1.List(0)` den Wert `a` und `List1.ListCount` den Wert 2
#### Scenario: Keine Auswahl
- **WHEN** eine ListBox ohne Auswahl gelesen wird
- **THEN** liefert `ListIndex` den Wert 1
### Requirement: Timer-Steuerelement
Ein Timer SHALL bei `Enabled = -1` und `Interval > 0` sein
`Timer`-Ereignis im eingestellten Abstand auslösen, gestützt auf die
Zeitquelle der Ereignissteuerung. `Interval = 0` SHALL ihn abschalten.
Sind mehrere Timer gleichzeitig fällig, SHALL die Reihenfolge festgelegt
und dokumentiert sein.
#### Scenario: Timer feuert im Abstand
- **WHEN** ein Timer mit `Interval = 100` läuft und die Zeit um 250 ms vorrückt
- **THEN** ist sein Ereignis zweimal gelaufen
#### Scenario: Interval 0 schaltet ab
- **WHEN** `Timer1.Interval = 0` gesetzt wird
- **THEN** läuft kein weiteres Ereignis
### Requirement: Menüsystem
Ein Formular SHALL eine Menüleiste mit bis zu sechs Ebenen tragen.
Menüeinträge SHALL Access-Keys (`&`), Shortcuts, `Checked`, `Enabled`,
`Visible` und Separatoren (`-`) unterstützen; ein Separator MUST NOT
`Checked`, deaktiviert oder mit Shortcut versehen sein, ein Menütitel
MUST NOT einen Shortcut tragen. Solange ein Menü geöffnet ist, MUST die
Zustellung von Zeitereignissen und klassischen Traps ruhen und danach
fortgesetzt werden.
#### Scenario: Menüauswahl löst Click aus
- **WHEN** ein Menüeintrag über seinen Access-Key gewählt wird
- **THEN** läuft seine `Click`-Prozedur
#### Scenario: Traps ruhen im geöffneten Menü
- **WHEN** ein Menü geöffnet ist und ein Zeit-Trap fällig wird
- **THEN** läuft sein Handler erst, nachdem das Menü geschlossen wurde
### Requirement: Vordefinierte Dialoge
`MSGBOX text$ [, typ% [, titel$]]` SHALL als Anweisung und als Funktion
verfügbar sein; die Funktion SHALL die gedrückte Schaltfläche als
INTEGER liefern (1 OK, 2 Cancel/Esc, 3 Abort, 4 Retry, 5 Ignore, 6 Yes,
7 No). `typ%` SHALL die Schaltflächengruppe (05) und die
Vorgabeschaltfläche (0/256/512) tragen. `INPUTBOX$(text$ [, titel$
[, vorgabe$ [, x%, y%]]])` SHALL eine Zeichenkette liefern und bei
Abbruch den leeren String. Beide Dialoge SHALL modal sein; `INPUTBOX$`
SHALL 46×16 Zeichen messen und ohne Positionsangabe zentriert
erscheinen.
#### Scenario: MSGBOX als Funktion
- **WHEN** `a% = MSGBOX("Weiter?", 4, "Frage")` ausgeführt und `Yes` gewählt wird
- **THEN** liefert der Aufruf 6
#### Scenario: INPUTBOX$ abgebrochen
- **WHEN** ein `INPUTBOX$`-Dialog mit Esc geschlossen wird
- **THEN** liefert er den leeren String
#### Scenario: Dialog ist modal
- **WHEN** ein Dialog offen ist
- **THEN** wird die Anweisung nach dem Aufruf erst nach dem Schließen ausgeführt

View File

@@ -0,0 +1,29 @@
## ADDED Requirements
### Requirement: Korpusabdeckung der Formularprogramme
Der Testkorpus SHALL Formularprogramme mit byte-genauer
Bildschirm-Sollausgabe führen. Ihre Ereignisfolge (Tasten, Maus, Zeit)
SHALL im Programmkopf deklariert und vom Harness eingespeist werden,
sodass ein Lauf ohne Terminal und ohne Wartezeit auskommt und zweimal
dasselbe Ergebnis liefert. Abgedeckt SHALL sein: Fokus- und
Tabreihenfolge, Access-Key, Klick über die Maus, Menüauswahl, ein
Listen-Steuerelement, ein Timer und ein modaler Dialog.
#### Scenario: Formularprogramm im Korpus
- **WHEN** ein Formular-Korpusprogramm mit deklarierter Ereignisfolge ausgeführt wird
- **THEN** entspricht der Bildschirminhalt byte-genau der Sollausgabe
#### Scenario: Wiederholbarkeit
- **WHEN** dasselbe Programm zweimal ausgeführt wird
- **THEN** ist die Ausgabe beide Male identisch
### Requirement: Kompatibilitätsnachweis an Fremdprogrammen
Die Formularprogramme aus dem öffentlichen Bestand des Vorbilds SHALL
sich ohne Non-Features übersetzen lassen und bedienbar sein. Ein
Programm, das an einem Non-Feature scheitert, MUST das Element
namentlich nennen; ein Scheitern aus anderem Grund MUST als Befund
festgehalten werden.
#### Scenario: Fremdprogramm übersetzt
- **WHEN** ein Formularprogramm des öffentlichen Bestands übersetzt wird
- **THEN** entstehen keine Diagnosen außer namentlich genannten Non-Features

View File

@@ -0,0 +1,49 @@
## 1. Festlegungen vorab
- [ ] 1.1 Optik je Klasse und Zustand (normal, fokussiert, deaktiviert) als Zeichenbild in `docs/forms-referenz.md` festhalten, aus den Original-Screenshots abgeleitet (D3); verifiziert durch je ein Zeichenbild pro Klasse und Zustand
- [ ] 1.2 Z-Reihenfolge und Timer-Reihenfolge festlegen und als unsere Festlegung kennzeichnen (D3); verifiziert durch die beiden Abschnitte in der Forms-Referenz
## 2. Darstellung und Eingabekette
- [ ] 2.1 Zeichnen je Klasse aus dem Eigenschaftszustand in den Zellenpuffer (D1); verifiziert durch Snapshot-Tests je Klasse, darunter die drei Höhenformen des CommandButton
- [ ] 2.2 Eingabekette für Tastatur und Maus (D2); verifiziert durch Unit-Tests, die je Station den Vorrang prüfen
- [ ] 2.3 Trefferprüfung über die Z-Reihenfolge; verifiziert durch einen Test mit überlappenden Steuerelementen und einem Klick ins Formular
## 3. Fokus und Tastatur
- [ ] 3.1 Tabreihenfolge über `TabIndex`/`TabStop` vorwärts und rückwärts, deaktivierte Elemente überspringen; verifiziert durch Unit-Tests je Fall
- [ ] 3.2 Access-Keys aus `&`, `Default` für Enter, `Cancel` für Esc; verifiziert durch Unit-Tests je Auslöser
- [ ] 3.3 `SETFOCUS`, `GotFocus`/`LostFocus` in der festgelegten Reihenfolge; verifiziert durch einen Test, der die Reihenfolge der beiden Ereignisse prüft
## 4. Steuerelementklassen
- [ ] 4.1 CommandButton, Label, Frame, CheckBox, OptionButton (inkl. Gruppierung im Container); verifiziert durch Snapshot- und Verhaltenstests je Klasse
- [ ] 4.2 TextBox mit `Text`, `SelStart`/`SelLength`/`SelText`, `MultiLine`, `ScrollBars`, Ereignis `Change`; verifiziert durch Tests für Eingabe, Auswahl und Umbruch
- [ ] 4.3 ListBox und ComboBox mit `ADDITEM`/`REMOVEITEM`, `List`/`ListCount`/`ListIndex`, `Sorted`, den drei ComboBox-Stilarten; verifiziert durch Tests für Einfügen, Sortierung und „keine Auswahl"
- [ ] 4.4 HScrollBar/VScrollBar mit `Min`/`Max`/`Value`/`SmallChange`/`LargeChange`/`Attached` und Ereignis `Change`; verifiziert durch Tests für Tastatur- und Mausbedienung
- [ ] 4.5 PictureBox als Textzeichenfläche (`PRINT`, `CLS`, `CurrentX`/`CurrentY`, `TEXTWIDTH`/`TEXTHEIGHT`) und als Container; verifiziert durch Snapshot-Tests
- [ ] 4.6 Timer auf der Zeitquelle der Ereignisschleife, Reihenfolge nach 1.2; verifiziert durch Tests mit virtueller Zeit für Abstand, `Interval = 0` und zwei gleichzeitig fällige Timer
- [ ] 4.7 DirListBox, DriveListBox, FileListBox plattformneutral (D6) mit `Path`/`Drive`/`FileName`/`Pattern` und ihren Ereignissen; verifiziert durch Tests auf einem angelegten Verzeichnisbaum
- [ ] 4.8 Ziehen und Ablegen: `DragMode`, `DRAG action%`, `DragOver` mit Zustand, `DragDrop` mit Quelle; verifiziert durch Tests für automatisches und manuelles Ziehen sowie Abbruch
## 5. Menüs und Dialoge
- [ ] 5.1 Menüleiste mit bis zu sechs Ebenen, Access-Keys, Shortcuts, `Checked`/`Enabled`/`Visible`/`Separator`, Menü-Arrays; verifiziert durch Snapshot- und Verhaltenstests, darunter die Regelverstöße (Separator mit Shortcut)
- [ ] 5.2 Ereigniszustellung ruht im geöffneten Menü über den vorhandenen `STOP`-Zustand (D5); verifiziert durch einen Test mit fälligem Zeit-Trap bei offenem Menü
- [ ] 5.3 `MSGBOX` als Anweisung und Funktion mit Schaltflächengruppen, Vorgabeschaltfläche und Rückgabewerten; verifiziert durch Tests je Gruppe und Rückgabewert
- [ ] 5.4 `INPUTBOX$` mit fester Größe 46×16, Positionierung in Zeichen, leerem String bei Abbruch; verifiziert durch Snapshot-Test und Abbruchtest
- [ ] 5.5 Frontend-Signaturen für `MSGBOX` (Anweisung und Funktion) und `INPUTBOX$`, `Unsupported`-Absenkung entfernen; verifiziert durch `cargo test -p tb-frontend`
## 6. Korpus und Kompatibilität
- [ ] 6.1 Ereignisfolge-Direktive im Programmkopf und ihre Einspeisung durch den Harness; verifiziert durch einen Harness-Test mit deklarierten Tasten-, Maus- und Zeitereignissen
- [ ] 6.2 Formular-Korpusprogramme für Fokus/Tab, Access-Key, Mausklick, Menüauswahl, Liste, Timer und modalen Dialog; verifiziert durch `cargo test -p tb-cli` gegen die Sollausgaben
- [ ] 6.3 Meilenstein: die Formularprogramme aus `github.com/cout/vbdos` übersetzen und bedienen, jeden Befund festhalten; verifiziert durch den Lauf über den Bestand mit Befundliste
- [ ] 6.4 Meilenstein: die Beispiel-Formularprogramme des Korpus laufen; verifiziert durch den grünen Korpuslauf
## 7. Inventar, Dokumentation, Abschluss
- [ ] 7.1 `docs/inventar.md`: Einträge dieses Changes auf `implementiert`; verifiziert durch `inventar_stimmt_mit_code_ueberein` mit Abdeckung 0 offen für Phase 4
- [ ] 7.2 Abweichungen (Dateisystem-Steuerelemente, festgelegte Optik, Z- und Timer-Reihenfolge) in `docs/sprachreferenz.md` eintragen; verifiziert durch den Abschnitt „Abweichungen"
- [ ] 7.3 PLAN.md: die verbleibenden Phase-4-Punkte abhaken und die Befunde der Phase festhalten; verifiziert durch die abgeschlossene Phase-4-Liste
- [ ] 7.4 `cargo test` grün und `openspec validate phase-4-steuerelemente --strict` ohne Befund; verifiziert durch beide Kommandos

View File

@@ -0,0 +1,72 @@
# forms-dateiformat Specification
## Purpose
Das Formulardateiformat legt fest, wie ein Formular samt seiner
Steuerelemente und seines Codes als Textdatei abgelegt, wieder gelesen
und aus binären Dateien des Vorbilds übernommen wird — die Grundlage
dafür, dass Formulare überhaupt gespeichert und ausgetauscht werden
können.
## Requirements
### Requirement: Aufbau des Textformats
Eine Formulardatei SHALL aus einer `VERSION`-Zeile, einem
Beschreibungsteil und einem Codeteil bestehen. Der Beschreibungsteil
SHALL aus verschachtelten Blöcken `Begin <Klasse> <Name>``End` mit
Zeilen `Eigenschaft = Wert` bestehen; Zeichenketten stehen in
Anführungszeichen. Der Codeteil SHALL gewöhnlicher Quelltext des
Formularmoduls sein. Die Versionen `1.00` und `2.00` SHALL angenommen
werden; eine andere Version MUST mit Nennung der vorgefundenen Version
abgewiesen werden.
#### Scenario: Formular mit einem Steuerelement
- **WHEN** eine Datei ein `Form`-Blockelement mit einem eingebetteten `CommandButton`-Block und anschließendem `SUB`-Code enthält
- **THEN** entsteht daraus eine Formularbeschreibung mit einem Steuerelement und dem zugehörigen Quelltext
#### Scenario: Unbekannte Version
- **WHEN** die Datei mit `VERSION 3.00` beginnt
- **THEN** wird sie abgewiesen und die Meldung nennt `3.00`
### Requirement: Schreiben ist die Umkehrung des Lesens
Das Schreiben einer gelesenen Formularbeschreibung SHALL dieselbe Datei
ergeben. Geschrieben SHALL nur werden, was vom Vorgabewert abweicht;
Reihenfolge und Einrückung SHALL festgelegt und dokumentiert sein, damit
zwei Läufe dieselbe Datei erzeugen.
#### Scenario: Rundlauf
- **WHEN** eine Formulardatei gelesen und unverändert wieder geschrieben wird
- **THEN** ist die geschriebene Datei byte-gleich zur gelesenen
#### Scenario: Vorgabewerte werden nicht geschrieben
- **WHEN** ein Steuerelement nur Vorgabewerte trägt
- **THEN** enthält sein Block außer `Begin`/`End` keine Eigenschaftszeile
### Requirement: Fehlerhafte Dateien werden benannt
Eine unbekannte Klasse, eine für die Klasse unbekannte Eigenschaft, ein
Wert außerhalb des Wertebereichs und ein unausgeglichener Block MUST je
mit Dateiname, Zeilennummer und dem betroffenen Namen gemeldet werden.
Eine solche Datei MUST NOT teilweise übernommen werden.
#### Scenario: Unbekannte Eigenschaft
- **WHEN** ein `CommandButton`-Block die Zeile `Farbe = 3` enthält
- **THEN** nennt die Meldung Datei, Zeile, `CommandButton` und `Farbe`
#### Scenario: Unausgeglichener Block
- **WHEN** einer Datei ein `End` fehlt
- **THEN** nennt die Meldung die Zeile des offenen `Begin`-Blocks
### Requirement: Konvertierung binärer Formulardateien
Ein Unterbefehl SHALL eine binäre Formulardatei des Vorbilds (Kennung
`FC 08 01 00`) in das Textformat übersetzen. Eine nicht erkannte oder
beschädigte Datei MUST mit Nennung der Fundstelle abgewiesen werden;
eine Teilausgabe MUST NOT entstehen. Der erschlossene Aufbau des
Binärformats SHALL dokumentiert sein.
#### Scenario: Bekannte Beispieldatei
- **WHEN** eine binäre Beispieldatei konvertiert wird
- **THEN** entsteht eine Textdatei, deren Lesen dieselbe Formularbeschreibung ergibt wie die dokumentierte Erwartung
#### Scenario: Fremde Datei
- **WHEN** eine Datei ohne die Kennung übergeben wird
- **THEN** bricht der Befehl mit einer Meldung ab und schreibt keine Ausgabedatei