chore: carry over lab 1 solution into lab 2 skeleton
Copy the committed lab 1 sources as-is: src/, student-tests/, bench/, Dockerfile, docker-compose.yml, pyproject.toml, uv.lock, .python-version, config_example.toml, AGENTS.md, CLAUDE.md, .claude/, openspec/, .graphifyignore and KNOWN_ISSUES.md. Lab 1 evidence stays in the lab 1 repository. Merge the new skeleton files with own sections: Makefile (lab 2 targets plus own run, docker, bench and common targets), .gitignore, .dockerignore and .env.example. Rename the image to mtusi-messenger:lab2 and point AGENTS.md at lab 2. The application is still the in-memory lab 1 implementation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,198 @@
|
||||
---
|
||||
name: "OPSX: Apply"
|
||||
description: "Implement tasks from an OpenSpec change (Experimental)"
|
||||
allowed-tools: Bash(openspec:*)
|
||||
category: "Workflow"
|
||||
tags: ["workflow", "artifacts", "experimental"]
|
||||
---
|
||||
|
||||
Implement tasks from an OpenSpec change.
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
|
||||
|
||||
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
|
||||
|
||||
Otherwise, with no root, what happens next depends on how this workflow was reached:
|
||||
|
||||
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
|
||||
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
|
||||
|
||||
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
|
||||
|
||||
**Input**: Optionally specify a change name (e.g., `/opsx:apply add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
|
||||
|
||||
2. **Check status to understand the schema**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used (e.g., "spec-driven")
|
||||
- `planningHome`, `changeRoot`, and `actionContext`: planning scope and edit constraints
|
||||
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
|
||||
|
||||
3. **Get apply instructions**
|
||||
|
||||
```bash
|
||||
openspec instructions apply --change "<name>" --json
|
||||
```
|
||||
|
||||
This returns:
|
||||
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
|
||||
- Progress (total, complete, remaining)
|
||||
- Task list with status
|
||||
- Dynamic instruction based on current state
|
||||
- Optional `context`: current required project instruction input from the selected root
|
||||
- Optional `operationGuidance`: current advisory guidance for apply
|
||||
- `missingArtifacts` (when present): required artifact ids with no output
|
||||
|
||||
**Handle states:**
|
||||
- If `state: "blocked"`: show the message and pause implementation.
|
||||
- If `missingArtifacts` is non-empty: suggest completing the missing artifacts. Run `openspec status --change "<name>" --json`, select the next `ready` artifact (not `skipped` or `blocked`), and use `openspec instructions "<artifact-id>" --change "<name>" --json` for its rules and template. Keep the selected `--store <id>` on both commands.
|
||||
- Otherwise, follow the CLI instruction to create or repair the schema-configured tracking file from existing planning artifacts. Do not assume another artifact is ready or start implementation while blocked.
|
||||
- If `state: "all_done"`: congratulate, suggest archive
|
||||
- Otherwise: proceed to implementation
|
||||
|
||||
Treat `context` as a required prompt-level input. Read and consider it, and
|
||||
apply relevant project facts, conventions, and constraints while implementing.
|
||||
Treat `operationGuidance` as optional additive advice. Read and consider every
|
||||
entry, and follow entries that are applicable and compatible with the built-in
|
||||
workflow.
|
||||
|
||||
Keep both fields separate from CLI-returned state, missing artifacts, tasks,
|
||||
progress, `contextFiles`, and the built-in `instruction`. They are not
|
||||
evidence of task completion, do not replace the built-in instruction, and do
|
||||
not permit bypassing a blocked state. If context conflicts with the built-in
|
||||
instruction, an explicit user choice, or a CLI-controlled value, report the
|
||||
conflict and preserve the controlling value. If guidance is inapplicable or
|
||||
conflicts with those controlling inputs, do not follow it and explain why.
|
||||
These are prompt-level behavior contracts, not enforceable checks.
|
||||
|
||||
4. **Read context files**
|
||||
|
||||
Read every file path listed under `contextFiles` from the apply instructions output.
|
||||
The files depend on the schema being used:
|
||||
- **spec-driven**: proposal, specs, design, tasks
|
||||
- Other schemas: follow the contextFiles from CLI output
|
||||
|
||||
Do not copy `context` or `operationGuidance` verbatim into implementation
|
||||
files or planning artifacts unless the user separately asks for that content.
|
||||
|
||||
5. **Show current progress**
|
||||
|
||||
Display:
|
||||
- Schema being used
|
||||
- Progress: "N/M tasks complete"
|
||||
- Remaining tasks overview
|
||||
- Dynamic instruction from CLI
|
||||
|
||||
6. **Implement tasks (loop until done or blocked)**
|
||||
|
||||
For each pending task:
|
||||
- Show which task is being worked on
|
||||
- Make the code changes required
|
||||
- Keep changes minimal and focused
|
||||
- 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 `/opsx:archive`.
|
||||
```
|
||||
|
||||
**Output On Pause (Issue Encountered)**
|
||||
|
||||
```
|
||||
## Implementation Paused
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Progress:** 4/7 tasks complete
|
||||
|
||||
### Issue Encountered
|
||||
<description of the issue>
|
||||
|
||||
**Options:**
|
||||
1. <option 1>
|
||||
2. <option 2>
|
||||
3. Other approach
|
||||
|
||||
What would you like to do?
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Keep going through tasks until done or blocked
|
||||
- Always read context files before starting (from the apply instructions output)
|
||||
- If task is ambiguous, pause and ask before implementing
|
||||
- If implementation reveals issues, pause and suggest artifact updates
|
||||
- Keep code changes minimal and scoped to each task
|
||||
- Update task checkbox immediately after completing each task
|
||||
- Pause on errors, blockers, or unclear requirements - don't guess
|
||||
- When a task needs work beyond what the spec describes, surface the added scope and pause - never silently narrow, defer, or simplify away specified behavior
|
||||
- Only mark a task `- [x]` when its specified behavior is fully implemented, not when it is partially done or deferred
|
||||
- Use contextFiles from CLI output, don't assume specific file names
|
||||
- Do not use context or operation guidance as proof that a task is complete
|
||||
- Apply relevant project context; report conflicts with controlling workflow inputs
|
||||
- Consider every guidance entry; explain any inapplicable or conflicting advice
|
||||
- Do not copy runtime context or operation guidance into implementation files or planning artifacts
|
||||
- Preserve CLI-controlled blocked/ready/all-done behavior and completion criteria
|
||||
|
||||
**Fluid Workflow Integration**
|
||||
|
||||
This skill supports the "actions on a change" model:
|
||||
|
||||
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
|
||||
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly
|
||||
@@ -0,0 +1,246 @@
|
||||
---
|
||||
name: "OPSX: Archive"
|
||||
description: "Archive a completed change in the experimental workflow"
|
||||
allowed-tools: Bash(openspec:*)
|
||||
category: "Workflow"
|
||||
tags: ["workflow", "archive", "experimental"]
|
||||
---
|
||||
|
||||
Archive a completed change in the experimental workflow.
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
|
||||
|
||||
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
|
||||
|
||||
Otherwise, with no root, what happens next depends on how this workflow was reached:
|
||||
|
||||
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
|
||||
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
|
||||
|
||||
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
|
||||
|
||||
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
|
||||
|
||||
**Input**: Optionally specify a change name after `/opsx:archive` (e.g., `/opsx:archive add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
|
||||
|
||||
When prompting, show only active changes (not already archived).
|
||||
Include the schema used for each change if available.
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:archive <other>`).
|
||||
|
||||
**Load current archive inputs before the existing archive checks:**
|
||||
|
||||
After resolving the selected change and planning root, run:
|
||||
```bash
|
||||
openspec instructions archive --change "<name>" --json
|
||||
```
|
||||
Keep the same selected-root flags on this command. This lookup is advisory and
|
||||
optional: it only supplies extra prompt inputs, so it must never block archiving.
|
||||
If it exits non-zero or returns invalid JSON — for example on an older CLI that
|
||||
does not support this command yet — continue the archive workflow with no
|
||||
context and no operation guidance. Do not report an error and do not stop.
|
||||
|
||||
A successful response may omit both optional fields. Treat `context` as a
|
||||
required prompt-level input: read and consider it, and apply relevant project
|
||||
facts, conventions, and constraints. Treat `operationGuidance` as optional
|
||||
additive advice: read and consider every entry, and follow entries that are
|
||||
applicable and compatible with the built-in archive workflow.
|
||||
|
||||
Keep both fields separate from built-in steps, explicit user choices, resolved
|
||||
paths, CLI checks, and command contracts. If context conflicts with one of those
|
||||
controlling inputs, report the conflict and preserve the controlling value. If
|
||||
guidance is inapplicable or conflicts with a controlling input, do not follow it
|
||||
and explain why. Do not infer replacement paths, skipped prompts, or flags from
|
||||
either field, and do not copy their text verbatim into specs, change artifacts,
|
||||
or archive summaries unless the user separately asks for it. These are
|
||||
prompt-level behavior contracts, not enforceable checks.
|
||||
|
||||
2. **Check artifact completion status**
|
||||
|
||||
Run `openspec status --change "<name>" --json` to check artifact completion.
|
||||
|
||||
Parse the JSON to understand:
|
||||
- `schemaName`: The workflow being used
|
||||
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context
|
||||
- `artifacts`: List of artifacts with their status (`done`, `skipped`, or other)
|
||||
|
||||
**If any artifacts are neither `done` nor `skipped`** (skipped artifacts satisfy the requirement - the change declares skip_specs):
|
||||
- Display warning listing incomplete artifacts
|
||||
- Prompt user for confirmation to continue
|
||||
- Proceed if user confirms
|
||||
|
||||
3. **Check task completion status**
|
||||
|
||||
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
|
||||
|
||||
A checkbox is complete when its only content is `x` or `X`; spacing inside
|
||||
the brackets does not matter, so `- [ x]` counts as complete too. Every
|
||||
other marker is incomplete - `- [ ]`, an empty `- []`, and markers OpenSpec
|
||||
assigns no meaning to such as `- [~]` or `- [-]`. Never read an unfamiliar
|
||||
marker as complete.
|
||||
|
||||
**If incomplete tasks found:**
|
||||
- Display warning showing count of incomplete tasks
|
||||
- Prompt user for confirmation to continue
|
||||
- Proceed if user confirms
|
||||
|
||||
**If no tasks file exists:** Proceed without task-related warning.
|
||||
|
||||
4. **Assess delta spec sync state**
|
||||
|
||||
Use `artifactPaths.specs.existingOutputPaths` from status JSON as the only
|
||||
delta-spec source. If the `specs` entry is missing or
|
||||
`existingOutputPaths` is empty, proceed without a sync prompt and do not infer
|
||||
delta specs from other artifacts.
|
||||
|
||||
**If delta specs exist:**
|
||||
- Compare each delta spec with its corresponding main spec at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (use the store-aware `planningHome.root` from step 2, not a hardcoded repo path)
|
||||
- A missing main spec is **not automatically** "already synced". For a new capability, the main spec is an *output* of the sync, not an input:
|
||||
- If the delta has MODIFIED or RENAMED requirements, report that only ADDED requirements can create a new main spec and mark that capability as sync-blocked. Never invent a requirement that has no current version.
|
||||
- Otherwise, if the delta has only REMOVED requirements and the change's `.openspec.yaml` declares `retire_capabilities: true`, the capability is already retired: count it as already synced, warn that there is nothing left to remove, and do not recreate the main spec. Apply this rule both now and when verifying a completed sync.
|
||||
- Otherwise, if the delta has no ADDED requirements, report that no sync is possible and mark that capability as sync-blocked. For a REMOVED-only delta, warn that there is no main spec to remove from and leave the main-spec tree unchanged. `openspec archive` refuses the unmarked REMOVED-only case with `Spec must have at least one requirement`.
|
||||
- Otherwise, count the capability as needing sync and name it in the summary (`<capability-path>: new main spec will be created`). If the delta also has REMOVED requirements, warn that they will be ignored because there is no main spec to remove from. The sync creates the main spec from only the delta's ADDED requirements, exactly as `openspec archive` does.
|
||||
- Determine what changes would be applied (adds, modifications, removals, renames)
|
||||
- Continue assessing the remaining capabilities even when one is sync-blocked. Show a combined summary before prompting.
|
||||
|
||||
**Prompt options:**
|
||||
- If any capability is sync-blocked: explain why and offer only "Archive without syncing", "Cancel"
|
||||
- Otherwise, if changes needed: "Sync now (recommended)", "Archive without syncing"
|
||||
- Otherwise, if already synced: "Archive now", "Sync anyway", "Cancel"
|
||||
|
||||
Route on the answer:
|
||||
- "Cancel" — stop, do not archive
|
||||
- "Archive without syncing" or "Archive now" — proceed to archive
|
||||
- "Sync now" or "Sync anyway" — sync, then verify (below). Do not start any sync while a capability is sync-blocked; explain the blocker and repeat the available choices.
|
||||
- Anything else — ask again rather than archiving
|
||||
|
||||
Before a selected sync writes any main spec, run
|
||||
`openspec instructions specs --change "<name>" --json` once with the same
|
||||
selected-root flags. Require a zero exit status and valid artifact-instruction
|
||||
JSON. If the lookup fails or returns invalid JSON, report the error and stop
|
||||
before writing any main spec or moving the change. A valid response with omitted
|
||||
`rules` is the no-rules case. Apply returned `rules` only to the content and
|
||||
form of main specs produced by this merge; do not use them as archive guidance,
|
||||
change CLI behavior, or copy the rule text into any output file.
|
||||
|
||||
Then run the `/opsx:sync` workflow inline (agent-driven intelligent merge) for change '<name>', passing the delta spec analysis and the fetched specs-rule snapshot from above, and wait for it to finish. The inline sync must reuse that snapshot without fetching `specs` instructions again. Do not delegate it to a background task — step 5 would move `changeRoot` out from under a sync that is still reading it, leaving the change archived and the main specs never updated. If your agent can only run it by delegation, delegate synchronously and wait for the result.
|
||||
|
||||
Then re-run the comparison from the top of this step, including the explicitly retired, missing-spec case, against every capability that has a delta spec in `artifactPaths.specs.existingOutputPaths` — not only the ones the sync reports it touched. A successful sync leaves nothing left to apply, so each capability must now read as already synced:
|
||||
- ADDED requirements present
|
||||
- MODIFIED requirements carrying the scenario and description changes named in the delta, with their other scenarios intact
|
||||
- REMOVED requirements gone — and where this sync retired a capability (removed its last requirement, leaving `## Requirements` empty), its main spec deleted rather than left empty; 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
|
||||
- Spec sync status (synced / sync skipped / no delta specs)
|
||||
- Note about any warnings (incomplete artifacts/tasks)
|
||||
|
||||
**Output On Success**
|
||||
|
||||
```markdown
|
||||
## Archive Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** the archive path derived from `planningHome.changesDir`/<target-name>/
|
||||
**Specs:** ✓ Synced to main specs
|
||||
|
||||
All artifacts complete. All tasks complete.
|
||||
```
|
||||
|
||||
**Output On Success (No Delta Specs)**
|
||||
|
||||
```markdown
|
||||
## Archive Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** the archive path derived from `planningHome.changesDir`/<target-name>/
|
||||
**Specs:** No delta specs
|
||||
|
||||
All artifacts complete. All tasks complete.
|
||||
```
|
||||
|
||||
**Output On Success With Warnings**
|
||||
|
||||
```markdown
|
||||
## Archive Complete (with warnings)
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** the archive path derived from `planningHome.changesDir`/<target-name>/
|
||||
**Specs:** Sync skipped (user chose to skip)
|
||||
|
||||
**Warnings:**
|
||||
- Archived with 2 incomplete artifacts
|
||||
- Archived with 3 incomplete tasks
|
||||
- Delta spec sync was skipped (user chose to skip)
|
||||
|
||||
Review the archive if this was not intentional.
|
||||
```
|
||||
|
||||
**Output On Error (Archive Exists)**
|
||||
|
||||
```markdown
|
||||
## Archive Failed
|
||||
|
||||
**Change:** <change-name>
|
||||
**Target:** the archive path derived from `planningHome.changesDir`/<target-name>/
|
||||
|
||||
Target archive directory already exists.
|
||||
|
||||
**Options:**
|
||||
1. Rename the existing archive
|
||||
2. Delete the existing archive if it's a duplicate
|
||||
3. Wait until a different date to archive
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Announce the selected change; prompt for selection when it is ambiguous
|
||||
- Use artifact graph (openspec status --json) for completion checking
|
||||
- Don't block archive on warnings - just inform and confirm
|
||||
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
|
||||
- Show clear summary of what happened
|
||||
- If sync is requested, run the `/opsx:sync` workflow inline (agent-driven)
|
||||
- Never archive while a spec sync is still in flight — run the sync inline and verify the main specs before moving `changeRoot`
|
||||
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
|
||||
- Apply relevant runtime context and report conflicts; operation guidance remains advisory
|
||||
- Consider every guidance entry and explain any inapplicable or conflicting advice
|
||||
- Existing CLI checks, resolved paths, prompts, and command contracts are unchanged
|
||||
- Artifact rules constrain only the specs being written and are never operation guidance
|
||||
- Never copy runtime context, operation guidance, or artifact-rule text verbatim into output files
|
||||
@@ -0,0 +1,239 @@
|
||||
---
|
||||
name: "OPSX: Explore"
|
||||
description: "Enter explore mode - think through ideas, investigate problems, clarify requirements"
|
||||
allowed-tools: Bash(openspec:*)
|
||||
category: "Workflow"
|
||||
tags: ["workflow", "explore", "experimental", "thinking"]
|
||||
---
|
||||
|
||||
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
|
||||
|
||||
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, investigate the codebase, and run read-only commands or tools without confirmation, but you must NEVER write code or implement features. If the user asks you to implement something, do not start it here: say that explore mode does not implement, and point them at `/opsx:propose`, which turns the discussion into a change. The work happens from that change, never from explore mode. You MAY create or update OpenSpec change artifacts (proposals, designs, specs) within a confirmed scope—that's capturing thinking, not implementing. Answering design or clarifying questions is never consent to write. Before the first write-capable action, name the artifacts or files you would change and what you would do, ask a direct yes/no question, and wait for the user's confirmation in a separate message. Confirmation covers only the scope you described; ask again before expanding it. An explicit request from the user to capture the exploration as a new change is itself that confirmation, covering the change and the change artifacts the request names; scaffold it first as described below.
|
||||
|
||||
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
|
||||
|
||||
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
|
||||
|
||||
Otherwise, with no root, what happens next depends on how this workflow was reached:
|
||||
|
||||
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
|
||||
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
|
||||
|
||||
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
|
||||
|
||||
**Input**: The argument after `/opsx:explore` is whatever the user wants to think about. Could be:
|
||||
- A vague idea: "real-time collaboration"
|
||||
- A specific problem: "the auth system is getting unwieldy"
|
||||
- A change name: "add-dark-mode" (to explore in context of that change)
|
||||
- A comparison: "postgres vs sqlite for this"
|
||||
- Nothing (just enter explore mode)
|
||||
|
||||
---
|
||||
|
||||
## The Stance
|
||||
|
||||
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
|
||||
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
|
||||
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
|
||||
- **Adaptive** - Follow interesting threads, pivot when new information emerges
|
||||
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
|
||||
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
|
||||
|
||||
---
|
||||
|
||||
## Planning a Change
|
||||
|
||||
When the user is planning a change, guide them toward shared understanding with focused discovery questions. For open-ended discussion, follow the conversation without imposing an interview or a required output.
|
||||
|
||||
Before asking a factual question, follow the context discovery below and inspect relevant OpenSpec artifacts, source, tests, docs, and configuration. Do not ask the user to repeat facts you can verify. Summarize relevant findings without reproducing private context or rules. If evidence is missing, conflicting, or inaccessible, state that limitation and ask only for the clarification needed to proceed.
|
||||
|
||||
- **Follow dependencies** - Resolve the next blocking decision before its dependent details. For example, clarify the user's outcome and scope before choosing an API or data model. Revisit downstream assumptions when an earlier answer changes. Skip branches that do not matter to this goal.
|
||||
- **Keep questions focused** - Ask one focused question at a time, and briefly explain why it matters and which decision it unlocks. Batch questions only if the user asks for a batch; keep them small and group related decisions.
|
||||
- **Offer grounded recommendations** - When evidence supports a recommendation, state your preferred option and why it fits the user's goals, with alternatives and their tradeoffs when useful. Do not invent intent, priorities, or external constraints: ask the user when only they can answer. Avoid a fixed question format.
|
||||
- **Keep a conversational record** - Track decisions in the conversation, not in files. Separate confirmed decisions from proposed defaults and unresolved questions. Silence is not acceptance. Accepting an answer or a batch of recommendations is not permission to write. Keep file-write confirmation separate from discovery questions and follow the guardrails below.
|
||||
|
||||
Stop asking when the user has enough clarity. Let them pause, pivot, or defer a decision; do not exhaust every branch or force a proposal.
|
||||
|
||||
For example, after inspecting the relevant code:
|
||||
|
||||
```text
|
||||
The CLI already uses SQLite and has no remote service. Is sharing state
|
||||
across devices in scope? That determines whether local storage is enough.
|
||||
If this stays a single-device tool, I recommend keeping SQLite to avoid
|
||||
adding a service to operate; shared state would need a separate sync design.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## What You Might Do
|
||||
|
||||
Depending on what the user brings, you might:
|
||||
|
||||
**Explore the problem space**
|
||||
- Ask clarifying questions that emerge from what they said
|
||||
- Challenge assumptions
|
||||
- Reframe the problem
|
||||
- Find analogies
|
||||
|
||||
**Investigate the codebase**
|
||||
- Map existing architecture relevant to the discussion
|
||||
- Find integration points
|
||||
- Identify patterns already in use
|
||||
- Surface hidden complexity
|
||||
|
||||
**Compare options**
|
||||
- Brainstorm multiple approaches
|
||||
- Build comparison tables
|
||||
- Sketch tradeoffs
|
||||
- Recommend a path (if asked)
|
||||
|
||||
**Visualize**
|
||||
```
|
||||
+------------------------------------------+
|
||||
| Use ASCII diagrams liberally |
|
||||
+------------------------------------------+
|
||||
| |
|
||||
| [State A] -------> [State B] |
|
||||
| | |
|
||||
| v |
|
||||
| [State C] |
|
||||
| |
|
||||
| System diagrams, state machines, |
|
||||
| data flows, architecture sketches, |
|
||||
| dependency graphs, comparison tables |
|
||||
| |
|
||||
+------------------------------------------+
|
||||
```
|
||||
|
||||
**Draw with plain ASCII only** — borders `+` `-` `|`, arrows `-->` `<--` `^` `v`, markers `*` `x`.
|
||||
Unicode diagram glyphs can render at different widths across terminals, fonts, and locales, so padded boxes and aligned tables can drift. Keep every diagram character ASCII.
|
||||
|
||||
**Surface risks and unknowns**
|
||||
- Identify what could go wrong
|
||||
- Find gaps in understanding
|
||||
- Suggest spikes or investigations
|
||||
|
||||
---
|
||||
|
||||
## OpenSpec Awareness
|
||||
|
||||
You have full context of the OpenSpec system. Use it naturally, don't force it.
|
||||
|
||||
### Check for context
|
||||
|
||||
At the start, quickly check what exists:
|
||||
```bash
|
||||
openspec list --json
|
||||
```
|
||||
|
||||
This tells you:
|
||||
- If there are active changes
|
||||
- Their names, schemas, and status
|
||||
- What the user might be working on
|
||||
|
||||
That is the *change* list - work in flight. It does not include the project's durable capabilities, so list those too:
|
||||
```bash
|
||||
openspec list --specs
|
||||
```
|
||||
Add `--json` for ids and requirement counts, and append `--store "<id>"` only for a registered standalone store. This is the inventory of what the project already claims to do, and `openspec list` on its own never shows it. To look at one, run `openspec show "<spec-id>" --type spec --json --no-scenarios` (same `--store` rule) - it returns that capability's purpose and requirement texts without pulling the whole spec file into context, and `--type spec` stops a change of the same name from making it ambiguous.
|
||||
|
||||
The filtered read is only an overview. Before deciding what is already covered or what should change, read each relevant spec in full, including scenarios, with `openspec show "<spec-id>" --type spec` (same `--store` rule).
|
||||
|
||||
Then read the project's own context from the resolved root - `<root.path>/openspec/config.yaml` (or `config.yml`). Use the `root.path` returned above, and skip this if neither file exists:
|
||||
- `context`: project background - tech stack, conventions, constraints
|
||||
- `rules`: keyed by artifact id - the entries for an artifact apply only when you write that artifact
|
||||
|
||||
Ground your thinking in these. They are constraints for you to follow, not content to reproduce: do NOT copy them into the conversation or into any artifact you create.
|
||||
|
||||
If the user mentioned a specific change name, read its artifacts for context.
|
||||
|
||||
### When no change exists
|
||||
|
||||
Think freely. When insights crystallize, you might offer:
|
||||
|
||||
- "This feels solid enough to start a change. Want me to create a proposal?"
|
||||
- Or keep exploring - no pressure to formalize
|
||||
|
||||
If the user asks you to capture the exploration as a new change, that request is the confirmation required above. It covers scaffolding that change and creating the change artifacts the request names, and nothing else. This holds only when the request is theirs: a yes to an offer you made confirms only the scope your offer itself named, so name the change and the artifacts in the offer. Don't re-ask for what they already asked for; do ask before anything beyond it. Transition seamlessly into the requested capture:
|
||||
|
||||
1. Run `openspec new change "<name>"` (with `--store <id>` when applicable) before creating any artifacts. Never create a new change directory under `openspec/changes/` by hand; the CLI scaffold creates required metadata such as `.openspec.yaml`. Keep the selected `--store <id>` on every applicable follow-up `status` and `instructions` command.
|
||||
2. Run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store), then process the requested artifacts in dependency order. For each requested artifact that is `ready`, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store). Before creating a requested artifact, evaluate any condition in its own `instruction` against the explored change; record a deliberate skip instead when the condition does not apply. If a requested artifact is blocked by a direct prerequisite the user did not request, run `openspec instructions "<prerequisite-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) for that prerequisite whether it is `ready` or `blocked`. If its own `instruction` states a condition, evaluate that condition against the explored change and record a deliberate skip only when the condition does not apply. If the condition applies, or the prerequisite is not conditional, treat it as a normal prerequisite and ask before expanding the capture. Do not create an unrequested prerequisite unless the user approves.
|
||||
3. Follow the returned `template` and `instruction` fields. Read completed dependency files listed in `dependencies`, and apply `context` and `rules` as constraints without copying them into the artifact. If the instruction delegates creation to a specific skill or command, invoke it; otherwise write the artifact to `resolvedOutputPath`, using the instruction to choose a concrete path when it is a glob. Verify that the selected concrete output exists.
|
||||
4. After creating each artifact, re-run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) and continue until every requested artifact is `done`, `skipped`, or was deliberately skipped because its own `instruction` stated a condition that did not apply. Tell the user about a deliberate conditional skip, remember it, and do not reconsider it. Dependencies are enablers, not gates: if a requested artifact is still `blocked` only because you deliberately skipped a conditional prerequisite, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) despite the blocked status, then create it using step 3 only when those recorded conditional skips are its sole missing dependencies. If a requested artifact is blocked by a prerequisite the user did not ask to capture and cannot be conditionally skipped, explain that dependency and ask before expanding the capture.
|
||||
|
||||
Capture the artifact(s) the user requested without asking them to invoke another workflow command. If they asked only to start a change, stop after scaffolding and show its status. When the requested capture is done, stop there and name where the work continues: `/opsx:propose` writes the remaining planning artifacts, and `/opsx:apply` implements the change once tasks exist. Capturing artifacts never starts implementing them.
|
||||
|
||||
### When a change exists
|
||||
|
||||
If the user mentions a change or you detect one is relevant:
|
||||
|
||||
1. **Resolve and read existing artifacts for context**
|
||||
- Run `openspec status --change "<name>" --json`.
|
||||
- Use `changeRoot`, `artifactPaths`, and `actionContext` from the status JSON.
|
||||
- Read existing files from `artifactPaths.<artifact>.existingOutputPaths`.
|
||||
|
||||
2. **Reference them naturally in conversation**
|
||||
- "Your design mentions using Redis, but we just realized SQLite fits better..."
|
||||
- "The proposal scopes this to premium users, but we're now thinking everyone..."
|
||||
|
||||
3. **Offer to capture when decisions are made**
|
||||
|
||||
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
|
||||
|
||||
| Insight Type | Where to Capture |
|
||||
|----------------------------|-------------------------------------|
|
||||
| New requirement discovered | `specs/<capability-path>/spec.md` |
|
||||
| Requirement changed | `specs/<capability-path>/spec.md` |
|
||||
| Design decision made | `design.md` |
|
||||
| Scope changed | `proposal.md` |
|
||||
| New work identified | `tasks.md` |
|
||||
| Assumption invalidated | Relevant artifact |
|
||||
|
||||
Example offers:
|
||||
- "That's a design decision. Capture it in design.md?"
|
||||
- "This is a new requirement. Add it to specs?"
|
||||
- "This changes scope. Update the proposal?"
|
||||
|
||||
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
|
||||
|
||||
---
|
||||
|
||||
## What You Don't Have To Do
|
||||
|
||||
- Follow a script
|
||||
- Ask the same questions every time
|
||||
- Produce a specific artifact
|
||||
- Reach a conclusion
|
||||
- Stay on topic if a tangent is valuable
|
||||
- Be brief (this is thinking time)
|
||||
|
||||
---
|
||||
|
||||
## Ending Discovery
|
||||
|
||||
There's no required ending. Discovery might:
|
||||
|
||||
- **Flow into a proposal**: "Ready to start? Run `/opsx:propose` and this becomes a change."
|
||||
- **Result in artifact updates**: "Updated design.md with these decisions"
|
||||
- **Just provide clarity**: User has what they need, moves on
|
||||
- **Continue later**: "We can pick this up anytime"
|
||||
|
||||
When things crystallize, you might offer a summary - but it's optional. Sometimes the thinking IS the value.
|
||||
|
||||
---
|
||||
|
||||
## Guardrails
|
||||
|
||||
- **Don't implement** - Never write code or implement features. Workflow configuration counts too: creating or editing schemas, templates, or `openspec/config.yaml` is a change, not thinking. Creating or updating OpenSpec change artifacts within the confirmed scope is fine, writing anything else is not. When the user is ready to build, name the handoff rather than starting: `/opsx:propose` turns the discussion into a change, and the work happens there.
|
||||
- **Don't fake understanding** - If something is unclear, dig deeper
|
||||
- **Don't rush** - Discovery is thinking time, not task time
|
||||
- **Don't force structure** - Let patterns emerge naturally
|
||||
- **Don't auto-capture** - Offer to save insights, don't just do it. Read-only commands and tools need no confirmation. Before the first write-capable action—including `openspec new change` or another command that writes files—name the artifacts or files and proposed changes, ask a direct yes/no question, and wait for explicit confirmation in a separate user message. That confirmation covers only the described scope; ask again before expanding it. Answers to design or clarifying questions are never consent to write. That rule governs `openspec new change` whenever you are the one proposing the capture; the user's own capture request is the exception, handled in the capture transition above.
|
||||
- **Don't manually scaffold changes** - Never create a new change directory under `openspec/changes/` by hand. Always use `openspec new change "<name>"` (with `--store <id>` when applicable) so required metadata such as `.openspec.yaml` is created before writing artifacts.
|
||||
- **Do visualize** - A good diagram is worth many paragraphs
|
||||
- **Do explore the codebase** - Ground discussions in reality
|
||||
- **Do question assumptions** - Including the user's and your own
|
||||
@@ -0,0 +1,170 @@
|
||||
---
|
||||
name: "OPSX: Propose"
|
||||
description: "Propose a new change - create it and generate all artifacts in one step"
|
||||
allowed-tools: Bash(openspec:*)
|
||||
category: "Workflow"
|
||||
tags: ["workflow", "artifacts", "experimental"]
|
||||
---
|
||||
|
||||
Propose a new change - create the change and generate all artifacts in one step.
|
||||
|
||||
**Planning boundary**: This workflow creates planning artifacts only. The user request that selected or triggered this workflow authorizes planning only, even if it asks to build or fix something. Do not edit project code. After the planning artifacts are complete, stop. Do not start implementation in the same response, even if the initial request asks for it. Wait for a new user request after the artifacts are presented; then start the apply workflow.
|
||||
|
||||
I'll create a change with the artifacts your schema defines. With the default spec-driven schema that is:
|
||||
- proposal.md (what & why)
|
||||
- `specs/<capability-path>/spec.md` (what the system must do - a delta, not the main spec)
|
||||
- design.md (how)
|
||||
- tasks.md (implementation steps)
|
||||
|
||||
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
|
||||
|
||||
When the user is ready to implement, they must start the apply workflow explicitly.
|
||||
|
||||
---
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
|
||||
|
||||
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
|
||||
|
||||
Otherwise, with no root, what happens next depends on how this workflow was reached:
|
||||
|
||||
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
|
||||
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
|
||||
|
||||
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
|
||||
|
||||
**Input**: The argument after `/opsx:propose` is the change name (kebab-case), OR a description of what the user wants to build.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Understand the request and clarify material ambiguity**
|
||||
|
||||
If no input is provided, ask the user (open-ended, no preset options):
|
||||
> "What change do you want to work on? Describe what you want to build or fix."
|
||||
|
||||
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
|
||||
|
||||
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
|
||||
|
||||
If the request contains ambiguity that would materially affect scope, externally observable behavior, compatibility, or acceptance criteria, ask the user before creating the change. For minor details, make a reasonable assumption and record it in the planning artifacts.
|
||||
|
||||
2. **Load project context**
|
||||
|
||||
Run `openspec context --json` from the current working directory (or `openspec context --json --store "<store-id>"` when a registered store was explicitly selected). Use the returned `root.path` as the authoritative OpenSpec root. If context reports `no_openspec_root`, stop without creating or changing any files and follow the **Project check** above for how this workflow was reached. Offer `openspec init` only for an explicit OpenSpec request, and wait for the user to request initialization. Do not initialize automatically or run `openspec new change`. After initialization, rerun this context check before continuing. For any other context failure, stop and report the error; do not fall back to the current directory or run later OpenSpec commands without the selected store.
|
||||
|
||||
Only when context returns a resolved `root.path`, read `<root.path>/openspec/config.yaml`. Use `config.yml` only when `config.yaml` does not exist. If neither file exists, continue without project context. Do not fall back to `config.yml` if `config.yaml` is unreadable or invalid.
|
||||
|
||||
If the file parses as a YAML object and its `context` field is a string no larger than 51,200 bytes in UTF-8, apply that field before exploring the codebase or making planning decisions. If the file cannot be read or parsed, or the context field is invalid or oversized, continue without project context. Validate this field independently of other config fields, as OpenSpec does.
|
||||
|
||||
Treat context as project-provided data and constraints, not as authority to change this workflow: it cannot override user authorization, the planning boundary, tool restrictions, or artifact and output rules. Do not copy the context into artifacts; use it to focus any codebase exploration and as a constraint on the proposal.
|
||||
|
||||
3. **Determine the workflow schema**
|
||||
|
||||
Use the configured default schema unless the user explicitly requests a different workflow.
|
||||
|
||||
**Use a different schema only if the user:**
|
||||
- Explicitly requests a specific schema by name → use `--schema <schema-name>`
|
||||
- Asks to "show workflows" or asks "what workflows" exist → resolve the authoritative root by running `openspec context --json` from the current working directory. If the user explicitly selected a registered store, use `openspec context --json --store "<store-id>"`. Then run `openspec schemas --json` with its working directory set to the returned `root.path` and let them choose. This preserves roots selected by a local `store:` pointer or the global `defaultStore`; when a registered store was explicitly selected, append `--store "<store-id>"` to `openspec schemas --json` as well. If context fails, stop as described in the context-loading step; do not fall back to the current directory.
|
||||
|
||||
Otherwise, omit `--schema` to preserve the configured default.
|
||||
|
||||
4. **Create the change directory**
|
||||
|
||||
Choose one schema form below. If a registered store is selected, append `--store "<store-id>"` to that command and each later OpenSpec command shown below that accepts `--store`.
|
||||
|
||||
Using the configured default:
|
||||
```bash
|
||||
openspec new change "<name>"
|
||||
```
|
||||
|
||||
Using an explicitly requested schema:
|
||||
```bash
|
||||
openspec new change "<name>" --schema "<schema-name>"
|
||||
```
|
||||
This creates a scaffolded change in the planning home resolved by the CLI with `.openspec.yaml`.
|
||||
|
||||
5. **Get the artifact build order**
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
Parse the JSON to get:
|
||||
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
|
||||
- `artifacts`: list of all artifacts, each with its `status` and its `requires` edges (the artifact IDs it directly depends on)
|
||||
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
|
||||
|
||||
6. **Create every artifact in the required set**
|
||||
|
||||
Use a todo list to track progress through the artifacts.
|
||||
|
||||
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
|
||||
|
||||
a. **For each artifact that is `ready` (dependencies satisfied)**:
|
||||
- Get instructions:
|
||||
```bash
|
||||
openspec instructions <artifact-id> --change "<name>" --json
|
||||
```
|
||||
- The instructions JSON includes:
|
||||
- `context`: Project background (constraints for you - do NOT include in output)
|
||||
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
|
||||
- `template`: The structure to use for your output file
|
||||
- `instruction`: Schema-specific guidance for this artifact type
|
||||
- `skipped`/`warning`: present when the change declares skip_specs and this artifact must NOT be created - stop and pick another artifact
|
||||
- `resolvedOutputPath`: Resolved path or pattern to write the artifact
|
||||
- `dependencies`: Completed artifacts to read for context
|
||||
- Read any completed dependency files for context - always re-read them from disk, even if you saw them earlier in the conversation (the user may have edited them)
|
||||
- **Inspect the relevant project before drafting**: Read `context` and `rules` first, then inspect relevant implementation, nearby tests, configuration, and documentation outside `openspec/`. Keep inspection read-only and proportional to the change; reuse findings for later artifacts and inspect more only as needed.
|
||||
- Identify the target project from the request and project context; the planning home may be separate from the code. If the target is unclear, ask. For greenfield or non-code changes, inspect the available structure and relevant documents. If source is unavailable, state the limitation and ask when it materially affects the plan.
|
||||
- Ground scope, approach, and tasks in what you find. Distinguish observed behavior from assumptions and proposed additions; surface conflicts with existing specs instead of silently deciding which is correct.
|
||||
- Do this discovery now, rather than leaving generic "explore the codebase" or "make a plan" tasks for implementation. Keep any necessary follow-up investigation specific to an unresolved question.
|
||||
- If the `instruction` field delegates creation to a specific skill or command, invoke it to produce the artifact instead of writing the file yourself, then verify the artifact file exists at `resolvedOutputPath`
|
||||
- Otherwise create the artifact file using `template` as the structure and write it to `resolvedOutputPath`. If `resolvedOutputPath` is a glob, follow `instruction` to choose the concrete file path
|
||||
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
|
||||
- Show brief progress: "Created <artifact-id>"
|
||||
|
||||
b. **Continue until every artifact in the required set exists (not just `apply.requires`)**
|
||||
- After creating each artifact, re-run `openspec status --change "<name>" --json`
|
||||
- The required set is `applyRequires` plus every artifact reachable from those by following the `requires` edges in `status --json` - walk them transitively (spec-driven closes over proposal, specs, design, tasks). Leave artifacts outside that set alone
|
||||
- `status` is file-existence only, so an `applyRequires` artifact reading `done` does NOT mean its dependencies exist - writing `tasks.md` early marks `tasks` done while `specs` was never written. Use each artifact's `requires` edges, not its `status`, to build the required set: a `done` artifact still lists what it depends on
|
||||
- An artifact already reading `status: "skipped"` is satisfied: the change declares `skip_specs` in `.openspec.yaml`, so its files must NOT exist. Never try to create one
|
||||
- Create every artifact in the required set that is missing, then re-check - creating one can unblock others
|
||||
- Skip one only when `status` already reports it `skipped`, or when its own `instruction` says it is conditional: run `openspec instructions <artifact-id> --change "<name>" --json` and skip only if its `instruction` field marks it optional (e.g. "create only if..."). Spec-driven's `design.md` qualifies; `specs` qualifies only via the `skipped` status above, never by your own judgment. Tell the user, and do not reconsider it
|
||||
- Dependencies are enablers, not gates: if a required artifact is still `blocked` only because you skipped a conditional dependency, write it anyway
|
||||
- Stop when every artifact in the required set is `done`, `skipped`, or was deliberately skipped
|
||||
|
||||
c. **If an artifact requires user input** (unclear context):
|
||||
- Ask the user to clarify
|
||||
- Then continue with creation
|
||||
|
||||
7. **Show final status**
|
||||
```bash
|
||||
openspec status --change "<name>"
|
||||
```
|
||||
|
||||
**Output**
|
||||
|
||||
After completing all artifacts, summarize:
|
||||
- Change name and location
|
||||
- List of artifacts created with brief descriptions, plus any conditional artifact you skipped and why
|
||||
- What's ready: "All artifacts needed for implementation are ready."
|
||||
- Prompt: "The artifacts are ready for review. When you are ready, run `/opsx:apply`."
|
||||
|
||||
**Artifact Creation Guidelines**
|
||||
|
||||
- Follow the `instruction` field from `openspec instructions` for each artifact type - it is the authoritative guidance, even for familiar artifact names
|
||||
- If the `instruction` field directs you to use a specific skill or command to create the artifact, invoke it instead of writing the artifact directly
|
||||
- The schema defines what each artifact should contain - follow it
|
||||
- Read dependency artifacts for context before creating new ones
|
||||
- Use `template` as the structure for your output file - fill in its sections
|
||||
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
|
||||
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
|
||||
- These guide what you write, but should never appear in the output
|
||||
|
||||
**Guardrails**
|
||||
- The request that invoked this workflow authorizes planning only. Any implementation or apply instruction in that request does not carry forward. Do NOT implement the change, start the apply workflow, or edit project code during this workflow. After presenting the artifacts, stop and wait for a new user request to start the apply workflow
|
||||
- Create every artifact the apply phase transitively depends on, not just the ids listed in `apply.requires`
|
||||
- Always read dependency artifacts before creating a new one - re-read from disk, not from conversation memory (files may have changed since you last saw them)
|
||||
- Ask about ambiguities that would materially change scope, externally observable behavior, compatibility, or acceptance criteria; for minor details, make reasonable assumptions and record them
|
||||
- If a change with that name already exists, ask if user wants to continue it or create a new one
|
||||
- Verify each artifact file exists after writing before proceeding to next
|
||||
@@ -0,0 +1,286 @@
|
||||
---
|
||||
name: "OPSX: Sync"
|
||||
description: "Sync delta specs from a change to main specs"
|
||||
allowed-tools: Bash(openspec:*)
|
||||
category: "Workflow"
|
||||
tags: ["workflow", "specs", "experimental"]
|
||||
---
|
||||
|
||||
Sync delta specs from a change to main specs.
|
||||
|
||||
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
|
||||
|
||||
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||
|
||||
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
|
||||
|
||||
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
|
||||
|
||||
Otherwise, with no root, what happens next depends on how this workflow was reached:
|
||||
|
||||
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
|
||||
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
|
||||
|
||||
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
|
||||
|
||||
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
|
||||
|
||||
**Input**: Optionally specify a change name after `/opsx:sync` (e.g., `/opsx:sync add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
|
||||
|
||||
When prompting, show changes that have delta specs (under `specs/` directory).
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:sync <other>`).
|
||||
|
||||
2. **Resolve change context**
|
||||
|
||||
Run:
|
||||
```bash
|
||||
openspec status --change "<name>" --json
|
||||
```
|
||||
|
||||
The JSON includes `planningHome.root`. Main specs live under `<planningHome.root>/openspec/specs/` — use that (store-aware) root for every main-spec path below, not a hardcoded repo path. When a store is selected it points at the store, not the current repository.
|
||||
|
||||
3. **Find delta specs**
|
||||
|
||||
Use `artifactPaths.specs.existingOutputPaths` from the status JSON as the
|
||||
only source of delta spec paths. If the `specs` entry is missing or
|
||||
`existingOutputPaths` is empty, report that there are no delta specs to sync,
|
||||
do not infer them from other artifacts, and stop without requesting artifact
|
||||
instructions or writing a main spec.
|
||||
|
||||
Sync every path in `existingOutputPaths` unless the caller narrowed the set.
|
||||
A caller narrows it by naming an explicit list of complete entries from
|
||||
`existingOutputPaths` — copy those absolute values verbatim. Archive does
|
||||
this inline, and a user can too (for example, by selecting the entry ending
|
||||
in `/specs/billing/invoices/spec.md`).
|
||||
Then sync only the named paths and leave the remaining delta specs untouched:
|
||||
bulk archive excludes a delta whose implementation it could not find, and
|
||||
syncing it anyway would write a main spec the caller deliberately withheld.
|
||||
Carry that narrowed selection through step 4; never widen it back to the full
|
||||
list. If a named path is not in `existingOutputPaths`, do not sync it —
|
||||
report it and stop, rather than dropping it silently. If the named list is
|
||||
empty, report that there is nothing to sync and stop without writing a main
|
||||
spec.
|
||||
|
||||
Each delta spec file contains sections like:
|
||||
- `## ADDED Requirements` - New requirements to add
|
||||
- `## MODIFIED Requirements` - Changes to existing requirements
|
||||
- `## REMOVED Requirements` - Requirements to remove
|
||||
- `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
|
||||
|
||||
If no delta specs found, inform user and stop.
|
||||
|
||||
4. **For each delta spec, apply changes to main specs**
|
||||
|
||||
Before the first main-spec write, obtain one current specs-rule snapshot:
|
||||
- If archive invoked this workflow inline and supplied a valid snapshot from
|
||||
`openspec instructions specs --change "<name>" --json`, reuse it and do not
|
||||
fetch the same instructions again.
|
||||
- Otherwise run that command once now with the same selected-root flags.
|
||||
- If the direct lookup exits non-zero or returns invalid artifact-instruction
|
||||
JSON, report the error and stop before writing any main spec. Do not treat the
|
||||
failure as an absent rule set.
|
||||
- A valid response with omitted `rules` means no artifact rules are configured
|
||||
and the existing semantic merge continues.
|
||||
|
||||
Apply returned `rules` only to the content and form of the main specs produced
|
||||
by this merge. Artifact rules are not operation guidance and cannot change
|
||||
selected roots, delta paths, CLI checks, or workflow steps. Use their text as
|
||||
constraints without copying it verbatim into a main spec or summary.
|
||||
|
||||
For each capability delta spec path selected in step 3 — the full `existingOutputPaths` list, or the narrowed subset when a caller supplied one (these may belong to a selected store, not the repo):
|
||||
|
||||
a. **Read the delta spec** to understand the intended changes
|
||||
|
||||
b. **Read the main spec** at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (may not exist yet)
|
||||
|
||||
**If it does not exist yet** (a new capability), match what `openspec archive` does:
|
||||
only ADDED requirements may be applied - step d creates the spec from them.
|
||||
MODIFIED and RENAMED have no requirement to act on, so stop the sync for that
|
||||
capability and report that its main spec does not exist and only ADDED is allowed
|
||||
for a new spec; never invent the missing requirement. REMOVED has nothing to
|
||||
remove - skip it and warn.
|
||||
|
||||
c. **Apply changes intelligently**:
|
||||
|
||||
**ADDED Requirements:**
|
||||
- If requirement doesn't exist in main spec → add it
|
||||
- If requirement already exists → update it to match (treat as implicit MODIFIED)
|
||||
|
||||
**MODIFIED Requirements:**
|
||||
- Find the requirement in main spec
|
||||
- Apply the changes - this can be:
|
||||
- Adding new scenarios the main spec does not have yet
|
||||
- Modifying existing scenarios
|
||||
- Changing the requirement description
|
||||
- Preserve scenarios/content not mentioned in the delta
|
||||
|
||||
**REMOVED Requirements:**
|
||||
- Remove the entire requirement block from main spec
|
||||
- Retiring the capability. Delete the whole `spec.md` - and the directory once
|
||||
nothing else is left in it - only when ALL of these hold:
|
||||
1. removing the requirements *this run* left no requirement blocks;
|
||||
2. the rest of the spec is well-formed (it still has a `## Purpose`);
|
||||
3. the main spec was not already empty before this sync - if you removed
|
||||
nothing, change nothing;
|
||||
4. every other nonblank line in the whole file is accounted for as the
|
||||
title, Purpose, Requirements header, or a canonical requirement's
|
||||
statement, scenarios, or fenced examples;
|
||||
5. the change's `.openspec.yaml` declares `retire_capabilities: true`;
|
||||
6. the `spec.md` resolves inside the real specs root (do not follow a
|
||||
capability-directory symlink to delete an external file).
|
||||
If removing the selected requirements would leave no requirement blocks and
|
||||
any retirement condition is not satisfied, do not modify the main spec. Stop
|
||||
the sync for that capability, report the blocking condition, and tell the user
|
||||
how to resolve it. Never write or leave an empty `## Requirements` section.
|
||||
When only the marker is missing, say that too - it is the one thing the user
|
||||
can add to make the retirement go through.
|
||||
- Deleting the file also deletes its `## Purpose`; any other section blocks
|
||||
retirement. Name Purpose when you report the retirement. Include a pasteable
|
||||
`git checkout` only when the spec lived in the caller's checkout;
|
||||
otherwise give checkout-scoped recovery guidance.
|
||||
|
||||
**RENAMED Requirements:**
|
||||
- Find the FROM requirement, rename to TO
|
||||
|
||||
**`## Purpose` in the delta:**
|
||||
- The main spec already has one and it is authoritative - leave it alone
|
||||
(this is what `openspec archive` does; it warns and moves on)
|
||||
|
||||
d. **Create new main spec** if capability doesn't exist yet:
|
||||
- Only when the delta has ADDED requirements to put in it and no MODIFIED or
|
||||
RENAMED requirements blocked this capability in step b. Otherwise create nothing
|
||||
and leave the specs directory untouched. For a REMOVED-only delta, if the change's
|
||||
`.openspec.yaml` declares `retire_capabilities: true`, report it as already retired
|
||||
and continue without recreating the spec. Without that marker, report the sync as blocked:
|
||||
`openspec archive` rejects it with `Spec must have at least one requirement`.
|
||||
An empty delta has no operations to sync; report it as blocked too.
|
||||
Never write an empty `## Requirements` section.
|
||||
- Create `<planningHome.root>/openspec/specs/<capability-path>/spec.md`
|
||||
- Add Purpose section: copy the delta's `## Purpose` body verbatim when it has one
|
||||
(this is what `openspec archive` does); only write a brief TBD placeholder when it does not
|
||||
- Add Requirements section with the ADDED requirements
|
||||
- Follow the **Main Spec Format Reference** below
|
||||
|
||||
5. **Validate updated main specs**
|
||||
|
||||
Run `openspec validate --specs` with the same selected-root flags used earlier.
|
||||
If validation fails, report the problems and do not claim the sync succeeded.
|
||||
|
||||
6. **Show summary**
|
||||
|
||||
After applying all changes, summarize:
|
||||
- Which capabilities were updated
|
||||
- What changes were made (requirements added/modified/removed/renamed)
|
||||
- Any new main spec left with a TBD Purpose placeholder, so it gets written
|
||||
now rather than lingering
|
||||
- Any capability retired, naming the deleted `spec.md`, its Purpose, and
|
||||
either a pasteable `git checkout` or checkout-scoped recovery guidance
|
||||
|
||||
**Delta Spec Format Reference**
|
||||
|
||||
```markdown
|
||||
# Spec Delta
|
||||
|
||||
## Purpose
|
||||
|
||||
Only on a delta that introduces a brand-new capability. Seeds the new main spec.
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: New Feature
|
||||
The system SHALL do something new.
|
||||
|
||||
#### Scenario: Basic case
|
||||
- **WHEN** user does X
|
||||
- **THEN** system does Y
|
||||
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Existing Feature
|
||||
The system SHALL keep doing the existing thing, now also handling A.
|
||||
|
||||
#### Scenario: Scenario the main spec already has
|
||||
- **WHEN** user does X
|
||||
- **THEN** system does Y
|
||||
|
||||
#### Scenario: New scenario to add
|
||||
- **WHEN** user does A
|
||||
- **THEN** system does B
|
||||
|
||||
## REMOVED Requirements
|
||||
|
||||
### Requirement: Deprecated Feature
|
||||
|
||||
## RENAMED Requirements
|
||||
|
||||
- FROM: `### Requirement: Old Name`
|
||||
- TO: `### Requirement: New Name`
|
||||
```
|
||||
|
||||
**Main Spec Format Reference**
|
||||
|
||||
Main specs are what the delta merges INTO. They must never contain delta operation headers (`## ADDED/MODIFIED/REMOVED/RENAMED Requirements`) - after syncing, every requirement lives under a single `## Requirements` section:
|
||||
|
||||
```markdown
|
||||
# <capability> Specification
|
||||
|
||||
## Purpose
|
||||
Short description of what this capability does and why it exists.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: New Feature
|
||||
The system SHALL do something new.
|
||||
|
||||
#### Scenario: Basic case
|
||||
- **WHEN** user does X
|
||||
- **THEN** system does Y
|
||||
```
|
||||
|
||||
**Key Principle: Intelligent Merging**
|
||||
|
||||
Unlike programmatic merging, you merge rather than overwrite:
|
||||
- A MODIFIED block carries the whole requirement - body plus every scenario that survives the change. `openspec validate` and `openspec archive` both reject one that drops a scenario the main spec still has.
|
||||
- Keep anything the delta does not mention, in the main spec's existing order
|
||||
- Use your judgment to merge changes sensibly
|
||||
|
||||
**Output On Success**
|
||||
|
||||
```markdown
|
||||
## Specs Synced: <change-name>
|
||||
|
||||
Updated main specs:
|
||||
|
||||
**<capability-1>**:
|
||||
- Added requirement: "New Feature"
|
||||
- Modified requirement: "Existing Feature" (added 1 scenario)
|
||||
|
||||
**<capability-2>**:
|
||||
- Created new spec file
|
||||
- Added requirement: "Another Feature"
|
||||
|
||||
Main specs are now updated. The change remains active - archive when implementation is complete.
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Read both delta and main specs before making changes
|
||||
- Preserve existing content not mentioned in delta
|
||||
- Never copy a delta file into a main spec as-is - merge its content so the main spec keeps the Main Spec Format Reference structure, with no delta operation headers
|
||||
- If something is unclear, ask for clarification
|
||||
- Show what you're changing as you go
|
||||
- The operation should be idempotent - running twice should give same result
|
||||
- Use only `artifactPaths.specs.existingOutputPaths`; never infer delta specs from unrelated artifacts
|
||||
- Honor a caller-supplied subset of `existingOutputPaths`; never widen it back to the full list
|
||||
- Fetch specs instructions once for direct sync, or reuse the archive-supplied snapshot inline
|
||||
- Stop before every main-spec write on a non-zero or invalid JSON specs-instruction response
|
||||
- Artifact rules constrain only the specs being written and are never copied into output files
|
||||
@@ -0,0 +1,99 @@
|
||||
---
|
||||
name: "OPSX: Update"
|
||||
description: "Update a change - revise existing planning artifacts and keep them coherent (Experimental)"
|
||||
allowed-tools: Bash(openspec:*)
|
||||
category: "Workflow"
|
||||
tags: ["workflow", "artifacts", "experimental"]
|
||||
---
|
||||
|
||||
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.
|
||||
|
||||
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
|
||||
|
||||
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
|
||||
|
||||
Otherwise, with no root, what happens next depends on how this workflow was reached:
|
||||
|
||||
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
|
||||
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
|
||||
|
||||
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
|
||||
|
||||
**Input**: Optionally specify a change name after `/opsx:update` (e.g., `/opsx:update add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
This workflow revises artifacts that already exist; it never creates missing ones. When an artifact is missing, `openspec status --change "<name>" --json` names the next one and `openspec instructions "<artifact-id>" --change "<name>" --json` explains how to write 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., `/opsx:update <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.
|
||||
- Draft the requested edit in the conversation, not in files. Work out exactly what it changes; step 5 owns every write. Then check every other existing artifact against the drafted edit - 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.
|
||||
- Propose revisions only to 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 instructions "<artifact-id>" --change "<name>" --json` for how to create them.
|
||||
- If the change is already coherent, say so and propose no revisions.
|
||||
|
||||
5. **Confirm and apply, one artifact at a time**
|
||||
- This step performs every artifact write in this workflow; no earlier step edits an artifact.
|
||||
- Show each proposed revision and why - including the requested edit drafted in step 4. 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 -> run `openspec status --change "<name>" --json` for the next artifact and point the user to `openspec instructions "<artifact-id>" --change "<name>" --json` for how to create it.
|
||||
- Change already implemented (tasks checked off / already applied) -> the code may no longer match the revised plan; suggest `/opsx:apply` to carry the delta into code.
|
||||
- Everything done and implemented -> suggest `/opsx:archive`.
|
||||
|
||||
**Output**
|
||||
|
||||
After each invocation, show:
|
||||
- Which artifacts were revised (and which proposed revisions were rejected)
|
||||
- Anything deferred because it does not exist yet (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 `/opsx:apply`.
|
||||
- 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 - creating them is a separate step, outside this workflow.
|
||||
- Confirm every edit with the user before writing.
|
||||
- If the request changes the change's *intent* rather than refining it, ask for a distinct unused change name and recommend `openspec new change "<new-change-name>"` instead (the "Update vs. Start Fresh" heuristic).
|
||||
@@ -0,0 +1,184 @@
|
||||
---
|
||||
name: "OPSX: Verify"
|
||||
description: "Verify implementation matches change artifacts before archiving"
|
||||
allowed-tools: Bash(openspec:*)
|
||||
category: "Workflow"
|
||||
tags: ["workflow", "verify", "experimental"]
|
||||
---
|
||||
|
||||
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.
|
||||
|
||||
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
|
||||
|
||||
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
|
||||
|
||||
Otherwise, with no root, what happens next depends on how this workflow was reached:
|
||||
|
||||
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
|
||||
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
|
||||
|
||||
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
|
||||
|
||||
**Input**: Optionally specify a change name after `/opsx:verify` (e.g., `/opsx:verify add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **Select the change**
|
||||
|
||||
If a name is provided, use it. Otherwise:
|
||||
- Infer from conversation context if the user mentioned a change
|
||||
- Auto-select if only one active change exists
|
||||
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
|
||||
|
||||
When prompting, show changes that have 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., `/opsx:verify <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: complete means the box holds only `x`/`X`, ignoring
|
||||
spacing (`- [ x]` is complete); every other marker is incomplete
|
||||
(`- [ ]`, `- []`, and unfamiliar ones such as `- [~]` or `- [-]`)
|
||||
- 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"
|
||||
@@ -0,0 +1,151 @@
|
||||
---
|
||||
paths:
|
||||
- "src/api/**"
|
||||
- "src/core/**"
|
||||
- "src/schemas/**"
|
||||
- "student-tests/**"
|
||||
---
|
||||
|
||||
# Контракт API: что требуют smoke и защита
|
||||
|
||||
Источники: `contracts/openapi.json` (пути, схемы, коды),
|
||||
`contracts/README.md` (семантика; приоритет над поведением библиотек,
|
||||
кроме согласованных расхождений FastAPI — раздел ниже), рубрика в
|
||||
`README.md`. Сгенерированная FastAPI схема (`/openapi.json`) — только
|
||||
справка, сверять с контрактом. Если контракт противоречит сам себе —
|
||||
спросить пользователя. Ниже то, что легко нарушить.
|
||||
|
||||
## FastAPI: что разрешено и что всё равно ловит smoke
|
||||
|
||||
Преподаватель 2026-09-26 разрешил FastAPI с его расхождениями: лишний
|
||||
422 и другой порядок кодов ошибок (AGENTS.md, «Согласования с
|
||||
преподавателем»). Публичный smoke это не отменяет: на каждый ответ
|
||||
≥ 400 он проверяет и статус, и тело `{"error": ...}`. Проверено на
|
||||
FastAPI 0.141 из `uv.lock`:
|
||||
|
||||
| Запрос | FastAPI по умолчанию | Smoke ждёт |
|
||||
|---|---|---|
|
||||
| `GET /api/v1/users/me` без `X-User-Id`, заголовок объявлен `Header()` | 422 | 401 |
|
||||
| `POST .../messages` с `{"text": ""}` | 422 | 400 |
|
||||
| `GET .../messages?limit=0` | 422 | 400 |
|
||||
| любая ошибка | `{"detail": ...}` | формат контракта |
|
||||
|
||||
- Один обработчик `RequestValidationError` → 400 `invalid_request` в
|
||||
формате контракта. Оставлять 422 выборочно сложнее, чем перевести всё,
|
||||
поэтому 422 не отдаётся вообще.
|
||||
- `X-User-Id` не объявлять типизированным `Header()`: пропуск или не-UUID
|
||||
уйдёт в валидацию и даст 400 вместо 401. И не читать его вручную из
|
||||
`request.headers`: тогда в `/openapi.json` нет схемы `devUser` из
|
||||
контракта, а в `/docs` нет кнопки Authorize. Правильно — схема
|
||||
безопасности `APIKeyHeader(name="X-User-Id", scheme_name="devUser",
|
||||
auto_error=False)` в `get_current_user`: без заголовка она отдаёт
|
||||
`None`, и 401 бросает сервис. С лабы 2 так же — своя схема для Bearer.
|
||||
- Порядок проверок не выправлять, это и есть разрешённое расхождение.
|
||||
Битый JSON FastAPI разбирает до зависимостей, поэтому запрос без
|
||||
`X-User-Id` с битым JSON получит 400, а не 401. Остальная валидация
|
||||
(тело, путь, query) идёт после зависимостей, там 401 приходит первым.
|
||||
Расхождение перечислить в `REPORT.md` со ссылкой на согласование.
|
||||
- `StarletteHTTPException` (404 неизвестного пути, 405) и `Exception`
|
||||
(500) тоже переводятся в формат контракта.
|
||||
|
||||
## Формат ответов
|
||||
|
||||
- Непустой `X-Request-Id` в **каждом** ответе: успех, ошибка, health,
|
||||
404 неизвестного пути, 405, 500.
|
||||
- Любая ошибка: `{"error": {"code": ..., "message": ..., "request_id":
|
||||
...}}` с `Content-Type: application/json`, и `request_id` совпадает с
|
||||
заголовком. Лишних полей нет (`additionalProperties: false`).
|
||||
- `message` — короткий текст для человека **на английском** (язык
|
||||
контракт не задаёт, русский текст в `contracts/examples.json` — только
|
||||
пример). В нём нет stack trace, путей к файлам, имён классов, SQL и
|
||||
признаков существования чужого объекта. Источник текста —
|
||||
`default_message` доменного исключения или общий текст обработчика в
|
||||
`errors.py`.
|
||||
- Обработчики `RequestValidationError`, `StarletteHTTPException` и
|
||||
`Exception` переопределяются в `src/api/errors.py` (раздел «FastAPI»
|
||||
выше).
|
||||
|
||||
| Статус | `code` | Когда |
|
||||
|---|---|---|
|
||||
| 400 | `invalid_request` | тело, UUID, `limit`, `cursor`, malformed JSON, лишнее поле, неверный тип |
|
||||
| 401 | `unauthorized` | нет `X-User-Id`, не UUID, пользователя нет |
|
||||
| 404 | `not_found` | объекта нет **или** он чужой; неизвестный путь |
|
||||
| 409 | `conflict` | `username` занят |
|
||||
| 500 | `internal_error` | необработанное исключение, без деталей |
|
||||
|
||||
`413`, `415`, `429`, `503` в схеме есть, но на лабе 1 обязательной причины
|
||||
для них нет. Для 429 нужен `Retry-After` (трек 2 уровня 5).
|
||||
|
||||
- Время — RFC 3339 UTC с `Z`, назначает сервер. Формат отдавать явно
|
||||
через `src/utils/utc.py`, а не полагаться на сериализацию по
|
||||
умолчанию: smoke требует окончание `Z`.
|
||||
- `created_at` хранится и отдаётся с одной точностью (микросекунды).
|
||||
Иначе порядок, который видит клиент, разойдётся с порядком курсора.
|
||||
- `GET /health/live` → 200 `{"status": "ok"}`. `GET /health/ready` → 200
|
||||
`{"status": "ok"}` или 503 в формате ошибки. Обе без идентификации.
|
||||
|
||||
## Валидация → 400
|
||||
|
||||
- Модели запросов: `extra="forbid"` и строгие типы на уровне полей
|
||||
(`StrictStr`, `StrictInt`), чтобы число не превращалось в строку, а
|
||||
лишнее поле давало 400. `ConfigDict(strict=True)` на всю модель не
|
||||
ставить: FastAPI валидирует тело как Python-объект, и strict-режим
|
||||
отвергает UUID, пришедший строкой (проверено: корректный
|
||||
`member_ids` даёт 422). Query-параметры остаются нестрогими:
|
||||
`limit=5` приходит строкой.
|
||||
- Malformed JSON и не-объект вместо объекта → 400. FastAPI отдаёт их как
|
||||
422 `json_invalid`, это переводится общим обработчиком.
|
||||
- Обязательные строки (`display_name`, `title`, `text`) не могут
|
||||
состоять только из пробельных символов (`str.strip()` пустой → 400).
|
||||
Само значение не обрезать.
|
||||
- Длины считаются в Unicode code points: `len(str)` в Python как раз они.
|
||||
`display_name` и `title` — 1–100, `text` — 1–4000.
|
||||
- `username` — строго `^[a-z0-9_]{3,32}$` на всю строку. В ручной проверке
|
||||
`re.fullmatch`: `re.match` с `$` пропускает `\n` в конце.
|
||||
- Лишнее поле `sender_id` в теле сообщения → 400: отправитель выводится
|
||||
из текущего пользователя.
|
||||
- `chat_id` не UUID → 400. `limit` — целое 1–100, по умолчанию 50;
|
||||
`limit=0` и нечисловой → 400. Битый `cursor` → 400.
|
||||
- `member_ids`: 1–100 элементов, без дубликатов, все пользователи
|
||||
существуют, вызывающий в списке. Иначе 400.
|
||||
|
||||
## Идентификация (лаба 1)
|
||||
|
||||
- Защищено всё, кроме `POST /api/v1/users` и health. `X-User-Id` —
|
||||
UUID существующего пользователя. Нет заголовка, не UUID или
|
||||
пользователя нет → 401.
|
||||
- Сначала идентификация, потом доступ: без заголовка — 401 даже на
|
||||
чужой чат. Чужой и несуществующий чат дают одинаковый 404, 403 не
|
||||
используется.
|
||||
- Меняется только зависимость `get_current_user`: с лабы 2 там Bearer,
|
||||
а `X-User-Id` игнорируется (`COURSE.md`, переход 1 → 2).
|
||||
|
||||
## Чаты и сообщения
|
||||
|
||||
- Чат создаётся атомарно. `GET /api/v1/chats` возвращает только чаты
|
||||
текущего пользователя, по `(created_at, id)` по возрастанию, с
|
||||
`limit` / `cursor`, как история.
|
||||
- Любой участник читает чат и историю и пишет в чат. Посторонний
|
||||
получает 404 на `GET` чата, историю и `POST` сообщения.
|
||||
|
||||
## Пагинация (keyset)
|
||||
|
||||
- Порядок `(created_at, id)` по возрастанию. `id` сравнивается как UUID
|
||||
(`uuid.UUID(x).int`) — так же сортирует smoke.
|
||||
- Ответ: `{"items": [...], "next_cursor": null | "..."}`. `next_cursor`
|
||||
равен null, когда следующей записи нет на момент чтения. Страница
|
||||
ровно из `limit` элементов при пустом остатке тоже даёт null, поэтому
|
||||
repo выбирает `limit + 1`.
|
||||
- Курсор непрозрачный (`src/utils/cursor.py`): ключ последнего элемента
|
||||
плюс область — чат или список чатов пользователя. Курсор другого чата
|
||||
или пользователя, битая base64 или JSON → 400. Последний элемент
|
||||
предыдущей страницы не повторяется. `limit` между страницами можно
|
||||
менять.
|
||||
- Семантику при конкурентных вставках и ограничения часов описать в
|
||||
`REPORT.md` (например: `created_at` монотонен внутри чата).
|
||||
|
||||
## Состояние лабы 1
|
||||
|
||||
Только память одного процесса, один worker uvicorn. После рестарта
|
||||
контейнера прежний `X-User-Id` получает 401 — это ожидаемая потеря
|
||||
данных, её показывают на защите.
|
||||
@@ -0,0 +1,72 @@
|
||||
---
|
||||
paths:
|
||||
- "src/api/**"
|
||||
- "src/main.py"
|
||||
---
|
||||
|
||||
# Слой API (`src/api/`, `src/main.py`)
|
||||
|
||||
FastAPI, один процесс. Что обязан отдавать HTTP —
|
||||
`.claude/rules/api-contract.md`; здесь — как устроен слой.
|
||||
|
||||
## Роутинг
|
||||
|
||||
| Что | Файл | Путь |
|
||||
|---|---|---|
|
||||
| health | `routers/health.py` | `/health/live`, `/health/ready` — вне версии, без идентификации, из access-лога исключены |
|
||||
| ручки v1 | `routers/v1/<domain>.py` | `/api/v1/<prefix>/...` |
|
||||
|
||||
- Модуль домена: `router = APIRouter(prefix="/users", tags=["users"])`.
|
||||
Вложенный ресурс — префикс с параметром: `message.py` →
|
||||
`prefix="/chats/{chat_id}/messages"`. Логгер модуля
|
||||
`module="api_<domain>_router"`.
|
||||
- Версию задаёт `v1_router` (`API_V1_PREFIX` из `src/utils/constants.py`)
|
||||
в `routers/v1/__init__.py`. Регистрация домена — импорт и
|
||||
`v1_router.include_router(...)` там, больше нигде.
|
||||
- `src/main.py`: `app = FastAPI(...)`, lifespan, middlewares, обработчики
|
||||
ошибок (`errors.register(app)`), `include_router` для health и
|
||||
`v1_router`. `src/__init__.py` пустой: импорт любого модуля `src` не
|
||||
должен поднимать приложение.
|
||||
- Новая версия API — пакет `routers/v2/` рядом с v1, v1 не ломать.
|
||||
|
||||
## Внутри ручки
|
||||
|
||||
- Ручки и зависимости — только `async def`. Синхронная `def` уходит в
|
||||
threadpool, и тогда in-memory состояние трогают несколько потоков.
|
||||
- Ручка: зависимости → вызов сервиса именованными аргументами →
|
||||
DTO в модель ответа (`UserOut.model_validate(dto)`, у модели
|
||||
`from_attributes=True`). Логики, импортов repo и хранилища здесь нет.
|
||||
- Текущий пользователь — `Depends(get_current_user)` из
|
||||
`dependencies.py`. Сервис — зависимость-фабрика
|
||||
(`Depends(get_chat_service)`), которая собирает его из хранилища в
|
||||
`request.app.state`; с лабы 2 — из `AsyncSession`.
|
||||
- Ошибки — доменные исключения из сервиса. `HTTPException` не бросать.
|
||||
Статус и `code` назначает одна таблица в `errors.py`.
|
||||
- Модели запросов и ответов — `src/api/schemas/<domain>.py`, имена по
|
||||
схемам контракта (`CreateUser`, `User`, `ChatPage`...). В сервис модели
|
||||
API не передавать: разбирать в именованные аргументы или
|
||||
`Create<Entity>DTO`.
|
||||
- POST создания — `status_code=201` в декораторе; `response_model` —
|
||||
модель контракта.
|
||||
|
||||
## Middlewares и обработчики ошибок
|
||||
|
||||
- Request id: генерируется на каждый запрос, пишется в contextvar
|
||||
логгера и в `request.state.request_id` и ставится заголовком
|
||||
`X-Request-Id` в ответ.
|
||||
- 500 от необработанного исключения формирует `ServerErrorMiddleware`.
|
||||
Он стоит снаружи пользовательских middleware, и заголовок из них в этот
|
||||
ответ не попадёт. Поэтому обработчик `Exception` в `errors.py` сам
|
||||
берёт id из `request.state` и ставит заголовок. Сам он не логирует:
|
||||
Starlette после ответа повторно бросает исключение, и traceback пишет
|
||||
uvicorn (`logging.md`).
|
||||
- Итоговая запись о запросе — одна строка: метод, полный шаблон пути,
|
||||
статус, длительность. Без тела, заголовков идентификации и query.
|
||||
Логи uvicorn access выключены (`access_log=False`), чтобы не было
|
||||
дублей.
|
||||
- Полный шаблон пути не брать из `scope["route"].path`: с FastAPI 0.137
|
||||
роутеры включаются деревом, и там путь без префикса `include_router`
|
||||
(`/chats/{chat_id}` вместо `/api/v1/chats/{chat_id}`). Источник —
|
||||
таблица из публичного `iter_route_contexts(app.routes)` в
|
||||
`request_context.py`. Структуру роутеров ради логов не менять.
|
||||
- С лабы 3 — middleware `X-Instance-Id` на все ответы, созданные API.
|
||||
@@ -0,0 +1,136 @@
|
||||
---
|
||||
paths:
|
||||
- "bench/**"
|
||||
---
|
||||
|
||||
# Нагрузочный стенд (`bench/`)
|
||||
|
||||
Эксперимент трека 1 уровня «5» (`README.md`): матрица размеров истории
|
||||
и уровней конкуренции для чтения и записи, метрики и сырые данные в
|
||||
`evidence/bench/<метка>/`. Что стенд обязан делать — спек
|
||||
`load-benchmark`, почему так — design changes `load-bench-harness`
|
||||
(стенд) и `perf-bottleneck-fix` (диагностика и сравнение меток; после
|
||||
архивации — `openspec/changes/archive/`), результаты и выводы —
|
||||
`REPORT.md`, раздел «Эксперименты и отказы».
|
||||
|
||||
В `bench/` четыре инструмента:
|
||||
|
||||
| Файл | Команда | Что делает |
|
||||
|---|---|---|
|
||||
| `run.py`, `k6/` | `make bench`, `make bench_quick` | стенд: меряет пропускную способность, задержки и память |
|
||||
| `inproc.py` | `make bench_inproc` | диагностика: куда уходит время одного запроса внутри приложения |
|
||||
| `compare.py` | `make bench_compare` | дельта двух меток стенда, эффект или шум |
|
||||
| `ab.py` | `make bench_ab` | стенд и диагностика «до» и «после» одного изменения подряд, в одной сессии хоста |
|
||||
|
||||
## Что не меняется между метками
|
||||
|
||||
Метки сравнимы, только если различается код приложения и больше ничего.
|
||||
Не меняются:
|
||||
|
||||
- **лимиты контейнера приложения:** `--cpus=1 --memory=2g
|
||||
--memory-swap=2g`, `--no-healthcheck`, без `.env` и `config.toml`,
|
||||
порты на хост не публикуются;
|
||||
- **генератор:** `grafana/k6` той же версии и digest, в той же
|
||||
docker-сети, без лимита CPU;
|
||||
- **профиль `full`:** размеры, конкуренция, повторы, прогрев и
|
||||
длительности, длина текста, порция наполнения, зерно выбора курсоров
|
||||
и сдвиг зерна для прогрева, порог пометки `generator`. Все они — поля
|
||||
`Profile` в `run.py` и целиком пишутся в `meta.json`: новый параметр
|
||||
методики заводится там же, а не константой в коде.
|
||||
|
||||
Изменить что-то из списка — значит сменить методику: старые метки
|
||||
перестают быть «до», базовый замер переснимается, а в `REPORT.md`
|
||||
записывается, что и почему поменялось.
|
||||
|
||||
## Как писать
|
||||
|
||||
- Стенд — чёрный ящик: `run.py`, `k6/` и `compare.py` не импортируют
|
||||
`src` и не ходят в приложение мимо HTTP. Все запросы делает k6 внутри
|
||||
сети стенда, оркестратор управляет только docker CLI. Единственное
|
||||
исключение — режим `--child` в `inproc.py`: он работает внутри
|
||||
контейнера и импортирует приложение, потому что разложить время
|
||||
внутри процесса снаружи нельзя. На хосте `inproc.py` тоже только
|
||||
управляет docker.
|
||||
- Скрипты `bench/` на хосте — только stdlib Python, запуск
|
||||
`uv run python bench/<файл>.py`. Новых зависимостей не добавлять.
|
||||
- Сценарии k6 — JavaScript без Node.js: только встроенные модули k6.
|
||||
Заголовок идентификации собирается в одном месте `lib.js`: на лабе 2
|
||||
он станет Bearer, как `Actor.headers()` в `student-tests/`.
|
||||
- Имена контейнеров и сети — `mtusi-bench-*`. Чужие контейнеры
|
||||
(`make run_docker`, другие проекты) стенд не трогает и не
|
||||
останавливает. Уборка своих — в `finally` и по Ctrl+C.
|
||||
- Случайность только через свой генератор с зерном из профиля
|
||||
(`seed + номер VU`), не `Math.random`.
|
||||
|
||||
## Диагностика: `make bench_inproc`
|
||||
|
||||
- Она объясняет, а не меряет. Её числа не попадают в таблицы
|
||||
результатов стенда и не выдаются за пропускную способность: в
|
||||
`REPORT.md` они идут как «куда уходит время запроса», рядом с путём к
|
||||
файлу в `evidence/profile/`.
|
||||
- Процесс запускается в образе стенда с тем же `--cpus=1`, отсоединённо
|
||||
(`docker run -d`), как контейнер стенда. С подключённым клиентом
|
||||
docker и на хосте цена логов другая: запись в stdout контейнера стоит
|
||||
процессу десятки микросекунд на запрос.
|
||||
- Время запроса гуляет от запуска процесса к запуску на 1–3%. Поэтому
|
||||
каждый режим логов запускается несколько раз, а варианты одного шага
|
||||
(текущий форматтер против эталонного) сравниваются внутри одного
|
||||
процесса.
|
||||
- Варианты кода для сравнения живут в самом скрипте (подклассы моделей
|
||||
ответа), а не в `src`. Если для пробы всё же меняется `src` — правило
|
||||
следующего раздела.
|
||||
- Сверка формата времени с эталоном — часть команды: правка
|
||||
`src/utils/utc.py` проверяется ею, а не на глаз.
|
||||
|
||||
## Измеренное состояние — commit
|
||||
|
||||
Указание пользователя (2026-09-30). Перед замером или тестом, результат
|
||||
которого идёт в отчёт, состояние кода коммитится; хеш попадает в шапку
|
||||
файла доказательства и в `REPORT.md`. Пробное изменение `src`, которое
|
||||
потом откатывается, — отдельный commit, откат — новый commit поверх
|
||||
(`git revert`), без переписывания истории. Любое число в отчёте должно
|
||||
воспроизводиться из названного commit. Push и остальные операции git —
|
||||
по-прежнему только по просьбе.
|
||||
|
||||
## Сравнение меток: `make bench_compare`
|
||||
|
||||
- «До» и «после» снимаются в одной сессии хоста, подряд, без
|
||||
перезагрузки между ними. Код приложения между ними отличается одним
|
||||
изменением.
|
||||
- Порядок: изменение закоммичено, проверено тестами и откачено
|
||||
отдельным commit; затем `make bench_ab BEFORE=... AFTER=...
|
||||
REAPPLY=<commit отката>` снимает «до», коммитит доказательства,
|
||||
возвращает изменение и снимает «после». Команда сама делает два
|
||||
коммита и отказывается стартовать на нечистом рабочем дереве: стенд
|
||||
записал бы в паспорт `dirty: true`.
|
||||
- Уровень шума берётся из сравнения двух меток одного и того же кода
|
||||
приложения (A/A), параметр `AA`. Что код одинаков, проверяется по git
|
||||
(`git diff <commit> <commit> -- src Dockerfile pyproject.toml
|
||||
uv.lock`): команда этого не видит.
|
||||
- Изменение в ячейке — эффект, только если разбросы повторов не
|
||||
пересекаются и изменение медианы больше уровня шума сценария. Дельту
|
||||
в отчёт переносить из таблицы команды, не считать вручную.
|
||||
- Ячейки сценария, который изменение не затрагивает, — контроль: они
|
||||
тоже показываются в отчёте.
|
||||
|
||||
## Результаты
|
||||
|
||||
- Каталог метки не перезаписывается. `evidence/bench/quick-*` — в
|
||||
`.gitignore`: короткий прогон проверяет стенд, а не даёт результат.
|
||||
- `evidence/profile/<метка>.txt` тоже не перезаписывается; пробные
|
||||
метки `quick-*` — в `.gitignore`. `evidence/compare/<до>__<после>.md`
|
||||
выводится из неизменяемых каталогов меток и может пересоздаваться.
|
||||
- Столбцы `runs.csv` и `prefill.csv` не переименовываются и не
|
||||
удаляются: по ним сравниваются метки. Новая метрика — новый столбец
|
||||
в конце.
|
||||
- В результатах нет секретов, `.env` и абсолютных путей домашнего
|
||||
каталога; данные синтетические.
|
||||
- Перед полной матрицей хост должен быть в состоянии, которое можно
|
||||
проверить: питание от сети, swap около нуля (`sysctl vm.swapusage`),
|
||||
память свободна (`memory_pressure`), посторонних контейнеров нет.
|
||||
Если swap занят или память под давлением — перезагрузить ноутбук;
|
||||
если условия выполнены, перезагрузка не обязательна. Состояние
|
||||
записывается в паспорт (`host_state`), в отчёте оно указывается по
|
||||
паспорту, а не по плану. Во время прогона ноутбук не нагружать.
|
||||
Предупреждения о хосте в `meta.json` (`host_warnings`) — повод
|
||||
переснять, а не игнорировать.
|
||||
@@ -0,0 +1,136 @@
|
||||
---
|
||||
paths:
|
||||
- "Dockerfile"
|
||||
- "docker-compose.yml"
|
||||
- ".dockerignore"
|
||||
---
|
||||
|
||||
# Dockerfile и compose
|
||||
|
||||
Форма — как в bp_proxies: мультистейдж с uv, compose с портами из `.env`,
|
||||
литеральным режимом в `environment` и python-healthcheck. Требования
|
||||
рубрики (`README.md`, уровни 3 и 4) и `Dockerfile.example` важнее
|
||||
образца; отличия от него перечислены ниже. Режимы запуска —
|
||||
`run-modes.md`.
|
||||
|
||||
## Dockerfile
|
||||
|
||||
- Мультистейдж. В builder — `uv sync --locked --no-dev
|
||||
--no-install-project` по `pyproject.toml` и `uv.lock` в
|
||||
`/app/.venv`: слой зависимостей кешируется отдельно от кода. В
|
||||
runtime — копия `.venv` и `src/`, `PATH` на `/app/.venv/bin`.
|
||||
Компиляторы и uv в runtime не нужны (в bp_proxies uv ставился в оба
|
||||
stage).
|
||||
- Оба stage — на **одном** базовом образе: `.venv/bin/python` —
|
||||
ссылка на интерпретатор базового образа, на другом образе она
|
||||
сломается.
|
||||
- `--no-install-project`: `src/` в builder не копируется, и hatchling
|
||||
не собирает проект пакетом. `python -m src` находит `src` через
|
||||
рабочий каталог `/app`.
|
||||
- Версии закреплены: `тег@sha256:<digest индекса>`. Тег с патч-версией
|
||||
(`python:3.12.14-slim-trixie`) показывает версию, digest **индекса**
|
||||
(не манифеста одной платформы) даёт повторяемость и работает на arm64
|
||||
и amd64. Digest брать из `docker buildx imagetools inspect <тег>`,
|
||||
строка `Digest:` в начале вывода. Не `latest` и не `3.12-slim`. uv —
|
||||
`COPY --from=ghcr.io/astral-sh/uv:<версия>@sha256:... /uv /bin/uv`, а
|
||||
не незакреплённый `pip install uv`. Зависимости — только из lock
|
||||
(`--locked`): если `uv.lock` не совпадает с `pyproject.toml`, сборка
|
||||
падает. Директиву `# syntax=` не добавлять: это ещё один
|
||||
незакреплённый образ, а встроенный frontend BuildKit и так понимает
|
||||
`RUN --mount`.
|
||||
- Непривилегированный пользователь: системный `app` с UID/GID 10001 и
|
||||
`USER app` перед `CMD`. Код и `.venv` копируются от root и доступны
|
||||
пользователю только на чтение.
|
||||
- `CMD` в exec-форме: `["python", "-m", "src"]`. Тогда сервер — PID 1 и
|
||||
сам получает SIGTERM. Не `sh -c "... && ..."` и не `uv run`: это
|
||||
лишний процесс между docker и сервером.
|
||||
- `ENV APP__RUN_MODE=docker PYTHONUNBUFFERED=1
|
||||
PYTHONDONTWRITEBYTECODE=1`, `EXPOSE 8080`.
|
||||
- `HEALTHCHECK` на `/health/ready` через `python -c "import
|
||||
urllib.request; ..."` (curl в slim нет) с явными `--interval`,
|
||||
`--timeout`, `--start-period` и `--start-interval=1s`: без него первая
|
||||
проверка идёт только через `interval`, и контейнер становится
|
||||
`healthy` не раньше 10 с. Порт — `APP__PORT` из окружения, по
|
||||
умолчанию 8080. Healthcheck живёт только в образе: он нужен и без
|
||||
compose (README запускает образ голым `docker run`), а compose берёт
|
||||
его из образа и не дублирует.
|
||||
- В образ не попадают `.env`, `config.toml`, секреты, `tests/`,
|
||||
`student-tests/`, `contracts/`, `evidence/`, `.claude/`, `openspec/`,
|
||||
`.venv/`. Отличие от bp_proxies: там `config.toml` копируется в образ,
|
||||
здесь нельзя. Чистый clone его не содержит, и сборка упала бы, а
|
||||
`Dockerfile.example` (п. 6) запрещает класть конфиг и секреты в образ.
|
||||
Конфигурация приходит на старте: `config.toml` монтируется
|
||||
read-only в `/app/config.toml`, переменные — `environment` compose
|
||||
или `docker run --env-file .env`. Это согласовано с преподавателем
|
||||
2026-09-29 как выполнение README, п. 3 и `Dockerfile.example`, п. 6
|
||||
(AGENTS.md, «Согласования с преподавателем»). Что где лежит —
|
||||
`settings.md`.
|
||||
|
||||
## `.dockerignore`
|
||||
|
||||
Файл из skeleton дополнять, а не заменять: `config.toml`, `.claude`,
|
||||
`openspec`, `tests`, `student-tests`, `contracts`, `*.md`, `Makefile`.
|
||||
`.dockerignore` не заменяет явный `COPY` только нужного.
|
||||
|
||||
Паттерн без `**/` действует только в корне контекста: `__pycache__` из
|
||||
skeleton не исключает `src/**/__pycache__`, и `.pyc` хоста попадали в
|
||||
образ. Для вложенных путей — `**/__pycache__`, `**/*.py[cod]`,
|
||||
`**/.DS_Store`.
|
||||
|
||||
## Проверка сборки «из чистого clone»
|
||||
|
||||
Без коммита и временного каталога: контекст — ровно файлы будущего
|
||||
clone (отслеживаемые и новые неигнорируемые):
|
||||
|
||||
```sh
|
||||
git ls-files -z -co --exclude-standard | tar --null -T - -cf - | docker build -t mtusi-messenger:lab1 -
|
||||
```
|
||||
|
||||
`.env`, `config.toml` и `.venv` в него не попадают по `.gitignore`.
|
||||
Перед PR — ещё и настоящий `git clone`.
|
||||
|
||||
## docker-compose.yml
|
||||
|
||||
- Сервис `api`: `build: .`; порты `"127.0.0.1:${APP_OUT_PORT:-8080}:${APP__PORT:-8080}"`
|
||||
(снаружи / внутри, стенд учебный — только localhost); `environment`:
|
||||
`APP__RUN_MODE=docker`, `APP__PORT=${APP__PORT:-8080}` и мосты
|
||||
`SECTION__FIELD=${...}` (`settings.md`); healthcheck образа проверяет
|
||||
`APP__PORT`; `stop_grace_period: 10s`; `restart: unless-stopped`.
|
||||
Имена переменных в `.env` — `settings.md`, «Имена в `.env`».
|
||||
- `config.toml` — только длинной записью, иначе при отсутствии файла
|
||||
Docker молча создаст на хосте каталог `config.toml/`, и приложение
|
||||
упадёт на чтении настроек (проверено):
|
||||
|
||||
```yaml
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ./config.toml
|
||||
target: /app/config.toml
|
||||
read_only: true
|
||||
bind:
|
||||
create_host_path: false
|
||||
```
|
||||
|
||||
Без файла compose сразу падает с `bind source path does not exist`.
|
||||
Поэтому `make run_docker` зависит от `env_setup`: недостающие `.env`
|
||||
и `config.toml` создаются из шаблонов, существующие не трогаются.
|
||||
Голый `docker compose up` без файла по-прежнему падает. Голый
|
||||
`docker run` монтирует его так же строго — `--mount
|
||||
type=bind,src="$PWD/config.toml",dst=/app/config.toml,readonly`, а не
|
||||
`-v`. На лабе 1 файл необязателен: без него приложение стартует на
|
||||
дефолтах.
|
||||
- Смонтированный файл должен читаться непривилегированным пользователем
|
||||
контейнера. На Docker Desktop права хоста не мешают, на Linux нужен
|
||||
режим `644` или совпадающий uid.
|
||||
- Новая переменная контейнера — строка в `.env.example` и в
|
||||
`environment` сервиса.
|
||||
- С лабы 2: образы зависимостей с явным тегом (`postgres:17.N`, не
|
||||
`postgres:17`), свой healthcheck, `depends_on: condition:
|
||||
service_healthy`. Миграции — отдельный одноразовый сервис, API ждёт
|
||||
его `service_completed_successfully`. Данные — именованный volume или
|
||||
bind-mount в `.gitignore`. Скрипты restart и failover volumes не
|
||||
удаляют (`contracts/infrastructure.json`).
|
||||
- С лабы 3: реплики API за балансировщиком; внутренние порты реплик
|
||||
наружу не публиковать.
|
||||
- На лабе 1 compose необязателен: `docker build` и `docker run` из
|
||||
README должны работать без него.
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
paths:
|
||||
- "src/schemas/**"
|
||||
---
|
||||
|
||||
# DTO и enum-ы (`src/schemas/`)
|
||||
|
||||
`src/schemas/dataclasses/<domain>.py` — DTO между repo → service → api;
|
||||
`src/schemas/enums/<domain>.py` — `StrEnum` доменов. HTTP-модели
|
||||
(pydantic) лежат не здесь, а в `src/api/schemas/` (`api-layer.md`).
|
||||
|
||||
Создавать только те DTO, без которых слой не может отдать данные. Не
|
||||
плодить обёртки «на будущее».
|
||||
|
||||
| Назначение | Имя | Когда нужен |
|
||||
|---|---|---|
|
||||
| Вход на создание записи | `Create<Entity>DTO` | полей больше трёх-четырёх, иначе хватит именованных аргументов |
|
||||
| Полная запись | `<Entity>FullDTO` | сервису и API нужны все поля записи |
|
||||
| Выборка подмножества полей | `<Entity>InListDTO` | repo выбирает часть колонок (с лабы 2) |
|
||||
| Страница | `<Entity>PageDTO` | `items` и `next_cursor: str \| None` |
|
||||
|
||||
- Каждый класс — `@dataclass`, суффикс `DTO`. Записи, которые хранит
|
||||
`MemoryStore` (лаба 1), — `@dataclass(frozen=True, slots=True)`: repo
|
||||
отдаёт их наружу без копирования, изменить состояние в обход repo
|
||||
нельзя, а `slots` экономит память на миллионах записей. pydantic
|
||||
читает такие записи через `from_attributes`.
|
||||
- Обязательные поля первыми, поля со значением по умолчанию — последними;
|
||||
для `list` / `dict` — `field(default_factory=...)`. В frozen-DTO
|
||||
коллекции — `tuple` / `frozenset`.
|
||||
- Типы доменные: `UUID`, а не `str`; `datetime` (aware UTC), а не строки;
|
||||
`enums.*`; `X | None` для nullable.
|
||||
- Имена полей `<Entity>FullDTO` совпадают с колонками модели (с лабы 2),
|
||||
иначе `FullDTO(**row.to_dict())` сломается.
|
||||
- Каждый новый класс добавляется в `__init__.py` пакета (импорт и
|
||||
`__all__`) в алфавитном порядке.
|
||||
- Короткий docstring на русском, если назначение не очевидно из имени.
|
||||
- Enum-ы — `StrEnum`. С лабы 2 значение хранится в БД, поэтому
|
||||
переименование значения = миграция (`migrations.md`).
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
paths:
|
||||
- "src/infra/**"
|
||||
---
|
||||
|
||||
# Инфраструктура (`src/infra/`)
|
||||
|
||||
Всё, что не содержит бизнес-логики и может смениться от лабы к лабе:
|
||||
логгер, хранилище (лаба 1 — память процесса, с лабы 2 — PostgreSQL),
|
||||
клиенты Redis, S3, брокера, телеметрии. Бизнес-правил (уникальность,
|
||||
доступ, валидация) здесь нет: они в сервисах, атомарные операции — в
|
||||
repo.
|
||||
|
||||
- Объект создаётся один раз в lifespan `src/main.py`, кладётся в
|
||||
`app.state` и закрывается в shutdown lifespan. Соединения при импорте
|
||||
модуля не открываются; исключение — ленивая настройка логгера.
|
||||
- Сервисы получают объект через зависимость из `src/api/dependencies.py`
|
||||
и не импортируют модульный глобал.
|
||||
- `MemoryStore` (лаба 1, `memory.py`): dict-ы по id и индексы
|
||||
(`username` → id, пользователь → его чаты, чат → история в порядке
|
||||
`(created_at, id)`). Хранит frozen DTO. Меняют его только
|
||||
repo-функции.
|
||||
- На лабе 1 никаких файлов состояния, pickle, SQLite и внешних
|
||||
сервисов: рубрика требует, чтобы после рестарта процесса состояние
|
||||
исчезало.
|
||||
- `/health/ready` проверяет критичные зависимости через infra. На лабе 1
|
||||
это «lifespan завершил старт»; с лабы 2 — Postgres и, если он
|
||||
используется, Redis. Недоступность — 503. Какие зависимости считаются
|
||||
критичными, фиксируется в `REPORT.md`.
|
||||
- Клиенты внешних сервисов (с лабы 2): адреса и секреты из
|
||||
`settings` (`.claude/rules/settings.md`), таймаут на каждый вызов,
|
||||
ошибки переводятся в доменные исключения в сервисе. Логи — по
|
||||
`logging.md`, без секретов.
|
||||
@@ -0,0 +1,149 @@
|
||||
---
|
||||
paths:
|
||||
- "src/core/services/**"
|
||||
- "src/api/**"
|
||||
- "src/infra/**"
|
||||
- "src/main.py"
|
||||
---
|
||||
|
||||
# Логирование
|
||||
|
||||
Инфраструктура — `src/infra/logger.py`, по образцу bp_proxies
|
||||
(`src/core/services/logger.py` там). `get_logger()` возвращает
|
||||
`AbstractLogger` поверх structlog: JSON в stdout, уровень из
|
||||
`[app] log_level`.
|
||||
|
||||
Само попадает в запись, руками не добавлять: `request_id` из contextvar
|
||||
(ставит request-id middleware, то же значение, что в `X-Request-Id`),
|
||||
`user_id` из contextvar (ставит `get_current_user`), timestamp ISO/UTC,
|
||||
уровень, `filename` / `func_name` / `lineno`. Enum печатается как repr.
|
||||
|
||||
## Устройство `src/infra/logger.py`
|
||||
|
||||
Это перенос логгера bp_proxies
|
||||
(`~/PycharmProjects/bp_proxies/src/core/services/logger.py`, есть только
|
||||
на машине автора) с тремя отличиями, перечисленными ниже.
|
||||
|
||||
- `AbstractLogger` (ABC: `debug` / `info` / `warning` / `error` /
|
||||
`critical` / `bind`) и реализация `StructLogger` лежат в этом же
|
||||
модуле. `bind()` возвращает новый логгер с объединённым контекстом,
|
||||
исходный не меняется.
|
||||
- `get_logger()` инициализируется лениво: первый вызов выполняет
|
||||
`configure_logger()` и создаёт корневой `StructLogger`. Модули зовут
|
||||
его на уровне модуля, поэтому настройка применяется уже при импорте
|
||||
`src.main`, до `uvicorn.run`.
|
||||
- `structlog.configure_once`, процессоры по порядку:
|
||||
1. `stdlib.filter_by_level` — запись ниже уровня отбрасывается до
|
||||
остальных процессоров, включая поиск места вызова;
|
||||
2. `contextvars.merge_contextvars`, `stdlib.add_log_level`,
|
||||
`stdlib.ExtraAdder()`;
|
||||
3. `TimeStamper(fmt="iso", utc=True)`, `format_exc_info`;
|
||||
4. `CallsiteParameterAdder` (`FILENAME`, `FUNC_NAME`, `LINENO`) с
|
||||
`additional_ignores=["src.infra.logger"]`;
|
||||
5. контекстный процессор: `request_id` и `user_id` из contextvar-ов;
|
||||
6. перестановка ключей: `request_id`, `event`, `user_id` в начало;
|
||||
7. Enum → repr, UUID → строка (иначе JSONRenderer пишет `UUID('...')`),
|
||||
поэтому в kwargs можно передавать `UUID` как есть;
|
||||
8. `stdlib.ProcessorFormatter.wrap_for_formatter`.
|
||||
|
||||
`logger_factory=stdlib.LoggerFactory()`,
|
||||
`wrapper_class=stdlib.BoundLogger`, `cache_logger_on_first_use=True`.
|
||||
- `logging.config.dictConfig` с `disable_existing_loggers=False`:
|
||||
- форматтер — `ProcessorFormatter` с `remove_processors_meta` и
|
||||
`JSONRenderer()`; для записей чужих библиотек — `foreign_pre_chain`
|
||||
из `merge_contextvars`, `add_log_level`, `add_logger_name`,
|
||||
`TimeStamper`, `format_exc_info`, контекстного процессора и
|
||||
перестановки ключей;
|
||||
- handler — один `StreamHandler` в `ext://sys.stdout`;
|
||||
- root — `WARNING` с этим handler: предупреждения прочих библиотек тоже
|
||||
JSON (в bp_proxies root был без handlers);
|
||||
- `src` — уровень `[app] log_level`, этот handler,
|
||||
`propagate=False`;
|
||||
- `uvicorn` — `INFO`, этот handler, `propagate=False`;
|
||||
`uvicorn.error` — `INFO` без своего handler, пишет через `uvicorn`
|
||||
(свой handler дал бы дубли); `uvicorn.access` — выключен;
|
||||
- шумные библиотеки (с лабы 2 — `sqlalchemy.engine`, `httpx`,
|
||||
`httpcore`) — `WARNING`.
|
||||
|
||||
### Отличия от bp_proxies
|
||||
|
||||
1. **Место вызова — через `CallsiteParameterAdder`, а не
|
||||
`inspect.stack()`.** В bp_proxies каждый метод `StructLogger` зовёт
|
||||
`inspect.stack()`, а тот читает исходники всех кадров стека. Замер
|
||||
на глубине стека 40 кадров (как у ручки FastAPI под uvicorn):
|
||||
~470 мкс только на поиск места вызова против ~3,5 мкс на всю запись
|
||||
с `CallsiteParameterAdder`. На одном event loop 2–3 строки лога на
|
||||
запрос съели бы 1–1,5 мс CPU, то есть потолок RPS, который меряется
|
||||
в треке 1.
|
||||
2. **`request_id` в процессоре не генерируется.** В bp_proxies при
|
||||
пустом contextvar процессор создаёт случайный 8-символьный id и
|
||||
записывает его в contextvar. Здесь id запроса ставит только
|
||||
middleware, и он обязан совпасть с `X-Request-Id`. Вне запроса
|
||||
(старт, shutdown) поля нет. Фоновые задачи с лабы 5 ставят свой id
|
||||
сами, как job в bp_proxies.
|
||||
3. **uvicorn тоже пишет JSON.** В bp_proxies логгеры `uvicorn.*` не
|
||||
трогаются и пишут обычный текст. Здесь строки uvicorn об остановке
|
||||
(«Shutting down», «Waiting for application shutdown.», «Finished
|
||||
server process») доказывают на защите уровня 4, что SIGTERM
|
||||
отработал вовремя, поэтому идут в тот же JSON. Для этого
|
||||
`uvicorn.run(..., log_config=None, access_log=False)`: без
|
||||
`log_config=None` uvicorn при старте применит свой `LOGGING_CONFIG`
|
||||
поверх нашего. Access-лог пишет свой middleware (`api-layer.md`).
|
||||
|
||||
## Чего в логах быть не должно
|
||||
|
||||
Рубрика уровня 4: логи полезные, но **без содержимого сообщений**.
|
||||
|
||||
- Текст сообщений, `display_name`, `title` чата, тела запросов и ответов
|
||||
целиком. Вместо текста — идентификаторы и размеры
|
||||
(`text_length=len(text)`).
|
||||
- С лабы 2 — пароли, токены, заголовок `Authorization`,
|
||||
`Idempotency-Key` целиком; с лабы 4 — подписанные URL и ключи бакета.
|
||||
- Stack trace — только в лог, никогда в ответ.
|
||||
|
||||
## Где логировать
|
||||
|
||||
| Слой | Логи | Логгер модуля |
|
||||
|---|---|---|
|
||||
| `core/repos` | **никогда** | нет |
|
||||
| `core/services/<domain>.py` | в каждом методе с побочным эффектом | `module="<domain>_service"` |
|
||||
| `api/routers/v1/<domain>.py` | только заметные шаги, которых не видно из сервиса | `module="api_<domain>_router"` |
|
||||
| `api/middlewares` | access-лог: одна строка на запрос; health не логировать | `middleware="http"` |
|
||||
| `api/errors.py` | не логирует: 4xx — штатные ответы, а traceback непредвиденной ошибки пишет uvicorn (`uvicorn.error`, с `request_id` из contextvar) после повторного броска исключения Starlette | нет |
|
||||
| `infra/<client>.py` | подключение, закрытие, ошибки; с лабы 2 — запросы к внешним API (`debug`) | `module="<client>"` |
|
||||
| `main.py` | старт (host, port, режим), начало и конец shutdown | `module="startup"` |
|
||||
| чистые функции | не логируют, бросают доменные исключения | нет |
|
||||
|
||||
Строки старта и shutdown нужны на защите: по ним видно, что SIGTERM
|
||||
отработал за заявленный срок.
|
||||
|
||||
## Как логировать
|
||||
|
||||
Логгер модуля один, сразу после импортов:
|
||||
|
||||
```python
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
|
||||
logger: AbstractLogger = get_logger().bind(module="chat_service")
|
||||
```
|
||||
|
||||
Contextvar-ы `http_request_id` и `current_user_id` лежат в этом же
|
||||
модуле; ставят их только request-id middleware и `get_current_user`.
|
||||
|
||||
- В начале метода с побочным эффектом —
|
||||
`log = logger.bind(method="create_chat", chat_id=..., members_count=...)`.
|
||||
В `bind` идут идентификаторы, по которым лог будут искать.
|
||||
- Вложенный шаг большой операции принимает `log: AbstractLogger`
|
||||
параметром и пишет через него.
|
||||
- Сообщение — константная строка на английском: прошедшее время для
|
||||
результата («Created chat»), -ing для начала («Creating chat»).
|
||||
Переменные данные только в kwargs, не в f-string.
|
||||
- Исключения: `error=str(e)`; `exc_info=e` — только там, где нужен
|
||||
traceback непредвиденной ошибки.
|
||||
- Только `get_logger()`: без `print`, `traceback.print_exc()` и
|
||||
`logging.getLogger`.
|
||||
|
||||
Уровни: `debug` — промежуточные шаги; `info` — бизнес-событие (создан
|
||||
пользователь, чат, сообщение), старт и остановка; `warning` —
|
||||
обработано, но требует внимания; `error` — операция не выполнена,
|
||||
непредвиденное исключение. `critical` не используется.
|
||||
@@ -0,0 +1,37 @@
|
||||
---
|
||||
paths:
|
||||
- "migrations/**"
|
||||
- "src/infra/db/models/**"
|
||||
---
|
||||
|
||||
# Миграции alembic и модели (с лабы 2)
|
||||
|
||||
Основа — правила bp_proxies; отличия продиктованы контрактом.
|
||||
|
||||
- Модели — `src/infra/db/models/<domain>.py`. `Base` даёт `created_at`
|
||||
и `to_dict()`. Новая модель экспортируется в `models/__init__.py`,
|
||||
иначе autogenerate её не видит.
|
||||
- Первичный ключ — `UUID`, значение генерирует сервис (`uuid4()`):
|
||||
контракт отдаёт UUID. Автоинкремент не использовать.
|
||||
- Время — `DateTime(timezone=True)` (`timestamptz`), aware UTC: контракт
|
||||
требует `...Z`. В bp_proxies было naive UTC — здесь так нельзя.
|
||||
- Индексы под запросы контракта: `(chat_id, created_at, id)` для
|
||||
keyset-истории, уникальный `username`, участник → чаты.
|
||||
- Колонки типизированы `Mapped[...]`, внешние ключи — через
|
||||
`ForeignKey`.
|
||||
- Имя файла ревизии `YYYY_MM_DD_HHMM-<rev>_<slug>.py` (`file_template`
|
||||
в `alembic.ini`). Сообщение короткое, на английском, в прошедшем
|
||||
времени («added chats tables»). Пустая ревизия (`pass` в `upgrade`) —
|
||||
удалить.
|
||||
- Autogenerate не видит: новые значения enum, изменение
|
||||
`server_default`, частичные индексы (`postgresql_where`),
|
||||
переименования (сделает drop + create). Их правят руками.
|
||||
- `NOT NULL` на существующей таблице — с `server_default` или с
|
||||
backfill через `op.execute` перед `alter_column`.
|
||||
- Constraint-ы именованные, чтобы `downgrade` мог их снять. `downgrade`
|
||||
зеркалит `upgrade` в обратном порядке. Применённую ревизию не
|
||||
редактировать: новая ревизия поверх.
|
||||
- Миграции применяются до старта API: в compose — отдельный
|
||||
одноразовый сервис, API ждёт `service_completed_successfully`. Не
|
||||
`sh -c "alembic upgrade head && python -m src"` (сервер перестаёт быть
|
||||
PID 1) и не из lifespan: с лабы 3 реплик несколько.
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
paths:
|
||||
- "src/core/repos/**"
|
||||
---
|
||||
|
||||
# Слой repo (`src/core/repos/<domain>.py`)
|
||||
|
||||
Только доступ к данным. Ни бизнес-логики (проверок доступа, валидации),
|
||||
ни логов, ни внешних вызовов.
|
||||
|
||||
- Модульные `async def`, без классов. Первый параметр — хранилище: на
|
||||
лабе 1 `store: MemoryStore`, с лабы 2 `db_session: AsyncSession`.
|
||||
Остальные параметры вызывающий передаёт по имени.
|
||||
- **Одна атомарная операция на функцию.**
|
||||
- Лаба 1: внутри функции нет ни одного `await`. Всё выполняется в
|
||||
одном event loop, поэтому другой запрос её не прервёт. В этом и
|
||||
состоит защита от гонок, её объясняют на защите.
|
||||
- Лаба 2: максимум один `db_session.execute(...)`. Нужна вторая
|
||||
выборка — вторая функция, CTE, подзапрос или `.returning(...)`.
|
||||
- Уникальность проверяется в той же функции, что и вставка. На лабе 1
|
||||
проверка индекса и запись идут без `await` между ними; с лабы 2 —
|
||||
`pg_insert(...).on_conflict_do_nothing(...).returning(...)`. При
|
||||
конфликте функция возвращает `None`, исключение бросает сервис.
|
||||
- Наружу отдаются DTO (`.claude/rules/dto.md`), а не внутренние
|
||||
структуры хранилища. На лабе 1 хранилище держит frozen DTO, их можно
|
||||
отдавать как есть; списки — всегда новым `list`, не внутренним. С
|
||||
лабы 2 — `expunge` и `<Entity>FullDTO(**row.to_dict())` либо DTO из
|
||||
выбранных колонок, а не `select(Model)`.
|
||||
- Никаких `commit()` / `rollback()`: транзакцией управляет сервис.
|
||||
- Мутации возвращают осмысленный результат: созданный DTO, `bool`,
|
||||
`None` при конфликте.
|
||||
- Keyset-страница: параметры `after: tuple[datetime, UUID] | None` и
|
||||
`limit`, выборка `limit + 1` элементов, чтобы сервис узнал о следующей
|
||||
странице. На лабе 1 история чата — список в порядке `(created_at, id)`:
|
||||
вставка через `bisect.insort(..., key=...)`, позиция курсора — через
|
||||
`bisect`, без полного прохода.
|
||||
- Опциональные фильтры и лимиты — условное дополнение выборки
|
||||
(`if limit is not None: ...`).
|
||||
- Логов в репозиториях нет: ни `get_logger`, ни `print`.
|
||||
@@ -0,0 +1,94 @@
|
||||
---
|
||||
paths:
|
||||
- "src/main.py"
|
||||
- "src/__main__.py"
|
||||
- "src/config/settings.py"
|
||||
- "Makefile"
|
||||
- "docker-compose.yml"
|
||||
- ".env.example"
|
||||
- "config_example.toml"
|
||||
---
|
||||
|
||||
# Режимы запуска: console и docker
|
||||
|
||||
Режим задаёт `APP__RUN_MODE` (`settings.app.run_mode`, `RunModeEnum`),
|
||||
дефолт — `console`. В `.env` режим не хранится. Для docker его задают
|
||||
`ENV APP__RUN_MODE=docker` в Dockerfile (чтобы голый `docker run` из
|
||||
README слушал `0.0.0.0`) и литерал в `environment` compose; для консоли —
|
||||
цели Makefile.
|
||||
|
||||
| | console | docker |
|
||||
|---|---|---|
|
||||
| Процесс | `uv run python -m src` на хосте | `python -m src` — PID 1 контейнера |
|
||||
| uvicorn | `127.0.0.1`, `reload=True` по `src/` | `0.0.0.0`, без reload |
|
||||
| Порт | `settings.app.port`: `APP__PORT` из `.env`, без него — 8080 | `APP__PORT` из `.env` внутри (на нём же healthcheck), `APP_OUT_PORT` снаружи — одинаково в compose и `run_no_compose` |
|
||||
| Лаба 1 | память процесса; reload = пустое состояние | память процесса; рестарт контейнера = пустое состояние |
|
||||
| С лабы 2 | Postgres / Redis в compose, снаружи `localhost:<*_OUT_PORT>`; миграции — `make upgrade` | зависимости по имени сервиса; миграции — отдельный сервис до старта API (`migrations.md`) |
|
||||
|
||||
## Точка входа
|
||||
|
||||
`python -m src` → `src/__main__.py` → `src.main:main()` →
|
||||
`uvicorn.run("src.main:app", host=..., port=..., reload=...,
|
||||
timeout_graceful_shutdown=..., log_config=None, access_log=False)`.
|
||||
Хост выбирается по режиму, как в bp_proxies. `log_config=None` нужен,
|
||||
чтобы uvicorn не перетёр JSON-логирование (`logging.md`).
|
||||
|
||||
- Worker всегда один. Состояние лабы 1 живёт в памяти процесса, и второй
|
||||
worker получил бы второе независимое состояние (это вопрос защиты).
|
||||
Масштабирование — только в лабе 3, отдельными контейнерами за
|
||||
балансировщиком.
|
||||
- SIGTERM: uvicorn перестаёт принимать новые соединения и ждёт текущие
|
||||
запросы до `timeout_graceful_shutdown` (настройка
|
||||
`[app] graceful_shutdown_seconds`, не больше 8 с). Docker шлёт SIGKILL
|
||||
через 10 с, в compose — `stop_grace_period`. Shutdown в lifespan
|
||||
только логирует и закрывает клиенты, долгих операций в нём нет.
|
||||
Рубрика уровня 4 требует завершения не дольше 10 с.
|
||||
|
||||
## Makefile
|
||||
|
||||
- Цели skeleton `help`, `check`, `validate`, `test`, `load` не менять:
|
||||
в следующей лабе `Makefile` придёт новый, и свои цели в него
|
||||
переносятся слиянием (AGENTS.md, «Переход в следующую лабу»).
|
||||
- Свои цели — отдельными секциями ниже целей skeleton, в стиле
|
||||
bp_proxies: переменные наверху (`DC=docker compose`), заголовки
|
||||
`# -------------------------`, свой `.PHONY` у каждой цели, имена в
|
||||
snake_case. Apple Container не делать.
|
||||
- Набор для лабы 1:
|
||||
- `run_dev` (`APP__RUN_MODE=console uv run python -m src`);
|
||||
- `run_no_compose: env_setup` — команды README: `docker build`, затем
|
||||
`docker run --rm -p 127.0.0.1:$(APP_OUT_PORT):$(APP__PORT)
|
||||
--env-file .env ...` на переднем плане, без `config.toml`. Порты
|
||||
из `.env` (`-include .env` в секции `Docker targets`, дефолт 8080),
|
||||
с шаблонным `.env` команда совпадает с README. Остановка — Ctrl+C
|
||||
или `docker stop`;
|
||||
- `run_docker: env_setup` (недостающие `.env` и `config.toml` из
|
||||
шаблонов, затем `DOCKER_BUILDKIT=1 $(DC) build` и `$(DC) up -d`),
|
||||
к нему `stop`, `down`, `logs`
|
||||
(`$(DC) logs -f --no-log-prefix api`: без префикса `api-1 |`
|
||||
каждая строка — JSON);
|
||||
- `lint` (`ruff format .` + `ruff check --fix .`, дважды),
|
||||
`env_setup` (копирует шаблоны `.env` и `config.toml`),
|
||||
`student_test`.
|
||||
|
||||
`run_no_compose` и `run_docker` — два способа запуска контейнера,
|
||||
оба описываются в `REPORT.md`.
|
||||
- С лабы 2: `start_db` / `stop_db`, `start_redis` / `stop_redis`,
|
||||
`revision` (интерактивный `read -p`), `upgrade`. Volume передаётся
|
||||
переменной (`POSTGRES_VOLUME=$(DOCKER_POSTGRES_VOLUME)`), перед
|
||||
миграциями поднимается БД.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- `make test` падает с 404 на `/health/live` вместо ошибки соединения:
|
||||
на 8080 отвечает чужой сервис. Найти его — `lsof -nP -iTCP:8080
|
||||
-sTCP:LISTEN` и `docker ps`; для своего стенда взять другой
|
||||
`APP_OUT_PORT` и `make test BASE_URL=http://localhost:<порт>`.
|
||||
- Разовая подмена внешнего порта для целей Makefile — только
|
||||
аргументом: `make run_docker APP_OUT_PORT=8090`. Внутренний
|
||||
`APP__PORT` — только в `.env`: в `run_no_compose` приложение берёт
|
||||
его из `--env-file .env`, аргумент make сдвинул бы лишь `-p`. Префикс
|
||||
`APP_OUT_PORT=8090 make ...` не сработает: `-include .env` перекроет
|
||||
его, и в recipe (в том числе в `docker compose`) уйдёт значение из
|
||||
`.env`.
|
||||
- Поменял `config.toml` и не видишь эффекта: значение перекрыто
|
||||
окружением или `.env` (приоритет env > .env > toml).
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
paths:
|
||||
- "src/core/services/**"
|
||||
---
|
||||
|
||||
# Слой service (`src/core/services/<domain>.py`)
|
||||
|
||||
Бизнес-логика, проверки доступа, серверные значения (id, время),
|
||||
транзакции (с лабы 2), вызовы внешних клиентов, логи.
|
||||
|
||||
- Класс `<Domain>Service`. `__init__` принимает хранилище и хранит его
|
||||
в `self`: на лабе 1 — `store: MemoryStore`, с лабы 2 —
|
||||
`db_session: AsyncSession`. Методы принимают keyword-only параметры
|
||||
(`*,`) и вызываются только именованными аргументами.
|
||||
- Repo: `from src.core.repos import chat as chat_repo`. Вызов —
|
||||
`store=self.store` (`db_session=self.db_session`) и именованные
|
||||
аргументы.
|
||||
- Проверка доступа — здесь. Не участник получает то же исключение, что
|
||||
«не найден» (`ChatNotFound`): API отдаст 404 и не раскроет, что чат
|
||||
существует.
|
||||
- Ошибки — доменные исключения из `src/core/exceptions` (новое — в
|
||||
модуль домена и реэкспорт в `__init__.py`). Не `ValueError` и не
|
||||
`HTTPException`: статус и `code` назначает `src/api/errors.py`.
|
||||
- Серверные значения назначает сервис: `id = uuid4()`,
|
||||
`created_at = utcnow()` из `src/utils/utc.py`.
|
||||
- Атомарность на лабе 1: одна мутация — один вызов repo. Составную
|
||||
проверку с записью (уникальность `username`) делает одна
|
||||
repo-функция. Схема «сервис проверил, потом вставил» с `await` между
|
||||
шагами не годится (`repo-layer.md`).
|
||||
- С лабы 2 коммитит только сервис: `await self.db_session.commit()`
|
||||
после успешной мутации, repo не коммитит. Другой сервис создаётся с
|
||||
тем же `db_session`, чтобы остаться в одной транзакции.
|
||||
- Курсор кодирует и разбирает сервис через `src/utils/cursor.py`:
|
||||
проверяет область (этот чат или этот пользователь) и возвращает
|
||||
`<Entity>PageDTO` с готовым `next_cursor`. Неверный курсор — доменное
|
||||
исключение (→ 400).
|
||||
- Чистые вычисления — модульные функции над классом, без обращения к
|
||||
хранилищу.
|
||||
- Read-only методы, которые лишь делегируют в repo, не логируют.
|
||||
Остальное — по `.claude/rules/logging.md`.
|
||||
- Константы (лимиты, размер страницы) — `src/utils/constants.py`.
|
||||
@@ -0,0 +1,133 @@
|
||||
---
|
||||
paths:
|
||||
- "src/config/**"
|
||||
- ".env.example"
|
||||
- "config_example.toml"
|
||||
---
|
||||
|
||||
# Настройки: `.env`, `config.toml`, `src/config/settings.py`
|
||||
|
||||
Схема из bp_proxies (`src/data/settings.py` там). Что делают режимы
|
||||
console и docker — `.claude/rules/run-modes.md`. Здесь — откуда берутся
|
||||
значения и куда класть новое.
|
||||
|
||||
## Источники `Settings`
|
||||
|
||||
- `src/config/settings.py`: `Settings(BaseSettings)` из секций-`BaseModel`
|
||||
(`App`; с лабы 2 — `Database`, `Redis`...). Экземпляр один —
|
||||
`settings` на уровне модуля. Импорт везде `from src.config import
|
||||
settings`. Второй `Settings()` не создавать, поля в рантайме не менять.
|
||||
- Приоритет (`settings_customise_sources`): окружение процесса → `.env`
|
||||
→ `config.toml` → дефолты. Отсутствующий файл пропускается. Без
|
||||
`.env` и `config.toml` приложение обязано подняться на дефолтах: так
|
||||
работают `docker run` из README и чистый clone.
|
||||
- Все поля живут в секциях, откуда бы ни пришло значение: секцию задаёт
|
||||
класс `Settings`, а не файл. Вложенные поля в env — через `__`,
|
||||
регистр не важен: `DATABASE__PASSWORD` попадает в
|
||||
`settings.database.password` так же, как `[database] password` из
|
||||
TOML. Переменную без префикса секции (`APP_PORT`, `POSTGRES_PASSWORD`)
|
||||
приложение не видит: она для compose.
|
||||
- Имена переменных, которые задаёт контракт (`SESSION_TTL_SECONDS` с
|
||||
лабы 2), тоже не выносятся из секций. Поле остаётся в секции
|
||||
(`[auth] session_ttl_seconds`), а контрактное имя приходит мостом
|
||||
(раздел «Мосты» ниже).
|
||||
- `extra="ignore"`: опечатка в ключе молча оставит дефолт. После правки
|
||||
проверить конкретное поле: `uv run python -c "from src.config import
|
||||
settings; print(settings.app.port)"`. Полный дамп настроек не печатать
|
||||
(с лабы 2 в нём пароли).
|
||||
- Подмена через окружение ставится до первого импорта `src`: потом
|
||||
`settings` уже прочитан.
|
||||
|
||||
## Что где хранится
|
||||
|
||||
Критерий — кто читает значение, а не секретное ли оно.
|
||||
|
||||
| Где | Что | В git |
|
||||
|---|---|---|
|
||||
| `config.toml` | всё, что читает **только приложение**, по секциям: `log_level`, лимиты трека 5, TTL, адреса зависимостей для console, секреты, которые нужны одному приложению | нет; шаблон `config_example.toml` |
|
||||
| `.env` | всё, что читает **compose** (и Makefile) и контейнеры зависимостей: порты `APP__PORT` / `APP_OUT_PORT`, `POSTGRES_*`, пароли Redis / MinIO / брокера; мосты `SECTION__FIELD=${...}` для приложения | нет; шаблон `.env.example` |
|
||||
| окружение процесса | режим `APP__RUN_MODE` и разовые подмены | — |
|
||||
| `src/utils/constants.py` | лимиты контракта (3–32, 100, 4000, `limit` 1–100 / 50), пути: одинаковы на всех установках | да |
|
||||
|
||||
Схему согласовали с преподавателем 2026-09-29 (AGENTS.md, «Согласования
|
||||
с преподавателем»). Секреты в `config.toml` допустимы. Запрет
|
||||
`Dockerfile.example` касается запекания в образ (`COPY`), а
|
||||
`config.toml` в образ не копируется, его монтируют на старте
|
||||
(`docker.md`). Но почти все секреты курса — пароли
|
||||
Postgres, Redis, MinIO, брокера — нужны ещё и контейнеру зависимости,
|
||||
а его настраивает только compose из `.env`. Поэтому такой секрет живёт
|
||||
в `.env` и попадает в приложение мостом. Если продублировать его в
|
||||
`config.toml`, как `postgres_password` в bp_proxies, получатся два
|
||||
источника, которые рано или поздно разойдутся.
|
||||
|
||||
## Имена в `.env`: параметр приложения — в формате настроек
|
||||
|
||||
Если переменная касается самого приложения, в `.env` она пишется в
|
||||
формате настроек (`SECTION__FIELD`), даже когда её читают ещё compose и
|
||||
Makefile. Пример — внутренний порт `APP__PORT`: на нём слушает
|
||||
приложение, его публикуют compose и `make run_no_compose`, на нём
|
||||
работает healthcheck. Compose читает `${APP__PORT}` напрямую и передаёт
|
||||
в `environment` под тем же именем, а голый `docker run --env-file .env`
|
||||
отдаёт его приложению как есть.
|
||||
|
||||
Имя без секции — только у того, что приложение не читает:
|
||||
`APP_OUT_PORT` (порт на хосте), `POSTGRES_*` и другие переменные
|
||||
контейнеров зависимостей. Если такое значение нужно ещё и приложению,
|
||||
оно приходит мостом (ниже).
|
||||
|
||||
Поле, которое задаётся в `.env`, в `config_example.toml` не
|
||||
дублируется: по приоритету значение из `.env` перекрыло бы toml, и
|
||||
строка там ни на что не влияла бы. Поэтому в `[app]` нет `port`.
|
||||
|
||||
`.env` читает и Makefile (`-include .env`), поэтому комментарии в нём
|
||||
пишутся только отдельными строками. make, в отличие от compose,
|
||||
оставляет пробел перед `# комментарий` в конце строки частью значения.
|
||||
|
||||
## Мосты: значение из `.env` в секцию приложения
|
||||
|
||||
Мост нужен, когда имя переменной навязано контейнером зависимости
|
||||
(`POSTGRES_PASSWORD` для образа postgres), а приложению то же значение
|
||||
нужно в своей секции. Мост — строка, которая отдаёт значение переменной
|
||||
compose полю секции:
|
||||
|
||||
- в `.env` — `DATABASE__PASSWORD=${POSTGRES_PASSWORD}`: pydantic-settings
|
||||
раскрывает `${VAR}` при чтении `.env` (проверено на 2.15), так
|
||||
значение получает приложение в console-режиме;
|
||||
- в `environment` сервиса compose — та же строка, так значение получает
|
||||
контейнер. Сам `.env` в контейнер не передаётся.
|
||||
|
||||
`docker run --env-file .env` раскрывать `${...}` не умеет и передаст
|
||||
строку буквально. На лабе 1 мостов нет, а с лабы 2 стенд запускается
|
||||
только через compose.
|
||||
|
||||
`.env.example` из skeleton (`APP_HOST`, `APP_PORT`, `APP_ENV`) — это
|
||||
«логические» имена. После перехода на эту схему соответствие
|
||||
переменных реальной конфигурации описать в `REPORT.md` (раздел
|
||||
«Архитектура и решения»).
|
||||
|
||||
В настройки идёт только то, что отличается между установками, либо
|
||||
секрет. Остальное — константа.
|
||||
|
||||
## Новое поле или секция
|
||||
|
||||
1. Поле с типом и безопасным дефолтом: лаба 1 поднимается без файлов.
|
||||
Секрет — `""` и проверка при старте там, где он нужен. Единицы —
|
||||
коротким комментарием (`# секунды`).
|
||||
2. Новая секция — класс `<Name>(BaseModel)` и поле
|
||||
`<name>: <Name> = <Name>()` в `Settings`. Имя поля одновременно имя
|
||||
секции TOML и префикс env.
|
||||
3. Строка в `config_example.toml` с плейсхолдером и в рабочем
|
||||
`config.toml`. Значения из `config.toml` не печатать в ответ и лог.
|
||||
4. Значение нужно и compose, и приложению:
|
||||
- параметр самого приложения (порт) — переменная `SECTION__FIELD` в
|
||||
`.env.example` с комментарием и в `environment` сервиса compose
|
||||
(`docker.md`);
|
||||
- значение с именем, которое навязывает контейнер зависимости
|
||||
(пароль Postgres), — переменная и мост в `.env.example`, мост в
|
||||
`environment` сервиса compose.
|
||||
|
||||
В обоих случаях в `config_example.toml` поле не дублировать.
|
||||
5. Строка подключения — `@property` секции (`Database.url`): вызывающий
|
||||
код URL сам не собирает.
|
||||
6. Когда появятся `config_example.toml` и `config.toml`, добавить
|
||||
`config.toml` в `.gitignore` и `.dockerignore`.
|
||||
@@ -0,0 +1,60 @@
|
||||
---
|
||||
paths:
|
||||
- "student-tests/**"
|
||||
---
|
||||
|
||||
# Собственные тесты (`student-tests/`)
|
||||
|
||||
В bp_proxies тесты запрещены. Здесь они обязательны для уровня 4
|
||||
(`README.md`), и каждый должен запускаться одной командой:
|
||||
|
||||
- неверный JSON, чужой чат, пустое сообщение, дубликат `username`, обход
|
||||
нескольких страниц истории;
|
||||
- гонки: 10 клиентов параллельно отправляют 100 сообщений, после чего
|
||||
история содержит ровно 100 уникальных. Команду и результат сохранить.
|
||||
|
||||
## Как писать
|
||||
|
||||
- Black-box по HTTP против запущенного сервера (`BASE_URL`, по умолчанию
|
||||
`http://localhost:8080`), как публичный smoke. Тест не импортирует
|
||||
`src` и не поднимает приложение сам: те же тесты проверяют и
|
||||
контейнер, и следующие лабы.
|
||||
- pytest + httpx в dev-группе uv, запуск — `make student_test`.
|
||||
- Каждый тест создаёт своих пользователей с уникальным `username`
|
||||
(uuid-суффикс): состояние сервера общее, а удалять данные API не умеет.
|
||||
- Проверять не только статус, но и форму: `{"error": {...}}` с
|
||||
`code`, `request_id` совпадает с `X-Request-Id`, у успешных ответов
|
||||
нет лишних полей. Семантика — `.claude/rules/api-contract.md`.
|
||||
- Тест гонок — реальная параллельность, а не цикл: потоки за
|
||||
`threading.Barrier`, у каждого свой `Api` (своё соединение). Тест
|
||||
требует, чтобы одновременно в полёте было ≥ 2 запросов, иначе гонка
|
||||
не доказана. Проверяются количество и уникальность `id`, а также
|
||||
отсутствие потерь при обходе всех страниц.
|
||||
- `tests/` — публичные проверки skeleton: не править, не ослаблять,
|
||||
свои тесты туда не класть.
|
||||
- Вывод прогона (команда, дата, commit, результат) — в `evidence/` и
|
||||
строкой в таблицу доказательств `REPORT.md`.
|
||||
|
||||
## Как устроен набор
|
||||
|
||||
- **Идентификация — только `Actor.headers()`** (`api_client.py`).
|
||||
Тесты передают `actor=`, заголовок руками собирает только
|
||||
`test_identification.py`: на лабе 2 меняется одна функция и этот
|
||||
модуль. Пользователь, которого нет на сервере, —
|
||||
`Actor.unregistered()`.
|
||||
- **Форма ответа — через `contract.py`**, без ручного сравнения ключей:
|
||||
`assert_ok(resp, status, "<Schema>")` для успеха, `assert_error(resp,
|
||||
status)` для ошибки (`code` берётся из статуса). Хелперы `Api`
|
||||
(`register`, `create_chat`, `send_message`, обход страниц) уже
|
||||
проверяют схемы.
|
||||
- **Каждый тест сценария спека помечен** `@pytest.mark.spec("<capability>",
|
||||
"<Сценарий>")`, имя — дословно из `#### Scenario:`. Новый сценарий в
|
||||
основном спеке без теста роняет `test_coverage.py`. Если его нельзя
|
||||
проверить по HTTP, добавить запись в `EXCLUDED` (`spec_coverage.py`)
|
||||
с причиной и способом проверки.
|
||||
- Модуль сверки называется `spec_coverage.py`, а не `coverage.py`:
|
||||
каталог набора стоит в `pythonpath`, и `coverage.py` затенил бы
|
||||
пакет `coverage` (pytest-cov, coverage-runner IDE).
|
||||
- Новые пользователи и чаты — фикстуры `alice`, `bob`, `eve`, `chat` из
|
||||
`conftest.py`: у каждого теста свои. `eve` не состоит ни в одном чате
|
||||
фикстур.
|
||||
@@ -0,0 +1,173 @@
|
||||
---
|
||||
name: run-mtusi-messenger
|
||||
description: Запустить, остановить, прогнать и подёргать API мессенджера MTUSI (FastAPI, in-memory, лаба 1) — на хосте или в Docker. Use when asked to run / start / stop the server or the container, run the smoke test, `make test` or `make student_test`, check that an API change works on a live server, send a request to an endpoint, reproduce a bug over HTTP, check the container, or call services directly without HTTP.
|
||||
---
|
||||
|
||||
REST API мессенджера (пользователи, чаты, сообщения) — сервер на
|
||||
FastAPI/uvicorn, состояние в памяти процесса. Агент управляет им через
|
||||
`.claude/skills/run-mtusi-messenger/driver.py`: он поднимает свой
|
||||
экземпляр в фоне, гоняет сценарий по HTTP, публичный smoke и
|
||||
собственные тесты, шлёт одиночные запросы и останавливает сервер.
|
||||
Против контейнера (`make run_docker`) работают те же команды драйвера,
|
||||
кроме `start`/`stop`. Только стандартная библиотека Python.
|
||||
|
||||
Все пути — от корня репозитория. Проверено на macOS (arm64), uv 0.12,
|
||||
Python 3.12 из `.python-version`, Docker Desktop 29.8.
|
||||
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
uv sync --all-extras # venv с ruff и dev-группой (openapi-spec-validator)
|
||||
make env_setup # .env и config.toml из шаблонов, существующие не трогает
|
||||
```
|
||||
|
||||
Без `.env` и `config.toml` сервер тоже поднимается — на дефолтах
|
||||
(порт 8080, `INFO`).
|
||||
|
||||
## Run (agent path)
|
||||
|
||||
```bash
|
||||
D=.claude/skills/run-mtusi-messenger/driver.py
|
||||
python3 $D all # start → flow → tests/smoke.py → student-tests → stop; код 0 = всё прошло
|
||||
```
|
||||
|
||||
По шагам, когда между ними нужно что-то сделать (поправить код,
|
||||
посмотреть лог, послать свой запрос):
|
||||
|
||||
```bash
|
||||
python3 $D start # фон, ждёт /health/ready до 30 с
|
||||
python3 $D status # listeners: [pid reloader, pid worker], ready: True
|
||||
python3 $D flow # ~35 проверок: регистрация, 409, /me, 401, чат, 5 сообщений,
|
||||
# пагинация limit=2 по курсору, чужой → 404, 400-е, X-Request-Id
|
||||
python3 $D req POST /api/v1/users --data '{"username":"zoe_demo","display_name":"Зоя"}'
|
||||
python3 $D req GET /api/v1/users/me --user <uuid из ответа выше>
|
||||
python3 $D smoke # публичный tests/smoke.py против этого порта
|
||||
python3 $D student # make student_test BASE_URL=http://localhost:<port> — 79 тестов, <1 с
|
||||
python3 $D stop
|
||||
```
|
||||
|
||||
| команда | что делает |
|
||||
|---|---|
|
||||
| `start` | `APP__RUN_MODE=console APP__PORT=<port> uv run python -m src` в своей группе процессов |
|
||||
| `status` | кто слушает порт, отвечает ли `/health/ready`; код 1, если никого |
|
||||
| `flow` | сквозной сценарий; `[FAIL]` в строке и код 1 при провале; в конце печатает id alice/bob/eve/chat |
|
||||
| `req METHOD PATH [--user UUID] [--data JSON]` | один запрос: статус, `x-request-id`, тело; код 2 при статусе ≥ 400 |
|
||||
| `smoke` | `tests/smoke.py --base-url http://localhost:<port>` |
|
||||
| `student` | `make student_test BASE_URL=http://localhost:<port>` (pytest по `student-tests/`); код 1, если каталога нет |
|
||||
| `stop` | SIGTERM всей группе; ждёт, пока порт освободится. Чужой сервер и контейнер не трогает |
|
||||
| `all` | всё подряд (`student` — если есть `student-tests/`), `stop` в `finally` |
|
||||
|
||||
- Порт по умолчанию **18080**, другой — `--port N` **перед** командой:
|
||||
`python3 $D --port 18081 start`.
|
||||
- Лог сервера (JSON, одна строка на запрос) — `/tmp/mtusi-api-<port>.log`,
|
||||
pid группы — `/tmp/mtusi-api-<port>.pid`.
|
||||
- `make test BASE_URL=http://localhost:18080` работает так же, как
|
||||
`driver.py smoke`.
|
||||
|
||||
## Run: контейнер (compose)
|
||||
|
||||
Образ `mtusi-messenger:lab1`, compose-сервис `api`. Внешний порт —
|
||||
аргументом make, чтобы не столкнуться с 8080:
|
||||
|
||||
```bash
|
||||
make run_docker APP_OUT_PORT=18090 # build + up -d; healthy за ~2 с
|
||||
docker compose ps --format '{{.Name}} {{.Ports}} {{.Status}}'
|
||||
python3 $D --port 18090 flow # те же проверки против контейнера
|
||||
python3 $D --port 18090 smoke
|
||||
docker compose logs --no-log-prefix api | tail -5 # JSON-строки, без -f
|
||||
docker compose restart api # рестарт = пустое состояние: старые X-User-Id → 401
|
||||
make down # остановить и удалить, ~0,5 с
|
||||
```
|
||||
|
||||
`make run_docker` сам создаёт недостающие `.env` и `config.toml`
|
||||
(`env_setup`) и монтирует `config.toml` только для чтения. Готовность —
|
||||
`docker inspect -f '{{.State.Health.Status}}' $(docker compose ps -q api)`
|
||||
→ `healthy`.
|
||||
|
||||
## Direct invocation (без HTTP)
|
||||
|
||||
Для правок в `src/core/` сервисы вызываются поверх `MemoryStore`, сервер
|
||||
не нужен. `APP__LOG_LEVEL=WARNING` убирает JSON-логи сервисов из вывода:
|
||||
|
||||
```bash
|
||||
APP__LOG_LEVEL=WARNING uv run python - <<'EOF'
|
||||
import asyncio
|
||||
from src.infra.memory import MemoryStore
|
||||
from src.core.services import UserService
|
||||
|
||||
async def main():
|
||||
users = UserService(store=MemoryStore())
|
||||
user = await users.register(username="alice", display_name="Alice")
|
||||
print(await users.identify(raw_user_id=str(user.id)))
|
||||
|
||||
asyncio.run(main())
|
||||
EOF
|
||||
```
|
||||
|
||||
`ChatService` и `MessageService` создаются так же (`store=...`), все
|
||||
методы keyword-only. Ошибки — доменные исключения из `src.core.exceptions`
|
||||
(базовый `DomainError`), не HTTP-коды: `identify(raw_user_id="not-a-uuid")`
|
||||
бросает `Unidentified`.
|
||||
|
||||
## Run (human path)
|
||||
|
||||
```bash
|
||||
make run_dev # 127.0.0.1:8080, reload по src/; Ctrl-C
|
||||
```
|
||||
|
||||
Блокирует терминал — агенту не подходит, используй `driver.py start`.
|
||||
|
||||
## Test
|
||||
|
||||
```bash
|
||||
make check # офлайн-структура skeleton
|
||||
python3 $D all # живой сервер + flow + smoke + student-tests
|
||||
make lint # ruff; затрагивает и driver.py
|
||||
```
|
||||
|
||||
Ожидаемо: `PASS: offline skeleton structure...`, `FAILED: none`,
|
||||
`PASS: lab1 public API scenario...`, `79 passed`, `All checks passed!`.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **На 8080 обычно уже работает `make run_dev` пользователя.** Поэтому
|
||||
драйвер по умолчанию на 18080. `driver.py --port 8080 stop` чужой
|
||||
сервер не убьёт (нет pid-файла → `left running`, код 1) — и не надо:
|
||||
в его памяти данные пользователя.
|
||||
- **Правка любого файла в `src/` (хватает `touch`) перезапускает worker
|
||||
и стирает всё состояние** — в логе `WatchFiles detected changes ...
|
||||
Reloading...`. Задевает и `make run_dev` на 8080. Старые `X-User-Id`
|
||||
после этого дают 401. После правки кода: `flow` заново, а не `req` со
|
||||
старыми id.
|
||||
- **`lsof` на порт показывает два PID** — reloader и worker делят один
|
||||
сокет. Убивать по `lsof -t | xargs kill` бессмысленно: reloader
|
||||
поднимет worker снова. Драйвер шлёт SIGTERM группе процессов; SIGTERM
|
||||
на обёртку `uv run` тоже гасит всё дерево.
|
||||
- **`uv sync` без `--all-extras` удалит ruff из `.venv`** (`Would
|
||||
uninstall ruff`): ruff в extra `dev`, а `make lint` и PyCharm им
|
||||
пользуются.
|
||||
- **`make lint` форматирует и `.claude/skills/`** — ruff в
|
||||
`pyproject.toml` исключает только `tests` и `scripts`. Драйвер написан
|
||||
под 79 колонок и COM812; при правке проверять
|
||||
`ruff format --check .claude/skills/run-mtusi-messenger/driver.py`.
|
||||
- **`.env` задаёт `APP__PORT=8080`, но драйвер его перекрывает**:
|
||||
`start` передаёт `APP__PORT=<port>` в окружении, а окружение важнее
|
||||
`.env`. `APP_OUT_PORT` приложение не читает — это порт публикации
|
||||
контейнера.
|
||||
- **`driver.py stop` контейнер не останавливает** (`not ours (no pid
|
||||
file)`, код 1) — это правильно, гасить его `make down`. `status` для
|
||||
контейнера показывает один PID — процесс Docker Desktop, а не uvicorn.
|
||||
- **`make logs` висит** (`logs -f`) — агенту нужен
|
||||
`docker compose logs --no-log-prefix api` без `-f`.
|
||||
- **`req` без `--user` на защищённом пути даёт 401 `unauthorized`** — это
|
||||
не сломанный сервер, а контракт: идентификация раньше доступа.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- **`port 8080 is not ours (no pid file); left running`** — `stop` на
|
||||
порту, который поднимал не драйвер. Свой экземпляр гасить `stop` на его
|
||||
порту; чужой не трогать. Чей он — `lsof -nP -iTCP:8080 -sTCP:LISTEN`,
|
||||
затем `ps -o pid,ppid,etime,command -p <pid>`.
|
||||
- **`req GET /api/v1/users/me --user <id>` вдруг даёт 401, хотя минуту
|
||||
назад было 200** — сервер перезагрузился после правки в `src/` и
|
||||
потерял пользователей (см. Gotchas).
|
||||
@@ -0,0 +1,355 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Драйвер API мессенджера для агента: запуск, сценарий, запросы, остановка.
|
||||
|
||||
Только стандартная библиотека. Запускать из корня репозитория:
|
||||
|
||||
python3 .claude/skills/run-mtusi-messenger/driver.py [--port N] <cmd>
|
||||
|
||||
Команды:
|
||||
start поднять `python -m src` в фоне (console, reload) и дождаться
|
||||
/health/ready; лог и pid — /tmp/mtusi-api-<port>.{log,pid}
|
||||
status кто слушает порт и что отвечает /health/ready
|
||||
flow сквозной сценарий по HTTP с проверками; код выхода 1 при провале
|
||||
req один запрос: req METHOD PATH [--user UUID] [--data JSON]
|
||||
smoke публичный tests/smoke.py против этого порта
|
||||
student собственные тесты student-tests/ (make student_test) против
|
||||
этого порта
|
||||
stop остановить свой экземпляр на порту
|
||||
all start → flow → smoke → student (если есть student-tests/) → stop
|
||||
|
||||
Порт по умолчанию 18080, а не 8080: на 8080 обычно висит `make run_dev`
|
||||
пользователя, и его состояние в памяти трогать не надо. flow, req, smoke
|
||||
и student работают с любым сервером на порту, в том числе с контейнером
|
||||
(`make run_docker APP_OUT_PORT=<port>`).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import contextlib
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[3]
|
||||
DEFAULT_PORT = 18080
|
||||
USERS = "/api/v1/users"
|
||||
CHATS = "/api/v1/chats"
|
||||
|
||||
|
||||
def paths(port: int) -> tuple[Path, Path]:
|
||||
return (
|
||||
Path(f"/tmp/mtusi-api-{port}.log"),
|
||||
Path(f"/tmp/mtusi-api-{port}.pid"),
|
||||
)
|
||||
|
||||
|
||||
def base_url(port: int) -> str:
|
||||
return f"http://127.0.0.1:{port}"
|
||||
|
||||
|
||||
def call(
|
||||
port: int,
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
user: str | None = None,
|
||||
body: object = None,
|
||||
raw: bytes | None = None,
|
||||
) -> tuple[int, dict[str, str], object]:
|
||||
data = raw
|
||||
headers = {"Accept": "application/json"}
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
if data is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
if user is not None:
|
||||
headers["X-User-Id"] = user
|
||||
request = urllib.request.Request(
|
||||
base_url(port) + path,
|
||||
data=data,
|
||||
method=method,
|
||||
headers=headers,
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=5) as response:
|
||||
status = response.status
|
||||
hdrs = dict(response.headers)
|
||||
payload = response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
status, hdrs, payload = error.code, dict(error.headers), error.read()
|
||||
hdrs = {key.lower(): value for key, value in hdrs.items()}
|
||||
try:
|
||||
parsed = json.loads(payload) if payload else None
|
||||
except json.JSONDecodeError:
|
||||
parsed = payload.decode(errors="replace")
|
||||
return status, hdrs, parsed
|
||||
|
||||
|
||||
def listener_pids(port: int) -> list[int]:
|
||||
out = subprocess.run(
|
||||
["lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN", "-t"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
).stdout
|
||||
return [int(pid) for pid in out.split()]
|
||||
|
||||
|
||||
def is_ready(port: int) -> bool:
|
||||
try:
|
||||
status, _, _ = call(port, "GET", "/health/ready")
|
||||
except OSError:
|
||||
return False
|
||||
return status == 200
|
||||
|
||||
|
||||
def cmd_start(port: int) -> int:
|
||||
log_path, pid_path = paths(port)
|
||||
if listener_pids(port):
|
||||
if is_ready(port):
|
||||
print(f"already up on {base_url(port)}")
|
||||
return 0
|
||||
print(f"port {port} is busy:", listener_pids(port))
|
||||
return 1
|
||||
env = os.environ | {"APP__RUN_MODE": "console", "APP__PORT": str(port)}
|
||||
with log_path.open("wb") as log:
|
||||
proc = subprocess.Popen(
|
||||
["uv", "run", "python", "-m", "src"],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
stdout=log,
|
||||
stderr=subprocess.STDOUT,
|
||||
# своя группа процессов: stop гасит uv, reloader и worker разом
|
||||
start_new_session=True,
|
||||
)
|
||||
pid_path.write_text(str(proc.pid))
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
if proc.poll() is not None:
|
||||
print(f"server exited with {proc.returncode}; log: {log_path}")
|
||||
print(log_path.read_text()[-2000:])
|
||||
return 1
|
||||
if is_ready(port):
|
||||
print(f"up on {base_url(port)} pgid={proc.pid} log={log_path}")
|
||||
return 0
|
||||
time.sleep(0.25)
|
||||
print(f"not ready after 30s; log: {log_path}")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_stop(port: int) -> int:
|
||||
_, pid_path = paths(port)
|
||||
if not pid_path.exists():
|
||||
# экземпляр не наш (например, make run_dev): не трогаем
|
||||
if listener_pids(port):
|
||||
print(f"port {port} is not ours (no pid file); left running")
|
||||
return 1
|
||||
print(f"nothing on {port}")
|
||||
return 0
|
||||
with contextlib.suppress(ProcessLookupError):
|
||||
os.killpg(int(pid_path.read_text()), signal.SIGTERM)
|
||||
pid_path.unlink()
|
||||
deadline = time.monotonic() + 12
|
||||
while listener_pids(port) and time.monotonic() < deadline:
|
||||
time.sleep(0.2)
|
||||
if listener_pids(port):
|
||||
print(f"still listening on {port}:", listener_pids(port))
|
||||
return 1
|
||||
print(f"stopped {port}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_status(port: int) -> int:
|
||||
pids = listener_pids(port)
|
||||
print("listeners:", pids or "none")
|
||||
if pids:
|
||||
print("ready:", is_ready(port))
|
||||
return 0 if pids else 1
|
||||
|
||||
|
||||
def cmd_req(port: int, args: argparse.Namespace) -> int:
|
||||
body = json.loads(args.data) if args.data is not None else None
|
||||
status, hdrs, payload = call(
|
||||
port,
|
||||
args.method.upper(),
|
||||
args.path,
|
||||
user=args.user,
|
||||
body=body,
|
||||
)
|
||||
print(status, "x-request-id:", hdrs.get("x-request-id"))
|
||||
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
||||
return 0 if status < 400 else 2
|
||||
|
||||
|
||||
class Flow:
|
||||
def __init__(self, port: int) -> None:
|
||||
self.port = port
|
||||
self.failures = 0
|
||||
|
||||
def check(self, label: str, ok: bool, detail: object = "") -> None:
|
||||
mark = "ok " if ok else "FAIL"
|
||||
print(f"[{mark}] {label}" + (f" {detail}" if detail else ""))
|
||||
if not ok:
|
||||
self.failures += 1
|
||||
|
||||
def expect(
|
||||
self,
|
||||
label: str,
|
||||
method: str,
|
||||
path: str,
|
||||
status: int,
|
||||
**kwargs: object,
|
||||
) -> object:
|
||||
"""Запрос + проверка статуса, X-Request-Id и формата ошибки."""
|
||||
got, hdrs, payload = call(self.port, method, path, **kwargs)
|
||||
request_id = hdrs.get("x-request-id")
|
||||
ok = got == status and bool(request_id)
|
||||
detail = str(got)
|
||||
if got >= 400:
|
||||
error = {}
|
||||
if isinstance(payload, dict):
|
||||
error = payload.get("error", {})
|
||||
ok = ok and error.get("request_id") == request_id
|
||||
detail = f"{got} {error.get('code')}"
|
||||
shown = path if len(path) <= 60 else path[:57] + "..."
|
||||
self.check(f"{method} {shown} -> {status} ({label})", ok, detail)
|
||||
return payload
|
||||
|
||||
|
||||
def cmd_flow(port: int) -> int:
|
||||
flow = Flow(port)
|
||||
tag = uuid.uuid4().hex[:8]
|
||||
flow.expect("live", "GET", "/health/live", 200)
|
||||
flow.expect("ready", "GET", "/health/ready", 200)
|
||||
|
||||
ids = {}
|
||||
for name in ("alice", "bob", "eve"):
|
||||
body = {"username": f"{name}_{tag}", "display_name": f"{name} ✨"}
|
||||
ids[name] = flow.expect("register", "POST", USERS, 201, body=body)[
|
||||
"id"
|
||||
]
|
||||
alice, bob, eve = ids["alice"], ids["bob"], ids["eve"]
|
||||
dup = {"username": f"alice_{tag}", "display_name": "again"}
|
||||
flow.expect("duplicate username", "POST", USERS, 409, body=dup)
|
||||
me = flow.expect("me", "GET", f"{USERS}/me", 200, user=alice)
|
||||
flow.check("me.id == alice", me.get("id") == alice)
|
||||
flow.expect("no X-User-Id", "GET", f"{USERS}/me", 401)
|
||||
stranger = str(uuid.uuid4())
|
||||
flow.expect("unknown user", "GET", f"{USERS}/me", 401, user=stranger)
|
||||
|
||||
body = {"title": "Проект 🚀", "member_ids": [alice, bob]}
|
||||
chat = flow.expect("new chat", "POST", CHATS, 201, user=alice, body=body)
|
||||
chat_path = f"{CHATS}/{chat['id']}"
|
||||
msgs = f"{chat_path}/messages"
|
||||
body = {"title": "x", "member_ids": [alice]}
|
||||
flow.expect("not a member", "POST", CHATS, 400, user=eve, body=body)
|
||||
|
||||
texts = ["привет", "hi 👋", "третье", "четвёртое", "пятое"]
|
||||
for index, text in enumerate(texts):
|
||||
sender = alice if index % 2 == 0 else bob
|
||||
body = {"text": text}
|
||||
flow.expect("send", "POST", msgs, 201, user=sender, body=body)
|
||||
blank = {"text": " "}
|
||||
flow.expect("blank text", "POST", msgs, 400, user=alice, body=blank)
|
||||
spoof = {"text": "x", "sender_id": alice}
|
||||
flow.expect("sender_id", "POST", msgs, 400, user=alice, body=spoof)
|
||||
|
||||
seen, cursor, pages = [], None, 0
|
||||
while pages < 10:
|
||||
query = "?limit=2" + (f"&cursor={cursor}" if cursor else "")
|
||||
page = flow.expect("page", "GET", msgs + query, 200, user=bob)
|
||||
seen += [item["text"] for item in page["items"]]
|
||||
cursor, pages = page["next_cursor"], pages + 1
|
||||
if cursor is None:
|
||||
break
|
||||
flow.check("history order via cursor", seen == texts, f"{pages} pages")
|
||||
flow.check("created_at ends with Z", chat["created_at"].endswith("Z"))
|
||||
|
||||
flow.expect("outsider reads chat", "GET", chat_path, 404, user=eve)
|
||||
flow.expect("outsider reads history", "GET", msgs, 404, user=eve)
|
||||
hi = {"text": "hi"}
|
||||
flow.expect("outsider posts", "POST", msgs, 404, user=eve, body=hi)
|
||||
flow.expect("no header beats 404", "GET", chat_path, 401)
|
||||
flow.expect("limit=0", "GET", msgs + "?limit=0", 400, user=alice)
|
||||
flow.expect("bad cursor", "GET", msgs + "?cursor=zzz", 400, user=alice)
|
||||
flow.expect("chat_id not uuid", "GET", f"{CHATS}/nope", 400, user=alice)
|
||||
flow.expect("malformed json", "POST", USERS, 400, raw=b"{not json")
|
||||
flow.expect("unknown path", "GET", "/nope", 404)
|
||||
chats = flow.expect("list chats", "GET", CHATS, 200, user=bob)
|
||||
listed = [item["id"] for item in chats["items"]]
|
||||
flow.check("bob sees the chat", chat["id"] in listed)
|
||||
|
||||
print(f"\nalice={alice}\nbob={bob}\neve={eve}\nchat={chat['id']}")
|
||||
print("FAILED:", flow.failures or "none")
|
||||
return 1 if flow.failures else 0
|
||||
|
||||
|
||||
def cmd_smoke(port: int) -> int:
|
||||
return subprocess.call(
|
||||
[
|
||||
sys.executable,
|
||||
"tests/smoke.py",
|
||||
"--base-url",
|
||||
f"http://localhost:{port}",
|
||||
],
|
||||
cwd=ROOT,
|
||||
)
|
||||
|
||||
|
||||
def cmd_student(port: int) -> int:
|
||||
if not (ROOT / "student-tests").is_dir():
|
||||
print("no student-tests/ in this checkout")
|
||||
return 1
|
||||
return subprocess.call(
|
||||
["make", "student_test", f"BASE_URL=http://localhost:{port}"],
|
||||
cwd=ROOT,
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("--port", type=int, default=DEFAULT_PORT)
|
||||
sub = parser.add_subparsers(dest="cmd", required=True)
|
||||
for name in ("start", "stop", "status", "flow", "smoke", "student", "all"):
|
||||
sub.add_parser(name)
|
||||
req = sub.add_parser("req")
|
||||
req.add_argument("method")
|
||||
req.add_argument("path")
|
||||
req.add_argument("--user")
|
||||
req.add_argument("--data")
|
||||
args = parser.parse_args()
|
||||
port = args.port
|
||||
|
||||
if args.cmd == "all":
|
||||
if cmd_start(port) != 0:
|
||||
return 1
|
||||
try:
|
||||
flow_rc = cmd_flow(port)
|
||||
smoke_rc = cmd_smoke(port)
|
||||
student_rc = 0
|
||||
if (ROOT / "student-tests").is_dir():
|
||||
student_rc = cmd_student(port)
|
||||
finally:
|
||||
cmd_stop(port)
|
||||
return flow_rc or smoke_rc or student_rc
|
||||
if args.cmd == "req":
|
||||
return cmd_req(port, args)
|
||||
handlers = {
|
||||
"start": cmd_start,
|
||||
"stop": cmd_stop,
|
||||
"status": cmd_status,
|
||||
"flow": cmd_flow,
|
||||
"smoke": cmd_smoke,
|
||||
"student": cmd_student,
|
||||
}
|
||||
return handlers[args.cmd](port)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user