devflow-toolkit 0.4.5__py3-none-any.whl → 0.4.7__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")
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
@@ -15,6 +15,7 @@ from devflow.adapters.base import execute_invocation
15
15
  from devflow.commands.harness import (
16
16
  adapter_for,
17
17
  print_setup_result,
18
+ prompt_for_model,
18
19
  resolve_harness,
19
20
  validate_harness_name,
20
21
  )
@@ -115,6 +116,15 @@ def spec(
115
116
  "changing the configuration."
116
117
  ),
117
118
  ),
119
+ scope: Optional[List[str]] = typer.Option(
120
+ None,
121
+ "--scope",
122
+ help=(
123
+ "Directory or file where the change happens, for example "
124
+ "apps/accounts. Repeat it for several places. The analysis and "
125
+ "the agent stay inside it. Only for a new change."
126
+ ),
127
+ ),
118
128
  allow_source_changes: bool = typer.Option(
119
129
  False,
120
130
  "--allow-source-changes",
@@ -148,6 +158,7 @@ def spec(
148
158
  model,
149
159
  auto,
150
160
  allow_source_changes,
161
+ tuple(scope or ()),
151
162
  )
152
163
  except (
153
164
  ArchitectureError,
@@ -178,6 +189,7 @@ def _create_specification(
178
189
  model: Optional[str] = None,
179
190
  auto: bool = False,
180
191
  allow_source_changes: bool = False,
192
+ scope: tuple[str, ...] = (),
181
193
  ) -> None:
182
194
  request = (description or "").strip()
183
195
  resume = (continue_id or "").strip() or None
@@ -241,8 +253,6 @@ def _create_specification(
241
253
  config = ConfigManager(root).set_documentation_language(
242
254
  documentation_language
243
255
  )
244
- effective_model = (model or config.model or "").strip() or None
245
-
246
256
  allow_prompt = sys.stdin.isatty()
247
257
  selected_harness, selection_warnings = resolve_harness(
248
258
  requested_harness,
@@ -251,6 +261,14 @@ def _create_specification(
251
261
  force_prompt=not explicit_harness,
252
262
  )
253
263
  adapter = adapter_for(selected_harness) if selected_harness else None
264
+ effective_model = _model_for_run(
265
+ model,
266
+ config,
267
+ selected_harness,
268
+ adapter,
269
+ allow_prompt=allow_prompt,
270
+ warnings=selection_warnings,
271
+ )
254
272
  if adapter is not None:
255
273
  config = _confirm_source_changes(
256
274
  config,
@@ -281,6 +299,7 @@ def _create_specification(
281
299
  language=documentation_language,
282
300
  model=effective_model,
283
301
  stop_after_discovery=stop_after_discovery,
302
+ scope=scope,
284
303
  )
285
304
  )
286
305
 
@@ -543,6 +562,44 @@ def _execution_mode(mode: str) -> tuple[str, list[str]]:
543
562
  return normalized, warnings
544
563
 
545
564
 
565
+ def _model_for_run(
566
+ model: str | None,
567
+ config: DevFlowConfig,
568
+ harness: str | None,
569
+ adapter,
570
+ *,
571
+ allow_prompt: bool,
572
+ warnings: list[str],
573
+ ) -> str | None:
574
+ """Return the model for this run.
575
+
576
+ The configured model belongs to the configured harness: model ids are
577
+ harness-specific, so another harness never receives it. When the run
578
+ uses a different harness, the user picks its model or its default is
579
+ used.
580
+ """
581
+ explicit = (model or "").strip()
582
+ if explicit:
583
+ return explicit
584
+ configured = config.model.strip()
585
+ if not configured or harness == config.agent_harness:
586
+ return configured or None
587
+ if adapter is not None and allow_prompt:
588
+ console.print(
589
+ f"The configured model {escape(configured)} belongs to "
590
+ f"{escape(config.agent_harness)}; choose one for "
591
+ f"{escape(adapter.display_name)}."
592
+ )
593
+ return prompt_for_model(adapter)
594
+ warnings.append(
595
+ f"The configured model '{configured}' belongs to "
596
+ f"{config.agent_harness}, so {harness} uses its default model. Pass "
597
+ "--model to choose one, or run 'devflow harness use "
598
+ f"{harness}' to make it the configured harness."
599
+ )
600
+ return None
601
+
602
+
546
603
  def _confirm_source_changes(
547
604
  config: DevFlowConfig,
548
605
  harness_name: str,
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."""
@@ -0,0 +1,66 @@
1
+ """Harness sessions shared by the Discovery and specification runs.
2
+
3
+ When both phases of a change use the same harness, the specification run
4
+ resumes the Discovery session: the agent keeps what it already read and
5
+ the provider can reuse its prompt cache, instead of starting from zero.
6
+
7
+ The record lives in ``.devflow/.local/sessions.json``, outside the specs
8
+ tree that agents may write. The folder ignores itself in git, because
9
+ sessions only exist on this machine.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import re
16
+ from pathlib import Path
17
+
18
+ from devflow.core.artifacts.errors import ArtifactError
19
+ from devflow.core.artifacts.store import ArtifactStore
20
+
21
+ LOCAL_RELATIVE_PATH = Path(".devflow") / ".local"
22
+ SESSIONS_RELATIVE_PATH = LOCAL_RELATIVE_PATH / "sessions.json"
23
+ _CHANGE = re.compile(r"^\d{3}-[\w.-]+$")
24
+ _SESSION_ID = re.compile(r"^[A-Za-z0-9_-]{8,128}$")
25
+
26
+
27
+ class SessionStore:
28
+ """Remember the harness session of each change."""
29
+
30
+ def __init__(self, root: Path) -> None:
31
+ self.root = root.resolve()
32
+ self.path = self.root / SESSIONS_RELATIVE_PATH
33
+ self.store = ArtifactStore(self.root)
34
+
35
+ def get(self, change: str, harness: str) -> str | None:
36
+ """Return the session of a change when it was made by ``harness``."""
37
+ entry = self._read().get(change)
38
+ if not isinstance(entry, dict) or entry.get("harness") != harness:
39
+ return None
40
+ session = entry.get("session")
41
+ if isinstance(session, str) and _SESSION_ID.match(session):
42
+ return session
43
+ return None
44
+
45
+ def set(self, change: str, harness: str, session: str) -> None:
46
+ """Record the session a harness used for a change."""
47
+ if not _CHANGE.match(change) or not _SESSION_ID.match(session):
48
+ return
49
+ data = self._read()
50
+ data[change] = {"harness": harness, "session": session}
51
+ try:
52
+ ignore = self.root / LOCAL_RELATIVE_PATH / ".gitignore"
53
+ if not ignore.exists():
54
+ self.store.write(ignore, "*\n")
55
+ self.store.write(self.path, json.dumps(data, indent=2, sort_keys=True))
56
+ except (ArtifactError, OSError):
57
+ return
58
+
59
+ def _read(self) -> dict[str, object]:
60
+ if self.path.is_symlink() or not self.path.is_file():
61
+ return {}
62
+ try:
63
+ data = json.loads(self.path.read_text(encoding="utf-8"))
64
+ except (OSError, ValueError):
65
+ return {}
66
+ return data if isinstance(data, dict) else {}