Personas & Executable BDD User Story Specifications
SpecOps models user needs and verifiable acceptance contracts as version-locked Markdown documents under docs/project/user_stories/ (Area 3 of the Declarative Specification Grammar defined in ADR-0022).
This reference specification defines the canonical directory topology, YAML frontmatter schemas, Markdown AST section grammars, regex extraction patterns, frontdoor Gherkin verification rules, and registry table format for User Personas and Executable BDD User Stories.
1. Directory Layout & File Topology
All persona and user story artifacts reside under docs/project/user_stories/:
docs/project/user_stories/
βββ PERSONAS.md # Canonical user archetype profiles
βββ REGISTRY.md # Sequential pipe-table index of all user stories
βββ accepted/ # Active executable BDD user story specifications
βββ us-0001-project-init.md
βββ us-0002-invariant-health.md
βββ us-XXXX-<slug>.md # Four-digit zero-padded story ID + kebab-case slug
Topology & Naming Rules
| Artifact Class | Path Pattern | Filename Regex | Frontmatter Policy |
|---|---|---|---|
| Persona Catalog | docs/project/user_stories/PERSONAS.md |
^PERSONAS\.md$ |
Optional / Ignored by schema audit (is_specification_file() -> False) |
| Story Registry | docs/project/user_stories/REGISTRY.md |
^REGISTRY\.md$ |
Forbidden (is_specification_file() -> False) |
| Executable User Story | docs/project/user_stories/accepted/us-XXXX- |
^us-\d{4}-[a-z0-9-]+\.md$ |
Required (UserStoryFrontmatter, extra="forbid") |
- Canonical Story ID Normalization:
normalize_story_id(raw, "US")insrc/spec_ops/core/story_models.pyextracts the integer digits fromidor the filename stem and formats them asUS-XXXX(e.g.,'0133'or'133'$\rightarrow$'US-0133'). - Slug Generation:
slugify_story_title(title)lowercases the title, strips non-alphanumeric characters ([^a-zA-Z0-9\s-]), collapses whitespace/underscores to single hyphens, and truncates to at most 50 characters (us-XXXX-)..md - Sequential Numbering:
StoryEngine.get_next_story_number()scans bothdocs/project/user_stories/*/.mdfilenames anddocs/project/user_stories/REGISTRY.mdentries (US-(\d+)) to allocatemax_num + 1.
2. `PERSONAS.md` Document Structure & Grammar
docs/project/user_stories/PERSONAS.md is a single multi-section Markdown document that defines every human stakeholder and autonomous agent archetype interacting with the system.
2.1 Document AST Grammar
- H1 Document Header:
- Must begin with
# SpecOps User Personasfollowed by a brief introductory paragraph and a horizontal rule (---).
- H2 Persona Archetype Sections:
- Each archetype is delimited by an H2 heading matching: ``
markdown ##``. β - Supported separators between
andare em-dash (β), en-dash (β), or hyphen (-). - Sections are separated by horizontal dividers (
---).
- Required Bullet Sub-sections:
- Role:- Pain Points:followed by an indented 2-space nested bullet list (-)- Goals with SpecOps:(or- Goals...:) followed by an indented 2-space nested bullet list (-)
2.2 Canonical `PERSONAS.md` Example
# SpecOps User Personas
Archetypes representing the software architects, engineering leads, and autonomous AI agents who interact with and rely on SpecOps.
---
## 1. Alex β The Agentic Systems Architect
- **Role**: Staff engineer and platform architect building complex, distributed systems with AI coding assistants.
- **Pain Points**:
- Context rot when specifications stored in external SaaS tools (Jira, Linear) drift from git code.
- Monolithic file sprawl (>500 lines) causing LLMs to lose context and introduce subtle bugs.
- **Goals with SpecOps**:
- Version-lock all project specifications (Personas, PRDs, Stories, Tasks, ADRs) in git alongside code.
- Non-negotiable file length caps (<500 lines) keeping codebases modular and LLM-friendly.
2.3 Parser Extraction Rules (`parse_personas` & `PersonaDocument`)
SpecOps provides two complementary parsers for PERSONAS.md:
- Graph & Core Domain Parser (
parse_personasinsrc/spec_ops/core/parser.py):
- Splits the file on
\n##\s+and iterates over each H2 block (sections[1:]). - Name Extraction: Matches
r"\d+\.\s*([^ββ-]+)"on the H2 header line. - Role Title Extraction: Matches
r"[ββ-]\s*(.+)$"on the H2 header line. - Canonical Persona ID (
id): Derived from the first token ofnamein lowercase (name.lower().split()[0], e.g.,"Alex"$\rightarrow$"alex"). - Pain Points Extraction: Matches
r"- \\Pain Points\\:(.?)(?=- \\*|\Z)"withre.DOTALLand strips leading-from each nested bullet line. - Goals Extraction: Matches
r"- \\Goals.?\\:(.?)(?=- \\|\Z)"withre.DOTALLand strips leading-from each nested bullet line. - Produces
Persona(id, name, role, pain_points, goals, raw_markdown, file_path)domain objects defined insrc/spec_ops/core/models.py.
- Round-Trip Document Model (
PersonaDocument.parseinsrc/spec_ops/core/persona_models.py):
- Parses
PERSONAS.mdintoPersonaDocumentcontainingPersonaProfile(name, role, role_description, pain_points, goals, goals_label, index, custom_notes)objects. - Extracts
- Role:description viar"-\s+\\Role\\:\s*([^\n]+)". - Supports lossless round-trip serialization (
doc.serialize()) and automated synthesis of emerging archetypes discovered duringspec-ops persona auditandspec-ops persona sync.
- Composite Persona Mention Resolution (
PersonaEngine.extract_persona_mentions):
- PRD
target_persona, User Storypersona, and Git commitSpecOps-Personatrailers may reference composite archetypes separated by&orand(e.g.,"Alex & Jordan"or"Alex (The Agentic Systems Architect)"). PersonaEnginesplits onr"(?:\s+&\s+|\s+and\s+)(?![^(]*\))"and matches each mention case-insensitively against registeredPersona.id,Persona.name, orPersona.role.
3. User Story YAML Frontmatter Schema (`UserStoryFrontmatter`)
Every file in docs/project/user_stories/accepted/us-XXXX- must begin with a YAML frontmatter block (--- ... ---) validated against UserStoryFrontmatter in src/spec_ops/core/schema_validator.py.
3.1 Field Reference Table
| Field | Type | Required | Default | Description & Constraints | ||
|---|---|---|---|---|---|---|
id |
`str \ | int (Any`) |
Yes | β | Four-digit zero-padded string ('0133') or canonical ID ('US-0133'). Normalized to US-XXXX by parse_user_story. |
|
title |
str |
Yes | β | Human-readable user story title matching the H1 heading and REGISTRY.md entry. |
||
persona |
str |
Yes | β | Target persona name or composite reference (e.g., "Alex", "Alex (The Agentic Systems Architect)", "Alex & Jordan"). Must resolve to a known persona in PERSONAS.md. |
||
governing_prd |
str |
Yes | β | Canonical ID of the parent PRD in docs/project/product/ (e.g., "PRD-0008"). Verified for relational existence by StoryEngine.trace(). |
||
status |
str |
No | "Accepted" |
Lifecycle status of the story ("Accepted" for active stories in accepted/). |
||
created |
`date \ | str \ | None` | No | None |
ISO-8601 creation date (YYYY-MM-DD). |
feature |
Optional[str] |
No | None |
Feature cluster identifier (FEAT-, e.g., "FEAT-SPEC-01"). Displayed in REGISTRY.md. |
||
target_bc |
Optional[str] |
No | None |
Target DDD bounded context slug (e.g., "core", "docs", "cli"). |
||
scenarios |
Optional[list[str]] |
No | None |
Summary list of Gherkin scenario titles covered by this user story. | ||
outcome_id |
`Optional[int \ | str]` | No | None |
Optional 1-indexed PRD Checkable Outcome identifier used by src/spec_ops/prd/delta.py during incremental PRD delta decomposition (find_existing_stories). Note: under strict UserStoryFrontmatter (extra="forbid"), persisted stories in accepted/ omit outcome_id unless explicitly permitted by schema extensions. |
3.2 Strict `extra="forbid"` Policy: What Can and Cannot Be Tracked
UserStoryFrontmatter enforces model_config = ConfigDict(extra="forbid") under SpecOps Schema v2.0 (src/spec_ops/core/schema_validator.py). Any unrecognized YAML key raises a SchemaDiagnosticError with err_type == "extra_forbidden" pinpointing the exact file, line, and column:
error: Schema Validation Error in docs/project/user_stories/accepted/us-0133-example.md:11:1
|
11 | dependencies: [TASK-0001]
| ^ Forbidden extra field 'dependencies' in schema v2.0
- Allowed in User Story Frontmatter:
- Identity and lifecycle metadata (
id,title,status,created). - Upward product & persona lineage (
persona,governing_prd,feature,target_bc). - High-level scenario index (
scenarios). - Forbidden in User Story Frontmatter (tracked in other document classes instead):
- Execution & Queue State (
dependencies,claimed_by,branch,priority_rank,slice_type,blocker,mutation_scope): Tracked exclusively inTaskFrontmatter(docs/project/backlog/). - Dual-Custody Sign-Off & Commit Provenance (
signed_off_by,signed_off_at,has_signed_commits,commit_signature_status,prs): Tracked on implementingTaskdocuments and Git commit trailers. - Plural Linkage Keys (
governing_prds,governing_adrs,governing_stories): Tasks link to multiple stories/PRDs/ADRs, whereas a User Story has a singlegoverning_prdstring andpersonastring. - UAT Sign-Off Receipts: Customer acceptance sign-off state (
outcome_id,status: verified, cryptographic receipt hashes) is stored indocs/project/product/uat_receipts.json, never mutated into User Story frontmatter.
4. User Story Markdown Body AST Grammar
Following the closing --- frontmatter delimiter, the Markdown body of a user story must follow a deterministic section structure so parse_user_story (src/spec_ops/core/parser.py) and StoryEngine (src/spec_ops/core/story_engine.py) can extract domain attributes without ambiguity.
4.1 Required & Optional Sections
- H1 Title Heading (
# US-XXXX β):
- Uses an em-dash (
β) separating the canonical story ID (US-XXXX) and the story title.
- Governing PRD Section (
## Governing PRD):
- Contains a bulleted relative Markdown link to the governing PRD file in
docs/project/product/accepted/: ```markdown ## Governing PRD PRD-0008: Formal Specification Grammar, Document Metamodel & Project Directory Schema Engine```
- User Story Narrative Block (
## User Story):
- Contains the three canonical Connextra narrative clauses (
As a/As an,I want,So that).
- Executable Acceptance Criteria (
## Acceptance Criteria):
- Contains one or more fenced
`gherkincode blocks, each defining an executableScenario:withGiven,When,Thensteps.
- Optional Rationale Section (
## Rationale & Compelling Value):
- Provides architectural context or domain rationale below the acceptance criteria.
4.2 Narrative Clause Regex Extraction Rules
parse_user_story(file_path) in src/spec_ops/core/parser.py populates the UserStory(as_a, i_want, so_that, scenarios) fields using case-insensitive regular expressions across the document content:
UserStory Attribute |
Extraction Regex Pattern (re.IGNORECASE) |
Termination Delimiter |
|---|---|---|
as_a |
r"\\As an?\\\s*([^\n,]+)" |
Stops at the first comma (,) or newline (\n). Supports both As a and As an. |
i_want |
r"\\I want\\\s*([^\n,]+)" |
Stops at the first comma (,) or newline (\n). |
so_that |
r"\\So that\\\s*([^\n.]+)" |
Stops at the first period (.) or newline (\n). |
scenarios |
r"Scenario:\s*(.+)" (re.findall) |
Extracts the trimmed title of every Scenario: line inside the document body. |
[!IMPORTANT] Because
as_aandi_wantstop at the first comma (,) andso_thatstops at the first period (.), narrative clauses should place their trailing punctuation at the end of the line: ``markdown As an Alex (The Agentic Systems Architect), I want declarative reference specifications for all project documents, So that humans and autonomous agents can author valid specifications without guesswork.``
4.3 Executable Gherkin `Scenario:` Grammar & Frontdoor Verification Rules
Under ADR-0003 (Blackbox Frontdoor Verification) and ADR-0006 (Executable BDD User Stories), every user story in docs/project/user_stories/accepted/ acts as an executable specification:
- Fenced Gherkin Blocks:
- Scenarios are enclosed in
`gherkin ...`fenced code blocks under## Acceptance Criteria. - Each block begins with
Scenario:followed by indented step lines beginning withGiven,When,Then, orAnd.
- Public Frontdoor Setup & Assertions Only:
Given(Preconditions): Test setup must initialize state exclusively through public frontdoors (CLI commands, public configuration files, or public domain constructors)βnever by mutating private attributes or injecting mock objects.When(Action): Triggers an observable public entry point (e.g.,When the architect runs "spec-ops schema check").Then/And(Observable Outcomes): Verifies return codes, stdout/stderr diagnostics, generated files, or public domain return values.
- Zero Private Mock Backdoors:
- Acceptance tests and
pytest-bddstep definitions (tests/acceptance/) are audited byspec-ops audit-tests(src/spec_ops/quality/frontdoor_gate.py). - Reaching into
_privateattributes or patching internal module functions (unittest.mock.patchon internal domain methods) is a hard invariant violation.
4.4 Complete User Story Document Example
---
id: '0133'
title: "Comprehensive Reference Specifications for Project Document Structures and Configuration"
status: Accepted
created: 2026-10-15
persona: "Alex"
target_bc: "docs"
feature: "FEAT-SPEC-01"
governing_prd: "PRD-0008"
scenarios:
- "Authoring reference specifications for PRDs personas user stories ADRs and backlog queues"
---
# US-0133 β Comprehensive Reference Specifications for Project Document Structures and Configuration
## Governing PRD
- [`PRD-0008: Formal Specification Grammar, Document Metamodel & Project Directory Schema Engine`](../../product/accepted/prd-0008-formal-specification-grammar--document-metamo.md)
## User Story
**As an** Alex,
**I want** an autonomous capability to execute "Comprehensive Reference Specifications for Project Document Structures and Configuration",
**So that** business outcomes are delivered reliably across the docs bounded context.
## Acceptance Criteria
With the ## Acceptance Criteria section containing one or more fenced gherkin scenario blocks:
Scenario: Authoring reference specifications for PRDs personas user stories ADRs and backlog queues
Given the system is initialized and ready
When the user executes the workflow for "Authoring reference specifications for PRDs personas user stories ADRs and backlog queues"
Then observable outputs satisfy public contracts without backdoor tampering.
5. User Story Registry Specification (`docs/project/user_stories/REGISTRY.md`)
docs/project/user_stories/REGISTRY.md maintains a single-file tabular index of all accepted user stories, sorted in ascending numerical order by canonical Story ID (US-0001 through US-XXXX).
5.1 Pipe Table Schema & Column Grammar
The document begins with # User Stories Registry followed by a 6-column Markdown pipe table:
# User Stories Registry
| ID | Title | Status | Persona | Feature | Governing PRD |
|---|---|---|---|---|---|
| `US-0001` | Project Initialization with Architectural Profiles | Accepted | Alex | FEAT-CORE-01 | `PRD-0001` |
| `US-0117` | Autonomous Full-Lifecycle SDLC Orchestrator Skill & Multi-Agent Coordination | Accepted | Alex & Jordan | FEAT-ORCH-01 | `PRD-0006` |
| `US-0133` | Comprehensive Reference Specifications for Project Document Structures and Configuration | Accepted | Alex | FEAT-SPEC-01 | `PRD-0008` |
| Column | Format | Source & Normalization Rule in StoryEngine.update_registry |
||
|---|---|---|---|---|
ID |
` US-XXXX ` |
Backtick-quoted canonical 4-digit story identifier (`r"\ | \sUS-(\d+)\s\ |
"`). |
Title |
Plain text | Exact story title from frontmatter. |
||
Status |
Plain text | Lifecycle status (Accepted). |
||
Persona |
Plain text | Short persona display name with parenthetical role descriptions stripped (re.sub(r"\s\([^)]\)", "", persona).strip()). |
||
Feature |
Plain text | Feature code (FEAT-). |
||
Governing PRD |
` PRD-XXXX ` |
Backtick-quoted canonical PRD identifier (PRD-XXXX). |
5.2 Atomic Update & Traceability Rules
- Atomic File Replacement:
StoryEngine.update_registry()parses existing rows matching| \US-(\d+)\|, inserts or updates the row keyed by integer story number, sorts all rows by integer ID, writes toREGISTRY.md.tmp, and atomically replacesREGISTRY.md. - Bidirectional Traceability Audit (
StoryEngine.trace): - Verifies every
UserStoryindocs/project/user_stories/accepted/links to an existingPRDindocs/project/product/(governing_prd) and a registeredPersonainPERSONAS.md(persona). - Maps implementing backlog tasks (
task.governing_stories) and Git commit hashes (GitMetadataHarvester) back to each story, flagging stories without valid PRD or Persona links asorphaned_storiesandbroken_references.
6. CLI & Python Verification Reference
6.1 Public CLI Commands
# Audit persona coverage across PRDs, user stories, and git commits
uv run spec-ops persona audit
# Preview synthesized persona profiles for emerging archetypes
uv run spec-ops persona sync --diff
# Scaffold a new executable BDD user story and update REGISTRY.md
uv run spec-ops story create --title "Example Capability" --prd PRD-0008 --persona Alex --bc core --dry-run
# Audit bidirectional story traceability across Personas -> PRDs -> Stories -> Tasks -> Commits
uv run spec-ops story trace
# Validate UserStoryFrontmatter schema conformance across all specifications
uv run spec-ops schema check
6.2 Python Domain & Parser API
from pathlib import Path
from spec_ops.core.parser import parse_personas, parse_user_story
from spec_ops.core.schema_validator import validate_document
# 1. Parse PERSONAS.md into Persona(id, name, role, pain_points, goals) objects
personas = parse_personas(Path("docs/project/user_stories/PERSONAS.md"))
# 2. Parse a User Story file into a UserStory domain model
story_path = Path(
"docs/project/user_stories/accepted/us-0133-comprehensive-reference-specifications-for-project.md"
)
story = parse_user_story(story_path)
# 3. Validate UserStoryFrontmatter schema conformance (extra="forbid")
errors = validate_document(story_path.read_text(encoding="utf-8"), file_path=story_path)
assert len(errors) == 0