#!/usr/bin/env python3 import sys import os import re import time import json import argparse import subprocess from collections import Counter from datetime import datetime from pathlib import Path FACTORY_HOME = os.path.expanduser("/Users/dave/warezfactory") REGISTRY_PATH = os.path.join(FACTORY_HOME, "config/factory_registry.json") CONTEXT_ROOT = os.path.join(FACTORY_HOME, "web/sites/higginsoft.com/context") def post_distributed_notification(name, user_info=None): """Posts a macOS distributed notification via AppleScript with Foundation framework.""" if user_info and isinstance(user_info, dict): target_agent = user_info.get("target_agent", "").replace('"', '\\"') message = user_info.get("message", "").replace('"', '\\"') osa_script = f''' use framework "Foundation" set dnc to current application's NSDistributedNotificationCenter's defaultCenter() set userInfo to current application's NSDictionary's dictionaryWithObjects:{{{chr(34)}{target_agent}{chr(34)}, {chr(34)}{message}{chr(34)}}} forKeys:{{{chr(34)}target_agent{chr(34)}, {chr(34)}message{chr(34)}}} dnc's postNotificationName:"{name}" object:(missing value) userInfo:userInfo deliverImmediately:true ''' else: osa_script = f''' use framework "Foundation" set dnc to current application's NSDistributedNotificationCenter's defaultCenter() dnc's postNotificationName:"{name}" object:(missing value) userInfo:(missing value) deliverImmediately:true ''' try: subprocess.run(["/usr/bin/osascript", "-e", osa_script], check=True, capture_output=True) except Exception as e: print(f"⚠️ Notification broadcast failed for '{name}': {e}") def find_owning_agent(registry, project_id, workspace_uuid=None): agents = registry.get("agents", {}) projects = registry.get("projects", {}) # Direct visible agent match first for _, agent in agents.items(): if agent.get("isVisible", False): if project_id in agent.get("projects", {}): return agent.get("name") # Workspace sibling match (e.g., frameworks inside Factory_Frameworks owned via Framework Manager/Test Harness) if workspace_uuid: for _, agent in agents.items(): if agent.get("isVisible", False): for assigned_pid in agent.get("projects", {}).keys(): assigned_proj = projects.get(assigned_pid, {}) if assigned_proj.get("workspace_uuid") == workspace_uuid: return agent.get("name") return None def resolve_project_and_agent(project_name, target_agent_override=None): if not os.path.exists(REGISTRY_PATH): return None, None, None, None, None with open(REGISTRY_PATH, 'r', encoding='utf-8') as f: registry = json.load(f) projects = registry.get("projects", {}) matches = [] for pid, proj in projects.items(): if proj.get("name", "").lower() == project_name.lower(): owner = find_owning_agent(registry, pid, proj.get("workspace_uuid")) matches.append((pid, proj, owner)) if not matches: return None, None, None, None, None # Prefer a match that has a visible owning agent (handles duplicate legacy project entries like Theme Cannon) resolved_proj_id, resolved_proj, detected_owner = next( ((pid, proj, owner) for pid, proj, owner in matches if owner), matches[0] ) raw_path = resolved_proj.get("project_path") or resolved_proj.get("stored_project_path", "") expanded_path = raw_path.replace("$FACTORY_HOME", FACTORY_HOME) # Extract project type and workspace_uuid proj_type = resolved_proj.get("type", "unknown") workspace_uuid = resolved_proj.get("workspace_uuid") owning_agent = target_agent_override.strip() if target_agent_override and target_agent_override.strip() else detected_owner if not owning_agent: # Dynamic scan for any visible agent whose name starts with "Zack" agents = registry.get("agents", {}) for _, agent in agents.items(): if agent.get("isVisible", False): name = agent.get("name", "") if name.startswith("Zack"): owning_agent = name break if not owning_agent: owning_agent = "Zack 4.0" return resolved_proj.get("name"), expanded_path, owning_agent, proj_type, workspace_uuid # ── Project Format Detection & Build Settings Parsing ───────────────────────── def find_xcodeproj_bundle(proj_path): """Locate the *.xcodeproj bundle inside proj_path, ignoring common build directories.""" skip_dirs = {".build", "DerivedData", ".git", "Framework_Stubs", "TestBinaries", "Pods"} for root, dirs, files in os.walk(proj_path): dirs[:] = [d for d in dirs if d not in skip_dirs] for d in dirs: if d.endswith(".xcodeproj"): return os.path.join(root, d) return None def parse_json5(text): """Strip JSON5 comments and trailing commas, then decode with json.loads.""" # Remove // line comments (outside string literals) lines = text.split('\n') cleaned_lines = [] in_block_comment = False for line in lines: if in_block_comment: if '*/' in line: line = line[line.index('*/')+2:] in_block_comment = False else: continue if '/*' in line: # Handle block comment on same line before, rest = line.split('/*', 1) if '*/' in rest: line = before + rest[rest.index('*/')+2:] else: line = before in_block_comment = True # Remove // comments if '//' in line: # Need to handle // inside string literals in_string = False escape = False comment_idx = -1 for i, ch in enumerate(line): if escape: escape = False continue if ch == '\\': escape = True continue if ch == '"' and not escape: in_string = not in_string continue if ch == '/' and i+1 < len(line) and line[i+1] == '/' and not in_string: comment_idx = i break if comment_idx >= 0: line = line[:comment_idx] cleaned_lines.append(line) cleaned = '\n'.join(cleaned_lines) # Remove trailing commas before } or ] cleaned = re.sub(r',(\s*[}\]])', r'\1', cleaned) return json.loads(cleaned) def parse_project_xcproj(proj_path): """Parse project.xcproj (JSON5) and return build settings with line numbers.""" xcproj_path = os.path.join(proj_path, "project.xcproj") if not os.path.exists(xcproj_path): return None, None, False with open(xcproj_path, 'r', encoding='utf-8') as f: content = f.read() lines = content.split('\n') try: data = parse_json5(content) except Exception as e: print(f"⚠️ Failed to parse project.xcproj: {e}") return None, None, False # Build line number map for settings with proper scope tracking line_map = {} current_key = None in_build_settings = False scope = "project" current_target = None in_targets_section = False targets_depth = 0 in_specialized_config = False for idx, line in enumerate(lines, 1): stripped = line.strip() # Track scope transitions - use brace counting for targets array if '"targets"' in stripped and ':' in stripped and stripped.index(':') < stripped.index('['): in_targets_section = True targets_depth = 1 scope = "targets" current_target = None continue if in_targets_section: # Count braces to track when we leave targets section for ch in line: if ch == '{' or ch == '[': targets_depth += 1 elif ch == '}' or ch == ']': targets_depth -= 1 if targets_depth <= 0: in_targets_section = False scope = "project" current_target = None if in_targets_section and '"name"' in stripped and ':' in stripped: match = re.search(r'"name"\s*:\s*"([^"]+)"', stripped) if match: name_value = match.group(1) # Only set current_target if we're not in specialized-configurations # (specialized-configurations have their own "name" fields like "Debug", "Release") if not in_specialized_config: current_target = name_value # Track entering specialized-configurations if in_targets_section and '"specialized-configurations"' in stripped: in_specialized_config = True elif in_specialized_config and stripped == ']': in_specialized_config = False # Detect build-settings blocks - check if we're in targets section if '"build-settings"' in stripped and ':' in stripped: in_build_settings = True # Determine scope based on whether we're in targets section if in_targets_section: scope = "target" else: scope = "project" continue # Detect end of build-settings block if in_build_settings and stripped == '}': in_build_settings = False # Don't clear current_target here - it's handled by targets section logic # Capture build settings keys with their line numbers if in_build_settings: # Match key: "value" or key: value match = re.search(r'"([^"]+)"\s*:\s*', stripped) if match: key = match.group(1) # Store with scope and target info if key not in line_map: line_map[key] = [] line_map[key].append({ "line": idx, "scope": scope, "target": current_target }) # Extract project-level build settings project_settings = {} if "build-settings" in data: project_settings = data["build-settings"] # Extract target-level build settings target_settings = {} if "targets" in data: for target in data["targets"]: name = target.get("name", "") if "build-settings" in target: target_settings[name] = target["build-settings"] # Fixed: check c.get("file") not t.get("file") has_factory_consumer = any(c.get("file") == "FactoryConsumer.xcconfig" for c in data.get("configurations", [])) or \ any(c.get("file") == "FactoryConsumer.xcconfig" for t in data.get("targets", []) if "specialized-configurations" in t for c in t.get("specialized-configurations", [])) return { "project_settings": project_settings, "target_settings": target_settings, "configurations": data.get("configurations", []), "targets": data.get("targets", []), "format": "project.xcproj (JSON)", "has_factory_consumer": has_factory_consumer }, line_map, True def parse_project_pbxproj(proj_path): """Parse project.pbxproj (OpenStep plist) and return build settings with line numbers.""" pbxproj_path = os.path.join(proj_path, "project.pbxproj") if not os.path.exists(pbxproj_path): return None, None, False with open(pbxproj_path, 'r', encoding='utf-8') as f: content = f.read() lines = content.split('\n') # First, build the object graph: map object IDs to their data # We need to find: # 1. PBXProject -> buildConfigurationList ID # 2. PBXNativeTarget -> (target_name, buildConfigurationList ID) # 3. XCConfigurationList -> list of XCBuildConfiguration IDs # 4. XCBuildConfiguration -> (name, buildSettings, baseConfigurationReference) object_data = {} # object_id -> {type, name, buildConfigurationList, buildConfigurations, buildSettings, etc.} # First pass: identify all objects and their types by reading the isa inside # The pbxproj format has all objects at the same nesting level (depth 2) inside the 'objects' dict current_obj_id = None current_obj_type = None obj_brace_depth = 0 # Track brace depth WITHIN the current object in_objects_section = False objects_brace_depth = 0 # Track brace depth of the objects dict itself for idx, line in enumerate(lines): stripped = line.strip() # Detect start of objects section if stripped == 'objects = {': in_objects_section = True objects_brace_depth = 1 continue if not in_objects_section: continue # FIRST: Check for object start BEFORE counting braces on this line # Detect object start: "OBJECT_ID /* COMMENT */ = {" obj_match = re.match(r'^([0-9A-F]+)\s*/\*.*?\*/\s*=\s*\{', stripped) if obj_match and current_obj_id is None and obj_brace_depth == 0: current_obj_id = obj_match.group(1) current_obj_type = None object_data[current_obj_id] = { "type": None, # Will be determined from isa "start_line": idx + 1, "lines": [line] } obj_brace_depth = 1 # We've seen the opening { # Check if this is a single-line object (ends with }; on same line) if stripped.endswith('};') or '};' in stripped[stripped.index('{')+1:]: # Single-line object - parse it immediately obj_brace_depth = 0 # Extract isa if present isa_match = re.search(r'isa\s*=\s*([^;]+);', stripped) if isa_match: current_obj_type = isa_match.group(1).strip() object_data[current_obj_id]["type"] = current_obj_type # Object ends immediately current_obj_id = None current_obj_type = None # Still need to count braces for objects section depth for ch in line: if ch == '{': objects_brace_depth += 1 elif ch == '}': objects_brace_depth -= 1 continue if current_obj_id is not None: object_data[current_obj_id]["lines"].append(line) # Track braces WITHIN this object for ch in line: if ch == '{': obj_brace_depth += 1 elif ch == '}': obj_brace_depth -= 1 # Check for isa inside the object if current_obj_type is None and 'isa = ' in stripped: isa_match = re.search(r'isa\s*=\s*([^;]+);', stripped) if isa_match: current_obj_type = isa_match.group(1).strip() object_data[current_obj_id]["type"] = current_obj_type # Track objects section brace depth for ch in line: if ch == '{': objects_brace_depth += 1 elif ch == '}': objects_brace_depth -= 1 # Object ends when brace depth returns to 0 if obj_brace_depth == 0: current_obj_id = None current_obj_type = None obj_brace_depth = 0 continue # Not currently in an object - just track objects section brace depth for ch in line: if ch == '{': objects_brace_depth += 1 elif ch == '}': objects_brace_depth -= 1 # Detect end of objects section (closing brace of objects dict) if objects_brace_depth == 0: in_objects_section = False continue # Extract key mappings project_config_list_id = None target_config_lists = {} # config_list_id -> target_name config_list_to_configs = {} # config_list_id -> [config_ids] config_details = {} # config_id -> {name, buildSettings, baseConfigRef} for obj_id, obj in object_data.items(): obj_type = obj.get("type", "") obj_lines = obj.get("lines", []) if obj_type == "PBXProject": # Find buildConfigurationList for l in obj_lines: match = re.search(r'buildConfigurationList\s*=\s*([0-9A-F]+)\s*/\*', l) if match: project_config_list_id = match.group(1) break elif obj_type == "PBXNativeTarget": target_name = None config_list_id = None for l in obj_lines: if target_name is None: match = re.search(r'name\s*=\s*([^;]+);', l.strip()) if match: target_name = match.group(1).strip().strip('"') if config_list_id is None: match = re.search(r'buildConfigurationList\s*=\s*([0-9A-F]+)\s*/\*', l) if match: config_list_id = match.group(1) if target_name and config_list_id: target_config_lists[config_list_id] = target_name elif obj_type == "XCConfigurationList": config_list_id = obj_id config_ids = [] in_build_configs = False for l in obj_lines: if 'buildConfigurations' in l: in_build_configs = True continue if in_build_configs: if ')' in l: # End of array in_build_configs = False # Find config IDs matches = re.findall(r'([0-9A-F]+)\s*/\*[^*]*\*/', l) for m in matches: if m not in config_ids: config_ids.append(m) if config_ids: config_list_to_configs[config_list_id] = config_ids elif obj_type == "XCBuildConfiguration": config_id = obj_id name = None base_config_ref = None build_settings = {} in_settings = False settings_brace_depth = 0 for l in obj_lines: stripped_l = l.strip() if name is None: match = re.search(r'name\s*=\s*([^;]+);', stripped_l) if match: name = match.group(1).strip().strip('"') if base_config_ref is None: match = re.search(r'baseConfigurationReference\s*=\s*[^/]*/\*\s*([^*]+)\s*\*/;', stripped_l) if match: base_config_ref = match.group(1).strip() if 'buildSettings' in stripped_l and '{' in stripped_l: in_settings = True settings_brace_depth = 1 continue if in_settings: for ch in l: if ch == '{': settings_brace_depth += 1 elif ch == '}': settings_brace_depth -= 1 if settings_brace_depth > 0: # Parse key = value; (supporting both quoted and unquoted) # Pattern: KEY = "value" or KEY = value match = re.search(r'([A-Z_][A-Z0-9_]*)\s*=\s*(.+?);', stripped_l) if match: key = match.group(1).strip() value = match.group(2).strip() # Clean up value if value.startswith('"') and value.endswith('"'): value = value[1:-1] build_settings[key] = value else: in_settings = False if name: config_details[config_id] = { "name": name, "buildSettings": build_settings, "baseConfigRef": base_config_ref } # Now map each config to its scope (project or target name) config_to_scope = {} # config_id -> ("project" or target_name, config_name) if project_config_list_id and project_config_list_id in config_list_to_configs: for config_id in config_list_to_configs[project_config_list_id]: config_name = config_details.get(config_id, {}).get("name", "Unknown") config_to_scope[config_id] = ("project", config_name) for config_list_id, target_name in target_config_lists.items(): if config_list_id in config_list_to_configs: for config_id in config_list_to_configs[config_list_id]: config_name = config_details.get(config_id, {}).get("name", "Unknown") config_to_scope[config_id] = (target_name, config_name) # Build final settings and line_map project_settings = {} target_settings = {} configurations = [] line_map = {} for config_id, details in config_details.items(): scope_info = config_to_scope.get(config_id, ("project", details.get("name", "Unknown"))) scope = scope_info[0] # "project" or target_name config_name = scope_info[1] build_settings = details.get("buildSettings", {}) base_config_ref = details.get("baseConfigRef", None) if scope == "project": for k, v in build_settings.items(): if k not in project_settings: project_settings[k] = v if config_name: configurations.append({"name": config_name, "file": base_config_ref}) else: # Target scope target_name = scope if target_name not in target_settings: target_settings[target_name] = {} for k, v in build_settings.items(): target_settings[target_name][k] = v # Build line_map for this config's settings # We need to find the actual lines where these settings appear # Use the object's lines to find the line numbers obj = object_data.get(config_id) if obj: obj_start = obj.get("start_line", 0) obj_lines = obj.get("lines", []) in_settings_block = False settings_brace_depth = 0 for line_idx, l in enumerate(obj_lines): actual_line = obj_start + line_idx stripped_l = l.strip() if 'buildSettings' in stripped_l and '{' in stripped_l: in_settings_block = True settings_brace_depth = 1 continue if in_settings_block: for ch in l: if ch == '{': settings_brace_depth += 1 elif ch == '}': settings_brace_depth -= 1 if settings_brace_depth > 0: match = re.search(r'([A-Z_][A-Z0-9_]*)\s*=\s*(.+?);', stripped_l) if match: key = match.group(1).strip() if key not in line_map: line_map[key] = [] line_map[key].append({ "line": actual_line + 1, # 1-indexed "scope": scope if scope != "project" else "project", "target": scope if scope != "project" else None, "config": config_name }) else: in_settings_block = False # Also check for FactoryConsumer.xcconfig has_factory_consumer = "FactoryConsumer.xcconfig" in content return { "project_settings": project_settings, "target_settings": target_settings, "configurations": configurations, "targets": [{"name": k} for k in target_settings.keys()], "format": "project.pbxproj (Legacy Property List)", "has_factory_consumer": has_factory_consumer }, line_map, True def parse_build_settings(proj_path): """Try project.xcproj first, fall back to project.pbxproj.""" # Try project.xcproj xcproj_bundle = find_xcodeproj_bundle(proj_path) if xcproj_bundle: xcproj_file = os.path.join(xcproj_bundle, "project.xcproj") if os.path.exists(xcproj_file): result, line_map, success = parse_project_xcproj(xcproj_bundle) if success and result: return result, line_map # Fall back to project.pbxproj xcproj_bundle = find_xcodeproj_bundle(proj_path) if xcproj_bundle: result, line_map, success = parse_project_pbxproj(xcproj_bundle) if success and result: return result, line_map return None, None # ── Swift Source Audit ──────────────────────────────────────────────────────── def scan_swift_files(root_path): swift_files = [] skip_dirs = {".build", "DerivedData", "Pods", ".git", "Framework_Stubs", "TestBinaries"} for root, dirs, files in os.walk(root_path): dirs[:] = [d for d in dirs if d not in skip_dirs] for f in files: if f.endswith(".swift"): swift_files.append(os.path.join(root, f)) return swift_files def is_authorized_stdio_process_file(filename, content): if filename.endswith("Transport.swift") or "Transport" in filename: return True if any(marker in content for marker in ("app-server", "--json", "readabilityHandler")): if "codex" in content.lower() or "mcp" in content.lower(): return True return False def extract_model_types(swift_files): """Two-pass extraction: Pass 1: Collect all @Model class names across the project. Pass 2: Index async methods/functions inside non-actor types, detecting isolation attributes. """ model_types = set() # Regex patterns for Pass 1 re_model = re.compile(r'@Model\s+(?:final\s+)?class\s+(\w+)') # ==== Pass 1: Collect @Model types ==== for file_path in swift_files: try: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() except Exception: continue for match in re_model.finditer(content): model_types.add(match.group(1)) # ==== Pass 2: Index async methods/functions ==== async_methods = [] # list of dicts with method details default_actor_isolation_main = False # Regex patterns for Pass 2 re_actor = re.compile(r'\bactor\s+(\w+)') re_class_struct_enum = re.compile(r'\b(class|struct|enum)\s+(\w+)') # Match async func declarations (async appears AFTER the parameter list in Swift) re_func = re.compile(r'(?:(?:public|internal|private|fileprivate|open)\s+)?(?:final\s+)?(?:static\s+)?(?:class\s+)?(?:override\s+)?func\s+(\w+)\s*\(([^)]*)\)\s*(?:async\s+)?(?:throws)?\s*(?:->\s*[^{]+)?\s*\{') re_nonisolated = re.compile(r'\bnonisolated\b') re_concurrent = re.compile(r'@concurrent\b') re_mainactor = re.compile(r'@MainActor\b') re_type_annotation = re.compile(r':\s*@MainActor\b') # For detecting attributes on the preceding line re_attr_line = re.compile(r'^\s*(@\w+(?:\([^)]*\))?\s*)+$') for file_path in swift_files: try: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() except Exception: continue lines = content.split('\n') # Track current type context current_type = None current_type_is_actor = False current_type_has_mainactor = False brace_depth = 0 type_brace_depth = 0 # Track previous line for attribute detection prev_stripped = "" for idx, line in enumerate(lines, 1): stripped = line.strip() if stripped.startswith("//") or "scout:ignore" in stripped: prev_stripped = stripped continue # Check for type declarations type_match = re_class_struct_enum.search(line) if type_match and brace_depth == 0: type_kind = type_match.group(1) type_name = type_match.group(2) current_type = type_name current_type_is_actor = (type_kind == "actor") or bool(re_actor.search(line)) current_type_has_mainactor = bool(re_mainactor.search(line)) or bool(re_type_annotation.search(line)) # Also check previous line for @MainActor attribute if not current_type_has_mainactor and re_mainactor.search(prev_stripped): current_type_has_mainactor = True type_brace_depth = 0 # Count opening braces on this line for ch in line: if ch == '{': brace_depth += 1 type_brace_depth += 1 elif ch == '}': brace_depth -= 1 type_brace_depth -= 1 prev_stripped = stripped continue # Update brace depth for ch in line: if ch == '{': brace_depth += 1 if current_type and type_brace_depth >= 0: type_brace_depth += 1 elif ch == '}': brace_depth -= 1 if current_type and type_brace_depth > 0: type_brace_depth -= 1 if brace_depth == 0: current_type = None current_type_is_actor = False current_type_has_mainactor = False # Check for async functions/methods (async appears after params in Swift) func_match = re_func.search(line) if func_match and current_type: # Skip actor methods entirely if current_type_is_actor: prev_stripped = stripped continue method_name = func_match.group(1) params = func_match.group(2) # Check if this method has explicit nonisolated or @concurrent on THIS line has_nonisolated = bool(re_nonisolated.search(line)) has_concurrent = bool(re_concurrent.search(line)) has_mainactor = bool(re_mainactor.search(line)) or current_type_has_mainactor # Also check previous line for attributes if not has_nonisolated and re_nonisolated.search(prev_stripped): has_nonisolated = True if not has_concurrent and re_concurrent.search(prev_stripped): has_concurrent = True if not has_mainactor and re_mainactor.search(prev_stripped): has_mainactor = True # Verify this is actually an async declaration (async appears after params) is_async = bool(re.search(r'\)\s*async\b', line)) or 'async' in line.split('func')[1].split('{')[0] if 'func' in line else False if not is_async: prev_stripped = stripped continue # Check if any parameter references a @Model type param_model_types = [] for model_type in model_types: # Match ModelType, [ModelType], [ModelType?], ModelType?, Dictionary, etc. patterns = [ rf'\b{re.escape(model_type)}\b', rf'\[\s*{re.escape(model_type)}\s*\]', rf'\[\s*{re.escape(model_type)}\s*\?\s*\]', rf'{re.escape(model_type)}\s*\?', rf'Dictionary\s*<\s*[^>]+,\s*{re.escape(model_type)}\s*>', rf'Array\s*<\s*{re.escape(model_type)}\s*>', ] for pat in patterns: if re.search(pat, params): param_model_types.append(model_type) break async_methods.append({ "type_name": current_type, "method_name": method_name, "is_static": "static" in line.split("func")[0], "has_nonisolated": has_nonisolated, "has_concurrent": has_concurrent, "has_mainactor": has_mainactor, "param_model_types": param_model_types, "file_path": file_path, "line": idx }) # Check for top-level async functions if not current_type and brace_depth == 0: func_match = re_func.search(line) if func_match: # Verify this is actually async (async appears after params) is_async = bool(re.search(r'\)\s*async\b', line)) if not is_async: prev_stripped = stripped continue method_name = func_match.group(1) params = func_match.group(2) has_nonisolated = bool(re_nonisolated.search(line)) has_concurrent = bool(re_concurrent.search(line)) has_mainactor = bool(re_mainactor.search(line)) # Also check previous line if not has_nonisolated and re_nonisolated.search(prev_stripped): has_nonisolated = True if not has_concurrent and re_concurrent.search(prev_stripped): has_concurrent = True if not has_mainactor and re_mainactor.search(prev_stripped): has_mainactor = True param_model_types = [] for model_type in model_types: patterns = [ rf'\b{re.escape(model_type)}\b', rf'\[\s*{re.escape(model_type)}\s*\]', rf'\[\s*{re.escape(model_type)}\s*\?\s*\]', rf'{re.escape(model_type)}\s*\?', ] for pat in patterns: if re.search(pat, params): param_model_types.append(model_type) break async_methods.append({ "type_name": "", "method_name": method_name, "is_static": False, "has_nonisolated": has_nonisolated, "has_concurrent": has_concurrent, "has_mainactor": has_mainactor, "param_model_types": param_model_types, "file_path": file_path, "line": idx }) prev_stripped = stripped return model_types, async_methods def detect_implicit_mainactor_async_methods(model_types, async_methods, default_actor_isolation_main): """Mark methods as implicitly @MainActor when default actor isolation is MainActor.""" for method in async_methods: # Actor methods are already isolated if method["type_name"] == "": continue # Explicit nonisolated or @concurrent means NOT @MainActor if method["has_nonisolated"] or method["has_concurrent"]: method["implicit_mainactor"] = False elif default_actor_isolation_main and not method["has_mainactor"]: # Non-actor async method without explicit isolation -> implicitly @MainActor method["implicit_mainactor"] = True else: method["implicit_mainactor"] = method["has_mainactor"] return async_methods def audit_cross_actor_sends(swift_files, model_types, async_methods, default_actor_isolation_main, project_root): """Pass 2: Check caller sites in nonisolated contexts for cross-actor sends.""" findings = [] # Build lookup for ALL async overloads keyed by TypeName.methodName # Track whether each overload has nonisolated/@concurrent or is implicitly @MainActor method_overloads = {} # key -> {"has_nonisolated": bool, "has_concurrent": bool, "implicit_mainactor_methods": [], "all_param_model_types": set} for method in async_methods: key = f"{method['type_name']}.{method['method_name']}" if key not in method_overloads: method_overloads[key] = { "has_nonisolated": False, "has_concurrent": False, "implicit_mainactor_methods": [], "all_param_model_types": set() } overload = method_overloads[key] if method["has_nonisolated"]: overload["has_nonisolated"] = True if method["has_concurrent"]: overload["has_concurrent"] = True if method["implicit_mainactor"] and method["param_model_types"]: overload["implicit_mainactor_methods"].append(method) overload["all_param_model_types"].update(method["param_model_types"]) # Updated regex to match nonisolated with any modifiers in any order before func # nonisolated can appear with: public, internal, private, fileprivate, open, final, static, class, override, @concurrent, @discardableResult re_nonisolated_func = re.compile( r'\bnonisolated\b\s*(?:(?:public|internal|private|fileprivate|open|final|static|class|override)\s+)*' r'(?:@concurrent\s+)?' r'(?:@discardableResult\s+)?' r'(?:async\s+)?' r'func\s+(\w+)' ) re_await_call = re.compile(r'\bawait\s+(\w+(?:\.\w+)?)\s*\(') re_var_decl = re.compile(r'(?:let|var)\s+(\w+)\s*:\s*([^=]+)\s*=') re_var_infer = re.compile(r'(?:let|var)\s+(\w+)\s*=\s*([^;]+)') # Regex to match for-loop patterns: for x in collection, for (x, y) in collection re_for_loop = re.compile(r'\bfor\s+(?:\(([^)]+)\)|(\w+))\s+in\s+(\w+)') for file_path in swift_files: try: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() except Exception: continue lines = content.split('\n') in_nonisolated = False nonisolated_depth = 0 awaiting_opening_brace = False # Track if we've seen nonisolated func but not yet entered its body tracked_vars = {} # var_name -> model_type(s) it holds for idx, line in enumerate(lines, 1): stripped = line.strip() if stripped.startswith("//") or "scout:ignore" in stripped: continue # Detect entry into nonisolated function/method nonisolated_match = re_nonisolated_func.search(line) if nonisolated_match and nonisolated_depth == 0: in_nonisolated = True awaiting_opening_brace = True nonisolated_depth = 0 # Start at 0, will increment when we see { tracked_vars = {} # Count braces on this line to see if opening brace is on same line for ch in line: if ch == '{': awaiting_opening_brace = False nonisolated_depth += 1 elif ch == '}': nonisolated_depth -= 1 continue if in_nonisolated: # If still awaiting opening brace, check this line if awaiting_opening_brace: for ch in line: if ch == '{': awaiting_opening_brace = False nonisolated_depth += 1 elif ch == '}': nonisolated_depth -= 1 if not awaiting_opening_brace: # Track brace depth normally for ch in line: if ch == '{': nonisolated_depth += 1 elif ch == '}': nonisolated_depth -= 1 if nonisolated_depth <= 0: in_nonisolated = False tracked_vars = {} continue # Track variable declarations that might hold @Model types var_match = re_var_decl.search(line) if var_match: var_name = var_match.group(1) var_type = var_match.group(2).strip() # Check if type references any @Model type using word boundary for model_type in model_types: if re.search(rf'\b{re.escape(model_type)}\b', var_type): tracked_vars[var_name] = model_type break var_match = re_var_infer.search(line) if var_match: var_name = var_match.group(1) var_expr = var_match.group(2).strip() # Check if expression creates/returns a @Model type using word boundary for model_type in model_types: if re.search(rf'\b{re.escape(model_type)}\b', var_expr): tracked_vars[var_name] = model_type break # Track for-loop variables - propagate @Model from collection to loop variable(s) for_match = re_for_loop.search(line) if for_match: # Check tuple form: for (v1, v2) in collection if for_match.group(1): tuple_vars = for_match.group(1) collection_var = for_match.group(3) # Check single var form: for v in collection else: tuple_vars = for_match.group(2) collection_var = for_match.group(3) # If the collection is a tracked @Model variable, propagate to loop variable(s) if collection_var in tracked_vars: model_type = tracked_vars[collection_var] # Handle tuple vars: split by comma if ',' in tuple_vars: for v in tuple_vars.split(','): v = v.strip() tracked_vars[v] = model_type else: tracked_vars[tuple_vars] = model_type # Check for await calls to implicitly @MainActor methods with @Model args await_matches = re_await_call.finditer(line) for match in await_matches: call_expr = match.group(1) # Match against exact TypeName.methodName key # call_expr could be "TypeName.methodName" or just "methodName" (which would be self.methodName) for method_key, overload in method_overloads.items(): if not overload["implicit_mainactor_methods"]: continue method_short_name = overload["implicit_mainactor_methods"][0]['method_name'] type_name = overload["implicit_mainactor_methods"][0]['type_name'] # Check if call_expr matches this method key # Case 1: Qualified call like TypeName.methodName if call_expr == method_key: pass # matches exactly # Case 2: Unqualified call like methodName - match if it's the short name and we're in the type context # We don't have full type context here, so we match on method name with word boundary # but only if it's a qualified call that matches, or if the call expression is just the method name elif call_expr == method_short_name: # For unqualified calls, we can't be certain of the type # But we'll match and let the other checks filter pass else: continue # Check if any argument is a tracked @Model variable has_model_arg = False arg_model_types = [] # Check tracked vars used as arguments (word boundary match) for var_name, model_type in tracked_vars.items(): if re.search(rf'\b{re.escape(var_name)}\b', line): has_model_arg = True arg_model_types.append(model_type) # Check for inline @Model collections for model_type in model_types: patterns = [ rf'\[\s*{re.escape(model_type)}\s*\]', rf'{re.escape(model_type)}\s*\(', ] for pat in patterns: if re.search(pat, line): has_model_arg = True arg_model_types.append(model_type) # REQUIRE has_model_arg - do NOT blindly flag based on param_model_types if has_model_arg: # If there's a nonisolated or @concurrent overload AND no model arg, skip # But since we require has_model_arg, this check is for completeness if (overload["has_nonisolated"] or overload["has_concurrent"]) and not has_model_arg: continue # Found a cross-actor send! method = overload["implicit_mainactor_methods"][0] # Compute relative path from project_root rel_path = os.path.relpath(file_path, project_root) findings.append({ "file": rel_path, "line": idx, "category": "Swift 6 Cross-Actor Send (Default MainActor)", "description": ( f"Call to implicitly `@MainActor` async method `{method_key}` from `nonisolated` context " f"passes non-`Sendable` SwiftData `@Model` instance(s) " f"({', '.join(set(arg_model_types))}). " f"Under `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`, the target async helper " f"defaults to `@MainActor` isolation. Sending `@Model` types (which are not `Sendable`) " f"across this actor boundary will trigger a Swift 6 data-race error once " f"`SWIFT_VERSION = 5.0` masking is removed. " f"Fix: mark the helper `nonisolated` (if thread-safe) or pass `Sendable` value-type DTOs." ), "code": stripped }) return findings def audit_file(file_path, project_root, proj_name, model_types, async_methods, default_actor_isolation_main): relative_path = os.path.relpath(file_path, project_root) findings = [] filename = os.path.basename(file_path) try: with open(file_path, 'r', encoding='utf-8') as f: lines = f.readlines() except Exception: return relative_path, findings content = "".join(lines) stdio_process_exempt = is_authorized_stdio_process_file(filename, content) is_factorykit = (proj_name.lower() == "factorykit") is_streamline = (proj_name.lower() == "streamlinefoundation") re_optional_existential = re.compile(r'\(\s*(some|any)\s+[^)]+\)\?') re_unchecked_sendable = re.compile(r'@unchecked\s+Sendable') re_observable_object = re.compile(r':\s*ObservableObject\b|,\s*ObservableObject\b') re_published = re.compile(r'@Published\b') re_state_object = re.compile(r'@StateObject\b') re_observed_object = re.compile(r'@ObservedObject\b') re_env_object = re.compile(r'@EnvironmentObject\b|\.environmentObject\s*\(') re_process_init = re.compile(r'\bProcess\s*\(\s*\)') re_dist_nc = re.compile(r'\bDistributedNotificationCenter\.default\b') re_gcd_main = re.compile(r'\bDispatchQueue\.main\.async(?:After)?\b') re_fg_color = re.compile(r'\.foregroundColor\s*\(') re_corner_radius = re.compile(r'\.cornerRadius\s*\(') re_nav_view = re.compile(r'\bNavigationView\s*[\{\(]') re_env_key = re.compile(r':\s*EnvironmentKey\b') re_xctest = re.compile(r'^\s*import\s+XCTest\b') re_default_store = re.compile(r'["\']default\.store["\']') # macOS 27 deprecation: NSItemProvider.loadItem(forTypeIdentifier:options:completionHandler:) # Matches both single-line: provider.loadItem(forTypeIdentifier: ...) # and multi-line where forTypeIdentifier: appears on next non-comment line inside call re_loaditem_deprecated = re.compile(r'\.?loadItem\s*\(') for idx, line in enumerate(lines, 1): stripped = line.strip() if stripped.startswith("//") or "scout:ignore" in stripped: continue # --- macOS 27 Deprecation: NSItemProvider.loadItem(forTypeIdentifier:...) --- # Detect loadItem( calls where the argument list begins with forTypeIdentifier: # Support both single-line and multi-line (forTypeIdentifier: on following line) if re_loaditem_deprecated.search(line): # Skip loadFileRepresentation and loadDataRepresentation (not deprecated) if re.search(r'\bloadFileRepresentation\s*\(', line) or re.search(r'\bloadDataRepresentation\s*\(', line): pass else: # Check if this line or the next non-comment non-empty line has forTypeIdentifier: has_for_type_id = bool(re.search(r'forTypeIdentifier\s*:', line)) if not has_for_type_id: # Peek ahead to find the next non-comment, non-empty line for look_idx in range(idx, min(idx + 5, len(lines))): look_line = lines[look_idx].strip() if not look_line or look_line.startswith("//"): continue if re.search(r'forTypeIdentifier\s*:', look_line): has_for_type_id = True break # Stop if we hit a closing paren or new statement if look_line.endswith(")") or look_line.startswith(("let ", "var ", "if ", "guard ", "return ", "throw ")): break if has_for_type_id: findings.append({ "line": idx, "category": "macOS 27 Deprecation", "description": ( "`NSItemProvider.loadItem(forTypeIdentifier:options:completionHandler:)` was deprecated in macOS 27.0. " "Use `loadObject(ofClass:completionHandler:)` for type-safe object loading, " "`loadFileRepresentation(forTypeIdentifier:completionHandler:)` for file representations, " "`loadDataRepresentation(forTypeIdentifier:completionHandler:)` for data representations, " "or adopt Swift's `Transferable` protocol for modern drag-and-drop/pasteboard workflows." ), "code": stripped }) if re_optional_existential.search(line): findings.append({ "line": idx, "category": "Swift 6.4 Ergonomics (SE-0521)", "description": "Parenthesized optional existential/opaque type. Swift 6.4 supports natural unparenthesized syntax (`some View?` / `any Protocol?`).", "code": stripped }) if re_unchecked_sendable.search(line): findings.append({ "line": idx, "category": "Concurrency Escape Hatch", "description": "Explicit `@unchecked Sendable` detected. Replace with proper actor isolation, `@Sendable` closures, or Swift 6.4 concurrency.", "code": stripped }) if re_observable_object.search(line): findings.append({ "line": idx, "category": "State Architecture", "description": "Conforms to legacy `ObservableObject`. Modernize to the `@Observable` macro.", "code": stripped }) if re_published.search(line): findings.append({ "line": idx, "category": "State Architecture", "description": "Legacy `@Published` wrapper detected. Standard stored properties work natively with `@Observable`.", "code": stripped }) if re_state_object.search(line) or re_observed_object.search(line): findings.append({ "line": idx, "category": "State Architecture", "description": "Legacy `@StateObject` or `@ObservedObject` detected. Modernize to `@State` or `@Bindable` with `@Observable`.", "code": stripped }) if re_env_object.search(line): findings.append({ "line": idx, "category": "State Architecture", "description": "Legacy `@EnvironmentObject` or `.environmentObject(...)` detected. Modernize to `@Environment(Type.self)` and `.environment(...)`.", "code": stripped }) if not is_factorykit and re_dist_nc.search(line): findings.append({ "line": idx, "category": "Factory IPC Standard", "description": "Raw `DistributedNotificationCenter.default` usage detected. Use `FactoryKit` helpers (`NotificationCenter.postDistributed` / `addDistributedObserver`).", "code": stripped }) if re_gcd_main.search(line): findings.append({ "line": idx, "category": "Swift 6 Concurrency", "description": "Legacy `DispatchQueue.main.async` detected. Modernize to Swift structured concurrency (`Task { @MainActor in }`).", "code": stripped }) if re_fg_color.search(line): findings.append({ "line": idx, "category": "Modern SwiftUI API", "description": "Deprecated `.foregroundColor(...)` modifier. Modernize to `.foregroundStyle(...)`.", "code": stripped }) if re_corner_radius.search(line): findings.append({ "line": idx, "category": "Modern SwiftUI API", "description": "Deprecated `.cornerRadius(...)` modifier. Modernize to `.clipShape(.rect(cornerRadius: ...))`.", "code": stripped }) if re_nav_view.search(line): findings.append({ "line": idx, "category": "Modern SwiftUI Navigation", "description": "Legacy `NavigationView` detected. Modernize to `NavigationStack` or `NavigationSplitView`.", "code": stripped }) if re_env_key.search(line): findings.append({ "line": idx, "category": "Modern SwiftUI Environment", "description": "Boilerplate `EnvironmentKey` conformance detected. Modernize using the `@Entry` macro inside `EnvironmentValues`.", "code": stripped }) if re_xctest.search(line): findings.append({ "line": idx, "category": "Swift Testing", "description": "Legacy `XCTest` import detected. Modernize to `import Testing` (`@Suite`, `@Test`, `#expect`).", "code": stripped }) if re_default_store.search(line): findings.append({ "line": idx, "category": "SwiftData Isolation", "description": "Hardcoded `default.store` detected. Resolve isolated SQLite URLs via `FactoryPaths.databaseURL(for:storeName:)`.", "code": stripped }) if re_process_init.search(line) and not is_streamline and not stdio_process_exempt: findings.append({ "line": idx, "category": "Process Execution", "description": "Direct Foundation `Process()` invocation outside an authorized stdio transport/runner. Prefer `StreamlineFoundation.runCommand`, `runSwift`, or `runPython`.", "code": stripped }) # Teardown Hygiene: Detect locally instantiated resources with async teardown called outside defer cleaned_content = re.sub(r'func\s+(stop|disconnect|teardown|close|cleanup)\b[^{]*\{.*?\n \}', '', content, flags=re.DOTALL) teardown_methods = ["stop", "disconnect", "teardown", "close", "cleanup"] for instance_match in re.finditer(r'(?:let|var)\s+(\w+)\s*=\s*\w*(Client|Session|Transport|Connection|Runner)\(', content): instance_name = instance_match.group(1) for m in teardown_methods: call_pattern = rf'await\s+{re.escape(instance_name)}\.{m}\(' if re.search(call_pattern, cleaned_content): defer_pattern = rf'defer\s*\{{[^}}]*await\s+{re.escape(instance_name)}\.{m}\(' if not re.search(defer_pattern, content): findings.append({ "line": 1, "category": "Teardown Hygiene (SE-0493)", "description": f"Local resource `{instance_name}` has manual `await {instance_name}.{m}()` teardown outside of a `defer` block. Swift 6.4 permits `await` directly inside `defer`.", "code": f"await {instance_name}.{m}()" }) break return relative_path, findings # ── Main ────────────────────────────────────────────────────────────────────── def main(): parser = argparse.ArgumentParser(description="Sidecar Modernization Scout") parser.add_argument("--project_target", default="Sidecar", nargs="?", help="Target project name in Factory Registry (defaults to Sidecar)") parser.add_argument("--target_agent", default="", nargs="?", help="Optional agent name to notify with the modernization report (auto-detected if omitted)") parser.add_argument("--notify_agent", default="true", nargs="?", help="Dispatch inbound alert to agent (true/false)") args = parser.parse_args() target_proj = args.project_target.strip() if (args.project_target and args.project_target.strip()) else "Sidecar" target_agt = args.target_agent.strip() if (args.target_agent and args.target_agent.strip()) else "" should_notify = str(args.notify_agent).strip().lower() in ("true", "1", "yes") proj_name, proj_path, owning_agent, proj_type, workspace_uuid = resolve_project_and_agent(target_proj, target_agt) if not proj_name or not proj_path or not os.path.exists(proj_path): print(f"❌ Error: Unable to resolve project path for '{target_proj}'.") sys.exit(1) # ── Build Settings Audit ──────────────────────────────────────────────── build_settings_result, line_map = parse_build_settings(proj_path) build_settings_findings = [] default_actor_isolation_main = False project_format = "Unknown" has_factory_consumer = False if build_settings_result: project_format = build_settings_result.get("format", "Unknown") has_factory_consumer = build_settings_result.get("has_factory_consumer", False) project_settings = build_settings_result.get("project_settings", {}) target_settings = build_settings_result.get("target_settings", {}) # Check SWIFT_DEFAULT_ACTOR_ISOLATION if project_settings.get("SWIFT_DEFAULT_ACTOR_ISOLATION") == "MainActor": default_actor_isolation_main = True for target_name, settings in target_settings.items(): if settings.get("SWIFT_DEFAULT_ACTOR_ISOLATION") == "MainActor": default_actor_isolation_main = True # Check SWIFT_VERSION (Hidden Swift 5 Mask) swift_version_project = project_settings.get("SWIFT_VERSION") if swift_version_project: try: major = int(swift_version_project.split('.')[0]) if major < 6: # Find line_map entry for project scope line_info = None if line_map and "SWIFT_VERSION" in line_map: for entry in line_map["SWIFT_VERSION"]: if entry.get("scope") == "project": line_info = entry break if not line_info: line_info = {"line": "?", "scope": "project"} fc_text = f"With `FactoryConsumer.xcconfig` present (which sets `SWIFT_VERSION = 6.0`), this setting overrides the xcconfig and silently prevents Swift 6 diagnostics from surfacing." if has_factory_consumer else "This setting masks Swift 6 concurrency/data-race errors from surfacing." build_settings_findings.append({ "file": "project.xcproj" if "JSON" in project_format else "project.pbxproj", "line": line_info.get("line", "?"), "category": "Build Settings / Swift 6 Mask", "description": f"Project-level `SWIFT_VERSION = {swift_version_project}` masks Swift 6 concurrency/data-race errors. {fc_text} Remove or raise to `6.0`.", "code": f"SWIFT_VERSION = {swift_version_project}" }) except: pass for target_name, settings in target_settings.items(): swift_version = settings.get("SWIFT_VERSION") if swift_version: try: major = int(swift_version.split('.')[0]) if major < 6: # Find line_map entry for this target line_info = None if line_map and "SWIFT_VERSION" in line_map: for entry in line_map["SWIFT_VERSION"]: if entry.get("scope") == "target" and entry.get("target") == target_name: line_info = entry break # Also check for "targets" scope (xcproj format) if entry.get("scope") == "targets" and entry.get("target") == target_name: line_info = entry break if not line_info: line_info = {"line": "?", "scope": f"target:{target_name}"} fc_text = f"With `FactoryConsumer.xcconfig` present (which sets `SWIFT_VERSION = 6.0`), this setting overrides the xcconfig and silently prevents Swift 6 diagnostics from surfacing." if has_factory_consumer else "This setting masks Swift 6 concurrency/data-race errors from surfacing." build_settings_findings.append({ "file": "project.xcproj" if "JSON" in project_format else "project.pbxproj", "line": line_info.get("line", "?"), "category": "Build Settings / Swift 6 Mask", "description": f"Target `{target_name}` `SWIFT_VERSION = {swift_version}` masks Swift 6 concurrency/data-race errors. {fc_text} Remove or raise to `6.0`.", "code": f"SWIFT_VERSION = {swift_version}" }) except: pass # Check MACOSX_DEPLOYMENT_TARGET (Stale Deployment Target) if proj_type == "app" and not workspace_uuid: # standalone app # Project level proj_deploy = project_settings.get("MACOSX_DEPLOYMENT_TARGET") if proj_deploy: try: version_tuple = tuple(map(int, proj_deploy.split('.'))) if version_tuple < (27, 2): # Find line_map entry for project scope line_info = None if line_map and "MACOSX_DEPLOYMENT_TARGET" in line_map: for entry in line_map["MACOSX_DEPLOYMENT_TARGET"]: if entry.get("scope") == "project": line_info = entry break if not line_info: line_info = {"line": "?"} build_settings_findings.append({ "file": "project.xcproj" if "JSON" in project_format else "project.pbxproj", "line": line_info.get("line", "?"), "category": "Build Settings / Deployment Target", "description": f"Project-level `MACOSX_DEPLOYMENT_TARGET = {proj_deploy}` is below the Xcode 27.2 baseline (27.2). " f"Recommend aligning to `27.2` at the Project scope.", "code": f"MACOSX_DEPLOYMENT_TARGET = {proj_deploy}" }) except: pass # Target level for target_name, settings in target_settings.items(): target_deploy = settings.get("MACOSX_DEPLOYMENT_TARGET") if target_deploy: try: version_tuple = tuple(map(int, target_deploy.split('.'))) if version_tuple < (27, 2): # Find line_map entry for this target line_info = None if line_map and "MACOSX_DEPLOYMENT_TARGET" in line_map: for entry in line_map["MACOSX_DEPLOYMENT_TARGET"]: if entry.get("scope") == "target" and entry.get("target") == target_name: line_info = entry break # Also check for "targets" scope (xcproj format) if entry.get("scope") == "targets" and entry.get("target") == target_name: line_info = entry break if not line_info: line_info = {"line": "?"} build_settings_findings.append({ "file": "project.xcproj" if "JSON" in project_format else "project.pbxproj", "line": line_info.get("line", "?"), "category": "Build Settings / Deployment Target", "description": f"Target `{target_name}` `MACOSX_DEPLOYMENT_TARGET = {target_deploy}` is below the Xcode 27.2 baseline (27.2). " f"Recommend aligning to `27.2` at the Target scope.", "code": f"MACOSX_DEPLOYMENT_TARGET = {target_deploy}" }) except: pass # ── Swift Source Audit ────────────────────────────────────────────────── swift_files = scan_swift_files(proj_path) total_files = len(swift_files) all_findings = {} category_counts = Counter() total_opportunities = 0 # Pass 1: Extract @Model types and async methods model_types, async_methods = extract_model_types(swift_files) async_methods = detect_implicit_mainactor_async_methods(model_types, async_methods, default_actor_isolation_main) # Pass 2: Cross-actor send detection cross_actor_findings = audit_cross_actor_sends(swift_files, model_types, async_methods, default_actor_isolation_main, proj_path) # Group cross-actor findings by file cross_actor_by_file = {} for finding in cross_actor_findings: rel_file = finding["file"] if rel_file not in cross_actor_by_file: cross_actor_by_file[rel_file] = [] cross_actor_by_file[rel_file].append({ "line": finding["line"], "category": finding["category"], "description": finding["description"], "code": finding["code"] }) # Regular audit for f in swift_files: rel_path, findings = audit_file(f, proj_path, proj_name, model_types, async_methods, default_actor_isolation_main) if findings: all_findings[rel_path] = findings total_opportunities += len(findings) for item in findings: category_counts[item["category"]] += 1 # Merge cross-actor findings for rel_path, ca_findings in cross_actor_by_file.items(): if rel_path not in all_findings: all_findings[rel_path] = [] all_findings[rel_path].extend(ca_findings) total_opportunities += len(ca_findings) for item in ca_findings: category_counts[item["category"]] += 1 # Add build settings findings for bs_finding in build_settings_findings: rel_file = bs_finding["file"] if rel_file not in all_findings: all_findings[rel_file] = [] all_findings[rel_file].append({ "line": bs_finding["line"], "category": bs_finding["category"], "description": bs_finding["description"], "code": bs_finding["code"] }) total_opportunities += 1 category_counts[bs_finding["category"]] += 1 agent_base_name = owning_agent.split()[0] if owning_agent else "Zack" clean_proj_name = proj_name.replace(" ", "_") now_str = datetime.now().strftime("%B %d, %Y at %I:%M %p") report_lines = [ f"# 🛠️ Modernization Audit: {proj_name}", f"**Target Workspace:** `{proj_name}`", f"**Project Type:** `{proj_type}`", f"**Workspace UUID:** `{workspace_uuid or 'N/A (standalone)'}`", f"**Project Format:** `{project_format}`", f"**FactoryConsumer.xcconfig:** `{'Configured' if has_factory_consumer else 'Not Detected'}`", f"**Default Actor Isolation:** `{'MainActor' if default_actor_isolation_main else 'None (legacy)'}`", f"**Governing Agent:** `{owning_agent}`", f"**Scan Timestamp:** {now_str}", "", "> **Toolchain Context:** Apple and *The Factory* have officially promoted the development baseline to **Xcode 27.2 and Swift 6.4**. This audit identifies opportunities to eliminate obsolete concurrency escape hatches, adopt async `defer` teardown hygiene, migrate to modern Observation/SwiftUI/FactoryKit APIs, standardize process execution, **audit `.xcodeproj` build settings (`project.xcproj` JSON or `project.pbxproj` Legacy) for `SWIFT_VERSION` masks and stale deployment targets**, and **detect Swift 6 cross-actor `@Model` sends under implicit `@MainActor` isolation**. This report is read-only; use these findings to formulate your refactoring blueprints.", "", "## Executive Summary", f"- **Files Scanned:** {total_files} Swift source files", f"- **Files with Opportunities:** {len(all_findings)}", f"- **Total Modernization Flags:** {total_opportunities}", ] if category_counts: breakdown = ", ".join(f"{cat}: {count}" for cat, count in category_counts.most_common()) report_lines.append(f"- **Breakdown:** {breakdown}") report_lines.append("") if not all_findings: report_lines.append("🎉 **Zero modernization gaps detected.** The codebase fully adheres to current Swift 6.4 and Factory standards!") else: report_lines.append("## Detailed File Findings") for rel_path in sorted(all_findings.keys()): items = all_findings[rel_path] report_lines.append(f"### 📄 `{rel_path}` ({len(items)} items)") for item in items: report_lines.append(f"- **Line {item['line']}** · *[{item['category']}]*") report_lines.append(f" - **Issue:** {item['description']}") report_lines.append(f" - **Code:** `{item['code']}`") report_lines.append("") report_lines.append("## Recommended Agent Action Items") report_lines.append("1. **Build Settings — Swift Version Mask:** Remove any `SWIFT_VERSION = 5.x` at Project or Target scope. `FactoryConsumer.xcconfig` already sets `SWIFT_VERSION = 6.0`; the local setting overrides it and hides real Swift 6 concurrency/data-race errors.") report_lines.append("2. **Build Settings — Deployment Target:** For standalone apps (`type == app` with no `workspace_uuid`), raise both Project-level and Target-level `MACOSX_DEPLOYMENT_TARGET` to `27.2` (Xcode 27.2 baseline).") report_lines.append("3. **Swift 6 Cross-Actor Sends:** Under `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`, any `nonisolated` context sending SwiftData `@Model` instances/collections to implicitly `@MainActor` async helpers will error at `SWIFT_VERSION = 6.0`. Fix by marking the helper `nonisolated` (if thread-safe) or passing `Sendable` value-type DTOs across the actor boundary.") report_lines.append("4. **State & Observation:** Replace `ObservableObject`, `@Published`, `@StateObject`, `@ObservedObject`, and `@EnvironmentObject` with `@Observable`, `@State`, `@Bindable`, and `@Environment`.") report_lines.append("5. **Concurrency & Teardown Hygiene:** Replace `@unchecked Sendable` and `DispatchQueue.main.async` with Swift 6.4 structured concurrency, and move local async teardown calls into `defer { await ... }`.") report_lines.append("6. **Modern SwiftUI & Factory Standards:** Replace `.foregroundColor`, `.cornerRadius`, `NavigationView`, `EnvironmentKey`, raw `DistributedNotificationCenter.default()`, and `XCTest` with modern equivalents. **macOS 27 Deprecations:** Migrate `NSItemProvider.loadItem(forTypeIdentifier:...)` to `loadObject(ofClass:)`, `loadFileRepresentation`, `loadDataRepresentation`, or Swift `Transferable`.") report_text = "\n".join(report_lines) agent_context_dir = os.path.join(CONTEXT_ROOT, agent_base_name) os.makedirs(agent_context_dir, exist_ok=True) report_filename = f"Modernization_Report_{clean_proj_name}.md" report_path = os.path.join(agent_context_dir, report_filename) with open(report_path, "w", encoding="utf-8") as f: f.write(report_text) post_distributed_notification("com.higginsoft.codecustodian.deploy_context") report_url = f"https://thegroovypanda.com/context/{agent_base_name}/{report_filename}" if should_notify: time.sleep(1.5) if total_opportunities == 0: summary_tail = "Zero modernization gaps detected — codebase is clean on Swift 6.4." else: top_cats = ", ".join(f"{cat} ({count})" for cat, count in category_counts.most_common(3)) summary_tail = f"{total_opportunities} modernization opportunities flagged ({top_cats})." alert_message = ( f"🚀 Toolchain Baseline: Xcode 27.2 & Swift 6.4 Active across The Factory.\n" f"📋 Modernization Scout: Audit complete for {proj_name}. {summary_tail}\n" f"Review read-only report: {report_url}" ) post_distributed_notification("com.higginsoft.factory.agent.inbound", { "target_agent": owning_agent, "message": alert_message }) print(f"✅ Modernization Audit Complete for {proj_name}") print(f"📊 Files Scanned: {total_files} | Modernization Flags: {total_opportunities}") if category_counts: print("🏷️ Categories: " + ", ".join(f"{cat}={count}" for cat, count in category_counts.most_common())) print(f"📄 Report Saved: {report_path}") print(f"🌐 Cloud URL: {report_url}") if should_notify: print(f"📢 Inbound alert dispatched to: {owning_agent}") else: print("🤫 Agent notification bypassed (private audit mode)") if __name__ == "__main__": main()