@michaelxwb/code-flow 0.6.2 → 0.6.4

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.
Files changed (74) hide show
  1. package/README.md +2 -2
  2. package/package.json +1 -1
  3. package/src/adapters/claude/commands/cf-init.md +1 -0
  4. package/src/adapters/claude/commands/cf-spec.md +7 -3
  5. package/src/adapters/claude/commands/cf-task/archive.md +5 -5
  6. package/src/adapters/claude/commands/cf-task/block.md +15 -9
  7. package/src/adapters/claude/commands/cf-task/graph.md +8 -1
  8. package/src/adapters/claude/commands/cf-task/note.md +1 -4
  9. package/src/adapters/claude/commands/cf-task/plan.md +2 -2
  10. package/src/adapters/claude/commands/cf-task/start.md +96 -25
  11. package/src/adapters/claude/commands/cf-task/verify-e2e.md +8 -9
  12. package/src/adapters/claude/commands/cf-validate.md +15 -13
  13. package/src/adapters/codex/skills/cf-init/SKILL.md +1 -0
  14. package/src/adapters/codex/skills/cf-spec/SKILL.md +6 -2
  15. package/src/adapters/codex/skills/cf-task-archive/SKILL.md +5 -5
  16. package/src/adapters/codex/skills/cf-task-block/SKILL.md +15 -9
  17. package/src/adapters/codex/skills/cf-task-graph/SKILL.md +8 -1
  18. package/src/adapters/codex/skills/cf-task-note/SKILL.md +1 -4
  19. package/src/adapters/codex/skills/cf-task-plan/SKILL.md +2 -2
  20. package/src/adapters/codex/skills/cf-task-start/SKILL.md +96 -25
  21. package/src/adapters/codex/skills/cf-task-verify-e2e/SKILL.md +106 -0
  22. package/src/adapters/codex/skills/cf-validate/SKILL.md +15 -13
  23. package/src/adapters/costrict/commands/cf-init.md +1 -0
  24. package/src/adapters/costrict/commands/cf-spec.md +7 -3
  25. package/src/adapters/costrict/commands/cf-task/archive.md +5 -5
  26. package/src/adapters/costrict/commands/cf-task/block.md +15 -9
  27. package/src/adapters/costrict/commands/cf-task/graph.md +8 -1
  28. package/src/adapters/costrict/commands/cf-task/note.md +1 -4
  29. package/src/adapters/costrict/commands/cf-task/plan.md +2 -2
  30. package/src/adapters/costrict/commands/cf-task/start.md +96 -25
  31. package/src/adapters/costrict/commands/cf-task/verify-e2e.md +8 -9
  32. package/src/adapters/costrict/commands/cf-validate.md +15 -13
  33. package/src/adapters/opencode/commands/cf-init.md +9 -4
  34. package/src/adapters/opencode/commands/cf-spec.md +6 -2
  35. package/src/adapters/opencode/commands/cf-task/archive.md +5 -5
  36. package/src/adapters/opencode/commands/cf-task/block.md +15 -9
  37. package/src/adapters/opencode/commands/cf-task/graph.md +8 -1
  38. package/src/adapters/opencode/commands/cf-task/note.md +1 -4
  39. package/src/adapters/opencode/commands/cf-task/plan.md +2 -2
  40. package/src/adapters/opencode/commands/cf-task/start.md +96 -25
  41. package/src/adapters/opencode/commands/cf-task/verify-e2e.md +8 -9
  42. package/src/adapters/opencode/commands/cf-validate.md +15 -13
  43. package/src/adapters/opencode/opencode.json +1 -2
  44. package/src/adapters/opencode/plugins/code-flow/index.js +176 -94
  45. package/src/adapters/opencode/plugins/code-flow/package.json +1 -1
  46. package/src/cli.js +228 -64
  47. package/src/core/code-flow/config.yml +2 -1
  48. package/src/core/code-flow/scripts/cf_acceptance_evidence.py +100 -0
  49. package/src/core/code-flow/scripts/cf_acceptance_manifest.py +137 -42
  50. package/src/core/code-flow/scripts/cf_acceptance_runner.py +123 -38
  51. package/src/core/code-flow/scripts/cf_acceptance_schema.py +83 -0
  52. package/src/core/code-flow/scripts/cf_core.py +34 -1
  53. package/src/core/code-flow/scripts/cf_exec_base.py +112 -0
  54. package/src/core/code-flow/scripts/cf_post_hook.py +5 -4
  55. package/src/core/code-flow/scripts/cf_pre_tool_hook.py +22 -7
  56. package/src/core/code-flow/scripts/cf_scan.py +8 -6
  57. package/src/core/code-flow/scripts/cf_spec_context.py +197 -63
  58. package/src/core/code-flow/scripts/cf_spec_gate.py +26 -4
  59. package/src/core/code-flow/scripts/cf_spec_resolver.py +7 -2
  60. package/src/core/code-flow/scripts/cf_spec_router.py +3 -1
  61. package/src/core/code-flow/scripts/cf_spec_session.py +3 -2
  62. package/src/core/code-flow/scripts/cf_spec_verify.py +42 -31
  63. package/src/core/code-flow/scripts/cf_stats.py +41 -9
  64. package/src/core/code-flow/scripts/cf_stop_hook.py +128 -61
  65. package/src/core/code-flow/scripts/cf_task_index.py +148 -0
  66. package/src/core/code-flow/scripts/cf_task_parallel.py +385 -0
  67. package/src/core/code-flow/scripts/cf_task_runtime.py +98 -29
  68. package/src/core/code-flow/scripts/cf_task_state.py +3 -0
  69. package/src/core/code-flow/scripts/cf_task_workflow.py +107 -0
  70. package/src/core/code-flow/scripts/cf_user_prompt_hook.py +9 -5
  71. package/src/core/code-flow/scripts/cf_validation.py +81 -0
  72. package/src/core/code-flow/scripts/cf_workflow_service.py +366 -0
  73. package/src/core/code-flow/scripts/cf_workflow_transaction.py +96 -0
  74. package/src/core/code-flow/validation.yml +5 -0
@@ -0,0 +1,366 @@
1
+ #!/usr/bin/env python3
2
+ """Unified workflow state machine: single entry for task state transitions.
3
+
4
+ Markdown task files are a readable view; the active marker plus Context are
5
+ the facts. Every transition below validates preconditions, mutates the marker
6
+ through cf_spec_context primitives, and syncs the Markdown view in the same
7
+ call with a recovery journal. Interrupted transitions can be rolled forward;
8
+ concurrent user edits block recovery instead of being overwritten.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ import json
15
+ from dataclasses import replace
16
+ from datetime import date
17
+ from pathlib import Path
18
+ from typing import Mapping, Optional, Sequence
19
+ from cf_spec_context import ActiveTask, SpecContext
20
+ from cf_workflow_transaction import recover_transition
21
+ from cf_task_state import FINISHED_STATUSES
22
+
23
+
24
+ class WorkflowError(ValueError):
25
+ """Fail-closed transition error with a stable code."""
26
+
27
+ def __init__(self, code: str, message: str, details: tuple[str, ...] = ()) -> None:
28
+ self.code = code
29
+ self.details = details
30
+ super().__init__(f"[{code}] {message}" + (f": {'; '.join(details)}" if details else ""))
31
+
32
+
33
+ def locate_task_file(task_dir: str, task_id: str) -> Optional[Path]:
34
+ """Find the unique task file containing the TASK section."""
35
+ matches: list[Path] = []
36
+ try:
37
+ files = sorted(Path(task_dir).glob("*.md"))
38
+ except OSError:
39
+ return None
40
+ for path in files:
41
+ if path.name.endswith((".prd.md", ".design.md")):
42
+ continue
43
+ try:
44
+ content = path.read_text(encoding="utf-8")
45
+ except (OSError, UnicodeError):
46
+ continue
47
+ if f"## {task_id}:" in content:
48
+ matches.append(path)
49
+ return matches[0] if len(matches) == 1 else None
50
+
51
+
52
+ def read_task_section(task_file: str, task_id: str) -> str:
53
+ try:
54
+ text = Path(task_file).read_text(encoding="utf-8")
55
+ except (OSError, UnicodeError) as exc:
56
+ raise WorkflowError("task_read_error", str(exc)) from exc
57
+ start = text.find(f"## {task_id}:")
58
+ if start == -1:
59
+ raise WorkflowError("task_not_found", task_id, (task_file,))
60
+ end = text.find("\n## TASK-", start)
61
+ return text[start:] if end == -1 else text[start:end]
62
+
63
+
64
+ def section_status(section: str) -> str:
65
+ """Markdown status; absent Status line means draft (pre-contract tasks)."""
66
+ match = re.search(r"(?m)^- \*\*Status\*\*:[ \t]*([^\n]+)", section)
67
+ return match.group(1).strip() if match else "draft"
68
+
69
+
70
+ def section_depends(section: str) -> tuple[str, ...]:
71
+ match = re.search(r"(?m)^- \*\*Depends\*\*:[ \t]*([^\n]*)", section)
72
+ if match is None:
73
+ return ()
74
+ return tuple(part.strip() for part in re.split(r"[,,\s]+", match.group(1).strip()) if re.fullmatch(r"TASK-\d+", part.strip()))
75
+
76
+
77
+ def section_notes(section: str) -> tuple[str, ...]:
78
+ return tuple(
79
+ line.strip()
80
+ for line in section.splitlines()
81
+ if "#NOTES" in line
82
+ )
83
+
84
+
85
+ def _all_statuses(task_file: str) -> Mapping[str, str]:
86
+ try:
87
+ text = Path(task_file).read_text(encoding="utf-8")
88
+ except (OSError, UnicodeError):
89
+ return {}
90
+ statuses: dict[str, str] = {}
91
+ for match in re.finditer(r"(?m)^## (TASK-\d+):[^\n]*$", text):
92
+ section = read_task_section(task_file, match.group(1))
93
+ statuses[match.group(1)] = section_status(section)
94
+ return statuses
95
+
96
+
97
+ def check_startable(task_file: str, task_id: str) -> list[str]:
98
+ """Collectors of start blockers; empty means the TASK may start."""
99
+ section = read_task_section(task_file, task_id)
100
+ status = section_status(section)
101
+ blockers: list[str] = []
102
+ if status == "blocked":
103
+ blockers.append(f"{task_id} is blocked; resolve Log BLOCKED entries first")
104
+ elif status == "done":
105
+ blockers.append(f"{task_id} is already done; verify contract or reopen explicitly")
106
+ elif status not in ("draft", "in-progress"):
107
+ blockers.append(f"{task_id} has unexpected status '{status}'")
108
+ notes = section_notes(section)
109
+ if notes:
110
+ blockers.append(f"{len(notes)} unresolved #NOTES: {notes[0][:80]}")
111
+ statuses = _all_statuses(task_file)
112
+ unmet = [dep for dep in section_depends(section) if statuses.get(dep) not in FINISHED_STATUSES]
113
+ if unmet:
114
+ rendered = ", ".join(dep + "(" + str(statuses.get(dep, "missing")) + ")" for dep in unmet)
115
+ blockers.append("unmet depends: " + rendered)
116
+ return blockers
117
+
118
+
119
+ def _today() -> str:
120
+ return date.today().isoformat()
121
+
122
+
123
+ def _set_status(section: str, status: str, log_line: str = "") -> str:
124
+ if re.search(r"(?m)^- \*\*Status\*\*:", section):
125
+ section = re.sub(r"(?m)^- \*\*Status\*\*:.*$", f"- **Status**: {status}", section, count=1)
126
+ else:
127
+ anchor = re.search(r"(?m)^## TASK-\d+:.*$", section)
128
+ insert_at = anchor.end() if anchor else 0
129
+ section = section[:insert_at] + f"\n- **Status**: {status}" + section[insert_at:]
130
+ if log_line and log_line not in section.splitlines():
131
+ section = section.rstrip() + ("\n" if "### Log" in section else "\n\n### Log\n") + log_line + "\n"
132
+ return section
133
+
134
+
135
+ def _render_markdown(text: str, task_id: str, status: str, log_line: str = "", prepend: str = "") -> str:
136
+ match = re.search(rf"(?ms)^## {re.escape(task_id)}:.*?(?=^## |\Z)", text)
137
+ if match is None:
138
+ raise WorkflowError("task_not_found", task_id)
139
+ section = _set_status(match.group(0), status, log_line)
140
+ if prepend and prepend not in section:
141
+ section = section.replace("### Log", prepend + "\n### Log", 1) if "### Log" in section else section + "\n" + prepend + "\n"
142
+ text = text[:match.start()] + section + text[match.end():]
143
+ return re.sub(r"(?m)^- \*\*Updated\*\*:.*$", f"- **Updated**: {_today()}", text, count=1)
144
+
145
+
146
+ def _sync_markdown(task_file: str, task_id: str, status: str, log_line: str = "", prepend: str = "") -> str:
147
+ from cf_spec_context import _atomic_text
148
+ target = Path(task_file)
149
+ text = target.read_text(encoding="utf-8")
150
+ _atomic_text(target, _render_markdown(text, task_id, status, log_line, prepend))
151
+ return "synced"
152
+
153
+
154
+ def _commit_state(root: str, task_file: str, task_id: str, status: str, previous: Optional[ActiveTask],
155
+ updated: Optional[ActiveTask], log_line: str = "", prepend: str = "") -> str:
156
+ from cf_spec_context import _active_data
157
+ from cf_workflow_transaction import commit_transition
158
+ marker = Path(root) / ".code-flow/.active-task.json"
159
+ marker_before = marker.read_text(encoding="utf-8") if marker.exists() else None
160
+ actual = json.loads(marker_before) if marker_before is not None else None
161
+ expected = _active_data(previous) if previous is not None else None
162
+ if actual != expected:
163
+ raise WorkflowError("active_mismatch", "active task changed before commit")
164
+ marker_after = json.dumps(_active_data(updated), ensure_ascii=False, indent=2) + "\n" if updated is not None else None
165
+ task = Path(task_file)
166
+ before = task.read_text(encoding="utf-8")
167
+ after = _render_markdown(before, task_id, status, log_line, prepend)
168
+ try:
169
+ commit_transition(root, task, before, after, marker_before, marker_after)
170
+ except (OSError, ValueError) as exc:
171
+ raise WorkflowError("transition_failed", str(exc)) from exc
172
+ return "synced"
173
+
174
+
175
+ def _resolve_paths(root: str, task_dir: str, task_file: str) -> tuple[Path, Path]:
176
+ base = Path(root)
177
+ directory = Path(task_dir) if Path(task_dir).is_absolute() else base / task_dir
178
+ candidate = Path(task_file) if Path(task_file).is_absolute() else base / task_file
179
+ if base.resolve() not in candidate.resolve().parents or candidate.parent.resolve() != directory.resolve() or not candidate.is_file():
180
+ raise WorkflowError("invalid_task_file", str(candidate), (str(directory),))
181
+ return directory, candidate
182
+
183
+
184
+ def _validate_start_manifest(directory: Path, candidate: Path) -> None:
185
+ if "## Acceptance Coverage" not in candidate.read_text(encoding="utf-8"):
186
+ return
187
+ manifest_file = directory / ".acceptance-manifest.json"
188
+ if not manifest_file.is_file():
189
+ raise WorkflowError("acceptance_manifest_missing", str(manifest_file), ("run plan verification and lock the manifest",))
190
+ from cf_acceptance_manifest import validate_manifest
191
+ valid, reason = validate_manifest(str(candidate), str(manifest_file))
192
+ if not valid:
193
+ raise WorkflowError(reason or "acceptance_manifest_invalid", str(manifest_file), ("run plan verification before coding",))
194
+
195
+
196
+ def _write_projection(root: str, candidate: Path, context: SpecContext, task_id: str, session_output: str) -> Path:
197
+ from cf_spec_context import _atomic_text
198
+ from cf_spec_session import project_task_session
199
+ try:
200
+ projection = project_task_session(context, str(candidate), task_id)
201
+ except ValueError as exc:
202
+ raise WorkflowError("task_projection_failed", str(exc)) from exc
203
+ if projection.truncated:
204
+ raise WorkflowError("task_projection_truncated", task_id, ("split the TASK before coding",))
205
+ output = Path(session_output) if session_output else (
206
+ Path(root) / ".code-flow/specs/_session" / f"task-{candidate.stem}.md"
207
+ )
208
+ try:
209
+ output.parent.mkdir(parents=True, exist_ok=True)
210
+ _atomic_text(output, projection.text)
211
+ except (OSError, ValueError) as exc:
212
+ raise WorkflowError("session_write_failed", str(exc)) from exc
213
+ return output
214
+
215
+
216
+ def start_task(
217
+ root: str,
218
+ task_dir: str,
219
+ task_file: str,
220
+ task_id: str,
221
+ owned_paths: Sequence[str] = (),
222
+ session_output: str = "",
223
+ ) -> dict[str, object]:
224
+ """Full Start Gate: hard preconditions first, then the guarded pipeline
225
+ (refresh → manifest check → projection → activation), then the Markdown
226
+ view flips to in-progress in the same call."""
227
+ from cf_spec_context import load_context, refresh_context, save_context, _new_active
228
+ from cf_spec_session import context_sha256
229
+
230
+ recover_transition(root)
231
+ directory, candidate = _resolve_paths(root, task_dir, task_file)
232
+ blockers = check_startable(str(candidate), task_id)
233
+ marker_active = (Path(root) / ".code-flow" / ".active-task.json").exists()
234
+ if marker_active:
235
+ blockers = [f"active_exists: run cf-spec doctor before starting {task_id}"] + blockers
236
+ if blockers:
237
+ raise WorkflowError("start_blocked", task_id, tuple(blockers))
238
+
239
+ context_path = directory / "spec-context.yml"
240
+ refreshed = refresh_context(load_context(str(context_path)), root, artifact_root=str(directory))
241
+ save_context(str(context_path), refreshed.context)
242
+ # No marker exists at this point (active_exists raised above), so no
243
+ # re-sync is needed before activation below.
244
+ current_hash = context_sha256(refreshed.context)
245
+ owned = tuple(item for item in owned_paths if isinstance(item, str))
246
+ _validate_start_manifest(directory, candidate)
247
+ output = _write_projection(root, candidate, refreshed.context, task_id, session_output)
248
+ try:
249
+ active = replace(_new_active(root, str(directory), task_id, current_hash, owned), status="active")
250
+ markdown = _commit_state(root, str(candidate), task_id, "in-progress", None, active, f"- [{_today()}] started")
251
+ except Exception as exc:
252
+ code = getattr(exc, "code", "activation_failed") if isinstance(exc, ValueError) else "activation_failed"
253
+ raise WorkflowError(str(code), str(exc)) from exc
254
+ from cf_spec_context import _active_data
255
+
256
+ return {
257
+ "ok": True,
258
+ "context_sha256": current_hash,
259
+ "refresh_changes": [item.__dict__ for item in refreshed.changes],
260
+ "active": _active_data(active),
261
+ "session_output": str(output),
262
+ "acceptance_manifest": str(directory / ".acceptance-manifest.json") if (directory / ".acceptance-manifest.json").is_file() else None,
263
+ "markdown": markdown,
264
+ }
265
+
266
+
267
+ def _require_marker_task(root: str, task_id: str, task_dir: str, task_file: str) -> None:
268
+ from cf_spec_context import ContextError, load_active_task
269
+
270
+ recover_transition(root)
271
+ try:
272
+ active = load_active_task(root)
273
+ except (ContextError, OSError, ValueError) as exc:
274
+ raise WorkflowError("no_active_task", str(exc)) from exc
275
+ directory, candidate = _resolve_paths(root, task_dir, task_file)
276
+ if active.task_id != task_id or (Path(root) / active.task_dir).resolve() != directory.resolve():
277
+ raise WorkflowError("active_mismatch", f"marker={active.task_id} requested={task_id}")
278
+ located = locate_task_file(str(directory), task_id)
279
+ if located is None or located.resolve() != candidate.resolve():
280
+ raise WorkflowError("active_mismatch", "TASK file must be unique and match the active demand")
281
+
282
+
283
+ def block_task(root: str, task_dir: str, task_file: str, task_id: str, reason: str) -> dict[str, object]:
284
+ """Block a TASK: marker (when it is ours and active) plus Markdown view."""
285
+ from cf_spec_context import ContextError, load_active_task
286
+
287
+ if not reason.strip():
288
+ raise WorkflowError("block_reason_required", task_id)
289
+ recover_transition(root)
290
+ _, target = _resolve_paths(root, task_dir, task_file)
291
+ task_file = str(target)
292
+ section = read_task_section(task_file, task_id)
293
+ if section_status(section) in FINISHED_STATUSES:
294
+ raise WorkflowError("task_already_done", task_id, ("completed TASKs cannot be blocked",))
295
+ marker = "skipped_no_marker"
296
+ active = None
297
+ updated = None
298
+ try:
299
+ active = load_active_task(root)
300
+ _require_marker_task(root, task_id, task_dir, task_file)
301
+ if active.task_id == task_id and active.status == "active":
302
+ updated = replace(active, status="blocked")
303
+ marker = "blocked"
304
+ elif active.task_id == task_id:
305
+ marker = active.status
306
+ updated = active
307
+ except ContextError:
308
+ if (Path(root) / ".code-flow/.active-task.json").exists():
309
+ raise
310
+ marker = "skipped_no_marker"
311
+ today = _today()
312
+ markdown = _commit_state(
313
+ root, task_file, task_id, "blocked", active, updated,
314
+ f"- [{today}] blocked ({reason})",
315
+ prepend=f"> BLOCKED: {reason}",
316
+ )
317
+ return {"ok": True, "task_id": task_id, "marker": marker, "markdown": markdown}
318
+
319
+
320
+ def resume_task(root: str, task_dir: str, task_file: str, task_id: str) -> dict[str, object]:
321
+ """Resume a blocked/paused TASK after its blockers clear."""
322
+ from cf_spec_context import load_active_task
323
+
324
+ recover_transition(root)
325
+ _, target = _resolve_paths(root, task_dir, task_file)
326
+ task_file = str(target)
327
+ active = None
328
+ if (Path(root) / ".code-flow/.active-task.json").exists():
329
+ _require_marker_task(root, task_id, task_dir, task_file)
330
+ active = load_active_task(root)
331
+ if active.status not in ("blocked", "paused"):
332
+ raise WorkflowError("resume_unexpected_state", active.status, (task_id,))
333
+ section = read_task_section(task_file, task_id)
334
+ if active is None and section_status(section) != "blocked":
335
+ raise WorkflowError("resume_unexpected_state", section_status(section), (task_id,))
336
+ notes = section_notes(section)
337
+ statuses = _all_statuses(task_file)
338
+ unmet = [dep for dep in section_depends(section) if statuses.get(dep) not in FINISHED_STATUSES]
339
+ if notes or unmet:
340
+ raise WorkflowError(
341
+ "resume_blocked", task_id,
342
+ tuple(([f"{len(notes)} unresolved #NOTES"] if notes else []) + ([f"unmet depends: {', '.join(unmet)}"] if unmet else [])),
343
+ )
344
+ resumed = replace(active, status="active") if active is not None else None
345
+ status = "in-progress" if resumed is not None else "draft"
346
+ markdown = _commit_state(root, task_file, task_id, status, active, resumed, f"- [{_today()}] resumed ({status})")
347
+ return {"ok": True, "task_id": task_id, "marker": resumed.status if resumed else "absent", "markdown": markdown}
348
+
349
+
350
+ def complete_task(root: str, task_dir: str, task_file: str, task_id: str, gate_passed: bool) -> dict[str, object]:
351
+ """Complete a TASK after its Done Gate passed; syncs both records."""
352
+ from cf_spec_context import load_active_task
353
+
354
+ if not gate_passed:
355
+ raise WorkflowError("gate_failed", task_id, ("Done Gate 未通过",))
356
+ _require_marker_task(root, task_id, task_dir, task_file)
357
+ _, target = _resolve_paths(root, task_dir, task_file)
358
+ task_file = str(target)
359
+ active = load_active_task(root)
360
+ if active.status != "active":
361
+ raise WorkflowError("invalid_active_transition", active.status)
362
+ completed = replace(active, status="completed")
363
+ from cf_spec_context import _active_data
364
+
365
+ markdown = _commit_state(root, task_file, task_id, "done", active, None, f"- [{_today()}] completed (done)")
366
+ return {"ok": True, "task_id": task_id, "active": _active_data(completed), "markdown": markdown}
@@ -0,0 +1,96 @@
1
+ """Recoverable two-file workflow commits under the active-task lock."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from pathlib import Path
6
+ from typing import Optional
7
+
8
+ from cf_spec_context import _acquire_active_lock, _atomic_text, _release_active_lock
9
+
10
+
11
+ def _read(path: Path) -> Optional[str]:
12
+ try:
13
+ return path.read_text(encoding="utf-8")
14
+ except FileNotFoundError:
15
+ return None
16
+
17
+
18
+ def _write(path: Path, value: Optional[str]) -> None:
19
+ if _read(path) == value:
20
+ return
21
+ if value is None:
22
+ path.unlink()
23
+ else:
24
+ _atomic_text(path, value)
25
+
26
+
27
+ def _journal_path(root: str) -> Path:
28
+ return Path(root) / ".code-flow/.workflow-transition.json"
29
+
30
+
31
+ def _records(root: str, data: object) -> list[dict[str, object]]:
32
+ if not isinstance(data, dict) or data.get("version") != 1:
33
+ raise ValueError("workflow recovery: invalid journal")
34
+ rows = data.get("files")
35
+ if not isinstance(rows, list) or len(rows) != 2:
36
+ raise ValueError("workflow recovery: invalid files")
37
+ base = Path(root).resolve()
38
+ marker = base / ".code-flow/.active-task.json"
39
+ for row in rows:
40
+ if not isinstance(row, dict) or not isinstance(row.get("path"), str):
41
+ raise ValueError("workflow recovery: invalid record")
42
+ path = Path(row["path"]).resolve()
43
+ if base not in path.parents or (path != marker and path.suffix != ".md"):
44
+ raise ValueError("workflow recovery: out-of-scope path")
45
+ for field in ("before", "after"):
46
+ if field not in row or (row[field] is not None and not isinstance(row[field], str)):
47
+ raise ValueError("workflow recovery: invalid contents")
48
+ if _read(path) not in (row["before"], row["after"]):
49
+ raise ValueError(f"workflow recovery: concurrent change to {path}")
50
+ if Path(rows[1]["path"]).resolve() != marker or rows[0]["path"] == rows[1]["path"]:
51
+ raise ValueError("workflow recovery: marker must be last")
52
+ return rows
53
+
54
+
55
+ def recover_transition(root: str) -> bool:
56
+ journal = _journal_path(root)
57
+ if not journal.exists():
58
+ return False
59
+ lock = _acquire_active_lock(root)
60
+ try:
61
+ if not journal.exists():
62
+ return False
63
+ rows = _records(root, json.loads(journal.read_text(encoding="utf-8")))
64
+ for row in rows:
65
+ _write(Path(row["path"]), row["after"])
66
+ journal.unlink()
67
+ return True
68
+ finally:
69
+ _release_active_lock(lock)
70
+
71
+
72
+ def commit_transition(root: str, task: Path, before: str, after: str,
73
+ marker_before: Optional[str], marker_after: Optional[str]) -> None:
74
+ marker = Path(root).resolve() / ".code-flow/.active-task.json"
75
+ rows = [{"path": str(task.resolve()), "before": before, "after": after},
76
+ {"path": str(marker), "before": marker_before, "after": marker_after}]
77
+ journal = _journal_path(root)
78
+ lock = _acquire_active_lock(root)
79
+ try:
80
+ if journal.exists():
81
+ raise ValueError("workflow recovery required before transition")
82
+ _records(root, {"version": 1, "files": rows})
83
+ if any(_read(Path(row["path"])) != row["before"] for row in rows):
84
+ raise ValueError("workflow concurrent change; retry transition")
85
+ _atomic_text(journal, json.dumps({"version": 1, "files": rows}, ensure_ascii=False))
86
+ try:
87
+ for row in rows:
88
+ _write(Path(row["path"]), row["after"])
89
+ except (OSError, ValueError):
90
+ for row in reversed(rows):
91
+ _write(Path(row["path"]), row["before"])
92
+ journal.unlink()
93
+ raise
94
+ journal.unlink()
95
+ finally:
96
+ _release_active_lock(lock)
@@ -1,3 +1,6 @@
1
+ # validators 在每次 Stop 按“会话内编辑过的文件”匹配执行(quality_loop.stop_check)。
2
+ # 全量测试 / e2e 等慢命令标 `heavy: true`:Stop 每轮跳过,任务 finish 自动执行
3
+ # 一次,也可显式运行 /cf-validate;避免每个任务都重跑多遍。
1
4
  validators:
2
5
  - name: "Python 语法检查"
3
6
  trigger: "**/*.py"
@@ -33,6 +36,7 @@ validators:
33
36
  trigger: "**/*.{ts,tsx,js,jsx,vue}"
34
37
  command: "npx vitest run --reporter=dot"
35
38
  timeout: 60000
39
+ heavy: true
36
40
  on_fail: "前端测试失败,检查组件渲染和 mock 是否需要更新"
37
41
 
38
42
  - name: "Python 类型检查"
@@ -45,4 +49,5 @@ validators:
45
49
  trigger: "**/*.py"
46
50
  command: "python3 -m pytest --tb=short -q"
47
51
  timeout: 60000
52
+ heavy: true
48
53
  on_fail: "测试失败,检查断言和 mock 是否需要更新"