devflow-toolkit 0.4.4__py3-none-any.whl → 0.4.6__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.
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import json
6
+ import uuid
6
7
  import shlex
7
8
  import sys
8
9
 
@@ -66,6 +67,10 @@ class ClaudeCodeAdapter(HarnessAdapter):
66
67
  "manual" if context.mode == "interactive" else "dontAsk"
67
68
  )
68
69
  model = ("--model", context.model) if context.model else ()
70
+ session: tuple[str, ...] = ()
71
+ if context.session_id:
72
+ flag = "--resume" if context.resume_session else "--session-id"
73
+ session = (flag, context.session_id)
69
74
  # Load only the user's own settings and no MCP servers: hooks,
70
75
  # permissions and MCP servers committed in the project's .claude/ or
71
76
  # .mcp.json must not run with DevFlow's agent session.
@@ -75,6 +80,7 @@ class ClaudeCodeAdapter(HarnessAdapter):
75
80
  argv = (
76
81
  self.executable,
77
82
  *model,
83
+ *session,
78
84
  *isolation,
79
85
  "--permission-mode",
80
86
  permission_mode,
@@ -91,6 +97,7 @@ class ClaudeCodeAdapter(HarnessAdapter):
91
97
  self.executable,
92
98
  "-p",
93
99
  *model,
100
+ *session,
94
101
  *isolation,
95
102
  "--output-format",
96
103
  "text",
@@ -104,6 +111,10 @@ class ClaudeCodeAdapter(HarnessAdapter):
104
111
  )
105
112
  return Invocation(argv=argv, cwd=root, interactive=False)
106
113
 
114
+ def new_session_id(self) -> str:
115
+ """Claude Code accepts a UUID chosen by the caller (--session-id)."""
116
+ return str(uuid.uuid4())
117
+
107
118
  def permission_warnings(
108
119
  self,
109
120
  context: RunContext,
@@ -3,6 +3,8 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import os
6
+ import secrets
7
+ import string
6
8
  import subprocess
7
9
  import tempfile
8
10
 
@@ -126,11 +128,14 @@ class OpenCodeAdapter(HarnessAdapter):
126
128
  def build_run(self, context: RunContext) -> Invocation:
127
129
  root = context.root
128
130
  model = ("--model", context.model) if context.model else ()
131
+ # `--session` continues the session, or creates it with this id.
132
+ session = ("--session", context.session_id) if context.session_id else ()
129
133
  if context.mode == "interactive":
130
134
  argv = (
131
135
  self.executable,
132
136
  "mini",
133
137
  *model,
138
+ *session,
134
139
  "--agent",
135
140
  INTERACTIVE_AGENT,
136
141
  "--prompt",
@@ -147,12 +152,22 @@ class OpenCodeAdapter(HarnessAdapter):
147
152
  self.executable,
148
153
  "run",
149
154
  *model,
155
+ *session,
150
156
  "--agent",
151
157
  agent,
152
158
  context.prompt,
153
159
  )
154
160
  return Invocation(argv=argv, cwd=root, interactive=False)
155
161
 
162
+ def new_session_id(self) -> str:
163
+ """Return an id in OpenCode's format: ``ses_`` + 12 hex + 14 base62."""
164
+ alphabet = string.ascii_letters + string.digits
165
+ return (
166
+ "ses_"
167
+ + secrets.token_hex(6)
168
+ + "".join(secrets.choice(alphabet) for _ in range(14))
169
+ )
170
+
156
171
  def list_models(self) -> tuple[ModelOption, ...]:
157
172
  """Return models reported by ``opencode models``."""
158
173
  if not self.is_available():
@@ -25,8 +25,17 @@ from devflow.core.constitution import (
25
25
  ConstitutionError,
26
26
  ConstitutionLoader,
27
27
  )
28
+ from devflow.core.model_tiers import (
29
+ RECOMMENDATION_TEXT,
30
+ TIER_LARGE,
31
+ TIER_MEDIUM,
32
+ TIER_SMALL,
33
+ model_tier,
34
+ tier_label,
35
+ )
28
36
  from devflow.core.ports import (
29
37
  HarnessPort,
38
+ ModelOption,
30
39
  SetupResult,
31
40
  build_setup_context,
32
41
  )
@@ -57,13 +66,12 @@ def prompt_for_model(adapter: HarnessPort) -> str | None:
57
66
  )
58
67
  return answer.strip() or None
59
68
 
69
+ models = _by_recommendation(models)
60
70
  typer.echo(f"Models available for {adapter.display_name}:")
61
71
  typer.echo(" 0. Use the harness default")
62
72
  for index, model in enumerate(models, start=1):
63
- label = ""
64
- if model.label and model.label != model.id:
65
- label = f" — {model.label}"
66
- typer.echo(f" {index}. {model.id}{label}")
73
+ typer.echo(f" {index}. {_model_line(model)}")
74
+ typer.echo(RECOMMENDATION_TEXT)
67
75
  while True:
68
76
  answer = typer.prompt("Model number or id", default="0")
69
77
  value = answer.strip()
@@ -78,6 +86,22 @@ def prompt_for_model(adapter: HarnessPort) -> str | None:
78
86
  typer.echo("Choose a listed number or type a model id.")
79
87
 
80
88
 
89
+ def _by_recommendation(models: tuple[ModelOption, ...]) -> list[ModelOption]:
90
+ """Put the models recommended for specs first, keeping their order."""
91
+ order = {TIER_MEDIUM: 0, TIER_LARGE: 1, None: 2, TIER_SMALL: 3}
92
+ return sorted(models, key=lambda item: order[model_tier(item.id)])
93
+
94
+
95
+ def _model_line(model: ModelOption) -> str:
96
+ label = ""
97
+ if model.label and model.label != model.id:
98
+ label = f" — {model.label}"
99
+ recommendation = tier_label(model.id)
100
+ if recommendation:
101
+ label += f" [{recommendation}]"
102
+ return f"{model.id}{label}"
103
+
104
+
81
105
  def validate_harness_name(value: str) -> str:
82
106
  """Validate and normalize a harness name from the CLI."""
83
107
  canonical = canonical_harness_name(value)
@@ -278,9 +302,9 @@ def models(
278
302
  "Use --model with a model id supported by the harness."
279
303
  )
280
304
  return
281
- for option in options:
282
- label = f" — {option.label}" if option.label else ""
283
- console.print(f"- {option.id}{label}")
305
+ for option in _by_recommendation(options):
306
+ console.print(escape(f"- {_model_line(option)}"), soft_wrap=True)
307
+ console.print(RECOMMENDATION_TEXT)
284
308
 
285
309
 
286
310
  @harness_app.command("use")
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from pathlib import Path
6
+ from typing import Optional
6
7
 
7
8
  import typer
8
9
  from rich.console import Console
@@ -34,7 +35,18 @@ def reopen(
34
35
  discovery: bool = typer.Option(
35
36
  False,
36
37
  "--discovery",
37
- help="Also reopen Discovery to add or change decisions.",
38
+ help=(
39
+ "Reopen Discovery so the agent asks about new or changed "
40
+ "decisions. Works on approved and not-yet-approved changes."
41
+ ),
42
+ ),
43
+ add: Optional[str] = typer.Option(
44
+ None,
45
+ "--add",
46
+ help=(
47
+ "What to add or change, for example \"password recovery by "
48
+ "email\". Implies --discovery."
49
+ ),
38
50
  ),
39
51
  yes: bool = typer.Option(
40
52
  False,
@@ -43,9 +55,9 @@ def reopen(
43
55
  help="Do not ask for confirmation.",
44
56
  ),
45
57
  ) -> None:
46
- """Reopen an approved specification so it can be changed."""
58
+ """Reopen a specification to change or extend it."""
47
59
  try:
48
- _reopen(spec_id, path, discovery=discovery, yes=yes)
60
+ _reopen(spec_id, path, discovery=discovery, add=add or "", yes=yes)
49
61
  except (
50
62
  ArtifactError,
51
63
  ConfigError,
@@ -59,48 +71,73 @@ def reopen(
59
71
  raise typer.Exit(code=1) from error
60
72
 
61
73
 
62
- def _reopen(spec_id: str, path: Path, *, discovery: bool, yes: bool) -> None:
74
+ def _reopen(
75
+ spec_id: str,
76
+ path: Path,
77
+ *,
78
+ discovery: bool,
79
+ add: str,
80
+ yes: bool,
81
+ ) -> None:
63
82
  root = ProjectDetector().find_root(path)
64
83
  config = ConfigManager(root).load()
65
84
  location = WorkflowLocator(config.specifications_path).find(spec_id)
66
-
67
- if not yes and not typer.confirm(
68
- f"Reopen the approved specification {location.change}?",
69
- default=False,
70
- ):
71
- console.print("Cancelled. Nothing was changed.")
72
- raise typer.Exit(code=1)
73
-
74
85
  manager = WorkflowStateManager(
75
86
  config.specifications_path,
76
87
  project_root=config.root,
77
88
  )
78
- result = manager.reopen(location, discovery=discovery)
89
+ discovery = discovery or bool(add.strip())
90
+ approved = "spec" in manager.load(location).approvals
79
91
 
80
- console.print(
81
- f"[bold green]Reopened {location.change}.[/bold green] "
82
- "The spec approval was withdrawn."
83
- )
92
+ if approved:
93
+ question = (
94
+ f"Withdraw the approval of {location.change} so it can be changed?"
95
+ )
96
+ elif discovery:
97
+ question = (
98
+ f"Reopen Discovery of {location.change} to add or change decisions?"
99
+ )
100
+ else:
101
+ question = ""
102
+ if question and not yes and not typer.confirm(question, default=False):
103
+ console.print("Cancelled. Nothing was changed.")
104
+ raise typer.Exit(code=1)
105
+
106
+ result = manager.reopen(location, discovery=discovery, addition=add)
107
+
108
+ if result.approval_withdrawn:
109
+ console.print(
110
+ f"[bold green]Reopened {location.change}.[/bold green] "
111
+ "The spec approval was withdrawn."
112
+ )
113
+ else:
114
+ console.print(
115
+ f"[bold green]Reopened Discovery of {location.change}."
116
+ "[/bold green]"
117
+ )
84
118
  if result.archived is not None:
85
119
  console.print(
86
120
  "Approved spec archived: "
87
121
  f"{manager.store.display_path(result.archived)}"
88
122
  )
123
+ if add.strip():
124
+ console.print(f"Recorded what to add: {escape(add.strip())}")
89
125
  console.print(f"Workflow status: {result.state.status}")
90
126
 
91
127
  continue_command = f"devflow spec --continue {location.spec_id}"
92
128
  if discovery:
93
129
  console.print(
94
130
  f"\n[bold]Next:[/bold] {continue_command}\n"
95
- "[dim]Tell the agent what to add or change. Then run the same "
96
- "command again to write the new spec, and approve it with "
97
- f"devflow approve {location.spec_id}.[/dim]"
131
+ "[dim]The agent asks you about the new decisions (interactive "
132
+ "mode). Run the same command again to write the extended spec, "
133
+ f"then approve it with devflow approve {location.spec_id}.[/dim]"
98
134
  )
99
135
  else:
100
136
  console.print(
101
- "\n[bold]Next:[/bold] edit spec.md, then "
137
+ "\n[bold]Next:[/bold] edit spec.md yourself, then "
102
138
  f"{continue_command}\n"
103
- "[dim]DevFlow validates and registers your edited spec. Approve "
104
- f"it again with devflow approve {location.spec_id}. To change "
105
- "decisions instead, use devflow reopen with --discovery.[/dim]"
139
+ "[dim]DevFlow validates and registers your edited spec; approve it "
140
+ f"again with devflow approve {location.spec_id}. To have the agent "
141
+ f"extend it instead, run devflow reopen {location.spec_id} --add "
142
+ '"what to add".[/dim]'
106
143
  )
devflow/commands/spec.py CHANGED
@@ -5,7 +5,7 @@ from __future__ import annotations
5
5
  import sys
6
6
  from dataclasses import replace
7
7
  from pathlib import Path
8
- from typing import Optional
8
+ from typing import List, Optional
9
9
 
10
10
  import typer
11
11
  from rich.console import Console
@@ -115,6 +115,15 @@ def spec(
115
115
  "changing the configuration."
116
116
  ),
117
117
  ),
118
+ scope: Optional[List[str]] = typer.Option(
119
+ None,
120
+ "--scope",
121
+ help=(
122
+ "Directory or file where the change happens, for example "
123
+ "apps/accounts. Repeat it for several places. The analysis and "
124
+ "the agent stay inside it. Only for a new change."
125
+ ),
126
+ ),
118
127
  allow_source_changes: bool = typer.Option(
119
128
  False,
120
129
  "--allow-source-changes",
@@ -148,6 +157,7 @@ def spec(
148
157
  model,
149
158
  auto,
150
159
  allow_source_changes,
160
+ tuple(scope or ()),
151
161
  )
152
162
  except (
153
163
  ArchitectureError,
@@ -178,6 +188,7 @@ def _create_specification(
178
188
  model: Optional[str] = None,
179
189
  auto: bool = False,
180
190
  allow_source_changes: bool = False,
191
+ scope: tuple[str, ...] = (),
181
192
  ) -> None:
182
193
  request = (description or "").strip()
183
194
  resume = (continue_id or "").strip() or None
@@ -281,6 +292,7 @@ def _create_specification(
281
292
  language=documentation_language,
282
293
  model=effective_model,
283
294
  stop_after_discovery=stop_after_discovery,
295
+ scope=scope,
284
296
  )
285
297
  )
286
298
 
@@ -345,6 +357,13 @@ def _create_specification(
345
357
  f"{result.spec.path.relative_to(config.root)}",
346
358
  soft_wrap=True,
347
359
  )
360
+ spec_id = result.spec.spec_id
361
+ console.print(
362
+ "[dim]To have the agent extend or change it, run "
363
+ f'devflow reopen {spec_id} --add "what to add" and then '
364
+ f"devflow spec --continue {spec_id}. To approve it as it is, run "
365
+ f"devflow approve {spec_id}.[/dim]"
366
+ )
348
367
  else:
349
368
  _print_result(result=result, config=config)
350
369
 
devflow/core/discovery.py CHANGED
@@ -84,6 +84,7 @@ RESOLUTION_SOURCES = (
84
84
  )
85
85
 
86
86
  QUESTION_CATEGORIES = (
87
+ "code_location",
87
88
  "functional_scope",
88
89
  "user_behavior",
89
90
  "data_persistence",
@@ -95,6 +96,7 @@ QUESTION_CATEGORIES = (
95
96
  )
96
97
 
97
98
  _CATEGORY_MATERIALITY = {
99
+ "code_location": MATERIALITY_FUNCTIONAL,
98
100
  "functional_scope": MATERIALITY_FUNCTIONAL,
99
101
  "user_behavior": MATERIALITY_FUNCTIONAL,
100
102
  "data_persistence": MATERIALITY_FUNCTIONAL,
@@ -109,6 +111,9 @@ _CATEGORY_MATERIALITY = {
109
111
  # Unknown categories fall back to functional_scope; the materiality the
110
112
  # agent wrote is kept, so a critical decision stays critical.
111
113
  _CATEGORY_ALIASES = {
114
+ "location": "code_location",
115
+ "module": "code_location",
116
+ "placement": "code_location",
112
117
  "api": "functional_scope",
113
118
  "api_contract": "functional_scope",
114
119
  "api_design": "functional_scope",
@@ -518,6 +523,25 @@ _PLANNER_SIGNAL_WORDS = (
518
523
  # will be able to do. Matching only this vocabulary is not enough evidence
519
524
  # that the planner understood the feature, so it must still ask for scope.
520
525
  _WEAK_SIGNAL_WORDS = _DATA_WORDS | _VAGUE_TERMS
526
+
527
+ # From this many source files, a request that names no module gets a
528
+ # question about where the change happens.
529
+ LARGE_PROJECT_FILES = 150
530
+
531
+
532
+ def _names_a_project_path(request: str, project: Project) -> bool:
533
+ """Return whether the request names an existing directory or file."""
534
+ for candidate in re.findall(r"[\w.\-]+(?:/[\w.\-]+)+|[\w\-]+\.\w{1,5}", request):
535
+ path = candidate.strip("./")
536
+ if path and (project.root / path).exists():
537
+ return True
538
+ names = {
539
+ part
540
+ for source in project.source_files
541
+ for part in Path(source).parts[:-1]
542
+ }
543
+ words = set(re.findall(r"[\w\-]{3,}", request.lower()))
544
+ return bool(words & {name.lower() for name in names})
521
545
  _STRONG_SIGNAL_WORDS = _PLANNER_SIGNAL_WORDS - _WEAK_SIGNAL_WORDS
522
546
 
523
547
 
@@ -766,6 +790,9 @@ class DiscoveryDocument:
766
790
  assumptions: tuple[DiscoveryAssumption, ...] = ()
767
791
  deferred: tuple[DeferredItem, ...] = ()
768
792
  accepted_risks: tuple[AcceptedRisk, ...] = ()
793
+ # Project-relative directories or files where the change happens.
794
+ # Analysis and agent reads stay inside them.
795
+ scope: tuple[str, ...] = ()
769
796
  # Minor problems DevFlow corrected while reading the record. They are
770
797
  # reported to the user and never written back by themselves.
771
798
  notes: tuple[str, ...] = ()
@@ -940,6 +967,7 @@ class DiscoveryDocument:
940
967
  "status": self.status,
941
968
  "created_at": self.created_at,
942
969
  "updated_at": self.updated_at,
970
+ **({"scope": list(self.scope)} if self.scope else {}),
943
971
  "questions": [
944
972
  question.to_dict() for question in self.questions
945
973
  ],
@@ -1353,6 +1381,11 @@ class DiscoveryManager:
1353
1381
  msg = "Accepted risk ids must be unique."
1354
1382
  raise DiscoveryError(msg)
1355
1383
 
1384
+ scope = tuple(
1385
+ _scope_path(item)
1386
+ for item in _list(mapping.get("scope"), "scope")
1387
+ )
1388
+
1356
1389
  document = DiscoveryDocument(
1357
1390
  version=version,
1358
1391
  spec_id=spec_id,
@@ -1366,6 +1399,7 @@ class DiscoveryManager:
1366
1399
  assumptions=assumptions,
1367
1400
  deferred=deferred,
1368
1401
  accepted_risks=accepted_risks,
1402
+ scope=scope,
1369
1403
  notes=tuple(notes),
1370
1404
  )
1371
1405
  return document
@@ -1742,6 +1776,8 @@ class DiscoveryPlanner:
1742
1776
  architecture: ArchitectureManifest | None,
1743
1777
  now: str,
1744
1778
  require_question: bool = False,
1779
+ scope: tuple[str, ...] = (),
1780
+ reference_scores: dict[str, int] | None = None,
1745
1781
  ) -> DiscoveryDocument:
1746
1782
  """Return a deterministic discovery record for a request.
1747
1783
 
@@ -1785,6 +1821,35 @@ class DiscoveryPlanner:
1785
1821
  for word in words
1786
1822
  if len(word) >= 3 and word not in _STOPWORDS
1787
1823
  ]
1824
+
1825
+ if (
1826
+ project_mode == "existing"
1827
+ and not scope
1828
+ and len(project.source_files) >= LARGE_PROJECT_FILES
1829
+ and not _names_a_project_path(request, project)
1830
+ ):
1831
+ areas = location_options(
1832
+ reference_paths,
1833
+ scores=reference_scores,
1834
+ )
1835
+ if not areas or len(areas) > 1:
1836
+ options = tuple(
1837
+ f"`{directory}/` ({count} matching file{'s' if count != 1 else ''})"
1838
+ if directory != "."
1839
+ else f"Project root ({count} matching file{'s' if count != 1 else ''})"
1840
+ for directory, count in areas
1841
+ ) + (
1842
+ "Other: name the module, file, class or function.",
1843
+ )
1844
+ add_question(
1845
+ "code_location",
1846
+ "Where in the code should this change happen?",
1847
+ "The project is large and the request does not point to a "
1848
+ "module, so the agent would have to explore broadly. Naming "
1849
+ "the place keeps the analysis precise and cheaper.",
1850
+ options,
1851
+ )
1852
+
1788
1853
  if len(keywords) < 2:
1789
1854
  add_question(
1790
1855
  "functional_scope",
@@ -2205,6 +2270,7 @@ class DiscoveryPlanner:
2205
2270
  version=1,
2206
2271
  spec_id=spec_id,
2207
2272
  change=change,
2273
+ scope=tuple(scope),
2208
2274
  request=request.strip(),
2209
2275
  project_mode=project_mode,
2210
2276
  status=(
@@ -2333,6 +2399,97 @@ def _mapping(value: object, field: str) -> dict[str, Any]:
2333
2399
  return value
2334
2400
 
2335
2401
 
2402
+ MAX_SCOPE_ENTRIES = 10
2403
+ _LOCATION_PATH = re.compile(r"`([^`]+)`|([\w.\-]+/[\w./\-]*)")
2404
+
2405
+
2406
+ def normalize_scope_path(value: str) -> str:
2407
+ """Return a clean project-relative path, or raise ValueError."""
2408
+ text = value.strip().strip("`").replace("\\", "/")
2409
+ while text.startswith("./"):
2410
+ text = text[2:]
2411
+ text = text.rstrip("/")
2412
+ parts = text.split("/") if text else []
2413
+ if (
2414
+ not parts
2415
+ or text.startswith("/")
2416
+ or any(part in {"", ".", ".."} for part in parts)
2417
+ or "\x00" in text
2418
+ ):
2419
+ msg = f"Scope must be a path inside the project: {value!r}"
2420
+ raise ValueError(msg)
2421
+ return "/".join(parts)
2422
+
2423
+
2424
+ def _scope_path(value: object) -> str:
2425
+ if not isinstance(value, str):
2426
+ msg = "scope entries must be strings."
2427
+ raise DiscoveryError(msg)
2428
+ try:
2429
+ return normalize_scope_path(value)
2430
+ except ValueError as error:
2431
+ raise DiscoveryError(str(error)) from error
2432
+
2433
+
2434
+ def change_scope(
2435
+ document: DiscoveryDocument | None,
2436
+ root: Path,
2437
+ ) -> tuple[str, ...]:
2438
+ """Return the code scope of a change.
2439
+
2440
+ An explicit ``scope`` wins. Otherwise a resolved ``code_location``
2441
+ question supplies it when its answer names an existing project path,
2442
+ for example the option "`apps/accounts/` (12 matches)".
2443
+ """
2444
+ if document is None:
2445
+ return ()
2446
+ if document.scope:
2447
+ return document.scope[:MAX_SCOPE_ENTRIES]
2448
+ resolved_root = root.resolve()
2449
+ found: list[str] = []
2450
+ for question in document.questions:
2451
+ if question.category != "code_location" or not question.is_resolved:
2452
+ continue
2453
+ for backticked, bare in _LOCATION_PATH.findall(question.answer or ""):
2454
+ candidate = backticked or bare
2455
+ try:
2456
+ relative = normalize_scope_path(candidate)
2457
+ except ValueError:
2458
+ continue
2459
+ target = (resolved_root / relative).resolve()
2460
+ if (
2461
+ target.is_relative_to(resolved_root)
2462
+ and target.exists()
2463
+ and relative not in found
2464
+ ):
2465
+ found.append(relative)
2466
+ return tuple(found[:MAX_SCOPE_ENTRIES])
2467
+
2468
+
2469
+ def location_options(
2470
+ reference_paths: tuple[str, ...],
2471
+ limit: int = 3,
2472
+ scores: dict[str, int] | None = None,
2473
+ ) -> tuple[tuple[str, int], ...]:
2474
+ """Group matched files by directory, strongest evidence first.
2475
+
2476
+ Directories are ranked by their best-matching file, then by the number
2477
+ of matching files, so one precise match beats many weak ones.
2478
+ """
2479
+ scores = scores or {}
2480
+ counts: dict[str, int] = {}
2481
+ best: dict[str, int] = {}
2482
+ for path in reference_paths:
2483
+ directory = path.rsplit("/", maxsplit=1)[0] if "/" in path else "."
2484
+ counts[directory] = counts.get(directory, 0) + 1
2485
+ best[directory] = max(best.get(directory, 0), scores.get(path, 0))
2486
+ ranked = sorted(
2487
+ counts.items(),
2488
+ key=lambda item: (-best[item[0]], -item[1], item[0]),
2489
+ )
2490
+ return tuple(ranked[:limit])
2491
+
2492
+
2336
2493
  def _list(value: object, field: str) -> list[Any]:
2337
2494
  if value is None:
2338
2495
  return []
@@ -0,0 +1,62 @@
1
+ """Classify harness models to recommend one per workflow phase.
2
+
3
+ Discovery and specification need judgment, but DevFlow already provides
4
+ the stack, the code evidence, the ASVS baseline and the validation, so a
5
+ mid-range model is enough. Implementation benefits from the most capable
6
+ model. Very small models ask poor questions and miss decisions.
7
+
8
+ The classification is a name heuristic. Unknown names get no tier.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+
15
+ TIER_SMALL = "small"
16
+ TIER_MEDIUM = "medium"
17
+ TIER_LARGE = "large"
18
+
19
+ TIER_LABELS = {
20
+ TIER_MEDIUM: "mid-range · recommended for Discovery and specs",
21
+ TIER_LARGE: "most capable · best for implementation",
22
+ TIER_SMALL: "small · not recommended",
23
+ }
24
+
25
+ _SMALL = re.compile(
26
+ r"(nano|haiku|flash[-_.]?lite|\blite\b|tiny|\bsmall\b|"
27
+ r"(?<![0-9])[0-9](\.[0-9])?b\b|(?<![0-9])(1[0-4])b\b)"
28
+ )
29
+ _MEDIUM = re.compile(
30
+ r"(sonnet|(?<![a-z])mini|flash|medium|\bgpt-4o\b|(?<![0-9])(2[0-9]|3[0-4])b\b)"
31
+ )
32
+ _LARGE = re.compile(
33
+ r"(opus|[-_.]pro\b|\bpro[-_.]|ultra|large|\bo[1-9]\b|"
34
+ r"gpt-[5-9]|gpt-4\.[1-9]|codex|r1\b|(?<![0-9])([4-9][0-9]|[1-9][0-9]{2})b\b)"
35
+ )
36
+
37
+
38
+ def model_tier(model_id: str) -> str | None:
39
+ """Return the tier suggested by a model id, or None when unknown."""
40
+ name = model_id.lower().rsplit("/", maxsplit=1)[-1]
41
+ if _SMALL.search(name):
42
+ return TIER_SMALL
43
+ if _MEDIUM.search(name):
44
+ return TIER_MEDIUM
45
+ if _LARGE.search(name):
46
+ return TIER_LARGE
47
+ return None
48
+
49
+
50
+ def tier_label(model_id: str) -> str:
51
+ """Return the recommendation shown next to a model, or ''."""
52
+ tier = model_tier(model_id)
53
+ return TIER_LABELS.get(tier, "") if tier else ""
54
+
55
+
56
+ RECOMMENDATION_TEXT = (
57
+ "Recommendation: a mid-range model is enough for Discovery and the "
58
+ "specification, because DevFlow already supplies the stack, the code "
59
+ "evidence and the security baseline and validates the result. Keep "
60
+ "the most capable model for implementation. Avoid very small models: "
61
+ "they ask poor questions and miss decisions."
62
+ )
devflow/core/ports.py CHANGED
@@ -60,6 +60,9 @@ class RunContext:
60
60
  permissions: AgentPermissions
61
61
  output_path: Path | None = None
62
62
  model: str | None = None
63
+ # Harness session to create (resume_session False) or to resume.
64
+ session_id: str | None = None
65
+ resume_session: bool = False
63
66
 
64
67
 
65
68
  @dataclass(frozen=True)
@@ -133,6 +136,13 @@ class HarnessPort(ABC):
133
136
  # a file at these paths that DevFlow did not write.
134
137
  agent_definition_files: tuple[str, ...] = ()
135
138
 
139
+ def new_session_id(self) -> str | None:
140
+ """Return a fresh session id when the harness accepts a chosen one.
141
+
142
+ Harnesses that return None always start a new session.
143
+ """
144
+ return None
145
+
136
146
  @abstractmethod
137
147
  def is_available(self) -> bool:
138
148
  """Return whether the harness executable is available."""