@fabersep/spec 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,379 @@
1
+ #!/usr/bin/env python3
2
+ """One faber-discuss round: send <ledger>/<tag>-prompt.md to a read-only reviewer CLI (agy or claude),
3
+ save the raw reply, and print status, conversation id, token usage, verdict, and phase totals.
4
+
5
+ Exit codes:
6
+ 0 reply read and formatted cleanly
7
+ 2 quota, rate limit, or authentication error (stop the run)
8
+ 3 timeout
9
+ 4 reply missing findings and VERDICT (or CLI error)
10
+ 5 reviewer did not resume --conversation and opened a new conversation"""
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import re
17
+ import shutil
18
+ import subprocess
19
+ import sys
20
+ import time
21
+ from pathlib import Path
22
+
23
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
24
+ from discuss_log import parse_findings # noqa: E402
25
+
26
+ AGY_PERMISSIONS = {"permissions": {"allow": ["read_file(*)"], "deny": ["write_file(*)", "edit_file(*)", "command(*)"]}}
27
+ CLAUDE_READONLY_TOOLS = "Read,Glob,Grep"
28
+ CLAUDE_DISALLOWED_TOOLS = "Edit,Write,Bash,Agent,WebSearch,WebFetch,NotebookEdit"
29
+
30
+ DEFAULT_MODELS = {
31
+ "agy": "gemini-4-neon-medium",
32
+ "claude": "opus",
33
+ }
34
+ # Cheapest models, strictly for testing the skill itself.
35
+ CHEAPEST_TEST_MODELS = {
36
+ "agy": ("gemini-3.8-flash-low", "gemini-3.8-flash-medium"),
37
+ "claude": ("haiku",),
38
+ }
39
+ WARM_MINUTES = 7
40
+ USAGE_KEYS = ("input_tokens", "output_tokens", "thinking_tokens", "cache_read_tokens", "total_tokens")
41
+ STOP_WORDS = re.compile(
42
+ r"quota|resource.?exhausted|rate.?limit|not logged in|login|unauthenticated|oauth|credit balance",
43
+ re.I,
44
+ )
45
+
46
+
47
+ def infer_cli(model: str | None) -> str | None:
48
+ """Infer reviewer CLI from model name when --cli is omitted."""
49
+ if not model:
50
+ return None
51
+ lower = model.lower()
52
+ if lower in ("haiku", "sonnet", "opus", "fable"):
53
+ return "claude"
54
+ if lower.startswith(("gemini-", "gpt-oss-")) or lower.endswith(("-low", "-medium", "-high", "-xhigh")):
55
+ return "agy"
56
+ if lower.startswith("claude-"):
57
+ return "claude"
58
+ return None
59
+
60
+
61
+ def default_cli() -> str:
62
+ """Pick an installed reviewer CLI if --cli is omitted and model does not disambiguate."""
63
+ if shutil.which("agy"):
64
+ return "agy"
65
+ if shutil.which("claude"):
66
+ return "claude"
67
+ return "agy"
68
+
69
+
70
+ def resolve_cli_and_model(cli: str | None, model: str | None, effort: str | None, test: bool) -> tuple[str, str]:
71
+ resolved_cli = cli or infer_cli(model) or default_cli()
72
+ if test:
73
+ allowed = CHEAPEST_TEST_MODELS[resolved_cli]
74
+ resolved_model = model or allowed[0]
75
+ if resolved_model not in allowed:
76
+ raise ValueError(
77
+ f"with --test on '{resolved_cli}', model must be one of the cheapest test models: {', '.join(allowed)}"
78
+ )
79
+ else:
80
+ resolved_model = model or DEFAULT_MODELS[resolved_cli]
81
+ if resolved_cli == "claude" and effort not in ("", "low", "medium", "high", "xhigh", "max"):
82
+ raise ValueError(f"invalid --effort for claude: {effort}")
83
+ return resolved_cli, resolved_model
84
+
85
+
86
+ def build_command(
87
+ cli: str,
88
+ model: str,
89
+ prompt: str,
90
+ timeout: int,
91
+ add_dirs: list[str],
92
+ conversation: str,
93
+ effort: str,
94
+ ) -> tuple[list[str], str | None]:
95
+ """Return (argv, stdin_text) for the chosen read-only reviewer CLI."""
96
+ if cli == "agy":
97
+ cmd = [
98
+ "agy",
99
+ "-p",
100
+ prompt,
101
+ "--model",
102
+ model,
103
+ "--disable-slash-commands",
104
+ "--print-timeout",
105
+ f"{timeout}s",
106
+ "--output-format",
107
+ "json",
108
+ "--settings",
109
+ json.dumps(AGY_PERMISSIONS),
110
+ ]
111
+ for folder in add_dirs:
112
+ cmd += ["--add-dir", folder]
113
+ if conversation:
114
+ cmd += ["--conversation", conversation]
115
+ return cmd, None
116
+
117
+ if cli == "claude":
118
+ cmd = [
119
+ "claude",
120
+ "-p",
121
+ "--model",
122
+ model,
123
+ "--disable-slash-commands",
124
+ "--permission-mode",
125
+ "plan",
126
+ "--tools",
127
+ CLAUDE_READONLY_TOOLS,
128
+ "--disallowedTools",
129
+ CLAUDE_DISALLOWED_TOOLS,
130
+ "--strict-mcp-config",
131
+ "--output-format",
132
+ "json",
133
+ ]
134
+ if effort:
135
+ cmd += ["--effort", effort]
136
+ for folder in add_dirs:
137
+ cmd += ["--add-dir", folder]
138
+ if conversation:
139
+ cmd += ["--resume", conversation]
140
+ return cmd, prompt
141
+
142
+ raise ValueError(f"unsupported reviewer CLI: {cli}")
143
+
144
+
145
+ def normalize_reply(cli: str, raw: dict, stderr: str) -> dict:
146
+ """Normalize agy and claude JSON payloads into a common ledger schema."""
147
+ if cli == "agy":
148
+ reply = dict(raw)
149
+ reply["cli"] = "agy"
150
+ if stderr.strip():
151
+ reply["stderr"] = stderr[-4000:]
152
+ return reply
153
+
154
+ # Claude -p --output-format json normalization
155
+ raw_usage = raw.get("usage") or {}
156
+ cache_write = int(raw_usage.get("cache_creation_input_tokens") or 0)
157
+ cache_read = int(raw_usage.get("cache_read_input_tokens") or 0)
158
+ inp = int(raw_usage.get("input_tokens") or 0) + cache_write
159
+ out = int(raw_usage.get("output_tokens") or 0)
160
+ is_error = bool(raw.get("is_error"))
161
+ has_payload = bool(raw.get("session_id") or raw.get("result") is not None)
162
+ status = "ERROR" if (is_error or not has_payload) else "SUCCESS"
163
+ reply = {
164
+ "cli": "claude",
165
+ "status": status,
166
+ "conversation_id": raw.get("session_id", ""),
167
+ "response": raw.get("result", "") if isinstance(raw.get("result"), str) else "",
168
+ "num_turns": raw.get("num_turns"),
169
+ "usage": {
170
+ "input_tokens": inp,
171
+ "output_tokens": out,
172
+ "thinking_tokens": 0,
173
+ "cache_read_tokens": cache_read,
174
+ "total_tokens": inp + out,
175
+ },
176
+ "total_cost_usd": raw.get("total_cost_usd"),
177
+ "usage_cumulative": False,
178
+ "raw_provider": raw,
179
+ }
180
+ if is_error and raw.get("result"):
181
+ reply["error"] = str(raw.get("result"))[:1000]
182
+ if stderr.strip():
183
+ reply["stderr"] = stderr[-4000:]
184
+ return reply
185
+
186
+
187
+ def _parse_stdout(stdout: str, stderr: str) -> dict:
188
+ try:
189
+ return json.loads(stdout)
190
+ except json.JSONDecodeError:
191
+ return {"status": "ERROR", "is_error": True, "response": "", "raw": stdout[-4000:], "stderr": stderr[-4000:]}
192
+
193
+
194
+ def _round_order(path: Path) -> tuple[int, int]:
195
+ phase, rnd = path.name.split("-")[:2]
196
+ return int(phase[1:]), int(rnd[1:])
197
+
198
+
199
+ def round_usage(ledger: Path) -> list[tuple[str, dict[str, int]]]:
200
+ """Per-round token usage, handling agy's cumulative conversation totals vs per-turn claude totals."""
201
+ out: list[tuple[str, dict[str, int]]] = []
202
+ last: dict[str, dict[str, int]] = {}
203
+ for path in sorted(ledger.glob("p*-r*-reply.json"), key=_round_order):
204
+ reply = json.loads(path.read_text())
205
+ usage = {k: int(reply.get("usage", {}).get(k, 0) or 0) for k in USAGE_KEYS}
206
+ is_cumulative = reply.get("usage_cumulative", reply.get("cli", "agy") == "agy")
207
+ conv = reply.get("conversation_id", "")
208
+ if is_cumulative:
209
+ prev = last.get(conv) if conv else None
210
+ if prev and all(usage[k] >= prev[k] for k in USAGE_KEYS):
211
+ delta = {k: usage[k] - prev[k] for k in USAGE_KEYS}
212
+ else:
213
+ delta = usage
214
+ if conv:
215
+ last[conv] = usage
216
+ else:
217
+ delta = usage
218
+ out.append((path.name.split("-reply")[0], delta))
219
+ return out
220
+
221
+
222
+ def _totals(ledger: Path) -> dict[str, int]:
223
+ totals: dict[str, int] = {}
224
+ for name, usage in round_usage(ledger):
225
+ phase = name.split("-")[0]
226
+ totals[phase] = totals.get(phase, 0) + usage["total_tokens"]
227
+ return totals
228
+
229
+
230
+ def _minutes_since_last(ledger: Path, conversation: str, now: float) -> float | None:
231
+ times = [
232
+ json.loads(p.read_text()).get("finished_at")
233
+ for p in ledger.glob("p*-r*-reply.json")
234
+ if json.loads(p.read_text()).get("conversation_id") == conversation
235
+ ]
236
+ times = [t for t in times if isinstance(t, (int, float))]
237
+ return (now - max(times)) / 60 if times else None
238
+
239
+
240
+ def _log_round(
241
+ ledger: Path,
242
+ tag: str,
243
+ cli: str,
244
+ model: str,
245
+ test: bool,
246
+ conversation_requested: str,
247
+ add_dir: list[str],
248
+ timeout: int,
249
+ started: float,
250
+ reply: dict,
251
+ code: int,
252
+ prompt_chars: int,
253
+ ) -> None:
254
+ text = reply.get("response", "")
255
+ usage = dict(round_usage(ledger)).get(tag, {}) if reply else {}
256
+ verdict = re.findall(r"VERDICT:\s*(CONTINUE|DONE)", text)
257
+ row = {
258
+ "tag": tag,
259
+ "cli": cli,
260
+ "model": model,
261
+ "test": test,
262
+ "conversation_requested": conversation_requested,
263
+ "conversation_id": reply.get("conversation_id", ""),
264
+ "started_at": started,
265
+ "finished_at": reply.get("finished_at", time.time()),
266
+ "gap_minutes": reply.get("gap_minutes"),
267
+ "status": reply.get("status", "TIMEOUT" if code == 3 else ""),
268
+ "exit_code": code,
269
+ "num_turns": reply.get("num_turns"),
270
+ "usage": usage,
271
+ "usage_reported": reply.get("usage", {}),
272
+ "prompt_chars": prompt_chars,
273
+ "reply_chars": len(text),
274
+ "verdict": verdict[-1] if verdict else "",
275
+ "findings": parse_findings(text),
276
+ "owner_questions": sorted(set(re.findall(r"\bOQ-\d+\b", text))),
277
+ "add_dir": add_dir,
278
+ "timeout": timeout,
279
+ }
280
+ with (ledger / "rounds.jsonl").open("a") as handle:
281
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
282
+
283
+
284
+ def _report(ledger: Path, reply: dict, text: str, stderr: str) -> int:
285
+ rounds = round_usage(ledger)
286
+ usage = rounds[-1][1] if rounds else {}
287
+ print(f"cli: {reply.get('cli', 'agy')} status: {reply.get('status')} conversation_id: {reply.get('conversation_id', '')}")
288
+ print(
289
+ f"tokens this round: uncached {usage.get('total_tokens', 0)}, input {usage.get('input_tokens', 0)}, "
290
+ f"cache read {usage.get('cache_read_tokens', 0)}, turns {reply.get('num_turns', 0)}"
291
+ )
292
+ if reply.get("gap_minutes") is not None:
293
+ cold = " (cache likely cold: history may be re-read)" if reply["gap_minutes"] > WARM_MINUTES else ""
294
+ print(f"gap since the last round: {reply['gap_minutes']} min{cold}")
295
+ history = int(reply.get("usage", {}).get("input_tokens", 0) or 0)
296
+ print(f"next round: send within {WARM_MINUTES} min to keep the prompt cache; cold input is about {history}")
297
+ print("totals so far: " + ", ".join(f"{phase} {total}" for phase, total in _totals(ledger).items()))
298
+ if reply.get("status") != "SUCCESS":
299
+ found = stderr + reply.get("raw", "") + str(reply.get("error", "")) + text
300
+ print(f"ERROR: {(reply.get('error') or reply.get('raw') or stderr or text)[:600]}")
301
+ if "DEADLINE_EXCEEDED" in found or "print timeout" in found:
302
+ return 3
303
+ return 2 if STOP_WORDS.search(found) else 4
304
+ verdict = re.findall(r"VERDICT:\s*(CONTINUE|DONE)", text)
305
+ findings = re.findall(r"\bF-\d+\b", text)
306
+ print(f"verdict: {verdict[-1] if verdict else 'none'} finding ids: {len(set(findings))}")
307
+ return 0 if verdict or findings else 4
308
+
309
+
310
+ def _parse() -> argparse.Namespace:
311
+ parser = argparse.ArgumentParser()
312
+ parser.add_argument("ledger")
313
+ parser.add_argument("tag", help="p1-r1, p2-r3, ...")
314
+ parser.add_argument("--cli", choices=("agy", "claude"), default=None)
315
+ parser.add_argument("--model", default=None)
316
+ parser.add_argument("--effort", default="", help="reasoning effort for claude CLI (low, medium, high)")
317
+ parser.add_argument("--conversation", default="")
318
+ parser.add_argument("--add-dir", action="append", default=[])
319
+ parser.add_argument("--timeout", type=int, default=540)
320
+ parser.add_argument("--test", action="store_true", help="enforce cheapest model for testing the skill itself")
321
+ return parser.parse_args()
322
+
323
+
324
+ def main() -> int:
325
+ args = _parse()
326
+ try:
327
+ cli, model = resolve_cli_and_model(args.cli, args.model, args.effort, args.test)
328
+ except ValueError as exc:
329
+ print(f"ERROR: {exc}", file=sys.stderr)
330
+ return 2
331
+
332
+ ledger = Path(args.ledger)
333
+ prompt = (ledger / f"{args.tag}-prompt.md").read_text()
334
+ command, stdin_text = build_command(
335
+ cli=cli,
336
+ model=model,
337
+ prompt=prompt,
338
+ timeout=args.timeout,
339
+ add_dirs=args.add_dir,
340
+ conversation=args.conversation,
341
+ effort=args.effort,
342
+ )
343
+ started = time.time()
344
+ try:
345
+ done = subprocess.run(
346
+ command,
347
+ input=stdin_text,
348
+ capture_output=True,
349
+ text=True,
350
+ timeout=args.timeout + 30,
351
+ check=False,
352
+ )
353
+ except subprocess.TimeoutExpired:
354
+ print("TIMEOUT: no answer within the limit")
355
+ _log_round(ledger, args.tag, cli, model, args.test, args.conversation, args.add_dir, args.timeout, started, {}, 3, len(prompt))
356
+ return 3
357
+
358
+ raw = _parse_stdout(done.stdout, done.stderr)
359
+ reply = normalize_reply(cli, raw, done.stderr)
360
+ reply["finished_at"] = time.time()
361
+ if args.conversation:
362
+ gap = _minutes_since_last(ledger, args.conversation, started)
363
+ if gap is not None:
364
+ reply["gap_minutes"] = round(gap, 1)
365
+
366
+ (ledger / f"{args.tag}-reply.json").write_text(json.dumps(reply, indent=2, ensure_ascii=False))
367
+ text = reply.get("response", "")
368
+ (ledger / f"{args.tag}-reply.md").write_text(text)
369
+
370
+ code = _report(ledger, reply, text, done.stderr)
371
+ if code == 0 and args.conversation and reply.get("conversation_id") != args.conversation:
372
+ print(f"NEW CONVERSATION: asked to resume {args.conversation}, reviewer answered in {reply.get('conversation_id')}")
373
+ code = 5
374
+ _log_round(ledger, args.tag, cli, model, args.test, args.conversation, args.add_dir, args.timeout, started, reply, code, len(prompt))
375
+ return code
376
+
377
+
378
+ if __name__ == "__main__":
379
+ sys.exit(main())
@@ -0,0 +1,46 @@
1
+ ---
2
+ name: faber-extract-features
3
+ description: Scan an existing (brownfield) repository to identify its discrete capabilities and generate docs/features/<NN>-<slug>/prd.md and acceptance_criteria.md for each feature, plus docs/features/README.md. Use when bringing an existing codebase into FaberSEP's spec-driven standard, or when the user runs faber-extract-features.
4
+ ---
5
+
6
+ # faber-extract-features — Brownfield Feature Extraction
7
+
8
+ Discover discrete, user-facing or core domain features in an existing codebase and generate a clean `prd.md` and `acceptance_criteria.md` (BDD) for each, plus a feature index at `docs/features/README.md`.
9
+
10
+ ## Step 1: Load Rules and Templates
11
+
12
+ Read these files relative to this `SKILL.md` (or from `~/.faber/spec/` if installed as a standalone skill in Codex/Cursor) first:
13
+ 1. `../../rules/documentation-rules.md` (fallback: `~/.faber/spec/rules/documentation-rules.md`)
14
+ 2. `../../templates/feature-prd.md` (fallback: `~/.faber/spec/templates/feature-prd.md`)
15
+ 3. `../../templates/feature-bdd.md` (fallback: `~/.faber/spec/templates/feature-bdd.md`)
16
+
17
+ ## Step 2: Discover Features from Codebase Reality
18
+
19
+ 1. **Read existing project docs** if present: `docs/master-prd.md`, `docs/architecture.md`, `README.md`, and any existing `docs/features/` folders (never duplicate already-documented features).
20
+ 2. **Map the codebase:**
21
+ - If **Atlas MCP** is available, use `map` (`zoom: 0` / `zoom: 1`) and `hubs` to identify cohesive feature slices (CLI commands, MCP tools, API domains, UI flows, core engines).
22
+ - Otherwise inspect the source tree, entry points, and existing test suites.
23
+ 3. **Group into 3–10 cohesive feature slices:**
24
+ - Each feature must represent a meaningful capability (e.g., `01-ast-scanning`, `02-dependency-graph-queries`, `03-mcp-server`, `04-code-health`), not trivial helper utilities.
25
+ - Ignore pure internal plumbing unless it is a standalone user-facing capability.
26
+ 4. **Confirm scope when helpful:** If the feature list is large (> 6 features) or ambiguous, show the proposed numbered feature list first or proceed directly when the user asked for full extraction.
27
+
28
+ ## Step 3: Generate Feature Specs
29
+
30
+ For each feature `<NN>-<slug>` (e.g., `01-core-scan`):
31
+ 1. Create `docs/features/<NN>-<slug>/prd.md` following `templates/feature-prd.md`:
32
+ - Ground every `FR-XX` strictly in verified implemented behavior (mark planned/missing items explicitly as `Planned`, never as `Implemented`).
33
+ - Do not put internal code identifiers in functional requirements.
34
+ 2. Create `docs/features/<NN>-<slug>/acceptance_criteria.md` following `templates/feature-bdd.md`:
35
+ - Write atomic `GIVEN / WHEN / THEN` scenarios (`AC-01`, `AC-02`, ...) covering happy path, edge cases, and error handling verified against the codebase and tests.
36
+ - Map every `AC-XX` back to its `FR-XX` in the Scenario Coverage Matrix.
37
+ - Zero internal variable/function/class names in scenarios.
38
+ 3. Create or update `docs/features/README.md` with a summary table linking every feature folder, its status, and a one-line description.
39
+
40
+ ## Definition of Done
41
+
42
+ - [ ] `docs/features/README.md` lists all extracted features with links and statuses.
43
+ - [ ] Every feature folder contains both `prd.md` and `acceptance_criteria.md` following the templates.
44
+ - [ ] Every `FR-XX` is covered by at least one `AC-XX` scenario.
45
+ - [ ] Zero invented features, zero code identifiers in BDD scenarios, zero unresolved placeholders.
46
+ - [ ] Report a concise summary of extracted features and any detected gaps to the user.
@@ -0,0 +1,44 @@
1
+ ---
2
+ name: faber-init-arch
3
+ description: Reverse-engineer (brownfield) or draft (greenfield) a verified docs/architecture.md for the current repository using the FaberSEP architecture template and documentation rules. Use when initializing documentation for a project, refreshing stale architecture docs from code, or when the user runs faber-init-arch.
4
+ ---
5
+
6
+ # faber-init-arch — Project Architecture Synthesis
7
+
8
+ Generate or refresh `docs/architecture.md` in the active repository, grounded strictly in verified codebase evidence (brownfield) or the user's stated design (greenfield).
9
+
10
+ ## Step 1: Load Rules and Template
11
+
12
+ Read these two files relative to this `SKILL.md` (or from `~/.faber/spec/` if installed as a standalone skill in Codex/Cursor) before inspecting or writing anything:
13
+ 1. `../../rules/documentation-rules.md` (fallback: `~/.faber/spec/rules/documentation-rules.md`)
14
+ 2. `../../templates/architecture.md` (fallback: `~/.faber/spec/templates/architecture.md`)
15
+
16
+ Follow every invariant in `documentation-rules.md` strictly.
17
+
18
+ ## Step 2: Inspect the Repository (Evidence First)
19
+
20
+ Determine whether the repository already has source code (brownfield) or is empty/new (greenfield).
21
+
22
+ ### Brownfield (Existing Codebase)
23
+ 1. **Use Atlas MCP if available:** If Atlas MCP tools (`map`, `hubs`, `brief`, `flow`) are connected in this session, call `map` (`zoom: 0` then `zoom: 1` on key directories) and `hubs` first to get a complete structural map with minimal tokens.
24
+ 2. **Direct inspection (fallback or verification):** Read the repository root listing, package/dependency manifest (`package.json`, `pyproject.toml`, `pubspec.yaml`, `Cargo.toml`, etc.), entry points, CLI/API/MCP definitions, config files, and test setup.
25
+ 3. **Trace 1–3 core execution flows:** Follow real entry points through core modules to outputs or storage. Verify every file path, exported symbol, CLI flag, or tool name directly in source.
26
+ 4. **Never guess:** Do not invent infrastructure, layers, or patterns that are not in the codebase. Record missing concerns honestly as `None` or `N/A` and log ambiguities under `GAP-XX`.
27
+
28
+ ### Greenfield (New / Empty Project)
29
+ If no source code exists yet, ask the user 3–5 concise questions covering runtime/language, archetype (CLI, library, API, web/mobile app, plugin), storage/external dependencies, and key boundaries. Draft `docs/architecture.md` with `status: draft` and record open decisions under `GAP-XX`.
30
+
31
+ ## Step 3: Write `docs/architecture.md`
32
+
33
+ - Write directly to `<workspace>/docs/architecture.md` (create `docs/` if needed). Never copy template or rule files into the user's repository.
34
+ - Match the structure of `templates/architecture.md`, adapting subsections to the actual project archetype (omit or mark `N/A` any inapplicable interface subsections).
35
+ - Set frontmatter `last_updated` to today's date (`YYYY-MM-DD`) and `status: draft`.
36
+ - If `docs/architecture.md` already exists, update only the sections that changed and report what was updated.
37
+
38
+ ## Definition of Done
39
+
40
+ - [ ] `docs/architecture.md` exists and follows `templates/architecture.md`.
41
+ - [ ] Every file path, module name, command, and interface mentioned was verified in source (or explicitly marked as greenfield draft).
42
+ - [ ] Cross-cutting concerns table is honestly populated (`Implemented`, `Partial`, `None`, or `N/A`).
43
+ - [ ] Zero unresolved template placeholders (`<...>`, `{{...}}`, `[TODO]`).
44
+ - [ ] Summarize key architectural findings and any `GAP-XX` items for the user to review.
@@ -0,0 +1,38 @@
1
+ ---
2
+ name: faber-init-prd
3
+ description: Synthesize docs/master-prd.md (product vision, personas, core user journeys, capabilities, non-goals, KPIs, and gaps) for the current repository using the FaberSEP Master PRD template. Use when creating or refreshing a project's Master PRD, or when the user runs faber-init-prd.
4
+ ---
5
+
6
+ # faber-init-prd — Master PRD Synthesis
7
+
8
+ Generate or refresh `docs/master-prd.md` in the active repository, defining **WHAT** the product does and **WHY** in clear, domain-authentic product language.
9
+
10
+ ## Step 1: Load Rules and Template
11
+
12
+ Read these two files relative to this `SKILL.md` (or from `~/.faber/spec/` if installed as a standalone skill in Codex/Cursor) before writing anything:
13
+ 1. `../../rules/documentation-rules.md` (fallback: `~/.faber/spec/rules/documentation-rules.md`)
14
+ 2. `../../templates/master-prd.md` (fallback: `~/.faber/spec/templates/master-prd.md`)
15
+
16
+ ## Step 2: Gather Ground Truth
17
+
18
+ 1. **Read `docs/architecture.md` first** if it exists (recommend running `faber-init-arch` first for brownfield codebases if it is missing, or inspect the codebase directly if the user wants to proceed immediately).
19
+ 2. **Inspect project context:** Read `README.md`, `ROADMAP.md` (if present), package manifest, and existing `docs/features/` (if any).
20
+ 3. **Use Atlas MCP if available** (`map`, `hubs`) to verify major user-facing capabilities and entry points when documenting an existing codebase.
21
+ 4. **Greenfield mode:** If the repository has no code or README yet, ask the user 3–5 focused questions (problem, primary persona, core workflow, non-goals, target platform) before drafting.
22
+
23
+ ## Step 3: Write `docs/master-prd.md`
24
+
25
+ - Write directly to `<workspace>/docs/master-prd.md`. Never copy template or rule files into the user's repository.
26
+ - Follow `templates/master-prd.md` strictly:
27
+ - Keep it **product-centric ("WHAT & WHY")**, not a repetition of low-level code details from `docs/architecture.md`.
28
+ - Tailor personas, journeys, constraints, and KPIs to the actual product archetype (CLI, library, MCP server, API, web/mobile app, plugin). Do not inject irrelevant mobile/monetization boilerplate into non-applicable projects.
29
+ - Number all non-goals (`NG-01`, `NG-02`, ...) and context gaps (`GAP-01`, `GAP-02`, ...).
30
+ - Set frontmatter `last_updated` to today's date (`YYYY-MM-DD`) and `status: draft`.
31
+
32
+ ## Definition of Done
33
+
34
+ - [ ] `docs/master-prd.md` exists and follows `templates/master-prd.md`.
35
+ - [ ] Personas, journeys, capabilities, and constraints accurately reflect the real product domain.
36
+ - [ ] Non-goals (`NG-XX`) and gaps (`GAP-XX`) are explicit and numbered.
37
+ - [ ] Zero hallucinated metrics/formulas and zero unresolved placeholders (`<...>`, `{{...}}`, `[TODO]`).
38
+ - [ ] Present a concise key-point summary of the draft Master PRD so the owner can approve or adjust it quickly.
@@ -0,0 +1,51 @@
1
+ ---
2
+ name: faber-new-feature
3
+ description: Specify a new feature from an idea by clarifying missing product dimensions first, then generating docs/features/<NN>-<slug>/prd.md and acceptance_criteria.md (BDD) aligned with the project's Master PRD and architecture. Use before building any new capability, or when the user runs faber-new-feature.
4
+ ---
5
+
6
+ # faber-new-feature — Greenfield Feature Specification
7
+
8
+ Turn a feature idea into an owner-ready `prd.md` and `acceptance_criteria.md` (BDD) before writing implementation code.
9
+
10
+ ## Step 1: Load Rules and Templates
11
+
12
+ Read these files relative to this `SKILL.md` (or from `~/.faber/spec/` if installed as a standalone skill in Codex/Cursor) first:
13
+ 1. `../../rules/documentation-rules.md` (fallback: `~/.faber/spec/rules/documentation-rules.md`)
14
+ 2. `../../templates/feature-prd.md` (fallback: `~/.faber/spec/templates/feature-prd.md`)
15
+ 3. `../../templates/feature-bdd.md` (fallback: `~/.faber/spec/templates/feature-bdd.md`)
16
+
17
+ ## Step 2: Check Existing Project Context
18
+
19
+ Read if present in the active repository:
20
+ - `docs/master-prd.md` (align terminology, personas, and non-goals)
21
+ - `docs/architecture.md` (respect real system boundaries and constraints)
22
+ - `docs/features/README.md` (determine the next sequential feature number `<NN>` and avoid slug collisions)
23
+
24
+ ## Step 3: Clarify Missing Dimensions (Before Writing)
25
+
26
+ Evaluate the user's request across 5 dimensions:
27
+ 1. **Caller / Persona:** Who triggers this feature and what permissions or context do they have?
28
+ 2. **Happy Path vs. Edge Cases:** What happens on empty input, invalid arguments, conflicts, or failures?
29
+ 3. **State / Persistence:** Is anything stored on disk, cached, or stateless?
30
+ 4. **External Interfaces / Compatibility:** Does this change a CLI flag, API, MCP schema, or file format?
31
+ 5. **Boundaries / Non-Goals:** What is explicitly out of scope for the first version?
32
+
33
+ - If key dimensions are unclear, ask **3 to 5 concise, numbered questions** (with a recommended default for each) and wait for the user's answers before generating the spec.
34
+ - If the user already provided enough detail to specify cleanly, state your assumptions briefly and proceed directly.
35
+
36
+ ## Step 4: Generate `prd.md` and `acceptance_criteria.md`
37
+
38
+ 1. Create `docs/features/<NN>-<slug>/prd.md` following `templates/feature-prd.md` (`status: draft`, `last_updated: YYYY-MM-DD`).
39
+ 2. Create `docs/features/<NN>-<slug>/acceptance_criteria.md` following `templates/feature-bdd.md` (`status: draft`, `last_updated: YYYY-MM-DD`):
40
+ - Cover happy path, boundary/edge cases, and error handling with atomic `GIVEN / WHEN / THEN` scenarios (`AC-01`, ...).
41
+ - Map every `FR-XX` to one or more `AC-XX` rows in the Scenario Coverage Matrix.
42
+ - Use plain product/behavioral language — never internal variable or function names.
43
+ 3. Update `docs/features/README.md` (create it if it does not exist) with the new feature row.
44
+
45
+ ## Definition of Done
46
+
47
+ - [ ] `docs/features/<NN>-<slug>/prd.md` and `acceptance_criteria.md` are created with `status: draft`.
48
+ - [ ] `docs/features/README.md` is updated with the new feature.
49
+ - [ ] Every `FR-XX` maps to at least one atomic `AC-XX` scenario.
50
+ - [ ] Zero code identifiers in BDD scenarios and zero unresolved placeholders.
51
+ - [ ] Present a short key-point summary of the spec so the owner can approve it before implementation starts.