devflow-toolkit 0.3.22__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.
@@ -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
@@ -152,7 +157,14 @@ def _next_step(
152
157
  if spec is not None
153
158
  else f"{location.change}/spec.md"
154
159
  )
155
- 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
156
168
  if (
157
169
  state.status == WorkflowStatus.DRAFT.value
158
170
  and spec is not None
@@ -171,18 +183,18 @@ def _print_discovery(
171
183
  *,
172
184
  config: DevFlowConfig,
173
185
  location: ChangeLocation,
174
- ) -> None:
186
+ ) -> DiscoveryDocument | None:
175
187
  manager = DiscoveryManager(config.root)
176
188
  if not manager.exists(location.directory):
177
- return
189
+ return None
178
190
  console.print("\n[bold]Discovery[/bold]")
179
191
  try:
180
192
  discovery = manager.load(location.directory, required=True)
181
193
  except DiscoveryError as error:
182
194
  console.print(f"[yellow]- invalid discovery: {error}[/yellow]")
183
- return
195
+ return None
184
196
  if discovery is None:
185
- return
197
+ return None
186
198
  console.print(
187
199
  f" status: {discovery.status} · "
188
200
  f"{len(discovery.pending_questions)} pending · "
@@ -214,3 +226,10 @@ def _print_discovery(
214
226
  f"{assumption.value}",
215
227
  soft_wrap=True,
216
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(
@@ -637,14 +637,15 @@ class SpecWorkflow:
637
637
  if prepared.path.is_file():
638
638
  ArtifactStore(prepared.root).archive(prepared.path)
639
639
  prepared.path.unlink(missing_ok=True)
640
- discovery = discovery_manager.add_questions(
641
- discovery,
642
- error.questions,
643
- )
644
- discovery_path, discovery_digest = discovery_manager.write(
645
- prepared.directory,
646
- discovery,
647
- )
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
+ )
648
649
  discovery = discovery_manager.load(
649
650
  prepared.directory,
650
651
  required=True,
@@ -1058,6 +1059,7 @@ class SpecWorkflow:
1058
1059
  run_warnings,
1059
1060
  )
1060
1061
  if prepared.path.is_file():
1062
+ self._raise_if_returned_to_discovery(prepared, run_warnings)
1061
1063
  content = prepared.path.read_text(encoding="utf-8")
1062
1064
  self._raise_if_open_questions(
1063
1065
  content,
@@ -1089,6 +1091,7 @@ class SpecWorkflow:
1089
1091
  run_warnings,
1090
1092
  )
1091
1093
 
1094
+ self._raise_if_returned_to_discovery(prepared, run_warnings)
1092
1095
  run_warnings.append(
1093
1096
  "the interactive agent did not write the specification. "
1094
1097
  "Using deterministic DevFlow output."
@@ -1149,6 +1152,25 @@ class SpecWorkflow:
1149
1152
  if output_path is not None:
1150
1153
  output_path.unlink(missing_ok=True)
1151
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
+
1152
1174
  def _raise_if_open_questions(
1153
1175
  self,
1154
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(
@@ -307,6 +307,20 @@ def build_decision_context(
307
307
  lines.append("- None.")
308
308
  lines.append("")
309
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
+
310
324
  rendered = "\n".join(lines)
311
325
  if len(rendered) <= max_chars:
312
326
  return rendered
@@ -453,11 +467,15 @@ def _mode_instructions(
453
467
  return (
454
468
  "You are running interactively. Discovery is complete; use its "
455
469
  "recorded answers and accepted assumptions as settled decisions. "
456
- "Write the complete specification to "
457
- f"`{spec_path}` using the available file tools. If a decision is "
458
- "genuinely missing, do not write the specification: report it as "
459
- "a numbered item in section 7 so DevFlow can return it to "
460
- "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 "
461
479
  "complete document. Then tell the user that the specification is "
462
480
  "written and that they must exit this session so DevFlow can "
463
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,8 +334,10 @@ 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
342
  {{reopened_note}}## Execution Instructions
288
343
 
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.22
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.22`.**
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.22-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.22 |
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,7 +748,7 @@ 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.22`:
751
+ Available commands in `0.3.23`:
700
752
 
701
753
  | Command | Status |
702
754
  | --- | --- |
@@ -929,7 +981,7 @@ devflow approve 001
929
981
  ```
930
982
 
931
983
  Approval is explicit and binds the decision to the current artifact
932
- digests. For a `0.3.22` change it binds `spec.md`, `discovery.yaml` and,
984
+ digests. For a `0.3.23` change it binds `spec.md`, `discovery.yaml` and,
933
985
  when a manifest applies, the architecture manifest digest. Repeating the
934
986
  same approval is a no-op. If an artifact changes after validation,
935
987
  DevFlow marks it stale and refuses approval until it is regenerated and
@@ -940,7 +992,7 @@ and names the pending questions and assumptions. Approval also rejects a
940
992
  specification whose section 7 still lists open questions. Legacy `0.2.0`
941
993
  changes without `discovery.yaml` remain approvable with a warning.
942
994
 
943
- Only the `spec` stage is available in `0.3.22`, so `--stage` is optional
995
+ Only the `spec` stage is available in `0.3.23`, so `--stage` is optional
944
996
  and defaults to `spec`. `--stage plan` and `--stage review` are
945
997
  rejected. There are no `plan`, `implement` or
946
998
  `review` commands in this release.
@@ -20,20 +20,20 @@ devflow/commands/init.py,sha256=G2LDYDElWDSDPk3-1DfRtv8sW_z-9ITJH1Co6C5jiyw,1718
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=8xesusAw3ToCfX7aYsd-q5YnAyXU0DouQzLGoFZebwg,6082
23
+ devflow/commands/status.py,sha256=Lazqr7I8heJHCK-0q3NQxsIORwRzopDwkRgAnbcdnA4,6742
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=oIaC7S3c5zIrhzAz4J9pq6-pZqU1Q9vE0AgWdBDElBc,55994
29
+ devflow/core/discovery.py,sha256=_o321P0puy_kgrs0eMpBNavRYON-UnLGsjEpzvqSwUs,60022
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/spec_workflow.py,sha256=ZYBCZD5Xdiw9GVsVp_M2YYzEeFQsF9IXjFEpOpw6Fzs,40013
36
- 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
37
37
  devflow/core/artifacts/__init__.py,sha256=gt9xahPynoxv75FMq1ZJx91ILTIv4ExuvX1Ymrxwr2c,627
38
38
  devflow/core/artifacts/errors.py,sha256=hwZxnLFcUTtEjDWtN6rUCkM69EN19LGVlc6HD-pNZyk,493
39
39
  devflow/core/artifacts/models.py,sha256=xJjmY8jUAHxqYN9u1JEu8CbJB-IJg1xb9P-LDaP5_Hw,2049
@@ -59,12 +59,12 @@ devflow/profiles/django-backend/profile.yaml,sha256=SNj7a3yamdJx-P69GvIJmLkC2svO
59
59
  devflow/profiles/django-backend/constitution/django-standards.md,sha256=0M-XmxOpEmgIadcaVdf6OVmll8Oec0jEjcJ4C8MfwhQ,2052
60
60
  devflow/profiles/fastapi-backend/profile.yaml,sha256=5_b-zWSX0HV-tw_2ntRCSa4DyP3NUqYWmxOh55pXYmc,321
61
61
  devflow/profiles/fastapi-backend/constitution/fastapi-standards.md,sha256=iFKib4i_9z4wBQ9thl-uftg5g-CHwvmFWzMtLgA7CBk,1949
62
- devflow/prompts/__init__.py,sha256=dxPxXzY5qECes_c1RuoIfIGKcdkCwg1RLGAolled1o8,17454
62
+ devflow/prompts/__init__.py,sha256=umS5zRYLk0yU3oV3ZnFsMKYaFfWBjxLG8FCmSibKjYw,18134
63
63
  devflow/prompts/discovery-repair.md,sha256=YfTfrrw5uUZvC_x6X2lrYEDkMNhanhoe0ER3Yc2-rgI,1135
64
- devflow/prompts/discovery.md,sha256=9ON-NvkXTSZWwia12NqY6TU9Z9yc68oqhpiFURAHSoU,11557
65
- devflow/prompts/spec.md,sha256=ZbZXS_76mWqihqRD4BeHpCc62Rbqoeb-F9XmkKL3_ww,7153
66
- devflow_toolkit-0.3.22.dist-info/METADATA,sha256=cgK-ggOfjyYPqgHKSZg6N6X0cxZkcfZCH_xFVd9PJkI,46584
67
- devflow_toolkit-0.3.22.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
68
- devflow_toolkit-0.3.22.dist-info/entry_points.txt,sha256=wPmqE1081vi8s3xf-Wfzfvpl-44IKgwx7OGoLEK3u7o,44
69
- devflow_toolkit-0.3.22.dist-info/licenses/LICENSE,sha256=Wa04lstC8Goe4b9IYfEYWB2k7nokYBejZl6NdyAl8rA,1077
70
- devflow_toolkit-0.3.22.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,,