返回 CodeWhale
check-command-migration-manifest.py
根目录 / scripts / check-command-migration-manifest.py
1 #!/usr/bin/env python3
2 """Deterministic command migration manifest gate for EPIC-006 (FEAT-015).
3
4 Enforces the staged-migration contract:
5
6 1. The checked-in migration topology document (`scripts/command-migration-topology.json`)
7 is versioned and fail-closed: `schema_version` must be 1; unknown versions,
8 tags, fields, selector kinds, type/trait node tags, and const atoms are rejected.
9 2. The pending frontier is a valid topology frontier: sorted, unique, containing
10 only known leaves, and reachable from the roots by parent-to-all-children
11 replacements (documented splits) or leaf removals (migrations). Arbitrary
12 additions, partial splits, and stale entries fail closed.
13 3. The frontier exactly equals the set of groups/slices whose handlers still
14 contain concrete-`App` signatures (`&mut App` / `&mut crate::tui::app::App`)
15 within `crates/tui/src/commands/groups/` (bidirectional source scan; the
16 AST/selector resolution part lands in Phase 3, `scan_and_check`).
17
18 The guard is hermetic for its data parts: it reads the topology artifact and
19 optionally the source tree; it never starts the TUI and makes no network calls.
20
21 Usage:
22 python3 scripts/check-command-migration-manifest.py # enforce
23 """
24
25 from __future__ import annotations
26
27 import argparse
28 import json
29 import re
30 import subprocess
31 import sys
32 from pathlib import Path
33
34 REPO_ROOT = Path(__file__).resolve().parent.parent
35 TOPOLOGY_PATH = REPO_ROOT / "scripts" / "command-migration-topology.json"
36 CONTRACT_PATH = REPO_ROOT / "crates" / "tui" / "src" / "commands" / "contract.rs"
37 TOPOLOGY_REPO_PATH = "scripts/command-migration-topology.json"
38 SUPPORTED_SCHEMA_VERSION = 1
39
40 # Closed set of Rust integer suffixes accepted by selector const atoms.
41 INTEGER_SUFFIXES = {
42 "i8", "u8", "i16", "u16", "i32", "u32", "i64", "u64", "i128", "u128",
43 "isize", "usize",
44 }
45
46 # Closed set of primitive type names accepted by the type algebra (v1).
47 PRIMITIVE_TYPES = {
48 "u8", "u16", "u32", "u64", "u128", "usize",
49 "i8", "i16", "i32", "i64", "i128", "isize",
50 "f32", "f64", "bool", "char", "str",
51 }
52
53 VALID_SELECTOR_KINDS = {"free", "inherent", "trait_impl"}
54 VALID_TYPE_TAGS = {
55 "path", "qualified", "tuple", "reference", "pointer", "slice", "array",
56 "primitive", "never",
57 }
58 VALID_GENERIC_ARG_TAGS = {"lifetime", "type", "const"}
59 VALID_CONST_TAGS = {"bool", "int", "char", "path"}
60
61
62 class ManifestViolation:
63 """One deterministic manifest violation with an actionable diagnostic."""
64
65 def __init__(self, category: str, location: str, detail: str) -> None:
66 self.category = category
67 self.location = location
68 self.detail = detail
69
70 def __str__(self) -> str:
71 return f"{self.category}: {self.location}: {self.detail}"
72
73
74 # ---------------------------------------------------------------------------
75 # Const atom validation (Deep-Dive: closed four-tag records, canonical decimal
76 # magnitudes, byte bounds, fail-closed unknown forms).
77 # ---------------------------------------------------------------------------
78
79 def _canonical_magnitude(value: str, location: str) -> list[ManifestViolation]:
80 """Validate `0|[1-9][0-9]*` and return violations (never leading zeros)."""
81 if value == "0":
82 return []
83 if not value.isdigit() or value[0] == "0":
84 return [ManifestViolation(
85 "const-atom", location,
86 f"integer magnitude must be canonical unsigned decimal without leading zeros "
87 f"(0|[1-9][0-9]*), got {value!r}",
88 )]
89 return []
90
91
92 def validate_const_atom(atom, location: str) -> list[ManifestViolation]:
93 """Validate one const atom record; reject unknown tags/fields/forms."""
94 if not isinstance(atom, dict) or "tag" not in atom:
95 return [ManifestViolation("const-atom", location, "const atom must be an object with a tag")]
96 tag = atom["tag"]
97 if tag not in VALID_CONST_TAGS:
98 return [ManifestViolation(
99 "const-atom", location, f"unknown const atom tag {tag!r}; expected one of {sorted(VALID_CONST_TAGS)}",
100 )]
101 violations: list[ManifestViolation] = []
102 if tag == "bool":
103 if set(atom) != {"tag", "value"} or not isinstance(atom.get("value"), bool):
104 violations.append(ManifestViolation(
105 "const-atom", location, "bool const atom must be {{tag: bool, value: <bool>}}",
106 ))
107 elif tag == "int":
108 allowed = {"tag", "negative", "magnitude", "suffix"}
109 if set(atom) != allowed:
110 violations.append(ManifestViolation(
111 "const-atom", location,
112 f"int const atom must have exactly {{tag, negative, magnitude, suffix}}, got {sorted(atom)}",
113 ))
114 return violations
115 if not isinstance(atom.get("negative"), bool):
116 violations.append(ManifestViolation("const-atom", location, "int.negative must be a bool"))
117 magnitude = atom.get("magnitude")
118 if not isinstance(magnitude, str):
119 violations.append(ManifestViolation("const-atom", location, "int.magnitude must be a string"))
120 else:
121 violations.extend(_canonical_magnitude(magnitude, location))
122 suffix = atom.get("suffix")
123 if suffix is not None and suffix not in INTEGER_SUFFIXES:
124 violations.append(ManifestViolation(
125 "const-atom", location, f"int.suffix must be null or a Rust integer suffix, got {suffix!r}",
126 ))
127 # Negative zero is noncanonical: normalize to nonnegative.
128 if atom.get("negative") and magnitude == "0":
129 violations.append(ManifestViolation(
130 "const-atom", location, "negative zero must be normalized to nonnegative",
131 ))
132 # Decoded byte values (u8 suffix) must be within 0-255 inclusive.
133 if suffix == "u8" and magnitude is not None and magnitude.isdigit():
134 if int(magnitude) > 255:
135 violations.append(ManifestViolation(
136 "const-atom", location,
137 f"decoded byte value {magnitude} exceeds the inclusive u8 range 0-255",
138 ))
139 elif tag == "char":
140 if set(atom) != {"tag", "scalar"} or not isinstance(atom.get("scalar"), str):
141 violations.append(ManifestViolation(
142 "const-atom", location, "char const atom must be {{tag: char, scalar: <single Unicode scalar>}}",
143 ))
144 else:
145 scalar = atom["scalar"]
146 if len(scalar) != 1:
147 violations.append(ManifestViolation(
148 "const-atom", location, "char.scalar must be exactly one Unicode scalar",
149 ))
150 elif tag == "path":
151 if set(atom) != {"tag", "absolute", "segments"}:
152 violations.append(ManifestViolation(
153 "const-atom", location,
154 "path const atom must be {{tag: path, absolute: <bool>, segments: [...]}}",
155 ))
156 return violations
157 if not isinstance(atom.get("absolute"), bool):
158 violations.append(ManifestViolation("const-atom", location, "path.absolute must be a bool"))
159 segments = atom.get("segments")
160 if not isinstance(segments, list) or not segments:
161 violations.append(ManifestViolation("const-atom", location, "path.segments must be a nonempty array"))
162 elif not all(isinstance(s, str) and s for s in segments):
163 violations.append(ManifestViolation("const-atom", location, "path.segments must be nonempty strings"))
164 return violations
165
166
167 # ---------------------------------------------------------------------------
168 # Type algebra validation (Deep-Dive: closed v1 algebra, fail-closed).
169 # ---------------------------------------------------------------------------
170
171 def validate_type_node(node, location: str) -> list[ManifestViolation]:
172 """Validate a recursive type/trait node; reject unsupported syntax."""
173 if not isinstance(node, dict) or "tag" not in node:
174 return [ManifestViolation("type-algebra", location, "type node must be an object with a tag")]
175 tag = node["tag"]
176 if tag not in VALID_TYPE_TAGS:
177 return [ManifestViolation(
178 "type-algebra", location,
179 f"unknown type node tag {tag!r}; expected one of {sorted(VALID_TYPE_TAGS)}",
180 )]
181 violations: list[ManifestViolation] = []
182
183 if tag == "path":
184 allowed = {"tag", "absolute", "segments"}
185 if set(node) != allowed:
186 return [ManifestViolation(
187 "type-algebra", location, f"path node must have exactly {{tag, absolute, segments}}, got {sorted(node)}",
188 )]
189 if not isinstance(node.get("absolute"), bool):
190 violations.append(ManifestViolation("type-algebra", location, "path.absolute must be a bool"))
191 segments = node.get("segments")
192 if not isinstance(segments, list) or not segments:
193 return violations + [ManifestViolation("type-algebra", location, "path.segments must be a nonempty array")]
194 for i, seg in enumerate(segments):
195 seg_loc = f"{location}.segments[{i}]"
196 if not isinstance(seg, dict) or "name" not in seg or not isinstance(seg.get("name"), str) or not seg["name"]:
197 violations.append(ManifestViolation("type-algebra", seg_loc, "segment must be {{name: <string>, args?: [...]}}"))
198 continue
199 if "args" in seg:
200 if not isinstance(seg["args"], list):
201 violations.append(ManifestViolation("type-algebra", seg_loc, "segment.args must be an array"))
202 continue
203 for j, arg in enumerate(seg["args"]):
204 violations.extend(validate_generic_arg(arg, f"{seg_loc}.args[{j}]"))
205 elif tag == "qualified":
206 allowed = {"tag", "self", "assoc"}
207 if set(node) != allowed:
208 return [ManifestViolation("type-algebra", location, "qualified node must have exactly {tag, self, assoc}")]
209 violations.extend(validate_type_node(node.get("self"), f"{location}.self"))
210 if not isinstance(node.get("assoc"), str) or not node["assoc"]:
211 violations.append(ManifestViolation("type-algebra", location, "qualified.assoc must be a nonempty string"))
212 elif tag == "tuple":
213 if set(node) != {"tag", "elems"} or not isinstance(node.get("elems"), list):
214 return [ManifestViolation("type-algebra", location, "tuple node must be {{tag: tuple, elems: [...]}}")]
215 for i, elem in enumerate(node["elems"]):
216 violations.extend(validate_type_node(elem, f"{location}.elems[{i}]"))
217 elif tag in ("reference", "pointer"):
218 allowed = {"tag", "mut", "inner"}
219 if set(node) != allowed or not isinstance(node.get("mut"), bool):
220 return [ManifestViolation("type-algebra", location, f"{tag} node must be {{tag, mut, inner}}")]
221 violations.extend(validate_type_node(node.get("inner"), f"{location}.inner"))
222 elif tag == "slice":
223 if set(node) != {"tag", "inner"}:
224 return [ManifestViolation("type-algebra", location, "slice node must be {{tag: slice, inner}}")]
225 violations.extend(validate_type_node(node.get("inner"), f"{location}.inner"))
226 elif tag == "array":
227 allowed = {"tag", "inner", "len"}
228 if set(node) != allowed:
229 return [ManifestViolation("type-algebra", location, "array node must be {{tag: array, inner, len}}")]
230 violations.extend(validate_type_node(node.get("inner"), f"{location}.inner"))
231 violations.extend(validate_const_atom(node.get("len"), f"{location}.len"))
232 elif tag == "primitive":
233 if set(node) != {"tag", "name"} or node.get("name") not in PRIMITIVE_TYPES:
234 return [ManifestViolation(
235 "type-algebra", location,
236 f"primitive node must be {{tag: primitive, name}} with name in {sorted(PRIMITIVE_TYPES)}",
237 )]
238 elif tag == "never":
239 if set(node) != {"tag"}:
240 return [ManifestViolation("type-algebra", location, "never node must be {{tag: never}}")]
241 return violations
242
243
244 def validate_generic_arg(arg, location: str) -> list[ManifestViolation]:
245 """Validate one path-segment generic argument (type/lifetime/const)."""
246 if not isinstance(arg, dict) or "tag" not in arg:
247 return [ManifestViolation("type-algebra", location, "generic argument must be an object with a tag")]
248 tag = arg["tag"]
249 if tag not in VALID_GENERIC_ARG_TAGS:
250 return [ManifestViolation(
251 "type-algebra", location,
252 f"unknown generic argument tag {tag!r}; expected one of {sorted(VALID_GENERIC_ARG_TAGS)}",
253 )]
254 if tag == "lifetime":
255 if set(arg) != {"tag", "name"} or not isinstance(arg.get("name"), str) or not arg["name"]:
256 return [ManifestViolation("type-algebra", location, "lifetime argument must be {{tag: lifetime, name}}")]
257 elif tag == "type":
258 return validate_type_node(arg.get("node"), f"{location}.node")
259 else: # const
260 if set(arg) != {"tag", "atom"}:
261 return [ManifestViolation("type-algebra", location, "const argument must be {{tag: const, atom}}")]
262 return validate_const_atom(arg.get("atom"), f"{location}.atom")
263 return []
264
265
266 # ---------------------------------------------------------------------------
267 # Selector validation (Deep-Dive: tagged structural records).
268 # ---------------------------------------------------------------------------
269
270 def validate_selector(selector, location: str) -> list[ManifestViolation]:
271 """Validate one handler selector record (free / inherent / trait_impl)."""
272 if not isinstance(selector, dict) or "kind" not in selector:
273 return [ManifestViolation("selector", location, "selector must be an object with a kind")]
274 kind = selector["kind"]
275 if kind not in VALID_SELECTOR_KINDS:
276 return [ManifestViolation(
277 "selector", location,
278 f"unknown selector kind {kind!r}; expected one of {sorted(VALID_SELECTOR_KINDS)}",
279 )]
280 violations: list[ManifestViolation] = []
281 if kind == "free":
282 allowed = {"kind", "item"}
283 if set(selector) != allowed:
284 return [ManifestViolation("selector", location, f"free selector must have exactly {{kind, item}}, got {sorted(selector)}")]
285 item = selector.get("item")
286 if not isinstance(item, list) or len(item) < 2:
287 return [ManifestViolation("selector", location, "free.item must be a module path array ending with the function name")]
288 if not all(isinstance(s, str) and s for s in item):
289 return [ManifestViolation("selector", location, "free.item entries must be nonempty strings")]
290 elif kind == "inherent":
291 allowed = {"kind", "self_type", "method"}
292 if "method" not in selector:
293 return [ManifestViolation("selector", location, "inherent.method must be a nonempty string")]
294 if set(selector) != allowed:
295 return [ManifestViolation("selector", location, f"inherent selector must have exactly {{kind, self_type, method}}, got {sorted(selector)}")]
296 violations.extend(validate_type_node(selector.get("self_type"), f"{location}.self_type"))
297 if not isinstance(selector.get("method"), str) or not selector["method"]:
298 violations.append(ManifestViolation("selector", location, "inherent.method must be a nonempty string"))
299 else: # trait_impl
300 allowed = {"kind", "self_type", "trait_path", "method"}
301 if set(selector) != allowed:
302 return [ManifestViolation("selector", location, f"trait_impl selector must have exactly {{kind, self_type, trait_path, method}}, got {sorted(selector)}")]
303 violations.extend(validate_type_node(selector.get("self_type"), f"{location}.self_type"))
304 violations.extend(validate_type_node(selector.get("trait_path"), f"{location}.trait_path"))
305 if not isinstance(selector.get("method"), str) or not selector["method"]:
306 violations.append(ManifestViolation("selector", location, "trait_impl.method must be a nonempty string"))
307 return violations
308
309
310 # ---------------------------------------------------------------------------
311 # Topology / frontier validation.
312 # ---------------------------------------------------------------------------
313
314 def all_leaves(topology: dict) -> dict[str, str]:
315 """Map leaf name -> owning root for every group and predeclared slice."""
316 leaves: dict[str, str] = {}
317 for root, node in topology.items():
318 leaves[root] = root
319 for slice_node in node.get("slices", []):
320 leaves[slice_node["name"]] = root
321 return leaves
322
323
324 def validate_frontier(topology: dict, frontier: list[str]) -> list[ManifestViolation]:
325 """Frontier must be sorted, unique, and reference only known leaves."""
326 violations: list[ManifestViolation] = []
327 if not isinstance(frontier, list):
328 return [ManifestViolation("frontier", "frontier", "frontier must be an array")]
329 if frontier != sorted(frontier):
330 violations.append(ManifestViolation("frontier", "frontier", "frontier must be sorted"))
331 if len(frontier) != len(set(frontier)):
332 violations.append(ManifestViolation("frontier", "frontier", "frontier must contain no duplicates"))
333 leaves = all_leaves(topology)
334 for entry in frontier:
335 if entry not in leaves:
336 violations.append(ManifestViolation(
337 "frontier", entry, f"frontier entry {entry!r} is not a declared topology leaf",
338 ))
339 return violations
340
341
342 def is_documented_split(topology: dict, old: set[str], new: set[str]) -> bool:
343 """A parent was replaced by ALL of its declared children (1->N, no growth).
344
345 Exactly one entry is removed; it is a group with declared slices; the added
346 entries are exactly those declared children; nothing else changed.
347 """
348 removed = old - new
349 added = new - old
350 if len(removed) != 1:
351 return False
352 parent = next(iter(removed))
353 for root, node in topology.items():
354 children = {s["name"] for s in node.get("slices", [])}
355 if parent == root and children:
356 return children == added and len(added) == len(children) and added == new - old
357 return False
358
359
360 def is_valid_frontier_transition(topology: dict, old: list[str], new: list[str]) -> list[ManifestViolation]:
361 """Permit shrink (removal of migrated leaves) or documented parent-to-all-children split."""
362 old_set = set(old)
363 new_set = set(new)
364 violations: list[ManifestViolation] = []
365 removed = old_set - new_set
366 added = new_set - old_set
367
368 # Pure shrink: removed leaves only, nothing added.
369 if not added:
370 return violations # any removal is a shrink (gate re-checks source later)
371
372 # Documented split: exactly one parent removed, all its children added.
373 if is_documented_split(topology, old_set, new_set):
374 return violations
375
376 # Everything else is growth or partial split: fail closed.
377 if removed:
378 violations.append(ManifestViolation(
379 "frontier-transition", ", ".join(sorted(removed)),
380 "frontier shrank AND grew; only pure shrink or documented parent-to-all-children split is allowed",
381 ))
382 else:
383 violations.append(ManifestViolation(
384 "frontier-transition", ", ".join(sorted(added)),
385 "frontier grew without a documented parent-to-all-children split; arbitrary growth is forbidden",
386 ))
387 return violations
388
389
390 def validate_topology_document(doc: dict) -> list[ManifestViolation]:
391 """Validate the whole topology document (schema, topology, frontier, slices)."""
392 violations: list[ManifestViolation] = []
393 if not isinstance(doc, dict):
394 return [ManifestViolation("schema", "document", "topology document must be an object")]
395 if doc.get("schema_version") != SUPPORTED_SCHEMA_VERSION:
396 return [ManifestViolation(
397 "schema", "schema_version",
398 f"unsupported schema_version {doc.get('schema_version')!r}; only {SUPPORTED_SCHEMA_VERSION} is supported",
399 )]
400 topology = doc.get("topology")
401 if not isinstance(topology, dict) or not topology:
402 return [ManifestViolation("schema", "topology", "topology must be a nonempty object")]
403 for root, node in topology.items():
404 if not isinstance(node, dict):
405 violations.append(ManifestViolation("schema", root, "group node must be an object"))
406 continue
407 allowed_group_fields = {"kind", "scope", "slices"}
408 unknown = set(node) - allowed_group_fields
409 if unknown:
410 violations.append(ManifestViolation(
411 "schema", root, f"unknown group field(s) {sorted(unknown)}; expected {sorted(allowed_group_fields)}",
412 ))
413 if "kind" not in node or "scope" not in node or "slices" not in node:
414 violations.append(ManifestViolation(
415 "schema", root, "group node must be {{kind, scope, slices}}",
416 ))
417 continue
418 if node.get("kind") != "group":
419 violations.append(ManifestViolation("schema", root, f"group {root!r} kind must be 'group'"))
420 scope = node.get("scope")
421 if not isinstance(scope, list) or not scope or not all(isinstance(s, str) and s for s in scope):
422 violations.append(ManifestViolation("schema", root, "group scope must be a nonempty array of strings"))
423 slices = node.get("slices")
424 if not isinstance(slices, list):
425 violations.append(ManifestViolation("schema", root, "group slices must be an array"))
426 continue
427 seen: set[str] = set()
428 for i, slice_node in enumerate(slices):
429 loc = f"{root}.slices[{i}]"
430 if not isinstance(slice_node, dict):
431 violations.append(ManifestViolation("schema", loc, "slice must be an object"))
432 continue
433 allowed_slice_fields = {"name", "kind", "scope", "handlers"}
434 unknown = set(slice_node) - allowed_slice_fields
435 if unknown:
436 violations.append(ManifestViolation(
437 "schema", loc, f"unknown slice field(s) {sorted(unknown)}; expected {sorted(allowed_slice_fields)}",
438 ))
439 if "name" not in slice_node:
440 violations.append(ManifestViolation("schema", loc, "slice must be an object with a name"))
441 continue
442 name = slice_node["name"]
443 if name in seen:
444 violations.append(ManifestViolation("schema", loc, f"duplicate slice name {name!r}"))
445 seen.add(name)
446 if not name.startswith(f"{root}::"):
447 violations.append(ManifestViolation("schema", loc, f"slice name {name!r} must start with {root!r}::"))
448 if slice_node.get("kind") != "slice":
449 violations.append(ManifestViolation("schema", loc, f"slice {name!r} kind must be 'slice'"))
450 slice_scope = slice_node.get("scope")
451 if not isinstance(slice_scope, list) or not slice_scope or not all(isinstance(s, str) and s for s in slice_scope):
452 violations.append(ManifestViolation("schema", loc, f"slice {name!r} scope must be a nonempty array of strings"))
453 for selector in slice_node.get("handlers", []):
454 violations.extend(validate_selector(selector, f"{loc}.handlers"))
455 violations.extend(validate_frontier(topology, doc.get("frontier", [])))
456 return violations
457
458
459 def load_topology(path: Path = TOPOLOGY_PATH) -> dict:
460 with path.open(encoding="utf-8") as fh:
461 return json.load(fh)
462
463
464 def load_pending_groups(path: Path = CONTRACT_PATH) -> list[str]:
465 """Read the TUI frontier projection from `PENDING_GROUPS` fail-closed."""
466 source = path.read_text(encoding="utf-8")
467 match = re.search(
468 r"pub\(crate\)\s+const\s+PENDING_GROUPS\s*:\s*&\[&str\]\s*=\s*&\[(.*?)\];",
469 source,
470 re.DOTALL,
471 )
472 if match is None:
473 raise ValueError(f"could not locate PENDING_GROUPS in {path}")
474 body = match.group(1)
475 stripped = re.sub(r'"(?:\\.|[^"\\])*"', "", body)
476 if re.fullmatch(r"[\s,]*", stripped) is None:
477 raise ValueError("PENDING_GROUPS may contain string literals only")
478 return re.findall(r'"((?:\\.|[^"\\])*)"', body)
479
480
481 def validate_pending_projection(doc: dict, pending: list[str]) -> list[ManifestViolation]:
482 if pending != doc.get("frontier"):
483 return [ManifestViolation(
484 "frontier-projection",
485 "PENDING_GROUPS",
486 f"TUI projection {pending!r} does not equal JSON frontier {doc.get('frontier')!r}",
487 )]
488 return []
489
490
491 def load_topology_at_ref(ref: str, root: Path = REPO_ROOT) -> dict | None:
492 """Load the topology from a Git revision; return None before its introduction."""
493 commit = subprocess.run(
494 ["git", "rev-parse", "--verify", f"{ref}^{{commit}}"],
495 cwd=root,
496 capture_output=True,
497 text=True,
498 check=False,
499 )
500 if commit.returncode != 0:
501 raise ValueError(f"baseline ref {ref!r} is unavailable: {commit.stderr.strip()}")
502 shown = subprocess.run(
503 ["git", "show", f"{ref}:{TOPOLOGY_REPO_PATH}"],
504 cwd=root,
505 capture_output=True,
506 text=True,
507 check=False,
508 )
509 if shown.returncode != 0:
510 return None
511 return json.loads(shown.stdout)
512
513
514 def validate_baseline_transition(current: dict, previous: dict | None) -> list[ManifestViolation]:
515 """Enforce immutable topology and shrink-or-declared-split across revisions."""
516 if validate_topology_document(current):
517 return [ManifestViolation(
518 "current",
519 "topology",
520 "current topology is invalid; cannot validate a monotonic transition",
521 )]
522 if previous is None:
523 roots = sorted(current["topology"])
524 if current.get("frontier") != roots:
525 return [ManifestViolation(
526 "frontier-initialization",
527 "frontier",
528 f"first manifest revision must start at all topology roots {roots!r}",
529 )]
530 return []
531
532 violations = validate_topology_document(previous)
533 if violations:
534 return [ManifestViolation(
535 "baseline",
536 "topology",
537 "baseline topology is invalid; cannot validate a monotonic transition",
538 )]
539 if previous.get("topology") != current.get("topology"):
540 violations.append(ManifestViolation(
541 "topology-transition",
542 "topology",
543 "migration topology is immutable; only the frontier may change",
544 ))
545 return violations
546 violations.extend(
547 is_valid_frontier_transition(
548 previous["topology"], previous["frontier"], current["frontier"]
549 )
550 )
551 return violations
552
553
554 def detect_local_baseline_ref(root: Path = REPO_ROOT) -> str | None:
555 """Use the feature-branch merge-base, or the first parent on main."""
556 process = subprocess.run(
557 ["git", "merge-base", "HEAD", "origin/main"],
558 cwd=root,
559 capture_output=True,
560 text=True,
561 check=False,
562 )
563 baseline = process.stdout.strip() if process.returncode == 0 else None
564 head = subprocess.run(
565 ["git", "rev-parse", "HEAD"],
566 cwd=root,
567 capture_output=True,
568 text=True,
569 check=False,
570 ).stdout.strip()
571 if baseline and baseline != head:
572 return baseline
573 # A main checkout aligned with origin/main still has migration history.
574 # Comparing its parent preserves the ratchet after push and in manual CI.
575 parent = subprocess.run(
576 ["git", "rev-parse", "--verify", "HEAD^"],
577 cwd=root,
578 capture_output=True,
579 text=True,
580 check=False,
581 )
582 return parent.stdout.strip() if parent.returncode == 0 else None
583
584
585 # ---------------------------------------------------------------------------
586 # Source scan (Task 3.5): structural Rust item resolution and bidirectional
587 # frontier check. Pure-stdlib parser: brace/paren aware, resolves qualified
588 # item paths for free functions, inherent methods, and trait-impl methods.
589 # ---------------------------------------------------------------------------
590
591 GROUPS_ROOT = REPO_ROOT / "crates" / "tui" / "src" / "commands" / "groups"
592 CONCRETE_APP_PARAM = re.compile(
593 r"&\s*(?:'[A-Za-z_][A-Za-z0-9_]*\s+)?(?:mut\s+)?(?:crate::tui::app::|crate::app::|tui::app::)?App\b"
594 )
595 CFG_TEST_ATTR = re.compile(r"#\s*\[\s*cfg\s*\(\s*test\s*\)\s*\]")
596 MOD_TESTS_HEAD = re.compile(r"\bmod\s+tests\s*\{")
597 ATTRIBUTE_HEAD = re.compile(r"#\s*!?\s*\[")
598 CONST_FN_TAIL = r"(?:(?:async|unsafe)\s+|extern\s*(?:\"[^\"]*\"\s*)?)*fn\b"
599 SEMICOLON_ITEM = re.compile(
600 r"(?:pub(?:\s*\([^)]*\))?\s+)?(?:use|static|type|const(?!\s+" + CONST_FN_TAIL + r"))\b"
601 )
602 ITEM_HEAD = re.compile(
603 r"(?:pub(?:\s*\([^)]*\))?\s+)?(?:default\s+)?"
604 r"(?:fn|async|unsafe|extern|mod|use|impl|struct|enum|union|trait|const|static|type|macro_rules)\b"
605 )
606
607
608 class RustItem:
609 """One parsed Rust item relevant to the migration scan."""
610
611 def __init__(self, kind: str, name: str, qual_path: str, file: Path,
612 line: int, param_types: list[str], is_concrete_app: bool) -> None:
613 self.kind = kind # 'free' | 'inherent' | 'trait_impl'
614 self.name = name
615 self.qual_path = qual_path
616 self.file = file
617 self.line = line
618 self.param_types = param_types
619 self.is_concrete_app = is_concrete_app
620
621 def __repr__(self) -> str:
622 return f"RustItem({self.kind}, {self.qual_path}, app={self.is_concrete_app})"
623
624
625 class SourceScanViolation:
626 """One deterministic source-scan failure with an actionable diagnostic."""
627
628 def __init__(self, category: str, location: str, detail: str) -> None:
629 self.category = category
630 self.location = location
631 self.detail = detail
632
633 def __str__(self) -> str:
634 return f"{self.category}: {self.location}: {self.detail}"
635
636
637 def _strip_comments_and_strings(text: str) -> str:
638 """Replace comments and string/char literals with spaces so the structural
639 scanner sees only code. Keeps raw strings and byte/char literals intact
640 enough for delimiter counting (content is blanked)."""
641 out = list(text)
642 i = 0
643 n = len(text)
644 in_line_comment = False
645 in_block_comment = 0
646 while i < n:
647 ch = text[i]
648 if in_line_comment:
649 if ch == "\n":
650 in_line_comment = False
651 else:
652 out[i] = " "
653 i += 1
654 continue
655 if in_block_comment:
656 if text.startswith("*/", i):
657 in_block_comment -= 1
658 out[i] = out[i + 1] = " "
659 i += 2
660 else:
661 out[i] = " "
662 i += 1
663 continue
664 if text.startswith("//", i):
665 in_line_comment = True
666 out[i] = out[i + 1] = " "
667 i += 2
668 continue
669 if text.startswith("/*", i):
670 in_block_comment += 1
671 out[i] = out[i + 1] = " "
672 i += 2
673 continue
674 if ch == '"':
675 # String literal (possibly raw r#"..."#). Blank until closing quote.
676 out[i] = " "
677 i += 1
678 if text.startswith('#"', i - 1):
679 while i < n and text[i] == "#":
680 out[i] = " "
681 i += 1
682 while i < n:
683 if text[i] == "\\" and i + 1 < n:
684 out[i] = out[i + 1] = " "
685 i += 2
686 continue
687 if text[i] == '"':
688 out[i] = " "
689 i += 1
690 break
691 out[i] = " "
692 i += 1
693 continue
694 if ch == "'":
695 # Char or lifetime. Blank the atom conservatively (lifetimes are
696 # single-quote-prefixed identifiers; chars are 'x' or '\\x').
697 if i + 1 < n and text[i + 1] == "'":
698 out[i] = out[i + 1] = " "
699 i += 2
700 continue
701 out[i] = " "
702 i += 1
703 if i < n and text[i] == "\\":
704 out[i] = " "
705 i += 1
706 if i < n:
707 out[i] = " "
708 i += 1
709 if i < n and text[i] == "'":
710 out[i] = " "
711 i += 1
712 continue
713 i += 1
714 return "".join(out)
715
716
717 def _split_top_level(text: str, sep: str) -> list[str]:
718 """Split on a separator character outside (), [], {} and strings."""
719 parts: list[str] = []
720 start = 0
721 depth = 0
722 for i, ch in enumerate(text):
723 if ch in "([{":
724 depth += 1
725 elif ch in ")]}":
726 depth -= 1
727 elif ch == sep and depth == 0:
728 parts.append(text[start:i])
729 start = i + 1
730 parts.append(text[start:])
731 return parts
732
733
734 def _module_path_from_file(file: Path, root: Path, prefix: str = "crate::commands::groups::") -> str:
735 """Derive the crate-relative module path for a file under the groups root.
736
737 `mod.rs` resolves to its directory name; other files to
738 `dirname.file_name` (snake_case). Path segments are joined with `::`.
739 """
740 rel = file.relative_to(root)
741 parts = list(rel.parts)
742 if parts[-1] == "mod.rs":
743 parts = parts[:-1]
744 else:
745 parts[-1] = parts[-1].removesuffix(".rs")
746 return prefix + "::".join(parts)
747
748
749 def _first_param_type(fn_sig: str) -> str | None:
750 """Extract the first parameter's type from a `fn name(...)` signature text."""
751 open_idx = fn_sig.find("(")
752 if open_idx < 0:
753 return None
754 close_idx = fn_sig.rfind(")")
755 if close_idx < open_idx:
756 return None
757 params = _split_top_level(fn_sig[open_idx + 1:close_idx], ",")
758 params = [p.strip() for p in params if p.strip()]
759 if not params:
760 return None
761 first = params[0]
762 if first == "self" or first.startswith("self:") or first.startswith("&self"):
763 return None
764 # `name: Type` or `name: Type` with generic default: take after the first top-level ':'.
765 depth = 0
766 for idx, ch in enumerate(first):
767 if ch in "<([":
768 depth += 1
769 elif ch in ">)]":
770 depth -= 1
771 elif ch == ":" and depth == 0:
772 return first[idx + 1:].strip()
773 return None
774
775
776 # ---------------------------------------------------------------------------
777 # Retained host machinery
778 # ---------------------------------------------------------------------------
779 #
780 # All command groups have zero retained `&mut App` helpers. Kept empty so any
781 # concrete-App helper added under `crates/tui/src/commands/groups/` fails the
782 # migration gate.
783 RETAINED_HOST_MACHINERY: dict[str, list[dict]] = {}
784
785
786 def _is_concrete_app_type(param_type: str | None) -> bool:
787 if param_type is None:
788 return False
789 # Match `&mut App` / `&mut crate::tui::app::App` with optional spaces
790 # around `mut`; no whitespace normalization so `\s*` can bind.
791 return bool(CONCRETE_APP_PARAM.search(param_type))
792
793
794 def _skip_balanced(code: str, start: int, opener: str, closer: str) -> int:
795 depth = 0
796 i = start
797 n = len(code)
798 while i < n:
799 if code[i] == opener:
800 depth += 1
801 elif code[i] == closer:
802 depth -= 1
803 if depth == 0:
804 return i + 1
805 i += 1
806 return n
807
808
809 def _item_end(code: str, start: int) -> int:
810 """Index just past the Rust item starting at `start` (attributes already
811 skipped): the matching `}` of its body, or its terminating `;`."""
812 n = len(code)
813 semicolon_only = bool(SEMICOLON_ITEM.match(code, start))
814 depth = 0
815 i = start
816 while i < n:
817 ch = code[i]
818 if ch in "([":
819 depth += 1
820 elif ch in ")]":
821 depth -= 1
822 elif ch == "{" and depth == 0:
823 if semicolon_only:
824 i = _skip_balanced(code, i, "{", "}")
825 continue
826 return _skip_balanced(code, i, "{", "}")
827 elif ch == ";" and depth == 0:
828 return i + 1
829 i += 1
830 return n
831
832
833 def _blank_span(chars: list[str], start: int, end: int) -> None:
834 for k in range(start, min(end, len(chars))):
835 if chars[k] != "\n":
836 chars[k] = " "
837
838
839 def _blank_test_only_items(code: str) -> str:
840 """Blank `#[cfg(test)]` items and `mod tests { .. }` bodies so test-only
841 helpers are never counted as handlers. Offsets and newlines are kept.
842 On a field, variant, parameter or match arm only the attribute is blanked,
843 so the scan never runs past the enclosing item."""
844 chars = list(code)
845 for match in CFG_TEST_ATTR.finditer(code):
846 if chars[match.start()] == " ":
847 continue
848 j = match.end()
849 while True:
850 while j < len(code) and code[j].isspace():
851 j += 1
852 attr = ATTRIBUTE_HEAD.match(code, j)
853 if not attr:
854 break
855 j = _skip_balanced(code, code.index("[", j), "[", "]")
856 end = _item_end(code, j) if ITEM_HEAD.match(code, j) else j
857 _blank_span(chars, match.start(), end)
858 for match in MOD_TESTS_HEAD.finditer(code):
859 if chars[match.start()] == " ":
860 continue
861 brace = code.index("{", match.start())
862 _blank_span(chars, match.start(), _skip_balanced(code, brace, "{", "}"))
863 return "".join(chars)
864
865
866 def parse_rust_file(file: Path, root: Path) -> list[RustItem]:
867 """Structurally parse one Rust file for handler-relevant items.
868
869 Handles `fn name(...) -> R { ... }` free functions at top level and
870 `impl Trait for Type { fn ... }` / `impl Type { fn ... }` blocks. The
871 parser tracks braces to skip bodies and resolves qualified paths from the
872 module layout. It is deliberately narrow: it looks for function items with
873 a first parameter typed `&mut App` (the concrete-App handler signature).
874
875 Module paths use the owning commands crate or TUI groups directory.
876 Hermetic fixtures may supply their own module root.
877 """
878 raw = file.read_text(encoding="utf-8")
879 code = _blank_test_only_items(_strip_comments_and_strings(raw))
880 # Module paths derive from the source owner; hermetic tests use a synthetic
881 # root, in which case the passed root is the module-path base.
882 commands_root = root / "crates/commands/src"
883 try:
884 module_path = _module_path_from_file(file, commands_root, "crate::")
885 except ValueError:
886 try:
887 module_path = _module_path_from_file(file, GROUPS_ROOT)
888 except ValueError:
889 module_path = _module_path_from_file(file, root)
890 items: list[RustItem] = []
891 lines = raw.splitlines()
892
893 i = 0
894 n = len(code)
895 # Walk top-level items: skip until we find `fn` or `impl` at depth 0.
896 while i < n:
897 # find next top-level keyword occurrence
898 while i < n and code[i].isspace():
899 i += 1
900 if i >= n:
901 break
902 if code.startswith("fn", i) and (i == 0 or not (code[i - 1].isalnum() or code[i - 1] == "_")):
903 # free function
904 sig_end = _find_fn_signature_end(code, i + 2)
905 if sig_end is None:
906 i += 2
907 continue
908 sig_text = code[i:sig_end]
909 name_match = re.match(r"fn\s+([A-Za-z_][A-Za-z0-9_]*)", sig_text)
910 line_no = raw.count("\n", 0, code.find(sig_text[:20], 0)) + 1 if sig_text[:20] else 0
911 if name_match:
912 name = name_match.group(1)
913 param_type = _first_param_type(sig_text)
914 items.append(RustItem(
915 kind="free",
916 name=name,
917 qual_path=f"{module_path}::{name}",
918 file=file,
919 line=line_no,
920 param_types=[param_type] if param_type else [],
921 is_concrete_app=_is_concrete_app_type(param_type),
922 ))
923 # advance past the signature and body
924 i = sig_end
925 # skip the block body if present (or the `;` for a declaration)
926 while i < n and code[i].isspace():
927 i += 1
928 if i < n and code[i] == "{":
929 depth = 0
930 while i < n:
931 if code[i] == "{":
932 depth += 1
933 elif code[i] == "}":
934 depth -= 1
935 if depth == 0:
936 i += 1
937 break
938 i += 1
939 else:
940 i += 1 # consume the `;` (or advance past a non-body token)
941 continue
942 if code.startswith("impl", i) and (i == 0 or not (code[i - 1].isalnum() or code[i - 1] == "_")):
943 # impl block: header until '{'
944 brace_idx = code.find("{", i)
945 if brace_idx < 0:
946 i += 4
947 continue
948 header = code[i + 4:brace_idx].strip()
949 # `impl Trait for Type` vs `impl Type`
950 trait_impl = " for " in header
951 self_type = header.split(" for ")[-1].strip() if trait_impl else header.strip()
952 # methods inside
953 depth = 1
954 j = brace_idx + 1
955 while j < n and depth > 0:
956 if code[j] == "{":
957 depth += 1
958 elif code[j] == "}":
959 depth -= 1
960 if depth == 0:
961 break
962 elif code[j].isspace():
963 j += 1
964 continue
965 elif code.startswith("fn", j) and not (code[j - 1].isalnum() or code[j - 1] == "_"):
966 fn_start = j
967 sig_end = _find_fn_signature_end(code, j + 2)
968 if sig_end is None:
969 j += 2
970 continue
971 sig_text = code[fn_start:sig_end]
972 name_match = re.match(r"fn\s+([A-Za-z_][A-Za-z0-9_]*)", sig_text)
973 if name_match:
974 name = name_match.group(1)
975 param_type = _first_param_type(sig_text)
976 self_qual = _self_type_qual(self_type, module_path)
977 if trait_impl:
978 trait_path = header.split(" for ")[0].strip()
979 kind = "trait_impl"
980 qual = f"{self_qual}::{name} [{trait_path}]"
981 else:
982 kind = "inherent"
983 qual = f"{self_qual}::{name}"
984 line_no = raw.count("\n", 0, code.find(sig_text[:20], 0)) + 1 if sig_text[:20] else 0
985 items.append(RustItem(
986 kind=kind,
987 name=name,
988 qual_path=qual,
989 file=file,
990 line=line_no,
991 param_types=[param_type] if param_type else [],
992 is_concrete_app=_is_concrete_app_type(param_type),
993 ))
994 j = sig_end
995 # skip the method body (or consume `;` for a declaration)
996 while j < n and code[j].isspace():
997 j += 1
998 if j < n and code[j] == "{":
999 body_depth = 0
1000 while j < n:
1001 if code[j] == "{":
1002 body_depth += 1
1003 elif code[j] == "}":
1004 body_depth -= 1
1005 if body_depth == 0:
1006 j += 1
1007 break
1008 j += 1
1009 else:
1010 j += 1
1011 continue
1012 else:
1013 j += 1
1014 continue
1015 i = j + 1 if j < n else n
1016 continue
1017 i += 1
1018 return items
1019
1020
1021 def _find_fn_signature_end(code: str, start: int) -> int | None:
1022 """Find the index just after a `fn` signature (before `{` or `;`),
1023 respecting nested generics and parens. The `->` arrow's `>` is not a
1024 generic close delimiter."""
1025 depth = 0
1026 generic = 0
1027 i = start
1028 n = len(code)
1029 while i < n:
1030 ch = code[i]
1031 if ch in "([":
1032 depth += 1
1033 elif ch in ")]":
1034 depth -= 1
1035 elif ch == "<":
1036 generic += 1
1037 elif ch == ">":
1038 # `->` arrow: previous char is '-'; not a generic close.
1039 if i > 0 and code[i - 1] == "-":
1040 pass
1041 elif generic > 0:
1042 generic -= 1
1043 elif ch in "{;" and depth == 0 and generic == 0:
1044 return i
1045 i += 1
1046 return None
1047
1048
1049 def _self_type_qual(self_type: str, module_path: str) -> str:
1050 """Qualify a bare self type with the module path (e.g. `BranchCmd` ->
1051 `crate::commands::groups::session::branch::BranchCmd`). Already-qualified
1052 paths pass through."""
1053 cleaned = re.sub(r"\s+", "", self_type)
1054 if cleaned.startswith("crate::") or cleaned.startswith("super::"):
1055 return cleaned
1056 # Strip generic args for qualification purposes (path part only).
1057 base = re.split(r"[<({]", cleaned)[0]
1058 return f"{module_path}::{base}"
1059
1060
1061 def _selector_matches(selector: dict, item: RustItem) -> bool:
1062 """Match one RustItem against a checked-in selector (shared by
1063 `resolve_selector` and the retained-host source scan)."""
1064 kind = selector["kind"]
1065 if kind == "free":
1066 target = "::".join(selector["item"])
1067 return item.kind == "free" and item.qual_path == target
1068 if kind == "inherent":
1069 self_qual = _selector_type_to_text(selector["self_type"])
1070 return item.kind == "inherent" and item.name == selector["method"] \
1071 and item.qual_path.startswith(f"{self_qual}::")
1072 self_qual = _selector_type_to_text(selector["self_type"])
1073 trait_qual = _selector_type_to_text(selector["trait_path"])
1074 return item.kind == "trait_impl" and item.name == selector["method"] \
1075 and item.qual_path.startswith(f"{self_qual}::") \
1076 and f"[{trait_qual}]" in item.qual_path
1077
1078
1079 def resolve_selector(selector: dict, items: list[RustItem]) -> list[SourceScanViolation]:
1080 """Resolve one checked-in handler selector against parsed items.
1081
1082 Returns violations for missing, ambiguous, or non-concrete-App targets.
1083 """
1084 violations: list[SourceScanViolation] = []
1085 kind = selector["kind"]
1086 if kind == "free":
1087 target = "::".join(selector["item"])
1088 matches = [it for it in items if it.kind == "free" and it.qual_path == target]
1089 elif kind == "inherent":
1090 self_type = selector["self_type"]
1091 method = selector["method"]
1092 self_qual = _selector_type_to_text(self_type)
1093 matches = [
1094 it for it in items
1095 if it.kind == "inherent" and it.name == method and it.qual_path.startswith(f"{self_qual}::")
1096 ]
1097 else: # trait_impl
1098 self_type = selector["self_type"]
1099 trait_path = selector["trait_path"]
1100 method = selector["method"]
1101 self_qual = _selector_type_to_text(self_type)
1102 trait_qual = _selector_type_to_text(trait_path)
1103 matches = [
1104 it for it in items
1105 if it.kind == "trait_impl" and it.name == method
1106 and it.qual_path.startswith(f"{self_qual}::") and f"[{trait_qual}]" in it.qual_path
1107 ]
1108 if not matches:
1109 violations.append(SourceScanViolation(
1110 "selector-resolve", str(selector),
1111 "selector resolved to no source item; handler may have moved, been renamed, or the path is stale",
1112 ))
1113 elif len(matches) > 1:
1114 violations.append(SourceScanViolation(
1115 "selector-resolve", str(selector),
1116 f"selector resolved to {len(matches)} items (ambiguous): " + "; ".join(m.qual_path for m in matches),
1117 ))
1118 elif not matches[0].is_concrete_app:
1119 violations.append(SourceScanViolation(
1120 "selector-resolve", str(selector),
1121 f"resolved handler {matches[0].qual_path} no longer has a concrete-App signature",
1122 ))
1123 return violations
1124
1125
1126 def _selector_type_to_text(node) -> str:
1127 """Render a type-algebra node back to Rust text for matching."""
1128 if not isinstance(node, dict):
1129 return str(node)
1130 tag = node["tag"]
1131 if tag == "path":
1132 segments = []
1133 for seg in node.get("segments", []):
1134 name = seg["name"] if isinstance(seg, dict) else str(seg)
1135 segments.append(name)
1136 prefix = "" if node.get("absolute") else ""
1137 return prefix + "::".join(segments)
1138 if tag == "primitive":
1139 return node["name"]
1140 if tag == "never":
1141 return "!"
1142 if tag == "tuple":
1143 return "(" + ",".join(_selector_type_to_text(e) for e in node.get("elems", [])) + ")"
1144 if tag == "reference":
1145 return "&" + ("mut " if node.get("mut") else "") + _selector_type_to_text(node.get("inner"))
1146 if tag == "pointer":
1147 return "*" + ("mut " if node.get("mut") else "const ") + _selector_type_to_text(node.get("inner"))
1148 if tag == "slice":
1149 return "[" + _selector_type_to_text(node.get("inner")) + "]"
1150 if tag == "array":
1151 return "[" + _selector_type_to_text(node.get("inner")) + "; " + _selector_type_to_text(node.get("len")) + "]"
1152 return ""
1153
1154
1155 def scan_leaf_handlers(leaf_scope: list[str], root: Path) -> tuple[list[RustItem], list[SourceScanViolation]]:
1156 """Scan one leaf's source scope for concrete-App handler items.
1157
1158 `root` is the repo root (scope paths are repo-relative); module paths are
1159 derived against the groups root internally.
1160 """
1161 items: list[RustItem] = []
1162 violations: list[SourceScanViolation] = []
1163 for rel in leaf_scope:
1164 path = root / rel
1165 if not path.is_file():
1166 violations.append(SourceScanViolation(
1167 "source-scan", rel, "scope file missing from the source tree",
1168 ))
1169 continue
1170 try:
1171 items.extend(parse_rust_file(path, root))
1172 except Exception as exc: # pragma: no cover - defensive
1173 violations.append(SourceScanViolation(
1174 "source-scan", rel, f"failed to parse: {exc}",
1175 ))
1176 return items, violations
1177
1178
1179 UNLISTED_SLICE_ASSIGNMENT: dict[str, dict[str, list[str]]] = {
1180 "core": {
1181 "core::navigation": ["crates/tui/src/commands/groups/core/copy.rs"],
1182 "core::coordination": ["crates/commands/src/router.rs"],
1183 },
1184 }
1185
1186
1187 CORE_MOVED_SOURCES = {
1188 f"crates/tui/src/commands/groups/core/{old}.rs": f"crates/commands/src/{new}.rs"
1189 for old, new in {
1190 "clear": "core_policy", "effort": "core_policy", "feedback": "core_policy",
1191 "constitution": "constitution", "hooks": "hooks", "workflow": "workflow",
1192 "fleet": "fleet_lane/fleet", "lane": "fleet_lane/lane",
1193 }.items()
1194 }
1195
1196
1197 def slice_source_scope(group_name: str, slice_node: dict) -> list[str]:
1198 """A slice's historical scope plus the unlisted files the immutable
1199 topology never assigned to it."""
1200 if slice_node["name"] == "core::model-and-setup":
1201 return sorted(path.replace("crates/tui/src/commands/groups/core/", "crates/commands/src/model_setup/", 1)
1202 for path in slice_node.get("scope", []))
1203 extra = UNLISTED_SLICE_ASSIGNMENT.get(group_name, {}).get(slice_node["name"], [])
1204 return sorted({CORE_MOVED_SOURCES.get(path, path) for path in slice_node.get("scope", [])} | set(extra))
1205
1206
1207 def group_source_scope(group_name: str, node: dict, root: Path) -> list[str]:
1208 """Preserve the immutable historical topology and scan every group source.
1209
1210 Recursive discovery includes receipts, module roots, helpers and new
1211 nested files even when the historical manifest never listed them, so a
1212 handler added outside the frozen scope cannot pass unseen. Relocating
1213 declared debug paths preserves missing-file diagnostics after extraction.
1214 """
1215 scope = set(node.get("scope", []))
1216 directories = [root / "crates/tui/src/commands/groups" / group_name]
1217 if group_name == "debug":
1218 scope = {path.replace("crates/tui/src/commands/groups/debug/",
1219 "crates/commands/src/debug/", 1) for path in scope}
1220 directories.append(root / "crates/commands/src/debug")
1221 if group_name == "core":
1222 scope.add("crates/commands/src/router.rs")
1223 directories.append(root / "crates/commands/src/fleet_lane")
1224 scope = {CORE_MOVED_SOURCES.get(path, path) for path in scope}
1225 for slice_node in node.get("slices", []):
1226 if slice_node["name"] == "core::model-and-setup":
1227 scope.difference_update(slice_node["scope"])
1228 scope.update(slice_source_scope(group_name, slice_node))
1229 directories.append(root / "crates/commands/src/model_setup")
1230 for directory in directories:
1231 scope.update(path.relative_to(root).as_posix() for path in directory.rglob("*.rs"))
1232 return sorted(scope)
1233
1234
1235 def check_source_frontier(topology: dict, frontier: list[str], root: Path = REPO_ROOT) -> list[SourceScanViolation]:
1236 """Bidirectional scan: the frontier must exactly equal the leaves whose
1237 scopes still contain concrete-App handlers.
1238
1239 The frontier may name a whole group (all its files pending) or a group's
1240 declared slices (after a documented split). For every group:
1241
1242 - group pending: all concrete-App handlers in the group scope are covered.
1243 - group split: the frontier must name ALL its slices, and every handler
1244 in the group scope must fall inside a pending slice's scope.
1245 - otherwise: any concrete-App handler in the group is a stale-removal.
1246 """
1247 violations: list[SourceScanViolation] = []
1248 frontier_set = set(frontier)
1249
1250 for group_name, node in topology.items():
1251 group_items, scan_violations = scan_leaf_handlers(
1252 group_source_scope(group_name, node, root), root
1253 )
1254 violations.extend(scan_violations)
1255 handlers = [it for it in group_items if it.is_concrete_app]
1256
1257 slices = node.get("slices", [])
1258 if group_name in frontier_set:
1259 # Whole group pending: every handler is covered; a pending group
1260 # with no concrete-App handler is a stale entry.
1261 if not handlers:
1262 violations.append(SourceScanViolation(
1263 "stale-entry", group_name,
1264 "frontier group is pending but its scope has no concrete-App handler",
1265 ))
1266 for selector in node.get("handlers", []):
1267 violations.extend(resolve_selector(selector, group_items))
1268 continue
1269
1270 # Validate retained host machinery declarations first so the tracking
1271 # stays fail-closed even when the group has no other concrete-App
1272 # handlers (e.g. every retained helper lost its signature at once).
1273 retained_names: set[str] = set()
1274 for selector in RETAINED_HOST_MACHINERY.get(group_name, []):
1275 matches = [it for it in group_items if _selector_matches(selector, it)]
1276 if not matches:
1277 violations.append(SourceScanViolation(
1278 "retained-host", json.dumps(selector, sort_keys=True),
1279 f"retained host machinery selector resolves to no source item in {group_name!r}",
1280 ))
1281 for match in matches:
1282 if not match.is_concrete_app:
1283 violations.append(SourceScanViolation(
1284 "retained-host", match.qual_path,
1285 "retained host machinery must keep its concrete-App signature until FEAT-042 extracts it",
1286 ))
1287 retained_names.add(match.qual_path)
1288
1289 if not handlers:
1290 continue
1291
1292 if slices:
1293 slice_names = {s["name"] for s in slices}
1294 slice_pending = slice_names & frontier_set
1295 if slice_pending == slice_names:
1296 # Documented split: verify each slice scope holds its handlers.
1297 for slice_node in slices:
1298 slice_items, slice_violations = scan_leaf_handlers(
1299 slice_source_scope(group_name, slice_node), root
1300 )
1301 violations.extend(slice_violations)
1302 slice_handlers = [it for it in slice_items if it.is_concrete_app]
1303 if not slice_handlers:
1304 violations.append(SourceScanViolation(
1305 "stale-entry", slice_node["name"],
1306 "frontier slice is pending but its scope has no concrete-App handler",
1307 ))
1308 for selector in slice_node.get("handlers", []):
1309 violations.extend(resolve_selector(selector, slice_items))
1310 continue
1311 if slice_pending:
1312 # Partial split: some slices pending, some not.
1313 missing = sorted(slice_names - slice_pending)
1314 violations.append(SourceScanViolation(
1315 "partial-split", group_name,
1316 f"group is neither wholly pending nor fully split; pending slices "
1317 f"{sorted(slice_pending)} but missing {missing}",
1318 ))
1319 continue
1320
1321 # Not pending and not split: every remaining handler is a stale removal,
1322 # except the retained host machinery resolved above.
1323 stale = [h for h in handlers if h.qual_path not in retained_names]
1324 for handler in stale[:5]:
1325 violations.append(SourceScanViolation(
1326 "stale-removal", handler.qual_path,
1327 f"handler still uses concrete App but group {group_name!r} is not pending",
1328 ))
1329 if len(stale) > 5:
1330 violations.append(SourceScanViolation(
1331 "stale-removal", group_name,
1332 f"... and {len(stale) - 5} more concrete-App handlers in this group",
1333 ))
1334
1335 return violations
1336
1337
1338 def _leaf_node(topology: dict, leaf_name: str) -> dict | None:
1339 if leaf_name in topology:
1340 return topology[leaf_name]
1341 for root_name, node in topology.items():
1342 for slice_node in node.get("slices", []):
1343 if slice_node["name"] == leaf_name:
1344 return slice_node
1345 return None
1346
1347
1348 def main(argv: list[str] | None = None) -> int:
1349 parser = argparse.ArgumentParser(description=__doc__)
1350 parser.add_argument(
1351 "--baseline-ref",
1352 help="Git revision whose topology/frontier must transition monotonically to the current one",
1353 )
1354 args = parser.parse_args(argv)
1355
1356 try:
1357 doc = load_topology()
1358 pending = load_pending_groups()
1359 baseline_ref = args.baseline_ref or detect_local_baseline_ref()
1360 previous = load_topology_at_ref(baseline_ref) if baseline_ref else None
1361 except (OSError, ValueError, json.JSONDecodeError) as error:
1362 print(f"[command-migration-manifest] FAIL: {error}", file=sys.stderr)
1363 return 1
1364
1365 violations = validate_topology_document(doc)
1366 violations.extend(validate_pending_projection(doc, pending))
1367 violations.extend(validate_baseline_transition(doc, previous))
1368 if violations:
1369 print("[command-migration-manifest] FAIL", file=sys.stderr)
1370 for violation in violations:
1371 print(f" {violation}", file=sys.stderr)
1372 return 1
1373 source_violations = check_source_frontier(doc["topology"], doc["frontier"])
1374 if source_violations:
1375 print("[command-migration-manifest] FAIL (source scan)", file=sys.stderr)
1376 for violation in source_violations:
1377 print(f" {violation}", file=sys.stderr)
1378 return 1
1379 frontier = doc["frontier"]
1380 transition = f"; baseline {baseline_ref}" if baseline_ref else "; initialization"
1381 print(
1382 f"[command-migration-manifest] PASS: schema v{SUPPORTED_SCHEMA_VERSION}; "
1383 f"frontier [{', '.join(frontier)}] matches TUI projection and source{transition}"
1384 )
1385 return 0
1386
1387
1388 if __name__ == "__main__":
1389 sys.exit(main())
1390
1390 lines PYTHON