devflow-toolkit 0.3.21__py3-none-any.whl → 0.3.23__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.
@@ -178,8 +178,8 @@ def render_agent_instructions(
178
178
  "Out of Scope.",
179
179
  "5. Add or update tests for every `AC-XXX` and report each one as "
180
180
  "met or not met.",
181
- f"6. Do not edit files under `{specs_dir}/`; editing an approved "
182
- "spec makes its approval stale.",
181
+ f"6. Do not edit files under `{specs_dir}/`. To change an "
182
+ "approved spec, the user runs `devflow reopen NNN`.",
183
183
  "7. If the spec is ambiguous, wrong or conflicts with the code, "
184
184
  "stop and ask. Scope changes need a new `devflow spec`.",
185
185
  "",
devflow/cli.py CHANGED
@@ -11,6 +11,7 @@ from devflow.commands.doctor import doctor as doctor_command
11
11
  from devflow.commands.harness import harness_app
12
12
  from devflow.commands.init import init as init_command
13
13
  from devflow.commands.recover import recover as recover_command
14
+ from devflow.commands.reopen import reopen as reopen_command
14
15
  from devflow.commands.spec import spec as spec_command
15
16
  from devflow.commands.status import status as status_command
16
17
 
@@ -26,6 +27,7 @@ console = Console()
26
27
  app.command("init")(init_command)
27
28
  app.command("spec")(spec_command)
28
29
  app.command("approve")(approve_command)
30
+ app.command("reopen")(reopen_command)
29
31
  app.command("status")(status_command)
30
32
  app.command("doctor")(doctor_command)
31
33
  app.command("recover")(recover_command)
@@ -0,0 +1,105 @@
1
+ """Implementation of the devflow reopen command."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import typer
8
+ from rich.console import Console
9
+
10
+ from devflow.core.artifacts.errors import ArtifactError
11
+ from devflow.core.config import ConfigError, ConfigManager
12
+ from devflow.core.discovery import DiscoveryError
13
+ from devflow.core.project import ProjectDetector
14
+ from devflow.core.state import (
15
+ StateError,
16
+ WorkflowLocator,
17
+ WorkflowStateManager,
18
+ )
19
+
20
+ console = Console()
21
+ error_console = Console(stderr=True)
22
+
23
+
24
+ def reopen(
25
+ spec_id: str = typer.Argument(
26
+ ...,
27
+ help="Change id (001) or change directory (001-add-health).",
28
+ ),
29
+ path: Path = typer.Argument(
30
+ Path("."),
31
+ help="Project root or a path inside it.",
32
+ ),
33
+ discovery: bool = typer.Option(
34
+ False,
35
+ "--discovery",
36
+ help="Also reopen Discovery to add or change decisions.",
37
+ ),
38
+ yes: bool = typer.Option(
39
+ False,
40
+ "--yes",
41
+ "-y",
42
+ help="Do not ask for confirmation.",
43
+ ),
44
+ ) -> None:
45
+ """Reopen an approved specification so it can be changed."""
46
+ try:
47
+ _reopen(spec_id, path, discovery=discovery, yes=yes)
48
+ except (
49
+ ArtifactError,
50
+ ConfigError,
51
+ DiscoveryError,
52
+ StateError,
53
+ FileNotFoundError,
54
+ NotADirectoryError,
55
+ OSError,
56
+ ) as error:
57
+ error_console.print(f"[red]Error:[/red] {error}")
58
+ raise typer.Exit(code=1) from error
59
+
60
+
61
+ def _reopen(spec_id: str, path: Path, *, discovery: bool, yes: bool) -> None:
62
+ root = ProjectDetector().find_root(path)
63
+ config = ConfigManager(root).load()
64
+ location = WorkflowLocator(config.specifications_path).find(spec_id)
65
+
66
+ if not yes and not typer.confirm(
67
+ f"Reopen the approved specification {location.change}?",
68
+ default=False,
69
+ ):
70
+ console.print("Cancelled. Nothing was changed.")
71
+ raise typer.Exit(code=1)
72
+
73
+ manager = WorkflowStateManager(
74
+ config.specifications_path,
75
+ project_root=config.root,
76
+ )
77
+ result = manager.reopen(location, discovery=discovery)
78
+
79
+ console.print(
80
+ f"[bold green]Reopened {location.change}.[/bold green] "
81
+ "The spec approval was withdrawn."
82
+ )
83
+ if result.archived is not None:
84
+ console.print(
85
+ "Approved spec archived: "
86
+ f"{manager.store.display_path(result.archived)}"
87
+ )
88
+ console.print(f"Workflow status: {result.state.status}")
89
+
90
+ continue_command = f"devflow spec --continue {location.spec_id}"
91
+ if discovery:
92
+ console.print(
93
+ f"\n[bold]Next:[/bold] {continue_command}\n"
94
+ "[dim]Tell the agent what to add or change. Then run the same "
95
+ "command again to write the new spec, and approve it with "
96
+ f"devflow approve {location.spec_id}.[/dim]"
97
+ )
98
+ else:
99
+ console.print(
100
+ "\n[bold]Next:[/bold] edit spec.md, then "
101
+ f"{continue_command}\n"
102
+ "[dim]DevFlow validates and registers your edited spec. Approve "
103
+ f"it again with devflow approve {location.spec_id}. To change "
104
+ "decisions instead, use devflow reopen with --discovery.[/dim]"
105
+ )
@@ -14,7 +14,11 @@ from devflow.core.config import (
14
14
  ConfigManager,
15
15
  DevFlowConfig,
16
16
  )
17
- from devflow.core.discovery import DiscoveryError, DiscoveryManager
17
+ from devflow.core.discovery import (
18
+ DiscoveryDocument,
19
+ DiscoveryError,
20
+ DiscoveryManager,
21
+ )
18
22
  from devflow.core.project import ProjectDetector
19
23
  from devflow.core.state import (
20
24
  ChangeLocation,
@@ -99,7 +103,7 @@ def _status(spec_id: str, path: Path) -> None:
99
103
  else:
100
104
  console.print("\n[yellow]No artifacts are registered.[/yellow]")
101
105
 
102
- _print_discovery(config=config, location=location)
106
+ discovery = _print_discovery(config=config, location=location)
103
107
 
104
108
  if state.approvals:
105
109
  console.print("\n[bold]Approvals[/bold]")
@@ -123,7 +127,7 @@ def _status(spec_id: str, path: Path) -> None:
123
127
  "They are not approved and do not advance the change.[/dim]"
124
128
  )
125
129
 
126
- next_step = _next_step(current, location)
130
+ next_step = _next_step(current, location, discovery)
127
131
  if next_step:
128
132
  console.print(f"\n[bold]Next:[/bold] {next_step}")
129
133
 
@@ -131,6 +135,7 @@ def _status(spec_id: str, path: Path) -> None:
131
135
  def _next_step(
132
136
  current: ChangeStatus,
133
137
  location: ChangeLocation,
138
+ discovery: DiscoveryDocument | None = None,
134
139
  ) -> str:
135
140
  """Suggest the next action for the current workflow state."""
136
141
  state = current.state
@@ -140,17 +145,26 @@ def _next_step(
140
145
  record.status == ArtifactStatus.STALE.value
141
146
  for record in artifacts.values()
142
147
  )
143
- if stale or current.orphans:
148
+ if current.orphans:
144
149
  return f"devflow doctor {spec_id}"
145
150
 
146
151
  spec = artifacts.get("spec")
147
152
  if state.status == WorkflowStatus.SPEC_APPROVED.value:
153
+ if stale:
154
+ return f"devflow reopen {spec_id}"
148
155
  spec_path = (
149
156
  spec.path
150
157
  if spec is not None
151
158
  else f"{location.change}/spec.md"
152
159
  )
153
- return f"ask your coding agent to implement `{spec_path}`"
160
+ step = f"ask your coding agent to implement `{spec_path}`"
161
+ suggestions = (
162
+ discovery.suggested_next_specs() if discovery is not None else ()
163
+ )
164
+ if suggestions:
165
+ title = suggestions[0].title.replace('"', "'")
166
+ step += f'. Next level: devflow spec "{title}"'
167
+ return step
154
168
  if (
155
169
  state.status == WorkflowStatus.DRAFT.value
156
170
  and spec is not None
@@ -169,18 +183,18 @@ def _print_discovery(
169
183
  *,
170
184
  config: DevFlowConfig,
171
185
  location: ChangeLocation,
172
- ) -> None:
186
+ ) -> DiscoveryDocument | None:
173
187
  manager = DiscoveryManager(config.root)
174
188
  if not manager.exists(location.directory):
175
- return
189
+ return None
176
190
  console.print("\n[bold]Discovery[/bold]")
177
191
  try:
178
192
  discovery = manager.load(location.directory, required=True)
179
193
  except DiscoveryError as error:
180
194
  console.print(f"[yellow]- invalid discovery: {error}[/yellow]")
181
- return
195
+ return None
182
196
  if discovery is None:
183
- return
197
+ return None
184
198
  console.print(
185
199
  f" status: {discovery.status} · "
186
200
  f"{len(discovery.pending_questions)} pending · "
@@ -212,3 +226,10 @@ def _print_discovery(
212
226
  f"{assumption.value}",
213
227
  soft_wrap=True,
214
228
  )
229
+
230
+ suggestions = discovery.suggested_next_specs()
231
+ if suggestions:
232
+ console.print("\n[bold]Suggested next specifications[/bold]")
233
+ for index, item in enumerate(suggestions, start=1):
234
+ console.print(f" {index}. {item.title}: {item.why}", soft_wrap=True)
235
+ return discovery
devflow/core/discovery.py CHANGED
@@ -29,6 +29,7 @@ MAX_QUESTIONS = 100
29
29
  MAX_ASSUMPTIONS = 100
30
30
  MAX_TEXT_LENGTH = 4_000
31
31
  MAX_OPTIONS = 10
32
+ MAX_DEFERRED = 30
32
33
 
33
34
  DISCOVERY_PENDING = "pending"
34
35
  DISCOVERY_AWAITING = "awaiting_clarification"
@@ -479,6 +480,45 @@ class DiscoveryIncompleteError(DiscoveryError):
479
480
  """Raised when a workflow requires a complete discovery."""
480
481
 
481
482
 
483
+ @dataclass(frozen=True)
484
+ class NextLevel:
485
+ """The option that would take a decision one level further."""
486
+
487
+ option: str
488
+ why: str
489
+
490
+ def to_dict(self) -> dict[str, Any]:
491
+ return {"option": self.option, "why": self.why}
492
+
493
+
494
+ @dataclass(frozen=True)
495
+ class DeferredItem:
496
+ """A next-level improvement suggested for a later specification."""
497
+
498
+ title: str
499
+ why: str
500
+ question_id: str | None = None
501
+
502
+ def to_dict(self) -> dict[str, Any]:
503
+ data: dict[str, Any] = {"title": self.title, "why": self.why}
504
+ if self.question_id:
505
+ data["question_id"] = self.question_id
506
+ return data
507
+
508
+
509
+ def _same_choice(answer: str | None, option: str) -> bool:
510
+ """Return whether an answer selects the given option."""
511
+ if not answer:
512
+ return False
513
+
514
+ def normalized(value: str) -> str:
515
+ return " ".join(value.split()).casefold().rstrip(" .")
516
+
517
+ chosen = normalized(answer)
518
+ expected = normalized(option)
519
+ return bool(expected) and chosen.startswith(expected)
520
+
521
+
482
522
  @dataclass(frozen=True)
483
523
  class DiscoveryQuestion:
484
524
  """One decision that may block specification generation."""
@@ -496,6 +536,16 @@ class DiscoveryQuestion:
496
536
  materiality: str = ""
497
537
  resolution_source: str | None = None
498
538
  evidence: tuple[str, ...] = ()
539
+ next_level: NextLevel | None = None
540
+
541
+ @property
542
+ def chose_next_level(self) -> bool:
543
+ """Return whether the user selected the next-level option."""
544
+ return (
545
+ self.next_level is not None
546
+ and self.is_resolved
547
+ and _same_choice(self.answer, self.next_level.option)
548
+ )
499
549
 
500
550
  @property
501
551
  def effective_materiality(self) -> str:
@@ -563,9 +613,11 @@ class DiscoveryQuestion:
563
613
  data["resolution_source"] = self.resolution_source
564
614
  if self.evidence:
565
615
  data["evidence"] = list(self.evidence)
616
+ data["options"] = list(self.options)
617
+ if self.next_level is not None:
618
+ data["next_level"] = self.next_level.to_dict()
566
619
  data.update(
567
620
  {
568
- "options": list(self.options),
569
621
  "answer": self.answer,
570
622
  "answered_by": self.answered_by,
571
623
  "answered_at": self.answered_at,
@@ -618,6 +670,39 @@ class DiscoveryDocument:
618
670
  updated_at: str
619
671
  questions: tuple[DiscoveryQuestion, ...] = ()
620
672
  assumptions: tuple[DiscoveryAssumption, ...] = ()
673
+ deferred: tuple[DeferredItem, ...] = ()
674
+
675
+ def suggested_next_specs(self) -> tuple[DeferredItem, ...]:
676
+ """Return next-level improvements to propose as later specs.
677
+
678
+ Explicitly deferred items come first. A decided question whose
679
+ next-level option was not selected adds that option.
680
+ """
681
+ items: list[DeferredItem] = []
682
+ seen: set[str] = set()
683
+
684
+ def add(item: DeferredItem) -> None:
685
+ key = " ".join(item.title.split()).casefold()
686
+ if key in seen:
687
+ return
688
+ seen.add(key)
689
+ items.append(item)
690
+
691
+ for item in self.deferred:
692
+ add(item)
693
+ for question in self.questions:
694
+ if question.next_level is None or question.is_pending:
695
+ continue
696
+ if question.chose_next_level:
697
+ continue
698
+ add(
699
+ DeferredItem(
700
+ title=question.next_level.option,
701
+ why=question.next_level.why,
702
+ question_id=question.id,
703
+ )
704
+ )
705
+ return tuple(items)
621
706
 
622
707
  @property
623
708
  def pending_blocking(self) -> tuple[DiscoveryQuestion, ...]:
@@ -747,6 +832,11 @@ class DiscoveryDocument:
747
832
  "assumptions": [
748
833
  assumption.to_dict() for assumption in self.assumptions
749
834
  ],
835
+ **(
836
+ {"deferred": [item.to_dict() for item in self.deferred]}
837
+ if self.deferred
838
+ else {}
839
+ ),
750
840
  }
751
841
 
752
842
 
@@ -1129,6 +1219,15 @@ class DiscoveryManager:
1129
1219
  )
1130
1220
  raise DiscoveryError(msg)
1131
1221
 
1222
+ deferred_data = _list(mapping.get("deferred"), "deferred")
1223
+ if len(deferred_data) > MAX_DEFERRED:
1224
+ msg = f"At most {MAX_DEFERRED} deferred items are allowed."
1225
+ raise DiscoveryError(msg)
1226
+ deferred = tuple(
1227
+ self._deferred(item, index, question_ids)
1228
+ for index, item in enumerate(deferred_data, start=1)
1229
+ )
1230
+
1132
1231
  document = DiscoveryDocument(
1133
1232
  version=version,
1134
1233
  spec_id=spec_id,
@@ -1140,6 +1239,7 @@ class DiscoveryManager:
1140
1239
  updated_at=updated_at,
1141
1240
  questions=questions,
1142
1241
  assumptions=assumptions,
1242
+ deferred=deferred,
1143
1243
  )
1144
1244
  if (
1145
1245
  document.status == DISCOVERY_COMPLETE
@@ -1210,6 +1310,23 @@ class DiscoveryManager:
1210
1310
  if len(options) > MAX_OPTIONS:
1211
1311
  msg = f"{identifier} has too many options."
1212
1312
  raise DiscoveryError(msg)
1313
+ next_level = None
1314
+ next_level_data = mapping.get("next_level")
1315
+ if next_level_data is not None:
1316
+ next_level_mapping = _mapping(
1317
+ next_level_data,
1318
+ f"{identifier}.next_level",
1319
+ )
1320
+ next_level = NextLevel(
1321
+ option=_limited_text(
1322
+ next_level_mapping.get("option"),
1323
+ f"{identifier}.next_level.option",
1324
+ ),
1325
+ why=_limited_text(
1326
+ next_level_mapping.get("why"),
1327
+ f"{identifier}.next_level.why",
1328
+ ),
1329
+ )
1213
1330
  resolution_source = _optional_text(
1214
1331
  mapping.get("resolution_source"),
1215
1332
  f"{identifier}.resolution_source",
@@ -1316,6 +1433,30 @@ class DiscoveryManager:
1316
1433
  materiality=materiality,
1317
1434
  resolution_source=resolution_source,
1318
1435
  evidence=evidence,
1436
+ next_level=next_level,
1437
+ )
1438
+
1439
+ def _deferred(
1440
+ self,
1441
+ data: object,
1442
+ index: int,
1443
+ question_ids: set[str],
1444
+ ) -> DeferredItem:
1445
+ mapping = _mapping(data, f"deferred[{index}]")
1446
+ question_id = _optional_text(
1447
+ mapping.get("question_id"),
1448
+ f"deferred[{index}].question_id",
1449
+ )
1450
+ if question_id is not None and question_id not in question_ids:
1451
+ msg = (
1452
+ f"deferred[{index}] references unknown question "
1453
+ f"{question_id!r}."
1454
+ )
1455
+ raise DiscoveryError(msg)
1456
+ return DeferredItem(
1457
+ title=_limited_text(mapping.get("title"), f"deferred[{index}].title"),
1458
+ why=_limited_text(mapping.get("why"), f"deferred[{index}].why"),
1459
+ question_id=question_id,
1319
1460
  )
1320
1461
 
1321
1462
  def _assumption(
@@ -23,6 +23,7 @@ from devflow.core.constitution import (
23
23
  specification_documents,
24
24
  )
25
25
  from devflow.core.discovery import (
26
+ DISCOVERY_PENDING,
26
27
  DiscoveryDocument,
27
28
  DiscoveryError,
28
29
  DiscoveryManager,
@@ -636,14 +637,15 @@ class SpecWorkflow:
636
637
  if prepared.path.is_file():
637
638
  ArtifactStore(prepared.root).archive(prepared.path)
638
639
  prepared.path.unlink(missing_ok=True)
639
- discovery = discovery_manager.add_questions(
640
- discovery,
641
- error.questions,
642
- )
643
- discovery_path, discovery_digest = discovery_manager.write(
644
- prepared.directory,
645
- discovery,
646
- )
640
+ if error.questions:
641
+ discovery = discovery_manager.add_questions(
642
+ discovery,
643
+ error.questions,
644
+ )
645
+ discovery_path, discovery_digest = discovery_manager.write(
646
+ prepared.directory,
647
+ discovery,
648
+ )
647
649
  discovery = discovery_manager.load(
648
650
  prepared.directory,
649
651
  required=True,
@@ -794,6 +796,11 @@ class SpecWorkflow:
794
796
  question_budget_maximum=settings.question_budget_maximum,
795
797
  max_rounds=settings.max_rounds,
796
798
  assumptions_enabled=settings.assumptions_enabled,
799
+ reopened=(
800
+ discovery.status == DISCOVERY_PENDING
801
+ and not discovery.pending_questions
802
+ and not discovery.pending_assumptions
803
+ ),
797
804
  )
798
805
  run_context = RunContext(
799
806
  root=config.root,
@@ -1052,6 +1059,7 @@ class SpecWorkflow:
1052
1059
  run_warnings,
1053
1060
  )
1054
1061
  if prepared.path.is_file():
1062
+ self._raise_if_returned_to_discovery(prepared, run_warnings)
1055
1063
  content = prepared.path.read_text(encoding="utf-8")
1056
1064
  self._raise_if_open_questions(
1057
1065
  content,
@@ -1083,6 +1091,7 @@ class SpecWorkflow:
1083
1091
  run_warnings,
1084
1092
  )
1085
1093
 
1094
+ self._raise_if_returned_to_discovery(prepared, run_warnings)
1086
1095
  run_warnings.append(
1087
1096
  "the interactive agent did not write the specification. "
1088
1097
  "Using deterministic DevFlow output."
@@ -1143,6 +1152,25 @@ class SpecWorkflow:
1143
1152
  if output_path is not None:
1144
1153
  output_path.unlink(missing_ok=True)
1145
1154
 
1155
+ def _raise_if_returned_to_discovery(
1156
+ self,
1157
+ prepared: PreparedSpec,
1158
+ run_warnings: list[str],
1159
+ ) -> None:
1160
+ """Stop when the agent recorded new decisions instead of a spec."""
1161
+ try:
1162
+ current = DiscoveryManager(prepared.root).load(
1163
+ prepared.directory,
1164
+ required=True,
1165
+ )
1166
+ except DiscoveryError as error:
1167
+ run_warnings.append(
1168
+ f"the specification agent left an invalid discovery.yaml: {error}"
1169
+ )
1170
+ return
1171
+ if current is not None and not current.is_complete:
1172
+ raise SpecOpenQuestionsError((), tuple(run_warnings))
1173
+
1146
1174
  def _raise_if_open_questions(
1147
1175
  self,
1148
1176
  content: str,
@@ -48,6 +48,7 @@ IGNORED_FILENAMES = {
48
48
  MAX_FILE_BYTES = 256_000
49
49
  MAX_ANALYSIS_FILES = 3000
50
50
  MAX_REFERENCES = 25
51
+ NEXT_SPECS_HEADING = "### 10.1 Suggested next specifications"
51
52
 
52
53
  STOPWORDS = {
53
54
  "a",
@@ -889,6 +890,7 @@ class SpecificationManager:
889
890
  if not cleaned.strip():
890
891
  cleaned = prepared.fallback_content
891
892
  source = "static"
893
+ cleaned = self.with_next_specs(cleaned, prepared.discovery)
892
894
 
893
895
  prepared.directory.mkdir(parents=True, exist_ok=True)
894
896
  ArtifactStore(prepared.root).write(
@@ -1085,6 +1087,50 @@ class SpecificationManager:
1085
1087
  cleaned = cleaned[start:]
1086
1088
  return cleaned.strip()
1087
1089
 
1090
+ def with_next_specs(
1091
+ self,
1092
+ content: str,
1093
+ discovery: DiscoveryDocument | None,
1094
+ ) -> str:
1095
+ """Write section 10.1 from the Discovery suggestions.
1096
+
1097
+ DevFlow owns this subsection so the agent does not spend tokens on
1098
+ it and the suggestions always match the recorded decisions.
1099
+ """
1100
+ section = re.search(
1101
+ r"^##\s+10\.[^\n]*\n(?P<body>.*?)(?=^##\s+11\.|\Z)",
1102
+ content,
1103
+ re.MULTILINE | re.DOTALL,
1104
+ )
1105
+ if section is None:
1106
+ return content
1107
+
1108
+ suggestions = (
1109
+ discovery.suggested_next_specs() if discovery is not None else ()
1110
+ )
1111
+ lines = [NEXT_SPECS_HEADING, ""]
1112
+ if suggestions:
1113
+ for index, item in enumerate(suggestions, start=1):
1114
+ command = item.title.replace('"', "'")
1115
+ lines.append(f"{index}. **{item.title}**: {item.why}")
1116
+ lines.append(f' `devflow spec "{command}"`')
1117
+ else:
1118
+ lines.append("None.")
1119
+ block = "\n".join(lines)
1120
+
1121
+ body = re.sub(
1122
+ r"^###\s+10\.1\b.*",
1123
+ "",
1124
+ section.group("body"),
1125
+ flags=re.MULTILINE | re.DOTALL,
1126
+ ).rstrip()
1127
+ new_body = f"{body}\n\n{block}\n\n" if body else f"\n{block}\n\n"
1128
+ return (
1129
+ content[: section.start("body")]
1130
+ + new_body
1131
+ + content[section.end("body"):]
1132
+ )
1133
+
1088
1134
  def extract_open_questions(self, content: str) -> tuple[str, ...]:
1089
1135
  """Read the open questions listed by an agent specification."""
1090
1136
  match = re.search(
@@ -1099,13 +1145,31 @@ class SpecificationManager:
1099
1145
  if not body or "no open questions" in body.lower():
1100
1146
  return ()
1101
1147
 
1148
+ lines = body.splitlines()
1149
+ marker = r"(?:\d+[.)]|[-*])\s+(.*)"
1150
+ if not any(re.match(rf"^{marker}", line) for line in lines):
1151
+ # Every item is indented: treat each one as a question.
1152
+ return tuple(
1153
+ item.group(1).strip()
1154
+ for line in lines
1155
+ if (item := re.match(rf"^\s*{marker}", line))
1156
+ and item.group(1).strip()
1157
+ )
1158
+
1159
+ # Nested bullets and continuation lines belong to the item above,
1160
+ # so one question keeps all of its context.
1102
1161
  questions: list[str] = []
1103
- for line in body.splitlines():
1104
- item = re.match(r"^\s*(?:\d+[.)]|[-*])\s+(.*)", line)
1105
- if item:
1106
- question = item.group(1).strip()
1107
- if question:
1108
- questions.append(question)
1162
+ for line in lines:
1163
+ top = re.match(rf"^{marker}", line)
1164
+ if top:
1165
+ if top.group(1).strip():
1166
+ questions.append(top.group(1).strip())
1167
+ continue
1168
+ text = line.strip()
1169
+ if not text or not questions:
1170
+ continue
1171
+ nested = re.match(rf"^\s*{marker}", line)
1172
+ questions[-1] += " " + (nested.group(1).strip() if nested else text)
1109
1173
  return tuple(questions)
1110
1174
 
1111
1175
  def _next_spec_directory(
@@ -24,6 +24,7 @@ from devflow.core.state.locator import (
24
24
  from devflow.core.state.manager import (
25
25
  ApprovalResult,
26
26
  ChangeStatus,
27
+ ReopenResult,
27
28
  WorkflowStateManager,
28
29
  )
29
30
  from devflow.core.state.models import (
@@ -56,6 +57,7 @@ __all__ = [
56
57
  "InvalidEventLogError",
57
58
  "InvalidStateError",
58
59
  "InvalidTransitionError",
60
+ "ReopenResult",
59
61
  "StaleArtifactError",
60
62
  "StateError",
61
63
  "UnsupportedStageError",
@@ -38,10 +38,12 @@ ARTIFACT_EVENT_SUFFIXES = frozenset(
38
38
  {"generated", "validated", "rejected", "stale"}
39
39
  )
40
40
  APPROVAL_EVENT_SUFFIX = "approved"
41
+ REOPEN_EVENT_SUFFIX = "reopened"
41
42
 
42
43
  _EVENT_KIND_WORKFLOW = "workflow"
43
44
  _EVENT_KIND_ARTIFACT = "artifact"
44
45
  _EVENT_KIND_APPROVAL = "approval"
46
+ _EVENT_KIND_REOPEN = "reopen"
45
47
 
46
48
  _EVENT_STATUSES = {
47
49
  "generated": ArtifactStatus.GENERATED.value,
@@ -190,6 +192,8 @@ def classify_event(
190
192
  return _EVENT_KIND_ARTIFACT, stage, suffix
191
193
  if suffix == APPROVAL_EVENT_SUFFIX:
192
194
  return _EVENT_KIND_APPROVAL, stage, suffix
195
+ if suffix == REOPEN_EVENT_SUFFIX and stage in STAGE_TARGETS:
196
+ return _EVENT_KIND_REOPEN, stage, suffix
193
197
 
194
198
  msg = f"Unknown workflow event type: {event_type}"
195
199
  raise InvalidEventLogError(msg)
@@ -255,6 +259,10 @@ def apply_event(state: WorkflowState, event: WorkflowEvent) -> WorkflowState:
255
259
  if stage is None or suffix is None:
256
260
  raise _event_error(event, "artifact event is missing its stage.")
257
261
  _apply_artifact_event(state, event, stage, suffix)
262
+ elif kind == _EVENT_KIND_REOPEN:
263
+ if stage is None:
264
+ raise _event_error(event, "reopen event is missing its stage.")
265
+ _apply_reopen(state, event, stage)
258
266
  else:
259
267
  if stage is None:
260
268
  raise _event_error(event, "approval event is missing its stage.")
@@ -671,6 +679,56 @@ def _apply_approval(
671
679
  state.status = target_value
672
680
 
673
681
 
682
+ _REOPEN_TARGETS = frozenset(
683
+ {
684
+ WorkflowStatus.DRAFT.value,
685
+ WorkflowStatus.AWAITING_CLARIFICATION.value,
686
+ }
687
+ )
688
+
689
+
690
+ def _apply_reopen(
691
+ state: WorkflowState,
692
+ event: WorkflowEvent,
693
+ stage: str,
694
+ ) -> None:
695
+ """Withdraw an approval and return the workflow to an editable state."""
696
+ payload = event.payload
697
+ payload_stage = payload.get("stage")
698
+ if payload_stage != stage:
699
+ raise _event_error(
700
+ event,
701
+ f"payload stage {payload_stage!r} does not match event type.",
702
+ )
703
+ approval = state.approvals.get(stage)
704
+ if approval is None:
705
+ raise _event_error(event, f"stage {stage!r} is not approved.")
706
+ if state.status != STAGE_TARGETS[stage]:
707
+ raise _event_error(
708
+ event,
709
+ f"stage {stage!r} cannot be reopened from {state.status}.",
710
+ )
711
+ target_value = payload.get("workflow_status")
712
+ if target_value not in _REOPEN_TARGETS:
713
+ raise _event_error(
714
+ event,
715
+ f"reopen target {target_value!r} is not draft or "
716
+ "awaiting_clarification.",
717
+ )
718
+
719
+ for kind in approval.artifacts:
720
+ record = state.artifacts.get(kind)
721
+ if record is not None and record.status == ArtifactStatus.APPROVED.value:
722
+ state.artifacts[kind] = replace(
723
+ record,
724
+ status=ArtifactStatus.VALIDATED.value,
725
+ approved_at="",
726
+ updated_at=event.timestamp,
727
+ )
728
+ state.approvals.pop(stage)
729
+ state.status = target_value
730
+
731
+
674
732
  def _event_error(
675
733
  event: WorkflowEvent,
676
734
  reason: str,
@@ -2,7 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from dataclasses import dataclass
5
+ from dataclasses import dataclass, replace
6
6
  from datetime import datetime, timezone
7
7
  from pathlib import Path
8
8
  from typing import Any
@@ -26,6 +26,7 @@ from devflow.core.clock import (
26
26
  )
27
27
  from devflow.core.discovery import (
28
28
  DISCOVERY_FILENAME,
29
+ DISCOVERY_PENDING,
29
30
  DiscoveryIncompleteError,
30
31
  DiscoveryManager,
31
32
  )
@@ -147,6 +148,17 @@ class ApprovalResult:
147
148
  warnings: tuple[str, ...] = ()
148
149
 
149
150
 
151
+ @dataclass(frozen=True)
152
+ class ReopenResult:
153
+ """Outcome of reopening an approved stage."""
154
+
155
+ location: ChangeLocation
156
+ state: WorkflowState
157
+ stage: str
158
+ archived: Path | None
159
+ discovery: bool
160
+
161
+
150
162
  class WorkflowStateManager:
151
163
  """Own workflow state, artifact registration and human approvals."""
152
164
 
@@ -654,6 +666,96 @@ class WorkflowStateManager:
654
666
  warnings=tuple(warnings),
655
667
  )
656
668
 
669
+ def reopen(
670
+ self,
671
+ location: ChangeLocation,
672
+ stage: str = "spec",
673
+ *,
674
+ discovery: bool = False,
675
+ by: str = "user",
676
+ ) -> ReopenResult:
677
+ """Withdraw an approval so the change can be edited again."""
678
+ normalized = stage.strip().lower()
679
+ if normalized != "spec":
680
+ msg = (
681
+ f"Stage '{stage}' cannot be reopened. Only the 'spec' stage is "
682
+ "available in this release."
683
+ )
684
+ raise UnsupportedStageError(msg)
685
+
686
+ with self._lock(location):
687
+ state = self._load_state(location, persist=True)
688
+ state = self._reconcile_locked(location, state)
689
+ if normalized not in state.approvals:
690
+ msg = (
691
+ f"Stage '{normalized}' is not approved for {location.change}; "
692
+ "there is nothing to reopen. Continue it with 'devflow spec "
693
+ f"--continue {location.spec_id}'."
694
+ )
695
+ raise StateError(msg)
696
+ if state.status != STAGE_TARGETS[normalized]:
697
+ msg = (
698
+ f"Change '{location.change}' has advanced to {state.status} "
699
+ f"and cannot reopen the '{normalized}' stage."
700
+ )
701
+ raise StateError(msg)
702
+
703
+ archived: Path | None = None
704
+ spec_path = location.directory / "spec.md"
705
+ if spec_path.is_file() and not spec_path.is_symlink():
706
+ archived = self.store.archive(spec_path)
707
+
708
+ target = (
709
+ WorkflowStatus.AWAITING_CLARIFICATION.value
710
+ if discovery
711
+ else WorkflowStatus.DRAFT.value
712
+ )
713
+ state = self._append_and_save(
714
+ location,
715
+ state,
716
+ f"{normalized}_reopened",
717
+ {
718
+ "stage": normalized,
719
+ "by": by,
720
+ "workflow_status": target,
721
+ "discovery": discovery,
722
+ },
723
+ actor=by,
724
+ run_id=None,
725
+ )
726
+
727
+ if discovery and "discovery" in state.artifacts:
728
+ manager = DiscoveryManager(self.root, clock=self.clock)
729
+ document = manager.load(location.directory, required=True)
730
+ assert document is not None
731
+ path, digest = manager.write(
732
+ location.directory,
733
+ replace(document, status=DISCOVERY_PENDING),
734
+ )
735
+ state = self._append_and_save(
736
+ location,
737
+ state,
738
+ "discovery_generated",
739
+ {
740
+ "stage": "discovery",
741
+ "kind": "discovery",
742
+ "path": self._relative_artifact_path(path),
743
+ "digest": digest,
744
+ "source": "human",
745
+ "metadata": {"stage": "discovery", "reopened": True},
746
+ },
747
+ actor=by,
748
+ run_id=None,
749
+ )
750
+
751
+ return ReopenResult(
752
+ location=location,
753
+ state=state,
754
+ stage=normalized,
755
+ archived=archived,
756
+ discovery=discovery,
757
+ )
758
+
657
759
  def _ensure_artifact_current(
658
760
  self,
659
761
  location: ChangeLocation,
@@ -112,6 +112,7 @@ def build_discovery_prompt(
112
112
  question_budget_maximum: int = 12,
113
113
  max_rounds: int = 3,
114
114
  assumptions_enabled: bool = True,
115
+ reopened: bool = False,
115
116
  ) -> str:
116
117
  """Render the interactive discovery prompt for any harness."""
117
118
  template = load_prompt("discovery.md")
@@ -151,6 +152,7 @@ def build_discovery_prompt(
151
152
  ),
152
153
  "max_rounds": str(max(1, max_rounds)),
153
154
  "assumptions_note": assumptions_note,
155
+ "reopened_note": _REOPENED_NOTE if reopened else "",
154
156
  "permission_summary": _permission_summary(permissions),
155
157
  }
156
158
  rendered = template
@@ -159,6 +161,16 @@ def build_discovery_prompt(
159
161
  return rendered
160
162
 
161
163
 
164
+ _REOPENED_NOTE = (
165
+ "## Reopened Discovery\n\n"
166
+ "The user reopened Discovery after approving the specification. "
167
+ "Start by asking the user what to add or change. Append a new question "
168
+ "with the next `Qn` identifier for every new decision. Change an "
169
+ "existing answer only when the user explicitly asks for it, and keep "
170
+ "its id. Set `status` to `complete` when nothing remains pending.\n\n"
171
+ )
172
+
173
+
162
174
  def build_discovery_repair_prompt(
163
175
  *,
164
176
  discovery_path: str,
@@ -295,6 +307,20 @@ def build_decision_context(
295
307
  lines.append("- None.")
296
308
  lines.append("")
297
309
 
310
+ lines.extend(["### Suggested next specifications", ""])
311
+ suggestions = (
312
+ discovery.suggested_next_specs() if discovery is not None else ()
313
+ )
314
+ if suggestions:
315
+ for item in suggestions:
316
+ source = f" ({item.question_id})" if item.question_id else ""
317
+ lines.append(
318
+ f"- {_clip(item.title, 160)}{source}: {_clip(item.why, 200)}"
319
+ )
320
+ else:
321
+ lines.append("- None.")
322
+ lines.append("")
323
+
298
324
  rendered = "\n".join(lines)
299
325
  if len(rendered) <= max_chars:
300
326
  return rendered
@@ -441,11 +467,15 @@ def _mode_instructions(
441
467
  return (
442
468
  "You are running interactively. Discovery is complete; use its "
443
469
  "recorded answers and accepted assumptions as settled decisions. "
444
- "Write the complete specification to "
445
- f"`{spec_path}` using the available file tools. If a decision is "
446
- "genuinely missing, do not write the specification: report it as "
447
- "a numbered item in section 7 so DevFlow can return it to "
448
- "Discovery. Do not finish until the file exists and contains the "
470
+ "Before writing, check that every decision the specification "
471
+ "needs is recorded. If one is missing, do not write the "
472
+ "specification: append each missing decision to the discovery "
473
+ "record as a pending question with options and a `next_level`, "
474
+ "set its `status` to `awaiting_clarification`, and tell the user "
475
+ "to exit this session so DevFlow returns to Discovery. Otherwise "
476
+ "write the complete specification to "
477
+ f"`{spec_path}` using the available file tools. Do not finish "
478
+ "until the file exists and contains the "
449
479
  "complete document. Then tell the user that the specification is "
450
480
  "written and that they must exit this session so DevFlow can "
451
481
  "validate it. Exiting earlier makes DevFlow replace it with a "
@@ -36,6 +36,47 @@ persists, enforces invariants and decides completeness.
36
36
  Ask only what materially changes the implementation. Prefer explicit,
37
37
  reversible defaults for everything else.
38
38
 
39
+ ## Level-Based Discovery
40
+
41
+ Build the solution level by level. Assume a user with technical
42
+ knowledge who wants to learn and improve along the way; Discovery
43
+ traces that path instead of solving everything at once.
44
+
45
+ 1. **Level 1 first.** Scope this specification to the essential
46
+ behavior of the request, built with the tools the project already
47
+ has, plus basic and obvious security.
48
+ 2. **Security is never assumed or hidden.** Ask every basic security
49
+ decision explicitly, recommend the basic option and explain in one
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. If the user picks it, record the answer with that exact text. If
56
+ not, DevFlow proposes it as a next specification. Do not ask
57
+ follow-up questions about the next level in this specification.
58
+ 4. **Do not go deeper than this level.** When an answer opens a more
59
+ advanced decision (limits, expiration policies, multiple devices,
60
+ scaling), record it in `deferred` with a short `title` and `why`
61
+ instead of asking it now.
62
+ 5. **Split large requests.** When the request bundles several
63
+ independent features, ask in the first round which part this
64
+ specification covers, proposing a level-1 scope. Record the rest in
65
+ `deferred`.
66
+ 6. **Nothing is decided silently.** Every suggestion of yours reaches
67
+ the user with its explanation, as a question option or as a
68
+ `deferred` item; never as an unstated requirement.
69
+
70
+ ## Readiness Check
71
+
72
+ Before reporting Discovery as complete, walk through what the
73
+ specification will need and confirm a decision exists for each item:
74
+ every user-facing flow and the interfaces it uses (API, HTML pages,
75
+ CLI), the data stored and where, error and unauthenticated behavior,
76
+ how each level-1 security measure works, and what is out of scope. Ask
77
+ every missing decision in the same round. The specification writer
78
+ must not find new decisions.
79
+
39
80
  ## Decision Outcomes
40
81
 
41
82
  Every decision has exactly one outcome:
@@ -169,7 +210,12 @@ questions:
169
210
  reason: "..."
170
211
  blocking: true
171
212
  status: pending
172
- options: []
213
+ options:
214
+ - "Basic option (recommended for level 1)"
215
+ - "Next-level option"
216
+ next_level:
217
+ option: "Next-level option"
218
+ why: "What it improves and when it is worth it."
173
219
  - id: Q2
174
220
  category: architecture_boundary
175
221
  materiality: technical
@@ -198,8 +244,15 @@ assumptions:
198
244
  reason: "..."
199
245
  source: agent_default
200
246
  status: pending_acceptance
247
+ deferred:
248
+ - title: "Limit failed login attempts"
249
+ why: "Protects accounts from password guessing once login works."
250
+ question_id: Q1
201
251
  ```
202
252
 
253
+ `next_level` and `deferred` are optional, but every material question
254
+ should have a `next_level` unless no meaningful next level exists.
255
+
203
256
  ### YAML Safety Rules
204
257
 
205
258
  - Quote every free-text scalar with single quotes when it contains
@@ -281,10 +334,12 @@ assumption is unaccepted, and to `complete` only when nothing remains.
281
334
  - Stop asking only when no decision is pending and every assumption is
282
335
  accepted. A decision is not optional because it is marked
283
336
  non-blocking; resolve it or record an assumption instead.
284
- - If the answer to one question raises a new decision, append a new
285
- question before reporting Discovery as ready.
337
+ - If an answer raises a new decision needed at this level, append a
338
+ new question and ask it in the same round when it is independent. If
339
+ the new decision belongs to the next level, record it in `deferred`
340
+ instead.
286
341
 
287
- ## Execution Instructions
342
+ {{reopened_note}}## Execution Instructions
288
343
 
289
344
  {{mode_instructions}}
290
345
 
devflow/prompts/spec.md CHANGED
@@ -52,8 +52,9 @@ implemented code.
52
52
  - Write only the DevFlow specification. Never create implementation
53
53
  files.
54
54
  - Do not invent requirements. Every decision must already be recorded in
55
- Discovery. If a decision is genuinely missing, return it to Discovery
56
- instead of writing an open question into an approvable specification.
55
+ Discovery, however small. Check this before writing anything: if a
56
+ decision is missing, return it to Discovery instead of writing the
57
+ specification.
57
58
  - Do not duplicate or replace the project constitution. Reference the
58
59
  documents that apply.
59
60
  - Specs must remain portable between agent harnesses. Do not include
@@ -180,7 +181,9 @@ renumber the document.
180
181
  not add assumptions. If a decision is genuinely missing, leave the
181
182
  specification invalid by listing the unresolved question as a
182
183
  numbered item in section 7; DevFlow will return it to Discovery for a
183
- human answer. When a Discovery digest is provided, include that exact
184
+ human answer. Each missing decision is one top-level numbered item
185
+ with the complete question; do not use nested bullets. When a
186
+ Discovery digest is provided, include that exact
184
187
  digest in the header table, state that Discovery is complete, and
185
188
  reference the recorded answers and accepted assumptions without
186
189
  contradicting them.
@@ -189,7 +192,9 @@ renumber the document.
189
192
  - Section 9 lists the constitution documents that apply and their
190
193
  profile scope. Reference paths, do not copy their contents.
191
194
  - Section 10 states what is explicitly excluded from this change. In
192
- Greenfield, include code generation and planning in this stage.
195
+ 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.
193
198
  - Section 11 contains the review and approval checklist.
194
199
  <!-- devflow:mode existing -->
195
200
  - Section 3 cites real files from the context. Explain their relevance.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: devflow-toolkit
3
- Version: 0.3.21
3
+ Version: 0.3.23
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.21`.**
35
+ **Current version: `0.3.23`.**
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.21-py3-none-any.whl
155
+ pip install devflow_toolkit-0.3.23-py3-none-any.whl
156
156
  ```
157
157
 
158
158
  Verify the installation:
@@ -428,7 +428,7 @@ as an architectural constraint when it is present.
428
428
 
429
429
  ### Harnesses
430
430
 
431
- | Harness | Status in 0.3.21 |
431
+ | Harness | Status in 0.3.23 |
432
432
  | --- | --- |
433
433
  | OpenCode | Verified end-to-end; interactive Discovery uses the `question` tool |
434
434
  | Antigravity | Custom agents and scoped permissions generated; `agy` loading and print mode verified |
@@ -683,6 +683,58 @@ appends the question to `discovery.yaml`, and returns the change to
683
683
  specification is generated. `devflow approve` rejects a
684
684
  specification that still lists open questions.
685
685
 
686
+ In an interactive run the specification agent checks for missing
687
+ decisions **before** writing. If one is missing, it appends the question
688
+ to `discovery.yaml` and stops without writing `spec.md`, so no tokens are
689
+ spent on a document that would be discarded. When an agent lists
690
+ questions in section 7, nested bullets stay part of the same question.
691
+
692
+ ### Level-based Discovery
693
+
694
+ Discovery builds the solution level by level instead of solving
695
+ everything at once:
696
+
697
+ 1. **Level 1 first.** The spec covers the essential behavior, built with
698
+ the tools the project already has, plus basic and obvious security.
699
+ 2. **Security is always asked, never assumed.** Basic security decisions
700
+ are explicit questions with a recommended option and a short
701
+ explanation, so the user learns them by answering.
702
+ 3. **Every question offers a next level.** One option takes the decision
703
+ one level further. It is recorded in `next_level`:
704
+
705
+ ```yaml
706
+ options:
707
+ - "Token valid until logout (basic)"
708
+ - "Token that expires after 24 hours"
709
+ next_level:
710
+ option: "Token that expires after 24 hours"
711
+ why: "Limits the damage if a token leaks."
712
+ ```
713
+
714
+ If the user chooses it, the answer uses that exact text. If not,
715
+ DevFlow treats it as a suggestion for a later specification.
716
+ 4. **No deeper than this level.** More advanced decisions found along
717
+ the way, and parts of a large request left for later, are recorded in
718
+ `deferred`:
719
+
720
+ ```yaml
721
+ deferred:
722
+ - title: "Limit failed login attempts"
723
+ why: "Protects accounts from password guessing."
724
+ question_id: Q2
725
+ ```
726
+
727
+ 5. **Readiness check.** Before closing, the agent confirms a decision
728
+ exists for every flow, interface, stored data, error case and level-1
729
+ security measure, and asks what is missing in the same round.
730
+
731
+ DevFlow collects `deferred` items and every unchosen `next_level` into
732
+ **suggested next specifications**. They appear in the Decision Context,
733
+ in `devflow status`, after approval in the `Next:` line, and in
734
+ `spec.md` section `10.1 Suggested next specifications`. DevFlow writes
735
+ that subsection itself, with a ready-to-run `devflow spec "..."` command
736
+ for each item; the agent does not write it.
737
+
686
738
  ## Workflow
687
739
 
688
740
  1. Initialize the project with `devflow init`.
@@ -696,13 +748,14 @@ specification that still lists open questions.
696
748
  8. If artifacts exist without workflow state, diagnose with
697
749
  `devflow doctor <id>` and repair with `devflow recover <id>`.
698
750
 
699
- Available commands in `0.3.21`:
751
+ Available commands in `0.3.23`:
700
752
 
701
753
  | Command | Status |
702
754
  | --- | --- |
703
755
  | `devflow init` | Implemented |
704
756
  | `devflow spec` | Implemented: Discovery, specification, and `--continue` |
705
757
  | `devflow approve <id>` (stage `spec` by default) | Implemented |
758
+ | `devflow reopen <id>` | Implemented: withdraw a spec approval to change it |
706
759
  | `devflow status <id>` | Implemented |
707
760
  | `devflow doctor <id>` | Implemented: read-only diagnostics |
708
761
  | `devflow recover <id>` | Implemented: register existing artifacts |
@@ -928,7 +981,7 @@ devflow approve 001
928
981
  ```
929
982
 
930
983
  Approval is explicit and binds the decision to the current artifact
931
- digests. For a `0.3.21` change it binds `spec.md`, `discovery.yaml` and,
984
+ digests. For a `0.3.23` change it binds `spec.md`, `discovery.yaml` and,
932
985
  when a manifest applies, the architecture manifest digest. Repeating the
933
986
  same approval is a no-op. If an artifact changes after validation,
934
987
  DevFlow marks it stale and refuses approval until it is regenerated and
@@ -939,7 +992,7 @@ and names the pending questions and assumptions. Approval also rejects a
939
992
  specification whose section 7 still lists open questions. Legacy `0.2.0`
940
993
  changes without `discovery.yaml` remain approvable with a warning.
941
994
 
942
- Only the `spec` stage is available in `0.3.21`, so `--stage` is optional
995
+ Only the `spec` stage is available in `0.3.23`, so `--stage` is optional
943
996
  and defaults to `spec`. `--stage plan` and `--stage review` are
944
997
  rejected. There are no `plan`, `implement` or
945
998
  `review` commands in this release.
@@ -967,6 +1020,41 @@ The generated `AGENTS.md` (or `CLAUDE.md`) tells the agent to:
967
1020
  this step. Discovery and specification prompts skip it to save tokens;
968
1021
  the specification still lists it in section 9.
969
1022
 
1023
+ ### Reopen an approved specification
1024
+
1025
+ An approved specification is a contract. To change it, reopen it first;
1026
+ editing `spec.md` directly only marks it `stale`.
1027
+
1028
+ ```bash
1029
+ devflow reopen 001 # fix or extend the spec text yourself
1030
+ devflow reopen 001 --discovery # add or change decisions with the agent
1031
+ ```
1032
+
1033
+ `reopen` asks for confirmation (skip it with `--yes`), copies the
1034
+ current `spec.md` into `history/`, records a `spec_reopened` event and
1035
+ withdraws the approval. The previous approval stays in `events.jsonl`;
1036
+ nothing is deleted.
1037
+
1038
+ Without `--discovery`, the change returns to `draft`:
1039
+
1040
+ ```bash
1041
+ # edit spec.md
1042
+ devflow spec --continue 001 # validates and registers your edited spec
1043
+ devflow approve 001
1044
+ ```
1045
+
1046
+ With `--discovery`, the change returns to `awaiting_clarification` and
1047
+ Discovery is marked pending:
1048
+
1049
+ ```bash
1050
+ devflow spec --continue 001 # Discovery session: tell the agent what changes
1051
+ devflow spec --continue 001 # writes the new spec
1052
+ devflow approve 001
1053
+ ```
1054
+
1055
+ Only an approved spec can be reopened, and only while the change is in
1056
+ `spec_approved`.
1057
+
970
1058
  ## Generated files
971
1059
 
972
1060
  ```text
@@ -1006,12 +1094,13 @@ DevFlow rebuilds or rejects it rather than trusting it.
1006
1094
 
1007
1095
  ```text
1008
1096
  generated -> validated -> approved
1009
- | |
1010
- +-> rejected +-> stale
1097
+ | | |
1098
+ +-> rejected +-> stale +-> reopen -> validated
1011
1099
  ```
1012
1100
 
1013
1101
  - An approval stores the artifact kind and its SHA-256 digest.
1014
- - Editing an approved artifact makes it stale.
1102
+ - Editing an approved artifact makes it stale. Use `devflow reopen` to
1103
+ withdraw the approval and change it on purpose.
1015
1104
  - A stale, unvalidated or orphan artifact cannot be approved.
1016
1105
  - Semantic validation rejects malformed or inconsistent histories.
1017
1106
  - Artifact and state writes are atomic; a failed write does not leave a
@@ -1,5 +1,5 @@
1
1
  devflow/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
- devflow/cli.py,sha256=qs3XGZxEoJaxJPkAA1kxWxfPA-vdkQYtQYipMXMYu_M,1350
2
+ devflow/cli.py,sha256=jzawrjsQMjn4JfIoCAKDfXE9lQBDzydHhtBP_etuCqs,1449
3
3
  devflow/adapters/__init__.py,sha256=WcsjXQTKzHNzMAHx82-sdJQeR3ceHRVqLWTUtRlaraE,867
4
4
  devflow/adapters/agents.py,sha256=OZnz7wAJNcIojtgaQIK1iB6QKWGgv2VCmoBp8M9DUKE,1423
5
5
  devflow/adapters/antigravity.py,sha256=tbhAWUNQt5fPemN_N8zEEdaBMPDRExpcXfF6obvvXvo,9124
@@ -7,7 +7,7 @@ devflow/adapters/base.py,sha256=YggY_IwHExdybl5S9NjwZSlmmcw9Y6z7DhQsl3JLvXs,2055
7
7
  devflow/adapters/claude_code.py,sha256=El4wYuEgLMr4NAmZG58cVlpkSn_MCOAtQ7Qq2zFIOuI,3689
8
8
  devflow/adapters/codex.py,sha256=5EVBRlYg3ClYhvN1NmUfxhBrEURLryIZTpHQkyFtzx8,3616
9
9
  devflow/adapters/detector.py,sha256=92BkNAvWs2Vh8H6xJzMweBDCw6yuYVg7sV4LoSZ8KFo,3291
10
- devflow/adapters/instructions.py,sha256=lEzV03wzAFsrENDRDWwiHUyANeAqmCgfSEqmYaf12f4,10872
10
+ devflow/adapters/instructions.py,sha256=AUje2tYnyI8yxnZQ5JlUjBON8Nz_yq4_yxpCz_DQoys,10885
11
11
  devflow/adapters/kiro.py,sha256=1w9U8oP0i2un6YeiV5uOUQ8qrOYHiF1K-788iVqHzhA,7709
12
12
  devflow/adapters/opencode.py,sha256=AtIsgKam25Y3CjI4DlXqODQO_D74Cn_N-G02MIsBI44,8503
13
13
  devflow/adapters/registry.py,sha256=G1HquOcSggwT0qm8PIm_Fv5Wj354G20rnI0C7vPhrSo,1263
@@ -18,31 +18,32 @@ devflow/commands/doctor.py,sha256=vYk2i3OksbGpHEUFsqi7c4w44mAXRmY0OeEdO8h5j_M,41
18
18
  devflow/commands/harness.py,sha256=0IH_PPeYmW3aQ_WnUSkFzxpe3A4FtSyjWfHq-Ug7Eos,10549
19
19
  devflow/commands/init.py,sha256=G2LDYDElWDSDPk3-1DfRtv8sW_z-9ITJH1Co6C5jiyw,17188
20
20
  devflow/commands/recover.py,sha256=sV9x5-30E_3XRBe7JItDiSG-pqrowRzjqOkC_eyrhFQ,2165
21
+ devflow/commands/reopen.py,sha256=bZiX-dyKgmtdKdV4FHwEwRCFvuuX5jezBCI7wIpkHYU,2971
21
22
  devflow/commands/spec.py,sha256=7glxFHKuJd33mL6YayrxRJ6TViUmmQk5rijbNepsbig,16353
22
- devflow/commands/status.py,sha256=-T8mfRAaXRjEIZJ7xcrGf3oHUjYKwoo28fCI0ILfn14,6036
23
+ devflow/commands/status.py,sha256=Lazqr7I8heJHCK-0q3NQxsIORwRzopDwkRgAnbcdnA4,6742
23
24
  devflow/core/__init__.py,sha256=hN7i4-PDaZ7y4P8qRpZl_lJvIiPyQaN1TDGnw2BecYU,427
24
25
  devflow/core/architecture.py,sha256=qllllsUVqA76LiSU6z_s4U8dxMcs6ClKXU16HxI3yOI,13692
25
26
  devflow/core/clock.py,sha256=KZROv6o51Ln1EzK00ySCxfc7WPZqPlaQhFfjfdc_TMY,1651
26
27
  devflow/core/config.py,sha256=VsR2ezH1toydLVyniy-BXtC843vDIstxI2-8vh4VmnU,26455
27
28
  devflow/core/constitution.py,sha256=rPLc8Puv9nUMC_GZwzOqvr1B-4urdxAISr655od2IPM,5333
28
- devflow/core/discovery.py,sha256=oIaC7S3c5zIrhzAz4J9pq6-pZqU1Q9vE0AgWdBDElBc,55994
29
+ devflow/core/discovery.py,sha256=_o321P0puy_kgrs0eMpBNavRYON-UnLGsjEpzvqSwUs,60022
29
30
  devflow/core/file_types.py,sha256=5S5YywOaTESDiln4kP7qyJFEjxHoiF6tSBbwuXNpDDc,566
30
31
  devflow/core/ports.py,sha256=6jlqeR40MNaz-IuZIAPimXpRKew-wMUab3KzelcTXsU,4541
31
32
  devflow/core/profile_manager.py,sha256=QnnJka2KIKD2tCSWJkGTOUEFMgmQT0Z9Qv173JKWKHw,8937
32
33
  devflow/core/project.py,sha256=4OnudghY5N5rCOmafWO5Hk68M7T3-mOV0j0k0dh2luE,16891
33
34
  devflow/core/recovery.py,sha256=W2If6Ymb3ISwMN8IVQYCwptDUzhxejlF-P2NvMYyZP0,8818
34
- devflow/core/spec_workflow.py,sha256=qRKWeGc90NAkMAzX7Vdzgn25o2Ry_Z5V9kioZO6ODZ4,39830
35
- devflow/core/specification.py,sha256=wRFrS64YGS6YOMQeNjdD73TlEWaSSs6_mTTg7flRlHQ,64851
35
+ devflow/core/spec_workflow.py,sha256=FXzP1ZDBMACZ02xpBSxOXtU_OOSIwXcbnultBftddcs,40784
36
+ devflow/core/specification.py,sha256=3BkfHSUA8RFJNgyPZDZkCuq7bdjuRPOVErncMnR7Wkw,66893
36
37
  devflow/core/artifacts/__init__.py,sha256=gt9xahPynoxv75FMq1ZJx91ILTIv4ExuvX1Ymrxwr2c,627
37
38
  devflow/core/artifacts/errors.py,sha256=hwZxnLFcUTtEjDWtN6rUCkM69EN19LGVlc6HD-pNZyk,493
38
39
  devflow/core/artifacts/models.py,sha256=xJjmY8jUAHxqYN9u1JEu8CbJB-IJg1xb9P-LDaP5_Hw,2049
39
40
  devflow/core/artifacts/store.py,sha256=ZHAhWAFiqtviwhpfQ0GDkizndpcqtpU0opTbsSJKrWA,4167
40
- devflow/core/state/__init__.py,sha256=PiHKck1ZzUTSNvZBrFnk1O20godD2-Ah1hsEku1OR78,1545
41
+ devflow/core/state/__init__.py,sha256=FNjS0Qxegx8rAz1gM6hXEV49v_KLeZ6zVDupSo_3CgI,1579
41
42
  devflow/core/state/errors.py,sha256=dgF-x4TCxQTXc1OifyT8UZSU-0PBhATjO1x6OTMagac,1017
42
- devflow/core/state/events.py,sha256=IfwFCC0jbrQsH1tzADyqwm8HtWo5fR7QDD85M6JH8N0,20698
43
+ devflow/core/state/events.py,sha256=1l_9TijGE2mTw46WEoyguBTKuUrvBBaNpR8PCRlzN8A,22422
43
44
  devflow/core/state/locator.py,sha256=WD_T_a6QiXpAipKeCUm_Y72r7OcthzUnVaulXFRLqZ0,3177
44
45
  devflow/core/state/lock.py,sha256=94llvwHtCc5WOw-Uq8kDCu4iOBpRM4ccp6Q6fLZpYZ0,2089
45
- devflow/core/state/manager.py,sha256=YDe6-H-tg7iYLCFP24R1_queoRNJnQbeqO5oe_M6eLQ,28926
46
+ devflow/core/state/manager.py,sha256=o4Qo2C3pJOpOS6Id-NB4hNeKbvvoTDwbf6E2Jv_j-pE,31876
46
47
  devflow/core/state/models.py,sha256=4GTrS34ymbJIyBeZkcCi0z0e1bsq67vdxRSnSQ9O3gc,4654
47
48
  devflow/core/state/transitions.py,sha256=Go0zLhxcujWhaZEGg7JMqcC_UJU_nEFEBbpKIqrCtrs,3581
48
49
  devflow/models/__init__.py,sha256=hXX3IDZbHgklmuzVVlpiRs5SSPnrkO5kN1-k2hIEk7E,156
@@ -58,12 +59,12 @@ devflow/profiles/django-backend/profile.yaml,sha256=SNj7a3yamdJx-P69GvIJmLkC2svO
58
59
  devflow/profiles/django-backend/constitution/django-standards.md,sha256=0M-XmxOpEmgIadcaVdf6OVmll8Oec0jEjcJ4C8MfwhQ,2052
59
60
  devflow/profiles/fastapi-backend/profile.yaml,sha256=5_b-zWSX0HV-tw_2ntRCSa4DyP3NUqYWmxOh55pXYmc,321
60
61
  devflow/profiles/fastapi-backend/constitution/fastapi-standards.md,sha256=iFKib4i_9z4wBQ9thl-uftg5g-CHwvmFWzMtLgA7CBk,1949
61
- devflow/prompts/__init__.py,sha256=FxVGrfvitbWHLOeKosi-5mcvjX_cj-KC0UwYTx8wq6M,16960
62
+ devflow/prompts/__init__.py,sha256=umS5zRYLk0yU3oV3ZnFsMKYaFfWBjxLG8FCmSibKjYw,18134
62
63
  devflow/prompts/discovery-repair.md,sha256=YfTfrrw5uUZvC_x6X2lrYEDkMNhanhoe0ER3Yc2-rgI,1135
63
- devflow/prompts/discovery.md,sha256=NejWiC1QU5hfgQ90M1qRHkDmIoBS4v5INPp1eUYxy44,11540
64
- devflow/prompts/spec.md,sha256=ZbZXS_76mWqihqRD4BeHpCc62Rbqoeb-F9XmkKL3_ww,7153
65
- devflow_toolkit-0.3.21.dist-info/METADATA,sha256=ElTX0RrIr1bkIoQ800O_PY8ZSt3Yjxvaev65PWHBYkQ,45314
66
- devflow_toolkit-0.3.21.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
67
- devflow_toolkit-0.3.21.dist-info/entry_points.txt,sha256=wPmqE1081vi8s3xf-Wfzfvpl-44IKgwx7OGoLEK3u7o,44
68
- devflow_toolkit-0.3.21.dist-info/licenses/LICENSE,sha256=Wa04lstC8Goe4b9IYfEYWB2k7nokYBejZl6NdyAl8rA,1077
69
- devflow_toolkit-0.3.21.dist-info/RECORD,,
64
+ devflow/prompts/discovery.md,sha256=GoQzhWE9R10p22uzdusIt-vf56kIl9YnI6RoweLGvzM,14281
65
+ devflow/prompts/spec.md,sha256=90NI6atLfvCcLKAojcxgEfCJDSt-kbb70KGctu_1tXA,7375
66
+ devflow_toolkit-0.3.23.dist-info/METADATA,sha256=CJ0ogkTWQyAtosJPhzJCJ1Mx7DijrONHPl1zfsBMmIk,48787
67
+ devflow_toolkit-0.3.23.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
68
+ devflow_toolkit-0.3.23.dist-info/entry_points.txt,sha256=wPmqE1081vi8s3xf-Wfzfvpl-44IKgwx7OGoLEK3u7o,44
69
+ devflow_toolkit-0.3.23.dist-info/licenses/LICENSE,sha256=Wa04lstC8Goe4b9IYfEYWB2k7nokYBejZl6NdyAl8rA,1077
70
+ devflow_toolkit-0.3.23.dist-info/RECORD,,