{"repo": "Cranot/roam-code", "n_pairs": 200, "version": "v2_function_scoped", "contexts": {"tests/test_cut.py::239": {"resolved_imports": ["src/roam/commands/cmd_cut.py"], "used_names": [], "enclosing_function": "test_cut_boundary_fields", "extracted_code": "", "n_imports_parsed": 9, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_bus_factor.py::264": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_json_directories_have_expected_fields", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_conventions_cmd.py::221": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_exits_zero", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_migration_safety.py::239": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_json_summary_has_by_confidence", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_attest.py::352": {"resolved_imports": [], "used_names": ["_content_hash"], "enclosing_function": "test_content_hash_deterministic", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_anomaly.py::48": {"resolved_imports": ["src/roam/graph/anomaly.py"], "used_names": ["modified_z_score"], "enclosing_function": "test_known_anomaly_detected", "extracted_code": "# Source: src/roam/graph/anomaly.py\ndef modified_z_score(values: list[float | int], threshold: float = 3.5) -> list[dict]:\n \"\"\"Detect point anomalies using Modified Z-Score (MAD-based).\n\n More robust than standard Z-score for small datasets because it uses\n Median Absolute Deviation instead of standard deviation.\n\n Returns list of dicts with keys: index, value, z_score, is_anomaly.\n Requires n >= 5. Returns empty list if insufficient data.\n \"\"\"\n if len(values) < 5:\n return []\n\n med = median(values)\n mad_val = _mad(values)\n\n results: list[dict] = []\n for i, v in enumerate(values):\n if mad_val == 0.0:\n # All deviations from median are zero (or nearly); z-score is 0\n # unless the point itself differs from the median.\n z = 0.0 if v == med else float(\"inf\")\n else:\n # 0.6745 is the 0.75th quantile of the standard normal distribution.\n # Scaling by it makes the MAD consistent with std-dev for normal data.\n z = 0.6745 * (v - med) / mad_val\n results.append(\n {\n \"index\": i,\n \"value\": v,\n \"z_score\": round(z, 4) if math.isfinite(z) else z,\n \"is_anomaly\": abs(z) > threshold,\n }\n )\n return results", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 1320}, "tests/test_codeowners.py::361": {"resolved_imports": ["src/roam/cli.py"], "used_names": ["CliRunner", "cli", "git_init", "index_in_process"], "enclosing_function": "test_no_codeowners_file", "extracted_code": "# Source: src/roam/cli.py\ndef cli(ctx, json_mode, compact, agent, sarif_mode, budget, include_excluded, detail):\n \"\"\"Roam: Codebase comprehension tool.\"\"\"\n if agent and sarif_mode:\n raise click.UsageError(\"--agent cannot be combined with --sarif\")\n\n # Agent mode is optimized for CLI-invoked sub-agents:\n # - forces JSON for machine parsing\n # - uses compact envelope to reduce token overhead\n # - defaults to 500-token budget unless user overrides with --budget\n if agent:\n json_mode = True\n compact = True\n if budget <= 0:\n budget = 500\n\n ctx.ensure_object(dict)\n ctx.obj[\"json\"] = json_mode\n ctx.obj[\"compact\"] = compact\n ctx.obj[\"agent\"] = agent\n ctx.obj[\"sarif\"] = sarif_mode\n ctx.obj[\"budget\"] = budget\n ctx.obj[\"include_excluded\"] = include_excluded\n ctx.obj[\"detail\"] = detail", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 868}, "tests/test_context_propagation.py::289": {"resolved_imports": ["src/roam/graph/propagation.py"], "used_names": ["callee_chain"], "enclosing_function": "test_linear_chain_depths", "extracted_code": "# Source: src/roam/graph/propagation.py\ndef callee_chain(\n G,\n node: int,\n max_depth: int = 3,\n) -> List[Tuple[int, int]]:\n \"\"\"Return ordered list of transitive callees with their BFS depth.\n\n BFS from *node* through outgoing (callee) edges up to *max_depth*.\n Cycles are handled via a visited set — each callee is reported at\n the shallowest depth it is reached.\n\n Parameters\n ----------\n G:\n Directed call graph (caller -> callee edges).\n node:\n Starting symbol node ID.\n max_depth:\n Maximum callee depth to traverse. Defaults to 3.\n\n Returns\n -------\n list of (node_id, depth) tuples\n Ordered by BFS level (shallow callees first), then by node ID for\n determinism. The seed node itself is NOT included.\n \"\"\"\n if node not in G:\n return []\n\n visited: Dict[int, int] = {node: 0}\n queue: deque[Tuple[int, int]] = deque([(node, 0)])\n result: List[Tuple[int, int]] = []\n\n while queue:\n current, depth = queue.popleft()\n if depth >= max_depth:\n continue\n next_depth = depth + 1\n for neighbor in sorted(G.successors(current)): # sorted for determinism\n if neighbor not in visited:\n visited[neighbor] = next_depth\n result.append((neighbor, next_depth))\n queue.append((neighbor, next_depth))\n\n return result", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 1406}, "tests/test_orchestrate.py::70": {"resolved_imports": ["src/roam/db/connection.py", "src/roam/graph/builder.py", "src/roam/graph/partition.py"], "used_names": ["build_symbol_graph", "open_db", "os", "partition_for_agents"], "enclosing_function": "test_partition_correct_agent_count", "extracted_code": "# Source: src/roam/db/connection.py\ndef open_db(readonly: bool = False, project_root: Path | None = None):\n \"\"\"Context manager for database access. Creates schema if needed.\n\n Raises a descriptive ``click.ClickException`` if the database file is\n missing or corrupted so that agents receive actionable remediation steps\n instead of a raw SQLite traceback.\n \"\"\"\n import click\n\n db_path = get_db_path(project_root)\n try:\n conn = get_connection(db_path, readonly=readonly)\n except sqlite3.DatabaseError as exc:\n raise click.ClickException(\n f\"Database error: {exc}\\n\"\n \" The roam index may be corrupted. Run `roam init --force` to rebuild it\\n\"\n \" from scratch, or delete .roam/index.db and run `roam init`.\"\n ) from exc\n try:\n if not readonly:\n try:\n ensure_schema(conn)\n except sqlite3.DatabaseError as exc:\n conn.close()\n raise click.ClickException(\n f\"Database schema error: {exc}\\n\"\n \" The roam index may be corrupted or from an incompatible version.\\n\"\n \" Run `roam init --force` to rebuild it, or delete .roam/index.db\\n\"\n \" and run `roam init`.\"\n ) from exc\n yield conn\n if not readonly:\n conn.commit()\n finally:\n conn.close()\n\n\n# Source: src/roam/graph/builder.py\ndef build_symbol_graph(conn: sqlite3.Connection) -> nx.DiGraph:\n \"\"\"Build a directed graph from symbol edges.\n\n Nodes are symbol IDs with attributes: name, kind, file_path, qualified_name.\n Edges carry a ``kind`` attribute (calls, imports, inherits, etc.).\n \"\"\"\n G = nx.DiGraph()\n\n # Load nodes (ORDER BY id for deterministic graph construction)\n rows = conn.execute(\n \"SELECT s.id, s.name, s.kind, s.qualified_name, f.path AS file_path \"\n \"FROM symbols s JOIN files f ON s.file_id = f.id \"\n \"ORDER BY s.id\"\n ).fetchall()\n G.add_nodes_from(\n (row[0], {\"name\": row[1], \"kind\": row[2], \"qualified_name\": row[3], \"file_path\": row[4]}) for row in rows\n )\n\n # Load edges — pre-build node set for O(1) membership checks\n # ORDER BY for deterministic edge insertion order\n node_set = set(G)\n rows = conn.execute(\"SELECT source_id, target_id, kind FROM edges ORDER BY source_id, target_id\").fetchall()\n G.add_edges_from(\n (source_id, target_id, {\"kind\": kind})\n for source_id, target_id, kind in rows\n if source_id in node_set and target_id in node_set\n )\n\n return G\n\n\n# Source: src/roam/graph/partition.py\ndef partition_for_agents(\n G: nx.DiGraph,\n conn: sqlite3.Connection,\n n_agents: int,\n target_files: list[str] | None = None,\n) -> dict:\n \"\"\"Partition the symbol graph into non-overlapping agent work zones.\n\n Algorithm:\n 1. If *target_files* is given, extract the subgraph for those files.\n 2. Run Louvain community detection.\n 3. Merge or split clusters to match *n_agents*.\n 4. For each partition compute write files, read-only files,\n shared interfaces, and contracts.\n\n Returns a dict with ``agents``, ``merge_order``, ``conflict_probability``,\n and ``shared_interfaces``.\n \"\"\"\n if n_agents < 1:\n n_agents = 1\n\n # ── 1. Scope the graph ────────────────────────────────────────\n if target_files:\n target_set = set(target_files)\n keep = {n for n in G.nodes if G.nodes[n].get(\"file_path\", \"\") in target_set}\n if not keep:\n # Try prefix matching (directories)\n keep = {n for n in G.nodes if any(G.nodes[n].get(\"file_path\", \"\").startswith(t) for t in target_set)}\n if keep:\n G = G.subgraph(keep).copy()\n\n if len(G) == 0:\n return _empty_result(n_agents)\n\n # ── 2. Detect clusters ────────────────────────────────────────\n cluster_map = detect_clusters(G)\n if not cluster_map:\n # Assign every node to cluster 0\n cluster_map = {n: 0 for n in G.nodes}\n\n # Group nodes by cluster\n groups: dict[int, set[int]] = defaultdict(set)\n for node_id, cid in cluster_map.items():\n groups[cid].add(node_id)\n\n # ── 3. Adjust cluster count to match n_agents ─────────────────\n partitions = _adjust_cluster_count(G, groups, n_agents)\n\n # ── 4. Build agent descriptors ────────────────────────────────\n agents = _build_agent_descriptors(G, conn, partitions)\n\n # ── 5. Shared interfaces ──────────────────────────────────────\n shared_interfaces = _find_shared_interfaces(G, conn, partitions)\n\n # ── 6. Conflict probability ───────────────────────────────────\n conflict_prob = compute_conflict_probability(G, partitions)\n\n # ── 7. Merge order ────────────────────────────────────────────\n merge_order = compute_merge_order(G, partitions)\n\n # Count write conflicts (files appearing in multiple write lists)\n all_write_files: list[str] = []\n for a in agents:\n all_write_files.extend(a[\"write_files\"])\n file_counts = Counter(all_write_files)\n write_conflicts = sum(1 for c in file_counts.values() if c > 1)\n\n return {\n \"agents\": agents,\n \"merge_order\": merge_order,\n \"conflict_probability\": round(conflict_prob, 4),\n \"shared_interfaces\": [si[\"symbol\"] for si in shared_interfaces],\n \"write_conflicts\": write_conflicts,\n }", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 5416}, "tests/test_ci_gate_eval.py::27": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_scalar_gate_pass", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_metrics_cmd.py::459": {"resolved_imports": [], "used_names": ["parse_json_output"], "enclosing_function": "test_file_json_has_symbol_list", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_formatters.py::29": {"resolved_imports": ["src/roam/output/formatter.py"], "used_names": ["abbrev_kind"], "enclosing_function": "test_function", "extracted_code": "# Source: src/roam/output/formatter.py\ndef abbrev_kind(kind: str) -> str:\n return KIND_ABBREV.get(kind, kind)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 112}, "tests/test_auth_gaps.py::198": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_verdict_line", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_check_rules.py::630": {"resolved_imports": ["src/roam/cli.py", "src/roam/commands/cmd_check_rules.py"], "used_names": ["_resolve_rules"], "enclosing_function": "test_resolve_rules_disable_multiple", "extracted_code": "# Source: src/roam/commands/cmd_check_rules.py\ndef _resolve_rules(\n rule_filter: str | None,\n severity_filter: str | None,\n user_overrides: list[dict],\n) -> list:\n \"\"\"Return list of BuiltinRule objects to evaluate.\n\n Applies user config overrides (enable/disable, threshold changes).\n Filters by rule ID and/or severity as requested.\n \"\"\"\n import copy\n\n from roam.rules.builtin import BUILTIN_RULES\n\n # Build override map keyed by rule ID\n override_map: dict[str, dict] = {}\n for o in user_overrides:\n rid = o.get(\"id\", \"\")\n if rid:\n override_map[rid] = o\n\n # Clone and apply overrides\n resolved = []\n for rule in BUILTIN_RULES:\n r = copy.copy(rule)\n if rule.id in override_map:\n ov = override_map[rule.id]\n if \"enabled\" in ov:\n r.enabled = bool(ov[\"enabled\"])\n if \"threshold\" in ov and ov[\"threshold\"] is not None:\n r.threshold = float(ov[\"threshold\"])\n if \"severity\" in ov:\n r.severity = str(ov[\"severity\"])\n resolved.append(r)\n\n # Filter disabled rules\n resolved = [r for r in resolved if r.enabled]\n\n # Filter by specific rule ID\n if rule_filter:\n resolved = [r for r in resolved if r.id == rule_filter]\n\n # Filter by severity\n if severity_filter:\n resolved = [r for r in resolved if r.severity == severity_filter]\n\n return resolved", "n_imports_parsed": 9, "n_files_resolved": 2, "n_chars_extracted": 1451}, "tests/test_conventions_cmd.py::413": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output", "pytest"], "enclosing_function": "test_mixed_naming_violation_fields", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_vibe_check.py::314": {"resolved_imports": [], "used_names": ["json"], "enclosing_function": "test_json_patterns_array", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_batch_mcp.py::426": {"resolved_imports": [], "used_names": ["batch_search"], "enclosing_function": "test_multiple_queries", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_closure.py::112": {"resolved_imports": ["src/roam/cli.py"], "used_names": ["invoke_cli"], "enclosing_function": "test_closure_finds_tests", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_ai_ratio.py::337": {"resolved_imports": ["src/roam/commands/cmd_ai_ratio.py"], "used_names": ["_temporal_signal", "time"], "enclosing_function": "test_burst_session_detected", "extracted_code": "# Source: src/roam/commands/cmd_ai_ratio.py\ndef _temporal_signal(commits: list[dict]) -> tuple[float, int]:\n \"\"\"Score [0, 1] from temporal commit patterns.\n\n AI coding sessions show:\n - Burst patterns: many commits in short windows\n - Regular intervals: bot-like consistent spacing\n\n Returns (score, burst_session_count).\n \"\"\"\n if len(commits) < 3:\n return 0.0, 0\n\n # Sort by timestamp\n sorted_commits = sorted(commits, key=lambda c: c.get(\"timestamp\", 0))\n timestamps = [c.get(\"timestamp\", 0) for c in sorted_commits]\n\n # Detect burst sessions (clusters of commits within _BURST_WINDOW_SECONDS)\n burst_sessions = 0\n i = 0\n while i < len(timestamps):\n window_end = timestamps[i] + _BURST_WINDOW_SECONDS\n j = i + 1\n while j < len(timestamps) and timestamps[j] <= window_end:\n j += 1\n cluster_size = j - i\n if cluster_size >= _MIN_BURST_COMMITS:\n burst_sessions += 1\n i = j # skip past the cluster\n else:\n i += 1\n\n # Detect regularity: compute coefficient of variation of inter-commit intervals\n intervals = []\n for i in range(1, len(timestamps)):\n dt = timestamps[i] - timestamps[i - 1]\n if dt > 0: # ignore zero-interval duplicates\n intervals.append(float(dt))\n\n regularity_score = 0.0\n if len(intervals) >= 5:\n mean_iv = sum(intervals) / len(intervals)\n if mean_iv > 0:\n std_iv = math.sqrt(sum((x - mean_iv) ** 2 for x in intervals) / len(intervals))\n cv = std_iv / mean_iv\n # Very low CV (<0.15) suggests bot-like regularity\n if cv < _REGULARITY_THRESHOLD:\n regularity_score = 1.0 - (cv / _REGULARITY_THRESHOLD)\n\n # Burst ratio: fraction of commits that are in burst sessions\n burst_ratio = burst_sessions / max(1, len(timestamps) // _MIN_BURST_COMMITS)\n burst_ratio = min(burst_ratio, 1.0)\n\n # Combine: max of burst and regularity signals\n score = max(burst_ratio * 0.7, regularity_score * 0.3)\n return min(score, 1.0), burst_sessions", "n_imports_parsed": 12, "n_files_resolved": 1, "n_chars_extracted": 2105}, "tests/test_attest.py::187": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_attest_has_breaking_changes", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_conventions_cmd.py::465": {"resolved_imports": ["src/roam/commands/cmd_conventions.py"], "used_names": ["classify_case"], "enclosing_function": "test_dunder_returns_none", "extracted_code": "# Source: src/roam/commands/cmd_conventions.py\ndef classify_case(name: str) -> str | None:\n \"\"\"Return the case style of *name*, or None if unclassifiable.\"\"\"\n if len(name) < _MIN_NAME_LEN or name in _SKIP_NAMES:\n return None\n if name.startswith(\"__\") and name.endswith(\"__\"):\n return None # dunder\n\n for style, pattern in _CASE_PATTERNS.items():\n if pattern.match(name):\n return style\n\n # Single-word heuristics\n if _SINGLE_PASCAL.match(name):\n return \"PascalCase\"\n if _SINGLE_LOWER.match(name):\n return \"snake_case\" # single lowercase word is compatible with snake\n if _SINGLE_UPPER.match(name):\n return \"UPPER_SNAKE\"\n\n return None", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 714}, "tests/test_adrs.py::82": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_json_has_adrs_list", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_attest.py::167": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_attest_has_blast_radius", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_alerts_cmd.py::302": {"resolved_imports": ["src/roam/commands/cmd_alerts.py"], "used_names": ["_check_thresholds"], "enclosing_function": "test_check_thresholds_health_below_60", "extracted_code": "# Source: src/roam/commands/cmd_alerts.py\ndef _check_thresholds(current):\n \"\"\"Check current metrics against absolute thresholds.\"\"\"\n alerts = []\n for metric, rule in _THRESHOLDS.items():\n val = current.get(metric)\n if val is None:\n continue\n op, threshold, level = rule[\"op\"], rule[\"value\"], rule[\"level\"]\n triggered = False\n if op == \"<\" and val < threshold:\n triggered = True\n elif op == \">\" and val > threshold:\n triggered = True\n elif op == \">=\" and val >= threshold:\n triggered = True\n elif op == \"<=\" and val <= threshold:\n triggered = True\n if triggered:\n msg = f\"below {threshold} threshold\" if op == \"<\" else f\"above {threshold} threshold\"\n alerts.append(\n _make_alert(\n level,\n metric,\n f\"{metric}={val} ({msg})\",\n val,\n )\n )\n return alerts", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 1019}, "tests/test_attest.py::166": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_attest_has_blast_radius", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_ai_ratio.py::513": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_since_flag_long_range", "extracted_code": "", "n_imports_parsed": 11, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_describe.py::135": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_verdict_line", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_health_gate.py::78": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_gate_text_output_format", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_attest.py::374": {"resolved_imports": [], "used_names": ["_compute_verdict"], "enclosing_function": "test_safe_when_no_issues", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_backend_fixes_round3.py::156": {"resolved_imports": ["src/roam/commands/cmd_migration_safety.py"], "used_names": ["_RE_INFO_SCHEMA_GUARD"], "enclosing_function": "test_information_schema_columns", "extracted_code": "# Source: src/roam/commands/cmd_migration_safety.py\n_RE_INFO_SCHEMA_GUARD = re.compile(\n r\"information_schema\\s*\\.\\s*(?:columns|tables|statistics|table_constraints|key_column_usage)\",\n re.IGNORECASE,\n)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 207}, "tests/test_alerts_cmd.py::100": {"resolved_imports": [], "used_names": ["git_commit", "git_init", "index_in_process", "pytest"], "enclosing_function": "multi_snapshot_project", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_split_cmd.py::193": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output", "pytest"], "enclosing_function": "test_json_group_fields", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_context_propagation.py::421": {"resolved_imports": ["src/roam/commands/context_helpers.py"], "used_names": ["_get_propagation_scores_for_paths"], "enclosing_function": "test_callee_files_get_scores", "extracted_code": "# Source: src/roam/commands/context_helpers.py\ndef _get_propagation_scores_for_paths(conn, sym_ids, use_propagation, max_depth=3, decay=0.5):\n \"\"\"Compute per-file propagation scores for a set of seed symbol IDs.\n\n Builds a lightweight adjacency map (no networkx) by loading edges directly\n from the DB, runs BFS propagation, then aggregates per-file scores as the\n maximum propagation score of any symbol in that file.\n\n Returns a dict mapping ``{file_path: propagation_score}`` for all files\n reachable within max_depth from the seeds. Returns an empty dict when\n use_propagation is False or sym_ids is empty.\n \"\"\"\n if not use_propagation or not sym_ids:\n return {}\n\n # Build a lightweight networkx-free graph using adjacency dicts\n # to avoid importing networkx (it is a heavy dependency only loaded on demand).\n # We implement a small BFS directly rather than constructing a DiGraph.\n\n seed_set = set(sym_ids)\n\n # Load edges in both directions\n forward: dict = {} # caller -> {callee, ...}\n backward: dict = {} # callee -> {caller, ...}\n\n for batch_ids in _batch_list(list(seed_set), 400):\n _load_neighborhood_edges(conn, batch_ids, forward, backward, max_depth)\n\n # BFS callee direction (forward)\n callee_scores: dict[int, float] = {s: 1.0 for s in seed_set}\n visited_callee: dict[int, int] = {s: 0 for s in seed_set}\n queue = deque([(s, 0) for s in seed_set])\n while queue:\n node, depth = queue.popleft()\n if depth >= max_depth:\n continue\n for neighbor in forward.get(node, ()):\n if neighbor in seed_set:\n continue\n nd = depth + 1\n if neighbor not in visited_callee or visited_callee[neighbor] > nd:\n visited_callee[neighbor] = nd\n score = decay**nd\n prev = callee_scores.get(neighbor, 0.0)\n callee_scores[neighbor] = max(prev, score)\n queue.append((neighbor, nd))\n\n # BFS caller direction (backward), lower weight\n caller_decay = decay * 0.5\n visited_caller: dict[int, int] = {s: 0 for s in seed_set}\n queue = deque([(s, 0) for s in seed_set])\n while queue:\n node, depth = queue.popleft()\n if depth >= max_depth:\n continue\n for neighbor in backward.get(node, ()):\n if neighbor in seed_set:\n continue\n nd = depth + 1\n if neighbor not in visited_caller or visited_caller[neighbor] > nd:\n visited_caller[neighbor] = nd\n score = caller_decay**nd\n prev = callee_scores.get(neighbor, 0.0)\n callee_scores[neighbor] = max(prev, score)\n queue.append((neighbor, nd))\n\n if not callee_scores:\n return {}\n\n # Map symbol_id -> file_path and aggregate per file\n all_sym_ids = list(callee_scores.keys())\n path_max_score: dict[str, float] = {}\n\n for chunk in _batch_list(all_sym_ids, 400):\n ph = \",\".join(\"?\" * len(chunk))\n rows = conn.execute(\n f\"SELECT s.id, f.path FROM symbols s JOIN files f ON s.file_id = f.id WHERE s.id IN ({ph})\",\n chunk,\n ).fetchall()\n for row in rows:\n # Handle both sqlite3.Row and tuple\n try:\n sym_id_val = row[\"id\"]\n path_val = row[\"path\"]\n except (KeyError, TypeError):\n sym_id_val = row[0]\n path_val = row[1]\n path_val = (path_val or \"\").replace(\"\\\\\", \"/\")\n sc = callee_scores.get(sym_id_val, 0.0)\n if sc > path_max_score.get(path_val, 0.0):\n path_max_score[path_val] = sc\n\n return path_max_score", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 3741}, "tests/test_python_extractor_v2.py::147": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_default_value_extraction", "extracted_code": "", "n_imports_parsed": 1, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_bridges.py::72": {"resolved_imports": ["src/roam/bridges/__init__.py", "src/roam/bridges/registry.py", "src/roam/bridges/base.py", "src/roam/bridges/bridge_protobuf.py", "src/roam/bridges/bridge_salesforce.py"], "used_names": ["SalesforceBridge"], "enclosing_function": "test_register_and_get", "extracted_code": "# Source: src/roam/bridges/bridge_salesforce.py\nclass SalesforceBridge(LanguageBridge):\n \"\"\"Bridge between Apex controllers and Aura/LWC/Visualforce templates.\"\"\"\n\n @property\n def name(self) -> str:\n return \"salesforce\"\n\n @property\n def source_extensions(self) -> frozenset[str]:\n return _APEX_EXTS\n\n @property\n def target_extensions(self) -> frozenset[str]:\n return _SF_MARKUP_EXTS\n\n def detect(self, file_paths: list[str]) -> bool:\n \"\"\"Detect if project has both Apex and markup files.\"\"\"\n has_apex = False\n has_markup = False\n for fp in file_paths:\n ext = os.path.splitext(fp)[1].lower()\n if ext in _APEX_EXTS:\n has_apex = True\n if ext in _SF_MARKUP_EXTS:\n has_markup = True\n if has_apex and has_markup:\n return True\n return False\n\n def resolve(self, source_path: str, source_symbols: list[dict], target_files: dict[str, list[dict]]) -> list[dict]:\n \"\"\"Resolve Apex-to-markup cross-language links.\n\n Resolution strategies:\n 1. Naming convention: MyController.cls -> MyController.cmp\n 2. Controller attribute: \n 3. @AuraEnabled methods: match to components referencing that controller\n \"\"\"\n edges: list[dict] = []\n source_ext = os.path.splitext(source_path)[1].lower()\n\n if source_ext not in _APEX_EXTS:\n return edges\n\n # Get the Apex class name from the file path\n apex_class_name = os.path.basename(source_path).rsplit(\".\", 1)[0]\n\n # Build a lookup of target symbols by qualified name for fast matching\n target_symbol_index: dict[str, str] = {} # symbol_name -> qualified_name\n # Track which target files reference this Apex class as a controller\n controller_targets: list[tuple[str, list[dict]]] = []\n\n for tpath, tsymbols in target_files.items():\n text_ext = os.path.splitext(tpath)[1].lower()\n if text_ext not in _SF_MARKUP_EXTS:\n continue\n\n for sym in tsymbols:\n target_symbol_index[sym.get(\"name\", \"\")] = sym.get(\"qualified_name\", \"\")\n\n # Check if any target symbol references this Apex class\n # Aura components reference controllers via naming convention or\n # controller attribute (already extracted as references by AuraExtractor)\n target_basename = os.path.basename(tpath).rsplit(\".\", 1)[0]\n\n # Strategy 1: Naming convention match\n # MyController.cls -> MyController.cmp (same name)\n # MyController.cls -> MyControllerCmp.cmp (with suffix)\n if self._names_match(apex_class_name, target_basename):\n controller_targets.append((tpath, tsymbols))\n # Create edge from Apex class to the component\n edges.append(\n {\n \"source\": apex_class_name,\n \"target\": target_basename,\n \"kind\": \"x-lang\",\n \"bridge\": self.name,\n \"mechanism\": \"naming-convention\",\n }\n )\n\n # Strategy 2: Match @AuraEnabled methods to components that reference\n # this controller. Any component whose controller is this Apex class\n # can call its @AuraEnabled methods.\n aura_enabled_methods = self._find_aura_enabled_methods(source_symbols)\n\n for method_name, method_qname in aura_enabled_methods:\n for tpath, tsymbols in controller_targets:\n target_basename = os.path.basename(tpath).rsplit(\".\", 1)[0]\n edges.append(\n {\n \"source\": method_qname,\n \"target\": target_basename,\n \"kind\": \"x-lang\",\n \"bridge\": self.name,\n \"mechanism\": \"aura-enabled\",\n }\n )\n\n # Strategy 3: Check for Visualforce controller references\n # Visualforce pages specify controller=\"ClassName\" in \n # The VF extractor already extracts these as \"controller\" references,\n # but we create x-lang edges for them here\n for tpath, tsymbols in target_files.items():\n text_ext = os.path.splitext(tpath)[1].lower()\n if text_ext not in (\".page\", \".component\"):\n continue\n target_basename = os.path.basename(tpath).rsplit(\".\", 1)[0]\n # Check if any symbol in the target references this Apex class\n # We look for the component-level symbol whose name matches\n for sym in tsymbols:\n # Visualforce pages are top-level symbols of kind \"page\"/\"component\"\n if sym.get(\"kind\") in (\"page\", \"component\"):\n # The VF extractor creates controller references; check if\n # this Apex class is referenced by name in the target path\n # (We rely on naming convention or explicit controller attr)\n if self._names_match(apex_class_name, target_basename):\n # Already handled by strategy 1 above; skip duplicate\n pass\n\n return edges\n\n def _names_match(self, apex_name: str, target_name: str) -> bool:\n \"\"\"Check if an Apex class name matches a component name.\n\n Supports common Salesforce naming conventions:\n - Exact match: MyController -> MyController\n - Controller suffix: MyController -> My (component uses class as controller)\n - Component suffix: MyClass -> MyClassController (Apex has Controller suffix)\n \"\"\"\n apex_lower = apex_name.lower()\n target_lower = target_name.lower()\n\n # Exact match\n if apex_lower == target_lower:\n return True\n\n # Apex name is target + \"Controller\" suffix\n # e.g., MyComponentController.cls -> MyComponent.cmp\n if apex_lower == target_lower + \"controller\":\n return True\n\n # Target name is apex + \"Controller\" suffix (less common but possible)\n if target_lower == apex_lower + \"controller\":\n return True\n\n return False\n\n def _find_aura_enabled_methods(self, symbols: list[dict]) -> list[tuple[str, str]]:\n \"\"\"Find methods with @AuraEnabled annotation.\n\n Returns list of (method_name, qualified_name) tuples.\n \"\"\"\n results = []\n for sym in symbols:\n kind = sym.get(\"kind\", \"\")\n if kind not in (\"method\", \"function\"):\n continue\n sig = sym.get(\"signature\", \"\") or \"\"\n # Check if the signature or annotations contain @AuraEnabled\n if _AURA_ENABLED_RE.search(sig):\n results.append((sym.get(\"name\", \"\"), sym.get(\"qualified_name\", \"\")))\n continue\n # Also check docstring/annotations if stored there\n doc = sym.get(\"docstring\", \"\") or \"\"\n if _AURA_ENABLED_RE.search(doc):\n results.append((sym.get(\"name\", \"\"), sym.get(\"qualified_name\", \"\")))\n return results", "n_imports_parsed": 6, "n_files_resolved": 5, "n_chars_extracted": 7262}, "tests/test_pr_diff.py::270": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_pr_diff_footprint", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_competitor_site_data.py::38": {"resolved_imports": ["src/roam/competitor_site_data.py", "src/roam/surface_counts.py"], "used_names": ["build_site_payload"], "enclosing_function": "test_site_payload_has_expected_shape_and_count", "extracted_code": "# Source: src/roam/competitor_site_data.py\ndef build_site_payload(tracker_path: Path | None = None) -> dict[str, object]:\n path = tracker_path or default_tracker_path()\n lines = path.read_text(encoding=\"utf-8\").splitlines()\n\n tracker_updated = \"\"\n for line in lines:\n if line.startswith(\"> Updated:\"):\n tracker_updated = line.split(\":\", 1)[1].strip()\n break\n if not tracker_updated:\n raise ValueError(\"Could not parse tracker update line ('> Updated: ...').\")\n\n tracker_updated_iso = _parse_tracker_updated_iso(tracker_updated)\n confidence_map = _parse_matrix_confidence(lines)\n competitors = _matrix_to_competitors(lines, confidence_map, tracker_updated_iso)\n _append_ckb_from_leaderboard(lines, competitors, confidence_map, tracker_updated_iso)\n _append_extra_competitors(competitors, tracker_updated_iso)\n\n # Filter to landscape-included tools only.\n competitors = [c for c in competitors if str(c[\"name\"]) in LANDSCAPE_INCLUDE]\n\n # Keep visual map stable: order by descending analysis depth, then agent readiness.\n competitors.sort(key=lambda c: (-int(c[\"arch\"]), -int(c[\"agent\"]), str(c[\"name\"])))\n\n # Keep roam-code row count fields synced to source-of-truth command/tool registration.\n try:\n from roam.surface_counts import collect_surface_counts\n\n surface = collect_surface_counts()\n cli_counts = surface.get(\"cli\", {})\n mcp_counts = surface.get(\"mcp\", {})\n canonical = int(cli_counts.get(\"canonical_commands\", 0) or 0)\n alias_count = int(cli_counts.get(\"alias_names\", 0) or 0)\n mcp_tools = int(mcp_counts.get(\"registered_tools\", 0) or 0)\n for entry in competitors:\n if entry.get(\"name\") != \"roam-code\":\n continue\n entry[\"mcp\"] = str(mcp_tools)\n if alias_count > 0:\n entry[\"cli_commands\"] = f\"{canonical} canonical (+{alias_count} alias)\"\n else:\n entry[\"cli_commands\"] = str(canonical)\n break\n except Exception:\n # Do not fail payload generation if local surface-count parsing fails.\n pass\n\n methodology = {\n \"scoring_model\": [\n \"45 criteria across 7 categories, scored as binary (has/doesn't), count-tiered, or subjective.\",\n \"Y-axis (Analysis Depth) = Static Analysis (50%) + Graph Intelligence (25%) + Git Temporal (25%).\",\n \"X-axis (Agent Readiness) = Agent Integration (70%) + Ecosystem (30%).\",\n \"Security and Unique Capabilities affect total score only, not map position.\",\n \"All criteria scored by project maintainers. 44/45 are binary or tiered (count-based or depth-based). 1/45 is subjective (documentation quality).\",\n \"Weight sliders let viewers apply their own category priorities.\",\n ],\n \"limitations\": [\n \"Criteria selection bias: we chose which capabilities to measure, favoring tools with graph algorithms.\",\n \"Category weight bias: default weights reflect our perspective. Adjust sliders for yours.\",\n \"Assessment bias: we scored all competitors. Errors or missed capabilities are possible.\",\n \"Public vendor claims can be stale or inconsistent across pages.\",\n \"GitHub star counts may conflate main product repos with MCP extension repos.\",\n ],\n \"reproducibility\": {\n \"tracker\": str(path.relative_to(_repo_root())).replace(\"\\\\\", \"/\"),\n \"generator\": \"src/roam/competitor_site_data.py\",\n \"generated_at_reference\": tracker_updated_iso,\n },\n }\n\n # Rubric metadata for the frontend (weight sliders + methodology rendering)\n rubric_out: list[dict[str, object]] = []\n for cat in SCORING_RUBRIC:\n rubric_out.append(\n {\n \"id\": cat[\"id\"],\n \"label\": cat[\"label\"],\n \"max_points\": cat[\"max_points\"],\n \"default_weight\": cat[\"default_weight\"],\n \"criteria\": [{k: v for k, v in crit.items()} for crit in cat[\"criteria\"]],\n }\n )\n\n return {\n \"tracker_updated\": tracker_updated,\n \"tracker_updated_iso\": tracker_updated_iso,\n \"tracker_file\": str(path.relative_to(_repo_root())).replace(\"\\\\\", \"/\"),\n \"competitors\": competitors,\n \"methodology\": methodology,\n \"rubric\": rubric_out,\n }", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 4415}, "tests/test_math_tips.py::252": {"resolved_imports": [], "used_names": ["CliRunner", "invoke_cli", "parse_json_output"], "enclosing_function": "test_json_findings_have_language_and_tip_fields", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_budget_flag.py::212": {"resolved_imports": ["src/roam/output/formatter.py"], "used_names": ["estimate_tokens"], "enclosing_function": "test_basic_estimate", "extracted_code": "# Source: src/roam/output/formatter.py\ndef estimate_tokens(text: str) -> int:\n \"\"\"Estimate token count from character length (1 token ~ 4 chars).\"\"\"\n return max(1, len(text) // _CHARS_PER_TOKEN)", "n_imports_parsed": 8, "n_files_resolved": 1, "n_chars_extracted": 200}, "tests/test_ci_sarif_guard.py::75": {"resolved_imports": [], "used_names": ["deepcopy"], "enclosing_function": "test_apply_guardrails_run_and_result_caps", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_orchestrate.py::160": {"resolved_imports": ["src/roam/db/connection.py", "src/roam/graph/builder.py", "src/roam/graph/partition.py"], "used_names": ["build_symbol_graph", "open_db", "os", "partition_for_agents"], "enclosing_function": "test_partition_conflict_probability", "extracted_code": "# Source: src/roam/db/connection.py\ndef open_db(readonly: bool = False, project_root: Path | None = None):\n \"\"\"Context manager for database access. Creates schema if needed.\n\n Raises a descriptive ``click.ClickException`` if the database file is\n missing or corrupted so that agents receive actionable remediation steps\n instead of a raw SQLite traceback.\n \"\"\"\n import click\n\n db_path = get_db_path(project_root)\n try:\n conn = get_connection(db_path, readonly=readonly)\n except sqlite3.DatabaseError as exc:\n raise click.ClickException(\n f\"Database error: {exc}\\n\"\n \" The roam index may be corrupted. Run `roam init --force` to rebuild it\\n\"\n \" from scratch, or delete .roam/index.db and run `roam init`.\"\n ) from exc\n try:\n if not readonly:\n try:\n ensure_schema(conn)\n except sqlite3.DatabaseError as exc:\n conn.close()\n raise click.ClickException(\n f\"Database schema error: {exc}\\n\"\n \" The roam index may be corrupted or from an incompatible version.\\n\"\n \" Run `roam init --force` to rebuild it, or delete .roam/index.db\\n\"\n \" and run `roam init`.\"\n ) from exc\n yield conn\n if not readonly:\n conn.commit()\n finally:\n conn.close()\n\n\n# Source: src/roam/graph/builder.py\ndef build_symbol_graph(conn: sqlite3.Connection) -> nx.DiGraph:\n \"\"\"Build a directed graph from symbol edges.\n\n Nodes are symbol IDs with attributes: name, kind, file_path, qualified_name.\n Edges carry a ``kind`` attribute (calls, imports, inherits, etc.).\n \"\"\"\n G = nx.DiGraph()\n\n # Load nodes (ORDER BY id for deterministic graph construction)\n rows = conn.execute(\n \"SELECT s.id, s.name, s.kind, s.qualified_name, f.path AS file_path \"\n \"FROM symbols s JOIN files f ON s.file_id = f.id \"\n \"ORDER BY s.id\"\n ).fetchall()\n G.add_nodes_from(\n (row[0], {\"name\": row[1], \"kind\": row[2], \"qualified_name\": row[3], \"file_path\": row[4]}) for row in rows\n )\n\n # Load edges — pre-build node set for O(1) membership checks\n # ORDER BY for deterministic edge insertion order\n node_set = set(G)\n rows = conn.execute(\"SELECT source_id, target_id, kind FROM edges ORDER BY source_id, target_id\").fetchall()\n G.add_edges_from(\n (source_id, target_id, {\"kind\": kind})\n for source_id, target_id, kind in rows\n if source_id in node_set and target_id in node_set\n )\n\n return G\n\n\n# Source: src/roam/graph/partition.py\ndef partition_for_agents(\n G: nx.DiGraph,\n conn: sqlite3.Connection,\n n_agents: int,\n target_files: list[str] | None = None,\n) -> dict:\n \"\"\"Partition the symbol graph into non-overlapping agent work zones.\n\n Algorithm:\n 1. If *target_files* is given, extract the subgraph for those files.\n 2. Run Louvain community detection.\n 3. Merge or split clusters to match *n_agents*.\n 4. For each partition compute write files, read-only files,\n shared interfaces, and contracts.\n\n Returns a dict with ``agents``, ``merge_order``, ``conflict_probability``,\n and ``shared_interfaces``.\n \"\"\"\n if n_agents < 1:\n n_agents = 1\n\n # ── 1. Scope the graph ────────────────────────────────────────\n if target_files:\n target_set = set(target_files)\n keep = {n for n in G.nodes if G.nodes[n].get(\"file_path\", \"\") in target_set}\n if not keep:\n # Try prefix matching (directories)\n keep = {n for n in G.nodes if any(G.nodes[n].get(\"file_path\", \"\").startswith(t) for t in target_set)}\n if keep:\n G = G.subgraph(keep).copy()\n\n if len(G) == 0:\n return _empty_result(n_agents)\n\n # ── 2. Detect clusters ────────────────────────────────────────\n cluster_map = detect_clusters(G)\n if not cluster_map:\n # Assign every node to cluster 0\n cluster_map = {n: 0 for n in G.nodes}\n\n # Group nodes by cluster\n groups: dict[int, set[int]] = defaultdict(set)\n for node_id, cid in cluster_map.items():\n groups[cid].add(node_id)\n\n # ── 3. Adjust cluster count to match n_agents ─────────────────\n partitions = _adjust_cluster_count(G, groups, n_agents)\n\n # ── 4. Build agent descriptors ────────────────────────────────\n agents = _build_agent_descriptors(G, conn, partitions)\n\n # ── 5. Shared interfaces ──────────────────────────────────────\n shared_interfaces = _find_shared_interfaces(G, conn, partitions)\n\n # ── 6. Conflict probability ───────────────────────────────────\n conflict_prob = compute_conflict_probability(G, partitions)\n\n # ── 7. Merge order ────────────────────────────────────────────\n merge_order = compute_merge_order(G, partitions)\n\n # Count write conflicts (files appearing in multiple write lists)\n all_write_files: list[str] = []\n for a in agents:\n all_write_files.extend(a[\"write_files\"])\n file_counts = Counter(all_write_files)\n write_conflicts = sum(1 for c in file_counts.values() if c > 1)\n\n return {\n \"agents\": agents,\n \"merge_order\": merge_order,\n \"conflict_probability\": round(conflict_prob, 4),\n \"shared_interfaces\": [si[\"symbol\"] for si in shared_interfaces],\n \"write_conflicts\": write_conflicts,\n }", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 5416}, "tests/test_commands_architecture.py::51": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_map_shows_files", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_affected.py::195": {"resolved_imports": ["src/roam/cli.py"], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_affected_json_has_changed_files", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_context_propagation.py::321": {"resolved_imports": ["src/roam/graph/propagation.py"], "used_names": ["callee_chain"], "enclosing_function": "test_leaf_node_empty_chain", "extracted_code": "# Source: src/roam/graph/propagation.py\ndef callee_chain(\n G,\n node: int,\n max_depth: int = 3,\n) -> List[Tuple[int, int]]:\n \"\"\"Return ordered list of transitive callees with their BFS depth.\n\n BFS from *node* through outgoing (callee) edges up to *max_depth*.\n Cycles are handled via a visited set — each callee is reported at\n the shallowest depth it is reached.\n\n Parameters\n ----------\n G:\n Directed call graph (caller -> callee edges).\n node:\n Starting symbol node ID.\n max_depth:\n Maximum callee depth to traverse. Defaults to 3.\n\n Returns\n -------\n list of (node_id, depth) tuples\n Ordered by BFS level (shallow callees first), then by node ID for\n determinism. The seed node itself is NOT included.\n \"\"\"\n if node not in G:\n return []\n\n visited: Dict[int, int] = {node: 0}\n queue: deque[Tuple[int, int]] = deque([(node, 0)])\n result: List[Tuple[int, int]] = []\n\n while queue:\n current, depth = queue.popleft()\n if depth >= max_depth:\n continue\n next_depth = depth + 1\n for neighbor in sorted(G.successors(current)): # sorted for determinism\n if neighbor not in visited:\n visited[neighbor] = next_depth\n result.append((neighbor, next_depth))\n queue.append((neighbor, next_depth))\n\n return result", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 1406}, "tests/test_kotlin_swift_extractors.py::108": {"resolved_imports": ["src/roam/index/parser.py", "src/roam/languages/registry.py"], "used_names": [], "enclosing_function": "test_swift_protocol_struct_enum_constructor_and_properties", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_batch_mcp.py::236": {"resolved_imports": [], "used_names": ["_batch_search_one"], "enclosing_function": "test_fts_hit", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_bisect.py::80": {"resolved_imports": [], "used_names": ["json", "pytest"], "enclosing_function": "_parse_json", "extracted_code": "", "n_imports_parsed": 9, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_trends_cohort.py::130": {"resolved_imports": [], "used_names": ["json"], "enclosing_function": "test_trends_cohort_json_shape", "extracted_code": "", "n_imports_parsed": 9, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_deterministic_output.py::28": {"resolved_imports": ["src/roam/output/formatter.py"], "used_names": ["json", "to_json"], "enclosing_function": "test_sort_keys_enabled", "extracted_code": "# Source: src/roam/output/formatter.py\ndef to_json(data) -> str:\n \"\"\"Serialize data to a JSON string with deterministic key ordering.\n\n Uses ``sort_keys=True`` so that identical data always produces\n byte-identical output — critical for LLM prompt-caching compatibility.\n \"\"\"\n return _json.dumps(data, indent=2, default=str, sort_keys=True)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 355}, "tests/test_defer_loading.py::91": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_non_core_tools_deferred", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_closure.py::91": {"resolved_imports": ["src/roam/cli.py"], "used_names": ["invoke_cli"], "enclosing_function": "test_closure_finds_definition", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_verify.py::416": {"resolved_imports": [], "used_names": ["git_commit", "index_in_process", "invoke_cli", "parse_json_output"], "enclosing_function": "test_json_violation_fields", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_competitor_site_data.py::157": {"resolved_imports": ["src/roam/competitor_site_data.py", "src/roam/surface_counts.py"], "used_names": ["build_site_payload"], "enclosing_function": "test_rubric_in_payload", "extracted_code": "# Source: src/roam/competitor_site_data.py\ndef build_site_payload(tracker_path: Path | None = None) -> dict[str, object]:\n path = tracker_path or default_tracker_path()\n lines = path.read_text(encoding=\"utf-8\").splitlines()\n\n tracker_updated = \"\"\n for line in lines:\n if line.startswith(\"> Updated:\"):\n tracker_updated = line.split(\":\", 1)[1].strip()\n break\n if not tracker_updated:\n raise ValueError(\"Could not parse tracker update line ('> Updated: ...').\")\n\n tracker_updated_iso = _parse_tracker_updated_iso(tracker_updated)\n confidence_map = _parse_matrix_confidence(lines)\n competitors = _matrix_to_competitors(lines, confidence_map, tracker_updated_iso)\n _append_ckb_from_leaderboard(lines, competitors, confidence_map, tracker_updated_iso)\n _append_extra_competitors(competitors, tracker_updated_iso)\n\n # Filter to landscape-included tools only.\n competitors = [c for c in competitors if str(c[\"name\"]) in LANDSCAPE_INCLUDE]\n\n # Keep visual map stable: order by descending analysis depth, then agent readiness.\n competitors.sort(key=lambda c: (-int(c[\"arch\"]), -int(c[\"agent\"]), str(c[\"name\"])))\n\n # Keep roam-code row count fields synced to source-of-truth command/tool registration.\n try:\n from roam.surface_counts import collect_surface_counts\n\n surface = collect_surface_counts()\n cli_counts = surface.get(\"cli\", {})\n mcp_counts = surface.get(\"mcp\", {})\n canonical = int(cli_counts.get(\"canonical_commands\", 0) or 0)\n alias_count = int(cli_counts.get(\"alias_names\", 0) or 0)\n mcp_tools = int(mcp_counts.get(\"registered_tools\", 0) or 0)\n for entry in competitors:\n if entry.get(\"name\") != \"roam-code\":\n continue\n entry[\"mcp\"] = str(mcp_tools)\n if alias_count > 0:\n entry[\"cli_commands\"] = f\"{canonical} canonical (+{alias_count} alias)\"\n else:\n entry[\"cli_commands\"] = str(canonical)\n break\n except Exception:\n # Do not fail payload generation if local surface-count parsing fails.\n pass\n\n methodology = {\n \"scoring_model\": [\n \"45 criteria across 7 categories, scored as binary (has/doesn't), count-tiered, or subjective.\",\n \"Y-axis (Analysis Depth) = Static Analysis (50%) + Graph Intelligence (25%) + Git Temporal (25%).\",\n \"X-axis (Agent Readiness) = Agent Integration (70%) + Ecosystem (30%).\",\n \"Security and Unique Capabilities affect total score only, not map position.\",\n \"All criteria scored by project maintainers. 44/45 are binary or tiered (count-based or depth-based). 1/45 is subjective (documentation quality).\",\n \"Weight sliders let viewers apply their own category priorities.\",\n ],\n \"limitations\": [\n \"Criteria selection bias: we chose which capabilities to measure, favoring tools with graph algorithms.\",\n \"Category weight bias: default weights reflect our perspective. Adjust sliders for yours.\",\n \"Assessment bias: we scored all competitors. Errors or missed capabilities are possible.\",\n \"Public vendor claims can be stale or inconsistent across pages.\",\n \"GitHub star counts may conflate main product repos with MCP extension repos.\",\n ],\n \"reproducibility\": {\n \"tracker\": str(path.relative_to(_repo_root())).replace(\"\\\\\", \"/\"),\n \"generator\": \"src/roam/competitor_site_data.py\",\n \"generated_at_reference\": tracker_updated_iso,\n },\n }\n\n # Rubric metadata for the frontend (weight sliders + methodology rendering)\n rubric_out: list[dict[str, object]] = []\n for cat in SCORING_RUBRIC:\n rubric_out.append(\n {\n \"id\": cat[\"id\"],\n \"label\": cat[\"label\"],\n \"max_points\": cat[\"max_points\"],\n \"default_weight\": cat[\"default_weight\"],\n \"criteria\": [{k: v for k, v in crit.items()} for crit in cat[\"criteria\"]],\n }\n )\n\n return {\n \"tracker_updated\": tracker_updated,\n \"tracker_updated_iso\": tracker_updated_iso,\n \"tracker_file\": str(path.relative_to(_repo_root())).replace(\"\\\\\", \"/\"),\n \"competitors\": competitors,\n \"methodology\": methodology,\n \"rubric\": rubric_out,\n }", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 4415}, "tests/test_doctor.py::130": {"resolved_imports": ["src/roam/cli.py"], "used_names": [], "enclosing_function": "test_python_check_passes_current_version", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_capsule.py::129": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_capsule_has_topology", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_closure.py::94": {"resolved_imports": ["src/roam/cli.py"], "used_names": ["invoke_cli"], "enclosing_function": "test_closure_finds_definition", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_defer_loading.py::116": {"resolved_imports": [], "used_names": ["annotations"], "enclosing_function": "test_deferred_tools_have_annotations_object", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_fingerprint.py::56": {"resolved_imports": ["src/roam/db/connection.py", "src/roam/graph/builder.py", "src/roam/graph/fingerprint.py"], "used_names": ["build_symbol_graph", "compute_fingerprint", "open_db"], "enclosing_function": "test_compute_fingerprint_returns_dict", "extracted_code": "# Source: src/roam/db/connection.py\ndef open_db(readonly: bool = False, project_root: Path | None = None):\n \"\"\"Context manager for database access. Creates schema if needed.\n\n Raises a descriptive ``click.ClickException`` if the database file is\n missing or corrupted so that agents receive actionable remediation steps\n instead of a raw SQLite traceback.\n \"\"\"\n import click\n\n db_path = get_db_path(project_root)\n try:\n conn = get_connection(db_path, readonly=readonly)\n except sqlite3.DatabaseError as exc:\n raise click.ClickException(\n f\"Database error: {exc}\\n\"\n \" The roam index may be corrupted. Run `roam init --force` to rebuild it\\n\"\n \" from scratch, or delete .roam/index.db and run `roam init`.\"\n ) from exc\n try:\n if not readonly:\n try:\n ensure_schema(conn)\n except sqlite3.DatabaseError as exc:\n conn.close()\n raise click.ClickException(\n f\"Database schema error: {exc}\\n\"\n \" The roam index may be corrupted or from an incompatible version.\\n\"\n \" Run `roam init --force` to rebuild it, or delete .roam/index.db\\n\"\n \" and run `roam init`.\"\n ) from exc\n yield conn\n if not readonly:\n conn.commit()\n finally:\n conn.close()\n\n\n# Source: src/roam/graph/builder.py\ndef build_symbol_graph(conn: sqlite3.Connection) -> nx.DiGraph:\n \"\"\"Build a directed graph from symbol edges.\n\n Nodes are symbol IDs with attributes: name, kind, file_path, qualified_name.\n Edges carry a ``kind`` attribute (calls, imports, inherits, etc.).\n \"\"\"\n G = nx.DiGraph()\n\n # Load nodes (ORDER BY id for deterministic graph construction)\n rows = conn.execute(\n \"SELECT s.id, s.name, s.kind, s.qualified_name, f.path AS file_path \"\n \"FROM symbols s JOIN files f ON s.file_id = f.id \"\n \"ORDER BY s.id\"\n ).fetchall()\n G.add_nodes_from(\n (row[0], {\"name\": row[1], \"kind\": row[2], \"qualified_name\": row[3], \"file_path\": row[4]}) for row in rows\n )\n\n # Load edges — pre-build node set for O(1) membership checks\n # ORDER BY for deterministic edge insertion order\n node_set = set(G)\n rows = conn.execute(\"SELECT source_id, target_id, kind FROM edges ORDER BY source_id, target_id\").fetchall()\n G.add_edges_from(\n (source_id, target_id, {\"kind\": kind})\n for source_id, target_id, kind in rows\n if source_id in node_set and target_id in node_set\n )\n\n return G\n\n\n# Source: src/roam/graph/fingerprint.py\ndef compute_fingerprint(conn: sqlite3.Connection, G: nx.DiGraph) -> dict:\n \"\"\"Extract a topology fingerprint from the indexed graph.\n\n The fingerprint captures the structural signature of the codebase\n without any source code, enabling cross-repo comparison and\n architectural pattern transfer.\n\n Parameters\n ----------\n conn : sqlite3.Connection\n Open roam database connection.\n G : nx.DiGraph\n Symbol graph built from the database.\n\n Returns\n -------\n dict\n Fingerprint with topology, clusters, hub_bridge_ratio,\n pagerank_gini, dependency_direction, and antipatterns sections.\n \"\"\"\n from roam.graph.clusters import cluster_quality, detect_clusters, label_clusters\n from roam.graph.cycles import algebraic_connectivity, find_cycles\n from roam.graph.layers import detect_layers\n from roam.graph.pagerank import compute_pagerank\n\n n_nodes = len(G)\n\n # -- Layers --\n layers = detect_layers(G)\n max_layer = max(layers.values(), default=0)\n n_layers = max_layer + 1 if layers else 0\n\n # Layer distribution (% of nodes per layer)\n layer_counts: dict[int, int] = Counter(layers.values())\n layer_distribution = []\n for i in range(n_layers):\n pct = round(layer_counts.get(i, 0) * 100 / n_nodes, 1) if n_nodes > 0 else 0.0\n layer_distribution.append(pct)\n\n # -- Algebraic connectivity (Fiedler) --\n fiedler = algebraic_connectivity(G)\n\n # -- Clusters & modularity --\n cluster_map = detect_clusters(G)\n quality = cluster_quality(G, cluster_map)\n modularity = quality[\"modularity\"]\n\n # -- Tangle ratio: fraction of nodes in non-trivial SCCs --\n sccs = find_cycles(G, min_size=2)\n tangled_nodes = sum(len(scc) for scc in sccs)\n tangle_ratio = round(tangled_nodes / n_nodes, 4) if n_nodes > 0 else 0.0\n\n # -- Dependency direction --\n dep_direction = _dependency_direction(G, layers)\n\n # -- Cluster summaries --\n cluster_labels = label_clusters(cluster_map, conn)\n groups: dict[int, list[int]] = defaultdict(list)\n for nid, cid in cluster_map.items():\n groups[cid].append(nid)\n\n # Determine which layer each cluster mostly lives in\n cluster_summaries = []\n for cid, members in sorted(groups.items(), key=lambda x: -len(x[1])):\n size_pct = round(len(members) * 100 / n_nodes, 1) if n_nodes > 0 else 0.0\n conductance = quality[\"per_cluster\"].get(cid, 0.0)\n # Most common layer for this cluster\n member_layers = [layers.get(m, 0) for m in members]\n majority_layer = Counter(member_layers).most_common(1)[0][0] if member_layers else 0\n\n # Roles distribution (kind counts)\n roles: dict[str, int] = Counter()\n for m in members:\n data = G.nodes.get(m, {})\n kind = data.get(\"kind\", \"unknown\")\n roles[kind] += 1\n\n pattern = _classify_cluster_pattern(size_pct, conductance)\n\n cluster_summaries.append(\n {\n \"label\": cluster_labels.get(cid, f\"cluster-{cid}\"),\n \"layer\": majority_layer,\n \"size_pct\": size_pct,\n \"conductance\": conductance,\n \"roles\": dict(roles),\n \"pattern\": pattern,\n }\n )\n\n # -- PageRank Gini --\n pr = compute_pagerank(G)\n pagerank_gini = _gini_coefficient(list(pr.values())) if pr else 0.0\n\n # -- Hub/bridge ratio --\n hb_ratio = _hub_bridge_ratio(G)\n\n # -- Anti-patterns --\n # God objects: nodes with degree > 2 * average degree\n avg_degree = (sum(G.degree(n) for n in G) / n_nodes) if n_nodes > 0 else 0\n god_threshold = max(avg_degree * 2, 5)\n god_objects = sum(1 for n in G if G.degree(n) > god_threshold)\n\n # Cyclic clusters: SCCs that span multiple clusters\n cyclic_clusters = 0\n for scc in sccs:\n scc_cluster_ids = {cluster_map.get(n) for n in scc if n in cluster_map}\n scc_cluster_ids.discard(None)\n if len(scc_cluster_ids) > 1:\n cyclic_clusters += 1\n\n # -- Assemble fingerprint --\n fingerprint = {\n \"topology\": {\n \"layers\": n_layers,\n \"layer_distribution\": layer_distribution,\n \"fiedler\": fiedler,\n \"modularity\": modularity,\n \"tangle_ratio\": tangle_ratio,\n },\n \"clusters\": cluster_summaries,\n \"hub_bridge_ratio\": hb_ratio,\n \"pagerank_gini\": pagerank_gini,\n \"dependency_direction\": dep_direction,\n \"antipatterns\": {\n \"god_objects\": god_objects,\n \"cyclic_clusters\": cyclic_clusters,\n },\n }\n return fingerprint", "n_imports_parsed": 11, "n_files_resolved": 3, "n_chars_extracted": 7286}, "tests/test_n1.py::225": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_json_command_field_is_n1", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_affected.py::119": {"resolved_imports": ["src/roam/cli.py"], "used_names": ["cli"], "enclosing_function": "test_affected_help", "extracted_code": "# Source: src/roam/cli.py\ndef cli(ctx, json_mode, compact, agent, sarif_mode, budget, include_excluded, detail):\n \"\"\"Roam: Codebase comprehension tool.\"\"\"\n if agent and sarif_mode:\n raise click.UsageError(\"--agent cannot be combined with --sarif\")\n\n # Agent mode is optimized for CLI-invoked sub-agents:\n # - forces JSON for machine parsing\n # - uses compact envelope to reduce token overhead\n # - defaults to 500-token budget unless user overrides with --budget\n if agent:\n json_mode = True\n compact = True\n if budget <= 0:\n budget = 500\n\n ctx.ensure_object(dict)\n ctx.obj[\"json\"] = json_mode\n ctx.obj[\"compact\"] = compact\n ctx.obj[\"agent\"] = agent\n ctx.obj[\"sarif\"] = sarif_mode\n ctx.obj[\"budget\"] = budget\n ctx.obj[\"include_excluded\"] = include_excluded\n ctx.obj[\"detail\"] = detail", "n_imports_parsed": 8, "n_files_resolved": 1, "n_chars_extracted": 868}, "tests/test_commands_exploration.py::55": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_search_finds_symbol", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_sna_metrics.py::48": {"resolved_imports": ["src/roam/db/connection.py"], "used_names": ["open_db", "os", "pytest"], "enclosing_function": "test_graph_metrics_populates_sna_v2_values", "extracted_code": "# Source: src/roam/db/connection.py\ndef open_db(readonly: bool = False, project_root: Path | None = None):\n \"\"\"Context manager for database access. Creates schema if needed.\n\n Raises a descriptive ``click.ClickException`` if the database file is\n missing or corrupted so that agents receive actionable remediation steps\n instead of a raw SQLite traceback.\n \"\"\"\n import click\n\n db_path = get_db_path(project_root)\n try:\n conn = get_connection(db_path, readonly=readonly)\n except sqlite3.DatabaseError as exc:\n raise click.ClickException(\n f\"Database error: {exc}\\n\"\n \" The roam index may be corrupted. Run `roam init --force` to rebuild it\\n\"\n \" from scratch, or delete .roam/index.db and run `roam init`.\"\n ) from exc\n try:\n if not readonly:\n try:\n ensure_schema(conn)\n except sqlite3.DatabaseError as exc:\n conn.close()\n raise click.ClickException(\n f\"Database schema error: {exc}\\n\"\n \" The roam index may be corrupted or from an incompatible version.\\n\"\n \" Run `roam init --force` to rebuild it, or delete .roam/index.db\\n\"\n \" and run `roam init`.\"\n ) from exc\n yield conn\n if not readonly:\n conn.commit()\n finally:\n conn.close()", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 1420}, "tests/test_formatters.py::38": {"resolved_imports": ["src/roam/output/formatter.py"], "used_names": ["abbrev_kind"], "enclosing_function": "test_variable", "extracted_code": "# Source: src/roam/output/formatter.py\ndef abbrev_kind(kind: str) -> str:\n return KIND_ABBREV.get(kind, kind)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 112}, "tests/test_progress.py::251": {"resolved_imports": ["src/roam/index/indexer.py"], "used_names": ["_format_count"], "enclosing_function": "test_small_number", "extracted_code": "# Source: src/roam/index/indexer.py\ndef _format_count(n: int) -> str:\n \"\"\"Format an integer with thousands separators.\"\"\"\n return f\"{n:,}\"", "n_imports_parsed": 10, "n_files_resolved": 1, "n_chars_extracted": 144}, "tests/test_codeowners.py::48": {"resolved_imports": ["src/roam/commands/cmd_codeowners.py"], "used_names": ["parse_codeowners"], "enclosing_function": "test_multiple_owners", "extracted_code": "# Source: src/roam/commands/cmd_codeowners.py\n _codeowners_match,\n find_codeowners,\n parse_codeowners,\n resolve_owners,\n)\nfrom roam.commands.resolve import ensure_index\nfrom roam.db.connection import find_project_root, open_db\nfrom roam.output.formatter import format_table, json_envelope, to_json\n\n# ---------------------------------------------------------------------------\n# Analysis helpers\n# ---------------------------------------------------------------------------\n\n return\n\n rules = parse_codeowners(co_path)\n co_relpath = str(co_path.relative_to(project_root)).replace(\"\\\\\", \"/\")\n\n with open_db(readonly=True) as conn:\n # Get all indexed files\n all_files = conn.execute(\"SELECT id, path FROM files ORDER BY path\").fetchall()\n\n if not all_files:\n if json_mode:\n click.echo(", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 858}, "tests/test_gate_presets.py::50": {"resolved_imports": ["src/roam/commands/gate_presets.py"], "used_names": ["get_preset"], "enclosing_function": "test_get_go_preset", "extracted_code": "# Source: src/roam/commands/gate_presets.py\ndef get_preset(name: str) -> GatePreset | None:\n \"\"\"Get a preset by name.\"\"\"\n for p in ALL_PRESETS:\n if p.name == name:\n return p\n return None", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 213}, "tests/test_clones.py::76": {"resolved_imports": ["src/roam/cli.py"], "used_names": ["CliRunner", "cli", "os"], "enclosing_function": "test_identical_functions_detected", "extracted_code": "# Source: src/roam/cli.py\ndef cli(ctx, json_mode, compact, agent, sarif_mode, budget, include_excluded, detail):\n \"\"\"Roam: Codebase comprehension tool.\"\"\"\n if agent and sarif_mode:\n raise click.UsageError(\"--agent cannot be combined with --sarif\")\n\n # Agent mode is optimized for CLI-invoked sub-agents:\n # - forces JSON for machine parsing\n # - uses compact envelope to reduce token overhead\n # - defaults to 500-token budget unless user overrides with --budget\n if agent:\n json_mode = True\n compact = True\n if budget <= 0:\n budget = 500\n\n ctx.ensure_object(dict)\n ctx.obj[\"json\"] = json_mode\n ctx.obj[\"compact\"] = compact\n ctx.obj[\"agent\"] = agent\n ctx.obj[\"sarif\"] = sarif_mode\n ctx.obj[\"budget\"] = budget\n ctx.obj[\"include_excluded\"] = include_excluded\n ctx.obj[\"detail\"] = detail", "n_imports_parsed": 8, "n_files_resolved": 1, "n_chars_extracted": 868}, "tests/test_agent_mode.py::34": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_agent_mode_respects_explicit_budget", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_competitor_site_data.py::55": {"resolved_imports": ["src/roam/competitor_site_data.py", "src/roam/surface_counts.py"], "used_names": ["build_site_payload", "re"], "enclosing_function": "test_competitor_rows_include_evidence_metadata", "extracted_code": "# Source: src/roam/competitor_site_data.py\ndef build_site_payload(tracker_path: Path | None = None) -> dict[str, object]:\n path = tracker_path or default_tracker_path()\n lines = path.read_text(encoding=\"utf-8\").splitlines()\n\n tracker_updated = \"\"\n for line in lines:\n if line.startswith(\"> Updated:\"):\n tracker_updated = line.split(\":\", 1)[1].strip()\n break\n if not tracker_updated:\n raise ValueError(\"Could not parse tracker update line ('> Updated: ...').\")\n\n tracker_updated_iso = _parse_tracker_updated_iso(tracker_updated)\n confidence_map = _parse_matrix_confidence(lines)\n competitors = _matrix_to_competitors(lines, confidence_map, tracker_updated_iso)\n _append_ckb_from_leaderboard(lines, competitors, confidence_map, tracker_updated_iso)\n _append_extra_competitors(competitors, tracker_updated_iso)\n\n # Filter to landscape-included tools only.\n competitors = [c for c in competitors if str(c[\"name\"]) in LANDSCAPE_INCLUDE]\n\n # Keep visual map stable: order by descending analysis depth, then agent readiness.\n competitors.sort(key=lambda c: (-int(c[\"arch\"]), -int(c[\"agent\"]), str(c[\"name\"])))\n\n # Keep roam-code row count fields synced to source-of-truth command/tool registration.\n try:\n from roam.surface_counts import collect_surface_counts\n\n surface = collect_surface_counts()\n cli_counts = surface.get(\"cli\", {})\n mcp_counts = surface.get(\"mcp\", {})\n canonical = int(cli_counts.get(\"canonical_commands\", 0) or 0)\n alias_count = int(cli_counts.get(\"alias_names\", 0) or 0)\n mcp_tools = int(mcp_counts.get(\"registered_tools\", 0) or 0)\n for entry in competitors:\n if entry.get(\"name\") != \"roam-code\":\n continue\n entry[\"mcp\"] = str(mcp_tools)\n if alias_count > 0:\n entry[\"cli_commands\"] = f\"{canonical} canonical (+{alias_count} alias)\"\n else:\n entry[\"cli_commands\"] = str(canonical)\n break\n except Exception:\n # Do not fail payload generation if local surface-count parsing fails.\n pass\n\n methodology = {\n \"scoring_model\": [\n \"45 criteria across 7 categories, scored as binary (has/doesn't), count-tiered, or subjective.\",\n \"Y-axis (Analysis Depth) = Static Analysis (50%) + Graph Intelligence (25%) + Git Temporal (25%).\",\n \"X-axis (Agent Readiness) = Agent Integration (70%) + Ecosystem (30%).\",\n \"Security and Unique Capabilities affect total score only, not map position.\",\n \"All criteria scored by project maintainers. 44/45 are binary or tiered (count-based or depth-based). 1/45 is subjective (documentation quality).\",\n \"Weight sliders let viewers apply their own category priorities.\",\n ],\n \"limitations\": [\n \"Criteria selection bias: we chose which capabilities to measure, favoring tools with graph algorithms.\",\n \"Category weight bias: default weights reflect our perspective. Adjust sliders for yours.\",\n \"Assessment bias: we scored all competitors. Errors or missed capabilities are possible.\",\n \"Public vendor claims can be stale or inconsistent across pages.\",\n \"GitHub star counts may conflate main product repos with MCP extension repos.\",\n ],\n \"reproducibility\": {\n \"tracker\": str(path.relative_to(_repo_root())).replace(\"\\\\\", \"/\"),\n \"generator\": \"src/roam/competitor_site_data.py\",\n \"generated_at_reference\": tracker_updated_iso,\n },\n }\n\n # Rubric metadata for the frontend (weight sliders + methodology rendering)\n rubric_out: list[dict[str, object]] = []\n for cat in SCORING_RUBRIC:\n rubric_out.append(\n {\n \"id\": cat[\"id\"],\n \"label\": cat[\"label\"],\n \"max_points\": cat[\"max_points\"],\n \"default_weight\": cat[\"default_weight\"],\n \"criteria\": [{k: v for k, v in crit.items()} for crit in cat[\"criteria\"]],\n }\n )\n\n return {\n \"tracker_updated\": tracker_updated,\n \"tracker_updated_iso\": tracker_updated_iso,\n \"tracker_file\": str(path.relative_to(_repo_root())).replace(\"\\\\\", \"/\"),\n \"competitors\": competitors,\n \"methodology\": methodology,\n \"rubric\": rubric_out,\n }", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 4415}, "tests/test_ci_sarif_guard.py::56": {"resolved_imports": [], "used_names": ["json"], "enclosing_function": "test_merge_sarif_files_skips_invalid", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_docker_assets.py::19": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_dockerfile_is_alpine_based", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_basic.py::48": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_index", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_congestion.py::79": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_verdict_line", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_bridges.py::78": {"resolved_imports": ["src/roam/bridges/__init__.py", "src/roam/bridges/registry.py", "src/roam/bridges/base.py", "src/roam/bridges/bridge_protobuf.py", "src/roam/bridges/bridge_salesforce.py"], "used_names": ["ProtobufBridge", "SalesforceBridge"], "enclosing_function": "test_register_multiple", "extracted_code": "# Source: src/roam/bridges/bridge_protobuf.py\nclass ProtobufBridge(LanguageBridge):\n \"\"\"Bridge between .proto definitions and generated language stubs.\"\"\"\n\n @property\n def name(self) -> str:\n return \"protobuf\"\n\n @property\n def source_extensions(self) -> frozenset[str]:\n return _PROTO_EXT\n\n @property\n def target_extensions(self) -> frozenset[str]:\n return _TARGET_EXTS\n\n def detect(self, file_paths: list[str]) -> bool:\n \"\"\"Detect if project has .proto files and potential generated stubs.\"\"\"\n has_proto = False\n has_generated = False\n for fp in file_paths:\n ext = os.path.splitext(fp)[1].lower()\n if ext == \".proto\":\n has_proto = True\n # Check for generated stub patterns\n basename = os.path.basename(fp)\n for pattern in _GENERATED_PATTERNS.values():\n if pattern.search(basename):\n has_generated = True\n break\n if has_proto and has_generated:\n return True\n return False\n\n def resolve(self, source_path: str, source_symbols: list[dict], target_files: dict[str, list[dict]]) -> list[dict]:\n \"\"\"Resolve .proto symbols to their generated stubs.\n\n Resolution strategies:\n 1. File naming: foo.proto -> foo_pb2.py, foo.pb.go, etc.\n 2. Symbol naming: message MyMessage -> class MyMessage (Python),\n struct MyMessage (Go), MyMessage (Java inner class)\n 3. Service naming: service MyService -> MyServiceClient, MyServiceServer\n \"\"\"\n edges: list[dict] = []\n source_ext = os.path.splitext(source_path)[1].lower()\n\n if source_ext != \".proto\":\n return edges\n\n # Get the proto file stem (e.g., \"foo\" from \"foo.proto\")\n proto_stem = os.path.basename(source_path).rsplit(\".\", 1)[0]\n\n # Classify source symbols into messages, services, enums\n messages = []\n services = []\n enums = []\n for sym in source_symbols:\n kind = sym.get(\"kind\", \"\")\n if kind in (\"message\", \"class\", \"struct\"):\n messages.append(sym)\n elif kind in (\"service\", \"interface\"):\n services.append(sym)\n elif kind == \"enum\":\n enums.append(sym)\n\n # Find generated target files that correspond to this proto\n generated_targets = self._find_generated_files(proto_stem, target_files)\n\n # For each generated file, try to match symbols\n for tpath, tsymbols, lang in generated_targets:\n target_symbol_names = {sym.get(\"name\", \"\"): sym.get(\"qualified_name\", \"\") for sym in tsymbols}\n\n # Match message symbols\n for msg in messages:\n msg_name = msg.get(\"name\", \"\")\n msg_qname = msg.get(\"qualified_name\", msg_name)\n matched = self._match_message(msg_name, target_symbol_names, lang)\n for target_qname in matched:\n edges.append(\n {\n \"source\": msg_qname,\n \"target\": target_qname,\n \"kind\": \"x-lang\",\n \"bridge\": self.name,\n \"mechanism\": \"proto-message\",\n \"target_lang\": lang,\n }\n )\n\n # Match service symbols\n for svc in services:\n svc_name = svc.get(\"name\", \"\")\n svc_qname = svc.get(\"qualified_name\", svc_name)\n matched = self._match_service(svc_name, target_symbol_names, lang)\n for target_qname in matched:\n edges.append(\n {\n \"source\": svc_qname,\n \"target\": target_qname,\n \"kind\": \"x-lang\",\n \"bridge\": self.name,\n \"mechanism\": \"proto-service\",\n \"target_lang\": lang,\n }\n )\n\n # Match enum symbols\n for enum in enums:\n enum_name = enum.get(\"name\", \"\")\n enum_qname = enum.get(\"qualified_name\", enum_name)\n matched = self._match_enum(enum_name, target_symbol_names, lang)\n for target_qname in matched:\n edges.append(\n {\n \"source\": enum_qname,\n \"target\": target_qname,\n \"kind\": \"x-lang\",\n \"bridge\": self.name,\n \"mechanism\": \"proto-enum\",\n \"target_lang\": lang,\n }\n )\n\n return edges\n\n def _find_generated_files(\n self, proto_stem: str, target_files: dict[str, list[dict]]\n ) -> list[tuple[str, list[dict], str]]:\n \"\"\"Find target files that were likely generated from this proto.\n\n Returns list of (path, symbols, language) tuples.\n \"\"\"\n results = []\n proto_lower = proto_stem.lower()\n\n for tpath, tsymbols in target_files.items():\n basename = os.path.basename(tpath).lower()\n\n # Check each language pattern\n for lang, pattern in _GENERATED_PATTERNS.items():\n if pattern.search(basename):\n # Verify the stem matches the proto file\n # e.g., \"foo_pb2.py\" stem is \"foo\", \"foo.pb.go\" stem is \"foo\"\n generated_stem = self._extract_stem(basename, lang)\n if generated_stem and generated_stem == proto_lower:\n results.append((tpath, tsymbols, lang))\n break # Only match one language per file\n\n return results\n\n def _extract_stem(self, basename: str, lang: str) -> str | None:\n \"\"\"Extract the original proto stem from a generated filename.\n\n E.g., \"foo_pb2.py\" -> \"foo\", \"foo.pb.go\" -> \"foo\"\n \"\"\"\n lower = basename.lower()\n if lang == \"python\":\n # foo_pb2.py or foo_pb2.pyi\n m = re.match(r\"^(.+)_pb2\\.pyi?$\", lower)\n return m.group(1) if m else None\n elif lang == \"go\":\n # foo.pb.go\n m = re.match(r\"^(.+)\\.pb\\.go$\", lower)\n return m.group(1) if m else None\n elif lang == \"java\":\n # FooOuterClass.java or FooGrpc.java or FooProto.java\n m = re.match(r\"^(.+?)(?:outerclass|grpc|proto)\\.java$\", lower)\n return m.group(1) if m else None\n elif lang in (\"cpp_header\", \"cpp_source\"):\n # foo.pb.h or foo.pb.cc\n m = re.match(r\"^(.+)\\.pb\\.(?:h|cc)$\", lower)\n return m.group(1) if m else None\n elif lang == \"typescript\":\n # foo_pb.ts or foo_pb.d.ts\n m = re.match(r\"^(.+)_pb\\.(?:d\\.)?ts$\", lower)\n return m.group(1) if m else None\n elif lang == \"javascript\":\n # foo_pb.js\n m = re.match(r\"^(.+)_pb\\.js$\", lower)\n return m.group(1) if m else None\n elif lang == \"csharp\":\n # Foo.g.cs\n m = re.match(r\"^(.+)\\.g\\.cs$\", lower)\n return m.group(1) if m else None\n elif lang == \"ruby\":\n # foo_pb.rb\n m = re.match(r\"^(.+)_pb\\.rb$\", lower)\n return m.group(1) if m else None\n return None\n\n def _match_message(self, msg_name: str, target_names: dict[str, str], lang: str) -> list[str]:\n \"\"\"Match a proto message name to generated symbols.\n\n Naming conventions vary by language:\n - Python: class MyMessage in *_pb2.py (exact name)\n - Go: struct MyMessage in *.pb.go (CamelCase preserved)\n - Java: inner class MyMessage inside OuterClass\n - C++: class MyMessage in namespace\n \"\"\"\n matched = []\n msg_lower = msg_name.lower()\n\n for sym_name, sym_qname in target_names.items():\n sym_lower = sym_name.lower()\n\n # Exact match (most common for Python, Go, C++)\n if sym_lower == msg_lower:\n matched.append(sym_qname)\n continue\n\n # Go: proto snake_case -> CamelCase\n # e.g., my_message -> MyMessage\n if lang == \"go\" and self._snake_to_camel(msg_name).lower() == sym_lower:\n matched.append(sym_qname)\n continue\n\n # Java: OuterClass.MessageName pattern\n if lang == \"java\" and sym_lower.endswith(\".\" + msg_lower):\n matched.append(sym_qname)\n continue\n\n return matched\n\n def _match_service(self, svc_name: str, target_names: dict[str, str], lang: str) -> list[str]:\n \"\"\"Match a proto service name to generated symbols.\n\n Generated service stubs commonly use suffixes:\n - Python: MyServiceStub, MyServiceServicer\n - Go: MyServiceClient, MyServiceServer\n - Java: MyServiceGrpc, MyServiceBlockingStub\n \"\"\"\n matched = []\n svc_lower = svc_name.lower()\n\n # Common generated suffixes for service stubs\n suffixes = [\n \"\", # exact match\n \"client\",\n \"server\",\n \"stub\",\n \"servicer\",\n \"grpc\",\n \"blockingstub\",\n \"futurestub\",\n \"implbase\",\n ]\n\n for sym_name, sym_qname in target_names.items():\n sym_lower = sym_name.lower()\n for suffix in suffixes:\n if sym_lower == svc_lower + suffix:\n matched.append(sym_qname)\n break\n # Also check with underscore separator (Python style)\n if suffix and sym_lower == svc_lower + \"_\" + suffix:\n matched.append(sym_qname)\n break\n\n return matched\n\n def _match_enum(self, enum_name: str, target_names: dict[str, str], lang: str) -> list[str]:\n \"\"\"Match a proto enum name to generated symbols.\n\n Enums generally keep their name across languages.\n \"\"\"\n matched = []\n enum_lower = enum_name.lower()\n\n for sym_name, sym_qname in target_names.items():\n sym_lower = sym_name.lower()\n\n # Exact match\n if sym_lower == enum_lower:\n matched.append(sym_qname)\n continue\n\n # Go CamelCase conversion\n if lang == \"go\" and self._snake_to_camel(enum_name).lower() == sym_lower:\n matched.append(sym_qname)\n continue\n\n return matched\n\n def _snake_to_camel(self, name: str) -> str:\n \"\"\"Convert snake_case to CamelCase.\n\n E.g., my_message -> MyMessage, already_camel -> AlreadyCamel\n \"\"\"\n if \"_\" not in name:\n # Already CamelCase or single word; just capitalize first letter\n return name[0].upper() + name[1:] if name else name\n parts = name.split(\"_\")\n return \"\".join(p.capitalize() for p in parts if p)\n\n\n# Source: src/roam/bridges/bridge_salesforce.py\nclass SalesforceBridge(LanguageBridge):\n \"\"\"Bridge between Apex controllers and Aura/LWC/Visualforce templates.\"\"\"\n\n @property\n def name(self) -> str:\n return \"salesforce\"\n\n @property\n def source_extensions(self) -> frozenset[str]:\n return _APEX_EXTS\n\n @property\n def target_extensions(self) -> frozenset[str]:\n return _SF_MARKUP_EXTS\n\n def detect(self, file_paths: list[str]) -> bool:\n \"\"\"Detect if project has both Apex and markup files.\"\"\"\n has_apex = False\n has_markup = False\n for fp in file_paths:\n ext = os.path.splitext(fp)[1].lower()\n if ext in _APEX_EXTS:\n has_apex = True\n if ext in _SF_MARKUP_EXTS:\n has_markup = True\n if has_apex and has_markup:\n return True\n return False\n\n def resolve(self, source_path: str, source_symbols: list[dict], target_files: dict[str, list[dict]]) -> list[dict]:\n \"\"\"Resolve Apex-to-markup cross-language links.\n\n Resolution strategies:\n 1. Naming convention: MyController.cls -> MyController.cmp\n 2. Controller attribute: \n 3. @AuraEnabled methods: match to components referencing that controller\n \"\"\"\n edges: list[dict] = []\n source_ext = os.path.splitext(source_path)[1].lower()\n\n if source_ext not in _APEX_EXTS:\n return edges\n\n # Get the Apex class name from the file path\n apex_class_name = os.path.basename(source_path).rsplit(\".\", 1)[0]\n\n # Build a lookup of target symbols by qualified name for fast matching\n target_symbol_index: dict[str, str] = {} # symbol_name -> qualified_name\n # Track which target files reference this Apex class as a controller\n controller_targets: list[tuple[str, list[dict]]] = []\n\n for tpath, tsymbols in target_files.items():\n text_ext = os.path.splitext(tpath)[1].lower()\n if text_ext not in _SF_MARKUP_EXTS:\n continue\n\n for sym in tsymbols:\n target_symbol_index[sym.get(\"name\", \"\")] = sym.get(\"qualified_name\", \"\")\n\n # Check if any target symbol references this Apex class\n # Aura components reference controllers via naming convention or\n # controller attribute (already extracted as references by AuraExtractor)\n target_basename = os.path.basename(tpath).rsplit(\".\", 1)[0]\n\n # Strategy 1: Naming convention match\n # MyController.cls -> MyController.cmp (same name)\n # MyController.cls -> MyControllerCmp.cmp (with suffix)\n if self._names_match(apex_class_name, target_basename):\n controller_targets.append((tpath, tsymbols))\n # Create edge from Apex class to the component\n edges.append(\n {\n \"source\": apex_class_name,\n \"target\": target_basename,\n \"kind\": \"x-lang\",\n \"bridge\": self.name,\n \"mechanism\": \"naming-convention\",\n }\n )\n\n # Strategy 2: Match @AuraEnabled methods to components that reference\n # this controller. Any component whose controller is this Apex class\n # can call its @AuraEnabled methods.\n aura_enabled_methods = self._find_aura_enabled_methods(source_symbols)\n\n for method_name, method_qname in aura_enabled_methods:\n for tpath, tsymbols in controller_targets:\n target_basename = os.path.basename(tpath).rsplit(\".\", 1)[0]\n edges.append(\n {\n \"source\": method_qname,\n \"target\": target_basename,\n \"kind\": \"x-lang\",\n \"bridge\": self.name,\n \"mechanism\": \"aura-enabled\",\n }\n )\n\n # Strategy 3: Check for Visualforce controller references\n # Visualforce pages specify controller=\"ClassName\" in \n # The VF extractor already extracts these as \"controller\" references,\n # but we create x-lang edges for them here\n for tpath, tsymbols in target_files.items():\n text_ext = os.path.splitext(tpath)[1].lower()\n if text_ext not in (\".page\", \".component\"):\n continue\n target_basename = os.path.basename(tpath).rsplit(\".\", 1)[0]\n # Check if any symbol in the target references this Apex class\n # We look for the component-level symbol whose name matches\n for sym in tsymbols:\n # Visualforce pages are top-level symbols of kind \"page\"/\"component\"\n if sym.get(\"kind\") in (\"page\", \"component\"):\n # The VF extractor creates controller references; check if\n # this Apex class is referenced by name in the target path\n # (We rely on naming convention or explicit controller attr)\n if self._names_match(apex_class_name, target_basename):\n # Already handled by strategy 1 above; skip duplicate\n pass\n\n return edges\n\n def _names_match(self, apex_name: str, target_name: str) -> bool:\n \"\"\"Check if an Apex class name matches a component name.\n\n Supports common Salesforce naming conventions:\n - Exact match: MyController -> MyController\n - Controller suffix: MyController -> My (component uses class as controller)\n - Component suffix: MyClass -> MyClassController (Apex has Controller suffix)\n \"\"\"\n apex_lower = apex_name.lower()\n target_lower = target_name.lower()\n\n # Exact match\n if apex_lower == target_lower:\n return True\n\n # Apex name is target + \"Controller\" suffix\n # e.g., MyComponentController.cls -> MyComponent.cmp\n if apex_lower == target_lower + \"controller\":\n return True\n\n # Target name is apex + \"Controller\" suffix (less common but possible)\n if target_lower == apex_lower + \"controller\":\n return True\n\n return False\n\n def _find_aura_enabled_methods(self, symbols: list[dict]) -> list[tuple[str, str]]:\n \"\"\"Find methods with @AuraEnabled annotation.\n\n Returns list of (method_name, qualified_name) tuples.\n \"\"\"\n results = []\n for sym in symbols:\n kind = sym.get(\"kind\", \"\")\n if kind not in (\"method\", \"function\"):\n continue\n sig = sym.get(\"signature\", \"\") or \"\"\n # Check if the signature or annotations contain @AuraEnabled\n if _AURA_ENABLED_RE.search(sig):\n results.append((sym.get(\"name\", \"\"), sym.get(\"qualified_name\", \"\")))\n continue\n # Also check docstring/annotations if stored there\n doc = sym.get(\"docstring\", \"\") or \"\"\n if _AURA_ENABLED_RE.search(doc):\n results.append((sym.get(\"name\", \"\"), sym.get(\"qualified_name\", \"\")))\n return results", "n_imports_parsed": 6, "n_files_resolved": 5, "n_chars_extracted": 18444}, "tests/test_docs_coverage.py::93": {"resolved_imports": ["src/roam/exit_codes.py"], "used_names": ["invoke_cli"], "enclosing_function": "test_docs_coverage_runs", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_pagerank_truncation.py::83": {"resolved_imports": ["src/roam/output/formatter.py"], "used_names": ["_sort_by_importance"], "enclosing_function": "test_score_key", "extracted_code": "# Source: src/roam/output/formatter.py\ndef _sort_by_importance(items: list) -> tuple[list, bool]:\n \"\"\"Sort list items by importance descending if they carry an importance key.\n\n Returns ``(sorted_list, was_sorted)``. When no recognised importance\n key is found in the first dict item, the original order is preserved\n and ``was_sorted`` is ``False``.\n \"\"\"\n if not items:\n return items, False\n\n # Only attempt importance-sorting on lists of dicts\n first = items[0]\n if not isinstance(first, dict):\n return items, False\n\n # Find the importance key present in items\n imp_key: str | None = None\n for candidate in _IMPORTANCE_KEYS:\n if candidate in first:\n imp_key = candidate\n break\n\n if imp_key is None:\n return items, False\n\n # Sort descending by importance (highest first → kept on truncation)\n try:\n sorted_items = sorted(\n items,\n key=lambda d: d.get(imp_key, 0) if isinstance(d, dict) else 0,\n reverse=True,\n )\n return sorted_items, True\n except (TypeError, ValueError):\n return items, False", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1153}, "tests/test_flag_dead.py::111": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_verdict_line", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_context_propagation.py::213": {"resolved_imports": ["src/roam/graph/propagation.py"], "used_names": ["propagate_context"], "enclosing_function": "test_empty_graph_empty_seeds", "extracted_code": "# Source: src/roam/graph/propagation.py\ndef propagate_context(\n G,\n seed_nodes: Iterable[int],\n max_depth: int = 3,\n decay: float = 0.5,\n) -> Dict[int, float]:\n \"\"\"BFS from *seed_nodes* through the call graph, scoring reached nodes.\n\n Callee edges (outgoing / downstream) are traversed with weight\n ``decay ** depth``. Caller edges (incoming / upstream) are traversed with\n weight ``(decay * 0.5) ** depth`` — upstream context matters but is\n secondary to the transitive dependency chain.\n\n Handles cycles via a visited set: a node's score is only improved if we\n reach it via a *shorter* path; once a node is settled at the shortest\n callee distance it is not re-expanded through callee edges, and similarly\n for caller edges.\n\n Parameters\n ----------\n G:\n A ``networkx.DiGraph`` where edges go from caller to callee\n (i.e. ``A -> B`` means A calls B).\n seed_nodes:\n Iterable of node IDs that are the query targets (score = 1.0).\n max_depth:\n Maximum BFS depth (inclusive). Nodes at depth > max_depth are not\n added. Defaults to 3.\n decay:\n Per-level decay factor for callee direction. Caller direction uses\n ``decay * 0.5``. Defaults to 0.5.\n\n Returns\n -------\n dict[int, float]\n Mapping of ``{node_id: propagation_score}``. Seed nodes have score\n 1.0; unreachable nodes are absent.\n \"\"\"\n seeds = set(seed_nodes)\n if not seeds:\n return {}\n\n scores: Dict[int, float] = {}\n\n # Seed nodes always score 1.0\n for s in seeds:\n if s in G:\n scores[s] = 1.0\n\n # --- Callee BFS (forward / downstream direction) ---\n # Queue entries: (node_id, depth)\n # visited_callee tracks the minimum depth at which we reached each node\n visited_callee: Dict[int, int] = {s: 0 for s in seeds if s in G}\n callee_queue: deque[Tuple[int, int]] = deque((s, 0) for s in seeds if s in G)\n\n while callee_queue:\n node, depth = callee_queue.popleft()\n if depth >= max_depth:\n continue\n next_depth = depth + 1\n callee_score = decay**next_depth\n for neighbor in G.successors(node):\n if neighbor in seeds:\n continue # Seeds keep score 1.0\n if neighbor not in visited_callee or visited_callee[neighbor] > next_depth:\n visited_callee[neighbor] = next_depth\n prev = scores.get(neighbor, 0.0)\n scores[neighbor] = max(prev, callee_score)\n callee_queue.append((neighbor, next_depth))\n\n # --- Caller BFS (reverse / upstream direction) ---\n # Callers carry lower weight: decay * 0.5\n caller_decay = decay * 0.5\n visited_caller: Dict[int, int] = {s: 0 for s in seeds if s in G}\n caller_queue: deque[Tuple[int, int]] = deque((s, 0) for s in seeds if s in G)\n\n while caller_queue:\n node, depth = caller_queue.popleft()\n if depth >= max_depth:\n continue\n next_depth = depth + 1\n caller_score = caller_decay**next_depth\n for neighbor in G.predecessors(node):\n if neighbor in seeds:\n continue\n if neighbor not in visited_caller or visited_caller[neighbor] > next_depth:\n visited_caller[neighbor] = next_depth\n prev = scores.get(neighbor, 0.0)\n scores[neighbor] = max(prev, caller_score)\n caller_queue.append((neighbor, next_depth))\n\n return scores", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 3503}, "tests/test_ci_setup.py::29": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_explicit_platform_exits_zero", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_simulate_departure.py::355": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_json_key_symbols_structure", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_competitor_site_data.py::152": {"resolved_imports": ["src/roam/competitor_site_data.py", "src/roam/surface_counts.py"], "used_names": ["build_site_payload"], "enclosing_function": "test_rubric_in_payload", "extracted_code": "# Source: src/roam/competitor_site_data.py\ndef build_site_payload(tracker_path: Path | None = None) -> dict[str, object]:\n path = tracker_path or default_tracker_path()\n lines = path.read_text(encoding=\"utf-8\").splitlines()\n\n tracker_updated = \"\"\n for line in lines:\n if line.startswith(\"> Updated:\"):\n tracker_updated = line.split(\":\", 1)[1].strip()\n break\n if not tracker_updated:\n raise ValueError(\"Could not parse tracker update line ('> Updated: ...').\")\n\n tracker_updated_iso = _parse_tracker_updated_iso(tracker_updated)\n confidence_map = _parse_matrix_confidence(lines)\n competitors = _matrix_to_competitors(lines, confidence_map, tracker_updated_iso)\n _append_ckb_from_leaderboard(lines, competitors, confidence_map, tracker_updated_iso)\n _append_extra_competitors(competitors, tracker_updated_iso)\n\n # Filter to landscape-included tools only.\n competitors = [c for c in competitors if str(c[\"name\"]) in LANDSCAPE_INCLUDE]\n\n # Keep visual map stable: order by descending analysis depth, then agent readiness.\n competitors.sort(key=lambda c: (-int(c[\"arch\"]), -int(c[\"agent\"]), str(c[\"name\"])))\n\n # Keep roam-code row count fields synced to source-of-truth command/tool registration.\n try:\n from roam.surface_counts import collect_surface_counts\n\n surface = collect_surface_counts()\n cli_counts = surface.get(\"cli\", {})\n mcp_counts = surface.get(\"mcp\", {})\n canonical = int(cli_counts.get(\"canonical_commands\", 0) or 0)\n alias_count = int(cli_counts.get(\"alias_names\", 0) or 0)\n mcp_tools = int(mcp_counts.get(\"registered_tools\", 0) or 0)\n for entry in competitors:\n if entry.get(\"name\") != \"roam-code\":\n continue\n entry[\"mcp\"] = str(mcp_tools)\n if alias_count > 0:\n entry[\"cli_commands\"] = f\"{canonical} canonical (+{alias_count} alias)\"\n else:\n entry[\"cli_commands\"] = str(canonical)\n break\n except Exception:\n # Do not fail payload generation if local surface-count parsing fails.\n pass\n\n methodology = {\n \"scoring_model\": [\n \"45 criteria across 7 categories, scored as binary (has/doesn't), count-tiered, or subjective.\",\n \"Y-axis (Analysis Depth) = Static Analysis (50%) + Graph Intelligence (25%) + Git Temporal (25%).\",\n \"X-axis (Agent Readiness) = Agent Integration (70%) + Ecosystem (30%).\",\n \"Security and Unique Capabilities affect total score only, not map position.\",\n \"All criteria scored by project maintainers. 44/45 are binary or tiered (count-based or depth-based). 1/45 is subjective (documentation quality).\",\n \"Weight sliders let viewers apply their own category priorities.\",\n ],\n \"limitations\": [\n \"Criteria selection bias: we chose which capabilities to measure, favoring tools with graph algorithms.\",\n \"Category weight bias: default weights reflect our perspective. Adjust sliders for yours.\",\n \"Assessment bias: we scored all competitors. Errors or missed capabilities are possible.\",\n \"Public vendor claims can be stale or inconsistent across pages.\",\n \"GitHub star counts may conflate main product repos with MCP extension repos.\",\n ],\n \"reproducibility\": {\n \"tracker\": str(path.relative_to(_repo_root())).replace(\"\\\\\", \"/\"),\n \"generator\": \"src/roam/competitor_site_data.py\",\n \"generated_at_reference\": tracker_updated_iso,\n },\n }\n\n # Rubric metadata for the frontend (weight sliders + methodology rendering)\n rubric_out: list[dict[str, object]] = []\n for cat in SCORING_RUBRIC:\n rubric_out.append(\n {\n \"id\": cat[\"id\"],\n \"label\": cat[\"label\"],\n \"max_points\": cat[\"max_points\"],\n \"default_weight\": cat[\"default_weight\"],\n \"criteria\": [{k: v for k, v in crit.items()} for crit in cat[\"criteria\"]],\n }\n )\n\n return {\n \"tracker_updated\": tracker_updated,\n \"tracker_updated_iso\": tracker_updated_iso,\n \"tracker_file\": str(path.relative_to(_repo_root())).replace(\"\\\\\", \"/\"),\n \"competitors\": competitors,\n \"methodology\": methodology,\n \"rubric\": rubric_out,\n }", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 4415}, "tests/test_api_drift.py::62": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_exits_zero", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_budget.py::57": {"resolved_imports": ["src/roam/cli.py"], "used_names": ["CliRunner", "cli", "git_init", "index_in_process", "pytest"], "enclosing_function": "budget_project", "extracted_code": "# Source: src/roam/cli.py\ndef cli(ctx, json_mode, compact, agent, sarif_mode, budget, include_excluded, detail):\n \"\"\"Roam: Codebase comprehension tool.\"\"\"\n if agent and sarif_mode:\n raise click.UsageError(\"--agent cannot be combined with --sarif\")\n\n # Agent mode is optimized for CLI-invoked sub-agents:\n # - forces JSON for machine parsing\n # - uses compact envelope to reduce token overhead\n # - defaults to 500-token budget unless user overrides with --budget\n if agent:\n json_mode = True\n compact = True\n if budget <= 0:\n budget = 500\n\n ctx.ensure_object(dict)\n ctx.obj[\"json\"] = json_mode\n ctx.obj[\"compact\"] = compact\n ctx.obj[\"agent\"] = agent\n ctx.obj[\"sarif\"] = sarif_mode\n ctx.obj[\"budget\"] = budget\n ctx.obj[\"include_excluded\"] = include_excluded\n ctx.obj[\"detail\"] = detail", "n_imports_parsed": 8, "n_files_resolved": 1, "n_chars_extracted": 868}, "tests/test_difficulty_scoring.py::246": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_difficulty_in_json_output", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_budget_phase2.py::62": {"resolved_imports": [], "used_names": ["git_init", "index_in_process", "pytest"], "enclosing_function": "basic_project", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_mutate.py::66": {"resolved_imports": ["src/roam/refactor/codegen.py"], "used_names": ["detect_language"], "enclosing_function": "test_detect_language", "extracted_code": "# Source: src/roam/refactor/codegen.py\ndef detect_language(file_path: str) -> str:\n \"\"\"Detect language from file extension.\n\n Uses the roam language registry when available, falls back to\n extension-based detection for common languages.\n \"\"\"\n try:\n from roam.languages.registry import get_language_for_file\n\n lang = get_language_for_file(file_path)\n if lang:\n return lang\n except Exception:\n pass\n\n ext = os.path.splitext(file_path)[1].lower()\n ext_map = {\n \".py\": \"python\",\n \".js\": \"javascript\",\n \".jsx\": \"javascript\",\n \".mjs\": \"javascript\",\n \".ts\": \"typescript\",\n \".tsx\": \"typescript\",\n \".go\": \"go\",\n \".rs\": \"rust\",\n \".java\": \"java\",\n \".rb\": \"ruby\",\n \".php\": \"php\",\n \".c\": \"c\",\n \".h\": \"c\",\n \".cpp\": \"cpp\",\n }\n return ext_map.get(ext, \"unknown\")", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 913}, "tests/test_difficulty_scoring.py::73": {"resolved_imports": ["src/roam/commands/cmd_partition.py"], "used_names": ["compute_difficulty_score"], "enclosing_function": "test_empty_partitions", "extracted_code": "# Source: src/roam/commands/cmd_partition.py\ndef compute_difficulty_score(\n partitions: list[dict],\n *,\n complexity_weight: float = 0.3,\n coupling_weight: float = 0.25,\n churn_weight: float = 0.25,\n size_weight: float = 0.2,\n) -> list[dict]:\n \"\"\"Compute a composite difficulty score for each partition.\n\n Each metric is normalized to 0-100 relative to the max across all\n partitions before applying weights. The result is a 0-100 score\n with a human-readable label.\n\n Parameters\n ----------\n partitions:\n List of partition dicts (must already contain ``complexity``,\n ``cross_partition_edges``, ``churn``, and ``symbol_count``).\n complexity_weight, coupling_weight, churn_weight, size_weight:\n Relative importance of each factor (should sum to 1.0).\n\n Returns\n -------\n The same list with ``difficulty_score`` (float 0-100) and\n ``difficulty_label`` (str) added to each dict.\n \"\"\"\n if not partitions:\n return partitions\n\n # Collect raw values\n complexities = [p.get(\"complexity\", 0) for p in partitions]\n cross_edges = [p.get(\"cross_partition_edges\", 0) for p in partitions]\n churns = [p.get(\"churn\", 0) for p in partitions]\n sizes = [p.get(\"symbol_count\", 0) for p in partitions]\n\n max_complexity = max(complexities) or 1\n max_cross = max(cross_edges) or 1\n max_churn = max(churns) or 1\n max_size = max(sizes) or 1\n\n for i, p in enumerate(partitions):\n norm_complexity = (complexities[i] / max_complexity) * 100\n norm_cross = (cross_edges[i] / max_cross) * 100\n norm_churn = (churns[i] / max_churn) * 100\n norm_size = (sizes[i] / max_size) * 100\n\n score = (\n complexity_weight * norm_complexity\n + coupling_weight * norm_cross\n + churn_weight * norm_churn\n + size_weight * norm_size\n )\n\n p[\"difficulty_score\"] = round(score, 1)\n p[\"difficulty_label\"] = _difficulty_label(score)\n\n return partitions", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 2020}, "tests/test_attest.py::227": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_attest_has_attestation_metadata", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_api_changes.py::82": {"resolved_imports": [], "used_names": ["index_in_process", "invoke_cli"], "enclosing_function": "test_removed_function", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_simulate.py::202": {"resolved_imports": ["src/roam/graph/simulate.py"], "used_names": ["clone_graph"], "enclosing_function": "test_clone_graph_independent", "extracted_code": "# Source: src/roam/graph/simulate.py\ndef clone_graph(G: nx.DiGraph) -> nx.DiGraph:\n \"\"\"Deep-copy a graph preserving all node/edge attributes.\"\"\"\n return G.copy()", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 167}, "tests/test_supply_chain.py::462": {"resolved_imports": ["src/roam/commands/cmd_supply_chain.py"], "used_names": ["Dependency", "compute_risk_score"], "enclosing_function": "test_compute_risk_score_fields", "extracted_code": "# Source: src/roam/commands/cmd_supply_chain.py\nclass Dependency(NamedTuple):\n name: str\n version_spec: str\n is_dev: bool\n pin_status: str\n risk_level: str\n source_file: str\n ecosystem: str\n\ndef compute_risk_score(deps: list[Dependency]) -> dict:\n if not deps:\n return dict(\n score=100,\n pin_coverage=1.0,\n dev_ratio=0.0,\n total=0,\n direct_count=0,\n dev_count=0,\n exact_count=0,\n range_count=0,\n unpinned_count=0,\n )\n total = len(deps)\n direct = [d for d in deps if not d.is_dev]\n dev = [d for d in deps if d.is_dev]\n exact = sum(1 for d in deps if d.pin_status == \"exact\")\n rng = sum(1 for d in deps if d.pin_status == \"range\")\n unpinned = sum(1 for d in deps if d.pin_status == \"unpinned\")\n pin_coverage = exact / total\n dev_ratio = len(dev) / total\n diversity_penalty = 1.0 - (unpinned / total)\n raw = pin_coverage * 0.6 + dev_ratio * 0.2 + diversity_penalty * 0.2\n score = max(0, min(100, round(raw * 100)))\n return dict(\n score=score,\n pin_coverage=round(pin_coverage, 4),\n dev_ratio=round(dev_ratio, 4),\n total=total,\n direct_count=len(direct),\n dev_count=len(dev),\n exact_count=exact,\n range_count=rng,\n unpinned_count=unpinned,\n )", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 1377}, "tests/test_conventions_cmd.py::275": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_json_summary_has_total_symbols", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_dead_aging.py::56": {"resolved_imports": ["src/roam/commands/cmd_dead.py"], "used_names": ["_decay_score"], "enclosing_function": "test_score_bounded_0_to_100", "extracted_code": "# Source: src/roam/commands/cmd_dead.py\ndef _decay_score(age_days, cognitive_complexity, cluster_size, importing_files, author_active, dead_loc):\n \"\"\"0-100 decay score. Higher = more decayed, harder to remove.\n\n Scoring breakdown (max 100):\n age_points (max 35): 7 * log2(1 + age_days / 90)\n cc_points (max 25): cognitive_complexity * 1.5\n coupling_points (max 20): importing_files * 2 + cluster_size * 3\n size_points (max 10): dead_loc / 20\n author_points (max 10): 0 if author_active else 10\n \"\"\"\n age_points = min(35, 7 * math.log2(1 + age_days / 90))\n cc_points = min(25, cognitive_complexity * 1.5)\n coupling_points = min(20, importing_files * 2 + cluster_size * 3)\n size_points = min(10, dead_loc / 20)\n author_points = 0 if author_active else 10\n return min(100, int(round(age_points + cc_points + coupling_points + size_points + author_points)))", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 922}, "tests/test_backend_fixes_round3.py::203": {"resolved_imports": ["src/roam/commands/cmd_migration_safety.py"], "used_names": ["_check_add_column"], "enclosing_function": "test_has_table_guards_add_column", "extracted_code": "# Source: src/roam/commands/cmd_migration_safety.py\ndef _check_add_column(lines: list[str], up_start: int, up_end: int) -> list[dict]:\n \"\"\"Detect column definitions inside Schema::table() without hasColumn guard.\n\n Strategy: find Schema::table() blocks and check whether each column\n definition inside them is preceded by a hasColumn guard in the same\n containing block or outer if-statement.\n \"\"\"\n findings = []\n if up_start == 0:\n return findings\n\n up_lines = lines[up_start - 1 : up_end]\n\n # Find Schema::table() calls; each opens a closure for altering a table.\n # We detect the surrounding if-block or direct call and see if hasColumn\n # exists in the surrounding context.\n for rel_i, line in enumerate(up_lines):\n if not _RE_COLUMN_DEF.search(line):\n continue\n\n abs_line = up_start + rel_i\n\n # We only flag column additions inside a Schema::table() context\n # (altering an existing table). Skip if this looks like it's inside\n # a Schema::create() block (adding columns to a brand-new table is\n # always safe — the table didn't exist before).\n context_start = max(0, rel_i - 60)\n pre_context = \"\".join(up_lines[context_start : rel_i + 1])\n\n if _RE_SCHEMA_CREATE.search(pre_context) and not _RE_SCHEMA_TABLE.search(pre_context):\n continue # Inside Schema::create() — new table, no guard needed\n\n if not _RE_SCHEMA_TABLE.search(pre_context):\n continue # Not inside an alter-table block — skip\n\n # Check if hasColumn guard appears near this column definition\n if _RE_HAS_COLUMN.search(pre_context):\n continue # Guarded — OK\n if _RE_HAS_TABLE.search(pre_context):\n continue # hasTable guard — OK\n if _RE_INFO_SCHEMA_GUARD.search(pre_context):\n continue # information_schema guard — OK\n\n col_name = _extract_arg(line)\n\n findings.append(\n {\n \"line\": abs_line,\n \"confidence\": \"medium\",\n \"issue\": f\"->column({col_name!r}) without hasColumn guard in Schema::table() block\",\n \"fix\": (\n f\"Wrap with: if (!Schema::hasColumn($table, {col_name!r})) {{ ... }}\"\n if col_name\n else \"Wrap column addition with an if (!Schema::hasColumn(...)) check\"\n ),\n \"category\": \"add_column_without_check\",\n }\n )\n\n return findings", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 2511}, "tests/test_bus_factor.py::154": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_exits_zero", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_ci_sarif_guard.py::72": {"resolved_imports": [], "used_names": ["deepcopy"], "enclosing_function": "test_apply_guardrails_run_and_result_caps", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_comprehensive.py::794": {"resolved_imports": [], "used_names": ["git_init", "index_in_process", "pytest"], "enclosing_function": "polyglot", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_capsule.py::281": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_capsule_has_clusters", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_bridges.py::66": {"resolved_imports": ["src/roam/bridges/__init__.py", "src/roam/bridges/registry.py", "src/roam/bridges/base.py", "src/roam/bridges/bridge_protobuf.py", "src/roam/bridges/bridge_salesforce.py"], "used_names": [], "enclosing_function": "test_registry_starts_empty_after_clear", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 5, "n_chars_extracted": 0}, "tests/test_math_tips.py::60": {"resolved_imports": ["src/roam/catalog/tasks.py"], "used_names": ["get_tip"], "enclosing_function": "test_default_fallback_for_unknown_language", "extracted_code": "# Source: src/roam/catalog/tasks.py\ndef get_tip(task_id: str, way_id: str, language: str | None = None) -> str:\n \"\"\"Return the best tip for a task/way/language combination.\n\n Lookup order:\n 1. ``_LANGUAGE_TIPS[(task_id, way_id)][language]``\n 2. ``_LANGUAGE_TIPS[(task_id, way_id)][\"default\"]``\n 3. The static ``tip`` field on the way entry in CATALOG\n 4. ``\"\"``\n \"\"\"\n lang_key = (language or \"\").lower().strip()\n # Normalize common aliases\n if lang_key in (\"ts\", \"tsx\"):\n lang_key = \"typescript\"\n elif lang_key in (\"js\", \"jsx\"):\n lang_key = \"javascript\"\n elif lang_key in (\"c++\",):\n lang_key = \"cpp\"\n\n tips = _LANGUAGE_TIPS.get((task_id, way_id))\n if tips:\n if lang_key and lang_key in tips:\n return tips[lang_key]\n if \"default\" in tips:\n return tips[\"default\"]\n\n # Fall back to static tip on the way entry\n way = get_way(task_id, way_id)\n if way and way.get(\"tip\"):\n return way[\"tip\"]\n return \"\"", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 1022}, "tests/test_bisect.py::373": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_bisect_top_n", "extracted_code": "", "n_imports_parsed": 9, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_properties.py::544": {"resolved_imports": ["src/roam/db/connection.py", "src/roam/graph/simulate.py", "src/roam/output/formatter.py"], "used_names": ["clone_graph"], "enclosing_function": "test_clone_independence_add_node", "extracted_code": "# Source: src/roam/graph/simulate.py\ndef clone_graph(G: nx.DiGraph) -> nx.DiGraph:\n \"\"\"Deep-copy a graph preserving all node/edge attributes.\"\"\"\n return G.copy()", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 167}, "tests/test_doc_staleness.py::70": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_verdict_line", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_secrets.py::446": {"resolved_imports": [], "used_names": ["json"], "enclosing_function": "test_sarif_has_results", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_simulate.py::447": {"resolved_imports": ["src/roam/graph/simulate.py"], "used_names": ["apply_delete", "clone_graph", "compute_graph_metrics", "metric_delta"], "enclosing_function": "test_metrics_have_direction", "extracted_code": "# Source: src/roam/graph/simulate.py\ndef compute_graph_metrics(G: nx.DiGraph) -> dict:\n \"\"\"Compute all graph-derivable metrics on any DiGraph.\"\"\"\n from roam.graph.clusters import cluster_quality, detect_clusters\n from roam.graph.cycles import algebraic_connectivity, find_cycles, propagation_cost\n from roam.graph.layers import detect_layers, find_violations\n\n n = len(G)\n e = G.number_of_edges()\n\n # Cycles / tangle\n sccs = find_cycles(G)\n cycle_count = len(sccs)\n scc_nodes = sum(len(c) for c in sccs)\n tangle = round(100 * scc_nodes / n, 2) if n > 0 else 0.0\n\n # Layer violations\n layers = detect_layers(G)\n violations = find_violations(G, layers)\n lv_count = len(violations)\n\n # Modularity\n clusters = detect_clusters(G)\n quality = cluster_quality(G, clusters)\n modularity = quality.get(\"modularity\", 0.0)\n\n # Fiedler\n fiedler = algebraic_connectivity(G)\n\n # Propagation cost\n pc = propagation_cost(G) if n <= 500 else 0.0\n\n # God components: nodes with total degree > 20\n god_count = sum(1 for nd in G.nodes if G.degree(nd) > 20)\n\n # Bottlenecks: nodes with betweenness > 90th percentile\n bn_count = 0\n if n > 2:\n k = min(n, max(50, int(n**0.5 * 3)))\n bc = nx.betweenness_centrality(G, k=k)\n if bc:\n vals = sorted(bc.values())\n p90 = vals[int(len(vals) * 0.9)] if vals else 0\n bn_count = sum(1 for v in bc.values() if v > p90) if p90 > 0 else 0\n\n health = _approx_health(tangle, god_count, bn_count, lv_count)\n\n return {\n \"health_score\": health,\n \"nodes\": n,\n \"edges\": e,\n \"cycles\": cycle_count,\n \"tangle_ratio\": tangle,\n \"layer_violations\": lv_count,\n \"modularity\": round(modularity, 4),\n \"fiedler\": round(fiedler, 6),\n \"propagation_cost\": pc,\n \"god_components\": god_count,\n \"bottlenecks\": bn_count,\n }\n\ndef metric_delta(before: dict, after: dict) -> dict:\n \"\"\"Compute per-metric deltas with direction classification.\"\"\"\n result = {}\n for key in before:\n if key not in after:\n continue\n b = before[key]\n a = after[key]\n delta = a - b\n if b != 0:\n pct = round(100 * delta / abs(b), 1)\n else:\n pct = 0.0 if delta == 0 else 100.0\n\n higher_better = _HIGHER_IS_BETTER.get(key)\n if delta == 0:\n direction = \"unchanged\"\n elif higher_better is None:\n direction = \"changed\"\n elif (higher_better and delta > 0) or (not higher_better and delta < 0):\n direction = \"improved\"\n else:\n direction = \"degraded\"\n\n result[key] = {\n \"before\": b,\n \"after\": a,\n \"delta\": delta if isinstance(delta, int) else round(delta, 4),\n \"pct_change\": pct,\n \"direction\": direction,\n }\n return result\n\ndef clone_graph(G: nx.DiGraph) -> nx.DiGraph:\n \"\"\"Deep-copy a graph preserving all node/edge attributes.\"\"\"\n return G.copy()\n\ndef apply_delete(G: nx.DiGraph, node_ids: list[int]) -> dict:\n \"\"\"Remove nodes and all their edges from the graph.\"\"\"\n removed_names = []\n edges_before = G.number_of_edges()\n for nid in node_ids:\n if nid in G:\n removed_names.append(G.nodes[nid].get(\"name\", str(nid)))\n G.remove_node(nid)\n edges_after = G.number_of_edges()\n\n return {\n \"operation\": \"delete\",\n \"removed\": removed_names,\n \"removed_edges\": edges_before - edges_after,\n \"affected\": len(removed_names),\n }", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 3608}, "tests/test_ai_readiness.py::96": {"resolved_imports": [], "used_names": ["git_init", "index_in_process", "os", "pytest"], "enclosing_function": "well_structured_project", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_capsule.py::143": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_capsule_has_symbols", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_adversarial.py::526": {"resolved_imports": ["src/roam/commands/cmd_adversarial.py"], "used_names": ["_challenge"], "enclosing_function": "test_challenge_builder_default_location", "extracted_code": "# Source: src/roam/commands/cmd_adversarial.py\ndef _challenge(ctype, severity, title, description, question, location=None):\n \"\"\"Build a challenge dict with all required fields.\"\"\"\n return {\n \"type\": ctype,\n \"severity\": severity,\n \"title\": title,\n \"description\": description,\n \"question\": question,\n \"location\": location or \"\",\n }", "n_imports_parsed": 9, "n_files_resolved": 1, "n_chars_extracted": 381}, "tests/test_adrs.py::98": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_verdict_line", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_effects.py::303": {"resolved_imports": ["src/roam/analysis/effects.py"], "used_names": ["classify_symbol_effects"], "enclosing_function": "test_unknown_language_returns_empty", "extracted_code": "# Source: src/roam/analysis/effects.py\ndef classify_symbol_effects(\n body_text: str,\n language: str,\n tree=None,\n source: bytes | None = None,\n line_start: int = 0,\n line_end: int = 0,\n) -> set[str]:\n \"\"\"Classify the side effects of a function body.\n\n Args:\n body_text: The text of the function body (lines between line_start..line_end).\n language: Programming language identifier.\n tree: Optional tree-sitter parse tree for AST-aware string/comment filtering.\n source: Full file source bytes (needed with tree for range mapping).\n line_start: 1-based start line of the function.\n line_end: 1-based end line of the function.\n\n Returns:\n Set of effect type strings (e.g. {\"reads_db\", \"network\"}).\n Empty set if no effects detected (the function is considered pure).\n \"\"\"\n patterns = _LANGUAGE_PATTERNS.get(language, [])\n if not patterns:\n return set()\n\n # Build excluded ranges from tree-sitter AST if available\n excluded: list[tuple[int, int]] = []\n if tree is not None and source is not None and line_start > 0:\n excluded = _collect_excluded_ranges(tree, source, line_start, line_end)\n\n effects: set[str] = set()\n\n for pattern, effect in patterns:\n for match in pattern.finditer(body_text):\n # If we have AST info, check if match is inside a string/comment\n if excluded and _in_excluded(match.start(), excluded):\n continue\n effects.add(effect)\n break # One match per pattern is enough\n\n return effects", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 1593}, "tests/test_capsule.py::58": {"resolved_imports": [], "used_names": ["json", "pytest"], "enclosing_function": "_parse_capsule_json", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_ai_readiness.py::526": {"resolved_imports": [], "used_names": ["json"], "enclosing_function": "test_contributions_sum_near_composite", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_defer_loading.py::122": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_all_tool_names_unique", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_defer_loading.py::59": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_core_tools_not_deferred", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_capsule.py::150": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_capsule_has_symbols", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_agent_plan_context.py::102": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_agent_context_invalid_agent", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_budget_flag.py::354": {"resolved_imports": [], "used_names": ["git_init", "index_in_process", "pytest"], "enclosing_function": "health_project", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_context_propagation.py::353": {"resolved_imports": ["src/roam/graph/propagation.py"], "used_names": ["merge_rankings"], "enclosing_function": "test_basic_blend_in_range", "extracted_code": "# Source: src/roam/graph/propagation.py\ndef merge_rankings(\n pagerank_scores: Dict[int, float],\n propagation_scores: Dict[int, float],\n alpha: float = 0.6,\n) -> Dict[int, float]:\n \"\"\"Blend propagation scores with PageRank scores.\n\n Final score = ``alpha * norm_propagation + (1 - alpha) * norm_pagerank``\n\n Both inputs are normalised to [0, 1] before blending so that the scale\n difference between PageRank (tiny floats ~1e-4) and propagation (0–1)\n does not distort the result.\n\n Parameters\n ----------\n pagerank_scores:\n ``{node_id: pagerank_value}`` from ``compute_pagerank()``.\n propagation_scores:\n ``{node_id: propagation_score}`` from ``propagate_context()``.\n alpha:\n Weight given to propagation scores (0–1). Remaining weight\n ``1 - alpha`` goes to PageRank. Defaults to 0.6.\n\n Returns\n -------\n dict[int, float]\n ``{node_id: blended_score}`` for every node present in either input.\n \"\"\"\n if not pagerank_scores and not propagation_scores:\n return {}\n\n # Normalise pagerank\n max_pr = max(pagerank_scores.values(), default=0.0)\n norm_pr: Dict[int, float] = (\n {k: v / max_pr for k, v in pagerank_scores.items()} if max_pr > 0 else {k: 0.0 for k in pagerank_scores}\n )\n\n # Propagation scores are already in [0, 1] (decay-based)\n max_prop = max(propagation_scores.values(), default=0.0)\n norm_prop: Dict[int, float] = (\n {k: v / max_prop for k, v in propagation_scores.items()}\n if max_prop > 0\n else {k: 0.0 for k in propagation_scores}\n )\n\n all_nodes = set(norm_pr) | set(norm_prop)\n result: Dict[int, float] = {}\n for node in all_nodes:\n pr_val = norm_pr.get(node, 0.0)\n prop_val = norm_prop.get(node, 0.0)\n result[node] = alpha * prop_val + (1.0 - alpha) * pr_val\n\n return result", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 1872}, "tests/test_anomaly.py::74": {"resolved_imports": ["src/roam/graph/anomaly.py"], "used_names": ["modified_z_score"], "enclosing_function": "test_all_equal_values_mad_zero", "extracted_code": "# Source: src/roam/graph/anomaly.py\ndef modified_z_score(values: list[float | int], threshold: float = 3.5) -> list[dict]:\n \"\"\"Detect point anomalies using Modified Z-Score (MAD-based).\n\n More robust than standard Z-score for small datasets because it uses\n Median Absolute Deviation instead of standard deviation.\n\n Returns list of dicts with keys: index, value, z_score, is_anomaly.\n Requires n >= 5. Returns empty list if insufficient data.\n \"\"\"\n if len(values) < 5:\n return []\n\n med = median(values)\n mad_val = _mad(values)\n\n results: list[dict] = []\n for i, v in enumerate(values):\n if mad_val == 0.0:\n # All deviations from median are zero (or nearly); z-score is 0\n # unless the point itself differs from the median.\n z = 0.0 if v == med else float(\"inf\")\n else:\n # 0.6745 is the 0.75th quantile of the standard normal distribution.\n # Scaling by it makes the MAD consistent with std-dev for normal data.\n z = 0.6745 * (v - med) / mad_val\n results.append(\n {\n \"index\": i,\n \"value\": v,\n \"z_score\": round(z, 4) if math.isfinite(z) else z,\n \"is_anomaly\": abs(z) > threshold,\n }\n )\n return results", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 1320}, "tests/test_backend_fixes_round2.py::232": {"resolved_imports": ["src/roam/languages/registry.py"], "used_names": ["get_language_for_file"], "enclosing_function": "test_mdx_extension_detected", "extracted_code": "# Source: src/roam/languages/registry.py\ndef get_language_for_file(path: str) -> str | None:\n \"\"\"Determine the language for a file based on its extension.\n\n Returns the language name string, or None if unsupported.\n \"\"\"\n # Salesforce metadata files: *.cls-meta.xml, *.object-meta.xml, etc.\n if path.endswith(\"-meta.xml\"):\n return \"sfxml\"\n _, ext = os.path.splitext(path)\n ext = ext.lower()\n language = _EXTENSION_MAP.get(ext)\n if language:\n return language\n return _plugin_language_extensions().get(ext)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 547}, "tests/test_bridges_extended.py::101": {"resolved_imports": ["src/roam/bridges/__init__.py", "src/roam/bridges/registry.py", "src/roam/bridges/bridge_config.py", "src/roam/bridges/bridge_rest_api.py", "src/roam/bridges/bridge_template.py"], "used_names": [], "enclosing_function": "test_rest_api_bridge_detect", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 5, "n_chars_extracted": 0}, "tests/test_dead_aging.py::370": {"resolved_imports": ["src/roam/commands/cmd_dead.py"], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_json_dead_aging_includes_aging_data", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_annotations.py::293": {"resolved_imports": [], "used_names": ["git_init", "index_in_process", "pytest"], "enclosing_function": "annotated_project", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_check_rules.py::145": {"resolved_imports": ["src/roam/cli.py", "src/roam/rules/builtin.py"], "used_names": ["BuiltinRule"], "enclosing_function": "test_builtin_rule_evaluate_fn_error", "extracted_code": "# Source: src/roam/rules/builtin.py\nclass BuiltinRule:\n \"\"\"A single built-in governance rule.\"\"\"\n\n id: str\n severity: str\n description: str\n check: str\n threshold: float | None = None\n enabled: bool = True\n _fn: Callable | None = field(default=None, repr=False)\n\n def evaluate(self, conn: sqlite3.Connection, G: nx.DiGraph | None) -> list[dict]:\n \"\"\"Run the check and return violations.\"\"\"\n if self._fn is None:\n return []\n try:\n return self._fn(conn, G, self.threshold)\n except Exception as exc: # pragma: no cover\n return [make_violation(reason=\"check error: {}\".format(exc))]", "n_imports_parsed": 9, "n_files_resolved": 2, "n_chars_extracted": 667}, "tests/test_budget.py::196": {"resolved_imports": [], "used_names": ["invoke_cli", "json"], "enclosing_function": "test_budget_default_budgets", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_ci_gate_eval.py::25": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_scalar_gate_pass", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_drift.py::471": {"resolved_imports": ["src/roam/commands/cmd_drift.py"], "used_names": ["_top_contributor"], "enclosing_function": "test_top_contributor_empty", "extracted_code": "# Source: src/roam/commands/cmd_drift.py\ndef _top_contributor(ownership_shares: dict[str, float]) -> tuple[str, float]:\n \"\"\"Return ``(name, share)`` of the top contributor.\"\"\"\n if not ownership_shares:\n return (\"\", 0.0)\n top = max(ownership_shares.items(), key=lambda x: x[1])\n return top", "n_imports_parsed": 8, "n_files_resolved": 1, "n_chars_extracted": 307}, "tests/test_cut.py::278": {"resolved_imports": ["src/roam/commands/cmd_cut.py"], "used_names": [], "enclosing_function": "test_cut_leak_edge_fields", "extracted_code": "", "n_imports_parsed": 9, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_annotations.py::214": {"resolved_imports": ["src/roam/commands/cmd_migration_safety.py"], "used_names": ["_check_drop_column"], "enclosing_function": "test_drop_column_without_guard_still_flagged", "extracted_code": "# Source: src/roam/commands/cmd_migration_safety.py\ndef _check_drop_column(lines: list[str], up_start: int, up_end: int) -> list[dict]:\n \"\"\"Detect dropColumn without hasColumn guard.\"\"\"\n findings = []\n if up_start == 0:\n return findings\n\n up_lines = lines[up_start - 1 : up_end]\n\n for rel_i, line in enumerate(up_lines):\n if not _RE_DROP_COLUMN.search(line):\n continue\n\n abs_line = up_start + rel_i\n\n # Look backwards up to 30 lines for a hasColumn guard\n context_start = max(0, rel_i - 30)\n context_snippet = \"\".join(up_lines[context_start : rel_i + 1])\n\n if _RE_HAS_COLUMN.search(context_snippet):\n continue\n if _RE_HAS_TABLE.search(context_snippet):\n continue\n if _RE_INFO_SCHEMA_GUARD.search(context_snippet):\n continue\n\n col_name = _extract_arg(line)\n\n findings.append(\n {\n \"line\": abs_line,\n \"confidence\": \"medium\",\n \"issue\": f\"dropColumn({col_name!r}) without hasColumn guard\",\n \"fix\": (\n f\"Wrap with: if (Schema::hasColumn($table, {col_name!r})) {{ ... }}\"\n if col_name\n else \"Wrap dropColumn() with an if (Schema::hasColumn(...)) check\"\n ),\n \"category\": \"drop_column_without_check\",\n }\n )\n\n return findings", "n_imports_parsed": 8, "n_files_resolved": 1, "n_chars_extracted": 1430}, "tests/test_formatters.py::32": {"resolved_imports": ["src/roam/output/formatter.py"], "used_names": ["abbrev_kind"], "enclosing_function": "test_class", "extracted_code": "# Source: src/roam/output/formatter.py\ndef abbrev_kind(kind: str) -> str:\n return KIND_ABBREV.get(kind, kind)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 112}, "tests/conftest.py::142": {"resolved_imports": [], "used_names": ["json", "pytest"], "enclosing_function": "parse_json_output", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_attest.py::69": {"resolved_imports": [], "used_names": ["git_init", "index_in_process", "pytest"], "enclosing_function": "attest_project", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_api_drift.py::88": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_verdict_line", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_adrs.py::89": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_adr_entries_have_expected_fields", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_closure.py::162": {"resolved_imports": ["src/roam/cli.py"], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_closure_counts", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_migration_safety.py::420": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_confidence_low_filter", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_budget.py::229": {"resolved_imports": ["src/roam/commands/cmd_budget.py"], "used_names": ["_evaluate_rule"], "enclosing_function": "test_budget_evaluate_max_increase", "extracted_code": "# Source: src/roam/commands/cmd_budget.py\ndef _evaluate_rule(rule: dict, before: dict, after: dict) -> dict:\n \"\"\"Evaluate a single budget rule.\n\n Returns {name, metric, status, before, after, delta, budget, reason}.\n \"\"\"\n name = rule.get(\"name\", \"unnamed\")\n metric = rule.get(\"metric\", \"\")\n reason = rule.get(\"reason\", \"\")\n\n b_val = before.get(metric)\n a_val = after.get(metric)\n\n if b_val is None or a_val is None:\n return {\n \"name\": name,\n \"metric\": metric,\n \"status\": \"SKIP\",\n \"before\": b_val,\n \"after\": a_val,\n \"delta\": None,\n \"budget\": _budget_str(rule),\n \"reason\": reason or f\"metric '{metric}' not found\",\n }\n\n b_val = float(b_val)\n a_val = float(a_val)\n delta = a_val - b_val\n\n status = \"PASS\"\n\n if \"max_increase\" in rule:\n threshold = float(rule[\"max_increase\"])\n if delta > threshold:\n status = \"FAIL\"\n elif \"max_decrease\" in rule:\n threshold = float(rule[\"max_decrease\"])\n if (b_val - a_val) > threshold:\n status = \"FAIL\"\n elif \"max_increase_pct\" in rule:\n threshold = float(rule[\"max_increase_pct\"])\n if b_val != 0:\n pct = (delta / abs(b_val)) * 100\n else:\n pct = 0.0 if delta == 0 else 100.0\n if pct > threshold:\n status = \"FAIL\"\n\n return {\n \"name\": name,\n \"metric\": metric,\n \"status\": status,\n \"before\": b_val if b_val != int(b_val) else int(b_val),\n \"after\": a_val if a_val != int(a_val) else int(a_val),\n \"delta\": delta if delta != int(delta) else int(delta),\n \"budget\": _budget_str(rule),\n \"reason\": reason,\n }", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 1750}, "tests/test_bridges_extended.py::130": {"resolved_imports": ["src/roam/bridges/__init__.py", "src/roam/bridges/registry.py", "src/roam/bridges/bridge_config.py", "src/roam/bridges/bridge_rest_api.py", "src/roam/bridges/bridge_template.py"], "used_names": [], "enclosing_function": "test_rest_api_resolve_urls", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 5, "n_chars_extracted": 0}, "tests/test_commands_refactoring.py::45": {"resolved_imports": ["src/roam/cli.py"], "used_names": ["invoke_cli"], "enclosing_function": "test_dead_runs", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_agent_plan_context.py::53": {"resolved_imports": [], "used_names": ["assert_json_envelope", "invoke_cli", "parse_json_output"], "enclosing_function": "test_agent_plan_json", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_file_roles.py::24": {"resolved_imports": [], "used_names": ["classify_file"], "enclosing_function": "test_github_workflow", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_adrs.py::56": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_exits_zero", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_auth_gaps.py::223": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_routes_only_skips_controller_section", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_rule_profiles.py::203": {"resolved_imports": ["src/roam/rules/builtin.py"], "used_names": ["list_profiles"], "enclosing_function": "test_list_profiles_structure", "extracted_code": "# Source: src/roam/rules/builtin.py\ndef list_profiles() -> list[dict]:\n \"\"\"Return a list of available profile summaries.\n\n Each dict has keys: name, description, extends, rule_count.\n \"\"\"\n result = []\n for name, prof in sorted(BUILTIN_PROFILES.items()):\n result.append(\n {\n \"name\": name,\n \"description\": prof.get(\"description\", \"\"),\n \"extends\": prof.get(\"extends\"),\n \"rule_count\": len(prof.get(\"rules\", {})),\n }\n )\n return result", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 543}, "tests/test_attest.py::176": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_attest_has_risk", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_anomaly.py::57": {"resolved_imports": ["src/roam/graph/anomaly.py"], "used_names": ["modified_z_score"], "enclosing_function": "test_no_anomalies_in_uniform_data", "extracted_code": "# Source: src/roam/graph/anomaly.py\ndef modified_z_score(values: list[float | int], threshold: float = 3.5) -> list[dict]:\n \"\"\"Detect point anomalies using Modified Z-Score (MAD-based).\n\n More robust than standard Z-score for small datasets because it uses\n Median Absolute Deviation instead of standard deviation.\n\n Returns list of dicts with keys: index, value, z_score, is_anomaly.\n Requires n >= 5. Returns empty list if insufficient data.\n \"\"\"\n if len(values) < 5:\n return []\n\n med = median(values)\n mad_val = _mad(values)\n\n results: list[dict] = []\n for i, v in enumerate(values):\n if mad_val == 0.0:\n # All deviations from median are zero (or nearly); z-score is 0\n # unless the point itself differs from the median.\n z = 0.0 if v == med else float(\"inf\")\n else:\n # 0.6745 is the 0.75th quantile of the standard normal distribution.\n # Scaling by it makes the MAD consistent with std-dev for normal data.\n z = 0.6745 * (v - med) / mad_val\n results.append(\n {\n \"index\": i,\n \"value\": v,\n \"z_score\": round(z, 4) if math.isfinite(z) else z,\n \"is_anomaly\": abs(z) > threshold,\n }\n )\n return results", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 1320}, "tests/test_context_propagation.py::288": {"resolved_imports": ["src/roam/graph/propagation.py"], "used_names": ["callee_chain"], "enclosing_function": "test_linear_chain_depths", "extracted_code": "# Source: src/roam/graph/propagation.py\ndef callee_chain(\n G,\n node: int,\n max_depth: int = 3,\n) -> List[Tuple[int, int]]:\n \"\"\"Return ordered list of transitive callees with their BFS depth.\n\n BFS from *node* through outgoing (callee) edges up to *max_depth*.\n Cycles are handled via a visited set — each callee is reported at\n the shallowest depth it is reached.\n\n Parameters\n ----------\n G:\n Directed call graph (caller -> callee edges).\n node:\n Starting symbol node ID.\n max_depth:\n Maximum callee depth to traverse. Defaults to 3.\n\n Returns\n -------\n list of (node_id, depth) tuples\n Ordered by BFS level (shallow callees first), then by node ID for\n determinism. The seed node itself is NOT included.\n \"\"\"\n if node not in G:\n return []\n\n visited: Dict[int, int] = {node: 0}\n queue: deque[Tuple[int, int]] = deque([(node, 0)])\n result: List[Tuple[int, int]] = []\n\n while queue:\n current, depth = queue.popleft()\n if depth >= max_depth:\n continue\n next_depth = depth + 1\n for neighbor in sorted(G.successors(current)): # sorted for determinism\n if neighbor not in visited:\n visited[neighbor] = next_depth\n result.append((neighbor, next_depth))\n queue.append((neighbor, next_depth))\n\n return result", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 1406}, "tests/test_ci_setup.py::93": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_write_creates_file", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_file_roles.py::384": {"resolved_imports": [], "used_names": ["is_vendored"], "enclosing_function": "test_vendor_dir", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_dark_matter.py::192": {"resolved_imports": ["src/roam/graph/dark_matter.py", "src/roam/db/connection.py"], "used_names": ["dark_matter_edges", "open_db"], "enclosing_function": "test_dark_matter_edges_function", "extracted_code": "# Source: src/roam/graph/dark_matter.py\ndef dark_matter_edges(conn, *, min_cochanges: int = 3, min_npmi: float = 0.3) -> list[dict]:\n \"\"\"Find co-changing file pairs with no structural dependency.\n\n Returns list of dicts sorted by NPMI descending:\n {file_id_a, file_id_b, path_a, path_b, npmi, lift, strength, cochange_count}\n \"\"\"\n # Total commits\n row = conn.execute(\"SELECT COUNT(*) FROM git_commits\").fetchone()\n total_commits = max(row[0] if row else 1, 1)\n\n # Per-file commit counts\n file_commits: dict[int, int] = {}\n for fs in conn.execute(\"SELECT file_id, commit_count FROM file_stats\").fetchall():\n file_commits[fs[\"file_id\"]] = fs[\"commit_count\"] or 1\n\n # Co-change pairs above threshold\n cochange_rows = conn.execute(\n \"SELECT file_id_a, file_id_b, cochange_count FROM git_cochange WHERE cochange_count >= ?\",\n (min_cochanges,),\n ).fetchall()\n\n # Bidirectional structural edge set (any edge = not dark matter)\n structural: set[tuple[int, int]] = set()\n for fe in conn.execute(\"SELECT source_file_id, target_file_id FROM file_edges WHERE symbol_count >= 1\").fetchall():\n structural.add((fe[\"source_file_id\"], fe[\"target_file_id\"]))\n structural.add((fe[\"target_file_id\"], fe[\"source_file_id\"]))\n\n # File path lookup\n id_to_path: dict[int, str] = {}\n for f in conn.execute(\"SELECT id, path FROM files\").fetchall():\n id_to_path[f[\"id\"]] = f[\"path\"]\n\n results: list[dict] = []\n for r in cochange_rows:\n fid_a, fid_b = r[\"file_id_a\"], r[\"file_id_b\"]\n if (fid_a, fid_b) in structural:\n continue\n\n cochanges = r[\"cochange_count\"]\n ca = file_commits.get(fid_a, 1)\n cb = file_commits.get(fid_b, 1)\n\n p_ab = cochanges / total_commits\n p_a = ca / total_commits\n p_b = cb / total_commits\n npmi = _npmi(p_ab, p_a, p_b)\n\n if npmi < min_npmi:\n continue\n\n avg = (ca + cb) / 2\n strength = cochanges / avg if avg > 0 else 0\n lift = (cochanges * total_commits) / max(ca * cb, 1)\n\n results.append(\n {\n \"file_id_a\": fid_a,\n \"file_id_b\": fid_b,\n \"path_a\": id_to_path.get(fid_a, f\"file_id={fid_a}\"),\n \"path_b\": id_to_path.get(fid_b, f\"file_id={fid_b}\"),\n \"npmi\": round(npmi, 3),\n \"lift\": round(lift, 2),\n \"strength\": round(strength, 2),\n \"cochange_count\": cochanges,\n }\n )\n\n results.sort(key=lambda x: -x[\"npmi\"])\n return results\n\n\n# Source: src/roam/db/connection.py\ndef open_db(readonly: bool = False, project_root: Path | None = None):\n \"\"\"Context manager for database access. Creates schema if needed.\n\n Raises a descriptive ``click.ClickException`` if the database file is\n missing or corrupted so that agents receive actionable remediation steps\n instead of a raw SQLite traceback.\n \"\"\"\n import click\n\n db_path = get_db_path(project_root)\n try:\n conn = get_connection(db_path, readonly=readonly)\n except sqlite3.DatabaseError as exc:\n raise click.ClickException(\n f\"Database error: {exc}\\n\"\n \" The roam index may be corrupted. Run `roam init --force` to rebuild it\\n\"\n \" from scratch, or delete .roam/index.db and run `roam init`.\"\n ) from exc\n try:\n if not readonly:\n try:\n ensure_schema(conn)\n except sqlite3.DatabaseError as exc:\n conn.close()\n raise click.ClickException(\n f\"Database schema error: {exc}\\n\"\n \" The roam index may be corrupted or from an incompatible version.\\n\"\n \" Run `roam init --force` to rebuild it, or delete .roam/index.db\\n\"\n \" and run `roam init`.\"\n ) from exc\n yield conn\n if not readonly:\n conn.commit()\n finally:\n conn.close()", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 4022}, "tests/test_adversarial.py::171": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_adversarial_runs", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_bridges.py::84": {"resolved_imports": ["src/roam/bridges/__init__.py", "src/roam/bridges/registry.py", "src/roam/bridges/base.py", "src/roam/bridges/bridge_protobuf.py", "src/roam/bridges/bridge_salesforce.py"], "used_names": ["SalesforceBridge"], "enclosing_function": "test_get_bridges_returns_copy", "extracted_code": "# Source: src/roam/bridges/bridge_salesforce.py\nclass SalesforceBridge(LanguageBridge):\n \"\"\"Bridge between Apex controllers and Aura/LWC/Visualforce templates.\"\"\"\n\n @property\n def name(self) -> str:\n return \"salesforce\"\n\n @property\n def source_extensions(self) -> frozenset[str]:\n return _APEX_EXTS\n\n @property\n def target_extensions(self) -> frozenset[str]:\n return _SF_MARKUP_EXTS\n\n def detect(self, file_paths: list[str]) -> bool:\n \"\"\"Detect if project has both Apex and markup files.\"\"\"\n has_apex = False\n has_markup = False\n for fp in file_paths:\n ext = os.path.splitext(fp)[1].lower()\n if ext in _APEX_EXTS:\n has_apex = True\n if ext in _SF_MARKUP_EXTS:\n has_markup = True\n if has_apex and has_markup:\n return True\n return False\n\n def resolve(self, source_path: str, source_symbols: list[dict], target_files: dict[str, list[dict]]) -> list[dict]:\n \"\"\"Resolve Apex-to-markup cross-language links.\n\n Resolution strategies:\n 1. Naming convention: MyController.cls -> MyController.cmp\n 2. Controller attribute: \n 3. @AuraEnabled methods: match to components referencing that controller\n \"\"\"\n edges: list[dict] = []\n source_ext = os.path.splitext(source_path)[1].lower()\n\n if source_ext not in _APEX_EXTS:\n return edges\n\n # Get the Apex class name from the file path\n apex_class_name = os.path.basename(source_path).rsplit(\".\", 1)[0]\n\n # Build a lookup of target symbols by qualified name for fast matching\n target_symbol_index: dict[str, str] = {} # symbol_name -> qualified_name\n # Track which target files reference this Apex class as a controller\n controller_targets: list[tuple[str, list[dict]]] = []\n\n for tpath, tsymbols in target_files.items():\n text_ext = os.path.splitext(tpath)[1].lower()\n if text_ext not in _SF_MARKUP_EXTS:\n continue\n\n for sym in tsymbols:\n target_symbol_index[sym.get(\"name\", \"\")] = sym.get(\"qualified_name\", \"\")\n\n # Check if any target symbol references this Apex class\n # Aura components reference controllers via naming convention or\n # controller attribute (already extracted as references by AuraExtractor)\n target_basename = os.path.basename(tpath).rsplit(\".\", 1)[0]\n\n # Strategy 1: Naming convention match\n # MyController.cls -> MyController.cmp (same name)\n # MyController.cls -> MyControllerCmp.cmp (with suffix)\n if self._names_match(apex_class_name, target_basename):\n controller_targets.append((tpath, tsymbols))\n # Create edge from Apex class to the component\n edges.append(\n {\n \"source\": apex_class_name,\n \"target\": target_basename,\n \"kind\": \"x-lang\",\n \"bridge\": self.name,\n \"mechanism\": \"naming-convention\",\n }\n )\n\n # Strategy 2: Match @AuraEnabled methods to components that reference\n # this controller. Any component whose controller is this Apex class\n # can call its @AuraEnabled methods.\n aura_enabled_methods = self._find_aura_enabled_methods(source_symbols)\n\n for method_name, method_qname in aura_enabled_methods:\n for tpath, tsymbols in controller_targets:\n target_basename = os.path.basename(tpath).rsplit(\".\", 1)[0]\n edges.append(\n {\n \"source\": method_qname,\n \"target\": target_basename,\n \"kind\": \"x-lang\",\n \"bridge\": self.name,\n \"mechanism\": \"aura-enabled\",\n }\n )\n\n # Strategy 3: Check for Visualforce controller references\n # Visualforce pages specify controller=\"ClassName\" in \n # The VF extractor already extracts these as \"controller\" references,\n # but we create x-lang edges for them here\n for tpath, tsymbols in target_files.items():\n text_ext = os.path.splitext(tpath)[1].lower()\n if text_ext not in (\".page\", \".component\"):\n continue\n target_basename = os.path.basename(tpath).rsplit(\".\", 1)[0]\n # Check if any symbol in the target references this Apex class\n # We look for the component-level symbol whose name matches\n for sym in tsymbols:\n # Visualforce pages are top-level symbols of kind \"page\"/\"component\"\n if sym.get(\"kind\") in (\"page\", \"component\"):\n # The VF extractor creates controller references; check if\n # this Apex class is referenced by name in the target path\n # (We rely on naming convention or explicit controller attr)\n if self._names_match(apex_class_name, target_basename):\n # Already handled by strategy 1 above; skip duplicate\n pass\n\n return edges\n\n def _names_match(self, apex_name: str, target_name: str) -> bool:\n \"\"\"Check if an Apex class name matches a component name.\n\n Supports common Salesforce naming conventions:\n - Exact match: MyController -> MyController\n - Controller suffix: MyController -> My (component uses class as controller)\n - Component suffix: MyClass -> MyClassController (Apex has Controller suffix)\n \"\"\"\n apex_lower = apex_name.lower()\n target_lower = target_name.lower()\n\n # Exact match\n if apex_lower == target_lower:\n return True\n\n # Apex name is target + \"Controller\" suffix\n # e.g., MyComponentController.cls -> MyComponent.cmp\n if apex_lower == target_lower + \"controller\":\n return True\n\n # Target name is apex + \"Controller\" suffix (less common but possible)\n if target_lower == apex_lower + \"controller\":\n return True\n\n return False\n\n def _find_aura_enabled_methods(self, symbols: list[dict]) -> list[tuple[str, str]]:\n \"\"\"Find methods with @AuraEnabled annotation.\n\n Returns list of (method_name, qualified_name) tuples.\n \"\"\"\n results = []\n for sym in symbols:\n kind = sym.get(\"kind\", \"\")\n if kind not in (\"method\", \"function\"):\n continue\n sig = sym.get(\"signature\", \"\") or \"\"\n # Check if the signature or annotations contain @AuraEnabled\n if _AURA_ENABLED_RE.search(sig):\n results.append((sym.get(\"name\", \"\"), sym.get(\"qualified_name\", \"\")))\n continue\n # Also check docstring/annotations if stored there\n doc = sym.get(\"docstring\", \"\") or \"\"\n if _AURA_ENABLED_RE.search(doc):\n results.append((sym.get(\"name\", \"\"), sym.get(\"qualified_name\", \"\")))\n return results", "n_imports_parsed": 6, "n_files_resolved": 5, "n_chars_extracted": 7262}, "tests/test_properties.py::129": {"resolved_imports": ["src/roam/db/connection.py", "src/roam/graph/simulate.py", "src/roam/output/formatter.py"], "used_names": ["abbrev_kind"], "enclosing_function": "test_empty_string", "extracted_code": "# Source: src/roam/output/formatter.py\ndef abbrev_kind(kind: str) -> str:\n return KIND_ABBREV.get(kind, kind)", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 112}, "tests/test_languages.py::1590": {"resolved_imports": [], "used_names": ["invoke_cli", "json"], "enclosing_function": "test_c_file_skeleton", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_adversarial.py::612": {"resolved_imports": ["src/roam/commands/cmd_adversarial.py"], "used_names": ["_check_orphaned_symbols"], "enclosing_function": "test_check_orphaned_returns_list", "extracted_code": "# Source: src/roam/commands/cmd_adversarial.py\ndef _check_orphaned_symbols(conn, changed_sym_ids):\n \"\"\"Check for symbols in changed files with zero incoming edges.\"\"\"\n challenges = []\n if not changed_sym_ids:\n return challenges\n\n for sid in changed_sym_ids:\n try:\n row = conn.execute(\"SELECT COUNT(*) as cnt FROM edges WHERE target_id = ?\", (sid,)).fetchone()\n except Exception:\n continue\n if not row or row[\"cnt\"] != 0:\n continue\n\n try:\n sym = conn.execute(\n \"SELECT s.name, s.kind, f.path as file_path, s.line_start \"\n \"FROM symbols s JOIN files f ON s.file_id = f.id WHERE s.id = ?\",\n (sid,),\n ).fetchone()\n except Exception:\n continue\n if not sym:\n continue\n\n # Only flag substantive symbols\n if sym[\"kind\"] not in (\"function\", \"method\", \"class\"):\n continue\n\n file_path = (sym[\"file_path\"] or \"\").replace(\"\\\\\", \"/\")\n name = sym[\"name\"] or \"\"\n\n # Skip test files and private symbols\n is_test = file_path.startswith(\"test\") or \"tests/\" in file_path or \"test/\" in file_path or \"spec/\" in file_path\n if is_test:\n continue\n if name.startswith(\"_\"):\n continue\n\n location = loc(file_path, sym[\"line_start\"])\n challenges.append(\n _challenge(\n \"orphaned\",\n \"INFO\",\n f\"Orphaned symbol: {name}\",\n (f\"{name} ({abbrev_kind(sym['kind'])}) at {location} has no callers.\"),\n (\n \"This symbol is not called by anything in the indexed codebase. \"\n \"Is it a new entry point, a public API, or was a connection forgotten?\"\n ),\n location=location,\n )\n )\n return challenges", "n_imports_parsed": 9, "n_files_resolved": 1, "n_chars_extracted": 1914}, "tests/test_pr_diff.py::304": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_pr_diff_edge_analysis", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_check_rules.py::667": {"resolved_imports": ["src/roam/cli.py", "src/roam/commands/cmd_check_rules.py"], "used_names": ["_calculate_verdict"], "enclosing_function": "test_calculate_verdict_empty", "extracted_code": "# Source: src/roam/commands/cmd_check_rules.py\ndef _calculate_verdict(results: list[dict]) -> tuple[str, int]:\n \"\"\"Return (verdict_string, exit_code).\n\n PASS = 0, WARN = 0, FAIL = 1\n \"\"\"\n total = len(results)\n errors = [r for r in results if not r[\"passed\"] and r[\"severity\"] == \"error\"]\n warnings = [r for r in results if not r[\"passed\"] and r[\"severity\"] == \"warning\"]\n infos = [r for r in results if not r[\"passed\"] and r[\"severity\"] == \"info\"]\n passed = [r for r in results if r[\"passed\"]]\n\n if total == 0:\n return \"PASS - no rules configured\", 0\n\n if errors:\n verdict = \"FAIL - {} error(s), {} warning(s), {} info\".format(len(errors), len(warnings), len(infos))\n return verdict, 1\n elif warnings:\n verdict = \"WARN - {} warning(s), {} info\".format(len(warnings), len(infos))\n return verdict, 0\n else:\n verdict = \"PASS - all {} rule(s) passed\".format(len(passed))\n return verdict, 0", "n_imports_parsed": 9, "n_files_resolved": 2, "n_chars_extracted": 970}, "tests/test_batch_mcp.py::404": {"resolved_imports": [], "used_names": ["batch_search"], "enclosing_function": "test_empty_queries_returns_empty_results", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_coverage_gaps_cmd.py::306": {"resolved_imports": [], "used_names": ["parse_json_output"], "enclosing_function": "test_json_coverage_pct_range", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_commands_health.py::30": {"resolved_imports": ["src/roam/cli.py"], "used_names": ["invoke_cli"], "enclosing_function": "test_health_shows_score", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_formatters.py::53": {"resolved_imports": ["src/roam/output/formatter.py"], "used_names": ["abbrev_kind"], "enclosing_function": "test_empty_string_passes_through", "extracted_code": "# Source: src/roam/output/formatter.py\ndef abbrev_kind(kind: str) -> str:\n return KIND_ABBREV.get(kind, kind)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 112}, "tests/test_oss_bench_harness.py::69": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_markdown_renderer_outputs_na_for_missing_metrics", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_ci_sarif_guard.py::73": {"resolved_imports": [], "used_names": ["deepcopy"], "enclosing_function": "test_apply_guardrails_run_and_result_caps", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_progress.py::69": {"resolved_imports": ["src/roam/index/indexer.py"], "used_names": ["Indexer", "os"], "enclosing_function": "test_progress_output_to_stderr", "extracted_code": "# Source: src/roam/index/indexer.py\nclass Indexer:\n \"\"\"Orchestrates the full indexing pipeline.\"\"\"\n\n def __init__(self, project_root: Path | None = None):\n if project_root is None:\n project_root = find_project_root()\n self.root = Path(project_root).resolve()\n self._quiet = False\n self._progress_bar = True\n self.summary: dict | None = None\n\n def _log(self, msg: str):\n \"\"\"Log a message to stderr, respecting quiet mode.\"\"\"\n if not self._quiet:\n sys.stderr.write(f\"{msg}\\n\")\n sys.stderr.flush()\n\n def run(\n self,\n force: bool = False,\n verbose: bool = False,\n include_excluded: bool = False,\n quiet: bool = False,\n progress_bar: bool = True,\n ):\n \"\"\"Run the indexing pipeline.\n\n Args:\n force: If True, re-index all files. Otherwise, only changed files.\n verbose: If True, show detailed warnings during indexing.\n include_excluded: If True, skip .roamignore / config / built-in\n exclusion filtering.\n quiet: If True, suppress all progress output to stderr.\n progress_bar: If True (default), show progress bars for file\n processing. Set to False in non-TTY environments.\n \"\"\"\n global _quiet_mode\n self._quiet = quiet\n self._progress_bar = progress_bar\n _quiet_mode = quiet\n self._log(f\"Indexing {self.root}\")\n\n # Lock file to prevent concurrent indexing\n lock_path = self.root / \".roam\" / \"index.lock\"\n lock_path.parent.mkdir(exist_ok=True)\n if lock_path.exists():\n try:\n pid = int(lock_path.read_text().strip())\n try:\n os.kill(pid, 0)\n self._log(f\"Another indexing process (PID {pid}) is running. Exiting.\")\n return\n except (OSError, SystemError):\n # OSError: process not found (Unix/Windows)\n # SystemError: Windows os.kill edge case\n self._log(f\"Removing stale lock file (PID {pid} is not running).\")\n lock_path.unlink()\n except (ValueError, OSError):\n lock_path.unlink()\n\n lock_path.write_text(str(os.getpid()))\n try:\n self._do_run(force, verbose=verbose, include_excluded=include_excluded)\n finally:\n _quiet_mode = False\n try:\n lock_path.unlink()\n except OSError:\n pass\n\n def _extract_file_refs(\n self,\n rel_path,\n full_path,\n language,\n source,\n symbols,\n tree,\n parsed_source,\n extractor,\n all_references,\n verbose,\n ):\n \"\"\"Extract references from a single file (calls, imports, inheritance).\"\"\"\n refs = extract_references(tree, parsed_source, rel_path, extractor)\n for ref in refs:\n ref[\"source_file\"] = rel_path\n all_references.extend(refs)\n\n # Vue template scanning\n if rel_path.endswith(\".vue\"):\n tpl_result = extract_vue_template(source if isinstance(source, bytes) else b\"\")\n if tpl_result:\n tpl_content, tpl_start_line = tpl_result\n known_names = {s[\"name\"] for s in symbols} if symbols else set()\n tpl_refs = scan_template_references(\n tpl_content,\n tpl_start_line,\n known_names,\n rel_path,\n )\n all_references.extend(tpl_refs)\n\n # Generic supplement: inheritance refs Tier 1 extractors may miss\n if not isinstance(extractor, GenericExtractor) and language and tree is not None:\n try:\n generic = GenericExtractor(language=language)\n generic_refs = generic.extract_references(tree, parsed_source, rel_path)\n for ref in generic_refs:\n if ref.get(\"kind\") in (\"inherits\", \"implements\", \"uses_trait\"):\n ref[\"source_file\"] = rel_path\n all_references.append(ref)\n except Exception as e:\n if verbose:\n self._log(f\" Warning: generic extractor failed for {rel_path}: {e}\")\n\n def _process_files(self, conn, files_to_process, get_extractor, compute_complexity_fn, verbose):\n \"\"\"Parse, extract symbols, and store per-file data. Returns (all_symbol_rows, all_references, file_id_by_path).\"\"\"\n all_symbol_rows = {}\n all_references = []\n file_id_by_path = {}\n total = len(files_to_process)\n\n # Use progress bar when available and not quiet\n use_bar = self._progress_bar and not self._quiet and total > 0\n bar_ctx = None\n bar_obj = None\n if use_bar:\n try:\n import click\n\n bar_ctx = click.progressbar(\n length=total,\n label=\"Processing\",\n file=sys.stderr,\n width=36,\n )\n bar_obj = bar_ctx.__enter__()\n except Exception:\n use_bar = False\n\n try:\n for i, rel_path in enumerate(files_to_process, 1):\n full_path = self.root / rel_path\n language = detect_language(rel_path)\n\n if use_bar and bar_obj is not None:\n bar_obj.update(1)\n elif (i % 100 == 0) or (i == total):\n self._log(f\" Processing {i}/{total} files...\")\n\n if (i % 100 == 0) or (i == total):\n conn.commit()\n\n try:\n with open(full_path, \"rb\") as f:\n source = f.read()\n except OSError as e:\n if verbose:\n self._log(f\" Warning: Could not read {rel_path}: {e}\")\n continue\n\n line_count = _count_lines(source)\n complexity = _compute_complexity(source)\n try:\n mtime = full_path.stat().st_mtime\n except OSError:\n mtime = None\n fhash = file_hash(full_path)\n\n content_head = source[:2048].decode(\"utf-8\", errors=\"replace\") if source else None\n file_role = classify_file(rel_path, content_head)\n\n conn.execute(\n \"INSERT INTO files (path, language, file_role, hash, mtime, line_count) VALUES (?, ?, ?, ?, ?, ?)\",\n (rel_path, language, file_role, fhash, mtime, line_count),\n )\n row = conn.execute(\"SELECT last_insert_rowid()\").fetchone()\n if not row:\n self._log(f\" Warning: Failed to insert file record for {rel_path}\")\n continue\n file_id = row[0]\n file_id_by_path[rel_path] = file_id\n\n conn.execute(\n \"INSERT OR REPLACE INTO file_stats (file_id, complexity) VALUES (?, ?)\",\n (file_id, complexity),\n )\n\n tree, parsed_source, lang = parse_file(full_path, language)\n if tree is None and parsed_source is None:\n continue\n\n extractor = None\n if get_extractor is not None and lang is not None:\n try:\n extractor = get_extractor(lang)\n except Exception as e:\n if verbose:\n self._log(f\" Warning: No extractor for {lang}: {e}\")\n if extractor is None:\n continue\n\n symbols = extract_symbols(tree, parsed_source, rel_path, extractor)\n _store_symbols(conn, file_id, rel_path, symbols, all_symbol_rows)\n\n if compute_complexity_fn is not None and tree is not None:\n try:\n compute_complexity_fn(conn, file_id, tree, parsed_source)\n except Exception as e:\n if verbose:\n self._log(f\" Warning: complexity analysis failed for {rel_path}: {e}\")\n\n self._extract_file_refs(\n rel_path,\n full_path,\n language,\n source,\n symbols,\n tree,\n parsed_source,\n extractor,\n all_references,\n verbose,\n )\n finally:\n if bar_ctx is not None:\n try:\n bar_ctx.__exit__(None, None, None)\n except Exception:\n pass\n\n return all_symbol_rows, all_references, file_id_by_path\n\n @staticmethod\n def _find_affected_neighbor_files(conn, changed_file_ids):\n \"\"\"Find file IDs of unchanged files that had edges into changed files.\n\n When a changed file's symbols are deleted (CASCADE), edges FROM\n other files TO those symbols are also deleted. We need to re-extract\n references from those \"affected neighbor\" files to re-establish edges\n pointing to the new symbols.\n\n Returns a set of file_ids (excluding the changed files themselves).\n \"\"\"\n if not changed_file_ids:\n return set()\n\n changed_set = set(changed_file_ids)\n\n # Use source_file_id if available (v11+ databases)\n has_source_file_id = False\n try:\n row = conn.execute(\"SELECT source_file_id FROM edges LIMIT 1\").fetchone()\n has_source_file_id = row is not None and row[\"source_file_id\"] is not None\n except Exception:\n pass\n\n affected = set()\n ph = \",\".join(\"?\" for _ in changed_file_ids)\n\n if has_source_file_id:\n # Fast path: edges already track source_file_id\n rows = conn.execute(\n f\"SELECT DISTINCT e.source_file_id \"\n f\"FROM edges e \"\n f\"JOIN symbols s_tgt ON e.target_id = s_tgt.id \"\n f\"WHERE s_tgt.file_id IN ({ph}) \"\n f\"AND e.source_file_id NOT IN ({ph})\",\n changed_file_ids + changed_file_ids,\n ).fetchall()\n affected = {r[0] for r in rows if r[0] is not None}\n else:\n # Fallback for pre-v11 databases: derive source file from source symbol\n rows = conn.execute(\n f\"SELECT DISTINCT s_src.file_id \"\n f\"FROM edges e \"\n f\"JOIN symbols s_src ON e.source_id = s_src.id \"\n f\"JOIN symbols s_tgt ON e.target_id = s_tgt.id \"\n f\"WHERE s_tgt.file_id IN ({ph}) \"\n f\"AND s_src.file_id NOT IN ({ph})\",\n changed_file_ids + changed_file_ids,\n ).fetchall()\n affected = {r[0] for r in rows}\n\n return affected - changed_set\n\n def _re_extract_affected(self, conn, affected_file_ids, get_extractor, all_references, verbose):\n \"\"\"Re-extract references from only the affected neighbor files.\n\n These are files whose edges into changed files were CASCADE-deleted.\n We surgically delete their remaining edges and re-extract references\n so they can be re-resolved against the updated symbol table.\n \"\"\"\n if not affected_file_ids:\n return\n\n # Map file_id -> path for affected files\n ph = \",\".join(\"?\" for _ in affected_file_ids)\n fid_list = list(affected_file_ids)\n rows = conn.execute(f\"SELECT id, path FROM files WHERE id IN ({ph})\", fid_list).fetchall()\n affected_paths = {r[\"id\"]: r[\"path\"] for r in rows}\n\n self._log(f\"Re-extracting references from {len(affected_paths)} affected neighbor files...\")\n\n # Delete edges originating from affected files (they'll be rebuilt)\n conn.execute(f\"DELETE FROM edges WHERE source_file_id IN ({ph})\", fid_list)\n # Also delete file_edges from affected files\n conn.execute(f\"DELETE FROM file_edges WHERE source_file_id IN ({ph})\", fid_list)\n\n for fid, rel_path in affected_paths.items():\n full_path = self.root / rel_path\n language = detect_language(rel_path)\n tree, parsed_source, lang = parse_file(full_path, language)\n if tree is None and parsed_source is None:\n continue\n extractor = None\n if get_extractor is not None and lang is not None:\n try:\n extractor = get_extractor(lang)\n except Exception as e:\n if verbose:\n self._log(f\" Warning: no extractor for {lang}: {e}\")\n if extractor is None:\n continue\n try:\n symbols = extractor.extract_symbols(tree, parsed_source, rel_path)\n except Exception as e:\n symbols = []\n if verbose:\n self._log(f\" Warning: re-extract symbols failed for {rel_path}: {e}\")\n\n # Read raw source for Vue template scanning\n raw_source = None\n if rel_path.endswith(\".vue\"):\n from roam.index.parser import read_source\n\n raw_source = read_source(full_path)\n\n self._extract_file_refs(\n rel_path,\n full_path,\n language,\n raw_source or b\"\",\n symbols,\n tree,\n parsed_source,\n extractor,\n all_references,\n verbose,\n )\n\n @staticmethod\n def _backup_annotations(db_path):\n \"\"\"Read all annotations from the DB before force-reindex deletes it.\"\"\"\n import gc\n import sqlite3\n\n if not db_path.exists():\n return []\n conn = None\n try:\n conn = sqlite3.connect(str(db_path), timeout=10)\n conn.row_factory = sqlite3.Row\n # Check if annotations table exists\n tables = conn.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='annotations'\").fetchone()\n if not tables:\n return []\n rows = conn.execute(\"SELECT * FROM annotations\").fetchall()\n result = [dict(r) for r in rows]\n except Exception:\n return []\n finally:\n if conn is not None:\n try:\n conn.close()\n except Exception:\n pass\n del conn\n gc.collect() # Release file handles on Windows\n\n # Also write to JSON backup for crash safety\n backup_path = db_path.parent / \"annotations_backup.json\"\n try:\n import json\n\n backup_path.write_text(\n json.dumps(result, default=str),\n encoding=\"utf-8\",\n )\n except Exception:\n pass\n\n return result\n\n @staticmethod\n def _restore_annotations(conn, saved):\n \"\"\"Re-insert saved annotations and re-link to new symbol IDs.\"\"\"\n if not saved:\n return\n for ann in saved:\n conn.execute(\n \"INSERT INTO annotations \"\n \"(qualified_name, file_path, tag, content, author, \"\n \" created_at, expires_at) \"\n \"VALUES (?, ?, ?, ?, ?, ?, ?)\",\n (\n ann.get(\"qualified_name\"),\n ann.get(\"file_path\"),\n ann.get(\"tag\"),\n ann[\"content\"],\n ann.get(\"author\"),\n ann.get(\"created_at\"),\n ann.get(\"expires_at\"),\n ),\n )\n _relink_annotations(conn)\n _log(f\" Restored {len(saved)} annotations\")\n\n def _do_run(self, force: bool, verbose: bool = False, include_excluded: bool = False):\n t0 = time.monotonic()\n self._log(\"Discovering files...\")\n all_files = discover_files(self.root, include_excluded=include_excluded)\n self._log(f\" {_format_count(len(all_files))} files found\")\n\n saved_annotations = []\n if force:\n db_path = get_db_path(self.root)\n if db_path.exists():\n saved_annotations = self._backup_annotations(db_path)\n db_path.unlink()\n for suffix in (\"-wal\", \"-shm\"):\n wal = db_path.parent / (db_path.name + suffix)\n if wal.exists():\n wal.unlink()\n\n with open_db(project_root=self.root) as conn:\n if force:\n added = all_files\n modified = []\n removed = []\n else:\n added, modified, removed = get_changed_files(conn, all_files, self.root)\n\n total_changed = len(added) + len(modified) + len(removed)\n if total_changed == 0:\n self._log(\"Index is up to date.\")\n self.summary = {\n \"files\": 0,\n \"symbols\": 0,\n \"edges\": 0,\n \"elapsed\": 0.0,\n \"up_to_date\": True,\n }\n return\n\n self._log(f\" {len(added)} added, {len(modified)} modified, {len(removed)} removed\")\n\n # Collect file IDs of changed/removed files BEFORE deleting them\n changed_file_ids = []\n for path in removed + modified:\n row = conn.execute(\"SELECT id FROM files WHERE path = ?\", (path,)).fetchone()\n if row:\n changed_file_ids.append(row[\"id\"])\n\n # Find affected neighbor files BEFORE CASCADE deletes the edges\n # we need for the query. These are files whose edges INTO the\n # changed files will be lost and need rebuilding.\n affected_file_ids = set()\n if not force and modified and changed_file_ids:\n affected_file_ids = self._find_affected_neighbor_files(\n conn,\n changed_file_ids,\n )\n\n # Now delete the changed/removed file records (CASCADE cleans up\n # their symbols, edges, file_edges, graph_metrics, clusters, etc.)\n for path in removed + modified:\n row = conn.execute(\"SELECT id FROM files WHERE path = ?\", (path,)).fetchone()\n if row:\n fid = row[\"id\"]\n # Clean up tables with SET NULL FKs (not CASCADE)\n sym_ids = [\n r[0] for r in conn.execute(\"SELECT id FROM symbols WHERE file_id = ?\", (fid,)).fetchall()\n ]\n if sym_ids:\n ph = \",\".join(\"?\" for _ in sym_ids)\n for cleanup_sql in [\n f\"UPDATE runtime_stats SET symbol_id = NULL WHERE symbol_id IN ({ph})\",\n f\"UPDATE vulnerabilities SET matched_symbol_id = NULL WHERE matched_symbol_id IN ({ph})\",\n ]:\n try:\n conn.execute(cleanup_sql, sym_ids)\n except Exception:\n pass # Table may not exist in older DBs\n conn.execute(\"DELETE FROM files WHERE id = ?\", (fid,))\n\n get_extractor = _try_import_get_extractor()\n compute_complexity_fn = _try_import_complexity()\n\n # 3-6. Parse, extract, store\n files_to_process = added + modified\n all_symbol_rows, all_references, file_id_by_path = self._process_files(\n conn,\n files_to_process,\n get_extractor,\n compute_complexity_fn,\n verbose,\n )\n\n # Load existing symbols for incremental\n if not force:\n existing_rows = conn.execute(\n \"SELECT s.id, s.file_id, s.name, s.qualified_name, s.kind, \"\n \"s.is_exported, s.line_start, f.path as file_path \"\n \"FROM symbols s JOIN files f ON s.file_id = f.id\"\n ).fetchall()\n for row in existing_rows:\n sid = row[\"id\"]\n if sid not in all_symbol_rows:\n all_symbol_rows[sid] = {\n \"id\": sid,\n \"file_id\": row[\"file_id\"],\n \"file_path\": row[\"file_path\"],\n \"name\": row[\"name\"],\n \"qualified_name\": row[\"qualified_name\"],\n \"kind\": row[\"kind\"],\n \"is_exported\": bool(row[\"is_exported\"]),\n \"line_start\": row[\"line_start\"],\n }\n\n for row in conn.execute(\"SELECT id, path FROM files\").fetchall():\n file_id_by_path[row[\"path\"]] = row[\"id\"]\n\n # Fix incremental edge loss: re-extract only affected neighbors\n # instead of all unchanged files (O(affected) vs O(N))\n if not force and modified and affected_file_ids:\n self._re_extract_affected(\n conn,\n affected_file_ids,\n get_extractor,\n all_references,\n verbose,\n )\n\n # Resolve references into edges\n self._log(\"Resolving references...\")\n symbols_by_name: dict[str, list[dict]] = {}\n for sym in all_symbol_rows.values():\n symbols_by_name.setdefault(sym[\"name\"], []).append(sym)\n\n symbol_edges = resolve_references(all_references, symbols_by_name, file_id_by_path)\n\n conn.executemany(\n \"INSERT INTO edges (source_id, target_id, kind, line, source_file_id) VALUES (?, ?, ?, ?, ?)\",\n [(e[\"source_id\"], e[\"target_id\"], e[\"kind\"], e[\"line\"], e.get(\"source_file_id\")) for e in symbol_edges],\n )\n self._log(f\" {_format_count(len(symbol_edges))} symbol edges\")\n\n # Build file edges\n self._log(\"Building file-level edges...\")\n file_edges = build_file_edges(symbol_edges, all_symbol_rows)\n conn.executemany(\n \"INSERT INTO file_edges (source_file_id, target_file_id, kind, symbol_count) VALUES (?, ?, ?, ?)\",\n [(fe[\"source_file_id\"], fe[\"target_file_id\"], fe[\"kind\"], fe[\"symbol_count\"]) for fe in file_edges],\n )\n self._log(f\" {_format_count(len(file_edges))} file edges\")\n\n # Graph metrics\n (\n build_symbol_graph,\n _store_metrics,\n _detect_clusters,\n _label_clusters,\n _store_clusters,\n ) = _try_import_graph()\n G = None\n if build_symbol_graph is not None:\n self._log(\"Computing graph metrics...\")\n try:\n G = build_symbol_graph(conn)\n _store_metrics(conn, G)\n metric_count = conn.execute(\"SELECT COUNT(*) FROM graph_metrics\").fetchone()[0]\n self._log(f\" Metrics for {_format_count(metric_count)} symbols\")\n except Exception as e:\n self._log(f\" Graph metrics failed: {e}\")\n else:\n self._log(\"Skipping graph metrics (module not available)\")\n\n # Git history\n analyze_git = _try_import_git_stats()\n if analyze_git is not None:\n self._log(\"Analyzing git history...\")\n try:\n analyze_git(conn, self.root)\n except Exception as e:\n self._log(f\" Git analysis failed: {e}\")\n else:\n self._log(\"Skipping git analysis (module not available)\")\n\n # Clusters\n if _detect_clusters is not None and G is not None:\n self._log(\"Computing clusters...\")\n try:\n cluster_map = _detect_clusters(G)\n labels = _label_clusters(cluster_map, conn)\n _store_clusters(conn, cluster_map, labels)\n self._log(f\" {len(set(cluster_map.values()))} clusters\")\n except Exception as e:\n self._log(f\" Clustering failed: {e}\")\n else:\n self._log(\"Skipping clustering (module not available)\")\n\n # Effect classification + propagation\n _effects_fn = _try_import_effects()\n if _effects_fn is not None:\n self._log(\"Classifying symbol effects...\")\n try:\n _effects_fn(conn, self.root, G)\n effect_count = conn.execute(\"SELECT COUNT(*) FROM symbol_effects\").fetchone()[0]\n if effect_count:\n self._log(f\" {_format_count(effect_count)} effects classified\")\n except Exception as e:\n self._log(f\" Effect analysis failed: {e}\")\n\n # Taint analysis (inter-procedural)\n _taint_fn = _try_import_taint()\n if _taint_fn is not None:\n self._log(\"Computing taint summaries...\")\n try:\n _taint_fn(conn, self.root, G)\n taint_count = conn.execute(\"SELECT COUNT(*) FROM taint_findings\").fetchone()[0]\n if taint_count:\n self._log(f\" {_format_count(taint_count)} taint findings\")\n except Exception as e:\n self._log(f\" Taint analysis failed: {e}\")\n\n # Per-file health scores — pass G so cycle detection uses SCC, not SQL self-join\n self._log(\"Computing health scores...\")\n try:\n _compute_file_health_scores(conn, G)\n except Exception as e:\n self._log(f\" Health score computation failed: {e}\")\n\n # Cognitive load index\n self._log(\"Computing cognitive load...\")\n try:\n _compute_cognitive_load(conn)\n except Exception as e:\n self._log(f\" Cognitive load computation failed: {e}\")\n\n # Annotation survival\n if force and saved_annotations:\n self._log(\"Restoring annotations...\")\n try:\n self._restore_annotations(conn, saved_annotations)\n except Exception as e:\n self._log(f\" Annotation restore failed: {e}\")\n elif not force:\n # Re-link annotations after incremental reindex\n try:\n _relink_annotations(conn)\n except Exception:\n pass\n\n # Full-text search index (FTS5/BM25 primary, TF-IDF fallback)\n self._log(\"Building search index...\")\n try:\n from roam.search.index_embeddings import build_fts_index, fts5_available\n\n build_fts_index(conn, project_root=self.root)\n if fts5_available(conn):\n fts_count = conn.execute(\"SELECT COUNT(*) FROM symbol_fts\").fetchone()[0]\n self._log(f\" FTS5 index for {_format_count(fts_count)} symbols\")\n else:\n tfidf_count = conn.execute(\"SELECT COUNT(*) FROM symbol_tfidf\").fetchone()[0]\n self._log(f\" TF-IDF vectors for {_format_count(tfidf_count)} symbols (FTS5 unavailable)\")\n try:\n onnx_count = conn.execute(\n \"SELECT COUNT(*) FROM symbol_embeddings WHERE provider='onnx'\"\n ).fetchone()[0]\n if onnx_count:\n self._log(f\" ONNX vectors for {_format_count(onnx_count)} symbols\")\n except Exception:\n pass\n except Exception as e:\n self._log(f\" Search index build failed (non-fatal): {e}\")\n\n from roam.index.parser import get_parse_error_summary\n\n error_summary = get_parse_error_summary()\n if error_summary:\n self._log(f\" Parse issues: {error_summary}\")\n\n elapsed = time.monotonic() - t0\n file_count = conn.execute(\"SELECT COUNT(*) FROM files\").fetchone()[0]\n sym_count = conn.execute(\"SELECT COUNT(*) FROM symbols\").fetchone()[0]\n edge_count = conn.execute(\"SELECT COUNT(*) FROM edges\").fetchone()[0]\n self._log(\n f\"Index complete: {_format_count(file_count)} files, \"\n f\"{_format_count(sym_count)} symbols, \"\n f\"{_format_count(edge_count)} edges ({elapsed:.1f}s)\"\n )\n self.summary = {\n \"files\": file_count,\n \"symbols\": sym_count,\n \"edges\": edge_count,\n \"elapsed\": round(elapsed, 1),\n \"up_to_date\": False,\n }", "n_imports_parsed": 10, "n_files_resolved": 1, "n_chars_extracted": 29326}, "tests/test_bridges_extended.py::338": {"resolved_imports": ["src/roam/bridges/__init__.py", "src/roam/bridges/registry.py", "src/roam/bridges/bridge_config.py", "src/roam/bridges/bridge_rest_api.py", "src/roam/bridges/bridge_template.py"], "used_names": ["invoke_cli"], "enclosing_function": "test_xlang_command_runs", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 5, "n_chars_extracted": 0}, "tests/test_agent_export.py::81": {"resolved_imports": [], "used_names": ["index_in_process", "pytest"], "enclosing_function": "indexed_small_project", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_ai_ratio.py::85": {"resolved_imports": [], "used_names": ["json", "pytest"], "enclosing_function": "_parse_json", "extracted_code": "", "n_imports_parsed": 11, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_mermaid.py::66": {"resolved_imports": ["src/roam/output/mermaid.py"], "used_names": ["sanitize_id"], "enclosing_function": "test_empty_string", "extracted_code": "# Source: src/roam/output/mermaid.py\ndef sanitize_id(name: str) -> str:\n \"\"\"Convert a file path or symbol name to a valid Mermaid node ID.\n\n Replaces characters that are invalid in Mermaid identifiers\n (``/``, ``.``, ``-``, ``:``, `` ``) with underscores, and strips\n leading digits so the ID is always a valid identifier.\n \"\"\"\n s = re.sub(r\"[^A-Za-z0-9_]\", \"_\", name)\n # Mermaid IDs must not start with a digit\n if s and s[0].isdigit():\n s = \"_\" + s\n return s", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 494}, "tests/test_codeowners.py::301": {"resolved_imports": ["src/roam/commands/cmd_codeowners.py"], "used_names": ["_key_areas"], "enclosing_function": "test_key_areas", "extracted_code": "# Source: src/roam/commands/cmd_codeowners.py\ndef _key_areas(file_paths: list[str], max_areas: int = 3) -> list[str]:\n \"\"\"Extract the most common directory prefixes from a list of file paths.\"\"\"\n dir_counts: dict[str, int] = defaultdict(int)\n for fp in file_paths:\n fp = fp.replace(\"\\\\\", \"/\")\n parts = fp.split(\"/\")\n if len(parts) >= 2:\n # Use first two path components as the area\n area = \"/\".join(parts[:2]) + \"/\"\n elif len(parts) == 1:\n area = \"./\"\n else:\n area = \"./\"\n dir_counts[area] += 1\n\n sorted_areas = sorted(dir_counts.items(), key=lambda x: x[1], reverse=True)\n return [area for area, _count in sorted_areas[:max_areas]]", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 733}, "tests/test_batch_mcp.py::261": {"resolved_imports": [], "used_names": ["_batch_search_one"], "enclosing_function": "test_no_results", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_agent_mode.py::42": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_agent_mode_conflicts_with_sarif", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_context_propagation.py::287": {"resolved_imports": ["src/roam/graph/propagation.py"], "used_names": ["callee_chain"], "enclosing_function": "test_linear_chain_depths", "extracted_code": "# Source: src/roam/graph/propagation.py\ndef callee_chain(\n G,\n node: int,\n max_depth: int = 3,\n) -> List[Tuple[int, int]]:\n \"\"\"Return ordered list of transitive callees with their BFS depth.\n\n BFS from *node* through outgoing (callee) edges up to *max_depth*.\n Cycles are handled via a visited set — each callee is reported at\n the shallowest depth it is reached.\n\n Parameters\n ----------\n G:\n Directed call graph (caller -> callee edges).\n node:\n Starting symbol node ID.\n max_depth:\n Maximum callee depth to traverse. Defaults to 3.\n\n Returns\n -------\n list of (node_id, depth) tuples\n Ordered by BFS level (shallow callees first), then by node ID for\n determinism. The seed node itself is NOT included.\n \"\"\"\n if node not in G:\n return []\n\n visited: Dict[int, int] = {node: 0}\n queue: deque[Tuple[int, int]] = deque([(node, 0)])\n result: List[Tuple[int, int]] = []\n\n while queue:\n current, depth = queue.popleft()\n if depth >= max_depth:\n continue\n next_depth = depth + 1\n for neighbor in sorted(G.successors(current)): # sorted for determinism\n if neighbor not in visited:\n visited[neighbor] = next_depth\n result.append((neighbor, next_depth))\n queue.append((neighbor, next_depth))\n\n return result", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 1406}, "tests/test_ci_gate_eval.py::51": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_trend_latest_and_delta", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_agent_mode.py::43": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_agent_mode_conflicts_with_sarif", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_progress.py::266": {"resolved_imports": ["src/roam/index/indexer.py"], "used_names": ["_format_count"], "enclosing_function": "test_zero", "extracted_code": "# Source: src/roam/index/indexer.py\ndef _format_count(n: int) -> str:\n \"\"\"Format an integer with thousands separators.\"\"\"\n return f\"{n:,}\"", "n_imports_parsed": 10, "n_files_resolved": 1, "n_chars_extracted": 144}, "tests/test_backend_fixes_round3.py::222": {"resolved_imports": ["src/roam/commands/cmd_migration_safety.py"], "used_names": ["_check_add_column"], "enclosing_function": "test_no_guard_produces_finding", "extracted_code": "# Source: src/roam/commands/cmd_migration_safety.py\ndef _check_add_column(lines: list[str], up_start: int, up_end: int) -> list[dict]:\n \"\"\"Detect column definitions inside Schema::table() without hasColumn guard.\n\n Strategy: find Schema::table() blocks and check whether each column\n definition inside them is preceded by a hasColumn guard in the same\n containing block or outer if-statement.\n \"\"\"\n findings = []\n if up_start == 0:\n return findings\n\n up_lines = lines[up_start - 1 : up_end]\n\n # Find Schema::table() calls; each opens a closure for altering a table.\n # We detect the surrounding if-block or direct call and see if hasColumn\n # exists in the surrounding context.\n for rel_i, line in enumerate(up_lines):\n if not _RE_COLUMN_DEF.search(line):\n continue\n\n abs_line = up_start + rel_i\n\n # We only flag column additions inside a Schema::table() context\n # (altering an existing table). Skip if this looks like it's inside\n # a Schema::create() block (adding columns to a brand-new table is\n # always safe — the table didn't exist before).\n context_start = max(0, rel_i - 60)\n pre_context = \"\".join(up_lines[context_start : rel_i + 1])\n\n if _RE_SCHEMA_CREATE.search(pre_context) and not _RE_SCHEMA_TABLE.search(pre_context):\n continue # Inside Schema::create() — new table, no guard needed\n\n if not _RE_SCHEMA_TABLE.search(pre_context):\n continue # Not inside an alter-table block — skip\n\n # Check if hasColumn guard appears near this column definition\n if _RE_HAS_COLUMN.search(pre_context):\n continue # Guarded — OK\n if _RE_HAS_TABLE.search(pre_context):\n continue # hasTable guard — OK\n if _RE_INFO_SCHEMA_GUARD.search(pre_context):\n continue # information_schema guard — OK\n\n col_name = _extract_arg(line)\n\n findings.append(\n {\n \"line\": abs_line,\n \"confidence\": \"medium\",\n \"issue\": f\"->column({col_name!r}) without hasColumn guard in Schema::table() block\",\n \"fix\": (\n f\"Wrap with: if (!Schema::hasColumn($table, {col_name!r})) {{ ... }}\"\n if col_name\n else \"Wrap column addition with an if (!Schema::hasColumn(...)) check\"\n ),\n \"category\": \"add_column_without_check\",\n }\n )\n\n return findings", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 2511}, "tests/test_backend_fixes_round2.py::163": {"resolved_imports": ["src/roam/commands/cmd_auth_gaps.py"], "used_names": ["_analyze_service_provider"], "enclosing_function": "test_service_provider_non_provider_class", "extracted_code": "# Source: src/roam/commands/cmd_auth_gaps.py\ndef _analyze_service_provider(file_path: str, source: str) -> set[str]:\n \"\"\"Scan a ServiceProvider file for controllers registered inside auth middleware groups.\n\n Returns a set of controller class names (e.g. ``'OrderController'``) that are\n referenced inside ``Route::middleware(['auth:sanctum'])->group(...)`` blocks\n within a ServiceProvider ``boot()`` method.\n \"\"\"\n protected_controllers: set[str] = set()\n\n # Quick check: file must extend ServiceProvider and contain Route::middleware auth\n if not _RE_SERVICE_PROVIDER_CLASS.search(source):\n return protected_controllers\n if not _RE_PROVIDER_ROUTE_MIDDLEWARE.search(source):\n return protected_controllers\n\n # Track brace depth to detect controllers inside auth middleware groups.\n # Strategy: when we see Route::middleware('auth...')->group(, mark that depth\n # as auth-protected and collect controller refs until the group closes.\n lines = source.splitlines()\n brace_depth = 0\n auth_depth_stack: list[tuple[int, bool]] = [] # (depth_at_open, is_auth)\n\n for line in lines:\n opens, closes = _count_braces(line)\n\n # Check for auth middleware group opener\n if _RE_PROVIDER_ROUTE_MIDDLEWARE.search(line) and re.search(r\"->\\s*group\\s*\\(\", line):\n # Process closes first\n for _ in range(closes):\n brace_depth -= 1\n if brace_depth < 0:\n brace_depth = 0\n if auth_depth_stack and auth_depth_stack[-1][0] == brace_depth:\n auth_depth_stack.pop()\n auth_depth_stack.append((brace_depth, True))\n brace_depth += opens\n continue\n\n # Process closing braces\n for _ in range(closes):\n brace_depth -= 1\n if brace_depth < 0:\n brace_depth = 0\n if auth_depth_stack and auth_depth_stack[-1][0] == brace_depth:\n auth_depth_stack.pop()\n\n # Check if currently inside auth group\n currently_protected = any(auth for _, auth in auth_depth_stack)\n\n brace_depth += opens\n\n if currently_protected:\n for cm in _RE_CONTROLLER_REF.finditer(line):\n name = cm.group(1) or cm.group(2)\n if name:\n protected_controllers.add(name)\n\n return protected_controllers", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 2410}, "tests/test_kotlin_swift_extractors.py::105": {"resolved_imports": ["src/roam/index/parser.py", "src/roam/languages/registry.py"], "used_names": [], "enclosing_function": "test_swift_protocol_struct_enum_constructor_and_properties", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_competitor_site_data.py::85": {"resolved_imports": ["src/roam/competitor_site_data.py", "src/roam/surface_counts.py"], "used_names": ["SCORING_RUBRIC", "build_site_payload"], "enclosing_function": "test_every_competitor_has_scores_with_all_7_categories", "extracted_code": "# Source: src/roam/competitor_site_data.py\nSCORING_RUBRIC = [\n {\n \"id\": \"static_analysis\",\n \"label\": \"Static Analysis Depth\",\n \"max_points\": 20,\n \"default_weight\": 20,\n \"criteria\": [\n {\"id\": \"ast_parsing\", \"label\": \"AST parsing\", \"type\": \"binary\", \"max\": 2},\n {\"id\": \"persistent_index\", \"label\": \"Persistent index\", \"type\": \"binary\", \"max\": 3},\n {\n \"id\": \"call_graph\",\n \"label\": \"Call graph extraction\",\n \"type\": \"tiered\",\n \"max\": 3,\n \"tiers\": {\"none\": 0, \"basic\": 1, \"cross_file\": 2, \"dataflow\": 3},\n },\n {\n \"id\": \"cognitive_complexity\",\n \"label\": \"Cognitive complexity metrics\",\n \"type\": \"binary\",\n \"max\": 2,\n },\n {\n \"id\": \"vuln_reachability\",\n \"label\": \"Vulnerability reachability\",\n \"type\": \"tiered\",\n \"max\": 2,\n \"tiers\": {\"none\": 0, \"graph\": 1, \"taint\": 2},\n },\n {\n \"id\": \"dead_code\",\n \"label\": \"Dead code detection\",\n \"type\": \"tiered\",\n \"max\": 2,\n \"tiers\": {\"none\": 0, \"reference\": 1, \"dataflow\": 2},\n },\n {\n \"id\": \"dataflow_taint\",\n \"label\": \"Dataflow/taint analysis\",\n \"type\": \"tiered\",\n \"max\": 4,\n \"tiers\": {\"none\": 0, \"intra\": 1, \"inter\": 3, \"full\": 4},\n },\n {\n \"id\": \"languages_supported\",\n \"label\": \"Languages supported\",\n \"type\": \"tiered\",\n \"max\": 2,\n \"tiers\": [[0, 4, 0], [5, 15, 1], [16, None, 2]],\n },\n ],\n },\n {\n \"id\": \"graph_intelligence\",\n \"label\": \"Graph Intelligence\",\n \"max_points\": 10,\n \"default_weight\": 10,\n \"criteria\": [\n {\n \"id\": \"pagerank_centrality\",\n \"label\": \"PageRank / centrality\",\n \"type\": \"binary\",\n \"max\": 2,\n },\n {\n \"id\": \"cycle_detection_scc\",\n \"label\": \"Cycle detection (SCC)\",\n \"type\": \"binary\",\n \"max\": 2,\n },\n {\n \"id\": \"community_detection\",\n \"label\": \"Community detection (Louvain)\",\n \"type\": \"binary\",\n \"max\": 2,\n },\n {\"id\": \"topological_layers\", \"label\": \"Topological layers\", \"type\": \"binary\", \"max\": 1},\n {\n \"id\": \"architecture_simulation\",\n \"label\": \"Architecture simulation\",\n \"type\": \"binary\",\n \"max\": 2,\n },\n {\n \"id\": \"topology_fingerprint\",\n \"label\": \"Topology fingerprinting\",\n \"type\": \"binary\",\n \"max\": 1,\n },\n ],\n },\n {\n \"id\": \"git_temporal\",\n \"label\": \"Git & Temporal Analysis\",\n \"max_points\": 10,\n \"default_weight\": 10,\n \"criteria\": [\n {\n \"id\": \"git_churn_hotspots\",\n \"label\": \"Git churn / hotspots\",\n \"type\": \"binary\",\n \"max\": 3,\n },\n {\"id\": \"co_change_coupling\", \"label\": \"Co-change coupling\", \"type\": \"binary\", \"max\": 2},\n {\"id\": \"blame_ownership\", \"label\": \"Blame / ownership\", \"type\": \"binary\", \"max\": 2},\n {\"id\": \"entropy_analysis\", \"label\": \"Entropy analysis\", \"type\": \"binary\", \"max\": 2},\n {\"id\": \"pr_diff_risk\", \"label\": \"PR/diff risk scoring\", \"type\": \"binary\", \"max\": 1},\n ],\n },\n {\n \"id\": \"agent_integration\",\n \"label\": \"Agent Integration\",\n \"max_points\": 16,\n \"default_weight\": 16,\n \"criteria\": [\n {\n \"id\": \"mcp_tools_count\",\n \"label\": \"MCP tools\",\n \"type\": \"tiered\",\n \"max\": 6,\n \"tiers\": [[0, 0, 0], [1, 10, 2], [11, 30, 4], [31, None, 6]],\n },\n {\n \"id\": \"json_structured_output\",\n \"label\": \"JSON structured output\",\n \"type\": \"binary\",\n \"max\": 2,\n },\n {\"id\": \"token_budget\", \"label\": \"Token budget awareness\", \"type\": \"binary\", \"max\": 2},\n {\n \"id\": \"tool_presets\",\n \"label\": \"Tool presets / progressive disclosure\",\n \"type\": \"binary\",\n \"max\": 2,\n },\n {\n \"id\": \"cli_commands_count\",\n \"label\": \"CLI commands\",\n \"type\": \"tiered\",\n \"max\": 3,\n \"tiers\": [[0, 4, 0], [5, 20, 1], [21, 50, 2], [51, None, 3]],\n },\n {\n \"id\": \"compound_batch\",\n \"label\": \"Compound/batch operations\",\n \"type\": \"binary\",\n \"max\": 1,\n },\n ],\n },\n {\n \"id\": \"security_governance\",\n \"label\": \"Security & Governance\",\n \"max_points\": 15,\n \"default_weight\": 15,\n \"criteria\": [\n {\"id\": \"vuln_scanning\", \"label\": \"Vulnerability scanning\", \"type\": \"binary\", \"max\": 3},\n {\n \"id\": \"reachability_from_vulns\",\n \"label\": \"Reachability from vulns\",\n \"type\": \"binary\",\n \"max\": 3,\n },\n {\n \"id\": \"secret_detection\",\n \"label\": \"Secret detection\",\n \"type\": \"tiered\",\n \"max\": 3,\n \"tiers\": {\"none\": 0, \"regex\": 1, \"semantic\": 2, \"remediation\": 3},\n },\n {\n \"id\": \"quality_gates\",\n \"label\": \"Quality gates / policy rules\",\n \"type\": \"binary\",\n \"max\": 3,\n },\n {\n \"id\": \"rule_count\",\n \"label\": \"Rule count\",\n \"type\": \"tiered\",\n \"max\": 3,\n \"tiers\": [[0, 99, 0], [100, 999, 1], [1000, 4999, 2], [5000, None, 3]],\n },\n ],\n },\n {\n \"id\": \"ecosystem\",\n \"label\": \"Ecosystem & Accessibility\",\n \"max_points\": 19,\n \"default_weight\": 19,\n \"criteria\": [\n {\n \"id\": \"open_source\",\n \"label\": \"Open source\",\n \"type\": \"tiered\",\n \"max\": 2,\n \"tiers\": {\"full\": 2, \"partial\": 1, \"none\": 0},\n },\n {\"id\": \"free_tier\", \"label\": \"Free tier\", \"type\": \"binary\", \"max\": 2},\n {\n \"id\": \"zero_config_setup\",\n \"label\": \"Zero-config setup (install → insights)\",\n \"type\": \"tiered\",\n \"max\": 3,\n \"tiers\": {\"one_command\": 3, \"light_config\": 2, \"heavy_config\": 1, \"hosted_only\": 0},\n },\n {\"id\": \"ci_cd_integration\", \"label\": \"CI/CD integration\", \"type\": \"binary\", \"max\": 2},\n {\"id\": \"ide_integration\", \"label\": \"IDE integration\", \"type\": \"binary\", \"max\": 2},\n {\"id\": \"multi_platform\", \"label\": \"Multi-platform\", \"type\": \"binary\", \"max\": 1},\n {\n \"id\": \"documentation_quality\",\n \"label\": \"Documentation quality\",\n \"type\": \"subjective\",\n \"max\": 2,\n },\n {\n \"id\": \"active_maintenance\",\n \"label\": \"Active maintenance (90 days)\",\n \"type\": \"binary\",\n \"max\": 1,\n },\n {\"id\": \"sarif_output\", \"label\": \"SARIF output\", \"type\": \"binary\", \"max\": 2},\n {\n \"id\": \"local_zero_api\",\n \"label\": \"100% local / zero API keys\",\n \"type\": \"binary\",\n \"max\": 2,\n },\n ],\n },\n {\n \"id\": \"unique_capabilities\",\n \"label\": \"Unique Capabilities\",\n \"max_points\": 10,\n \"default_weight\": 10,\n \"criteria\": [\n {\n \"id\": \"multi_agent_partitioning\",\n \"label\": \"Multi-agent partitioning\",\n \"type\": \"binary\",\n \"max\": 1,\n },\n {\n \"id\": \"structural_pattern_matching\",\n \"label\": \"Structural pattern matching\",\n \"type\": \"binary\",\n \"max\": 3,\n },\n {\n \"id\": \"semantic_search\",\n \"label\": \"Embedding / semantic search\",\n \"type\": \"binary\",\n \"max\": 2,\n },\n {\n \"id\": \"multi_repo_federation\",\n \"label\": \"Multi-repo federation\",\n \"type\": \"binary\",\n \"max\": 3,\n },\n {\n \"id\": \"daemon_live_watch\",\n \"label\": \"Daemon / live-watch mode\",\n \"type\": \"binary\",\n \"max\": 1,\n },\n ],\n },\n]\n\ndef build_site_payload(tracker_path: Path | None = None) -> dict[str, object]:\n path = tracker_path or default_tracker_path()\n lines = path.read_text(encoding=\"utf-8\").splitlines()\n\n tracker_updated = \"\"\n for line in lines:\n if line.startswith(\"> Updated:\"):\n tracker_updated = line.split(\":\", 1)[1].strip()\n break\n if not tracker_updated:\n raise ValueError(\"Could not parse tracker update line ('> Updated: ...').\")\n\n tracker_updated_iso = _parse_tracker_updated_iso(tracker_updated)\n confidence_map = _parse_matrix_confidence(lines)\n competitors = _matrix_to_competitors(lines, confidence_map, tracker_updated_iso)\n _append_ckb_from_leaderboard(lines, competitors, confidence_map, tracker_updated_iso)\n _append_extra_competitors(competitors, tracker_updated_iso)\n\n # Filter to landscape-included tools only.\n competitors = [c for c in competitors if str(c[\"name\"]) in LANDSCAPE_INCLUDE]\n\n # Keep visual map stable: order by descending analysis depth, then agent readiness.\n competitors.sort(key=lambda c: (-int(c[\"arch\"]), -int(c[\"agent\"]), str(c[\"name\"])))\n\n # Keep roam-code row count fields synced to source-of-truth command/tool registration.\n try:\n from roam.surface_counts import collect_surface_counts\n\n surface = collect_surface_counts()\n cli_counts = surface.get(\"cli\", {})\n mcp_counts = surface.get(\"mcp\", {})\n canonical = int(cli_counts.get(\"canonical_commands\", 0) or 0)\n alias_count = int(cli_counts.get(\"alias_names\", 0) or 0)\n mcp_tools = int(mcp_counts.get(\"registered_tools\", 0) or 0)\n for entry in competitors:\n if entry.get(\"name\") != \"roam-code\":\n continue\n entry[\"mcp\"] = str(mcp_tools)\n if alias_count > 0:\n entry[\"cli_commands\"] = f\"{canonical} canonical (+{alias_count} alias)\"\n else:\n entry[\"cli_commands\"] = str(canonical)\n break\n except Exception:\n # Do not fail payload generation if local surface-count parsing fails.\n pass\n\n methodology = {\n \"scoring_model\": [\n \"45 criteria across 7 categories, scored as binary (has/doesn't), count-tiered, or subjective.\",\n \"Y-axis (Analysis Depth) = Static Analysis (50%) + Graph Intelligence (25%) + Git Temporal (25%).\",\n \"X-axis (Agent Readiness) = Agent Integration (70%) + Ecosystem (30%).\",\n \"Security and Unique Capabilities affect total score only, not map position.\",\n \"All criteria scored by project maintainers. 44/45 are binary or tiered (count-based or depth-based). 1/45 is subjective (documentation quality).\",\n \"Weight sliders let viewers apply their own category priorities.\",\n ],\n \"limitations\": [\n \"Criteria selection bias: we chose which capabilities to measure, favoring tools with graph algorithms.\",\n \"Category weight bias: default weights reflect our perspective. Adjust sliders for yours.\",\n \"Assessment bias: we scored all competitors. Errors or missed capabilities are possible.\",\n \"Public vendor claims can be stale or inconsistent across pages.\",\n \"GitHub star counts may conflate main product repos with MCP extension repos.\",\n ],\n \"reproducibility\": {\n \"tracker\": str(path.relative_to(_repo_root())).replace(\"\\\\\", \"/\"),\n \"generator\": \"src/roam/competitor_site_data.py\",\n \"generated_at_reference\": tracker_updated_iso,\n },\n }\n\n # Rubric metadata for the frontend (weight sliders + methodology rendering)\n rubric_out: list[dict[str, object]] = []\n for cat in SCORING_RUBRIC:\n rubric_out.append(\n {\n \"id\": cat[\"id\"],\n \"label\": cat[\"label\"],\n \"max_points\": cat[\"max_points\"],\n \"default_weight\": cat[\"default_weight\"],\n \"criteria\": [{k: v for k, v in crit.items()} for crit in cat[\"criteria\"]],\n }\n )\n\n return {\n \"tracker_updated\": tracker_updated,\n \"tracker_updated_iso\": tracker_updated_iso,\n \"tracker_file\": str(path.relative_to(_repo_root())).replace(\"\\\\\", \"/\"),\n \"competitors\": competitors,\n \"methodology\": methodology,\n \"rubric\": rubric_out,\n }", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 13559}, "tests/test_bus_factor.py::272": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_json_directories_bus_factor_positive", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_commands_workflow.py::44": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_preflight_user", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_auth_gaps.py::113": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_exits_zero_on_php_project", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_ci_gate_eval.py::88": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_unknown_metric_warns_but_does_not_fail", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_codeowners.py::28": {"resolved_imports": ["src/roam/commands/cmd_codeowners.py"], "used_names": ["parse_codeowners"], "enclosing_function": "test_simple_rules", "extracted_code": "# Source: src/roam/commands/cmd_codeowners.py\n _codeowners_match,\n find_codeowners,\n parse_codeowners,\n resolve_owners,\n)\nfrom roam.commands.resolve import ensure_index\nfrom roam.db.connection import find_project_root, open_db\nfrom roam.output.formatter import format_table, json_envelope, to_json\n\n# ---------------------------------------------------------------------------\n# Analysis helpers\n# ---------------------------------------------------------------------------\n\n return\n\n rules = parse_codeowners(co_path)\n co_relpath = str(co_path.relative_to(project_root)).replace(\"\\\\\", \"/\")\n\n with open_db(readonly=True) as conn:\n # Get all indexed files\n all_files = conn.execute(\"SELECT id, path FROM files ORDER BY path\").fetchall()\n\n if not all_files:\n if json_mode:\n click.echo(", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 858}, "tests/test_clones.py::275": {"resolved_imports": ["src/roam/cli.py"], "used_names": ["CliRunner", "cli", "os"], "enclosing_function": "test_top_flag", "extracted_code": "# Source: src/roam/cli.py\ndef cli(ctx, json_mode, compact, agent, sarif_mode, budget, include_excluded, detail):\n \"\"\"Roam: Codebase comprehension tool.\"\"\"\n if agent and sarif_mode:\n raise click.UsageError(\"--agent cannot be combined with --sarif\")\n\n # Agent mode is optimized for CLI-invoked sub-agents:\n # - forces JSON for machine parsing\n # - uses compact envelope to reduce token overhead\n # - defaults to 500-token budget unless user overrides with --budget\n if agent:\n json_mode = True\n compact = True\n if budget <= 0:\n budget = 500\n\n ctx.ensure_object(dict)\n ctx.obj[\"json\"] = json_mode\n ctx.obj[\"compact\"] = compact\n ctx.obj[\"agent\"] = agent\n ctx.obj[\"sarif\"] = sarif_mode\n ctx.obj[\"budget\"] = budget\n ctx.obj[\"include_excluded\"] = include_excluded\n ctx.obj[\"detail\"] = detail", "n_imports_parsed": 8, "n_files_resolved": 1, "n_chars_extracted": 868}, "tests/test_fn_coupling.py::77": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_verdict_line", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_properties.py::277": {"resolved_imports": ["src/roam/db/connection.py", "src/roam/graph/simulate.py", "src/roam/output/formatter.py"], "used_names": ["batched_in"], "enclosing_function": "test_all_ids_returns_all", "extracted_code": "# Source: src/roam/db/connection.py\ndef batched_in(conn, sql, ids, *, pre=(), post=(), batch_size=_BATCH_SIZE):\n \"\"\"Execute *sql* with ``{ph}`` placeholder(s) in batches.\n\n Handles single and double IN-clauses automatically::\n\n # Single IN\n batched_in(conn, \"SELECT * FROM t WHERE id IN ({ph})\", ids)\n\n # Double IN (same set)\n batched_in(conn, \"... WHERE src IN ({ph}) AND tgt IN ({ph})\", ids)\n\n # Extra params before / after\n batched_in(conn, \"... WHERE kind=? AND id IN ({ph})\", ids, pre=[kind])\n\n Returns a flat list of all rows across batches.\n \"\"\"\n if not ids:\n return []\n ids = list(ids)\n n_ph = sql.count(\"{ph}\")\n chunk = max(1, batch_size // max(n_ph, 1))\n\n rows = []\n for i in range(0, len(ids), chunk):\n batch = ids[i : i + chunk]\n ph = \",\".join(\"?\" for _ in batch)\n q = sql.replace(\"{ph}\", ph)\n params = list(pre) + batch * n_ph + list(post)\n rows.extend(conn.execute(q, params).fetchall())\n return rows", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 1031}, "tests/test_affected.py::136": {"resolved_imports": ["src/roam/cli.py"], "used_names": ["invoke_cli"], "enclosing_function": "test_affected_shows_changed_files", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_dataflow_dead.py::110": {"resolved_imports": ["src/roam/commands/cmd_dead.py", "src/roam/db/schema.py"], "used_names": ["_analyze_dataflow_dead", "sqlite3"], "enclosing_function": "test_returns_empty_when_no_taint_table", "extracted_code": "# Source: src/roam/commands/cmd_dead.py\ndef _analyze_dataflow_dead(conn):\n \"\"\"Analyze dataflow-based dead code patterns using taint summaries.\n\n Returns list of findings: [{type, symbol, file, line, reason, confidence, call_sites}]\n \"\"\"\n findings = []\n project_root = find_project_root()\n\n # Check if required tables exist\n try:\n conn.execute(\"SELECT 1 FROM taint_summaries LIMIT 0\")\n except Exception:\n return findings\n\n has_effects = True\n try:\n conn.execute(\"SELECT 1 FROM symbol_effects LIMIT 0\")\n except Exception:\n has_effects = False\n\n has_metrics = True\n try:\n conn.execute(\"SELECT 1 FROM symbol_metrics LIMIT 0\")\n except Exception:\n has_metrics = False\n\n # A. Unused Return Values\n if has_metrics:\n funcs_with_return = conn.execute(\n \"SELECT s.id, s.name, COALESCE(s.qualified_name, s.name) AS qname, \"\n \"f.path AS file_path, s.line_start, sm.return_count \"\n \"FROM symbols s \"\n \"JOIN files f ON s.file_id = f.id \"\n \"JOIN symbol_metrics sm ON s.id = sm.symbol_id \"\n \"WHERE sm.return_count > 0 \"\n \" AND s.kind IN ('function', 'method')\"\n ).fetchall()\n\n file_cache: dict[str, list[str]] = {}\n\n for func in funcs_with_return:\n # Get all callers (edges pointing to this function)\n callers = conn.execute(\n \"SELECT e.source_id, e.line, s.name AS caller_name, \"\n \"f.path AS caller_file, s.line_start AS caller_start \"\n \"FROM edges e \"\n \"JOIN symbols s ON e.source_id = s.id \"\n \"JOIN files f ON s.file_id = f.id \"\n \"WHERE e.target_id = ? AND e.kind = 'calls'\",\n (func[\"id\"],),\n ).fetchall()\n\n if not callers:\n continue\n\n # Check each call site\n all_discard = True\n call_site_info = []\n for caller in callers:\n call_line = caller[\"line\"]\n if not call_line:\n all_discard = False\n break\n caller_file = caller[\"caller_file\"]\n if caller_file not in file_cache:\n try:\n fpath = project_root / caller_file\n file_cache[caller_file] = fpath.read_text(encoding=\"utf-8\", errors=\"replace\").splitlines()\n except Exception:\n file_cache[caller_file] = []\n lines = file_cache.get(caller_file, [])\n if call_line <= len(lines):\n line_text = lines[call_line - 1].strip()\n # Check if return value is captured (= before function name, but not == or !=)\n prefix = line_text.split(func[\"name\"])[0] if func[\"name\"] in line_text else \"\"\n if re.search(r\"[A-Za-z_]\\w*\\s*=(?!=)\", prefix):\n all_discard = False\n break\n call_site_info.append({\"file\": caller_file, \"line\": call_line, \"caller\": caller[\"caller_name\"]})\n else:\n all_discard = False\n break\n\n if all_discard and callers:\n findings.append(\n {\n \"type\": \"unused_return\",\n \"symbol\": func[\"qname\"],\n \"file\": func[\"file_path\"],\n \"line\": func[\"line_start\"],\n \"reason\": (f\"return value of {func['qname']} is discarded by all {len(callers)} caller(s)\"),\n \"confidence\": 85,\n \"call_sites\": call_site_info[:5],\n }\n )\n\n # B. Dead Parameter Chains\n param_rows = conn.execute(\n \"SELECT ts.symbol_id, ts.param_taints_return, ts.param_to_sink, \"\n \"s.name, COALESCE(s.qualified_name, s.name) AS qname, \"\n \"s.signature, f.path AS file_path, s.line_start \"\n \"FROM taint_summaries ts \"\n \"JOIN symbols s ON ts.symbol_id = s.id \"\n \"JOIN files f ON s.file_id = f.id \"\n \"WHERE ts.is_sanitizer = 0 \"\n \" AND s.kind IN ('function', 'method')\"\n ).fetchall()\n\n for row in param_rows:\n try:\n ptr = json.loads(row[\"param_taints_return\"] or \"{}\")\n pts = json.loads(row[\"param_to_sink\"] or \"{}\")\n except Exception:\n continue\n\n # Parse param names from signature\n sig = row[\"signature\"] or \"\"\n m = re.search(r\"\\(([^)]*)\\)\", sig)\n if not m:\n continue\n params_str = m.group(1).strip()\n if not params_str:\n continue\n param_names = []\n for part in params_str.split(\",\"):\n token = part.strip().split(\":\")[0].split(\"=\")[0].strip()\n while token.startswith(\"*\"):\n token = token[1:]\n if token and token not in (\"self\", \"cls\", \"_\"):\n param_names.append(token)\n\n for idx, pname in enumerate(param_names):\n sidx = str(idx)\n has_return_effect = ptr.get(sidx, False)\n has_sink_effect = bool(pts.get(sidx))\n if not has_return_effect and not has_sink_effect:\n findings.append(\n {\n \"type\": \"dead_param_chain\",\n \"symbol\": row[\"qname\"],\n \"file\": row[\"file_path\"],\n \"line\": row[\"line_start\"],\n \"variable\": pname,\n \"reason\": (\n f\"parameter '{pname}' of {row['qname']} has no dataflow effect \"\n f\"(not returned, not used in sink)\"\n ),\n \"confidence\": 75,\n \"call_sites\": [],\n }\n )\n\n # C. Side-Effect-Only Functions\n if has_effects:\n # Find functions where all callers discard return AND effects are only logging/pure\n for f in findings:\n if f[\"type\"] != \"unused_return\":\n continue\n sym_id_row = conn.execute(\n \"SELECT id FROM symbols WHERE qualified_name = ? OR name = ? LIMIT 1\",\n (f[\"symbol\"], f[\"symbol\"]),\n ).fetchone()\n if not sym_id_row:\n continue\n sym_id = sym_id_row[\"id\"]\n effects = conn.execute(\n \"SELECT DISTINCT effect_type FROM symbol_effects WHERE symbol_id = ?\",\n (sym_id,),\n ).fetchall()\n effect_types = {e[\"effect_type\"] for e in effects}\n benign = {\"pure\", \"logging\"}\n if effect_types and effect_types <= benign:\n findings.append(\n {\n \"type\": \"side_effect_only\",\n \"symbol\": f[\"symbol\"],\n \"file\": f[\"file\"],\n \"line\": f[\"line\"],\n \"reason\": (\n f\"{f['symbol']} has only {'/'.join(sorted(effect_types))} effects \"\n f\"and return is always discarded\"\n ),\n \"confidence\": 70,\n \"call_sites\": f.get(\"call_sites\", []),\n }\n )\n\n findings.sort(key=lambda f: (-f[\"confidence\"], f[\"file\"], f.get(\"line\") or 0))\n return findings", "n_imports_parsed": 10, "n_files_resolved": 2, "n_chars_extracted": 7542}, "tests/test_entry_points_cmd.py::208": {"resolved_imports": [], "used_names": ["invoke_cli", "parse_json_output"], "enclosing_function": "test_json_entry_point_fields", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_ci_sarif_guard.py::94": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_apply_guardrails_size_cap_truncates", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_ai_readiness.py::242": {"resolved_imports": [], "used_names": ["json"], "enclosing_function": "test_json_dimensions_array", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_pagerank_truncation.py::120": {"resolved_imports": ["src/roam/output/formatter.py"], "used_names": ["_sort_by_importance"], "enclosing_function": "test_priority_pagerank_over_score", "extracted_code": "# Source: src/roam/output/formatter.py\ndef _sort_by_importance(items: list) -> tuple[list, bool]:\n \"\"\"Sort list items by importance descending if they carry an importance key.\n\n Returns ``(sorted_list, was_sorted)``. When no recognised importance\n key is found in the first dict item, the original order is preserved\n and ``was_sorted`` is ``False``.\n \"\"\"\n if not items:\n return items, False\n\n # Only attempt importance-sorting on lists of dicts\n first = items[0]\n if not isinstance(first, dict):\n return items, False\n\n # Find the importance key present in items\n imp_key: str | None = None\n for candidate in _IMPORTANCE_KEYS:\n if candidate in first:\n imp_key = candidate\n break\n\n if imp_key is None:\n return items, False\n\n # Sort descending by importance (highest first → kept on truncation)\n try:\n sorted_items = sorted(\n items,\n key=lambda d: d.get(imp_key, 0) if isinstance(d, dict) else 0,\n reverse=True,\n )\n return sorted_items, True\n except (TypeError, ValueError):\n return items, False", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1153}, "tests/test_commands_workflow.py::334": {"resolved_imports": [], "used_names": ["assert_json_envelope", "invoke_cli", "parse_json_output"], "enclosing_function": "test_context_json", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_partition.py::252": {"resolved_imports": ["src/roam/commands/cmd_partition.py", "src/roam/db/connection.py"], "used_names": ["compute_partition_manifest", "open_db", "os"], "enclosing_function": "test_conflict_hotspots_structure", "extracted_code": "# Source: src/roam/commands/cmd_partition.py\ndef compute_partition_manifest(\n conn: sqlite3.Connection,\n n_agents: int | None = None,\n) -> dict:\n \"\"\"Build a detailed partition manifest from the symbol graph.\n\n Parameters\n ----------\n conn:\n Open (readonly) connection to the roam index DB.\n n_agents:\n Number of agents. ``None`` means auto-detect from cluster count.\n\n Returns\n -------\n dict with keys: partitions, dependencies, conflict_hotspots,\n overall_conflict_probability, verdict.\n \"\"\"\n from roam.graph.builder import build_symbol_graph\n from roam.graph.clusters import detect_clusters\n from roam.graph.partition import (\n _adjust_cluster_count,\n compute_conflict_probability,\n compute_merge_order,\n )\n\n G = build_symbol_graph(conn)\n if len(G) == 0:\n return _empty_manifest(n_agents or 2)\n\n # -- 1. Detect communities -----------------------------------------------\n cluster_map = detect_clusters(G)\n if not cluster_map:\n cluster_map = {n: 0 for n in G.nodes}\n\n groups: dict[int, set[int]] = defaultdict(set)\n for node_id, cid in cluster_map.items():\n groups[cid].add(node_id)\n\n # Auto-detect agent count from natural cluster count\n if n_agents is None:\n n_agents = max(2, len(groups))\n\n partitions = _adjust_cluster_count(G, groups, n_agents)\n\n # -- 2. Gather node metadata in bulk -------------------------------------\n all_node_ids = list(set().union(*(p[\"nodes\"] for p in partitions)))\n node_meta: dict[int, dict] = {}\n if all_node_ids:\n rows = batched_in(\n conn,\n \"SELECT s.id, s.name, s.kind, s.qualified_name, f.path, f.language, \"\n \"f.file_role, COALESCE(gm.pagerank, 0) AS pagerank, \"\n \"COALESCE(sm.cognitive_complexity, 0) AS complexity \"\n \"FROM symbols s \"\n \"JOIN files f ON s.file_id = f.id \"\n \"LEFT JOIN graph_metrics gm ON s.id = gm.symbol_id \"\n \"LEFT JOIN symbol_metrics sm ON s.id = sm.symbol_id \"\n \"WHERE s.id IN ({ph})\",\n all_node_ids,\n )\n for r in rows:\n node_meta[r[\"id\"]] = {\n \"name\": r[\"name\"],\n \"kind\": r[\"kind\"],\n \"qualified_name\": r[\"qualified_name\"],\n \"path\": r[\"path\"].replace(\"\\\\\", \"/\"),\n \"language\": r[\"language\"],\n \"file_role\": r[\"file_role\"],\n \"pagerank\": r[\"pagerank\"],\n \"complexity\": r[\"complexity\"],\n }\n\n # -- 3. Build node → partition index -------------------------------------\n node_part: dict[int, int] = {}\n for idx, p in enumerate(partitions):\n for n in p[\"nodes\"]:\n node_part[n] = idx\n\n # -- 4. Co-change data for conflict analysis -----------------------------\n # Build file_path → file_id mapping\n file_path_to_id: dict[str, int] = {}\n file_rows = conn.execute(\"SELECT id, path FROM files\").fetchall()\n for fr in file_rows:\n file_path_to_id[fr[\"path\"].replace(\"\\\\\", \"/\")] = fr[\"id\"]\n\n cochange_map: dict[tuple[int, int], int] = {}\n cochange_rows = conn.execute(\"SELECT file_id_a, file_id_b, cochange_count FROM git_cochange\").fetchall()\n for cr in cochange_rows:\n cochange_map[(cr[\"file_id_a\"], cr[\"file_id_b\"])] = cr[\"cochange_count\"]\n cochange_map[(cr[\"file_id_b\"], cr[\"file_id_a\"])] = cr[\"cochange_count\"]\n\n # -- 5. Build per-partition descriptors ----------------------------------\n result_partitions = []\n all_partition_files: list[set[str]] = []\n\n for idx, p in enumerate(partitions):\n nodes = p[\"nodes\"]\n files_set: set[str] = set()\n language_counter: Counter = Counter()\n total_complexity = 0.0\n test_file_count = 0\n symbols_with_tests = 0\n key_symbols = []\n\n for n in nodes:\n meta = node_meta.get(n)\n if not meta:\n continue\n files_set.add(meta[\"path\"])\n if meta[\"language\"]:\n lang_label = _EXTENSION_ROLES.get(\n \".\" + (meta[\"language\"] or \"\").lower().split(\"/\")[-1],\n meta[\"language\"],\n )\n language_counter[lang_label] += 1\n total_complexity += meta[\"complexity\"]\n if meta[\"file_role\"] == \"test\":\n test_file_count += 1\n\n # Key symbols: top-5 by PageRank\n ranked_nodes = sorted(\n [n for n in nodes if n in node_meta],\n key=lambda n: node_meta[n][\"pagerank\"],\n reverse=True,\n )\n for n in ranked_nodes[:5]:\n m = node_meta[n]\n key_symbols.append(\n {\n \"name\": m[\"name\"],\n \"kind\": abbrev_kind(m[\"kind\"]),\n \"pagerank\": round(m[\"pagerank\"], 4),\n \"file\": m[\"path\"],\n }\n )\n\n # Test coverage: ratio of symbols that have a test-role file in this partition\n # or whose name appears in a test file within the partition\n total_source_symbols = sum(1 for n in nodes if n in node_meta and node_meta[n][\"file_role\"] != \"test\")\n test_names = set()\n for n in nodes:\n meta = node_meta.get(n)\n if meta and meta[\"file_role\"] == \"test\":\n test_names.add(meta[\"name\"].lower())\n\n if total_source_symbols > 0 and test_names:\n for n in nodes:\n meta = node_meta.get(n)\n if meta and meta[\"file_role\"] != \"test\":\n # Check if any test symbol references this name\n if meta[\"name\"].lower() in test_names:\n symbols_with_tests += 1\n elif f\"test_{meta['name'].lower()}\" in test_names:\n symbols_with_tests += 1\n\n test_coverage = round(symbols_with_tests / total_source_symbols, 2) if total_source_symbols > 0 else 0.0\n\n # Cross-partition edge count for this partition\n cross_edges = 0\n for n in nodes:\n for succ in G.successors(n):\n if succ in node_part and node_part[succ] != idx:\n cross_edges += 1\n for pred in G.predecessors(n):\n if pred in node_part and node_part[pred] != idx:\n cross_edges += 1\n\n # Co-change conflict score: files in this partition that co-change\n # with files in OTHER partitions\n cochange_score = 0\n partition_file_ids = {file_path_to_id[f] for f in files_set if f in file_path_to_id}\n # Iterate known cochange pairs\n for (fid_a, fid_b), count in cochange_map.items():\n if fid_a in partition_file_ids and fid_b not in partition_file_ids:\n cochange_score += count\n\n # Conflict risk label\n if cross_edges <= 3 and cochange_score <= 2:\n conflict_risk = \"LOW\"\n elif cross_edges <= 10 or cochange_score <= 5:\n conflict_risk = \"MEDIUM\"\n else:\n conflict_risk = \"HIGH\"\n\n # Per-partition churn: sum of churn across files in this partition\n partition_churn = 0\n if partition_file_ids:\n for pfid in partition_file_ids:\n try:\n churn_row = conn.execute(\n \"SELECT total_churn FROM file_stats WHERE file_id = ?\",\n (pfid,),\n ).fetchone()\n if churn_row and churn_row[\"total_churn\"]:\n partition_churn += churn_row[\"total_churn\"]\n except Exception:\n pass\n\n # Suggest role\n role = _suggest_role(sorted(files_set), language_counter)\n\n # Cluster label from directory majority\n dirs = [os.path.dirname(f).replace(\"\\\\\", \"/\") for f in files_set if f]\n dir_counts = Counter(dirs) if dirs else Counter()\n if dir_counts:\n label = dir_counts.most_common(1)[0][0]\n label = label.rstrip(\"/\").rsplit(\"/\", 1)[-1] if label else f\"partition-{idx + 1}\"\n if not label:\n label = f\"root-{idx + 1}\"\n else:\n label = f\"partition-{idx + 1}\"\n\n all_partition_files.append(files_set)\n\n result_partitions.append(\n {\n \"id\": idx + 1,\n \"label\": label,\n \"role\": role,\n \"files\": sorted(files_set),\n \"file_count\": len(files_set),\n \"symbol_count\": len(nodes),\n \"key_symbols\": key_symbols,\n \"complexity\": round(total_complexity, 1),\n \"churn\": partition_churn,\n \"test_coverage\": test_coverage,\n \"conflict_risk\": conflict_risk,\n \"cross_partition_edges\": cross_edges,\n \"cochange_score\": cochange_score,\n }\n )\n\n # -- 6. Balance partitions by complexity → assign to agents ---------------\n # Sort partitions by complexity descending, assign round-robin to balance\n sorted_parts = sorted(\n range(len(result_partitions)),\n key=lambda i: result_partitions[i][\"complexity\"],\n reverse=True,\n )\n agent_loads = [0.0] * n_agents\n for pi in sorted_parts:\n # Assign to the agent with the least load\n min_agent = min(range(n_agents), key=lambda a: agent_loads[a])\n result_partitions[pi][\"agent\"] = f\"Worker-{min_agent + 1}\"\n agent_loads[min_agent] += result_partitions[pi][\"complexity\"]\n\n # -- 6b. Compute composite difficulty scores ------------------------------\n compute_difficulty_score(result_partitions)\n\n # -- 7. Cross-partition dependencies -------------------------------------\n dep_counter: dict[tuple[int, int], list[str]] = defaultdict(list)\n for u, v in G.edges:\n pu = node_part.get(u)\n pv = node_part.get(v)\n if pu is not None and pv is not None and pu != pv:\n u_meta = node_meta.get(u, {})\n v_meta = node_meta.get(v, {})\n u_file = u_meta.get(\"path\", \"?\")\n v_file = v_meta.get(\"path\", \"?\")\n edge_desc = f\"{u_file} -> {v_file}\"\n dep_counter[(pu + 1, pv + 1)].append(edge_desc)\n\n dependencies = []\n for (from_id, to_id), edge_descs in sorted(dep_counter.items()):\n # Find shared files\n shared = all_partition_files[from_id - 1] & all_partition_files[to_id - 1]\n dependencies.append(\n {\n \"from\": from_id,\n \"to\": to_id,\n \"edge_count\": len(edge_descs),\n \"sample_edges\": edge_descs[:5],\n \"shared_files\": sorted(shared),\n }\n )\n\n # -- 8. Conflict hotspots ------------------------------------------------\n # Files referenced by symbols in multiple partitions\n file_partitions: dict[str, set[int]] = defaultdict(set)\n for n, pidx in node_part.items():\n meta = node_meta.get(n)\n if meta:\n file_partitions[meta[\"path\"]].add(pidx + 1)\n\n conflict_hotspots = []\n for fpath, part_ids in sorted(file_partitions.items()):\n if len(part_ids) >= 2:\n conflict_hotspots.append(\n {\n \"file\": fpath,\n \"partition_count\": len(part_ids),\n \"partitions\": sorted(part_ids),\n }\n )\n conflict_hotspots.sort(key=lambda h: -h[\"partition_count\"])\n conflict_hotspots = conflict_hotspots[:20] # cap\n\n # -- 9. Overall conflict probability -------------------------------------\n overall_cp = compute_conflict_probability(G, partitions)\n\n # -- 10. Merge order -----------------------------------------------------\n merge_order = compute_merge_order(G, partitions)\n\n verdict = (\n f\"{len(result_partitions)} partitions for {n_agents} agents, conflict probability {int(overall_cp * 100)}%\"\n )\n\n return {\n \"verdict\": verdict,\n \"total_partitions\": len(result_partitions),\n \"n_agents\": n_agents,\n \"overall_conflict_probability\": round(overall_cp, 4),\n \"merge_order\": merge_order,\n \"partitions\": result_partitions,\n \"dependencies\": dependencies,\n \"conflict_hotspots\": conflict_hotspots,\n }\n\n\n# Source: src/roam/db/connection.py\ndef open_db(readonly: bool = False, project_root: Path | None = None):\n \"\"\"Context manager for database access. Creates schema if needed.\n\n Raises a descriptive ``click.ClickException`` if the database file is\n missing or corrupted so that agents receive actionable remediation steps\n instead of a raw SQLite traceback.\n \"\"\"\n import click\n\n db_path = get_db_path(project_root)\n try:\n conn = get_connection(db_path, readonly=readonly)\n except sqlite3.DatabaseError as exc:\n raise click.ClickException(\n f\"Database error: {exc}\\n\"\n \" The roam index may be corrupted. Run `roam init --force` to rebuild it\\n\"\n \" from scratch, or delete .roam/index.db and run `roam init`.\"\n ) from exc\n try:\n if not readonly:\n try:\n ensure_schema(conn)\n except sqlite3.DatabaseError as exc:\n conn.close()\n raise click.ClickException(\n f\"Database schema error: {exc}\\n\"\n \" The roam index may be corrupted or from an incompatible version.\\n\"\n \" Run `roam init --force` to rebuild it, or delete .roam/index.db\\n\"\n \" and run `roam init`.\"\n ) from exc\n yield conn\n if not readonly:\n conn.commit()\n finally:\n conn.close()", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 13772}, "tests/test_ci_gate_eval.py::26": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_scalar_gate_pass", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_congestion.py::53": {"resolved_imports": [], "used_names": ["invoke_cli"], "enclosing_function": "test_exits_zero", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_batch_mcp.py::270": {"resolved_imports": [], "used_names": ["_batch_search_one"], "enclosing_function": "test_limit_respected", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_secrets.py::370": {"resolved_imports": [], "used_names": ["json"], "enclosing_function": "test_json_finding_fields", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_ai_readiness.py::240": {"resolved_imports": [], "used_names": ["json"], "enclosing_function": "test_json_dimensions_array", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}}}