devflow-toolkit 0.3.24__py3-none-any.whl → 0.3.25__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.
devflow/commands/init.py CHANGED
@@ -37,6 +37,7 @@ from devflow.core.ports import (
37
37
  SetupResult,
38
38
  build_setup_context,
39
39
  )
40
+ from devflow.core import security_tools
40
41
  from devflow.core.profile_manager import ProfileError, ProfileManager
41
42
  from devflow.core.project import ProjectDetector
42
43
  from devflow.models.profile import Profile
@@ -113,6 +114,14 @@ def init(
113
114
  "during an interactive init."
114
115
  ),
115
116
  ),
117
+ security_tools: Optional[bool] = typer.Option(
118
+ None,
119
+ "--security-tools/--no-security-tools",
120
+ help=(
121
+ "Install local security checks (Semgrep, Bandit, pip-audit, "
122
+ "gitleaks) with pre-commit. When omitted, an interactive init asks."
123
+ ),
124
+ ),
116
125
  ) -> None:
117
126
  """Initialize DevFlow in a project."""
118
127
  try:
@@ -127,6 +136,7 @@ def init(
127
136
  project_mode,
128
137
  language,
129
138
  model,
139
+ security_tools,
130
140
  )
131
141
  except (
132
142
  ArchitectureError,
@@ -151,6 +161,7 @@ def _initialize(
151
161
  project_mode: Optional[str],
152
162
  language: Optional[str],
153
163
  model: Optional[str],
164
+ security_tools: Optional[bool] = None,
154
165
  ) -> None:
155
166
  requested_harness = _requested_harness(harness, no_agent)
156
167
  requested_model = (model or "").strip()
@@ -216,6 +227,12 @@ def _initialize(
216
227
  model_override=model is not None,
217
228
  allow_prompt=not yes and sys.stdin.isatty(),
218
229
  )
230
+ _offer_security_tools(
231
+ config=config_manager.load(),
232
+ project=project,
233
+ requested=security_tools,
234
+ allow_prompt=not yes and sys.stdin.isatty(),
235
+ )
219
236
  return
220
237
 
221
238
  selected = list(explicit_profiles) or detected_names
@@ -323,11 +340,62 @@ def _initialize(
323
340
  f"[green]Specifications directory:[/green] "
324
341
  f"{config.specifications_path.relative_to(root)}"
325
342
  )
343
+ _offer_security_tools(
344
+ config=config,
345
+ project=project,
346
+ requested=security_tools,
347
+ allow_prompt=not yes and sys.stdin.isatty(),
348
+ )
326
349
  console.print(
327
350
  "\nNext: [bold]devflow spec \"Describe the change\"[/bold]"
328
351
  )
329
352
 
330
353
 
354
+ def _offer_security_tools(
355
+ *,
356
+ config: DevFlowConfig,
357
+ project: Project,
358
+ requested: Optional[bool],
359
+ allow_prompt: bool,
360
+ ) -> None:
361
+ """Offer the local security checks and install them on request."""
362
+ if requested is False:
363
+ return
364
+ root = config.root
365
+ plan = security_tools.plan_for(project, root)
366
+ if requested is None:
367
+ if security_tools.is_configured(root):
368
+ return
369
+ if not allow_prompt:
370
+ console.print(
371
+ "[dim]Tip: add local security checks with "
372
+ "'devflow init --security-tools'.[/dim]"
373
+ )
374
+ return
375
+ console.print()
376
+ for line in security_tools.describe(
377
+ plan,
378
+ config.documentation_language,
379
+ ):
380
+ console.print(line)
381
+ if not typer.confirm(
382
+ security_tools.confirm_prompt(config.documentation_language),
383
+ default=True,
384
+ ):
385
+ return
386
+
387
+ result = security_tools.install(root, plan)
388
+ if result.config_status in {"created", "updated"}:
389
+ console.print(
390
+ f"[green]Security checks configured:[/green] "
391
+ f"{security_tools.PRECOMMIT_CONFIG} ({', '.join(plan.tools)})"
392
+ )
393
+ for message in result.messages:
394
+ console.print(f"[green]{message}[/green]")
395
+ for warning in result.warnings:
396
+ console.print(f"[yellow]Warning:[/yellow] {warning}")
397
+
398
+
331
399
  def _prompt_for_language() -> str:
332
400
  """Ask for the documentation language during interactive initialization."""
333
401
  console.print(
@@ -33,6 +33,14 @@ from devflow.core.state import (
33
33
  console = Console()
34
34
  error_console = Console(stderr=True)
35
35
 
36
+ _REVIEW_CHECKLIST = (
37
+ "The scope matches the request and the Discovery decisions.",
38
+ "Every FR-XXX has at least one AC-XXX that verifies it.",
39
+ "Every AC-XXX can be checked by a test or an inspection.",
40
+ "Security risks in section 4 are mitigated or explicitly accepted.",
41
+ "Section 10 excludes what you do not want built now.",
42
+ )
43
+
36
44
 
37
45
  def status(
38
46
  spec_id: str = typer.Argument(
@@ -127,6 +135,16 @@ def _status(spec_id: str, path: Path) -> None:
127
135
  "They are not approved and do not advance the change.[/dim]"
128
136
  )
129
137
 
138
+ spec_record = state.artifacts.get("spec")
139
+ if (
140
+ state.status == WorkflowStatus.DRAFT.value
141
+ and spec_record is not None
142
+ and spec_record.status == ArtifactStatus.VALIDATED.value
143
+ ):
144
+ console.print("\n[bold]Review before approving[/bold]")
145
+ for item in _REVIEW_CHECKLIST:
146
+ console.print(f" - {item}")
147
+
130
148
  next_step = _next_step(current, location, discovery)
131
149
  if next_step:
132
150
  console.print(f"\n[bold]Next:[/bold] {next_step}")
devflow/core/discovery.py CHANGED
@@ -490,9 +490,19 @@ class NextLevel:
490
490
 
491
491
  option: str
492
492
  why: str
493
+ title: str = ""
494
+
495
+ @property
496
+ def spec_title(self) -> str:
497
+ """Return the request to use for a later specification."""
498
+ return self.title or self.option
493
499
 
494
500
  def to_dict(self) -> dict[str, Any]:
495
- return {"option": self.option, "why": self.why}
501
+ data: dict[str, Any] = {"option": self.option}
502
+ if self.title:
503
+ data["title"] = self.title
504
+ data["why"] = self.why
505
+ return data
496
506
 
497
507
 
498
508
  @dataclass(frozen=True)
@@ -701,7 +711,7 @@ class DiscoveryDocument:
701
711
  continue
702
712
  add(
703
713
  DeferredItem(
704
- title=question.next_level.option,
714
+ title=question.next_level.spec_title,
705
715
  why=question.next_level.why,
706
716
  question_id=question.id,
707
717
  )
@@ -1310,6 +1320,10 @@ class DiscoveryManager:
1310
1320
  next_level_mapping.get("why"),
1311
1321
  f"{identifier}.next_level.why",
1312
1322
  ),
1323
+ title=_optional_text(
1324
+ next_level_mapping.get("title"),
1325
+ f"{identifier}.next_level.title",
1326
+ ) or "",
1313
1327
  )
1314
1328
  # The recommended option is level 1, never the next level.
1315
1329
  if _RECOMMENDED.search(next_level.option):
@@ -0,0 +1,301 @@
1
+ """Local security tools that run on every commit, without tokens."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib.util
6
+ import shutil
7
+ import subprocess
8
+ import sys
9
+ from collections.abc import Callable, Sequence
10
+ from dataclasses import dataclass, field
11
+ from pathlib import Path
12
+
13
+ from devflow.core.artifacts.store import ArtifactStore
14
+ from devflow.models.project import Project
15
+
16
+ PRECOMMIT_CONFIG = ".pre-commit-config.yaml"
17
+ PRECOMMIT_MARKER = "# devflow:managed"
18
+
19
+ # Pinned hook revisions. Update them with `pre-commit autoupdate`.
20
+ GITLEAKS_REV = "v8.30.1"
21
+ SEMGREP_REV = "v1.184.0"
22
+ BANDIT_REV = "1.9.4"
23
+ PIP_AUDIT_REV = "v2.10.1"
24
+
25
+ Runner = Callable[[Sequence[str], Path], int]
26
+
27
+ _DESCRIPTIONS = {
28
+ "en": (
29
+ "Tools that run locally on every commit, without tokens:",
30
+ [
31
+ ("Semgrep", "with rules for {semgrep_rules}"),
32
+ ("Bandit", "for Python code"),
33
+ ("pip-audit", "for vulnerable dependencies"),
34
+ ("gitleaks", "for secrets in the code"),
35
+ ],
36
+ "pre-commit (pre-commit.com) runs these tools automatically on "
37
+ "every commit.",
38
+ "Install them now?",
39
+ ),
40
+ "es": (
41
+ "Herramientas que se ejecutan localmente en cada commit, sin tokens:",
42
+ [
43
+ ("Semgrep", "con reglas para {semgrep_rules}"),
44
+ ("Bandit", "para código Python"),
45
+ ("pip-audit", "para dependencias vulnerables"),
46
+ ("gitleaks", "para secretos en el código"),
47
+ ],
48
+ "pre-commit (pre-commit.com) ejecuta esas herramientas "
49
+ "automáticamente en cada commit.",
50
+ "¿Instalarlas ahora?",
51
+ ),
52
+ }
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class SecurityPlan:
57
+ """Which hooks apply to a project."""
58
+
59
+ python: bool
60
+ django: bool
61
+ requirements: str | None
62
+ pyproject: bool
63
+
64
+ @property
65
+ def semgrep_configs(self) -> tuple[str, ...]:
66
+ configs: list[str] = []
67
+ if self.django:
68
+ configs.append("p/django")
69
+ elif self.python:
70
+ configs.append("p/python")
71
+ configs.append("p/owasp-top-ten")
72
+ return tuple(configs)
73
+
74
+ @property
75
+ def tools(self) -> tuple[str, ...]:
76
+ names = ["Semgrep"]
77
+ if self.python:
78
+ names.append("Bandit")
79
+ if self.requirements or self.pyproject:
80
+ names.append("pip-audit")
81
+ names.append("gitleaks")
82
+ return tuple(names)
83
+
84
+
85
+ @dataclass
86
+ class SecurityInstallResult:
87
+ """What the installation changed and what still needs the user."""
88
+
89
+ config_status: str = ""
90
+ messages: list[str] = field(default_factory=list)
91
+ warnings: list[str] = field(default_factory=list)
92
+
93
+
94
+ def plan_for(project: Project, root: Path) -> SecurityPlan:
95
+ """Select the hooks that apply to the detected project."""
96
+ languages = {value.lower() for value in project.languages}
97
+ frameworks = {value.lower() for value in project.frameworks}
98
+ requirements = None
99
+ for candidate in ("requirements.txt", "requirements/base.txt"):
100
+ if (root / candidate).is_file():
101
+ requirements = candidate
102
+ break
103
+ return SecurityPlan(
104
+ python="python" in languages,
105
+ django="django" in frameworks,
106
+ requirements=requirements,
107
+ pyproject=(root / "pyproject.toml").is_file(),
108
+ )
109
+
110
+
111
+ def describe(plan: SecurityPlan, language: str) -> list[str]:
112
+ """Return the user-facing description of the tools."""
113
+ base = (language or "en").split("-")[0].lower()
114
+ title, items, closing, _ = _DESCRIPTIONS.get(base, _DESCRIPTIONS["en"])
115
+ rules = " y ".join(
116
+ "Django" if config == "p/django"
117
+ else "Python" if config == "p/python"
118
+ else "OWASP"
119
+ for config in plan.semgrep_configs
120
+ )
121
+ if base != "es":
122
+ rules = rules.replace(" y ", " and ")
123
+ lines = [title]
124
+ for name, detail in items:
125
+ if name in plan.tools:
126
+ lines.append(f"- {name}, {detail.format(semgrep_rules=rules)};")
127
+ lines.append(closing)
128
+ return lines
129
+
130
+
131
+ def confirm_prompt(language: str) -> str:
132
+ """Return the confirmation question in the documentation language."""
133
+ base = (language or "en").split("-")[0].lower()
134
+ return _DESCRIPTIONS.get(base, _DESCRIPTIONS["en"])[3]
135
+
136
+
137
+ def render_precommit_config(plan: SecurityPlan) -> str:
138
+ """Render the managed .pre-commit-config.yaml."""
139
+ semgrep_args = []
140
+ for config in plan.semgrep_configs:
141
+ semgrep_args.extend(["--config", config])
142
+ semgrep_args.extend(
143
+ [
144
+ "--error",
145
+ "--disable-version-check",
146
+ "--quiet",
147
+ "--skip-unknown-extensions",
148
+ ]
149
+ )
150
+ lines = [
151
+ PRECOMMIT_MARKER,
152
+ "# Security checks that run locally on every commit, without tokens.",
153
+ "# Generated by `devflow init`. Delete the first line to stop DevFlow",
154
+ "# from updating this file. Update revisions with",
155
+ "# `pre-commit autoupdate`.",
156
+ "repos:",
157
+ " - repo: https://github.com/gitleaks/gitleaks",
158
+ f" rev: {GITLEAKS_REV}",
159
+ " hooks:",
160
+ " - id: gitleaks",
161
+ " - repo: https://github.com/semgrep/semgrep",
162
+ f" rev: {SEMGREP_REV}",
163
+ " hooks:",
164
+ " - id: semgrep",
165
+ f" args: [{', '.join(semgrep_args)}]",
166
+ ]
167
+ if plan.python:
168
+ lines.extend(
169
+ [
170
+ " - repo: https://github.com/PyCQA/bandit",
171
+ f" rev: {BANDIT_REV}",
172
+ " hooks:",
173
+ " - id: bandit",
174
+ " # Medium severity and above; tests and migrations are",
175
+ " # excluded.",
176
+ " args: [-q, -ll]",
177
+ " exclude: '(^|/)(tests?|migrations)/|(^|/)tests?\\.py$'",
178
+ ]
179
+ )
180
+ if plan.requirements:
181
+ lines.extend(
182
+ [
183
+ " - repo: https://github.com/pypa/pip-audit",
184
+ f" rev: {PIP_AUDIT_REV}",
185
+ " hooks:",
186
+ " - id: pip-audit",
187
+ f" args: [-r, {plan.requirements}]",
188
+ " files: '^requirements.*\\.txt$|^requirements/'",
189
+ ]
190
+ )
191
+ elif plan.pyproject:
192
+ lines.extend(
193
+ [
194
+ " - repo: https://github.com/pypa/pip-audit",
195
+ f" rev: {PIP_AUDIT_REV}",
196
+ " hooks:",
197
+ " - id: pip-audit",
198
+ " args: ['.']",
199
+ " files: '^pyproject\\.toml$'",
200
+ ]
201
+ )
202
+ return "\n".join(lines) + "\n"
203
+
204
+
205
+ def _write_config(root: Path, content: str) -> str:
206
+ """Create or update the managed config without touching user files."""
207
+ path = root / PRECOMMIT_CONFIG
208
+ if path.is_symlink():
209
+ return "skipped"
210
+ if path.exists():
211
+ try:
212
+ existing = path.read_text(encoding="utf-8")
213
+ except OSError:
214
+ return "skipped"
215
+ if PRECOMMIT_MARKER not in existing:
216
+ return "skipped"
217
+ if existing == content:
218
+ return "unchanged"
219
+ ArtifactStore(root).write(path, content)
220
+ return "updated"
221
+ ArtifactStore(root).write(path, content)
222
+ return "created"
223
+
224
+
225
+ def _run(command: Sequence[str], cwd: Path) -> int:
226
+ completed = subprocess.run( # noqa: S603 - fixed argument lists
227
+ list(command),
228
+ cwd=cwd,
229
+ check=False,
230
+ )
231
+ return completed.returncode
232
+
233
+
234
+ def _precommit_command() -> list[str] | None:
235
+ executable = shutil.which("pre-commit")
236
+ if executable:
237
+ return [executable]
238
+ if importlib.util.find_spec("pre_commit") is not None:
239
+ return [sys.executable, "-m", "pre_commit"]
240
+ return None
241
+
242
+
243
+ def install(
244
+ root: Path,
245
+ plan: SecurityPlan,
246
+ *,
247
+ runner: Runner = _run,
248
+ ) -> SecurityInstallResult:
249
+ """Write the hook configuration, install pre-commit and its git hook."""
250
+ result = SecurityInstallResult()
251
+ result.config_status = _write_config(root, render_precommit_config(plan))
252
+ if result.config_status == "skipped":
253
+ result.warnings.append(
254
+ f"{PRECOMMIT_CONFIG} already exists and is not managed by DevFlow. "
255
+ "It was left untouched; add the hooks yourself if you want them."
256
+ )
257
+
258
+ command = _precommit_command()
259
+ if command is None:
260
+ code = runner(
261
+ [sys.executable, "-m", "pip", "install", "pre-commit"],
262
+ root,
263
+ )
264
+ if code != 0:
265
+ result.warnings.append(
266
+ "Could not install pre-commit. Install it with "
267
+ "'pip install pre-commit', then run 'pre-commit install'."
268
+ )
269
+ return result
270
+ result.messages.append("pre-commit installed.")
271
+ command = _precommit_command() or [sys.executable, "-m", "pre_commit"]
272
+
273
+ if not (root / ".git").exists():
274
+ result.warnings.append(
275
+ "This project is not a git repository yet. Run 'git init' and "
276
+ "then 'pre-commit install' to activate the checks."
277
+ )
278
+ return result
279
+
280
+ if runner([*command, "install"], root) != 0:
281
+ result.warnings.append(
282
+ "Could not install the git hook. Run 'pre-commit install'."
283
+ )
284
+ return result
285
+ result.messages.append(
286
+ "Git hook installed: the checks run on every commit. The first "
287
+ "commit downloads the tools and may take a few minutes. Run "
288
+ "'pre-commit run --all-files' to check the whole project now."
289
+ )
290
+ return result
291
+
292
+
293
+ def is_configured(root: Path) -> bool:
294
+ """Return whether a DevFlow-managed hook configuration exists."""
295
+ path = root / PRECOMMIT_CONFIG
296
+ try:
297
+ return path.is_file() and PRECOMMIT_MARKER in path.read_text(
298
+ encoding="utf-8"
299
+ )
300
+ except OSError:
301
+ return False
@@ -418,6 +418,7 @@ class PreparedSpec:
418
418
  architecture: ArchitectureManifest | None = None
419
419
  discovery: DiscoveryDocument | None = None
420
420
  discovery_digest: str | None = None
421
+ language: str = "en"
421
422
 
422
423
 
423
424
  def normalize_word(value: str) -> str:
@@ -867,6 +868,7 @@ class SpecificationManager:
867
868
  architecture=architecture,
868
869
  discovery=discovery,
869
870
  discovery_digest=discovery_digest,
871
+ language=config.documentation_language,
870
872
  )
871
873
 
872
874
  def materialize_context(self, prepared: PreparedSpec) -> Path:
@@ -891,6 +893,12 @@ class SpecificationManager:
891
893
  cleaned = prepared.fallback_content
892
894
  source = "static"
893
895
  cleaned = self.with_next_specs(cleaned, prepared.discovery)
896
+ cleaned = self.with_plain_criteria(cleaned)
897
+ cleaned = self.with_approval_section(
898
+ cleaned,
899
+ prepared.spec_id,
900
+ prepared.language,
901
+ )
894
902
 
895
903
  prepared.directory.mkdir(parents=True, exist_ok=True)
896
904
  ArtifactStore(prepared.root).write(
@@ -1087,6 +1095,47 @@ class SpecificationManager:
1087
1095
  cleaned = cleaned[start:]
1088
1096
  return cleaned.strip()
1089
1097
 
1098
+ def with_plain_criteria(self, content: str) -> str:
1099
+ """Remove checkboxes from acceptance criteria.
1100
+
1101
+ Criteria are verified during implementation, not ticked in an
1102
+ approved document: editing it would invalidate the approval.
1103
+ """
1104
+ return re.sub(
1105
+ r"^(\s*)[-*]\s+\[[ xX]\]\s+(\*\*AC-)",
1106
+ r"\1- \2",
1107
+ content,
1108
+ flags=re.MULTILINE,
1109
+ )
1110
+
1111
+ def with_approval_section(
1112
+ self,
1113
+ content: str,
1114
+ spec_id: str,
1115
+ language: str = "en",
1116
+ ) -> str:
1117
+ """Write the body of section 11; DevFlow owns the approval record."""
1118
+ section = re.search(
1119
+ r"^##\s+11\.[^\n]*\n(?P<body>.*?)(?=^##\s|\Z)",
1120
+ content,
1121
+ re.MULTILINE | re.DOTALL,
1122
+ )
1123
+ if section is None:
1124
+ return content
1125
+ kept = [
1126
+ line
1127
+ for line in section.group("body").splitlines()
1128
+ if not re.match(r"^\s*[-*]\s+\[[ xX]\]", line)
1129
+ ]
1130
+ rest = "\n".join(kept).strip()
1131
+ note = _approval_note(spec_id, language)
1132
+ body = f"\n{note}\n\n" + (f"{rest}\n\n" if rest else "")
1133
+ return (
1134
+ content[: section.start("body")]
1135
+ + body
1136
+ + content[section.end("body"):]
1137
+ )
1138
+
1090
1139
  def stamp_discovery_digest(self, content: str, digest: str) -> str:
1091
1140
  """Write the authoritative Discovery digest into the header row."""
1092
1141
  return re.sub(
@@ -1596,7 +1645,7 @@ class SpecificationManager:
1596
1645
  "Use the eleven numbered sections defined by the Greenfield "
1597
1646
  "prompt. Describe the target system in future tense. Use "
1598
1647
  "`**FR-XXX:**` identifiers for functional requirements and "
1599
- "`- [ ] **AC-XXX:**` checklist items for acceptance criteria.",
1648
+ "`- **AC-XXX:**` list items for acceptance criteria.",
1600
1649
  "",
1601
1650
  "End the document with `## Appendix A: Declared Architecture "
1602
1651
  "Manifest` and include the manifest digest.",
@@ -1882,7 +1931,7 @@ class SpecificationManager:
1882
1931
  )
1883
1932
  for index, criterion in enumerate(criteria, start=1):
1884
1933
  lines.append(
1885
- f"- [ ] **AC-{index:03d}:** {criterion}"
1934
+ f"- **AC-{index:03d}:** {criterion}"
1886
1935
  )
1887
1936
 
1888
1937
  lines.extend(
@@ -2106,8 +2155,8 @@ class SpecificationManager:
2106
2155
  "",
2107
2156
  "Use the eleven numbered sections defined by the DevFlow "
2108
2157
  "specification prompt. Use `**FR-XXX:**` identifiers for "
2109
- "functional requirements and `- [ ] **AC-XXX:**` checklist "
2110
- "items for acceptance criteria.",
2158
+ "functional requirements and `- **AC-XXX:**` list items for "
2159
+ "acceptance criteria.",
2111
2160
  "",
2112
2161
  "The specification must remain valid if the project later "
2113
2162
  "switches to a different agent harness.",
@@ -2400,7 +2449,7 @@ class SpecificationManager:
2400
2449
 
2401
2450
  for index, criterion in enumerate(criteria, start=1):
2402
2451
  lines.append(
2403
- f"- [ ] **AC-{index:03d}:** {criterion}"
2452
+ f"- **AC-{index:03d}:** {criterion}"
2404
2453
  )
2405
2454
 
2406
2455
  lines.extend(
@@ -2460,3 +2509,28 @@ class SpecificationManager:
2460
2509
  )
2461
2510
 
2462
2511
  return "\n".join(lines)
2512
+
2513
+
2514
+ _APPROVAL_NOTES = {
2515
+ "en": (
2516
+ "Approve with `devflow approve {spec_id}`. The approval is recorded "
2517
+ "in `events.jsonl`, bound to the SHA-256 digests of this file and "
2518
+ "`discovery.yaml`. Do not edit this file afterwards: to change it, "
2519
+ "run `devflow reopen {spec_id}`. Acceptance criteria are verified "
2520
+ "during implementation, not ticked here."
2521
+ ),
2522
+ "es": (
2523
+ "Se aprueba con `devflow approve {spec_id}`. La aprobación queda "
2524
+ "registrada en `events.jsonl`, ligada a las huellas SHA-256 de este "
2525
+ "archivo y de `discovery.yaml`. No edites este archivo después: "
2526
+ "para cambiarlo, ejecuta `devflow reopen {spec_id}`. Los criterios de "
2527
+ "aceptación se verifican durante la implementación, no se marcan "
2528
+ "aquí."
2529
+ ),
2530
+ }
2531
+
2532
+
2533
+ def _approval_note(spec_id: str, language: str) -> str:
2534
+ base = (language or "en").split("-")[0].lower()
2535
+ template = _APPROVAL_NOTES.get(base, _APPROVAL_NOTES["en"])
2536
+ return template.format(spec_id=spec_id)
@@ -48,12 +48,17 @@ traces that path instead of solving everything at once.
48
48
  2. **Security is never assumed or hidden.** Ask every basic security
49
49
  decision explicitly, recommend the basic option and explain in one
50
50
  sentence why it matters. Answering it is how the user learns it.
51
- 3. **Every question offers a next level.** Add one option that takes
52
- the decision one level further and record it in `next_level`:
53
- `option` is the exact option text (also listed in `options`) and
54
- `why` explains in one sentence what it improves and when it is worth
55
- it. It is never the recommended level-1 option; DevFlow ignores a
56
- `next_level` marked as recommended. If the user picks it, record the answer with that exact text. If
51
+ 3. **Every question offers a next level, when one exists.** Add one
52
+ option that is a real improvement over the recommended level-1
53
+ option (more secure, more capable or more robust), never a mere
54
+ alternative, a reduction or a stricter variant with a worse
55
+ experience. Record it in `next_level`: `option` is the exact option
56
+ text (also listed in `options`), `title` is that improvement phrased
57
+ as a short request for a future specification (for example
58
+ "Require passwords of at least 12 characters"), and `why` explains in
59
+ one sentence what it improves and when it is worth it. It is never
60
+ the recommended option; DevFlow ignores a `next_level` marked as
61
+ recommended. When no real improvement exists, omit `next_level`. If the user picks it, record the answer with that exact text. If
57
62
  not, DevFlow proposes it as a next specification. Do not ask
58
63
  follow-up questions about the next level in this specification.
59
64
  4. **Do not go deeper than this level.** When an answer opens a more
@@ -216,6 +221,7 @@ questions:
216
221
  - "Next-level option"
217
222
  next_level:
218
223
  option: "Next-level option"
224
+ title: "Short request for a future specification"
219
225
  why: "What it improves and when it is worth it."
220
226
  - id: Q2
221
227
  category: architecture_boundary
@@ -251,8 +257,8 @@ deferred:
251
257
  question_id: Q1
252
258
  ```
253
259
 
254
- `next_level` and `deferred` are optional, but every material question
255
- should have a `next_level` unless no meaningful next level exists.
260
+ `next_level` and `deferred` are optional. Add a `next_level` only when
261
+ it is a real improvement.
256
262
 
257
263
  ### YAML Safety Rules
258
264
 
devflow/prompts/spec.md CHANGED
@@ -163,8 +163,13 @@ Produce exactly one Markdown document with this structure:
163
163
  ```
164
164
 
165
165
  Every functional requirement must use an identifier such as
166
- `**FR-001:**`. Every acceptance criterion must use a checklist item
167
- such as `- [ ] **AC-001:**` and must be verifiable.
166
+ `**FR-001:**`. Every acceptance criterion must use a list item such as
167
+ `- **AC-001:**`, without a checkbox, and must be verifiable.
168
+
169
+ Be concise. State each fact once and reference it elsewhere by its
170
+ `FR-XXX`, `AC-XXX` or `Qn` identifier instead of repeating it. The
171
+ implementer reads the whole document, so every extra sentence costs
172
+ tokens.
168
173
 
169
174
  Use the exact specification ID and path in `{{spec_path}}`. Do not
170
175
  renumber the document.
@@ -172,7 +177,8 @@ renumber the document.
172
177
  ## Content Requirements
173
178
 
174
179
  - Section 1 quotes the original request or requirements.
175
- - Section 2 summarizes the change and its intended outcome.
180
+ - Section 2 summarizes the change and its intended outcome in one
181
+ short paragraph. Do not restate every decision.
176
182
  - Section 5 contains complete, testable functional requirements.
177
183
  - Section 6 records constraints, dependencies, compatibility rules and
178
184
  quality gates.
@@ -193,9 +199,9 @@ renumber the document.
193
199
  profile scope. Reference paths, do not copy their contents.
194
200
  - Section 10 states what is explicitly excluded from this change. In
195
201
  Greenfield, include code generation and planning in this stage. Do not
196
- write subsection 10.1: DevFlow writes the suggested next
197
- specifications from Discovery.
198
- - Section 11 contains the review and approval checklist.
202
+ repeat the deferred items or next-level options: DevFlow writes them
203
+ in subsection 10.1, so do not write 10.1 yourself.
204
+ - Leave section 11 empty: DevFlow writes the approval note.
199
205
  <!-- devflow:mode existing -->
200
206
  - Section 3 cites real files from the context. Explain their relevance.
201
207
  - Section 4 identifies affected areas and compatibility risks.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: devflow-toolkit
3
- Version: 0.3.24
3
+ Version: 0.3.25
4
4
  Summary: Specification workflow toolkit for AI-assisted software changes
5
5
  Author: DevFlow contributors
6
6
  License-Expression: MIT
@@ -32,7 +32,7 @@ Description-Content-Type: text/markdown
32
32
 
33
33
  # DevFlow Toolkit
34
34
 
35
- **Current version: `0.3.24`.**
35
+ **Current version: `0.3.25`.**
36
36
 
37
37
  DevFlow is a command-line toolkit for leading AI models and coding
38
38
  agents through specification-driven changes in real software projects.
@@ -152,7 +152,7 @@ pip install devflow-toolkit
152
152
  To install a specific built artifact instead:
153
153
 
154
154
  ```bash
155
- pip install devflow_toolkit-0.3.24-py3-none-any.whl
155
+ pip install devflow_toolkit-0.3.25-py3-none-any.whl
156
156
  ```
157
157
 
158
158
  Verify the installation:
@@ -315,6 +315,30 @@ error instead of silently switching to deterministic analysis. Pass
315
315
  `--harness none` or `--no-agent` to opt into deterministic output
316
316
  explicitly.
317
317
 
318
+ ### Local security checks
319
+
320
+ `devflow init` offers tools that run locally on every commit, without
321
+ tokens:
322
+
323
+ - Semgrep, with rules for Django (or Python) and OWASP;
324
+ - Bandit, for Python code;
325
+ - pip-audit, for vulnerable dependencies;
326
+ - gitleaks, for secrets in the code.
327
+
328
+ pre-commit (pre-commit.com) runs these tools automatically on every
329
+ commit. In an interactive terminal `init` describes them and asks; use
330
+ `--security-tools` to install them without asking, or
331
+ `--no-security-tools` to skip the offer.
332
+
333
+ Accepting writes a managed `.pre-commit-config.yaml` with pinned hook
334
+ revisions, installs `pre-commit` with pip when it is missing and runs
335
+ `pre-commit install` when the project is a git repository. Only the
336
+ hooks that apply are added: Bandit and pip-audit for Python projects,
337
+ `p/django` rules for Django. An existing, unmanaged
338
+ `.pre-commit-config.yaml` is never overwritten. The first commit
339
+ downloads the tools; `pre-commit run --all-files` checks the whole
340
+ project.
341
+
318
342
  ## Configuration
319
343
 
320
344
  `.devflow/config.yaml` stores project settings. It references the
@@ -428,7 +452,7 @@ as an architectural constraint when it is present.
428
452
 
429
453
  ### Harnesses
430
454
 
431
- | Harness | Status in 0.3.24 |
455
+ | Harness | Status in 0.3.25 |
432
456
  | --- | --- |
433
457
  | OpenCode | Verified end-to-end; interactive Discovery uses the `question` tool |
434
458
  | Antigravity | Custom agents and scoped permissions generated; `agy` loading and print mode verified |
@@ -717,8 +741,10 @@ everything at once:
717
741
  2. **Security is always asked, never assumed.** Basic security decisions
718
742
  are explicit questions with a recommended option and a short
719
743
  explanation, so the user learns them by answering.
720
- 3. **Every question offers a next level.** One option takes the decision
721
- one level further. It is recorded in `next_level`:
744
+ 3. **Questions offer a next level when a real improvement exists.** One
745
+ option takes the decision one level further (more secure, capable or
746
+ robust; never a mere alternative or a reduction). It is recorded in
747
+ `next_level`, with a `title` phrased as a future spec request:
722
748
 
723
749
  ```yaml
724
750
  options:
@@ -726,13 +752,14 @@ everything at once:
726
752
  - "Token that expires after 24 hours"
727
753
  next_level:
728
754
  option: "Token that expires after 24 hours"
755
+ title: "Expire login tokens after 24 hours"
729
756
  why: "Limits the damage if a token leaks."
730
757
  ```
731
758
 
732
759
  If the user chooses it, the answer uses that exact text. If not,
733
- DevFlow treats it as a suggestion for a later specification. The
734
- recommended option is level 1, so a `next_level` marked as
735
- recommended is ignored.
760
+ DevFlow suggests `title` (or the option text when there is no title)
761
+ as a later specification. The recommended option is level 1, so a
762
+ `next_level` marked as recommended is ignored.
736
763
  4. **No deeper than this level.** More advanced decisions found along
737
764
  the way, and parts of a large request left for later, are recorded in
738
765
  `deferred`:
@@ -768,7 +795,7 @@ for each item; the agent does not write it.
768
795
  8. If artifacts exist without workflow state, diagnose with
769
796
  `devflow doctor <id>` and repair with `devflow recover <id>`.
770
797
 
771
- Available commands in `0.3.24`:
798
+ Available commands in `0.3.25`:
772
799
 
773
800
  | Command | Status |
774
801
  | --- | --- |
@@ -1001,7 +1028,7 @@ devflow approve 001
1001
1028
  ```
1002
1029
 
1003
1030
  Approval is explicit and binds the decision to the current artifact
1004
- digests. For a `0.3.24` change it binds `spec.md`, `discovery.yaml` and,
1031
+ digests. For a `0.3.25` change it binds `spec.md`, `discovery.yaml` and,
1005
1032
  when a manifest applies, the architecture manifest digest. Repeating the
1006
1033
  same approval is a no-op. If an artifact changes after validation,
1007
1034
  DevFlow marks it stale and refuses approval until it is regenerated and
@@ -1012,7 +1039,7 @@ and names the pending questions and assumptions. Approval also rejects a
1012
1039
  specification whose section 7 still lists open questions. Legacy `0.2.0`
1013
1040
  changes without `discovery.yaml` remain approvable with a warning.
1014
1041
 
1015
- Only the `spec` stage is available in `0.3.24`, so `--stage` is optional
1042
+ Only the `spec` stage is available in `0.3.25`, so `--stage` is optional
1016
1043
  and defaults to `spec`. `--stage plan` and `--stage review` are
1017
1044
  rejected. There are no `plan`, `implement` or
1018
1045
  `review` commands in this release.
@@ -16,24 +16,25 @@ devflow/commands/approve.py,sha256=twXcP_9OIlqgJlgiAeeB32yXa-hZjyB5unAox89UGQY,2
16
16
  devflow/commands/config.py,sha256=9EV3S_0j_OAokE2Hd1uhA3srBbTDSOInYcnULcHG3sM,1300
17
17
  devflow/commands/doctor.py,sha256=vYk2i3OksbGpHEUFsqi7c4w44mAXRmY0OeEdO8h5j_M,4161
18
18
  devflow/commands/harness.py,sha256=0IH_PPeYmW3aQ_WnUSkFzxpe3A4FtSyjWfHq-Ug7Eos,10549
19
- devflow/commands/init.py,sha256=G2LDYDElWDSDPk3-1DfRtv8sW_z-9ITJH1Co6C5jiyw,17188
19
+ devflow/commands/init.py,sha256=yIA1r5_qbWod2WsglQBGb-vGcP8sFTji9niqABYxtSM,19143
20
20
  devflow/commands/recover.py,sha256=sV9x5-30E_3XRBe7JItDiSG-pqrowRzjqOkC_eyrhFQ,2165
21
21
  devflow/commands/reopen.py,sha256=bZiX-dyKgmtdKdV4FHwEwRCFvuuX5jezBCI7wIpkHYU,2971
22
22
  devflow/commands/spec.py,sha256=7glxFHKuJd33mL6YayrxRJ6TViUmmQk5rijbNepsbig,16353
23
- devflow/commands/status.py,sha256=Lazqr7I8heJHCK-0q3NQxsIORwRzopDwkRgAnbcdnA4,6742
23
+ devflow/commands/status.py,sha256=dLleIMLK39hRuQ3JdaUval70o0cIkMPKZOKTsNeML4Q,7407
24
24
  devflow/core/__init__.py,sha256=hN7i4-PDaZ7y4P8qRpZl_lJvIiPyQaN1TDGnw2BecYU,427
25
25
  devflow/core/architecture.py,sha256=qllllsUVqA76LiSU6z_s4U8dxMcs6ClKXU16HxI3yOI,13692
26
26
  devflow/core/clock.py,sha256=KZROv6o51Ln1EzK00ySCxfc7WPZqPlaQhFfjfdc_TMY,1651
27
27
  devflow/core/config.py,sha256=VsR2ezH1toydLVyniy-BXtC843vDIstxI2-8vh4VmnU,26455
28
28
  devflow/core/constitution.py,sha256=rPLc8Puv9nUMC_GZwzOqvr1B-4urdxAISr655od2IPM,5333
29
- devflow/core/discovery.py,sha256=EIffENMOrmF3SmdJJAPVJDVAo0kG0SMw8RSW-LWnC10,59943
29
+ devflow/core/discovery.py,sha256=drquy0yxRKblEEgnOBDNYkeyPKc2SXo6SIwQyZgDB2w,60337
30
30
  devflow/core/file_types.py,sha256=5S5YywOaTESDiln4kP7qyJFEjxHoiF6tSBbwuXNpDDc,566
31
31
  devflow/core/ports.py,sha256=6jlqeR40MNaz-IuZIAPimXpRKew-wMUab3KzelcTXsU,4541
32
32
  devflow/core/profile_manager.py,sha256=QnnJka2KIKD2tCSWJkGTOUEFMgmQT0Z9Qv173JKWKHw,8937
33
33
  devflow/core/project.py,sha256=4OnudghY5N5rCOmafWO5Hk68M7T3-mOV0j0k0dh2luE,16891
34
34
  devflow/core/recovery.py,sha256=W2If6Ymb3ISwMN8IVQYCwptDUzhxejlF-P2NvMYyZP0,8818
35
+ devflow/core/security_tools.py,sha256=F-JdGzycS-Vov_1SE5qciNVi31DqnnJXVqHqoDocSAA,8912
35
36
  devflow/core/spec_workflow.py,sha256=Ngma_-7MLsp96gNd2avVC81_SjWTAk4jscsQinmCml4,43961
36
- devflow/core/specification.py,sha256=JSd-OHuoMWi4yuNblulFEGJ0HYmBNh8R_8MF6tMx-lo,67214
37
+ devflow/core/specification.py,sha256=6AhbWSFRyPEFwn_CIbyivujZ8-zlQBA610ZQxEUdKF4,69524
37
38
  devflow/core/artifacts/__init__.py,sha256=gt9xahPynoxv75FMq1ZJx91ILTIv4ExuvX1Ymrxwr2c,627
38
39
  devflow/core/artifacts/errors.py,sha256=hwZxnLFcUTtEjDWtN6rUCkM69EN19LGVlc6HD-pNZyk,493
39
40
  devflow/core/artifacts/models.py,sha256=xJjmY8jUAHxqYN9u1JEu8CbJB-IJg1xb9P-LDaP5_Hw,2049
@@ -61,10 +62,10 @@ devflow/profiles/fastapi-backend/profile.yaml,sha256=5_b-zWSX0HV-tw_2ntRCSa4DyP3
61
62
  devflow/profiles/fastapi-backend/constitution/fastapi-standards.md,sha256=iFKib4i_9z4wBQ9thl-uftg5g-CHwvmFWzMtLgA7CBk,1949
62
63
  devflow/prompts/__init__.py,sha256=DttfMavd0nfmhKkVE46VhpIHkGS-4amYfufABEM20xI,19120
63
64
  devflow/prompts/discovery-repair.md,sha256=YfTfrrw5uUZvC_x6X2lrYEDkMNhanhoe0ER3Yc2-rgI,1135
64
- devflow/prompts/discovery.md,sha256=AqHl0jz_uZZSlupQnxoRYzPhAzvkNCxIv34yGV5uBt8,14470
65
- devflow/prompts/spec.md,sha256=90NI6atLfvCcLKAojcxgEfCJDSt-kbb70KGctu_1tXA,7375
66
- devflow_toolkit-0.3.24.dist-info/METADATA,sha256=abbM1nIO4KP2e8_XfmSPr7xq0XJsrRXxXxvpwj8H6hM,49731
67
- devflow_toolkit-0.3.24.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
68
- devflow_toolkit-0.3.24.dist-info/entry_points.txt,sha256=wPmqE1081vi8s3xf-Wfzfvpl-44IKgwx7OGoLEK3u7o,44
69
- devflow_toolkit-0.3.24.dist-info/licenses/LICENSE,sha256=Wa04lstC8Goe4b9IYfEYWB2k7nokYBejZl6NdyAl8rA,1077
70
- devflow_toolkit-0.3.24.dist-info/RECORD,,
65
+ devflow/prompts/discovery.md,sha256=4eApdy5QwT9nFeXpgMA4IfPaw5uCciZysOWKgpZ4vPM,14852
66
+ devflow/prompts/spec.md,sha256=Kze_ZvE5yn0tfncvr98Nw6GQLEZlJmcZFWDNUpLMnlc,7689
67
+ devflow_toolkit-0.3.25.dist-info/METADATA,sha256=l10VriUZ2uFgJ9sp7UO2GN-5OG3fmSwOIB_AAduncRQ,50944
68
+ devflow_toolkit-0.3.25.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
69
+ devflow_toolkit-0.3.25.dist-info/entry_points.txt,sha256=wPmqE1081vi8s3xf-Wfzfvpl-44IKgwx7OGoLEK3u7o,44
70
+ devflow_toolkit-0.3.25.dist-info/licenses/LICENSE,sha256=Wa04lstC8Goe4b9IYfEYWB2k7nokYBejZl6NdyAl8rA,1077
71
+ devflow_toolkit-0.3.25.dist-info/RECORD,,