specnest 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
specnest/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """SpecNest provides reusable spec-driven workflow tools.
2
+
3
+ Plans (docs/plans) and architecture decision records (docs/architecture/decisions)
4
+ are Markdown files with YAML front matter. Humans curate and approve them; AI agents implement approved plan tasks.
5
+ """
6
+
7
+ __version__ = "1.0.0"
specnest/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+
4
+ raise SystemExit(main())
specnest/cli.py ADDED
@@ -0,0 +1,190 @@
1
+ """Command line interface: python -m specnest <command>."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from pathlib import Path
9
+ from typing import Callable, Dict, List, Optional
10
+
11
+ from . import __version__
12
+ from .model import ADR, PLAN, TASK_STATUSES, Repo
13
+ from .parser import SpecnestError, find_root, load_repo
14
+ from .rules import validate_repo
15
+ from .workflow import (
16
+ approve,
17
+ document_summary,
18
+ new_document,
19
+ next_task,
20
+ set_task_status,
21
+ task_brief,
22
+ )
23
+
24
+
25
+ EXIT_OK = 0
26
+ EXIT_FAILED = 1
27
+ EXIT_NO_READY_TASK = 3
28
+
29
+
30
+ def _cmd_validate(repo: Repo, args: argparse.Namespace) -> int:
31
+ issues = validate_repo(repo)
32
+ for issue in issues:
33
+ print(issue.format())
34
+ errors = sum(1 for issue in issues if issue.is_error)
35
+ warnings = len(issues) - errors
36
+ plans, adrs = len(repo.plans), len(repo.adrs)
37
+ if errors:
38
+ print(
39
+ f"FAILED: {errors} error(s), {warnings} warning(s) in {plans} plan(s) and {adrs} ADR(s)"
40
+ )
41
+ return EXIT_FAILED
42
+ print(f"OK: {plans} plan(s) and {adrs} ADR(s) valid, {warnings} warning(s)")
43
+ return EXIT_OK
44
+
45
+
46
+ def _cmd_list(repo: Repo, args: argparse.Namespace) -> int:
47
+ print("Plans")
48
+ for plan_id, plan in sorted(repo.plans.items()):
49
+ done = sum(1 for task in plan.tasks if task.status == "done")
50
+ progress = f"{done}/{len(plan.tasks)} done"
51
+ print(f" {plan_id} {plan.status:<9} {progress:<10} {plan.title}")
52
+ print("ADRs")
53
+ for adr_id, adr in sorted(repo.adrs.items()):
54
+ print(f" {adr_id} {adr.status:<9} {adr.title}")
55
+ return EXIT_OK
56
+
57
+
58
+ def _cmd_next(repo: Repo, args: argparse.Namespace) -> int:
59
+ task, notes = next_task(repo, args.plan)
60
+ if args.json:
61
+ if task is None:
62
+ print(json.dumps({"task": None, "reasons": notes}, indent=2))
63
+ else:
64
+ plan = repo.plan_of(task)
65
+ print(
66
+ json.dumps(
67
+ {
68
+ "task": task.id,
69
+ "title": task.title,
70
+ "status": task.status,
71
+ "agent": task.agent,
72
+ "plan": plan.id,
73
+ "plan_path": plan.path.as_posix(),
74
+ },
75
+ indent=2,
76
+ )
77
+ )
78
+ elif task is None:
79
+ print("No ready task.")
80
+ for note in notes:
81
+ print(f" - {note}")
82
+ else:
83
+ print(task_brief(repo, task), end="")
84
+ return EXIT_OK if task is not None else EXIT_NO_READY_TASK
85
+
86
+
87
+ def _cmd_show(repo: Repo, args: argparse.Namespace) -> int:
88
+ if args.id in repo.tasks:
89
+ print(task_brief(repo, repo.tasks[args.id]), end="")
90
+ return EXIT_OK
91
+ document = repo.find(args.id)
92
+ if document is None:
93
+ raise SpecnestError(f"unknown id {args.id}")
94
+ print(document_summary(repo, document), end="")
95
+ return EXIT_OK
96
+
97
+
98
+ def _cmd_task(repo: Repo, args: argparse.Namespace) -> int:
99
+ for message in set_task_status(repo, args.id, args.status, args.reason):
100
+ print(message)
101
+ return EXIT_OK
102
+
103
+
104
+ def _cmd_approve(repo: Repo, args: argparse.Namespace) -> int:
105
+ for message in approve(repo, args.id, args.by):
106
+ print(message)
107
+ return EXIT_OK
108
+
109
+
110
+ def _cmd_new(repo: Repo, args: argparse.Namespace) -> int:
111
+ path = new_document(
112
+ repo, PLAN if args.kind == "plan" else ADR, args.title, args.owner
113
+ )
114
+ print(f"created {path.relative_to(repo.root).as_posix()} (status: draft)")
115
+ return EXIT_OK
116
+
117
+
118
+ def build_parser() -> argparse.ArgumentParser:
119
+ parser = argparse.ArgumentParser(
120
+ prog="specnest",
121
+ description="Validate and drive spec-driven development.",
122
+ )
123
+ parser.add_argument("--version", action="version", version=f"specnest {__version__}")
124
+ parser.add_argument(
125
+ "--root",
126
+ type=Path,
127
+ help="repository root (default: auto-detected from the cwd)",
128
+ )
129
+ commands = parser.add_subparsers(dest="command", required=True, metavar="<command>")
130
+
131
+ commands.add_parser(
132
+ "validate", help="validate all plans and ADRs (exit 1 on errors)"
133
+ )
134
+ commands.add_parser("list", help="list plans and ADRs with status and progress")
135
+
136
+ next_parser = commands.add_parser(
137
+ "next", help=f"show the next ready task (exit {EXIT_NO_READY_TASK} if none)"
138
+ )
139
+ next_parser.add_argument("--plan", help="only consider this plan")
140
+ next_parser.add_argument(
141
+ "--json", action="store_true", help="machine-readable output"
142
+ )
143
+
144
+ show_parser = commands.add_parser("show", help="show a task brief, plan or ADR")
145
+ show_parser.add_argument("id", help="task, plan or ADR id")
146
+
147
+ task_parser = commands.add_parser(
148
+ "task", help="change a task's status (approved plans only)"
149
+ )
150
+ task_parser.add_argument("id", help="task id, e.g. PLAN-0001-T01")
151
+ task_parser.add_argument("--status", required=True, choices=TASK_STATUSES)
152
+ task_parser.add_argument(
153
+ "--reason", help="why the task is blocked (required for 'blocked')"
154
+ )
155
+
156
+ approve_parser = commands.add_parser(
157
+ "approve",
158
+ help="HUMAN ONLY: approve a plan / accept an ADR and seal its content",
159
+ )
160
+ approve_parser.add_argument("id", help="plan or ADR id")
161
+ approve_parser.add_argument("--by", required=True, help="approver GitHub handle")
162
+
163
+ new_parser = commands.add_parser("new", help="scaffold a new draft plan or ADR")
164
+ new_parser.add_argument("kind", choices=("plan", "adr"))
165
+ new_parser.add_argument("title")
166
+ new_parser.add_argument(
167
+ "--owner", help="GitHub handle of the owner (default: first approver)"
168
+ )
169
+ return parser
170
+
171
+
172
+ COMMANDS: Dict[str, Callable[[Repo, argparse.Namespace], int]] = {
173
+ "validate": _cmd_validate,
174
+ "list": _cmd_list,
175
+ "next": _cmd_next,
176
+ "show": _cmd_show,
177
+ "task": _cmd_task,
178
+ "approve": _cmd_approve,
179
+ "new": _cmd_new,
180
+ }
181
+
182
+
183
+ def main(argv: Optional[List[str]] = None) -> int:
184
+ args = build_parser().parse_args(argv)
185
+ try:
186
+ root = args.root.resolve() if args.root else find_root(Path.cwd())
187
+ return COMMANDS[args.command](load_repo(root), args)
188
+ except SpecnestError as exc:
189
+ print(f"specnest: error: {exc}", file=sys.stderr)
190
+ return EXIT_FAILED
specnest/edits.py ADDED
@@ -0,0 +1,122 @@
1
+ """Formatting-preserving edits of spec documents.
2
+
3
+ specnest only rewrites the specific lines it owns (front matter keys and task metadata
4
+ keys) so that human formatting and wording stay untouched.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ from typing import List, Optional
12
+
13
+ import yaml
14
+
15
+ from .parser import FENCE_OPEN_RE, SpecnestError, closes_fence, fence_mask
16
+
17
+
18
+ SAFE_PLAIN_RE = re.compile(r"[A-Za-z0-9][\w .,/()+-]*")
19
+ TRAILING_COMMENT_RE = re.compile(r"\s+#.*$")
20
+
21
+
22
+ def yaml_scalar(value: str) -> str:
23
+ """Render a string as a YAML scalar, quoting it only when needed."""
24
+ if SAFE_PLAIN_RE.fullmatch(value) and not value.endswith(" "):
25
+ try:
26
+ if yaml.safe_load(f"k: {value}") == {"k": value}:
27
+ return value
28
+ except yaml.YAMLError:
29
+ pass
30
+ return json.dumps(value, ensure_ascii=False)
31
+
32
+
33
+ def _trailing_comment(line: str) -> str:
34
+ value = line.partition(":")[2]
35
+ if '"' in value or "'" in value:
36
+ return ""
37
+ match = TRAILING_COMMENT_RE.search(value)
38
+ return match.group(0) if match else ""
39
+
40
+
41
+ def _front_end(lines: List[str]) -> int:
42
+ if not lines or lines[0].strip() != "---":
43
+ raise SpecnestError("document has no YAML front matter")
44
+ for index in range(1, len(lines)):
45
+ if lines[index].strip() == "---":
46
+ return index
47
+ raise SpecnestError("document has unterminated YAML front matter")
48
+
49
+
50
+ def _value_end(lines: List[str], index: int, end: int) -> int:
51
+ """Return the index after the last line of the YAML value of the key at `index`.
52
+
53
+ Indented continuation lines belong to the value, including blank lines inside block
54
+ scalars. Blank lines after the last indented line don't.
55
+ """
56
+ stop = cursor = index + 1
57
+ while cursor < end and (
58
+ not lines[cursor].strip() or lines[cursor][:1] in (" ", "\t")
59
+ ):
60
+ if lines[cursor].strip():
61
+ stop = cursor + 1
62
+ cursor += 1
63
+ return stop
64
+
65
+
66
+ def _replace_key(
67
+ lines: List[str], start: int, end: int, key: str, new_lines: Optional[List[str]]
68
+ ) -> bool:
69
+ """Replace (or delete, if new_lines is None) a top-level key and its whole value.
70
+
71
+ A trailing comment on a single-line value is kept when the replacement is one line.
72
+ """
73
+ key_re = re.compile(rf"^{re.escape(key)}\s*:")
74
+ for index in range(start, end):
75
+ if key_re.match(lines[index]):
76
+ stop = _value_end(lines, index, end)
77
+ replacement = list(new_lines or [])
78
+ if len(replacement) == 1 and stop == index + 1:
79
+ replacement[0] += _trailing_comment(lines[index])
80
+ lines[index:stop] = replacement
81
+ return True
82
+ return False
83
+
84
+
85
+ def set_front_lines(text: str, key: str, new_lines: Optional[List[str]]) -> str:
86
+ lines = text.split("\n")
87
+ end = _front_end(lines)
88
+ if not _replace_key(lines, 1, end, key, new_lines) and new_lines:
89
+ lines[end:end] = new_lines
90
+ return "\n".join(lines)
91
+
92
+
93
+ def set_front_value(text: str, key: str, rendered: str) -> str:
94
+ return set_front_lines(text, key, [f"{key}: {rendered}"])
95
+
96
+
97
+ def set_task_value(text: str, task_id: str, key: str, rendered: Optional[str]) -> str:
98
+ """Set (or remove, if rendered is None) a key in a task's ```yaml metadata block."""
99
+ lines = text.split("\n")
100
+ mask = fence_mask(lines, _front_end(lines) + 1)
101
+ heading_re = re.compile(rf"^###\s+{re.escape(task_id)}:\s")
102
+ for index, line in enumerate(lines):
103
+ if mask[index] or not heading_re.match(line):
104
+ continue
105
+ cursor = index + 1
106
+ while cursor < len(lines) and not lines[cursor].strip():
107
+ cursor += 1
108
+ opening = FENCE_OPEN_RE.match(lines[cursor]) if cursor < len(lines) else None
109
+ if not opening or opening.group("info").lower() not in ("yaml", "yml"):
110
+ raise SpecnestError(f"{task_id}: metadata block not found")
111
+ close = cursor + 1
112
+ while close < len(lines) and not closes_fence(
113
+ lines[close], opening.group("fence")
114
+ ):
115
+ close += 1
116
+ if close >= len(lines):
117
+ raise SpecnestError(f"{task_id}: unterminated metadata block")
118
+ new_lines = None if rendered is None else [f"{key}: {rendered}"]
119
+ if not _replace_key(lines, cursor + 1, close, key, new_lines) and new_lines:
120
+ lines[close:close] = new_lines
121
+ return "\n".join(lines)
122
+ raise SpecnestError(f"task {task_id} not found")
specnest/model.py ADDED
@@ -0,0 +1,169 @@
1
+ """Domain model for spec documents: plans, their tasks, and ADRs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+ from typing import Any, Dict, List, Optional, Set, Tuple
9
+
10
+
11
+ PLANS_DIR = Path("docs/plans")
12
+ ADRS_DIR = Path("docs/architecture/decisions")
13
+ AGENTS_DIR = Path(".github/agents")
14
+ TEMPLATES_DIR = Path("docs/templates")
15
+ CONFIG_FILE = Path("docs/specs.config.yaml")
16
+
17
+ PLAN = "plan"
18
+ ADR = "adr"
19
+
20
+ PLAN_ID_RE = re.compile(r"^PLAN-\d{4}$")
21
+ ADR_ID_RE = re.compile(r"^ADR-\d{4}$")
22
+ TASK_ID_RE = re.compile(r"^PLAN-\d{4}-T\d{2}$")
23
+
24
+ PLAN_STATUSES = ("draft", "review", "approved", "done", "abandoned")
25
+ ADR_STATUSES = ("draft", "proposed", "accepted", "rejected", "deprecated", "superseded")
26
+ TASK_STATUSES = ("todo", "in-progress", "done", "blocked")
27
+
28
+ # Statuses whose content is sealed by an approval digest.
29
+ PLAN_SEALED_STATUSES = ("approved", "done")
30
+ ADR_SEALED_STATUSES = ("accepted", "deprecated", "superseded")
31
+
32
+ # Fields that may change after approval without invalidating the seal.
33
+ MUTABLE_FRONT_KEYS = frozenset({"status", "updated", "approval", "superseded_by"})
34
+ MUTABLE_TASK_KEYS = frozenset({"status", "blocked_reason"})
35
+
36
+ REQUIRED_FRONT_KEYS = ("id", "title", "status", "owner", "created", "updated")
37
+ TASK_META_KEYS = frozenset({"status", "depends_on", "agent", "blocked_reason"})
38
+ DEFAULT_AGENT = "implementer"
39
+
40
+ PLAN_REQUIRED_SECTIONS = (
41
+ "Context",
42
+ "Goals",
43
+ "Non-goals",
44
+ "Approach",
45
+ "Tasks",
46
+ "Validation",
47
+ "Risks",
48
+ )
49
+ ADR_REQUIRED_SECTIONS = ("Context", "Decision", "Consequences")
50
+
51
+
52
+ @dataclass
53
+ class Section:
54
+ title: str
55
+ line: int
56
+ text: str
57
+
58
+
59
+ @dataclass
60
+ class Task:
61
+ id: str
62
+ title: str
63
+ plan_id: str
64
+ line: int
65
+ meta: Dict[str, Any] = field(default_factory=dict)
66
+ meta_error: Optional[str] = None
67
+ # 0-based indexes (opening fence, closing fence) of the metadata block in the file.
68
+ meta_span: Optional[Tuple[int, int]] = None
69
+ body: str = ""
70
+ acceptance_criteria: List[str] = field(default_factory=list)
71
+
72
+ @property
73
+ def status(self) -> str:
74
+ return str(self.meta.get("status", "todo"))
75
+
76
+ @property
77
+ def depends_on(self) -> List[str]:
78
+ return _as_str_list(self.meta.get("depends_on"))
79
+
80
+ @property
81
+ def agent(self) -> str:
82
+ return str(self.meta.get("agent") or DEFAULT_AGENT)
83
+
84
+ @property
85
+ def blocked_reason(self) -> Optional[str]:
86
+ reason = self.meta.get("blocked_reason")
87
+ return str(reason) if reason else None
88
+
89
+
90
+ @dataclass
91
+ class Document:
92
+ kind: str
93
+ path: Path
94
+ text: str
95
+ front: Dict[str, Any]
96
+ front_error: Optional[str]
97
+ front_end_line: int
98
+ h1: Optional[str]
99
+ h1_line: int
100
+ sections: List[Section]
101
+ tasks: List[Task]
102
+ malformed_task_headings: List[Section] = field(default_factory=list)
103
+
104
+ @property
105
+ def id(self) -> str:
106
+ return str(self.front.get("id", ""))
107
+
108
+ @property
109
+ def title(self) -> str:
110
+ return str(self.front.get("title", ""))
111
+
112
+ @property
113
+ def status(self) -> str:
114
+ return str(self.front.get("status", ""))
115
+
116
+ @property
117
+ def sealed(self) -> bool:
118
+ statuses = PLAN_SEALED_STATUSES if self.kind == PLAN else ADR_SEALED_STATUSES
119
+ return self.status in statuses
120
+
121
+ def section(self, title: str) -> Optional[Section]:
122
+ for section in self.sections:
123
+ if section.title.lower() == title.lower():
124
+ return section
125
+ return None
126
+
127
+ def list_field(self, key: str) -> List[str]:
128
+ return _as_str_list(self.front.get(key))
129
+
130
+
131
+ @dataclass
132
+ class Repo:
133
+ root: Path
134
+ approvers: List[str]
135
+ agents: Set[str]
136
+ documents: List[Document]
137
+ plans: Dict[str, Document]
138
+ adrs: Dict[str, Document]
139
+ tasks: Dict[str, Task]
140
+ load_issues: List[Issue]
141
+
142
+ def find(self, doc_id: str) -> Optional[Document]:
143
+ return self.plans.get(doc_id) or self.adrs.get(doc_id)
144
+
145
+ def plan_of(self, task: Task) -> Document:
146
+ return self.plans[task.plan_id]
147
+
148
+
149
+ @dataclass(frozen=True)
150
+ class Issue:
151
+ severity: str
152
+ path: str
153
+ line: int
154
+ message: str
155
+
156
+ @property
157
+ def is_error(self) -> bool:
158
+ return self.severity == "error"
159
+
160
+ def format(self) -> str:
161
+ return f"{self.path}:{self.line}: {self.severity}: {self.message}"
162
+
163
+
164
+ def _as_str_list(value: Any) -> List[str]:
165
+ if value is None:
166
+ return []
167
+ if isinstance(value, (list, tuple)):
168
+ return [str(item) for item in value]
169
+ return [str(value)]