Unified lifecycle/process router. Concurrent FSM that discovers context, runs embedded alignment checks, researches, proposes, specs behavior, and routes to specialist skills. Guard scoring is constant, not gated. Artifacts are spec-first.
Unified lifecycle/process router. Concurrent FSM that discovers context, runs embedded alignment checks, researches, proposes, specs behavior, and routes to specialist skills. Guard scoring is constant, not gated. Artifacts are spec-first.
One entry point for all work. Concurrent FSM with PLANNING and EXECUTION phases. Guard scoring runs constantly (not as a gate). DISCOVER runs interview, memory prefetch, prior art, and search concurrently. All artifacts stored as beads custom types.
PLANNING PHASE EXECUTION PHASE
┌───────────────────┐ ┌───────┐ ┌──────────┐ ┌─────────┐ ┌──────┐ ┌─────────┐ ┌──────────┐ ┌──────┐ ┌───────┐
│ DISCOVER │──▶│ ALIGN │──▶│ RESEARCH │──▶│ PROPOSE │──▶│ SPEC │──▶│ EXECUTE │──▶│ VALIDATE │──▶│ EMIT │──▶│ LEARN │
│ (concurrent) │ └───────┘ └──────────┘ └─────────┘ └──────┘ └─────────┘ └──────────┘ └──────┘ └───────┘
│ │ north star deeper code CDO graph BDD + spawn layer-dep close cm outcome
│ ┌──────────────┐ │ ALIGN gate analysis 5-role contracts team/agents strictness bead cm reflect
│ │ Interview(fg)│ │ classify C1-C4 map think accept. inline gates update br learning
│ │ PriorArt(bg) │ │ layers DoR compl. proposal criteria cm add status cass index
│ │ Search (bg) │ │ alignment bead (learn)
│ └──────────────┘ │ verdict
│ │
│ ╔════════════════╗│ Guard is NOT a step -- it scores 6 categories every turn.
│ ║ GUARD(constant)║│ <=30% -> PASS | 30-60% -> ASK inline | >60% -> interview skill
│ ╚════════════════╝│
└───────────────────┘
Task Tracker Adapter (bd | br | td)
The work skill is backend-agnostic for task tracking. Detect which tool is available and route through the adapter. Preference order: bd > br > td.
"design", "propose", "architect", "learn", "guide me"
crystallized
custom:spec
planning, tracker
"plan", "implement", "specify"
manifesting
handoff bead
Team coordination, tracker
"working on", "in progress"
completed
archive bead
lev-lifecycle
"done", "finished", "closed"
discarded
tombstone link
work guard + validation
"discard", "drop", "reject"
Learning artifacts are created post-completion by LEARN, but custom:learning is not a lifecycle state.
All artifacts are stored as beads custom types (not files on disk). A hook generates markdown views from beads for human readability.
Shortcuts
Key
Action
Route
(l)
Start learn interview
learn [context]
(p)
Start proposal
work --stage=crystallizing
(u)
Show update diff
work --stage=update
(s)
Browse skills
skills-db query (inline)
(d)
Design/UX hub
ux hub
Operational Command Constellation
These are agent <-> human operational commands and aliases. Map them to root primitives, not ad-hoc flows.
Canonical source for CLI alias + FSM stage + schema handler mapping:
lev get "{kw}" --scope=knowledge --depth=fs --pattern="SKILL.md"
If substantial prior art found, present findings and ask:
Review existing work?
Extend existing work?
Proceed with new work anyway?
Flexible ordering: Steps have dependency gates, not fixed sequence. If prior art returns empty fast, skip ahead. If interview reveals complexity, loop back. Guard score dropping below 30% unblocks ALIGN regardless of other tracks.
Skip guard when: Explicit file paths provided, multi-turn context established, --no-guard flag, or resuming from saved session.
Output:custom:report beads with discovery results, guard scores, and skill manifest.
ALIGN -- North Star Alignment
Check project alignment before deeper work. This is an embedded work gate. Use lev-align only for standalone deep-dive audits.
ALIGN:
├── North star exists?
│ ├── YES -> Compare current state to north star
│ │ └── Drift type? (Stale Docs | Product Pivot | Coverage Gap | Status Drift | Path Drift)
│ └── NO -> Deep research codebase -> define north star -> save as custom:system bead
├── Classify layers (lev-portable):
│ ├── Stewart Brand shearing layers: Site | Structure | Skin | Services | Space Plan | Stuff
│ ├── Depth: L0 (overview) -> L1 (structure) -> L2 (details) -> L3 (runtime)
│ └── Persistence: System graph (permanent) vs CDO graph (ephemeral)
└── Output: alignment verdict (aligned | drift | gap)
Layer
Timescale
Risk
Examples
Site
Decades
High
DB schema, core model
Structure
30-50y
High
Auth, API contracts
Skin
20y
Medium
UI framework, design system
Services
7-15y
Medium
CI/CD, monitoring
Space Plan
3-7y
Lower
Routes, features
Stuff
Daily
Lowest
Copy, env vars
If no alignment data exists, create a custom:system bead to capture project context:
Spec must include: BDD scenarios (Given/When/Then), contracts, acceptance criteria, team structure, and workstream assignments. See VALIDATE gates for full requirements.
PROPOSE Dashboard Footer
Every PROPOSE output ends with a structured footer. This is a display convention (not a gate). The agent renders it as markdown; the user responds with a number or letter shortcut.
---
🔨 **Work:** {stage} | 🎯 {layer} | 📊 Guard: {score}%
**Skills loaded:** {loaded_list}
**Available:** {available_count} more via skills-db
🪄 **Next:**
1. [s] Skills — browse/load from skills-db
2. [r] Research — deepen with lev-research
3. [p] Prior art — review beads and artifacts
4. Proceed to SPEC
5. All of the above
6. ⬅️ Back to DISCOVER
#### SPEC Promotion Path
When a spec passes validation (`gate:propose-spec`) and template questions are answered, the agent must identify the promotion target:
1. **Start:** `.lev/pm/specs/spec-{topic}.md` (Ephemeral Draft)
2. **Review:** Gate passes.
3. **Promote:** Move to `docs/specs/spec-{module}.md` (Canonical)
- If module exists: Update existing spec.
- If new module: Create new spec file.
- Naming: Use `spec-{module}.md` for core, `spec-{module}-{slug}.md` for extensions.
#### FlowMind Naming Structure & Config Keys
The `work` skill recognizes specific configuration keys for identifying specs and promoting them:
| Key | Value Pattern | Purpose |
|-----|---------------|---------|
| `naming_structure` | `flowmind` | Enforce `spec-{module}.md` naming |
| `filename_mask` | `core-*-mask` | Regex for validating core filenames |
| `spec_target` | `docs/specs/` | Target directory for promotion |
Example Config (`.lev/config.yaml`):
```yaml
work:
naming_structure: flowmind
filename_mask: "spec-.*\\.md"
spec_target: "docs/specs/"
Shortcut behavior:
- [s] -> lev-skill resolve "{topic}" --json, present results, offer to cat SKILL.md
- [r] -> route to lev-research with current context
- [p] -> br search "{topic}" + cass search "{topic}"
---
## FSM States: EXECUTION PHASE
> **Note:** ROUTE and MANIFESTING are sub-operations within the EXECUTION PHASE, not distinct FSM states. The FSM states are the 7 states (+ discarded branch) in the diagram above. ROUTE selects which skill to invoke; MANIFESTING describes the handoff contract format.
### ROUTE -- Sub-Skill Routing
| Stage | Primary Skill | Secondary Skills | When |
|-------|--------------|------------------|------|
| **ephemeral** | None | `thinking-parliament` | Meta questions only |
| **captured** | `lev get` | `lev-research`, `deep-research` | Progressive context gathering |
| **captured** | `lev-research` | None | Deep research mode |
| **crystallizing** | `lev-learn` | `lev-cdo` | Guided intake when user invokes learn mode |
| **crystallizing** | `lev-cdo` | `thinking-parliament`, `work` alignment gate | Strategic design |
| **crystallizing** | `ux` | `lev-cdo`, `planning` | Product/design/UX shaping before spec |
| **crystallized** | `planning` | tracker | Spec authoring with BDD + contracts |
| **manifesting** | tracker | `lev-clwd` | Task tracking/coordination + handoff emission |
| **completed** | `lev-lifecycle` | None | Archive and summarize |
Routing logic:
- `captured` + simple query → `lev get`; deep ambiguity or broad unknowns → `lev-research`
- explicit `learn` intent or underspecified request needing guided intake → `lev-learn` (proposal + handoff)
- `crystallizing` + product/design/UX framing needed → `ux` hub (routes to design-os, pencil, or pipeline)
- `crystallizing` + needs adversarial validation → `thinking-parliament` + `lev-cdo`; else → `lev-cdo`
- `crystallized` → always `planning` (spec-authoring backend, DoR enforcement) + tracker
- `manifesting` → tracker + `lev-clwd` + mandatory handoff contract output
### MANIFESTING -- Handoff Contract (Required)
When emitting `handoff.md`, follow the checkpoint format contract below. This is the canonical handoff schema for continuity.
1. Write `3-15` checkpoints in chronological order.
2. For each checkpoint, use exactly one block type:
- `⚡ CHECKPOINT Progress`
- `📋 Code Context`
- `📋 User feedback / ADR created`
3. Across checkpoints, include:
- files worked on
- files loaded into context
- what was learned and why it matters
4. End with both:
- `System Prompt for Next Agent`
- `Context Confidence Score`
5. File location:
- `.lev/pm/handoffs/{YYYYMMDD-HHMMSS}-{topic}.md`
6. Template source:
- `~/.agents/skills/work/templates/handoff.md`
### EXECUTE -- Spawn Workers
Based on PROPOSE and ROUTE outputs:
1. **Direct execution:** Load matched skill inline, execute in current context
2. **Ephemeral subagents:** Spawn via Task tool with skill content injected into prompt
- Each agent gets: task description + inlined skill content + workspace context
- Instruct agents to return manifest of files touched + executive brief
3. **Formal team:** Create team config, spawn via TeamCreate + Task tool
- Assign workstreams with skill-to-agent mapping
- Set dependency ordering between workstreams
#### Inline Learning Capture
During execution, immediately capture learnings that survive context compaction:
| Trigger | Command | Category |
|---------|---------|----------|
| Bug fixed | `cm add "{description}" --category bug --json` | bug |
| Gotcha discovered | `cm add "{description}" --category {cat} --json` | architecture, testing, tooling |
| Performance issue | `cm add "{description}" --category performance --json` | performance |
| Security concern | `cm add "{description}" --category security --json` | security |
Categories: `bug`, `performance`, `architecture`, `testing`, `security`, `workflow`, `tooling`
**Why inline:** Context compaction loses session details. `cm add` persists immediately to the playbook, surviving any compaction event.
### VALIDATE -- Quality Gates
> Full per-gate definitions (layer modulation, confidence routing, failure actions): `./references/gates.md`
#### Gate Summary Matrix
| Gate | Transition | Severity | FORMAL Checks | DIRECT Checks | Confidence Skip |
|------|-----------|----------|---------------|---------------|-----------------|
| `gate:discover-align` | DISCOVER -> ALIGN | MANDATORY | 5/5 (strict) | 1/5 | >= 0.90 auto-pass |
| `gate:align-research` | ALIGN -> RESEARCH | CRITICAL | 7/7 | 2/7 | >= 0.90 skip to 3 |
| `gate:research-propose` | RESEARCH -> PROPOSE | MANDATORY | 6/6 | 1/6 | >= 0.90 skip to 1 |
| `gate:propose-spec` | PROPOSE -> SPEC | CRITICAL | 7/7 + human | 1/7 | >= 0.90 skip to 2 |
| `gate:spec-execute` | SPEC -> EXECUTE | CATASTROPHIC | 16/16 + human | 3/16 | Never fully skip |
| `gate:execute-validate` | EXECUTE -> VALIDATE | MANDATORY | 8/8 | 2/8 | >= 0.90 skip to 3 |
| `gate:validate-emit` | VALIDATE -> EMIT | CRITICAL | 10/10 + human | 1/10 | >= 0.90 layer-min |
| `gate:emit-learn` | EMIT -> LEARN | WARNING | 6/6 | 2/6 | >= 0.90 skip to 2 |
#### Confidence Routing Table
| Confidence | Gate Behavior |
|------------|---------------|
| >= 0.90 | Skip INFO + WARNING gates; execute MANDATORY+ only |
| 0.80 - 0.89 | Standard: all gates at their declared severity |
| 0.60 - 0.79 | All gates fire + deliberation mode (Think 5-role) required before PROPOSE |
| < 0.60 | All gates + extended checks + human review required before SPEC |
#### Backtracking Table
| Gate Failure | Backtrack To | Condition |
|-------------|-------------|-----------|
| `gate:discover-align` | DISCOVER | Insufficient context — re-interview or re-search |
| `gate:align-research` | ALIGN or DISCOVER | Misclassification or missing north star |
| `gate:research-propose` | RESEARCH | Insufficient depth — deepen analysis |
| `gate:propose-spec` | PROPOSE or RESEARCH | Think disagreement or alignment drift |
| `gate:spec-execute` | SPEC or PROPOSE | Missing sections or invalid contracts |
| `gate:execute-validate` | EXECUTE | Incomplete work — finish remaining items |
| `gate:validate-emit` | EXECUTE or VALIDATE | Test failures or visual validation failure |
| `gate:emit-learn` | EMIT (retry) | Write failure — never blocks LEARN |
**Max backtrack depth:** 3 consecutive failures at the same gate before escalating to human review.
#### CATASTROPHIC gate:spec-execute (Inlined — Never Skip)
The spec completeness gate has 16 checks and **cannot be degraded or bypassed** by any mechanism (confidence, layer, user override):
| # | Check | Pass Condition |
|---|-------|---------------|
| 1 | Spec bead exists | `custom:spec` bead created |
| 2 | Executive summary | Present and <= 3 paragraphs |
| 3 | Context defined | Existing state AND target state documented |
| 4 | BDD scenarios | Given/When/Then covering primary flows |
| 5 | Input/Processing/Output | I/P/O triples defined per scenario |
| 6 | Dependencies declared | All external deps with versions/contracts |
| 7 | Integration points | All integration boundaries documented |
| 8 | Breaking changes | Explicitly noted (even if "none") |
| 9 | Recommended skills | Execution skills listed |
| 10 | Team structure | Team + workstreams if complexity > Simple |
| 11 | Unit test cases | Test cases defined |
| 12 | Integration tests | Integration test scenarios |
| 13 | E2E verification | E2E verification command specified |
| 14 | Success criteria | Measurable criteria with acceptance thresholds |
| 15 | BD tasks created | Spec decomposed into BD epics/tasks |
| 16 | Rollback plan | How to undo if execution fails |
**Layer modulation:** FORMAL = all 16 + human sign-off; DIRECT = checks 1, 3, 14 only. See `./references/gates.md` for full per-tier breakdown.
**Failure:** CATASTROPHIC BLOCK. List every failing check with remediation. Return to SPEC. After 3 consecutive failures, escalate to human. Never auto-waive. Never skip. Never degrade severity.
### EMIT -- Create Artifact Bead
Create the stage-appropriate bead and let the hook render a markdown view for human readability.
1. Create bead via `br create` with the correct custom type and labels
2. Hook auto-renders a markdown view from bead content
3. Report bead ID to user
| Stage | Bead Type | Labels |
|-------|-----------|--------|
| captured | `custom:report` | `report,{domain}` |
| crystallizing | `custom:proposal` | `proposal,{layer},{domain}` |
| crystallized | `custom:spec` | `spec,{layer},{domain}` |
| manifesting | handoff bead | `handoff,{topic}` |
| completed | archive bead | `archive,{domain}` |
Learning artifacts are emitted by LEARN after completion:
- `custom:learning` with labels `learning,retrospective,{domain}`
### LEARN -- Session Close Ceremony
Final FSM step. Reflects on the session, records outcomes, creates a learnings bead.
**Triggers:** Session end, `/handoff`, `/exit`, explicit `learn` close request.
#### Steps
1. **Record outcomes** for rules used this session:
```bash
cm outcome {success|failure|mixed} {bullet-ids} --session $SESSION --json
Add new learnings not captured inline during EXECUTE:
cm add "{learning}" --category {category} --json
Reflect on session (extract patterns):
cm reflect --days 1 --json --dry-run
# Review proposed rules. If good:
cm reflect --days 1 --json
Role definition - Clarifies operating scope and prevents ambiguous execution.
Context enrichment - Captures required inputs before actions.
Output structuring - Standardizes deliverables for consistent reuse.
Step-by-step workflow - Reduces errors by making execution order explicit.
Edge-case handling - Documents safe fallbacks when assumptions fail.
Technique Notes
These techniques improve reliability by making intent, inputs, outputs, and fallback paths explicit. Keep this section concise and additive so existing domain guidance remains primary.
Prompt Architect Overlay
Role Definition
You are the prompt-architect-enhanced specialist for work, responsible for deterministic execution of this skill's guidance while preserving existing workflow and constraints.
Input Contract
Required: clear user intent and relevant context for this skill.
Preferred: repository/project constraints, existing artifacts, and success criteria.
If context is missing, ask focused questions before proceeding.
Output Contract
Provide structured, actionable outputs aligned to this skill's existing format.
Include assumptions and next steps when appropriate.
Preserve compatibility with existing sections and related skills.
Edge Cases & Fallbacks
If prerequisites are missing, provide a minimal safe path and request missing inputs.
If scope is ambiguous, narrow to the highest-confidence sub-task.
If a requested action conflicts with existing constraints, explain and offer compliant alternatives.