Compare commits
5 Commits
7aa0d191db
...
f44bc27ce1
| Author | SHA1 | Date | |
|---|---|---|---|
| f44bc27ce1 | |||
| 757f3413e9 | |||
| e31b5f2552 | |||
| d4bf3ed1ad | |||
| c7430d1b8a |
@@ -0,0 +1,188 @@
|
|||||||
|
---
|
||||||
|
name: openspec-apply-change
|
||||||
|
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.
|
||||||
|
allowed-tools: Bash(openspec:*)
|
||||||
|
license: MIT
|
||||||
|
compatibility: Requires openspec CLI.
|
||||||
|
metadata:
|
||||||
|
author: openspec
|
||||||
|
version: "1.0"
|
||||||
|
generatedBy: "1.12.0"
|
||||||
|
---
|
||||||
|
|
||||||
|
Implement tasks from an OpenSpec change.
|
||||||
|
|
||||||
|
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||||
|
|
||||||
|
**Input**: Optionally specify a change name (e.g., `/openspec-apply-change add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **Select the change**
|
||||||
|
|
||||||
|
If a name is provided, use it. Otherwise:
|
||||||
|
- Infer from conversation context if the user mentioned a change
|
||||||
|
- Auto-select if only one active change exists
|
||||||
|
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
|
||||||
|
|
||||||
|
Always announce: "Using change: <name>" and how to override (e.g., `/openspec-apply-change <other>`).
|
||||||
|
|
||||||
|
2. **Check status to understand the schema**
|
||||||
|
```bash
|
||||||
|
openspec status --change "<name>" --json
|
||||||
|
```
|
||||||
|
Parse the JSON to understand:
|
||||||
|
- `schemaName`: The workflow being used (e.g., "spec-driven")
|
||||||
|
- `planningHome`, `changeRoot`, and `actionContext`: planning scope and edit constraints
|
||||||
|
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
|
||||||
|
|
||||||
|
3. **Get apply instructions**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
openspec instructions apply --change "<name>" --json
|
||||||
|
```
|
||||||
|
|
||||||
|
This returns:
|
||||||
|
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
|
||||||
|
- Progress (total, complete, remaining)
|
||||||
|
- Task list with status
|
||||||
|
- Dynamic instruction based on current state
|
||||||
|
- Optional `context`: current required project instruction input from the selected root
|
||||||
|
- Optional `operationGuidance`: current advisory guidance for apply
|
||||||
|
|
||||||
|
**Handle states:**
|
||||||
|
- If `state: "blocked"` (missing artifacts): show message, suggest using `/openspec-continue-change` (if it is not installed, run `openspec status --change "<name>" --json` to see the next artifact and `openspec instructions <artifact-id> --change "<name>" --json` for how to create it)
|
||||||
|
- If `state: "all_done"`: congratulate, suggest archive
|
||||||
|
- Otherwise: proceed to implementation
|
||||||
|
|
||||||
|
Treat `context` as a required prompt-level input. Read and consider it, and
|
||||||
|
apply relevant project facts, conventions, and constraints while implementing.
|
||||||
|
Treat `operationGuidance` as optional additive advice. Read and consider every
|
||||||
|
entry, and follow entries that are applicable and compatible with the built-in
|
||||||
|
workflow.
|
||||||
|
|
||||||
|
Keep both fields separate from CLI-returned state, missing artifacts, tasks,
|
||||||
|
progress, `contextFiles`, and the built-in `instruction`. They are not
|
||||||
|
evidence of task completion, do not replace the built-in instruction, and do
|
||||||
|
not permit bypassing a blocked state. If context conflicts with the built-in
|
||||||
|
instruction, an explicit user choice, or a CLI-controlled value, report the
|
||||||
|
conflict and preserve the controlling value. If guidance is inapplicable or
|
||||||
|
conflicts with those controlling inputs, do not follow it and explain why.
|
||||||
|
These are prompt-level behavior contracts, not enforceable checks.
|
||||||
|
|
||||||
|
4. **Read context files**
|
||||||
|
|
||||||
|
Read every file path listed under `contextFiles` from the apply instructions output.
|
||||||
|
The files depend on the schema being used:
|
||||||
|
- **spec-driven**: proposal, specs, design, tasks
|
||||||
|
- Other schemas: follow the contextFiles from CLI output
|
||||||
|
|
||||||
|
Do not copy `context` or `operationGuidance` verbatim into implementation
|
||||||
|
files or planning artifacts unless the user separately asks for that content.
|
||||||
|
|
||||||
|
5. **Show current progress**
|
||||||
|
|
||||||
|
Display:
|
||||||
|
- Schema being used
|
||||||
|
- Progress: "N/M tasks complete"
|
||||||
|
- Remaining tasks overview
|
||||||
|
- Dynamic instruction from CLI
|
||||||
|
|
||||||
|
6. **Implement tasks (loop until done or blocked)**
|
||||||
|
|
||||||
|
For each pending task:
|
||||||
|
- Show which task is being worked on
|
||||||
|
- Make the code changes required
|
||||||
|
- Keep changes minimal and focused
|
||||||
|
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
|
||||||
|
- Continue to next task
|
||||||
|
|
||||||
|
**Pause if:**
|
||||||
|
- Task is unclear → ask for clarification
|
||||||
|
- Implementation reveals a design issue → suggest updating artifacts
|
||||||
|
- A task needs work beyond what the spec and tasks describe, or you are tempted to drop, narrow, defer, or accept exceptions to specified behavior to make it fit → surface the added scope and ask; do not absorb it silently
|
||||||
|
- Error or blocker encountered → report and wait for guidance
|
||||||
|
- User interrupts
|
||||||
|
|
||||||
|
7. **On completion or pause, show status**
|
||||||
|
|
||||||
|
Display:
|
||||||
|
- Tasks completed this session
|
||||||
|
- Overall progress: "N/M tasks complete"
|
||||||
|
- If all done: suggest archive
|
||||||
|
- If paused: explain why and wait for guidance
|
||||||
|
|
||||||
|
**Output During Implementation**
|
||||||
|
|
||||||
|
```
|
||||||
|
## Implementing: <change-name> (schema: <schema-name>)
|
||||||
|
|
||||||
|
Working on task 3/7: <task description>
|
||||||
|
[...implementation happening...]
|
||||||
|
✓ Task complete
|
||||||
|
|
||||||
|
Working on task 4/7: <task description>
|
||||||
|
[...implementation happening...]
|
||||||
|
✓ Task complete
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output On Completion**
|
||||||
|
|
||||||
|
```
|
||||||
|
## Implementation Complete
|
||||||
|
|
||||||
|
**Change:** <change-name>
|
||||||
|
**Schema:** <schema-name>
|
||||||
|
**Progress:** 7/7 tasks complete ✓
|
||||||
|
|
||||||
|
### Completed This Session
|
||||||
|
- [x] Task 1
|
||||||
|
- [x] Task 2
|
||||||
|
...
|
||||||
|
|
||||||
|
All tasks complete! You can archive this change with `/openspec-archive-change`.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output On Pause (Issue Encountered)**
|
||||||
|
|
||||||
|
```
|
||||||
|
## Implementation Paused
|
||||||
|
|
||||||
|
**Change:** <change-name>
|
||||||
|
**Schema:** <schema-name>
|
||||||
|
**Progress:** 4/7 tasks complete
|
||||||
|
|
||||||
|
### Issue Encountered
|
||||||
|
<description of the issue>
|
||||||
|
|
||||||
|
**Options:**
|
||||||
|
1. <option 1>
|
||||||
|
2. <option 2>
|
||||||
|
3. Other approach
|
||||||
|
|
||||||
|
What would you like to do?
|
||||||
|
```
|
||||||
|
|
||||||
|
**Guardrails**
|
||||||
|
- Keep going through tasks until done or blocked
|
||||||
|
- Always read context files before starting (from the apply instructions output)
|
||||||
|
- If task is ambiguous, pause and ask before implementing
|
||||||
|
- If implementation reveals issues, pause and suggest artifact updates
|
||||||
|
- Keep code changes minimal and scoped to each task
|
||||||
|
- Update task checkbox immediately after completing each task
|
||||||
|
- Pause on errors, blockers, or unclear requirements - don't guess
|
||||||
|
- When a task needs work beyond what the spec describes, surface the added scope and pause - never silently narrow, defer, or simplify away specified behavior
|
||||||
|
- Only mark a task `- [x]` when its specified behavior is fully implemented, not when it is partially done or deferred
|
||||||
|
- Use contextFiles from CLI output, don't assume specific file names
|
||||||
|
- Do not use context or operation guidance as proof that a task is complete
|
||||||
|
- Apply relevant project context; report conflicts with controlling workflow inputs
|
||||||
|
- Consider every guidance entry; explain any inapplicable or conflicting advice
|
||||||
|
- Do not copy runtime context or operation guidance into implementation files or planning artifacts
|
||||||
|
- Preserve CLI-controlled blocked/ready/all-done behavior and completion criteria
|
||||||
|
|
||||||
|
**Fluid Workflow Integration**
|
||||||
|
|
||||||
|
This skill supports the "actions on a change" model:
|
||||||
|
|
||||||
|
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
|
||||||
|
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
---
|
||||||
|
name: openspec-archive-change
|
||||||
|
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
|
||||||
|
allowed-tools: Bash(openspec:*)
|
||||||
|
license: MIT
|
||||||
|
compatibility: Requires openspec CLI.
|
||||||
|
metadata:
|
||||||
|
author: openspec
|
||||||
|
version: "1.0"
|
||||||
|
generatedBy: "1.12.0"
|
||||||
|
---
|
||||||
|
|
||||||
|
Archive a completed change in the experimental workflow.
|
||||||
|
|
||||||
|
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||||
|
|
||||||
|
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
|
||||||
|
|
||||||
|
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **Select the change**
|
||||||
|
|
||||||
|
If a name is provided, use it. Otherwise:
|
||||||
|
- Infer from conversation context if the user mentioned a change
|
||||||
|
- Auto-select if only one active change exists
|
||||||
|
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
|
||||||
|
|
||||||
|
When prompting, show only active changes (not already archived).
|
||||||
|
Include the schema used for each change if available.
|
||||||
|
|
||||||
|
Always announce: "Using change: <name>" and how to override (e.g., `/openspec-archive-change <other>`).
|
||||||
|
|
||||||
|
**Load current archive inputs before the existing archive checks:**
|
||||||
|
|
||||||
|
After resolving the selected change and planning root, run:
|
||||||
|
```bash
|
||||||
|
openspec instructions archive --change "<name>" --json
|
||||||
|
```
|
||||||
|
Keep the same selected-root flags on this command. This lookup is advisory and
|
||||||
|
optional: it only supplies extra prompt inputs, so it must never block archiving.
|
||||||
|
If it exits non-zero or returns invalid JSON — for example on an older CLI that
|
||||||
|
does not support this command yet — continue the archive workflow with no
|
||||||
|
context and no operation guidance. Do not report an error and do not stop.
|
||||||
|
|
||||||
|
A successful response may omit both optional fields. Treat `context` as a
|
||||||
|
required prompt-level input: read and consider it, and apply relevant project
|
||||||
|
facts, conventions, and constraints. Treat `operationGuidance` as optional
|
||||||
|
additive advice: read and consider every entry, and follow entries that are
|
||||||
|
applicable and compatible with the built-in archive workflow.
|
||||||
|
|
||||||
|
Keep both fields separate from built-in steps, explicit user choices, resolved
|
||||||
|
paths, CLI checks, and command contracts. If context conflicts with one of those
|
||||||
|
controlling inputs, report the conflict and preserve the controlling value. If
|
||||||
|
guidance is inapplicable or conflicts with a controlling input, do not follow it
|
||||||
|
and explain why. Do not infer replacement paths, skipped prompts, or flags from
|
||||||
|
either field, and do not copy their text verbatim into specs, change artifacts,
|
||||||
|
or archive summaries unless the user separately asks for it. These are
|
||||||
|
prompt-level behavior contracts, not enforceable checks.
|
||||||
|
|
||||||
|
2. **Check artifact completion status**
|
||||||
|
|
||||||
|
Run `openspec status --change "<name>" --json` to check artifact completion.
|
||||||
|
|
||||||
|
Parse the JSON to understand:
|
||||||
|
- `schemaName`: The workflow being used
|
||||||
|
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context
|
||||||
|
- `artifacts`: List of artifacts with their status (`done`, `skipped`, or other)
|
||||||
|
|
||||||
|
**If any artifacts are neither `done` nor `skipped`** (skipped artifacts satisfy the requirement - the change declares skip_specs):
|
||||||
|
- Display warning listing incomplete artifacts
|
||||||
|
- Ask the user to confirm they want to proceed
|
||||||
|
- Proceed if user confirms
|
||||||
|
|
||||||
|
3. **Check task completion status**
|
||||||
|
|
||||||
|
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
|
||||||
|
|
||||||
|
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
|
||||||
|
|
||||||
|
**If incomplete tasks found:**
|
||||||
|
- Display warning showing count of incomplete tasks
|
||||||
|
- Ask the user to confirm they want to proceed
|
||||||
|
- Proceed if user confirms
|
||||||
|
|
||||||
|
**If no tasks file exists:** Proceed without task-related warning.
|
||||||
|
|
||||||
|
4. **Assess delta spec sync state**
|
||||||
|
|
||||||
|
Use `artifactPaths.specs.existingOutputPaths` from status JSON as the only
|
||||||
|
delta-spec source. If the `specs` entry is missing or
|
||||||
|
`existingOutputPaths` is empty, proceed without a sync prompt and do not infer
|
||||||
|
delta specs from other artifacts.
|
||||||
|
|
||||||
|
**If delta specs exist:**
|
||||||
|
- Compare each delta spec with its corresponding main spec at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (use the store-aware `planningHome.root` from step 2, not a hardcoded repo path)
|
||||||
|
- Determine what changes would be applied (adds, modifications, removals, renames)
|
||||||
|
- Show a combined summary before prompting
|
||||||
|
|
||||||
|
**Prompt options:**
|
||||||
|
- If changes needed: "Sync now (recommended)", "Archive without syncing"
|
||||||
|
- If already synced: "Archive now", "Sync anyway", "Cancel"
|
||||||
|
|
||||||
|
Route on the answer:
|
||||||
|
- "Cancel" — stop, do not archive
|
||||||
|
- "Archive without syncing" or "Archive now" — proceed to archive
|
||||||
|
- "Sync now" or "Sync anyway" — sync, then verify (below)
|
||||||
|
- Anything else — ask again rather than archiving
|
||||||
|
|
||||||
|
Before a selected sync writes any main spec, run
|
||||||
|
`openspec instructions specs --change "<name>" --json` once with the same
|
||||||
|
selected-root flags. Require a zero exit status and valid artifact-instruction
|
||||||
|
JSON. If the lookup fails or returns invalid JSON, report the error and stop
|
||||||
|
before writing any main spec or moving the change. A valid response with omitted
|
||||||
|
`rules` is the no-rules case. Apply returned `rules` only to the content and
|
||||||
|
form of main specs produced by this merge; do not use them as archive guidance,
|
||||||
|
change CLI behavior, or copy the rule text into any output file.
|
||||||
|
|
||||||
|
Then run the `openspec-sync-specs` workflow inline (agent-driven intelligent merge) for change '<name>', passing the delta spec analysis and the fetched specs-rule snapshot from above, and wait for it to finish. The inline sync must reuse that snapshot without fetching `specs` instructions again. Do not delegate it to a background task — step 5 would move `changeRoot` out from under a sync that is still reading it, leaving the change archived and the main specs never updated. If your agent can only run it by delegation, delegate synchronously and wait for the result.
|
||||||
|
|
||||||
|
Then re-run the comparison from the top of this step against every capability that has a delta spec in `artifactPaths.specs.existingOutputPaths` — not only the ones the sync reports it touched. A successful sync leaves nothing left to apply, so each capability must now read as already synced:
|
||||||
|
- ADDED requirements present
|
||||||
|
- MODIFIED requirements carrying the scenario and description changes named in the delta, with their other scenarios intact
|
||||||
|
- REMOVED requirements gone — and where this sync retired a capability (removed its last requirement, leaving `## Requirements` empty), its main spec deleted rather than left empty; a spec the sync deliberately kept and reported is also a match
|
||||||
|
- RENAMED requirements present under the new name and absent under the old one
|
||||||
|
|
||||||
|
If the sync failed, or any capability does not match, report what differs and stop — do not archive. Nothing has moved and `changeRoot` is intact, so the user can fix the mismatch or re-run the sync and start the archive again.
|
||||||
|
|
||||||
|
5. **Perform the archive**
|
||||||
|
|
||||||
|
Create an `archive` directory under `planningHome.changesDir` if it doesn't exist:
|
||||||
|
```bash
|
||||||
|
mkdir -p "<planningHome.changesDir>/archive"
|
||||||
|
```
|
||||||
|
|
||||||
|
Generate the target name: use the change name as-is when it already starts with a `YYYY-MM-DD-` prefix; otherwise prepend the current date as `YYYY-MM-DD-<change-name>`. Never stack a second date (same rule as `openspec archive`).
|
||||||
|
|
||||||
|
**Check if target already exists:**
|
||||||
|
- If yes: Fail with error, suggest renaming existing archive or using different date
|
||||||
|
- If no: Move `changeRoot` to the archive directory
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mv "<changeRoot>" "<planningHome.changesDir>/archive/<target-name>"
|
||||||
|
```
|
||||||
|
|
||||||
|
6. **Display summary**
|
||||||
|
|
||||||
|
Show archive completion summary including:
|
||||||
|
- Change name
|
||||||
|
- Schema that was used
|
||||||
|
- Archive location
|
||||||
|
- Whether specs were synced (if applicable)
|
||||||
|
- Note about any warnings (incomplete artifacts/tasks)
|
||||||
|
|
||||||
|
**Output On Success**
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## Archive Complete
|
||||||
|
|
||||||
|
**Change:** <change-name>
|
||||||
|
**Schema:** <schema-name>
|
||||||
|
**Archived to:** the archive path derived from `planningHome.changesDir`/<target-name>/
|
||||||
|
**Specs:** <"✓ Synced to main specs" only if the step 4 verification passed; otherwise "No delta specs" or "Sync skipped">
|
||||||
|
|
||||||
|
<"All artifacts complete. All tasks complete." — or, if archived with warnings, list them instead (e.g. "Archived with 2 incomplete tasks")>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Guardrails**
|
||||||
|
- Announce the selected change; prompt for selection when it is ambiguous
|
||||||
|
- Use artifact graph (openspec status --json) for completion checking
|
||||||
|
- Don't block archive on warnings - just inform and confirm
|
||||||
|
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
|
||||||
|
- Show clear summary of what happened
|
||||||
|
- If sync is requested, run the `openspec-sync-specs` workflow inline (agent-driven)
|
||||||
|
- Never archive while a spec sync is still in flight — run the sync inline and verify the main specs before moving `changeRoot`
|
||||||
|
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
|
||||||
|
- Apply relevant runtime context and report conflicts; operation guidance remains advisory
|
||||||
|
- Consider every guidance entry and explain any inapplicable or conflicting advice
|
||||||
|
- Existing CLI checks, resolved paths, prompts, and command contracts are unchanged
|
||||||
|
- Artifact rules constrain only the specs being written and are never operation guidance
|
||||||
|
- Never copy runtime context, operation guidance, or artifact-rule text verbatim into output files
|
||||||
@@ -0,0 +1,335 @@
|
|||||||
|
---
|
||||||
|
name: openspec-explore
|
||||||
|
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
|
||||||
|
allowed-tools: Bash(openspec:*)
|
||||||
|
license: MIT
|
||||||
|
compatibility: Requires openspec CLI.
|
||||||
|
metadata:
|
||||||
|
author: openspec
|
||||||
|
version: "1.0"
|
||||||
|
generatedBy: "1.12.0"
|
||||||
|
---
|
||||||
|
|
||||||
|
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
|
||||||
|
|
||||||
|
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, investigate the codebase, and run read-only commands or tools without confirmation, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create or update OpenSpec change artifacts (proposals, designs, specs) within a confirmed scope—that's capturing thinking, not implementing. Answering design or clarifying questions is never consent to write. Before the first write-capable action, name the artifacts or files you would change and what you would do, ask a direct yes/no question, and wait for the user's confirmation in a separate message. Confirmation covers only the scope you described; ask again before expanding it. For a new change, scaffold it first as described below.
|
||||||
|
|
||||||
|
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
|
||||||
|
|
||||||
|
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## The Stance
|
||||||
|
|
||||||
|
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
|
||||||
|
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
|
||||||
|
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
|
||||||
|
- **Adaptive** - Follow interesting threads, pivot when new information emerges
|
||||||
|
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
|
||||||
|
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Planning a Change
|
||||||
|
|
||||||
|
When the user is planning a change, guide them toward shared understanding with focused discovery questions. For open-ended discussion, follow the conversation without imposing an interview or a required output.
|
||||||
|
|
||||||
|
Before asking a factual question, follow the context discovery below and inspect relevant OpenSpec artifacts, source, tests, docs, and configuration. Do not ask the user to repeat facts you can verify. Summarize relevant findings without reproducing private context or rules. If evidence is missing, conflicting, or inaccessible, state that limitation and ask only for the clarification needed to proceed.
|
||||||
|
|
||||||
|
- **Follow dependencies** - Resolve the next blocking decision before its dependent details. For example, clarify the user's outcome and scope before choosing an API or data model. Revisit downstream assumptions when an earlier answer changes. Skip branches that do not matter to this goal.
|
||||||
|
- **Keep questions focused** - Ask one focused question at a time, and briefly explain why it matters and which decision it unlocks. Batch questions only if the user asks for a batch; keep them small and group related decisions.
|
||||||
|
- **Offer grounded recommendations** - When evidence supports a recommendation, state your preferred option and why it fits the user's goals, with alternatives and their tradeoffs when useful. Do not invent intent, priorities, or external constraints: ask the user when only they can answer. Avoid a fixed question format.
|
||||||
|
- **Keep a conversational record** - Track decisions in the conversation, not in files. Separate confirmed decisions from proposed defaults and unresolved questions. Silence is not acceptance. Accepting an answer or a batch of recommendations is not permission to write. Keep file-write confirmation separate from discovery questions and follow the guardrails below.
|
||||||
|
|
||||||
|
Stop asking when the user has enough clarity. Let them pause, pivot, or defer a decision; do not exhaust every branch or force a proposal.
|
||||||
|
|
||||||
|
For example, after inspecting the relevant code:
|
||||||
|
|
||||||
|
```text
|
||||||
|
The CLI already uses SQLite and has no remote service. Is sharing state
|
||||||
|
across devices in scope? That determines whether local storage is enough.
|
||||||
|
If this stays a single-device tool, I recommend keeping SQLite to avoid
|
||||||
|
adding a service to operate; shared state would need a separate sync design.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What You Might Do
|
||||||
|
|
||||||
|
Depending on what the user brings, you might:
|
||||||
|
|
||||||
|
**Explore the problem space**
|
||||||
|
- Ask clarifying questions that emerge from what they said
|
||||||
|
- Challenge assumptions
|
||||||
|
- Reframe the problem
|
||||||
|
- Find analogies
|
||||||
|
|
||||||
|
**Investigate the codebase**
|
||||||
|
- Map existing architecture relevant to the discussion
|
||||||
|
- Find integration points
|
||||||
|
- Identify patterns already in use
|
||||||
|
- Surface hidden complexity
|
||||||
|
|
||||||
|
**Compare options**
|
||||||
|
- Brainstorm multiple approaches
|
||||||
|
- Build comparison tables
|
||||||
|
- Sketch tradeoffs
|
||||||
|
- Recommend a path (if asked)
|
||||||
|
|
||||||
|
**Visualize**
|
||||||
|
```
|
||||||
|
+------------------------------------------+
|
||||||
|
| Use ASCII diagrams liberally |
|
||||||
|
+------------------------------------------+
|
||||||
|
| |
|
||||||
|
| [State A] -------> [State B] |
|
||||||
|
| | |
|
||||||
|
| v |
|
||||||
|
| [State C] |
|
||||||
|
| |
|
||||||
|
| System diagrams, state machines, |
|
||||||
|
| data flows, architecture sketches, |
|
||||||
|
| dependency graphs, comparison tables |
|
||||||
|
| |
|
||||||
|
+------------------------------------------+
|
||||||
|
```
|
||||||
|
|
||||||
|
**Draw with plain ASCII only** — borders `+` `-` `|`, arrows `-->` `<--` `^` `v`, markers `*` `x`.
|
||||||
|
Unicode diagram glyphs can render at different widths across terminals, fonts, and locales, so padded boxes and aligned tables can drift. Keep every diagram character ASCII.
|
||||||
|
|
||||||
|
**Surface risks and unknowns**
|
||||||
|
- Identify what could go wrong
|
||||||
|
- Find gaps in understanding
|
||||||
|
- Suggest spikes or investigations
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## OpenSpec Awareness
|
||||||
|
|
||||||
|
You have full context of the OpenSpec system. Use it naturally, don't force it.
|
||||||
|
|
||||||
|
### Check for context
|
||||||
|
|
||||||
|
At the start, quickly check what exists:
|
||||||
|
```bash
|
||||||
|
openspec list --json
|
||||||
|
```
|
||||||
|
|
||||||
|
This tells you:
|
||||||
|
- If there are active changes
|
||||||
|
- Their names, schemas, and status
|
||||||
|
- What the user might be working on
|
||||||
|
|
||||||
|
Then read the project's own context from the resolved root - `<root.path>/openspec/config.yaml` (or `config.yml`). Use the `root.path` returned above, and skip this if neither file exists:
|
||||||
|
- `context`: project background - tech stack, conventions, constraints
|
||||||
|
- `rules`: keyed by artifact id - the entries for an artifact apply only when you write that artifact
|
||||||
|
|
||||||
|
Ground your thinking in these. They are constraints for you to follow, not content to reproduce: do NOT copy them into the conversation or into any artifact you create.
|
||||||
|
|
||||||
|
### When no change exists
|
||||||
|
|
||||||
|
Think freely. When insights crystallize, you might offer:
|
||||||
|
|
||||||
|
- "This feels solid enough to start a change. Want me to create a proposal?"
|
||||||
|
- Or keep exploring - no pressure to formalize
|
||||||
|
|
||||||
|
If the user asks you to capture the exploration as a new change, transition seamlessly into the requested capture:
|
||||||
|
|
||||||
|
1. Run `openspec new change "<name>"` (with `--store <id>` when applicable) before creating any artifacts. Never create a new change directory under `openspec/changes/` by hand; the CLI scaffold creates required metadata such as `.openspec.yaml`. Keep the selected `--store <id>` on every applicable follow-up `status` and `instructions` command.
|
||||||
|
2. Run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store), then process the requested artifacts in dependency order. For each requested artifact that is `ready`, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store). Before creating a requested artifact, evaluate any condition in its own `instruction` against the explored change; record a deliberate skip instead when the condition does not apply. If a requested artifact is blocked by a direct prerequisite the user did not request, run `openspec instructions "<prerequisite-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) for that prerequisite whether it is `ready` or `blocked`. If its own `instruction` states a condition, evaluate that condition against the explored change and record a deliberate skip only when the condition does not apply. If the condition applies, or the prerequisite is not conditional, treat it as a normal prerequisite and ask before expanding the capture. Do not create an unrequested prerequisite unless the user approves.
|
||||||
|
3. Follow the returned `template` and `instruction` fields. Read completed dependency files listed in `dependencies`, and apply `context` and `rules` as constraints without copying them into the artifact. If the instruction delegates creation to a specific skill or command, invoke it; otherwise write the artifact to `resolvedOutputPath`, using the instruction to choose a concrete path when it is a glob. Verify that the selected concrete output exists.
|
||||||
|
4. After creating each artifact, re-run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) and continue until every requested artifact is `done`, `skipped`, or was deliberately skipped because its own `instruction` stated a condition that did not apply. Tell the user about a deliberate conditional skip, remember it, and do not reconsider it. Dependencies are enablers, not gates: if a requested artifact is still `blocked` only because you deliberately skipped a conditional prerequisite, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) despite the blocked status, then create it using step 3 only when those recorded conditional skips are its sole missing dependencies. If a requested artifact is blocked by a prerequisite the user did not ask to capture and cannot be conditionally skipped, explain that dependency and ask before expanding the capture.
|
||||||
|
|
||||||
|
Capture the artifact(s) the user requested without asking them to invoke another workflow command. If they asked only to start a change, stop after scaffolding and show its status.
|
||||||
|
|
||||||
|
### When a change exists
|
||||||
|
|
||||||
|
If the user mentions a change or you detect one is relevant:
|
||||||
|
|
||||||
|
1. **Resolve and read existing artifacts for context**
|
||||||
|
- Run `openspec status --change "<name>" --json`.
|
||||||
|
- Use `changeRoot`, `artifactPaths`, and `actionContext` from the status JSON.
|
||||||
|
- Read existing files from `artifactPaths.<artifact>.existingOutputPaths`.
|
||||||
|
|
||||||
|
2. **Reference them naturally in conversation**
|
||||||
|
- "Your design mentions using Redis, but we just realized SQLite fits better..."
|
||||||
|
- "The proposal scopes this to premium users, but we're now thinking everyone..."
|
||||||
|
|
||||||
|
3. **Offer to capture when decisions are made**
|
||||||
|
|
||||||
|
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
|
||||||
|
|
||||||
|
| Insight Type | Where to Capture |
|
||||||
|
|----------------------------|-------------------------------------|
|
||||||
|
| New requirement discovered | `specs/<capability-path>/spec.md` |
|
||||||
|
| Requirement changed | `specs/<capability-path>/spec.md` |
|
||||||
|
| Design decision made | `design.md` |
|
||||||
|
| Scope changed | `proposal.md` |
|
||||||
|
| New work identified | `tasks.md` |
|
||||||
|
| Assumption invalidated | Relevant artifact |
|
||||||
|
|
||||||
|
Example offers:
|
||||||
|
- "That's a design decision. Capture it in design.md?"
|
||||||
|
- "This is a new requirement. Add it to specs?"
|
||||||
|
- "This changes scope. Update the proposal?"
|
||||||
|
|
||||||
|
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What You Don't Have To Do
|
||||||
|
|
||||||
|
- Follow a script
|
||||||
|
- Ask the same questions every time
|
||||||
|
- Produce a specific artifact
|
||||||
|
- Reach a conclusion
|
||||||
|
- Stay on topic if a tangent is valuable
|
||||||
|
- Be brief (this is thinking time)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Handling Different Entry Points
|
||||||
|
|
||||||
|
**User brings a vague idea:**
|
||||||
|
```
|
||||||
|
User: I'm thinking about adding real-time collaboration
|
||||||
|
|
||||||
|
You: Real-time collab is a big space. Let me think about this...
|
||||||
|
|
||||||
|
COLLABORATION SPECTRUM
|
||||||
|
============================================
|
||||||
|
|
||||||
|
Awareness Coordination Sync
|
||||||
|
| | |
|
||||||
|
v v v
|
||||||
|
+--------+ +--------+ +--------+
|
||||||
|
|Presence| |Cursors | | CRDT |
|
||||||
|
| "3 | | Multi | |Conflict|
|
||||||
|
|online" | | select | | free |
|
||||||
|
+--------+ +--------+ +--------+
|
||||||
|
| | |
|
||||||
|
trivial moderate complex
|
||||||
|
|
||||||
|
Where's your head at?
|
||||||
|
```
|
||||||
|
|
||||||
|
**User brings a specific problem:**
|
||||||
|
```
|
||||||
|
User: The auth system is a mess
|
||||||
|
|
||||||
|
You: [reads codebase]
|
||||||
|
|
||||||
|
+---------------------------------------------+
|
||||||
|
| CURRENT AUTH FLOW |
|
||||||
|
+---------------------------------------------+
|
||||||
|
|
|
||||||
|
+-------------+-------------+
|
||||||
|
v v v
|
||||||
|
+---------+ +---------+ +---------+
|
||||||
|
| Google | | GitHub | | Email |
|
||||||
|
| OAuth | | OAuth | | Magic |
|
||||||
|
+----+----+ +----+----+ +----+----+
|
||||||
|
| | |
|
||||||
|
+-------------+-------------+
|
||||||
|
v
|
||||||
|
+-----------+
|
||||||
|
| Session |
|
||||||
|
+-----+-----+
|
||||||
|
|
|
||||||
|
v
|
||||||
|
+-----------+
|
||||||
|
| Perms |
|
||||||
|
+-----------+
|
||||||
|
|
||||||
|
I see three tangles. Which one's burning?
|
||||||
|
```
|
||||||
|
|
||||||
|
**User is stuck mid-implementation:**
|
||||||
|
```
|
||||||
|
User: /openspec-explore add-auth-system
|
||||||
|
The OAuth integration is more complex than expected
|
||||||
|
|
||||||
|
You: [reads change artifacts]
|
||||||
|
|
||||||
|
You're on task 4: "Implement OAuth flow"
|
||||||
|
|
||||||
|
Let me trace what's involved...
|
||||||
|
|
||||||
|
[draws diagram, explores options, suggests paths]
|
||||||
|
|
||||||
|
Want to update the design to reflect this?
|
||||||
|
Or add a spike task to investigate?
|
||||||
|
```
|
||||||
|
|
||||||
|
**User wants to compare options:**
|
||||||
|
```
|
||||||
|
User: Should we use Postgres or SQLite?
|
||||||
|
|
||||||
|
You: Generic answer is boring. What's the context?
|
||||||
|
|
||||||
|
User: A CLI tool that tracks local dev environments
|
||||||
|
|
||||||
|
You: That changes everything.
|
||||||
|
|
||||||
|
+-------------------------------------------------+
|
||||||
|
| CLI TOOL DATA STORAGE |
|
||||||
|
+-------------------------------------------------+
|
||||||
|
|
||||||
|
Key constraints:
|
||||||
|
- No daemon running
|
||||||
|
- Must work offline
|
||||||
|
- Single user
|
||||||
|
|
||||||
|
SQLite Postgres
|
||||||
|
Deployment embedded needs server
|
||||||
|
Offline yes no
|
||||||
|
Single file yes no
|
||||||
|
|
||||||
|
SQLite. Not even close.
|
||||||
|
|
||||||
|
Unless... is there a sync component?
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ending Discovery
|
||||||
|
|
||||||
|
There's no required ending. Discovery might:
|
||||||
|
|
||||||
|
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
|
||||||
|
- **Result in artifact updates**: "Updated design.md with these decisions"
|
||||||
|
- **Just provide clarity**: User has what they need, moves on
|
||||||
|
- **Continue later**: "We can pick this up anytime"
|
||||||
|
|
||||||
|
When it feels like things are crystallizing, you might summarize:
|
||||||
|
|
||||||
|
```
|
||||||
|
## What We Figured Out
|
||||||
|
|
||||||
|
**The problem**: [crystallized understanding]
|
||||||
|
|
||||||
|
**The approach**: [if one emerged]
|
||||||
|
|
||||||
|
**Open questions**: [if any remain]
|
||||||
|
|
||||||
|
**Next steps** (if ready):
|
||||||
|
- Create a change proposal
|
||||||
|
- Keep exploring: just keep talking
|
||||||
|
```
|
||||||
|
|
||||||
|
But this summary is optional. Sometimes the thinking IS the value.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Guardrails
|
||||||
|
|
||||||
|
- **Don't implement** - Never write code or implement features. Workflow configuration counts too: creating or editing schemas, templates, or `openspec/config.yaml` is a change, not thinking. Creating or updating OpenSpec change artifacts within the confirmed scope is fine, writing anything else is not.
|
||||||
|
- **Don't fake understanding** - If something is unclear, dig deeper
|
||||||
|
- **Don't rush** - Discovery is thinking time, not task time
|
||||||
|
- **Don't force structure** - Let patterns emerge naturally
|
||||||
|
- **Don't auto-capture** - Offer to save insights, don't just do it. Read-only commands and tools need no confirmation. Before the first write-capable action—including `openspec new change` or another command that writes files—name the artifacts or files and proposed changes, ask a direct yes/no question, and wait for explicit confirmation in a separate user message. That confirmation covers only the described scope; ask again before expanding it. Answers to design or clarifying questions are never consent to write.
|
||||||
|
- **Don't manually scaffold changes** - Never create a new change directory under `openspec/changes/` by hand. Always use `openspec new change "<name>"` (with `--store <id>` when applicable) so required metadata such as `.openspec.yaml` is created before writing artifacts.
|
||||||
|
- **Do visualize** - A good diagram is worth many paragraphs
|
||||||
|
- **Do explore the codebase** - Ground discussions in reality
|
||||||
|
- **Do question assumptions** - Including the user's and your own
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
---
|
||||||
|
name: openspec-propose
|
||||||
|
description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.
|
||||||
|
allowed-tools: Bash(openspec:*)
|
||||||
|
license: MIT
|
||||||
|
compatibility: Requires openspec CLI.
|
||||||
|
metadata:
|
||||||
|
author: openspec
|
||||||
|
version: "1.0"
|
||||||
|
generatedBy: "1.12.0"
|
||||||
|
---
|
||||||
|
|
||||||
|
Propose a new change - create the change and generate all artifacts in one step.
|
||||||
|
|
||||||
|
**Planning boundary**: This workflow creates planning artifacts only. The user request that selected or triggered this workflow authorizes planning only, even if it asks to build or fix something. Do not edit project code. After the planning artifacts are complete, stop. Do not start implementation in the same response, even if the initial request asks for it. Wait for a new user request after the artifacts are presented; then start the apply workflow.
|
||||||
|
|
||||||
|
I'll create a change with the artifacts your schema defines. With the default spec-driven schema that is:
|
||||||
|
- proposal.md (what & why)
|
||||||
|
- `specs/<capability-path>/spec.md` (what the system must do - a delta, not the main spec)
|
||||||
|
- design.md (how)
|
||||||
|
- tasks.md (implementation steps)
|
||||||
|
|
||||||
|
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
|
||||||
|
|
||||||
|
When the user is ready to implement, they must start the apply workflow explicitly.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||||
|
|
||||||
|
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **Understand the request and clarify material ambiguity**
|
||||||
|
|
||||||
|
If no clear input is provided, ask the user (open-ended, no preset options):
|
||||||
|
> "What change do you want to work on? Describe what you want to build or fix."
|
||||||
|
|
||||||
|
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
|
||||||
|
|
||||||
|
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
|
||||||
|
|
||||||
|
If the request contains ambiguity that would materially affect scope, externally observable behavior, compatibility, or acceptance criteria, ask the user before creating the change. For minor details, make a reasonable assumption and record it in the planning artifacts.
|
||||||
|
|
||||||
|
2. **Determine the workflow schema**
|
||||||
|
|
||||||
|
Use the configured default schema unless the user explicitly requests a different workflow.
|
||||||
|
|
||||||
|
**Use a different schema only if the user:**
|
||||||
|
- Explicitly requests a specific schema by name → use `--schema <schema-name>`
|
||||||
|
- Asks to "show workflows" or asks "what workflows" exist → resolve the authoritative root by running `openspec context --json` from the current working directory. If the user explicitly selected a registered store, use `openspec context --json --store "<store-id>"`. Then run `openspec schemas --json` with its working directory set to the returned `root.path` and let them choose. This preserves roots selected by a local `store:` pointer or the global `defaultStore`; when a registered store was explicitly selected, append `--store "<store-id>"` to `openspec schemas --json` as well. If context reports only `no_openspec_root`, run `openspec schemas --json` from the current working directory instead. Do not use this fallback for invalid or unavailable stores.
|
||||||
|
|
||||||
|
Otherwise, omit `--schema` to preserve the configured default.
|
||||||
|
|
||||||
|
3. **Create the change directory**
|
||||||
|
|
||||||
|
Choose one schema form below. If a registered store is selected, append `--store "<store-id>"` to that command and each later OpenSpec command shown below that accepts `--store`.
|
||||||
|
|
||||||
|
Using the configured default:
|
||||||
|
```bash
|
||||||
|
openspec new change "<name>"
|
||||||
|
```
|
||||||
|
|
||||||
|
Using an explicitly requested schema:
|
||||||
|
```bash
|
||||||
|
openspec new change "<name>" --schema "<schema-name>"
|
||||||
|
```
|
||||||
|
This creates a scaffolded change in the planning home resolved by the CLI with `.openspec.yaml`.
|
||||||
|
|
||||||
|
4. **Get the artifact build order**
|
||||||
|
```bash
|
||||||
|
openspec status --change "<name>" --json
|
||||||
|
```
|
||||||
|
Parse the JSON to get:
|
||||||
|
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
|
||||||
|
- `artifacts`: list of all artifacts, each with its `status` and its `requires` edges (the artifact IDs it directly depends on)
|
||||||
|
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
|
||||||
|
|
||||||
|
5. **Create every artifact in the required set**
|
||||||
|
|
||||||
|
Use a todo list to track progress through the artifacts.
|
||||||
|
|
||||||
|
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
|
||||||
|
|
||||||
|
a. **For each artifact that is `ready` (dependencies satisfied)**:
|
||||||
|
- Get instructions:
|
||||||
|
```bash
|
||||||
|
openspec instructions <artifact-id> --change "<name>" --json
|
||||||
|
```
|
||||||
|
- The instructions JSON includes:
|
||||||
|
- `context`: Project background (constraints for you - do NOT include in output)
|
||||||
|
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
|
||||||
|
- `template`: The structure to use for your output file
|
||||||
|
- `instruction`: Schema-specific guidance for this artifact type
|
||||||
|
- `skipped`/`warning`: present when the change declares skip_specs and this artifact must NOT be created - stop and pick another artifact
|
||||||
|
- `resolvedOutputPath`: Resolved path or pattern to write the artifact
|
||||||
|
- `dependencies`: Completed artifacts to read for context
|
||||||
|
- Read any completed dependency files for context - always re-read them from disk, even if you saw them earlier in the conversation (the user may have edited them)
|
||||||
|
- **Inspect the relevant project before drafting**: Read `context` and `rules` first, then inspect relevant implementation, nearby tests, configuration, and documentation outside `openspec/`. Keep inspection read-only and proportional to the change; reuse findings for later artifacts and inspect more only as needed.
|
||||||
|
- Identify the target project from the request and project context; the planning home may be separate from the code. If the target is unclear, ask. For greenfield or non-code changes, inspect the available structure and relevant documents. If source is unavailable, state the limitation and ask when it materially affects the plan.
|
||||||
|
- Ground scope, approach, and tasks in what you find. Distinguish observed behavior from assumptions and proposed additions; surface conflicts with existing specs instead of silently deciding which is correct.
|
||||||
|
- Do this discovery now, rather than leaving generic "explore the codebase" or "make a plan" tasks for implementation. Keep any necessary follow-up investigation specific to an unresolved question.
|
||||||
|
- If the `instruction` field delegates creation to a specific skill or command, invoke it to produce the artifact instead of writing the file yourself, then verify the artifact file exists at `resolvedOutputPath`
|
||||||
|
- Otherwise create the artifact file using `template` as the structure and write it to `resolvedOutputPath`. If `resolvedOutputPath` is a glob, follow `instruction` to choose the concrete file path
|
||||||
|
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
|
||||||
|
- Show brief progress: "Created <artifact-id>"
|
||||||
|
|
||||||
|
b. **Continue until every artifact in the required set exists (not just `apply.requires`)**
|
||||||
|
- After creating each artifact, re-run `openspec status --change "<name>" --json`
|
||||||
|
- The required set is `applyRequires` plus every artifact reachable from those by following the `requires` edges in `status --json` - walk them transitively (spec-driven closes over proposal, specs, design, tasks). Leave artifacts outside that set alone
|
||||||
|
- `status` is file-existence only, so an `applyRequires` artifact reading `done` does NOT mean its dependencies exist - writing `tasks.md` early marks `tasks` done while `specs` was never written. Use each artifact's `requires` edges, not its `status`, to build the required set: a `done` artifact still lists what it depends on
|
||||||
|
- An artifact already reading `status: "skipped"` is satisfied: the change declares `skip_specs` in `.openspec.yaml`, so its files must NOT exist. Never try to create one
|
||||||
|
- Create every artifact in the required set that is missing, then re-check - creating one can unblock others
|
||||||
|
- Skip one only when `status` already reports it `skipped`, or when its own `instruction` says it is conditional: run `openspec instructions <artifact-id> --change "<name>" --json` and skip only if its `instruction` field marks it optional (e.g. "create only if..."). Spec-driven's `design.md` qualifies; `specs` qualifies only via the `skipped` status above, never by your own judgment. Tell the user, and do not reconsider it
|
||||||
|
- Dependencies are enablers, not gates: if a required artifact is still `blocked` only because you skipped a conditional dependency, write it anyway
|
||||||
|
- Stop when every artifact in the required set is `done`, `skipped`, or was deliberately skipped
|
||||||
|
|
||||||
|
c. **If an artifact requires user input** (unclear context):
|
||||||
|
- Ask the user to clarify
|
||||||
|
- Then continue with creation
|
||||||
|
|
||||||
|
6. **Show final status**
|
||||||
|
```bash
|
||||||
|
openspec status --change "<name>"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output**
|
||||||
|
|
||||||
|
After completing all artifacts, summarize:
|
||||||
|
- Change name and location
|
||||||
|
- List of artifacts created with brief descriptions, plus any conditional artifact you skipped and why
|
||||||
|
- What's ready: "All artifacts needed for implementation are ready."
|
||||||
|
- Prompt: "The artifacts are ready for review. When you are ready, run `/openspec-apply-change` or ask me to apply this change."
|
||||||
|
|
||||||
|
**Artifact Creation Guidelines**
|
||||||
|
|
||||||
|
- Follow the `instruction` field from `openspec instructions` for each artifact type - it is the authoritative guidance, even for familiar artifact names
|
||||||
|
- If the `instruction` field directs you to use a specific skill or command to create the artifact, invoke it instead of writing the artifact directly
|
||||||
|
- The schema defines what each artifact should contain - follow it
|
||||||
|
- Read dependency artifacts for context before creating new ones
|
||||||
|
- Use `template` as the structure for your output file - fill in its sections
|
||||||
|
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
|
||||||
|
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
|
||||||
|
- These guide what you write, but should never appear in the output
|
||||||
|
|
||||||
|
**Guardrails**
|
||||||
|
- The request that invoked this workflow authorizes planning only. Any implementation or apply instruction in that request does not carry forward. Do NOT implement the change, start the apply workflow, or edit project code during this workflow. After presenting the artifacts, stop and wait for a new user request to start the apply workflow
|
||||||
|
- Create every artifact the apply phase transitively depends on, not just the ids listed in `apply.requires`
|
||||||
|
- Always read dependency artifacts before creating a new one - re-read from disk, not from conversation memory (files may have changed since you last saw them)
|
||||||
|
- Ask about ambiguities that would materially change scope, externally observable behavior, compatibility, or acceptance criteria; for minor details, make reasonable assumptions and record them
|
||||||
|
- If a change with that name already exists, ask if user wants to continue it or create a new one
|
||||||
|
- Verify each artifact file exists after writing before proceeding to next
|
||||||
@@ -0,0 +1,262 @@
|
|||||||
|
---
|
||||||
|
name: openspec-sync-specs
|
||||||
|
description: Sync delta specs from a change to main specs. Use when the user wants to update main specs with changes from a delta spec, without archiving the change.
|
||||||
|
allowed-tools: Bash(openspec:*)
|
||||||
|
license: MIT
|
||||||
|
compatibility: Requires openspec CLI.
|
||||||
|
metadata:
|
||||||
|
author: openspec
|
||||||
|
version: "1.0"
|
||||||
|
generatedBy: "1.12.0"
|
||||||
|
---
|
||||||
|
|
||||||
|
Sync delta specs from a change to main specs.
|
||||||
|
|
||||||
|
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
|
||||||
|
|
||||||
|
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||||
|
|
||||||
|
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
|
||||||
|
|
||||||
|
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **Select the change**
|
||||||
|
|
||||||
|
If a name is provided, use it. Otherwise:
|
||||||
|
- Infer from conversation context if the user mentioned a change
|
||||||
|
- Auto-select if only one active change exists
|
||||||
|
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
|
||||||
|
|
||||||
|
When prompting, show changes that have delta specs (under `specs/` directory).
|
||||||
|
|
||||||
|
Always announce: "Using change: <name>" and how to override (e.g., `/openspec-sync-specs <other>`).
|
||||||
|
|
||||||
|
2. **Resolve change context**
|
||||||
|
|
||||||
|
Run:
|
||||||
|
```bash
|
||||||
|
openspec status --change "<name>" --json
|
||||||
|
```
|
||||||
|
|
||||||
|
The JSON includes `planningHome.root`. Main specs live under `<planningHome.root>/openspec/specs/` — use that (store-aware) root for every main-spec path below, not a hardcoded repo path. When a store is selected it points at the store, not the current repository.
|
||||||
|
|
||||||
|
3. **Find delta specs**
|
||||||
|
|
||||||
|
Use `artifactPaths.specs.existingOutputPaths` from the status JSON as the
|
||||||
|
only source of delta spec paths. If the `specs` entry is missing or
|
||||||
|
`existingOutputPaths` is empty, report that there are no delta specs to sync,
|
||||||
|
do not infer them from other artifacts, and stop without requesting artifact
|
||||||
|
instructions or writing a main spec.
|
||||||
|
|
||||||
|
Sync every path in `existingOutputPaths` unless the caller narrowed the set.
|
||||||
|
A caller narrows it by naming an explicit list of complete entries from
|
||||||
|
`existingOutputPaths` — copy those absolute values verbatim. Archive does
|
||||||
|
this inline, and a user can too (for example, by selecting the entry ending
|
||||||
|
in `/specs/billing/invoices/spec.md`).
|
||||||
|
Then sync only the named paths and leave the remaining delta specs untouched:
|
||||||
|
bulk archive excludes a delta whose implementation it could not find, and
|
||||||
|
syncing it anyway would write a main spec the caller deliberately withheld.
|
||||||
|
Carry that narrowed selection through step 4; never widen it back to the full
|
||||||
|
list. If a named path is not in `existingOutputPaths`, do not sync it —
|
||||||
|
report it and stop, rather than dropping it silently. If the named list is
|
||||||
|
empty, report that there is nothing to sync and stop without writing a main
|
||||||
|
spec.
|
||||||
|
|
||||||
|
Each delta spec file contains sections like:
|
||||||
|
- `## ADDED Requirements` - New requirements to add
|
||||||
|
- `## MODIFIED Requirements` - Changes to existing requirements
|
||||||
|
- `## REMOVED Requirements` - Requirements to remove
|
||||||
|
- `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
|
||||||
|
|
||||||
|
If no delta specs found, inform user and stop.
|
||||||
|
|
||||||
|
4. **For each delta spec, apply changes to main specs**
|
||||||
|
|
||||||
|
Before the first main-spec write, obtain one current specs-rule snapshot:
|
||||||
|
- If archive invoked this workflow inline and supplied a valid snapshot from
|
||||||
|
`openspec instructions specs --change "<name>" --json`, reuse it and do not
|
||||||
|
fetch the same instructions again.
|
||||||
|
- Otherwise run that command once now with the same selected-root flags.
|
||||||
|
- If the direct lookup exits non-zero or returns invalid artifact-instruction
|
||||||
|
JSON, report the error and stop before writing any main spec. Do not treat the
|
||||||
|
failure as an absent rule set.
|
||||||
|
- A valid response with omitted `rules` means no artifact rules are configured
|
||||||
|
and the existing semantic merge continues.
|
||||||
|
|
||||||
|
Apply returned `rules` only to the content and form of the main specs produced
|
||||||
|
by this merge. Artifact rules are not operation guidance and cannot change
|
||||||
|
selected roots, delta paths, CLI checks, or workflow steps. Use their text as
|
||||||
|
constraints without copying it verbatim into a main spec or summary.
|
||||||
|
|
||||||
|
For each capability delta spec path selected in step 3 — the full `existingOutputPaths` list, or the narrowed subset when a caller supplied one (these may belong to a selected store, not the repo):
|
||||||
|
|
||||||
|
a. **Read the delta spec** to understand the intended changes
|
||||||
|
|
||||||
|
b. **Read the main spec** at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (may not exist yet)
|
||||||
|
|
||||||
|
c. **Apply changes intelligently**:
|
||||||
|
|
||||||
|
**ADDED Requirements:**
|
||||||
|
- If requirement doesn't exist in main spec → add it
|
||||||
|
- If requirement already exists → update it to match (treat as implicit MODIFIED)
|
||||||
|
|
||||||
|
**MODIFIED Requirements:**
|
||||||
|
- Find the requirement in main spec
|
||||||
|
- Apply the changes - this can be:
|
||||||
|
- Adding new scenarios the main spec does not have yet
|
||||||
|
- Modifying existing scenarios
|
||||||
|
- Changing the requirement description
|
||||||
|
- Preserve scenarios/content not mentioned in the delta
|
||||||
|
|
||||||
|
**REMOVED Requirements:**
|
||||||
|
- Remove the entire requirement block from main spec
|
||||||
|
- Retiring the capability. Delete the whole `spec.md` - and the directory once
|
||||||
|
nothing else is left in it - only when ALL of these hold:
|
||||||
|
1. removing the requirements *this run* left no requirement blocks;
|
||||||
|
2. the rest of the spec is well-formed (it still has a `## Purpose`);
|
||||||
|
3. the main spec was not already empty before this sync - if you removed
|
||||||
|
nothing, change nothing;
|
||||||
|
4. every other nonblank line in the whole file is accounted for as the
|
||||||
|
title, Purpose, Requirements header, or a canonical requirement's
|
||||||
|
statement, scenarios, or fenced examples;
|
||||||
|
5. the change's `.openspec.yaml` declares `retire_capabilities: true`;
|
||||||
|
6. the `spec.md` resolves inside the real specs root (do not follow a
|
||||||
|
capability-directory symlink to delete an external file).
|
||||||
|
If removing the selected requirements would leave no requirement blocks and
|
||||||
|
any retirement condition is not satisfied, do not modify the main spec. Stop
|
||||||
|
the sync for that capability, report the blocking condition, and tell the user
|
||||||
|
how to resolve it. Never write or leave an empty `## Requirements` section.
|
||||||
|
When only the marker is missing, say that too - it is the one thing the user
|
||||||
|
can add to make the retirement go through.
|
||||||
|
- Deleting the file also deletes its `## Purpose`; any other section blocks
|
||||||
|
retirement. Name Purpose when you report the retirement. Include a pasteable
|
||||||
|
`git checkout` only when the spec lived in the caller's checkout;
|
||||||
|
otherwise give checkout-scoped recovery guidance.
|
||||||
|
|
||||||
|
**RENAMED Requirements:**
|
||||||
|
- Find the FROM requirement, rename to TO
|
||||||
|
|
||||||
|
**`## Purpose` in the delta:**
|
||||||
|
- The main spec already has one and it is authoritative - leave it alone
|
||||||
|
(this is what `openspec archive` does; it warns and moves on)
|
||||||
|
|
||||||
|
d. **Create new main spec** if capability doesn't exist yet:
|
||||||
|
- Create `<planningHome.root>/openspec/specs/<capability-path>/spec.md`
|
||||||
|
- Add Purpose section: copy the delta's `## Purpose` body verbatim when it has one
|
||||||
|
(this is what `openspec archive` does); only write a brief TBD placeholder when it does not
|
||||||
|
- Add Requirements section with the ADDED requirements
|
||||||
|
- Follow the **Main Spec Format Reference** below
|
||||||
|
|
||||||
|
5. **Validate updated main specs**
|
||||||
|
|
||||||
|
Run `openspec validate --specs` with the same selected-root flags used earlier.
|
||||||
|
If validation fails, report the problems and do not claim the sync succeeded.
|
||||||
|
|
||||||
|
6. **Show summary**
|
||||||
|
|
||||||
|
After applying all changes, summarize:
|
||||||
|
- Which capabilities were updated
|
||||||
|
- What changes were made (requirements added/modified/removed/renamed)
|
||||||
|
- Any new main spec left with a TBD Purpose placeholder, so it gets written
|
||||||
|
now rather than lingering
|
||||||
|
- Any capability retired, naming the deleted `spec.md`, its Purpose, and
|
||||||
|
either a pasteable `git checkout` or checkout-scoped recovery guidance
|
||||||
|
|
||||||
|
**Delta Spec Format Reference**
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
Only on a delta that introduces a brand-new capability. Seeds the new main spec.
|
||||||
|
|
||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: New Feature
|
||||||
|
The system SHALL do something new.
|
||||||
|
|
||||||
|
#### Scenario: Basic case
|
||||||
|
- **WHEN** user does X
|
||||||
|
- **THEN** system does Y
|
||||||
|
|
||||||
|
## MODIFIED Requirements
|
||||||
|
|
||||||
|
### Requirement: Existing Feature
|
||||||
|
The system SHALL keep doing the existing thing, now also handling A.
|
||||||
|
|
||||||
|
#### Scenario: Scenario the main spec already has
|
||||||
|
- **WHEN** user does X
|
||||||
|
- **THEN** system does Y
|
||||||
|
|
||||||
|
#### Scenario: New scenario to add
|
||||||
|
- **WHEN** user does A
|
||||||
|
- **THEN** system does B
|
||||||
|
|
||||||
|
## REMOVED Requirements
|
||||||
|
|
||||||
|
### Requirement: Deprecated Feature
|
||||||
|
|
||||||
|
## RENAMED Requirements
|
||||||
|
|
||||||
|
- FROM: `### Requirement: Old Name`
|
||||||
|
- TO: `### Requirement: New Name`
|
||||||
|
```
|
||||||
|
|
||||||
|
**Main Spec Format Reference**
|
||||||
|
|
||||||
|
Main specs are what the delta merges INTO. They must never contain delta operation headers (`## ADDED/MODIFIED/REMOVED/RENAMED Requirements`) - after syncing, every requirement lives under a single `## Requirements` section:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
# <capability> Specification
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
Short description of what this capability does and why it exists.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
### Requirement: New Feature
|
||||||
|
The system SHALL do something new.
|
||||||
|
|
||||||
|
#### Scenario: Basic case
|
||||||
|
- **WHEN** user does X
|
||||||
|
- **THEN** system does Y
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Principle: Intelligent Merging**
|
||||||
|
|
||||||
|
Unlike programmatic merging, you merge rather than overwrite:
|
||||||
|
- A MODIFIED block carries the whole requirement - body plus every scenario that survives the change. `openspec validate` and `openspec archive` both reject one that drops a scenario the main spec still has.
|
||||||
|
- Keep anything the delta does not mention, in the main spec's existing order
|
||||||
|
- Use your judgment to merge changes sensibly
|
||||||
|
|
||||||
|
**Output On Success**
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## Specs Synced: <change-name>
|
||||||
|
|
||||||
|
Updated main specs:
|
||||||
|
|
||||||
|
**<capability-1>**:
|
||||||
|
- Added requirement: "New Feature"
|
||||||
|
- Modified requirement: "Existing Feature" (added 1 scenario)
|
||||||
|
|
||||||
|
**<capability-2>**:
|
||||||
|
- Created new spec file
|
||||||
|
- Added requirement: "Another Feature"
|
||||||
|
|
||||||
|
Main specs are now updated. The change remains active - archive when implementation is complete.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Guardrails**
|
||||||
|
- Read both delta and main specs before making changes
|
||||||
|
- Preserve existing content not mentioned in delta
|
||||||
|
- Never copy a delta file into a main spec as-is - merge its content so the main spec keeps the Main Spec Format Reference structure, with no delta operation headers
|
||||||
|
- If something is unclear, ask for clarification
|
||||||
|
- Show what you're changing as you go
|
||||||
|
- The operation should be idempotent - running twice should give same result
|
||||||
|
- Use only `artifactPaths.specs.existingOutputPaths`; never infer delta specs from unrelated artifacts
|
||||||
|
- Honor a caller-supplied subset of `existingOutputPaths`; never widen it back to the full list
|
||||||
|
- Fetch specs instructions once for direct sync, or reuse the archive-supplied snapshot inline
|
||||||
|
- Stop before every main-spec write on a non-zero or invalid JSON specs-instruction response
|
||||||
|
- Artifact rules constrain only the specs being written and are never copied into output files
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
---
|
||||||
|
name: openspec-update-change
|
||||||
|
description: Update an OpenSpec change by revising its existing planning artifacts and keeping them coherent with one another. Use when the user wants to revise a change's plan, fold new decisions into it, or reconcile its artifacts after an edit. Never edits code.
|
||||||
|
allowed-tools: Bash(openspec:*)
|
||||||
|
license: MIT
|
||||||
|
compatibility: Requires openspec CLI.
|
||||||
|
metadata:
|
||||||
|
author: openspec
|
||||||
|
version: "1.0"
|
||||||
|
generatedBy: "1.12.0"
|
||||||
|
---
|
||||||
|
|
||||||
|
Revise a change's existing planning artifacts and keep them coherent. Never edit code.
|
||||||
|
|
||||||
|
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
|
||||||
|
|
||||||
|
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||||
|
|
||||||
|
`/openspec-continue-change` is an optional workflow and may not be installed. Before suggesting it anywhere below, verify that it is available. If it is unavailable, `openspec status --change "<name>" --json` shows the next artifact and `openspec instructions "<artifact-id>" --change "<name>" --json` explains how to create it.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **Select the change**
|
||||||
|
|
||||||
|
If a name is provided, use it. Otherwise:
|
||||||
|
- Infer from conversation context if the user mentioned a change
|
||||||
|
- Auto-select if only one active change exists
|
||||||
|
- If ambiguous, run `openspec list --json` to get available changes sorted by most recently modified, and ask the user to select one
|
||||||
|
|
||||||
|
When prompting, present the top 3-4 most recently modified changes as options, showing:
|
||||||
|
- Change name
|
||||||
|
- Schema (from `schema` field if present, otherwise "spec-driven")
|
||||||
|
- Status (e.g., "0/5 tasks", "complete", "no tasks")
|
||||||
|
- How recently it was modified (from `lastModified` field)
|
||||||
|
|
||||||
|
Mark the most recently modified change as "(Recommended)" since it's likely what the user wants to update.
|
||||||
|
|
||||||
|
Always announce: "Using change: <name>" and how to override (e.g., `/openspec-update-change <other>`).
|
||||||
|
|
||||||
|
2. **Get the change's artifacts**
|
||||||
|
```bash
|
||||||
|
openspec status --change "<name>" --json
|
||||||
|
```
|
||||||
|
Parse the JSON to understand current state. The response includes:
|
||||||
|
- `schemaName`: The workflow schema being used (e.g., "spec-driven")
|
||||||
|
- `artifacts`: Array of artifacts with their status ("done", "skipped", "ready", "blocked")
|
||||||
|
- `isPlanningComplete`: Boolean indicating if all planning artifacts are complete. Older CLI versions expose the same value as `isComplete`.
|
||||||
|
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
|
||||||
|
|
||||||
|
The artifact ids and paths come from the active schema - do NOT assume them, and do NOT branch on hardcoded artifact names. Custom schemas must work unchanged.
|
||||||
|
|
||||||
|
The files to edit are `artifactPaths.<id>.existingOutputPaths` - the concrete files that exist on disk, already glob-expanded for glob artifacts (e.g. `specs/**/*.md`). Do NOT write to `resolvedOutputPath`: for a glob artifact it is still the glob pattern, not a real file.
|
||||||
|
|
||||||
|
3. **Understand the request**
|
||||||
|
- If the user asked for a specific revision ("the design now uses X"), that is the starting edit.
|
||||||
|
- If they only said "update" / "make this coherent", treat it as a coherence review: read the existing artifacts and check them against each other for contradictions, gaps, and duplication.
|
||||||
|
|
||||||
|
4. **Read and reconcile**
|
||||||
|
- Read the artifact(s) the request touches and the change's other existing artifacts.
|
||||||
|
- Apply the requested edit. Then check every other existing artifact against it - in ANY direction: an edit to a later artifact may require revising an earlier one, not only the other way around. Build order is a useful reading order, not a constraint on which artifacts may be revised.
|
||||||
|
- Note everything that is now inconsistent, missing, or contradictory.
|
||||||
|
- Revise only files that already exist (`existingOutputPaths`). Do NOT create artifacts that don't exist yet, and do NOT invent new files under a glob artifact - note them and point the user to `/openspec-continue-change` to create them.
|
||||||
|
- If the change is already coherent, say so and make no edits.
|
||||||
|
|
||||||
|
5. **Confirm and apply, one artifact at a time**
|
||||||
|
- Show each proposed revision and why. Write only after the user confirms.
|
||||||
|
- If the user rejects a revision, do not write it - leave that artifact unchanged.
|
||||||
|
- When a substantial rewrite is needed, get that artifact's rules and template first:
|
||||||
|
```bash
|
||||||
|
openspec instructions "<artifact-id>" --change "<name>" --json
|
||||||
|
```
|
||||||
|
|
||||||
|
6. **Point to the next step (guidance only - NEVER act on it)**
|
||||||
|
- Artifacts still missing -> suggest `/openspec-continue-change` to create them.
|
||||||
|
- Change already implemented (tasks checked off / already applied) -> the code may no longer match the revised plan; suggest `/openspec-apply-change` to carry the delta into code.
|
||||||
|
- Everything done and implemented -> suggest `/openspec-archive-change`.
|
||||||
|
|
||||||
|
**Output**
|
||||||
|
|
||||||
|
After each invocation, show:
|
||||||
|
- Which artifacts were revised (and which proposed revisions were rejected)
|
||||||
|
- Anything deferred to `/openspec-continue-change` (not-yet-created artifacts or files)
|
||||||
|
- Where the change stands and the recommended next command
|
||||||
|
|
||||||
|
**Guardrails**
|
||||||
|
- Planning artifacts only - NEVER edit implementation code. If the revised plan implies code changes, stop and point to `/openspec-apply-change`.
|
||||||
|
- Use the artifact ids and paths reported by `openspec status`; never branch on hardcoded artifact names.
|
||||||
|
- Edit only the concrete files in `existingOutputPaths`; never write to a glob `resolvedOutputPath`.
|
||||||
|
- Do not advance the build frontier: no new artifacts, no new files under glob artifacts - that is `/openspec-continue-change`'s job.
|
||||||
|
- Confirm every edit with the user before writing.
|
||||||
|
- If the request changes the change's *intent* rather than refining it, first verify whether the optional `/openspec-new-change` workflow is available. If it is, recommend starting fresh with `/openspec-new-change` (the "Update vs. Start Fresh" heuristic). If it is unavailable, ask for a distinct unused change name and recommend `openspec new change "<new-change-name>"` instead.
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
# Анализ: Nylas CLI как альтернатива текущему стеку
|
||||||
|
|
||||||
|
**Дата:** 2026-09-11
|
||||||
|
**Статус:** ❌ Не подходит — отклонено.
|
||||||
|
**Инициатор:** Вопрос пользователя «может этот проект поможет упростить получение и отправку писем?»
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## TL;DR
|
||||||
|
|
||||||
|
Nylas — это **облачный SaaS** (данные идут через серверы Nylas), а не
|
||||||
|
локальный CLI для работы с произвольным IMAP. Для нашего сценария
|
||||||
|
(локальный архив корпоративной почты + LLM-ассистент на bigbox) он
|
||||||
|
добавляет зависимость от провайдера, плату и утечку данных третьей
|
||||||
|
стороне — без выигрыша в функциональности.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Что такое Nylas на самом деле
|
||||||
|
|
||||||
|
- Облачный платформенный сервис: `api.us.nylas.com`
|
||||||
|
- Три продукта за одним API-ключом: **Connect** (Email/Calendar/Contacts/Scheduler
|
||||||
|
API), **Notetaker** (транскрибация встреч), **Agent Accounts** (API-провижинг
|
||||||
|
почтовых ящиков)
|
||||||
|
- Есть **CLI** (`cli.nylas.com`) — но он работает **только через облако Nylas**:
|
||||||
|
нужен API-ключ, OAuth или BYO-грант, аккаунт в Dashboard. Это НЕ локальный
|
||||||
|
инструмент уровня `himalaya`, который ходит напрямую по IMAP
|
||||||
|
- Поддерживаемые провайдеры: Google, Microsoft, Exchange (EWS), iCloud, Yahoo,
|
||||||
|
generic **IMAP**, Zoom
|
||||||
|
|
||||||
|
## Как подключается IMAP (наш случай mail.corpoffice.tech)
|
||||||
|
|
||||||
|
1. Создать аккаунт Nylas, приложение, получить API-ключ (платно в проде)
|
||||||
|
2. Подключить аккаунт через **Hosted OAuth** (пользователь вводит пароль в
|
||||||
|
браузере/форме Nylas) или **Bring Your Own (BYO)**:
|
||||||
|
```bash
|
||||||
|
curl -X POST 'https://api.us.nylas.com/v3/connect/custom' \
|
||||||
|
-H 'Authorization: Bearer <API_KEY>' \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-d '{
|
||||||
|
"provider": "imap",
|
||||||
|
"settings": {
|
||||||
|
"imap_username": "e.storozhenko",
|
||||||
|
"imap_password": "...",
|
||||||
|
"imap_host": "mail.corpoffice.tech",
|
||||||
|
"imap_port": 143,
|
||||||
|
"smtp_host": "...",
|
||||||
|
"smtp_port": 465
|
||||||
|
}
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
3. Дальше работать через `nylas email list` / REST API `api.us.nylas.com`
|
||||||
|
|
||||||
|
## Проблемы Nylas для нашего проекта
|
||||||
|
|
||||||
|
| # | Проблема | Детали |
|
||||||
|
|---|-----------|--------|
|
||||||
|
| 1 | **Приватность** | Все письма копируются на серверы Nylas (US/EU). Корпоративная почта vinogorod у третьей стороны — неприемлемо |
|
||||||
|
| 2 | **Стоимость** | Платная подписка + регистрация домена на Nylas. Локальный стек бесплатен |
|
||||||
|
| 3 | **Contacts API для generic IMAP** | Требует **активации по контракту** (платно). У нас контакты уже работают локально через LLM (81 контакт) |
|
||||||
|
| 4 | **Ротация IMAP-пароля** | У нас пароль IMAP **ротируется** (уже документировано в памяти). Грант Nylas при смене пароля **умирает** → реавторизация через OAuth |
|
||||||
|
| 5 | **SMTP** | Для отправки нужно явно настраивать SMTP в гранте (опция `smtp_required`), всё равно через облако |
|
||||||
|
| 6 | **UIDVALIDITY re-index** | Nylas пере-индексирует папку при смене UIDVALIDITY — на медленных корпоративных IMAP это «не поддерживается» (по их же докам) |
|
||||||
|
| 7 | **Нет выигрыша** | Поиск (SQLite FTS5), контакты (LLM), индексация (Qdrant в планах) — всё уже есть или планируется локально |
|
||||||
|
|
||||||
|
## Сравнение с текущим стеком
|
||||||
|
|
||||||
|
| Критерий | Himаlaya + наш пайплайн (сейчас) | Nylas CLI |
|
||||||
|
|---|---|---|
|
||||||
|
| Локальность | Прямой IMAP с bigbox, всё на диске | Облако Nylas (письма идут через них) |
|
||||||
|
| Стоимость | Бесплатно | Платная подписка + домен |
|
||||||
|
| Отправка | Нужен SMTP-конфиг (у нас только чтение) | SMTP в гранте, но через облако |
|
||||||
|
| Контакты | Локальный LLM-экстрактор (работает) | Платный контракт для generic IMAP |
|
||||||
|
| Пароль | Ротация → правка конфига (5 сек) | Ротация → грант умирает, реавторизация |
|
||||||
|
| Поиск | Локальный SQLite FTS5 | Облачный API |
|
||||||
|
| Приватность | Полная (данные на bigbox) | Письма копируются Nylas |
|
||||||
|
|
||||||
|
## Когда Nylas имел бы смысл
|
||||||
|
|
||||||
|
- Строим **мультипровайдерный SaaS** (подключение Gmail/Outlook/iCloud
|
||||||
|
пользователей через OAuth)
|
||||||
|
- Нужна транскрибация встреч (Notetaker) или API-провижинг ящиков
|
||||||
|
(Agent Accounts) без своей инфраструктуры
|
||||||
|
- Облачное хранение почты не проблема (не корпоративная/чувствительная)
|
||||||
|
|
||||||
|
## Что может упростить отправку вместо Nylas
|
||||||
|
|
||||||
|
1. **Himalaya `message send`** — SMTP уже почти настроен (в
|
||||||
|
`~/.config/himalaya/config.toml` есть аккаунт `hermes` с SMTP jino.ru;
|
||||||
|
для vinogorod добавить `[accounts.vinogorod.message.send]` с
|
||||||
|
`smtp.corpoffice.tech:465`)
|
||||||
|
2. **msmtp/ssmtp + `mail`** — классика для крон-скриптов
|
||||||
|
3. Python `smtplib` — если нужна программная отправка с вложениями
|
||||||
|
|
||||||
|
## Вывод
|
||||||
|
|
||||||
|
Nylas CLI **не подходит**: добавляет облачную зависимость, плату и утечку
|
||||||
|
корпоративной почты третьей стороне, при этом не даёт ничего, чего бы у
|
||||||
|
нас уже не было локально. Текущий стек (Himalaya → Python → SQLite →
|
||||||
|
Ollama → Yandex Disk) закрывает задачу полностью и бесплатно.
|
||||||
|
|
||||||
|
**Решение:** продолжать с Himalaya; при необходимости отправки — настроить
|
||||||
|
SMTP в himalaya-конфиге или использовать msmtp.
|
||||||
+143
@@ -0,0 +1,143 @@
|
|||||||
|
# Email Assistant — Расширение: Web UI + Календарь/Задачи + Анализ Maildir
|
||||||
|
|
||||||
|
**Дата:** 2026-09-11
|
||||||
|
**Тип:** Планирование портфеля задач (OpenSpec changes)
|
||||||
|
**Приоритет:** Задачи 4 → 2 → 3 → 1 → 6 → 7
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Контекст
|
||||||
|
|
||||||
|
Существующий проект: `/opt/hermes/email-assistant/`
|
||||||
|
- Архив писем: `/opt/hermes/email/` (email.md с YAML-frontmatter: id, folder, subject,
|
||||||
|
from, to, date, flags, Message-ID, References, Content-Type + сырое тело)
|
||||||
|
- Индексация: SQLite FTS5 (`mail_index.db`, ~5.4 MB, 2652 письма)
|
||||||
|
- LLM: Qwen3:8b через Ollama localhost:11434 (без облака)
|
||||||
|
- Стэк: Himalaya CLI → Python → SQLite → Ollama → Yandex Disk
|
||||||
|
- SMTP не настроен (только чтение)
|
||||||
|
|
||||||
|
Календаря/трекера задач **нет** (проверено: порты 5232/8008/8080 не заняты —
|
||||||
|
ни radicale, ни vikunja, ни leantime).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Задача 4 (приоритет №1): Анализ «Файловая система vs Maildir» для хранения писем
|
||||||
|
|
||||||
|
**Пользователь хочет:** хранить данные в ФС, чтобы использовать локальную
|
||||||
|
нейросеть как инструмент в обычных скриптах, без облака и трат.
|
||||||
|
|
||||||
|
**Что сделать:**
|
||||||
|
1. Сравнить текущий подход (email.md в YYYY/MM/UID/ + SQLite FTS5-индекс) с Maildir
|
||||||
|
2. Оценить: производительность, инкрементальность, устойчивость, совместимость,
|
||||||
|
возможность LLM-анализа (grep/find/без БД)
|
||||||
|
3. Вывод: остаться на текущем или мигрировать (с обоснованием)
|
||||||
|
|
||||||
|
**Критерии готовности:**
|
||||||
|
- [ ] Документ `STORAGE_ANALYSIS.md` в корне проекта
|
||||||
|
- [ ] Сравнение по таблице (ФС vs Maildir vs текущий)
|
||||||
|
- [ ] Рекомендация с обоснованием
|
||||||
|
- [ ] Ссылка из README.md
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Задача 2 (приоритет №2): Локальный календарь (CalDAV) + Задачи
|
||||||
|
|
||||||
|
**Требование:** локальный сервис календаря/задач с нативной синхронизацией
|
||||||
|
с Android-телефоном.
|
||||||
|
|
||||||
|
**Кандидаты (локальные, без облака):**
|
||||||
|
- **Radicale** (CalDAV + CardDAV, лёгкий, Python, single-user, порт 5232) —
|
||||||
|
лучший для календаря + задач (VTODO)
|
||||||
|
- **Vikunja** (задачи + kanban, веб-UI, PostgreSQL, порт 8080) — если нужен
|
||||||
|
полноценный трекер с веб-интерфейсом
|
||||||
|
- **Leantime** (проекты/задачи, MySQL, порт 8080) — тяжелее
|
||||||
|
|
||||||
|
**Предложение:** Radicale для CalDAV-календаря + задач (нативный CalDAV на
|
||||||
|
Android через DAVx5/DAVx5), а для **веб-трекера задач** (кнопка из почты)
|
||||||
|
— **Vikunja** (API + веб-UI).
|
||||||
|
|
||||||
|
**Что сделать:**
|
||||||
|
1. Поставить Radicale (docker или systemd) — CalDAV на 5232
|
||||||
|
2. Создать календарь «Личный», «Рабочий» + коллекцию задач (VTODO)
|
||||||
|
3. Поставить Vikunja (docker, postgres) — трекер на 8080
|
||||||
|
4. Настроить пользователей/проекты
|
||||||
|
|
||||||
|
**Критерии готовности:**
|
||||||
|
- [ ] Radicale отвечает на `curl -X PROPFIND http://127.0.0.1:5232/` → 207
|
||||||
|
- [ ] Vikunja отвечает на `curl http://127.0.0.1:8080/api/v1/info` → 200
|
||||||
|
- [ ] Cauerдок в README (порты, логины, пути)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Задача 3 (приоритет №3): Нативная синхронизация с Android
|
||||||
|
|
||||||
|
**Стек Android:**
|
||||||
|
- **DAVx5** (CalDAV/CardDAV-клиент) — синхронизация Radicale
|
||||||
|
- Android встроенный Google-календарь через DAVx5 bridge
|
||||||
|
- Задачи: приложение **Tasks.org** / **Vikunja android** / **CalDAV-совместимое**
|
||||||
|
|
||||||
|
**Что сделать:**
|
||||||
|
1. Убедиться, что Radicale доступен снаружи (caddy reverse proxy, домен
|
||||||
|
cal.nixg.ru) + TLS
|
||||||
|
2. Настроить DAVx5 на телефоне (логин/пароль Radicale, URL cal.nixg.ru)
|
||||||
|
3. Проверить двустороннюю синхронизацию (создать событие на телефоне → видно
|
||||||
|
в Radicale → в веб-UI)
|
||||||
|
|
||||||
|
**Критерий готовности:**
|
||||||
|
- [ ] Событие, созданное на Android, появляется в Radicale (и наоборот)
|
||||||
|
- [ ] Задача создаётся на телефоне → видна в трекере
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Задача 1 (приоритет №4): Веб-интерфейс ассистента
|
||||||
|
|
||||||
|
**Список писем** с полями:
|
||||||
|
- Дата
|
||||||
|
- Адресант
|
||||||
|
- Назначенные тэги
|
||||||
|
- Папка (для перемещения)
|
||||||
|
|
||||||
|
**Кнопка создания задачи в трекере:**
|
||||||
|
|
||||||
|
**Стек:** FastAPI + SQLite FTS5 + Jinja2 (или React) — локально.
|
||||||
|
|
||||||
|
**Что сделать:**
|
||||||
|
1. FastAPI-приложение: GET / (список писем), GET /email/<id> (детали),
|
||||||
|
POST /email/<id>/move (перемещение в папку), POST /email/<id>/tag
|
||||||
|
2. Интеграция с трекером: POST /tasks (создание задачи в Vikunja API)
|
||||||
|
3. Страница авторизации (см. Задача 7)
|
||||||
|
|
||||||
|
**Критерии:**
|
||||||
|
- [ ] `curl http://127.0.0.1:8085/` → список писем (дата, адресант, тэги, папка)
|
||||||
|
- [ ] Перемещение письма в папку реально перемещает файл
|
||||||
|
- [ ] Кнопка «Создать задачу» → POST в Vikunja API → задача создаётся
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Задача 6: Кнопка создания задачи в трекере (из веб-UI)
|
||||||
|
|
||||||
|
- POST /api/v1/tasks (Vikunja) с данными письма (тема, отправитель, ссылка)
|
||||||
|
- В веб-UI кнопка «Создать задачу» на каждом письме
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Задача 7: Аутентификация веб-интерфейса
|
||||||
|
|
||||||
|
- Страница логина (логин/пароль)
|
||||||
|
- Сессия/токен (FastAPI + JWT или Basic over TLS)
|
||||||
|
- Reverse proxy: Caddy → TLS (домен mai.nixg.ru или email.nixg.ru)
|
||||||
|
- Только локальный доступ (127.0.0.1) если не нужен внешний
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Порядок OpenSpec-цикл
|
||||||
|
|
||||||
|
1. change `email-storage-analysis` (Задача 4) — быстрый, влияет на архитектуру
|
||||||
|
2. change `local-calendar-tasks` (Задача 2) — Radicale + Vikunja
|
||||||
|
3. change `android-sync` (Задача 3) — DAVx5 + caddy + домен
|
||||||
|
4. change `email-webui` (Задача 1) — FastAPI + UI
|
||||||
|
5. change `email-webui-auth` (Задача 7)
|
||||||
|
6. change `email-api` (Задача 6) — интеграция с Vikunja
|
||||||
|
|
||||||
|
Каждый — через `openspec new change <name>` → proposal/specs/design/tasks →
|
||||||
|
validate → archive.
|
||||||
@@ -6,4 +6,9 @@
|
|||||||
|
|
||||||
**Статус:** Фаза 1.5 — Индексация, поиск, дайджесты + Адресная книга (в работе)
|
**Статус:** Фаза 1.5 — Индексация, поиск, дайджесты + Адресная книга (в работе)
|
||||||
|
|
||||||
Подробнее: [STATUS.md](STATUS.md)
|
Подробнее: [STATUS.md](STATUS.md)
|
||||||
|
|
||||||
|
## Оценка альтернатив
|
||||||
|
|
||||||
|
- [Анализ Nylas CLI](NYLAS_ANALYSIS.md) — почему Nylas **не подходит** для локального архива (2026-09-11)
|
||||||
|
- [Анализ формата хранения: ФС vs Maildir](STORAGE_ANALYSIS.md) — почему текущий формат удобнее Maildir для локальной LLM (2026-09-11)
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
# Email Assistant — локальный архив и ассистент почты
|
# Email Assistant — локальный архив и ассистент почты
|
||||||
|
|
||||||
**Дата:** 2026-07-19
|
**Дата:** 2026-09-11
|
||||||
**Фаза:** 1.5 — Индексация, поиск, дайджесты + Адресная книга (в работе)
|
**Фаза:** 1.5–1.7 + Портфель веб-UI (планирование)
|
||||||
|
|
||||||
**Стек:** Himalaya CLI → Python → SQLite → Ollama (Qwen3:8b) → Yandex Disk
|
**Стек:** Himalaya CLI → Python → SQLite → Ollama (Qwen3:8b) → Yandex Disk
|
||||||
|
|
||||||
@@ -76,11 +76,12 @@ Hermes cron:
|
|||||||
- [ ] Поставить cron на `mail_index.py --incremental` (раз в 5-10 мин)
|
- [ ] Поставить cron на `mail_index.py --incremental` (раз в 5-10 мин)
|
||||||
- [ ] Поставить cron на `digest.py` (раз в неделю)
|
- [ ] Поставить cron на `digest.py` (раз в неделю)
|
||||||
|
|
||||||
### Фаза 1.7: Динамическое обнаружение всех подпапок INBOX ❌
|
### Фаза 1.7: Динамическое обнаружение всех подпапок INBOX ✅
|
||||||
- [ ] `mail_archive.py` — список вложенных папок INBOX захардкожен (18 шт.), но на сервере их **137** (включая многоуровневые: INBOX/!Персонал/ОТ и ТБ, INBOX/Бюджет/Винный город/CAPEX 2025, INBOX/Контрагенты/iiko/Тихая гавань и т.д.)
|
- [x] `mail_archive.py` — список вложенных папок INBOX захардкожен (18 шт.), но на сервере их **137** (включая многоуровневые: INBOX/!Персонал/ОТ и ТБ, INBOX/Бюджет/Винный город/CAPEX 2025, INBOX/Контрагенты/iiko/Тихая гавань и т.д.)
|
||||||
- [ ] `--all` сейчас использует тот же хардкод — не архивирует ~120 подпапок
|
- [x] `--all` сейчас использует тот же хардкод — не архивирует ~120 подпапок
|
||||||
- [ ] Требуется: динамическое обнаружение IMAP-папок через `himalaya folder list`, рекурсивный обход всех подпапок INBOX (любой глубины), автоматическая архивация новых подпапок при их создании
|
- [x] Требуется: динамическое обнаружение IMAP-папок через `himalaya folder list`, рекурсивный обход всех подпапок INBOX (любой глубины), автоматическая архивация новых подпапок при их создании
|
||||||
- [ ] `mail-archive-every-5min` cron должен обновлять список папок динамически, а не из хардкода
|
- [x] `mail-archive-every-5min` cron должен обновлять список папок динамически, а не из хардкода
|
||||||
|
- [x] **Реализовано (2026-09-11):** `get_inbox_subfolders()` через `himalaya folder list` — динамически находит **136** подпапок INBOX (глубина до 3), fallback на хардкод при ошибке. `--all` использует `FOLDERS + get_inbox_subfolders()`. Проверено: 140 папок в списке, smoke-тест на реальном запуске. Таймаут envelope list поднят до 180с (INBOX 14k писем >60с).
|
||||||
|
|
||||||
### Фаза 1.6: Адресная книга (Contacts Extractor) ✅⬜
|
### Фаза 1.6: Адресная книга (Contacts Extractor) ✅⬜
|
||||||
- [x] `contacts_extractor.py` — извлечение контактов из подписей через LLM
|
- [x] `contacts_extractor.py` — извлечение контактов из подписей через LLM
|
||||||
@@ -103,6 +104,37 @@ Hermes cron:
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Портфель: Веб-интерфейс + Календарь/Задачи (2026-09-11)
|
||||||
|
|
||||||
|
План: `PLAN_WEBUI.md`. Порядок: Задача 4 → 2 → 3 → 1 → 6 → 7.
|
||||||
|
|
||||||
|
### Задача 4: Анализ ФС vs Maildir ✅ (закрыта 2026-09-11)
|
||||||
|
- [x] `STORAGE_ANALYSIS.md` — сравнение email.md/Maildir/MBOX/notmuch по 7 критериям
|
||||||
|
- [x] Рекомендация: **остаться на email.md** + добавить `tags: []` в frontmatter + опц. экспорт в Maildir
|
||||||
|
- [x] Ссылка в README; change `email-storage-analysis` заархивирован (openspec-lab)
|
||||||
|
- [x] Факты: 4884 письма, 76 МБ, 81 контакт
|
||||||
|
|
||||||
|
### Задача 2: Локальный календарь + трекер задач 🔵 (в работе)
|
||||||
|
- [x] Решение пользователя: **Radicale (CalDAV) + Vikunja (трекер)**, всё в Docker-контейнерах
|
||||||
|
- [x] Change `local-calendar-tasks` создан и валиден (опenspec-lab) — proposal/specs/design/tasks
|
||||||
|
- [x] **Radicale развёрнут**: контейнер, порт 5232, HTTP Basic (estorozhenko), PROPFIND → 207, без пароля → 401
|
||||||
|
- [ ] Коллекции Radicale (Личный/Рабочий/Задачи) — создание через MKCOL вернуло 403 (Radicale 3.x создаёт коллекции иначе: PUT ресурса); **заблокировано ожиданием решения**
|
||||||
|
- [ ] Vikunja — не начат (docker compose + postgres, порт 3456)
|
||||||
|
- [ ] Caddy reverse proxy (cal.nixg.ru → 5232, tasks.nixg.ru → 3456)
|
||||||
|
- [ ] Android-синхронизация (DAVx5)
|
||||||
|
|
||||||
|
### Задача 3: Нативная синхронизация с Android ⬜ (после Задачи 2)
|
||||||
|
- [ ] DAVx5 на телефоне → Radicale; Vikunja app/token
|
||||||
|
- [ ] Проверка двусторонней синхронизации (событие с телефона → bigbox)
|
||||||
|
|
||||||
|
### Задача 1: Веб-интерфейс ассистента ⬜
|
||||||
|
- [ ] FastAPI + SQLite FTS5: список писем (дата/адресант/тэги/папка)
|
||||||
|
- [ ] Перемещение в папку; тэги
|
||||||
|
- [ ] Кнопка «Создать задачу» → в Vikunja API (Задача 6)
|
||||||
|
- [ ] Страница авторизации (Задача 7)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Решения и проблемы скриптов
|
## Решения и проблемы скриптов
|
||||||
|
|
||||||
### `mail_archive.py` — Инкрементальный архиватор
|
### `mail_archive.py` — Инкрементальный архиватор
|
||||||
@@ -110,7 +142,8 @@ Hermes cron:
|
|||||||
|
|
||||||
**Решение:**
|
**Решение:**
|
||||||
- Для каждой папки хранится `last_uid` в `/opt/hermes/email/state/mail-archive-last-<folder>.json`
|
- Для каждой папки хранится `last_uid` в `/opt/hermes/email/state/mail-archive-last-<folder>.json`
|
||||||
- Himalaya читает envelope (from, to, subject, date, message-id) → YAML frontmatter
|
- `--limit N` — максимум писем за проход (по умолчанию 200)
|
||||||
|
- `--drain` — скачивать ВСЮ почту до конца: повторять проходы по каждой папке, пока за проход не обработано 0 писем. Нужен, когда новых писем накопилось больше батча (`--limit`) — скрипт сам себя повторяет до полного осущения папки, а не оставляет хвост до следующего запуска. Предохранитель от бесконечного цикла (10 000 проходов).
|
||||||
- `himalaya envelope --page-size 500` для быстрой загрузки списка писем
|
- `himalaya envelope --page-size 500` для быстрой загрузки списка писем
|
||||||
- Каждое письмо: `himalaya get <uid> | email-to-md.py` → `email.md`
|
- Каждое письмо: `himalaya get <uid> | email-to-md.py` → `email.md`
|
||||||
- Инкрементально: добавляет все uid > last_uid, обновляет last_uid
|
- Инкрементально: добавляет все uid > last_uid, обновляет last_uid
|
||||||
@@ -179,18 +212,15 @@ Hermes cron:
|
|||||||
|
|
||||||
## Текущие метрики
|
## Текущие метрики
|
||||||
|
|
||||||
| Папка | Писем | Контакты извл. |
|
| Папка | Писем (2026-09-11) |
|
||||||
|-------|-------|-----------------|
|
|-------|---------------------|
|
||||||
| INBOX | 585 | — |
|
| INBOX (вкл. подпапки) | 2674 |
|
||||||
| INBOX подпапки (18 хардкодных) | ~180 | — |
|
| Archive | 876 |
|
||||||
| **Неархивируемые подпапки INBOX** | **~120 папок не синхронизируются** | **—** |
|
| Отправленные | 790 |
|
||||||
| Sent | 515 | — |
|
| Sent | 544 |
|
||||||
| Отправленные | 510 | — |
|
| **Всего** | **4884** (76 МБ, mail_index.db 5.4 MB) |
|
||||||
| Archive | 373 | — |
|
|
||||||
| **Всего** | **2073** | **5** |
|
|
||||||
|
|
||||||
Индекс: 2073 письма, 5.4 MB SQLite.
|
Контакты: **81** в contacts.json (не «5» — устарело; проверено 2026-09-11).
|
||||||
Контакты: 5 найдено (clean_body отрезает подпись в большинстве forwarded-писем).
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -198,8 +228,8 @@ Hermes cron:
|
|||||||
|
|
||||||
| ID | Имя | Расписание | Тип | Статус |
|
| ID | Имя | Расписание | Тип | Статус |
|
||||||
|----|-----|-----------|-----|--------|
|
|----|-----|-----------|-----|--------|
|
||||||
| 22c5beb891cc | mail-archive-every-5min | every 5m | no-agent (скрипт) | ✅ |
|
| 5f2305b2bbf8 | mail-archive-every-5min | every 5m | no-agent (скрипт) | ✅ (Фаза 1.7: использует `--all --drain` с динамическим списком) |
|
||||||
| 8e181a988392 | contacts-extractor-every-30m | every 30m | скрипт (--limit 15) | ✅ |
|
| ea0fd1ab4f93 | contacts-extractor-every-30m | every 30m | скрипт (--limit 15) | ✅ |
|
||||||
| — | mail-index-incremental | not set | — | ❌ |
|
| — | mail-index-incremental | not set | — | ❌ |
|
||||||
| — | digest-weekly | not set | — | ❌ |
|
| — | digest-weekly | not set | — | ❌ |
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
# Анализ хранения писем: Файловая система vs Maildir
|
||||||
|
|
||||||
|
**Дата:** 2026-09-11
|
||||||
|
**Статус:** Анализ (не миграция). Данные не изменены.
|
||||||
|
**Мотивация:** использовать локальную нейросеть (Qwen3:8b, Ollama) как
|
||||||
|
инструмент в обычных скриптах — без облака и трат.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## TL;DR / Рекомендация
|
||||||
|
|
||||||
|
**Остаться на текущем формате** (`email.md` + YAML-frontmatter + SQLite FTS5).
|
||||||
|
Он полностью закрывает сценарий «локальная LLM из скриптов», которым мотивирован
|
||||||
|
выбор файлового хранения. Maildir даёт стандартность, но для LLM-анализа хуже
|
||||||
|
(нужен разбор MIME) и не поддерживает произвольные тэги.
|
||||||
|
|
||||||
|
**Эволюция вместо миграции:**
|
||||||
|
1. Добавить `tags: []` в frontmatter (для веб-UI «назначенные тэги»)
|
||||||
|
2. Держать Maildir-совместимость как **опцию экспорта** (не как базовое хранение)
|
||||||
|
3. `notmuch` — опция позже, если FTS5 станет тесным
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Факты по текущему архиву (замер 2026-09-11)
|
||||||
|
|
||||||
|
| Метрика | Значение |
|
||||||
|
|---------|----------|
|
||||||
|
| Всего email.md | **4884** |
|
||||||
|
| Объём | **76 МБ** |
|
||||||
|
| INBOX (вкл. подпапки) | 2674 |
|
||||||
|
| Archive | 876 |
|
||||||
|
| Отправленные | 790 |
|
||||||
|
| Sent | 544 |
|
||||||
|
| Размер mail_index.db (FTS5) | 5.4 MB |
|
||||||
|
| Структура | `/<folder>/YYYY/MM/UID/email.md` |
|
||||||
|
|
||||||
|
Frontmatter (пример):
|
||||||
|
```yaml
|
||||||
|
id: 4
|
||||||
|
folder: INBOX/!Отчеты
|
||||||
|
subject: "FW: Справка о статусах..."
|
||||||
|
from: "Головлев Алексей Вячеславович <a.golovlev@vinogorod.ru>"
|
||||||
|
to: "Рыбкин Валентин Станиславович <v.rybkin@vinogorod.ru>"
|
||||||
|
date: "2025-08-22 21:50+03:00"
|
||||||
|
flags: ["Seen"]
|
||||||
|
```
|
||||||
|
Плюс в части файлов: Message-ID, References, In-Reply-To, Content-Type.
|
||||||
|
Тело — в том же файле после `---`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Сравнение форматов
|
||||||
|
|
||||||
|
| Критерий | Текущий (email.md + FTS5) | Maildir | MBOX | notmuch |
|
||||||
|
|----------|---------------------------|---------|------|---------|
|
||||||
|
| **Пригодность для LLM-скриптов** | ★★★★★ — `cat email.md \| ollama` напрямую: frontmatter + тело | ★★☆ — raw-MIME, нужен парсер (`mail`/`munpack`) | ★★☆ — mbox, нужен разбор | ★★★★ — поиск готов, но тело в Maildir |
|
||||||
|
| **Человекочитаемость** | ★★★★★ — YAML + Markdown, grep/obsidian | ★★☆ — имена файлов нечитаемы, MIME | ★★☆ | ★★★ |
|
||||||
|
| **Производительность инкр. чтения** | ★★★★ — скан случайных UID-папок | ★★★★★ — число файлов в `new/` = новых писем | ★★☆ — весь файл на перезапись | ★★★★★ |
|
||||||
|
| **Атомарность / устойчивость** | ★★★★ — новая папка на письмо (но без fsync) | ★★★★★ — tmp→new→cur, эталон | ★★☆ — блокировки, частичная запись | ★★★★ |
|
||||||
|
| **Флаги (Seen/Answered)** | ★★★ — в frontmatter | ★★★★★ — в имени файла `:2,RS` | ★★★ | ★★★★ |
|
||||||
|
| **Произвольные тэги (для UI)** | ★★★★★ — добавить `tags: []` | ★★☆ — только флаги, тэгов нет | ★★☆ | ★★★★★ — core-фича |
|
||||||
|
| **Стандарт / совместимость с MUA** | ★★☆ — свой, MUA не читают | ★★★★★ — mutt/neomutt/thunderbird/dovecot | ★★★★★ — legacy | ★★★★ (поверх Maildir) |
|
||||||
|
| **Масштабируемость (10k–100k)** | ★★★★ — но много маленьких файлов | ★★★★★ | ★★☆ | ★★★★★ |
|
||||||
|
| **Бэкапы (Yandex Disk / git)** | ★★★★★ — простой копией/grep | ★★★★ — тысячи файлов | ★★★★ | ★★★ (нужен индекс) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Детали по каждому подходу
|
||||||
|
|
||||||
|
### Текущий формат `email.md` (выбран)
|
||||||
|
**Плюсы:**
|
||||||
|
- Идеален для локальной LLM: `cat email.md | ollama run qwen3:8b "резюмируй"` —
|
||||||
|
тело уже очищено от MIME, frontmatter даёт атрибуты для фильтрации в скрипте
|
||||||
|
- Прозрачность: `grep`, `find`, `jq`, Obsidian, VS Code
|
||||||
|
- Атомарность записи: `mail_archive.py` создаёт новую папку `UID/`, не трогая
|
||||||
|
существующие письма → устойчиво к сбою в любой момент
|
||||||
|
- Бэкап = копирование директории (Yandex Disk FUSE)
|
||||||
|
|
||||||
|
**Минусы:**
|
||||||
|
- Нестандартный: ни один MUA (mutt/thunderbird) не читает напрямую
|
||||||
|
- Флаги в frontmatter, не в ФС-атрибутах → медленнее для MUA
|
||||||
|
- Нет встроенной семантики целостности Maildir (fsync) — но для архива это ок
|
||||||
|
- Дублирование с FTS5-индексом (mail_index.db) — два источника правды
|
||||||
|
- 4884 файла = 4884 маленьких файла → фирменных лимитов на inode нет, но
|
||||||
|
на сотнях тысяч лучше Maildir
|
||||||
|
|
||||||
|
### Maildir
|
||||||
|
**Плюсы:**
|
||||||
|
- **Стандарт де-факто**: mutt, neomutt, thunderbird, dovecot читают
|
||||||
|
- **Эталон атомарности**: `tmp/` → `new/` → `cur/`, флаги в имени файла
|
||||||
|
- Новые письма = файлы в `new/` → быстрый инкрементальный скан (нет SQL)
|
||||||
|
- Надёжность при сбое: никогда не частичного файла
|
||||||
|
|
||||||
|
**Минусы (критично для нас):**
|
||||||
|
- Тело в **raw-MIME**: для LLM-анализа нужен парсер (email.message, munpack).
|
||||||
|
У нас аналогично 2674 письма, но LLM должен читать frontmatter за `cat`
|
||||||
|
- Имена файлов нечитаемы (`1700000000.12345.host:2,S`) — grep по теме невозможен
|
||||||
|
- **Нет произвольных тэгов** — только Seen/Answered/Flagged/Deleted. Для
|
||||||
|
«назначенных тэгов» в веб-UI пришлось бы вести отдельный индекс (notmuch/SQLite)
|
||||||
|
- Не человекочитаем в Obsidian
|
||||||
|
|
||||||
|
### MBOX
|
||||||
|
Исключается сразу: один большой файл на папку, перезапись при любом изменении,
|
||||||
|
блокировки, плохо для инкрементального чтения и бэкапов по частям. Для LLM
|
||||||
|
и бэкапов на Yandex Disk — худший выбор.
|
||||||
|
|
||||||
|
### notmuch (поверх Maildir или email.md)
|
||||||
|
**Плюсы:** полнотекстовый поиск с тэгами — идеален для UI-тэгов.
|
||||||
|
**Минусы:** это **индексный слой**, не хранилище. Требует демона/индекса,
|
||||||
|
дублирует то, что уже делает FTS5. Дисквалифицирует простоту `grep`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Гибридный путь (рекомендация)
|
||||||
|
|
||||||
|
Сохранить текущий `email.md` как **каноническое хранилище** (источник правды),
|
||||||
|
но:
|
||||||
|
1. **Добавить `tags: []`** в frontmatter при записи (для UI) — тривиально в
|
||||||
|
`mail_archive.py`
|
||||||
|
2. **Экспорт в Maildir** как **опция** (для чтения в mutt/thunderbird при
|
||||||
|
желании), не зеркало в реальном времени — по запросу
|
||||||
|
3. **FTS5 остаётся** поисковым индексом; при росте >50k писем — оценить notmuch
|
||||||
|
|
||||||
|
Это даёт: LLM-удобство (текущий), стандартную совместимость (опция экспорта),
|
||||||
|
UI-тэги (frontmatter), поиск (FTS5). Без потери данных и без миграции.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Влияние на веб-интерфейс (задача 1)
|
||||||
|
|
||||||
|
Текущий формат уже содержит всё для UI-списка:
|
||||||
|
- `date` → дата письма
|
||||||
|
- `from` → адресант
|
||||||
|
- `subject` → тема
|
||||||
|
- (новое) `tags` → назначенные тэги
|
||||||
|
- `folder` → текущая папка (для перемещения: `mail_archive.py` или прямой
|
||||||
|
`mv` + обновить frontmatter + FTS5)
|
||||||
|
|
||||||
|
Maildir не дал бы тэгов без отдельного индекса. Текущий формат — оптимален.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Вывод
|
||||||
|
|
||||||
|
Текущий подход (`email.md` + FTS5) **удобнее** Maildir для заявленной цели
|
||||||
|
(локальная LLM из скриптов без облака). Maildir выигрывает только в
|
||||||
|
«стандартной совместимости с MUA» и «инкрементном скане без БД» — что не
|
||||||
|
критично для нашего сценария. **Рекомендуется остаться на текущем + добавить
|
||||||
|
`tags` в frontmatter + опциональный экспорт в Maildir.**
|
||||||
|
|
||||||
|
Ссылки: [README](README.md) · [STATUS](STATUS.md)
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# TODO — Email Assistant
|
||||||
|
|
||||||
|
Формат: | дата | задача | статус | закрыта в |
|
||||||
|
|
||||||
|
## 2026-07 (Фазы 1–1.5)
|
||||||
|
| Дата | Задача | Статус | Закрыта в |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 2026-07-16 | Фаза 0.5: рефакторинг формата — meta.json+body.md → email.md (YAML-frontmatter) | ✅ закрыта | STATUS.md |
|
||||||
|
| 2026-07-16 | Фаза 1: локальный архив (INBOX 585, Sent 515, Отправленные 510, Archive 373) | ✅ закрыта | STATUS.md |
|
||||||
|
| 2026-07-16 | Фаза 1.5: mail_index.py (SQLite FTS5) + sqlite_search.py + digest.py | ✅ закрыта | STATUS.md |
|
||||||
|
|
||||||
|
## 2026-07-19
|
||||||
|
| Дата | Задача | Статус | Закрыта в |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 2026-07-19 | Фаза 1.6: Contacts Extractor (LLM-подписи → contacts.json/vcf) | 🔵 в работе | |
|
||||||
|
| 2026-07-19 | clean_body — вырезание цитируемой переписки (Outlook/forward) | ✅ закрыта | STATUS.md контекст |
|
||||||
|
| 2026-07-19 | Cron mail-index-incremental | 🔵 открыта | |
|
||||||
|
| 2026-07-19 | Cron digest-weekly | 🔵 открыта | |
|
||||||
|
| 2026-07-19 | Push mirror gitea → gitverse.ru | 🔵 открыта | |
|
||||||
|
|
||||||
|
## 2026-09-11
|
||||||
|
| Дата | Задача | Статус | Закрыта в |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 2026-09-11 | Фаза 1.7: динамическое обнаружение подпапок INBOX (get_inbox_subfolders, --all, fix run_cmd) | ✅ закрыта | STATUS.md §1.7, git c7430d1 |
|
||||||
|
| 2026-09-11 | Анализ Nylas CLI → NYLAS_ANALYSIS.md + ссылка из README | ✅ закрыта | git d4bf3ed |
|
||||||
|
| 2026-09-11 | Задача 4: Анализ ФС vs Maildir → STORAGE_ANALYSIS.md + README | ✅ закрыта | git e31b5f2; openspec change email-storage-analysis (архивирован) |
|
||||||
|
| 2026-09-11 | Задача 2: Radicale развёрнут (docker :5232, HTTP Basic, PROPFIND 207) | 🔵 в работе | openspec change local-calendar-tasks |
|
||||||
|
| 2026-09-11 | Задача 2: коллекции Radicale (Личный/Рабочий/Задачи) — MKCOL 403, ждёт решения способа | 🔵 заблокировано | |
|
||||||
|
| 2026-09-11 | Задача 2: Vikunja (docker :3456, postgres) | 🔵 открыта | |
|
||||||
|
| 2026-09-11 | Задача 2: Caddy reverse proxy (cal.nixg.ru, tasks.nixg.ru) | 🔵 открыта | |
|
||||||
|
| 2026-09-11 | Задача 3: Android-синхронизация (DAVx5 → Radicale, Vikunja app) | 🔵 открыта | |
|
||||||
|
| 2026-09-11 | Задача 1: веб-интерфейс (FastAPI, список писем, перемещение, тэги) | 🔵 открыта | |
|
||||||
|
| 2026-09-11 | Задача 6: кнопка «Создать задачу» → Vikunja API | 🔵 открыта | |
|
||||||
|
| 2026-09-11 | Задача 7: аутентификация веб-интерфейса | 🔵 открыта | |
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
# WALKTHROUGH — Email Assistant (капитанский журнал)
|
||||||
|
|
||||||
|
Воспроизводимость: хронология, команды, решения, ошибки и как чинили.
|
||||||
|
|
||||||
|
## 2026-09-11
|
||||||
|
|
||||||
|
### Фаза 1.7: динамическое обнаружение подпапок INBOX
|
||||||
|
|
||||||
|
**Проблема:** `mail_archive.py` хардкодил 18 подпапок INBOX, на сервере их 136+.
|
||||||
|
|
||||||
|
**Решение в `mail_archive.py`:**
|
||||||
|
1. `get_inbox_subfolders()` — парсит `himalaya folder list` (таблица ASCII),
|
||||||
|
фильтрует `INBOX/`, поддерживает глубину 3, fallback на хардкод при ошибке.
|
||||||
|
2. `--all` = `FOLDERS + get_inbox_subfolders()` → 140 папок.
|
||||||
|
3. `run_cmd()` — добавлен `try/except FileNotFoundError` (himalaya не в PATH).
|
||||||
|
4. Таймаут envelope list поднят 60 → 180с: INBOX (14k писем) перечислялась >60с.
|
||||||
|
|
||||||
|
**Проверено:**
|
||||||
|
- `get_inbox_subfolders()` → 136 папок, 120 глубоких.
|
||||||
|
- `--folder "INBOX/!Реестр платежей/Акты" --limit 10 --drain` — работает.
|
||||||
|
- `--folder "INBOX/!Завки/Либра" --limit 5 --drain` — 4 письма, OK.
|
||||||
|
- Smoke `--all` с заглушкой archive_folder — 140 папок в списке.
|
||||||
|
- Fallback (HIMALAYA_CMD=несуществующий) — работает.
|
||||||
|
|
||||||
|
**Зависание `--all`:** `envelope list` на большой INBOX висел >60с (таймаут).
|
||||||
|
Поднятие до 180с + `--drain` (предохранитель 10k проходов) решило. Крон-обёртка
|
||||||
|
`mail-archive.sh` переведена на `--all --drain` + `HOME=/home/estorozhenko`
|
||||||
|
(himalaya не находил конфиг из-за смены HOME).
|
||||||
|
|
||||||
|
**Git:** c7430d1 «feat: динамическое обнаружение подпапок INBOX (Фаза 1.7)».
|
||||||
|
|
||||||
|
### Анализ Nylas CLI → отклонено
|
||||||
|
|
||||||
|
**Задача:** пользователь спросил, упростит ли Nylas получение/отправку писем.
|
||||||
|
|
||||||
|
**Вывод:** Nylas — **облачный SaaS** (api.us.nylas.com), не локальный CLI.
|
||||||
|
Письма идут через серверы Nylas; платная подписка; IMAP-гранты гибнут при
|
||||||
|
ротации пароля; Contacts API для generic IMAP платный. Для корпоративного
|
||||||
|
IMAP + локального архива — **не подходит**.
|
||||||
|
|
||||||
|
**Artifacts:** `NYLAS_ANALYSIS.md` + ссылка в README. Git: d4bf3ed.
|
||||||
|
|
||||||
|
### Задача 4: Анализ ФС vs Maildir → закрыт
|
||||||
|
|
||||||
|
**Задача:** оценить, удобен ли формат `email.md` (ФС) vs Maildir/MBOX/notmuch,
|
||||||
|
учитывая мотивацию — локальная LLM в скриптах без облака.
|
||||||
|
|
||||||
|
**Реальные данные (замер):** 4884 email.md, 76 МБ; INBOX 2674 (вкл. 1224 в 2026/),
|
||||||
|
Archive 876, Отправленные 790, Sent 544; контактов 81 (а не 5!).
|
||||||
|
|
||||||
|
**Вывод (STORAGE_ANALYSIS.md):** **остаться на email.md** — он идеален для
|
||||||
|
LLM-скриптов (`cat email.md | ollama run qwen3:8b`), человекочитаем, атомарен
|
||||||
|
(папка UID на письмо). Maildir даёт стандартность, но raw-MIME (нужен парсер),
|
||||||
|
нечитаемые имена, НЕТ тэгов. Эволюция: `tags: []` в frontmatter + опц. экспорт
|
||||||
|
в Maildir + FTS5 остаётся.
|
||||||
|
|
||||||
|
**OpenSpec:** change `email-storage-analysis` (3 требования) → validate → archive
|
||||||
|
(delta → openspec/specs/email-storage-format/spec.md). Git e31b5f2.
|
||||||
|
|
||||||
|
### Портфель: веб-UI + календарь/задачи (ПЛАН)
|
||||||
|
|
||||||
|
`PLAN_WEBUI.md` — 7 задач, порядок 4→2→3→1→6→7. Решения пользователя:
|
||||||
|
- Трекер задач и календаря НЕТ → добавлять как отдельные сервисы.
|
||||||
|
- **Все сервисы — в отдельных Docker-контейнерах.**
|
||||||
|
- Стек: **Radicale (CalDAV) + Vikunja (трекер)**.
|
||||||
|
|
||||||
|
### Задача 2: Radicale (docker) — развёрнут частично
|
||||||
|
|
||||||
|
**Сделано:**
|
||||||
|
1. `/opt/hermes/radicale/docker-compose.yml` (образ `kozea/radicale`, порт 5232).
|
||||||
|
2. Конфиг `/opt/hermes/radicale/config/config` (htpasswd, owner_only, /data/collections).
|
||||||
|
3. Пользователь `estorozhenko` — `htpasswd -c -b -m data/users estorozhenko <pass>`
|
||||||
|
(пароль в `/opt/hermes/radicale/.env`, `RADICALE_PASS`).
|
||||||
|
4. `docker compose up -d` → контейнер `radicale` работает.
|
||||||
|
|
||||||
|
**Проверено:** `curl -X PROPFIND http://127.0.0.1:5232/ -u estorozhenko:PASS` → **207**;
|
||||||
|
без пароля → **401** ✅. Radicale 3.8.1.dev0, слушает 0.0.0.0:5232.
|
||||||
|
|
||||||
|
**Ошибка/урок:** `command: ["radicale", "-C", ...]` падал `unrecognized arguments:
|
||||||
|
radicale` — entrypoint образа УЖЕ вызывает `radicale`, передавать только флаги:
|
||||||
|
`command: ["-C", "/config/config"]`.
|
||||||
|
|
||||||
|
**Заблокировано:** создание коллекций. `MKCOL /Личный/` → **403**. Radicale 3.x
|
||||||
|
создаёт коллекции иначе (PUT ресурса с Content-Type: text/calendar в новую
|
||||||
|
коллекцию). Попытка проверки через PUT тестового VEVENT была **заблокирована
|
||||||
|
таймаутом команды** (execution guard) — жду решение пользователя/возобновление.
|
||||||
|
|
||||||
|
**Осталось (Задача 2):** коллекции (Личный/Рабочий/Задачи), Vikunja (:3456,
|
||||||
|
postgres), Caddy (cal.nixg.ru, tasks.nixg.ru), Android.
|
||||||
|
|
||||||
|
### Известные открытые хвосты (репозиторий)
|
||||||
|
- `PLAN_WEBUI.md` — untracked (не закоммичен).
|
||||||
|
- Cron mail-index-incremental и digest-weekly — не настроены.
|
||||||
|
- Push mirror gitea → gitverse — не настроен (нужен токен [REDACTED]).
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
created: 2026-09-11
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
# Design: Анализ хранения писем — ФС vs Maildir
|
||||||
|
|
||||||
|
## Обзор
|
||||||
|
|
||||||
|
Документ `STORAGE_ANALYSIS.md` пишется вручную (это аналитика, не код).
|
||||||
|
Анализ опирается на:
|
||||||
|
- реальные данные архива (структуру, число файлов, размеры)
|
||||||
|
- стандарты Maildir/MBOX/notmuch
|
||||||
|
- мотивацию пользователя (локальная LLM в скриптах)
|
||||||
|
|
||||||
|
## Файлы
|
||||||
|
|
||||||
|
| Файл | Действие | Описание |
|
||||||
|
|-------|----------|----------|
|
||||||
|
| `/opt/hermes/email-assistant/STORAGE_ANALYSIS.md` | создать | Анализ + таблица + рекомендация |
|
||||||
|
| `/opt/hermes/email-assistant/README.md` | изменить | Добавить ссылку в раздел «Оценка альтернатив» |
|
||||||
|
|
||||||
|
## Анализ (что будет в документе)
|
||||||
|
|
||||||
|
### Текущий формат (`email.md`)
|
||||||
|
- **Плюсы:** человекочитаемый (YAML-frontmatter + Markdown-тело), идеален для LLM
|
||||||
|
(grep/find/obsidian), атомарность записи (новая директория UID), прозрачность бэкапов
|
||||||
|
- **Минусы:** нестандартный (MUA не читают), без флагов на уровне ФС (Seen/Answered
|
||||||
|
в frontmatter, не атрибут), дублирование с SQLite-индексом (mail_index.db),
|
||||||
|
нет жёсткой гарантии целостности (нет fsync-семантики Maildir)
|
||||||
|
|
||||||
|
### Maildir
|
||||||
|
- **Плюсы:** стандарт (mutt/neomutt/thunderbird, dovecot), атомарность
|
||||||
|
(tmp→new→cur), флаги в имени файла (`:2,RS`), быстрый инкрементальный скан
|
||||||
|
(число файлов в new/), не требует БД
|
||||||
|
- **Минусы:** тело в raw-MIME (нужен парсинг для LLM — но `mail`/`mhonarc`
|
||||||
|
извлекают), имена файлов нечитаемы, нет человекочитаемых метаданных, сложнее
|
||||||
|
grep по теме (тема в заголовке MIME, не в frontmatter)
|
||||||
|
|
||||||
|
### MBOX
|
||||||
|
- **Минусы:** один файл на папку (перезапись всего файла при изменении),
|
||||||
|
блокировки, не для инкрементального чтения LLM — сразу исключается для
|
||||||
|
нашего сценария
|
||||||
|
|
||||||
|
### notmuch
|
||||||
|
- **Плюсы:** индексный слой поверх Maildir, быстрый полнотекстовый поиск,
|
||||||
|
тэги (подходят для «назначенных тэгов» из UI), интеграция с MUA
|
||||||
|
- **Минусы:** нужен демон/индекс, не заменяет хранение (всё равно Maildir
|
||||||
|
или own format), ещё один слой сложности
|
||||||
|
|
||||||
|
### LLM-сценарий (главный)
|
||||||
|
- LLM в скриптах: `cat email.md | ollama run qwen3:8b` — работает напрямую
|
||||||
|
(frontmatter + тело). Для Maildir нужен `mail`/`munpack`/свой парсер MIME.
|
||||||
|
- Тэги для веб-UI: в текущем формате можно добавить поле `tags: []` в
|
||||||
|
frontmatter. Maildir — тэги как флаги не предусмотрены (только Seen/Answered/
|
||||||
|
Flagged), для UI-тэгов нужен отдельный индекс (notmuch или SQLite)
|
||||||
|
|
||||||
|
## Рекомендация (предварительная)
|
||||||
|
|
||||||
|
**Остаться на текущем `email.md` + SQLite FTS5**, но с эволюцией:
|
||||||
|
1. Добавить `tags: []` в frontmatter для UI-тэгов
|
||||||
|
2. Оставить Maildir-совместимость как опцию экспорта (не миграции)
|
||||||
|
3. notmuch — опция для поиска, если FTS5 станет тесным
|
||||||
|
|
||||||
|
**Обоснование:** мотивация пользователя (LLM из скриптов) полностью закрывается
|
||||||
|
текущим форматом; Maildir даёт стандартность, но теряет человекочитаемость,
|
||||||
|
удобство LLM и требует парсинга MIME. Гибрид (email.md + экспорт в Maildir/
|
||||||
|
notmuch) даёт лучшее из двух миров. Окончательный вывод — после замеров.
|
||||||
|
|
||||||
|
## Команды применения
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Создать анализ (вручную, здесь)
|
||||||
|
# Обновить README: добавить ссылку
|
||||||
|
```
|
||||||
|
|
||||||
|
## Верификация
|
||||||
|
|
||||||
|
```bash
|
||||||
|
grep -q 'STORAGE_ANALYSIS' /opt/hermes/email-assistant/README.md
|
||||||
|
test -f /opt/hermes/email-assistant/STORAGE_ANALYSIS.md
|
||||||
|
find /opt/hermes/email -name 'email.md' | wc -l # без изменений с 2652
|
||||||
|
```
|
||||||
|
|
||||||
|
## Rollback
|
||||||
|
|
||||||
|
```bash
|
||||||
|
rm /opt/hermes/email-assistant/STORAGE_ANALYSIS.md
|
||||||
|
# убрать ссылку из README.md
|
||||||
|
```
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# Proposal: Анализ хранения писем — ФС vs Maildir
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
Пользователь хранит письма в файловой системе как `email.md` (YAML-frontmatter + тело)
|
||||||
|
в `/opt/hermes/email/<folder>/YYYY/MM/UID/`. Мотивация — **использовать локальную
|
||||||
|
нейросеть (Qwen3:8b через Ollama) как инструмент в обычных скриптах**, без облака
|
||||||
|
и трат. Но перед развитием веб-интерфейса (и вообще проекта) нужно **объективно
|
||||||
|
оценить**, удобен ли текущий формат хранения по сравнению с **Maildir** и
|
||||||
|
аналогичными (MBOX, notmuch) — чтобы не закладывать архитектуру на неправильном
|
||||||
|
фундаменте.
|
||||||
|
|
||||||
|
Пользователь явно сказал: «анализировать насколько мой подход в хранении писем
|
||||||
|
в файловой системе удобен по сравнению с maildir и ему подобными способами.
|
||||||
|
Последняя задача в приоритете, пока мы не ушли далеко».
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
Создаётся документ `STORAGE_ANALYSIS.md` в корне `/opt/hermes/email-assistant/` —
|
||||||
|
объективное сравнение подходов к хранению писем:
|
||||||
|
|
||||||
|
1. **Текущий формат** (`email.md`: YAML-frontmatter + тело в `/YYYY/MM/UID/`)
|
||||||
|
2. **Maildir** (стандарт: `cur/`, `new/`, `tmp/`, имя файла = `host.timestamp.pid_uid.size:2,S`)
|
||||||
|
3. **MBOX** (один mbox-файл на папку)
|
||||||
|
4. **notmuch** (индексный слой поверх Maildir/почты)
|
||||||
|
|
||||||
|
Критерии сравнения (таблица):
|
||||||
|
- **Производительность** инкрементального чтения (LLM-анализ в скриптах)
|
||||||
|
- **Устойчивость** к сбоям (атомарность, потеря данных)
|
||||||
|
- **Интеграция** с инструментами (grep/find/jq/obsidian)
|
||||||
|
- **Пригодность для LLM** (быстрое чтение тела без парсинга MIME)
|
||||||
|
- **Совместимость** со стандартными MUA (mutt/neomutt/thunderbird)
|
||||||
|
- **Масштабируемость** (10k, 100k писем)
|
||||||
|
- **Резервное копирование** (Yandex Disk, git)
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
### New Capabilities
|
||||||
|
- `email-storage-format`: Документированное обоснование выбора формата хранения писем
|
||||||
|
(текущий vs Maildir vs MBOX vs notmuch) и рекомендация по дальнейшему развитию.
|
||||||
|
|
||||||
|
### Modified Capabilities
|
||||||
|
<!-- нет -->
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
|
||||||
|
- **Код:** нет изменений кода, только документация
|
||||||
|
- **Документация:** новый файл `STORAGE_ANALYSIS.md`, ссылка из `README.md`
|
||||||
|
- **Риск:** анализ может порекомендовать миграцию на Maildir — тогда это
|
||||||
|
отдельный change (следующий шаг). Пока — только документ, **ничего не мигрируем**.
|
||||||
|
|
||||||
|
## Rollback
|
||||||
|
|
||||||
|
- Удалить `STORAGE_ANALYSIS.md` и ссылку из `README.md`.
|
||||||
|
- Данные не трогаются — откат тривиален.
|
||||||
+45
@@ -0,0 +1,45 @@
|
|||||||
|
# Email Storage Format — Requirement Spec (Delta)
|
||||||
|
|
||||||
|
> New capability: `email-storage-format`
|
||||||
|
> Change: `email-storage-analysis`
|
||||||
|
|
||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: REQ-EMA-STORAGE-001: Обоснование выбора формата хранения
|
||||||
|
|
||||||
|
**MUST** — проект должен содержать документ `STORAGE_ANALYSIS.md` в корне
|
||||||
|
`/opt/hermes/email-assistant/`, объективно сравнивающий текущий формат
|
||||||
|
хранения (`email.md` в `/<folder>/YYYY/MM/UID/`) с Maildir, MBOX и notmuch.
|
||||||
|
|
||||||
|
#### Scenario: Документ анализа существует
|
||||||
|
|
||||||
|
**GIVEN** файл `STORAGE_ANALYSIS.md` существует
|
||||||
|
**WHEN** его открывают
|
||||||
|
**THEN** он содержит:
|
||||||
|
- таблицу сравнения по критериям (производительность, устойчивость, интеграция,
|
||||||
|
пригодность для LLM, совместимость с MUA, масштабируемость, бэкапы)
|
||||||
|
- явную рекомендацию (остаться на текущем / мигрировать на Maildir / иное)
|
||||||
|
- обоснование рекомендации с учётом мотивации пользователя (локальная LLM
|
||||||
|
в скриптах, без облака)
|
||||||
|
|
||||||
|
### Requirement: REQ-EMA-STORAGE-002: Ссылка из README
|
||||||
|
|
||||||
|
**MUST** — `README.md` проекта должен содержать ссылку на `STORAGE_ANALYSIS.md`.
|
||||||
|
|
||||||
|
#### Scenario: README содержит ссылку
|
||||||
|
|
||||||
|
**GIVEN** `README.md` проекта
|
||||||
|
**WHEN** открываем его
|
||||||
|
**THEN** в разделе «Оценка альтернатив» (или аналогичном) есть ссылка
|
||||||
|
`[Анализ формата хранения (ФС vs Maildir)](STORAGE_ANALYSIS.md)`.
|
||||||
|
|
||||||
|
### Requirement: REQ-EMA-STORAGE-003: Без изменения данных
|
||||||
|
|
||||||
|
**MUST** — change не должен модифицировать, мигрировать или удалять
|
||||||
|
существующие письма в `/opt/hermes/email/`. Анализ — только документация.
|
||||||
|
|
||||||
|
#### Scenario: Архив не изменён
|
||||||
|
|
||||||
|
**GIVEN** архив `/opt/hermes/email/`
|
||||||
|
**WHEN** change применён
|
||||||
|
**THEN** файлы писем остаются без изменений (проверка: `find /opt/hermes/email -name 'email.md' | wc -l` — то же число, что и до change).
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Tasks: Анализ хранения писем — ФС vs Maildir
|
||||||
|
|
||||||
|
## Implementation Tasks
|
||||||
|
|
||||||
|
- [x] T1: Собрать факты по текущему формату (структура, число файлов, размеры,
|
||||||
|
frontmatter-поля)
|
||||||
|
- Команда: `find /opt/hermes/email -name 'email.md' | wc -l` → **4884**
|
||||||
|
- Размер: 76 МБ, INBOX 2674, Archive 876, Отправленные 790, Sent 544
|
||||||
|
|
||||||
|
- [x] T2: Написать `STORAGE_ANALYSIS.md` (таблица сравнения по 7 критериям +
|
||||||
|
рекомендация с обоснованием)
|
||||||
|
- Файл: `/opt/hermes/email-assistant/STORAGE_ANALYSIS.md` (создан 2026-09-11)
|
||||||
|
|
||||||
|
- [x] T3: Добавить ссылку в `README.md` (раздел «Оценка альтернатив»)
|
||||||
|
- Файл: `/opt/hermes/email-assistant/README.md` (добавлена ссылка на STORAGE_ANALYSIS.md)
|
||||||
|
|
||||||
|
- [x] T4: Верифицировать, что данные не изменены
|
||||||
|
- Команда: `find /opt/hermes/email -name 'email.md' | wc -l` → **4884** (проверено, без изменений)
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
- [ ] V1: `test -f /opt/hermes/email-assistant/STORAGE_ANALYSIS.md`
|
||||||
|
- [ ] V2: `grep -q 'STORAGE_ANALYSIS' /opt/hermes/email-assistant/README.md`
|
||||||
|
- [ ] V3: `find /opt/hermes/email -name 'email.md' | wc -l` → 2652 (без изменений)
|
||||||
|
- [ ] V4: `cd /opt/hermes/openspec-lab && openspec validate email-storage-analysis`
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
created: 2026-09-11
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
# Design: Локальные сервисы календаря (Radicale) и задач (Vikunja)
|
||||||
|
|
||||||
|
## Архитектура (по требованию пользователя)
|
||||||
|
|
||||||
|
> **ВСЕ сервисы работают в отдельных Docker-контейнерах.**
|
||||||
|
> Полный стек изолирован в docker compose; никаких systemd-сервисов
|
||||||
|
> для Radicale/Vikunja.
|
||||||
|
|
||||||
|
```
|
||||||
|
┌────────────────────────────────────────────┐
|
||||||
|
│ bigbox (docker) │
|
||||||
|
│ ┌──────────────┐ ┌───────────────────┐ │
|
||||||
|
│ │ radicale │ │ vikunja │ │
|
||||||
|
│ │ :5232 CalDAV │ │ :3456 WebUI+API │ │
|
||||||
|
│ │ │ │ └─ postgres (:5433)│ │
|
||||||
|
│ └──────────────┘ └───────────────────┘ │
|
||||||
|
└────────────────────────────────────────────┘
|
||||||
|
│ │
|
||||||
|
└── Caddy reverse proxy (TLS) → Android DAVx5
|
||||||
|
```
|
||||||
|
|
||||||
|
## Сервисы и файлы
|
||||||
|
|
||||||
|
| Сервис | Образ | Порт | Каталог | Данные |
|
||||||
|
|--------|-------|------|---------|--------|
|
||||||
|
| Radicale | `tobymossman/radicale` | 5232 | `/opt/hermes/radicale/` | volume `radicale-data` (коллекции .xand) |
|
||||||
|
| Vikunja | `vikunja/vikunja:latest` | 3456 | `/opt/hermes/vikunja/` | volume `vikunja-files`, `vikunja-db` |
|
||||||
|
| PostgreSQL | `postgres:16-alpine` | 5433 (внутр.) | — | volume `vikunja-db` |
|
||||||
|
|
||||||
|
## Radicale (docker)
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# /opt/hermes/radicale/docker-compose.yml
|
||||||
|
services:
|
||||||
|
radicale:
|
||||||
|
image: tobyworrall/radicale:latest
|
||||||
|
container_name: radicale
|
||||||
|
ports:
|
||||||
|
- "5232:5232"
|
||||||
|
volumes:
|
||||||
|
- ./data:/data
|
||||||
|
- ./config:/config
|
||||||
|
environment:
|
||||||
|
- RADICALE_APPS=caldav
|
||||||
|
restart: unless-stopped
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Auth:** HTTP Basic. Пользователи в `config` (htpasswd-файл users)
|
||||||
|
- **Коллекции:** `/data/collections/` (календари .xand, задачи .ics)
|
||||||
|
- **Создание коллекций:** через DAVx5/curl PUT, или вручную скриптом
|
||||||
|
(`radicale_collections.sh` создаёт «Личный», «Рабочий», «Задачи»)
|
||||||
|
|
||||||
|
## Vikunja (docker)
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# /opt/hermes/vikunja/docker-compose.yml
|
||||||
|
services:
|
||||||
|
db:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
environment:
|
||||||
|
POSTGRES_PASSWORD: [REDACTED]
|
||||||
|
POSTGRES_DB: vikunja
|
||||||
|
volumes:
|
||||||
|
- vikunja-db:/var/lib/postgresql/data
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
vikunja:
|
||||||
|
image: vikunja/vikunja:latest
|
||||||
|
depends_on: [db]
|
||||||
|
environment:
|
||||||
|
VIKUNJA_DATABASE_TYPE: postgres
|
||||||
|
VIKUNJA_DATABASE_HOST: db
|
||||||
|
VIKUNJA_DATABASE_DATABASE: vikunja
|
||||||
|
VIKUNJA_DATABASE_USERNAME: vikunja
|
||||||
|
VIKUNJA_DATABASE_PASSWORD: [REDACTED]
|
||||||
|
VIKUNJA_SERVICE_JWTSECRET: [REDACTED]
|
||||||
|
VIKUNJA_SERVICE_FRONTENDURL: https://tasks.nixg.ru
|
||||||
|
VIKUNJA_SERVICE_PUBLICURL: https://tasks.nixg.ru
|
||||||
|
ports:
|
||||||
|
- "3456:80"
|
||||||
|
volumes:
|
||||||
|
- vikunja-files:/app/files
|
||||||
|
restart: unless-stopped
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Порт:** 3456 (netbox на 8080 — не конфликтует)
|
||||||
|
- **Postgres:** внутренний контейнер на 5433 (не публикуем наружу)
|
||||||
|
- **Данные:** volumes vikunja-db + vikunja-files
|
||||||
|
- **Логин:** первый зарегистрированный пользователь становится админом
|
||||||
|
- **API:** `/api/v1/` — токен в Настройки → API tokens
|
||||||
|
|
||||||
|
## Caddy reverse proxy (TLS для Android)
|
||||||
|
|
||||||
|
Radicale (DAVx5) и Vikunja доступны снаружи через Caddy (он уже есть в
|
||||||
|
/opt/gitea.nixg.ru). Домены:
|
||||||
|
- `cal.nixg.ru` → Radicale :5232
|
||||||
|
- `tasks.nixg.ru` → Vikunja :3456
|
||||||
|
|
||||||
|
```caddy
|
||||||
|
cal.nixg.ru {
|
||||||
|
reverse_proxy 127.0.0.1:5232
|
||||||
|
}
|
||||||
|
tasks.nixg.ru {
|
||||||
|
reverse_proxy 127.0.0.1:3456
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
TLS — Let's Encrypt через Caddy (получает автоматически).
|
||||||
|
|
||||||
|
## Команды применения
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Radicale
|
||||||
|
mkdir -p /opt/hermes/radicale/{config,data}
|
||||||
|
cd /opt/hermes/radicale && docker compose up -d
|
||||||
|
|
||||||
|
# Vikunja
|
||||||
|
mkdir -p /opt/hermes/vikunja
|
||||||
|
cd /opt/hermes/vikunja && docker compose up -d
|
||||||
|
|
||||||
|
# Проверка
|
||||||
|
curl -i -X PROPFIND http://127.0.0.1:5232/ -u estorozhenko:...
|
||||||
|
curl http://127.0.0.1:3456/api/v1/info
|
||||||
|
```
|
||||||
|
|
||||||
|
## Верификация (GIVEN/WHEN/THEN → команды)
|
||||||
|
|
||||||
|
1. Radicale: `curl -s -o /dev/null -w '%{http_code}' -X PROPFIND http://127.0.0.1:5232/ -u estorozhenko:...` → 207
|
||||||
|
2. Vikunja: `curl -s http://127.0.0.1:3456/api/v1/info` → JSON 200
|
||||||
|
3. API-токен: создать задачу → 201
|
||||||
|
4. Android/DAVx5: событие с телефона появляется в Radicale
|
||||||
|
|
||||||
|
## Rollback
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /opt/hermes/vikunja && docker compose down -v # удалить всё, включая volume
|
||||||
|
cd /opt/hermes/radicale && docker compose down -v
|
||||||
|
rm -rf /opt/hermes/vikunja /opt/hermes/radicale
|
||||||
|
# убрать строки из Caddy и перезапустить его (внешне, sudo systemctl restart)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Секреты
|
||||||
|
|
||||||
|
Пароли/токены — только в `.env` файлах сервисов ([REDACTED] в доках), НЕ в git.
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
# Proposal: Локальные сервисы календаря (Radicale) и задач (Vikunja)
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
Для синхронизации календаря и задач с Android-телефоном нужны локальные
|
||||||
|
сервисы (без облака). Пользователь хочет:
|
||||||
|
- **Календарь** — нативная синхронизация с Android
|
||||||
|
- **Трекер задач** — с веб-UI и API, чтобы веб-интерфейс почты мог
|
||||||
|
создавать задачи кнопкой
|
||||||
|
- Всё **локально** (bigbox), без облачных зависимостей
|
||||||
|
|
||||||
|
Сейчас календаря и трекера задач **нет** (проверено: порт 5232 свободен,
|
||||||
|
образы radicale/vikunja не установлены). Порт 8080 занят NetBox.
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
Два новых сервиса в `/opt/hermes/`:
|
||||||
|
|
||||||
|
### 1. Radicale (CalDAV) — календарь + задачи VTODO
|
||||||
|
- **Порт:** 5232 (свободен)
|
||||||
|
- **Путь:** `/opt/hermes/radicale/`
|
||||||
|
- **Способ:** Python pip (лёгкий, systemd) ИЛИ docker
|
||||||
|
- **Назначение:** CalDAV-сервер для:
|
||||||
|
- Календаря «Личный» + «Рабочий» (синхронизация с Android через DAVx5)
|
||||||
|
- Задач (VTODO) — тоже через CalDAV
|
||||||
|
- **Конфиг:** лёгкий, single-user (правки через UI/файл)
|
||||||
|
|
||||||
|
### 2. Vikunja (трекер задач) — веб-UI + REST API + Android app
|
||||||
|
- **Порт:** 3456 (дефолт Vikunja, свободен)
|
||||||
|
- **Путь:** `/opt/hermes/vikunja/`
|
||||||
|
- **Способ:** docker compose (postgres + vikunja)
|
||||||
|
- **Назначение:**
|
||||||
|
- Трекер задач с веб-интерфейсом (kanban/список)
|
||||||
|
- **REST API** — для кнопки «Создать задачу» из веб-интерфейса почты
|
||||||
|
- Android-приложение (нативный клиент Vikunja)
|
||||||
|
- **БД:** PostgreSQL (docker), данные в volume
|
||||||
|
|
||||||
|
### Общие решения
|
||||||
|
- **Доступ:** 127.0.0.1 (локально) + опционально через Caddy reverse proxy
|
||||||
|
на поддомене (caddy есть в /opt/gitea.nixg.ru)
|
||||||
|
- **Порты:** 5232 (radicale), 3456 (vikunja) — не конфликтуют с 8080 (NetBox)
|
||||||
|
- **Авторизация:** Radicale — HTTP Basic (логин/пароль в конфиге);
|
||||||
|
Vikunja — своя (регистрация/логин, API-токены)
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
### New Capabilities
|
||||||
|
- `calendar-caldav`: Локальный CalDAV-сервер (Radicale) для календаря и
|
||||||
|
задач, синхронизация с Android через DAVx5
|
||||||
|
- `task-tracker-vikunja`: Локальный трекер задач Vikunja с веб-UI и REST API,
|
||||||
|
интеграция с веб-интерфейсом почты через API-токен
|
||||||
|
|
||||||
|
### Modified Capabilities
|
||||||
|
<!-- нет -->
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
|
||||||
|
- **Новые сервисы:** `/opt/hermes/radicale/`, `/opt/hermes/vikunja/`
|
||||||
|
- **Порты:** 5232 (radicale), 3456 (vikunja) — новые
|
||||||
|
- **Данные:** календари/задачи будут храниться локально
|
||||||
|
- **Документация:** обновить README/STATUS (порты, логины, как синхронизировать)
|
||||||
|
- **Риск:** Vikunja тянет Postgres (память/диск); Radicale — минимален
|
||||||
|
|
||||||
|
## Rollback
|
||||||
|
|
||||||
|
1. **Radicale:** `systemctl stop radicale` + удалить `/opt/hermes/radicale/`
|
||||||
|
2. **Vikunja:** `docker compose -f /opt/hermes/vikunja/docker-compose.yml down -v`
|
||||||
|
(удалить контейнеры и volume с данными) + убрать `/opt/hermes/vikunja/`
|
||||||
|
3. Убрать упоминания из README/STATUS
|
||||||
|
4. Вернуть порты в исходное состояние (оба сейчас свободны, конфликтов нет)
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# Calendar CalDAV — Requirement Spec (Delta)
|
||||||
|
|
||||||
|
> New capability: `calendar-caldav`
|
||||||
|
> Change: `local-calendar-tasks`
|
||||||
|
|
||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: REQ-CAL-001: Локальный CalDAV-сервер
|
||||||
|
|
||||||
|
**MUST** — на bigbox должен работать CalDAV-сервер (Radicale), доступный по
|
||||||
|
HTTP на 127.0.0.1:5232, предоставляющий календари и задачи по стандарту CalDAV.
|
||||||
|
|
||||||
|
#### Scenario: Radicale отвечает
|
||||||
|
|
||||||
|
**GIVEN** Radicale запущен
|
||||||
|
**WHEN** выполняется `curl -i -X PROPFIND http://127.0.0.1:5232/ -u login:pass`
|
||||||
|
**THEN** ответ содержит HTTP 207 (Multi-Status) и список коллекций.
|
||||||
|
|
||||||
|
### Requirement: REQ-CAL-002: Календарь и задачи через CalDAV
|
||||||
|
|
||||||
|
**MUST** — Radicale должен поддерживать как календари (VEVENT), так и задачи
|
||||||
|
(VTODO), чтобы Android-клиент (DAVx5) синхронизировал и календарь, и задачи.
|
||||||
|
|
||||||
|
#### Scenario: Создание события
|
||||||
|
|
||||||
|
**GIVEN** настроенный календарь пользователя
|
||||||
|
**WHEN** клиент (DAVx5 на Android / curl) создаёт VEVENT через `PUT`
|
||||||
|
**THEN** событие сохраняется в Radicale и доступно для чтения обратно.
|
||||||
|
|
||||||
|
### Requirement: REQ-CAL-003: Синхронизация с Android
|
||||||
|
|
||||||
|
**MUST** — сервер должен поддерживать стандарт CalDAV (RFC 4791) для
|
||||||
|
двусторонней синхронизации с Android через DAVx5 (или аналог).
|
||||||
|
|
||||||
|
#### Scenario: Двусторонняя синхронизация
|
||||||
|
|
||||||
|
**GIVEN** DAVx5 настроен на Android с URL Radicale
|
||||||
|
**WHEN** создаётся событие на телефоне
|
||||||
|
**THEN** оно появляется на bigbox (Radicale) и наоборот (событие из Radicale
|
||||||
|
доступно на телефоне).
|
||||||
|
|
||||||
|
### Requirement: REQ-CAL-004: Безопасность
|
||||||
|
|
||||||
|
**MUST** — Radicale доступен только локально (127.0.0.1) или через TLS-прокси
|
||||||
|
(Caddy) с авторизацией; не должен быть открыт в интернет без TLS.
|
||||||
|
|
||||||
|
#### Scenario: Доступ снаружи
|
||||||
|
|
||||||
|
**GIVEN** Caddy reverse proxy настроен для Radicale
|
||||||
|
**WHEN** Android подключается по https://<домен>/
|
||||||
|
**THEN** соединение TLS + аутентификация работают; без Caddy доступ
|
||||||
|
ограничен локальным интерфейсом.
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# Task Tracker Vikunja — Requirement Spec (Delta)
|
||||||
|
|
||||||
|
> New capability: `task-tracker-vikunja`
|
||||||
|
> Change: `local-calendar-tasks`
|
||||||
|
|
||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: REQ-VIK-001: Локальный трекер задач
|
||||||
|
|
||||||
|
**MUST** — на bigbox должен работать трекер задач Vikunja, доступный по
|
||||||
|
HTTP на 127.0.0.1:3456 (или через Caddy на поддомене), с веб-интерфейсом
|
||||||
|
и REST API.
|
||||||
|
|
||||||
|
#### Scenario: Vikunja отвечает
|
||||||
|
|
||||||
|
**GIVEN** Vikunja запущен (docker compose)
|
||||||
|
**WHEN** выполняется `curl http://127.0.0.1:3456/api/v1/info`
|
||||||
|
**THEN** ответ содержит JSON с `version` и статус 200.
|
||||||
|
|
||||||
|
### Requirement: REQ-VIK-002: REST API для создания задач
|
||||||
|
|
||||||
|
**MUST** — API Vikunja позволяет создавать задачи программно (для кнопки
|
||||||
|
«Создать задачу» из веб-интерфейса почты), используя API-токен.
|
||||||
|
|
||||||
|
#### Scenario: Создание задачи через API
|
||||||
|
|
||||||
|
**GIVEN** валидный API-токен Vikunja
|
||||||
|
**WHEN** выполняется `POST /api/v1/projects/<id>/tasks` с телом
|
||||||
|
`{"title": "Тестовая задача", "description": "из письма"}`
|
||||||
|
**THEN** задача создаётся (HTTP 201) и видна в веб-UI.
|
||||||
|
|
||||||
|
### Requirement: REQ-VIK-003: Авторизация
|
||||||
|
|
||||||
|
**MUST** — Vikunja должен требовать аутентификацию (логин/пароль или
|
||||||
|
API-токен) для всех операций, кроме анонимного info.
|
||||||
|
|
||||||
|
#### Scenario: Доступ без токена запрещён
|
||||||
|
|
||||||
|
**GIVEN** неавторизованный запрос
|
||||||
|
**WHEN** выполняется `POST /api/v1/projects/<id>/tasks`
|
||||||
|
**THEN** возвращается 401/403, задача не создаётся.
|
||||||
|
|
||||||
|
### Requirement: REQ-VIK-004: Хранение данных
|
||||||
|
|
||||||
|
**MUST** — данные Vikunja хранятся в PostgreSQL (docker volume), переживают
|
||||||
|
перезапуск контейнера.
|
||||||
|
|
||||||
|
#### Scenario: Перезапуск Vikunja
|
||||||
|
|
||||||
|
**GIVEN** Vikunja с созданными задачами
|
||||||
|
**WHEN** контейнер перезапускается (`docker compose restart`)
|
||||||
|
**THEN** задачи и проекты сохраняются (volume не теряется).
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Tasks: Локальные сервисы календаря (Radicale) и задач (Vikunja)
|
||||||
|
|
||||||
|
## Implementation Tasks
|
||||||
|
|
||||||
|
### Radicale (CalDAV, docker :5232)
|
||||||
|
- [ ] R1: Создать `/opt/hermes/radicale/docker-compose.yml` (образ radicale, порт 5232, volumes, auth)
|
||||||
|
- [ ] R2: Создать коллекции: «Личный», «Рабочий», «Задачи» (VTODO) — через скрипт или DAVx5
|
||||||
|
- [ ] R3: Проверить `curl -X PROPFIND http://127.0.0.1:5232/` → 207
|
||||||
|
|
||||||
|
### Vikunja (трекер, docker :3456)
|
||||||
|
- [ ] V1: Создать `/opt/hermes/vikunja/docker-compose.yml` (postgres + vikunja, env, volumes)
|
||||||
|
- [ ] V2: `docker compose up -d` → Vikunja отвечает на `http://127.0.0.1:3456/api/v1/info`
|
||||||
|
- [ ] V3: Создать админ-пользователя, получить API-токен
|
||||||
|
- [ ] V4: Тест: `POST /api/v1/projects/<id>/tasks` с токеном → 201
|
||||||
|
|
||||||
|
### Общее
|
||||||
|
- [ ] O1: Caddy reverse proxy (cal.nixg.ru → 5232, tasks.nixg.ru → 3456) + TLS
|
||||||
|
- [ ] O2: Проверить доступ с Android (DAVx5 для Radicale, Vikunja app/token для задач)
|
||||||
|
- [ ] O3: Обновить README/STATUS (порты, логины, как синхронизировать)
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
- [ ] V1: `curl -s -o /dev/null -w '%{http_code}' -X PROPFIND http://127.0.0.1:5232/ -u estorozhenko:...` → 207
|
||||||
|
- [ ] V2: `curl -s http://127.0.0.1:3456/api/v1/info` → 200
|
||||||
|
- [ ] V3: Задача через API → 201
|
||||||
|
- [ ] V4: `cd /opt/hermes/openspec-lab && openspec validate local-calendar-tasks`
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
|
||||||
|
# Project context (optional)
|
||||||
|
# This is shown to AI when creating artifacts.
|
||||||
|
# Add your tech stack, conventions, style guides, domain knowledge, etc.
|
||||||
|
# Example:
|
||||||
|
# context: |
|
||||||
|
# Tech stack: TypeScript, React, Node.js
|
||||||
|
# We use conventional commits
|
||||||
|
# Domain: e-commerce platform
|
||||||
|
|
||||||
|
# Per-artifact rules (optional)
|
||||||
|
# Add custom rules for specific artifacts.
|
||||||
|
# Example:
|
||||||
|
# rules:
|
||||||
|
# proposal:
|
||||||
|
# - Keep proposals under 500 words
|
||||||
|
# - Always include a "Non-goals" section
|
||||||
|
# tasks:
|
||||||
|
# - Break tasks into chunks of max 2 hours
|
||||||
|
|
||||||
|
# Per-operation guidance (optional)
|
||||||
|
# Add advisory guidance for how apply and archive work should be conducted.
|
||||||
|
# This is separate from artifact rules above.
|
||||||
|
# Example:
|
||||||
|
# operations:
|
||||||
|
# apply:
|
||||||
|
# guidance:
|
||||||
|
# - Keep test summaries concise
|
||||||
|
# archive:
|
||||||
|
# guidance:
|
||||||
|
# - Summarize the archive outcome before finishing
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# email-storage-format Specification
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
TBD - created by archiving change email-storage-analysis. Update Purpose after archive.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
### Requirement: REQ-EMA-STORAGE-001: Обоснование выбора формата хранения
|
||||||
|
|
||||||
|
**MUST** — проект должен содержать документ `STORAGE_ANALYSIS.md` в корне
|
||||||
|
`/opt/hermes/email-assistant/`, объективно сравнивающий текущий формат
|
||||||
|
хранения (`email.md` в `/<folder>/YYYY/MM/UID/`) с Maildir, MBOX и notmuch.
|
||||||
|
|
||||||
|
#### Scenario: Документ анализа существует
|
||||||
|
|
||||||
|
**GIVEN** файл `STORAGE_ANALYSIS.md` существует
|
||||||
|
**WHEN** его открывают
|
||||||
|
**THEN** он содержит:
|
||||||
|
- таблицу сравнения по критериям (производительность, устойчивость, интеграция,
|
||||||
|
пригодность для LLM, совместимость с MUA, масштабируемость, бэкапы)
|
||||||
|
- явную рекомендацию (остаться на текущем / мигрировать на Maildir / иное)
|
||||||
|
- обоснование рекомендации с учётом мотивации пользователя (локальная LLM
|
||||||
|
в скриптах, без облака)
|
||||||
|
|
||||||
|
### Requirement: REQ-EMA-STORAGE-002: Ссылка из README
|
||||||
|
|
||||||
|
**MUST** — `README.md` проекта должен содержать ссылку на `STORAGE_ANALYSIS.md`.
|
||||||
|
|
||||||
|
#### Scenario: README содержит ссылку
|
||||||
|
|
||||||
|
**GIVEN** `README.md` проекта
|
||||||
|
**WHEN** открываем его
|
||||||
|
**THEN** в разделе «Оценка альтернатив» (или аналогичном) есть ссылка
|
||||||
|
`[Анализ формата хранения (ФС vs Maildir)](STORAGE_ANALYSIS.md)`.
|
||||||
|
|
||||||
|
### Requirement: REQ-EMA-STORAGE-003: Без изменения данных
|
||||||
|
|
||||||
|
**MUST** — change не должен модифицировать, мигрировать или удалять
|
||||||
|
существующие письма в `/opt/hermes/email/`. Анализ — только документация.
|
||||||
|
|
||||||
|
#### Scenario: Архив не изменён
|
||||||
|
|
||||||
|
**GIVEN** архив `/opt/hermes/email/`
|
||||||
|
**WHEN** change применён
|
||||||
|
**THEN** файлы писем остаются без изменений (проверка: `find /opt/hermes/email -name 'email.md' | wc -l` — то же число, что и до change).
|
||||||
+131
-11
@@ -39,18 +39,35 @@ import sys
|
|||||||
import argparse
|
import argparse
|
||||||
import re
|
import re
|
||||||
import hashlib
|
import hashlib
|
||||||
|
import os
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
# Конфигурация
|
# Конфигурация
|
||||||
ARCHIVE_ROOT = Path("/opt/hermes/email")
|
ARCHIVE_ROOT = Path("/opt/hermes/email")
|
||||||
STATE_DIR = ARCHIVE_ROOT / "state"
|
STATE_DIR = ARCHIVE_ROOT / "state"
|
||||||
HIMALAYA_CMD = ["himalaya"]
|
|
||||||
|
# Himalaya конфиг: берём из ~/.config/himalaya/config.toml (HOME пользователя).
|
||||||
|
# В текущей сессии HOME=/opt/hermes/.hermes/home, поэтому явно подставляем
|
||||||
|
# реальный HOME из HERMES_REAL_HOME, иначе himalaya не найдёт конфиг.
|
||||||
|
def _himalaya_cmd():
|
||||||
|
cmd = ["himalaya"]
|
||||||
|
real_home = os.environ.get("HERMES_REAL_HOME") or os.path.expanduser("~")
|
||||||
|
if real_home != os.path.expanduser("~"):
|
||||||
|
cmd = ["env", f"HOME={real_home}"] + cmd
|
||||||
|
return cmd
|
||||||
|
|
||||||
|
HIMALAYA_CMD = _himalaya_cmd()
|
||||||
|
|
||||||
# Папки для полной архивации (основные папки)
|
# Папки для полной архивации (основные папки)
|
||||||
FOLDERS = ["INBOX", "Отправленные", "Archive", "Sent"]
|
FOLDERS = ["INBOX", "Отправленные", "Archive", "Sent"]
|
||||||
|
|
||||||
# Вложенные папки INBOX, которые тоже архивируем
|
# Вложенные папки INBOX, которые тоже архивируем
|
||||||
|
#
|
||||||
|
# ⚠️ Вместо захардкоженного списка используем динамическое обнаружение
|
||||||
|
# через `himalaya folder list` (см. get_inbox_subfolders()). Список ниже
|
||||||
|
# оставлен как FALLBACK на случай, если himalaya запущен без конфига
|
||||||
|
# (например, автономный запуск вне сессии и без HOME пользователя).
|
||||||
INBOX_SUBFOLDERS = [
|
INBOX_SUBFOLDERS = [
|
||||||
"INBOX/!Scan",
|
"INBOX/!Scan",
|
||||||
"INBOX/!Битрикс",
|
"INBOX/!Битрикс",
|
||||||
@@ -72,6 +89,21 @@ INBOX_SUBFOLDERS = [
|
|||||||
"INBOX/Эксплуатация",
|
"INBOX/Эксплуатация",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
# Папки, которые НЕ архивируем (системные/мусор)
|
||||||
|
EXCLUDED_FOLDERS = {
|
||||||
|
"INBOX",
|
||||||
|
"Drafts",
|
||||||
|
"Trash",
|
||||||
|
"Trash/archive",
|
||||||
|
"Archive",
|
||||||
|
"Archives",
|
||||||
|
"RSS-каналы",
|
||||||
|
"Junk",
|
||||||
|
"Spam",
|
||||||
|
"Sent",
|
||||||
|
"Отправленные",
|
||||||
|
}
|
||||||
|
|
||||||
# Какие дополнительные заголовки вытягивать через --header
|
# Какие дополнительные заголовки вытягивать через --header
|
||||||
EXTRA_HEADERS = [
|
EXTRA_HEADERS = [
|
||||||
"Message-ID",
|
"Message-ID",
|
||||||
@@ -84,12 +116,16 @@ EXTRA_HEADERS = [
|
|||||||
|
|
||||||
def run_cmd(cmd, timeout=60):
|
def run_cmd(cmd, timeout=60):
|
||||||
"""Выполнить команду, вернуть stdout."""
|
"""Выполнить команду, вернуть stdout."""
|
||||||
result = subprocess.run(
|
try:
|
||||||
cmd,
|
result = subprocess.run(
|
||||||
stdout=subprocess.PIPE,
|
cmd,
|
||||||
stderr=subprocess.PIPE,
|
stdout=subprocess.PIPE,
|
||||||
timeout=timeout,
|
stderr=subprocess.PIPE,
|
||||||
)
|
timeout=timeout,
|
||||||
|
)
|
||||||
|
except FileNotFoundError:
|
||||||
|
# himalaya не найден в PATH (автономный запуск без окружения)
|
||||||
|
raise RuntimeError(f"Command not found: {cmd[0]}")
|
||||||
if result.returncode != 0:
|
if result.returncode != 0:
|
||||||
stderr_text = result.stderr.decode("utf-8", errors="ignore")
|
stderr_text = result.stderr.decode("utf-8", errors="ignore")
|
||||||
if "No such folder" in stderr_text:
|
if "No such folder" in stderr_text:
|
||||||
@@ -98,6 +134,64 @@ def run_cmd(cmd, timeout=60):
|
|||||||
return result.stdout.decode("utf-8", errors="ignore")
|
return result.stdout.decode("utf-8", errors="ignore")
|
||||||
|
|
||||||
|
|
||||||
|
# Таймаут для envelope list: на больших папках (10k+ писем) himalaya
|
||||||
|
# перечисляет страницы медленно (IMAP через STARTTLS). 60с не хватает —
|
||||||
|
# INBOX (14k) занимает >2 мин. Даём 180с (как в mail-archive.sh DRAIN_TIMEOUT).
|
||||||
|
ENVELOPE_TIMEOUT = 180
|
||||||
|
|
||||||
|
|
||||||
|
def get_inbox_subfolders():
|
||||||
|
"""
|
||||||
|
Динамически получить список подпапок INBOX через `himalaya folder list`.
|
||||||
|
|
||||||
|
Himalaya выводит таблицу (ASCII-арт). Вытаскиваем имена папок,
|
||||||
|
начинающиеся с 'INBOX/' (исключая саму INBOX и системные папки).
|
||||||
|
|
||||||
|
Возвращает отсортированный список подпапок INBOX.
|
||||||
|
Папки, которые исчезли на сервере, пропускаем (archive_folder обработает
|
||||||
|
их как 'No such folder' → вернёт 0).
|
||||||
|
Штатно используется fallback INBOX_SUBFOLDERS, если himalaya не смог
|
||||||
|
выполниться (нет конфига, ошибка сети и т.п.).
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
stdout = run_cmd(
|
||||||
|
HIMALAYA_CMD + ["folder", "list"],
|
||||||
|
timeout=60,
|
||||||
|
)
|
||||||
|
except RuntimeError as e:
|
||||||
|
print(f" [WARN] Не удалось получить список папок: {e}; "
|
||||||
|
f"использую fallback ({len(INBOX_SUBFOLDERS)} папок)",
|
||||||
|
file=sys.stderr)
|
||||||
|
return INBOX_SUBFOLDERS
|
||||||
|
|
||||||
|
folders = []
|
||||||
|
for line in stdout.splitlines():
|
||||||
|
# Таблица himalaya: "| INBOX/путь | \HasNoChildren |"
|
||||||
|
line = line.strip()
|
||||||
|
if not line.startswith("|"):
|
||||||
|
continue
|
||||||
|
parts = [p.strip() for p in line.strip("|").split("|")]
|
||||||
|
if not parts:
|
||||||
|
continue
|
||||||
|
name = parts[0]
|
||||||
|
# Пропускаем шапку-разделитель ("----------------")
|
||||||
|
if not name or set(name) <= set("- "):
|
||||||
|
continue
|
||||||
|
if name in EXCLUDED_FOLDERS:
|
||||||
|
continue
|
||||||
|
if name.startswith("INBOX/"):
|
||||||
|
folders.append(name)
|
||||||
|
|
||||||
|
# Fallback на хардкод, если himalaya вернул пусто (нет сети/прав)
|
||||||
|
if not folders:
|
||||||
|
print(f" [WARN] himalaya folder list вернул 0 подпапок INBOX; "
|
||||||
|
f"использую fallback ({len(INBOX_SUBFOLDERS)} папок)",
|
||||||
|
file=sys.stderr)
|
||||||
|
return INBOX_SUBFOLDERS
|
||||||
|
|
||||||
|
return sorted(set(folders))
|
||||||
|
|
||||||
|
|
||||||
def get_state_file(folder):
|
def get_state_file(folder):
|
||||||
"""Получить путь к файлу состояния для папки."""
|
"""Получить путь к файлу состояния для папки."""
|
||||||
safe_name = folder.replace("/", "_").replace(" ", "_")
|
safe_name = folder.replace("/", "_").replace(" ", "_")
|
||||||
@@ -179,7 +273,7 @@ def get_envelopes(folder, limit=100, last_uid=0):
|
|||||||
"--page-size", str(page_size),
|
"--page-size", str(page_size),
|
||||||
"--output", "json",
|
"--output", "json",
|
||||||
],
|
],
|
||||||
timeout=60,
|
timeout=ENVELOPE_TIMEOUT,
|
||||||
)
|
)
|
||||||
except RuntimeError as e:
|
except RuntimeError as e:
|
||||||
if "No such folder" in str(e):
|
if "No such folder" in str(e):
|
||||||
@@ -413,21 +507,47 @@ def main():
|
|||||||
"--all", action="store_true",
|
"--all", action="store_true",
|
||||||
help="Архивировать включая вложенные папки INBOX"
|
help="Архивировать включая вложенные папки INBOX"
|
||||||
)
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--drain", action="store_true",
|
||||||
|
help="Скачивать ВСЮ почту до конца: повторять проходы по каждой папке, "
|
||||||
|
"пока за проход не обработано 0 писем (сколько бы ни накопилось сверх --limit)"
|
||||||
|
)
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
# Определить список папок
|
# Определить список папок
|
||||||
if args.folder:
|
if args.folder:
|
||||||
folders_to_archive = [args.folder]
|
folders_to_archive = [args.folder]
|
||||||
elif args.all:
|
elif args.all:
|
||||||
folders_to_archive = FOLDERS + INBOX_SUBFOLDERS
|
# Динамическое обнаружение: получаем актуальные подпапки INBOX
|
||||||
|
# через himalaya folder list (с fallback на хардкод)
|
||||||
|
folders_to_archive = FOLDERS + get_inbox_subfolders()
|
||||||
else:
|
else:
|
||||||
folders_to_archive = FOLDERS
|
folders_to_archive = FOLDERS
|
||||||
|
|
||||||
total = 0
|
total = 0
|
||||||
for folder in folders_to_archive:
|
for folder in folders_to_archive:
|
||||||
try:
|
try:
|
||||||
count = archive_folder(folder, limit=args.limit)
|
if args.drain:
|
||||||
total += count
|
# Режим "высушить": повторяем проходы, пока папка не опустеет
|
||||||
|
# (новые письма могут приходить во время скачивания — шли процесс
|
||||||
|
# идёт, пока проход не вернёт 0).
|
||||||
|
folder_total = 0
|
||||||
|
# Предохранитель от бесконечного цикла: не больше N проходов.
|
||||||
|
max_passes = 10_000
|
||||||
|
passes = 0
|
||||||
|
while passes < max_passes:
|
||||||
|
count = archive_folder(folder, limit=args.limit)
|
||||||
|
folder_total += count
|
||||||
|
passes += 1
|
||||||
|
if count == 0:
|
||||||
|
break
|
||||||
|
total += folder_total
|
||||||
|
if passes >= max_passes:
|
||||||
|
print(f" [WARN] {folder}: достигнут потолок проходов "
|
||||||
|
f"({max_passes}), возможен остаток", file=sys.stderr)
|
||||||
|
else:
|
||||||
|
count = archive_folder(folder, limit=args.limit)
|
||||||
|
total += count
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f" [ERROR] {folder}: {e}", file=sys.stderr)
|
print(f" [ERROR] {folder}: {e}", file=sys.stderr)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user