@deftai/directive-content 0.55.2 → 0.56.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/.githooks/pre-commit +143 -0
  2. package/.githooks/pre-push +121 -0
  3. package/QUICK-START.md +2 -2
  4. package/Taskfile.yml +934 -0
  5. package/UPGRADING.md +47 -1
  6. package/events/README.md +3 -3
  7. package/package.json +5 -4
  8. package/scripts/_agents_md.py +494 -0
  9. package/scripts/_cache_fetch.py +635 -0
  10. package/scripts/_cache_quota.py +529 -0
  11. package/scripts/_cache_refresh.py +163 -0
  12. package/scripts/_cache_validate.py +209 -0
  13. package/scripts/_content_root.py +42 -0
  14. package/scripts/_doctor_state.py +277 -0
  15. package/scripts/_event_detect.py +305 -0
  16. package/scripts/_events.py +514 -0
  17. package/scripts/_lifecycle_hygiene.py +568 -0
  18. package/scripts/_pathspec.py +91 -0
  19. package/scripts/_policy_show_cli.py +266 -0
  20. package/scripts/_precutover.py +92 -0
  21. package/scripts/_project_context.py +224 -0
  22. package/scripts/_project_definition_io.py +164 -0
  23. package/scripts/_relocate_snapshot.py +209 -0
  24. package/scripts/_relocate_states.py +343 -0
  25. package/scripts/_resolve_preflight_path.py +152 -0
  26. package/scripts/_safe_subprocess.py +167 -0
  27. package/scripts/_session_start_hook.py +205 -0
  28. package/scripts/_sor_gate_diff.py +365 -0
  29. package/scripts/_stdio_utf8.py +59 -0
  30. package/scripts/_triage_bootstrap_gitignore.py +904 -0
  31. package/scripts/_triage_classify_cli.py +122 -0
  32. package/scripts/_triage_queue_cli.py +625 -0
  33. package/scripts/_triage_scope_cli.py +343 -0
  34. package/scripts/_triage_scope_drift_cli.py +121 -0
  35. package/scripts/_triage_scope_ignores.py +286 -0
  36. package/scripts/_triage_scope_milestone.py +432 -0
  37. package/scripts/_triage_scope_mutations.py +337 -0
  38. package/scripts/_triage_scope_renderers.py +207 -0
  39. package/scripts/_triage_smoketest_stages.py +674 -0
  40. package/scripts/_triage_subscribe_cli.py +140 -0
  41. package/scripts/_triage_welcome_cli.py +421 -0
  42. package/scripts/_vbrief_build.py +239 -0
  43. package/scripts/_vbrief_fidelity.py +479 -0
  44. package/scripts/_vbrief_legacy.py +589 -0
  45. package/scripts/_vbrief_reconciliation.py +883 -0
  46. package/scripts/_vbrief_routing.py +277 -0
  47. package/scripts/_vbrief_safety.py +778 -0
  48. package/scripts/_vbrief_sources.py +312 -0
  49. package/scripts/_vbrief_speckit.py +262 -0
  50. package/scripts/_vbrief_story_quality.py +353 -0
  51. package/scripts/_vbrief_validation.py +299 -0
  52. package/scripts/build_dist.py +412 -0
  53. package/scripts/cache.py +1078 -0
  54. package/scripts/cache_scanner.py +745 -0
  55. package/scripts/candidates_log.py +432 -0
  56. package/scripts/capacity_backfill.py +680 -0
  57. package/scripts/capacity_show.py +653 -0
  58. package/scripts/ci_local.py +689 -0
  59. package/scripts/code_structure_validate.py +765 -0
  60. package/scripts/codebase_default_extractor.py +495 -0
  61. package/scripts/codebase_map.py +304 -0
  62. package/scripts/codebase_map_fresh.py +104 -0
  63. package/scripts/codebase_projection_registry.py +94 -0
  64. package/scripts/codebase_provider.py +582 -0
  65. package/scripts/doctor.py +2257 -0
  66. package/scripts/framework_commands.py +505 -0
  67. package/scripts/gh_rest.py +882 -0
  68. package/scripts/github_auth_modes.py +437 -0
  69. package/scripts/github_body.py +292 -0
  70. package/scripts/ip_risk.py +531 -0
  71. package/scripts/issue_emit.py +670 -0
  72. package/scripts/issue_ingest.py +1064 -0
  73. package/scripts/migrate_preflight.py +418 -0
  74. package/scripts/migrate_vbrief.py +2677 -0
  75. package/scripts/monitor_pr.py +401 -0
  76. package/scripts/pack_migrate_lessons.py +336 -0
  77. package/scripts/pack_migrate_patterns.py +254 -0
  78. package/scripts/pack_migrate_rules.py +350 -0
  79. package/scripts/pack_migrate_skills.py +423 -0
  80. package/scripts/pack_migrate_strategies.py +311 -0
  81. package/scripts/pack_migrate_swarm_spec.py +250 -0
  82. package/scripts/pack_render.py +434 -0
  83. package/scripts/packs_slice.py +712 -0
  84. package/scripts/platform_capabilities.py +336 -0
  85. package/scripts/policy.py +2826 -0
  86. package/scripts/policy_set.py +324 -0
  87. package/scripts/pr_check_closing_keywords.py +524 -0
  88. package/scripts/pr_check_protected_issues.py +267 -0
  89. package/scripts/pr_merge_readiness.py +1004 -0
  90. package/scripts/pr_wait_mergeable.py +669 -0
  91. package/scripts/prd_render.py +159 -0
  92. package/scripts/preflight_architecture_sor.py +974 -0
  93. package/scripts/preflight_branch.py +289 -0
  94. package/scripts/preflight_cache.py +974 -0
  95. package/scripts/preflight_gh.py +721 -0
  96. package/scripts/preflight_implementation.py +272 -0
  97. package/scripts/preflight_story_start.py +838 -0
  98. package/scripts/preflight_wip_cap.py +149 -0
  99. package/scripts/probe_session.py +545 -0
  100. package/scripts/project_render.py +293 -0
  101. package/scripts/quarantine_ext.py +237 -0
  102. package/scripts/reconcile_issues.py +1442 -0
  103. package/scripts/refresh-path.ps1 +107 -0
  104. package/scripts/release.py +2030 -0
  105. package/scripts/release_e2e.py +1011 -0
  106. package/scripts/release_publish.py +486 -0
  107. package/scripts/release_rollback.py +980 -0
  108. package/scripts/relocate.py +1034 -0
  109. package/scripts/resolve_changelog_unreleased.py +667 -0
  110. package/scripts/resolve_version.py +490 -0
  111. package/scripts/resume_conditions.py +706 -0
  112. package/scripts/ritual_sentinel.py +609 -0
  113. package/scripts/roadmap_render.py +635 -0
  114. package/scripts/rule_ownership_lint.py +325 -0
  115. package/scripts/scm.py +591 -0
  116. package/scripts/scope_audit_log.py +387 -0
  117. package/scripts/scope_decompose.py +654 -0
  118. package/scripts/scope_demote.py +509 -0
  119. package/scripts/scope_lifecycle.py +1126 -0
  120. package/scripts/scope_undo.py +772 -0
  121. package/scripts/session_start.py +406 -0
  122. package/scripts/setup_ghx.py +339 -0
  123. package/scripts/setup_windows.ps1 +220 -0
  124. package/scripts/slice_audit.py +585 -0
  125. package/scripts/slice_record.py +530 -0
  126. package/scripts/slice_record_existing.py +692 -0
  127. package/scripts/slug_normalize.py +178 -0
  128. package/scripts/spec_render.py +477 -0
  129. package/scripts/spec_validate.py +238 -0
  130. package/scripts/subagent_monitor.py +658 -0
  131. package/scripts/swarm_complete_cohort.py +644 -0
  132. package/scripts/swarm_launch.py +1206 -0
  133. package/scripts/swarm_readiness.py +554 -0
  134. package/scripts/swarm_verify_review_clean.py +438 -0
  135. package/scripts/swarm_worktrees.py +497 -0
  136. package/scripts/toolchain-check.py +52 -0
  137. package/scripts/triage_actions.py +871 -0
  138. package/scripts/triage_bootstrap.py +1153 -0
  139. package/scripts/triage_bulk.py +630 -0
  140. package/scripts/triage_classify.py +932 -0
  141. package/scripts/triage_help.py +1685 -0
  142. package/scripts/triage_queue.py +1944 -0
  143. package/scripts/triage_reconcile.py +581 -0
  144. package/scripts/triage_refresh.py +643 -0
  145. package/scripts/triage_scope.py +999 -0
  146. package/scripts/triage_scope_drift.py +575 -0
  147. package/scripts/triage_smoketest.py +396 -0
  148. package/scripts/triage_subscribe.py +399 -0
  149. package/scripts/triage_summary.py +1011 -0
  150. package/scripts/triage_welcome.py +1178 -0
  151. package/scripts/ts_check_lane.py +86 -0
  152. package/scripts/validate-links.py +64 -0
  153. package/scripts/validate_strategy_output.py +212 -0
  154. package/scripts/vbrief_activate.py +228 -0
  155. package/scripts/vbrief_migrate_conformance.py +368 -0
  156. package/scripts/vbrief_reconcile_graph.py +306 -0
  157. package/scripts/vbrief_reconcile_labels.py +460 -0
  158. package/scripts/vbrief_reconcile_umbrellas.py +741 -0
  159. package/scripts/vbrief_validate.py +1195 -0
  160. package/scripts/verify-stubs.py +61 -0
  161. package/scripts/verify_capacity.py +160 -0
  162. package/scripts/verify_encoding.py +699 -0
  163. package/scripts/verify_hooks_installed.py +206 -0
  164. package/scripts/verify_investigation.py +360 -0
  165. package/scripts/verify_judgment_gates.py +827 -0
  166. package/scripts/verify_no_task_runtime.py +171 -0
  167. package/scripts/verify_scm_boundary.py +509 -0
  168. package/scripts/verify_session_ritual.py +389 -0
  169. package/scripts/verify_tools.py +426 -0
  170. package/scripts/verify_vbrief_conformance.py +478 -0
  171. package/tasks/architecture.yml +13 -0
  172. package/tasks/cache.yml +69 -0
  173. package/tasks/capacity.yml +38 -0
  174. package/tasks/change.yml +46 -0
  175. package/tasks/changelog.yml +24 -0
  176. package/tasks/ci.yml +49 -0
  177. package/tasks/codebase.yml +47 -0
  178. package/tasks/commit.yml +30 -0
  179. package/tasks/core.yml +126 -0
  180. package/tasks/deployments.yml +54 -0
  181. package/tasks/framework.yml +74 -0
  182. package/tasks/install.yml +60 -0
  183. package/tasks/issue.yml +50 -0
  184. package/tasks/migrate.yml +73 -0
  185. package/tasks/packs.yml +92 -0
  186. package/tasks/policy.yml +75 -0
  187. package/tasks/pr.yml +89 -0
  188. package/tasks/prd.yml +39 -0
  189. package/tasks/project.yml +27 -0
  190. package/tasks/reconcile.yml +32 -0
  191. package/tasks/relocate.yml +56 -0
  192. package/tasks/roadmap.yml +28 -0
  193. package/tasks/scm.yml +126 -0
  194. package/tasks/scope-undo.yml +36 -0
  195. package/tasks/scope.yml +141 -0
  196. package/tasks/session.yml +19 -0
  197. package/tasks/setup.yml +37 -0
  198. package/tasks/slice.yml +69 -0
  199. package/tasks/spec.yml +41 -0
  200. package/tasks/swarm.yml +85 -0
  201. package/tasks/toolchain.yml +13 -0
  202. package/tasks/triage-actions.yml +94 -0
  203. package/tasks/triage-bootstrap.yml +43 -0
  204. package/tasks/triage-bulk.yml +75 -0
  205. package/tasks/triage-classify.yml +30 -0
  206. package/tasks/triage-queue.yml +50 -0
  207. package/tasks/triage-reconcile.yml +29 -0
  208. package/tasks/triage-scope-drift.yml +29 -0
  209. package/tasks/triage-scope.yml +31 -0
  210. package/tasks/triage-smoketest.yml +33 -0
  211. package/tasks/triage-subscribe.yml +36 -0
  212. package/tasks/triage-summary.yml +29 -0
  213. package/tasks/triage-welcome.yml +32 -0
  214. package/tasks/ts.yml +328 -0
  215. package/tasks/vbrief.yml +206 -0
  216. package/tasks/verify.yml +292 -0
  217. package/templates/agents-entry.md +1 -1
@@ -0,0 +1,495 @@
1
+ #!/usr/bin/env python3
2
+ """Dependency-free default extractor for #1595 codebase-map artifacts.
3
+
4
+ The default path is intentionally modest: it walks the repository, applies the
5
+ authored ``codeStructure`` module globs when available, and uses import-line
6
+ heuristics for coarse coupling. It does not parse ASTs, call the network, or
7
+ ask a model to summarize code. Richer providers can replace this artifact via
8
+ ``scripts/codebase_provider.py`` once they satisfy the provider contract.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import hashlib
15
+ import json
16
+ import os
17
+ import re
18
+ import sys
19
+ from collections import Counter, defaultdict
20
+ from contextlib import suppress
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ import code_structure_validate
25
+ from codebase_projection_registry import (
26
+ CODEBASE_MAP_FORMAT_VERSION,
27
+ CODEBASE_MAP_KIND,
28
+ CODEBASE_PROVIDER_CONTRACT_VERSION,
29
+ )
30
+
31
+ DEFAULT_PROVIDER_NAME = "directive-default-extractor"
32
+ DEFAULT_PROVIDER_VERSION = "0.1"
33
+ MAX_IMPORT_SCAN_BYTES = 262_144
34
+ MAX_FILES_PER_MODULE = 100
35
+ MAX_EVIDENCE_PER_EDGE = 5
36
+
37
+ SKIP_DIRS = {
38
+ ".git",
39
+ ".mypy_cache",
40
+ ".pytest_cache",
41
+ ".ruff_cache",
42
+ ".venv",
43
+ "__pycache__",
44
+ "build",
45
+ "dist",
46
+ "node_modules",
47
+ "swarm-worktrees",
48
+ }
49
+
50
+ LANGUAGE_BY_SUFFIX = {
51
+ ".go": "Go",
52
+ ".js": "JavaScript",
53
+ ".jsx": "JavaScript",
54
+ ".json": "JSON",
55
+ ".md": "Markdown",
56
+ ".py": "Python",
57
+ ".sh": "Shell",
58
+ ".ts": "TypeScript",
59
+ ".tsx": "TypeScript",
60
+ ".yaml": "YAML",
61
+ ".yml": "YAML",
62
+ }
63
+
64
+ ENTRYPOINT_NAMES = {
65
+ "__main__.py",
66
+ "cli.py",
67
+ "cmd.py",
68
+ "index.js",
69
+ "index.ts",
70
+ "main.go",
71
+ "main.py",
72
+ "run",
73
+ "run.py",
74
+ }
75
+
76
+ IMPORT_PATTERNS = [
77
+ re.compile(r"^\s*import\s+([A-Za-z_][\w.]*)"),
78
+ re.compile(r"^\s*from\s+([A-Za-z_][\w.]*)\s+import\s+"),
79
+ re.compile(r"^\s*import\s+.*?\s+from\s+[\"']([^\"']+)[\"']"),
80
+ re.compile(r"^\s*(?:const|let|var)\s+.*?=\s*require\([\"']([^\"']+)[\"']\)"),
81
+ re.compile(r"^\s*import\s+[\"']([^\"']+)[\"']"),
82
+ ]
83
+
84
+
85
+ def _posix(path: Path) -> str:
86
+ return path.as_posix()
87
+
88
+
89
+ def _relative_file(path: Path, project_root: Path) -> str:
90
+ return _posix(path.relative_to(project_root))
91
+
92
+
93
+ def file_sha256(path: Path) -> str:
94
+ digest = hashlib.sha256()
95
+ with path.open("rb") as handle:
96
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
97
+ digest.update(chunk)
98
+ return digest.hexdigest()
99
+
100
+
101
+ def _source_content_hash(project_root: Path, rel_paths: list[str]) -> dict[str, Any]:
102
+ digest = hashlib.sha256()
103
+ file_count = 0
104
+ for rel_path in sorted(set(rel_paths)):
105
+ path = project_root / rel_path
106
+ if not path.is_file():
107
+ continue
108
+ file_count += 1
109
+ digest.update(rel_path.encode("utf-8"))
110
+ digest.update(b"\0")
111
+ digest.update(file_sha256(path).encode("ascii"))
112
+ digest.update(b"\0")
113
+ return {
114
+ "algorithm": "sha256",
115
+ "scope": "codeStructure-and-module-files",
116
+ "value": digest.hexdigest(),
117
+ "fileCount": file_count,
118
+ }
119
+
120
+
121
+ def default_code_structure_path(project_root: Path, code_structure_path: Path | None) -> Path:
122
+ """Return the authored codeStructure source path used by the default extractor."""
123
+ return code_structure_path or project_root / "vbrief" / "PROJECT-DEFINITION.vbrief.json"
124
+
125
+
126
+ def _stable_id(value: str) -> str:
127
+ slug = re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")
128
+ return slug or "root"
129
+
130
+
131
+ def _repo_files(project_root: Path) -> list[Path]:
132
+ files: list[Path] = []
133
+ for dirpath, dirnames, filenames in os.walk(project_root):
134
+ dirnames[:] = [dirname for dirname in dirnames if dirname not in SKIP_DIRS]
135
+ for filename in filenames:
136
+ files.append(Path(dirpath) / filename)
137
+ return sorted(files, key=lambda item: _relative_file(item, project_root))
138
+
139
+
140
+ def _glob_files(project_root: Path, globs: list[str]) -> list[Path]:
141
+ files: dict[str, Path] = {}
142
+ for glob_value in globs:
143
+ for match in project_root.glob(glob_value):
144
+ if not match.is_file():
145
+ continue
146
+ rel_parts = match.relative_to(project_root).parts
147
+ if any(part in SKIP_DIRS for part in rel_parts):
148
+ continue
149
+ files[_relative_file(match, project_root)] = match
150
+ return [files[key] for key in sorted(files)]
151
+
152
+
153
+ def _load_authored_code_structure(
154
+ project_root: Path, code_structure_path: Path | None
155
+ ) -> tuple[dict[str, Any] | None, str | None]:
156
+ path = default_code_structure_path(project_root, code_structure_path)
157
+ if not path.exists():
158
+ return None, None
159
+ data = code_structure_validate.load_json_file(path)
160
+ extracted = code_structure_validate.extract_code_structure(data)
161
+ if extracted is None:
162
+ return None, None
163
+ return extracted.record, extracted.home
164
+
165
+
166
+ def _module_prefixes(module: dict[str, Any], files: list[Path], project_root: Path) -> set[str]:
167
+ prefixes: set[str] = set()
168
+ for glob_value in module.get("pathGlobs", []):
169
+ if not isinstance(glob_value, str):
170
+ continue
171
+ first = glob_value.split("/", maxsplit=1)[0]
172
+ if (
173
+ first
174
+ and not code_structure_validate._has_glob_magic(first)
175
+ and first not in {".", "**"}
176
+ ):
177
+ prefixes.add(first.removesuffix(".py"))
178
+ for file_path in files:
179
+ rel_parts = file_path.relative_to(project_root).parts
180
+ if len(rel_parts) > 1:
181
+ prefixes.add(rel_parts[0])
182
+ elif file_path.suffix == ".py":
183
+ prefixes.add(file_path.stem)
184
+ return {prefix for prefix in prefixes if prefix}
185
+
186
+
187
+ def _curated_modules(
188
+ project_root: Path, code_structure: dict[str, Any]
189
+ ) -> tuple[list[dict[str, Any]], dict[str, str], dict[str, set[str]], list[dict[str, str]]]:
190
+ artifacts: list[dict[str, Any]] = []
191
+ file_to_module: dict[str, str] = {}
192
+ prefixes_by_module: dict[str, set[str]] = {}
193
+ degraded: list[dict[str, str]] = []
194
+
195
+ for raw_module in code_structure.get("modules", []):
196
+ if not isinstance(raw_module, dict):
197
+ continue
198
+ module_id = str(raw_module.get("id", "unknown"))
199
+ globs = [value for value in raw_module.get("pathGlobs", []) if isinstance(value, str)]
200
+ files = _glob_files(project_root, globs)
201
+ rel_files = [_relative_file(path, project_root) for path in files]
202
+ for rel_path in rel_files:
203
+ file_to_module.setdefault(rel_path, module_id)
204
+ if len(rel_files) > MAX_FILES_PER_MODULE:
205
+ degraded.append(
206
+ {
207
+ "code": "MODULE-FILES-TRUNCATED",
208
+ "module": module_id,
209
+ "message": (
210
+ f"Module file list was truncated to {MAX_FILES_PER_MODULE} "
211
+ "deterministic entries."
212
+ ),
213
+ }
214
+ )
215
+ artifacts.append(
216
+ {
217
+ "id": module_id,
218
+ "name": raw_module.get("name"),
219
+ "purpose": raw_module.get("purpose"),
220
+ "pathGlobs": globs,
221
+ "fileCount": len(rel_files),
222
+ "files": rel_files[:MAX_FILES_PER_MODULE],
223
+ "derivedFrom": {
224
+ "intent": "codeStructure.modules[]",
225
+ "files": "repository-glob-walk",
226
+ },
227
+ }
228
+ )
229
+ prefixes_by_module[module_id] = _module_prefixes(raw_module, files, project_root)
230
+ return artifacts, file_to_module, prefixes_by_module, degraded
231
+
232
+
233
+ def _directory_modules(
234
+ project_root: Path,
235
+ ) -> tuple[list[dict[str, Any]], dict[str, str], dict[str, set[str]], list[dict[str, str]]]:
236
+ grouped: dict[str, list[Path]] = defaultdict(list)
237
+ for file_path in _repo_files(project_root):
238
+ parts = file_path.relative_to(project_root).parts
239
+ if not parts:
240
+ continue
241
+ top = parts[0] if len(parts) > 1 else "root-files"
242
+ grouped[top].append(file_path)
243
+
244
+ modules: list[dict[str, Any]] = []
245
+ file_to_module: dict[str, str] = {}
246
+ prefixes_by_module: dict[str, set[str]] = {}
247
+ degraded_markers: list[dict[str, str]] = [
248
+ {
249
+ "code": "NO-CODESTRUCTURE",
250
+ "message": (
251
+ "No authored codeStructure metadata was found; modules were derived from "
252
+ "top-level repository paths."
253
+ ),
254
+ }
255
+ ]
256
+ for top in sorted(grouped):
257
+ module_id = _stable_id(top)
258
+ rel_files = [_relative_file(path, project_root) for path in sorted(grouped[top])]
259
+ for rel_path in rel_files:
260
+ file_to_module.setdefault(rel_path, module_id)
261
+ if len(rel_files) > MAX_FILES_PER_MODULE:
262
+ degraded_markers.append(
263
+ {
264
+ "code": "MODULE-FILES-TRUNCATED",
265
+ "module": module_id,
266
+ "message": (
267
+ f"Module file list was truncated to {MAX_FILES_PER_MODULE} "
268
+ "deterministic entries."
269
+ ),
270
+ }
271
+ )
272
+ modules.append(
273
+ {
274
+ "id": module_id,
275
+ "name": top,
276
+ "purpose": None,
277
+ "pathGlobs": [f"{top}/**/*" if top != "root-files" else "*"],
278
+ "fileCount": len(rel_files),
279
+ "files": rel_files[:MAX_FILES_PER_MODULE],
280
+ "derivedFrom": {
281
+ "intent": "directory-derived-fallback",
282
+ "files": "repository-tree-walk",
283
+ },
284
+ }
285
+ )
286
+ prefixes_by_module[module_id] = {top} if top != "root-files" else set()
287
+
288
+ return modules, file_to_module, prefixes_by_module, degraded_markers
289
+
290
+
291
+ def _read_imports(path: Path) -> list[tuple[int, str]]:
292
+ if path.suffix not in {".go", ".js", ".jsx", ".py", ".ts", ".tsx"}:
293
+ return []
294
+ try:
295
+ if path.stat().st_size > MAX_IMPORT_SCAN_BYTES:
296
+ return []
297
+ lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
298
+ except OSError:
299
+ return []
300
+
301
+ imports: list[tuple[int, str]] = []
302
+ in_go_import_block = False
303
+ for line_number, line in enumerate(lines, start=1):
304
+ stripped = line.strip()
305
+ if path.suffix == ".go":
306
+ if stripped == "import (":
307
+ in_go_import_block = True
308
+ continue
309
+ if in_go_import_block and stripped == ")":
310
+ in_go_import_block = False
311
+ continue
312
+ if in_go_import_block:
313
+ match = re.search(r'"([^"]+)"', stripped)
314
+ if match:
315
+ imports.append((line_number, match.group(1)))
316
+ continue
317
+ match = re.match(r'^\s*import\s+"([^"]+)"', line)
318
+ if match:
319
+ imports.append((line_number, match.group(1)))
320
+ continue
321
+
322
+ for pattern in IMPORT_PATTERNS:
323
+ match = pattern.match(line)
324
+ if match:
325
+ imports.append((line_number, match.group(1)))
326
+ break
327
+ return imports
328
+
329
+
330
+ def _import_targets(ref: str, prefixes_by_module: dict[str, set[str]]) -> set[str]:
331
+ if ref.startswith("."):
332
+ return set()
333
+ normalized = ref.removeprefix("@")
334
+ first_segment = re.split(r"[/.]", normalized, maxsplit=1)[0]
335
+ targets: set[str] = set()
336
+ for module_id, prefixes in prefixes_by_module.items():
337
+ if first_segment in prefixes or ref in prefixes:
338
+ targets.add(module_id)
339
+ return targets
340
+
341
+
342
+ def _coupling_edges(
343
+ project_root: Path, file_to_module: dict[str, str], prefixes_by_module: dict[str, set[str]]
344
+ ) -> list[dict[str, Any]]:
345
+ edges: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list)
346
+ for rel_path, source_module in sorted(file_to_module.items()):
347
+ path = project_root / rel_path
348
+ for line_number, import_ref in _read_imports(path):
349
+ for target_module in _import_targets(import_ref, prefixes_by_module):
350
+ if target_module == source_module:
351
+ continue
352
+ evidence = edges[(source_module, target_module)]
353
+ if len(evidence) < MAX_EVIDENCE_PER_EDGE:
354
+ evidence.append(
355
+ {"path": rel_path, "line": line_number, "import": import_ref}
356
+ )
357
+
358
+ return [
359
+ {
360
+ "from": source,
361
+ "to": target,
362
+ "derivedFrom": "import-line-heuristic",
363
+ "confidence": "heuristic",
364
+ "evidence": evidence,
365
+ }
366
+ for (source, target), evidence in sorted(edges.items())
367
+ ]
368
+
369
+
370
+ def _entry_points(file_to_module: dict[str, str]) -> list[dict[str, str]]:
371
+ entries: list[dict[str, str]] = []
372
+ for rel_path, module_id in sorted(file_to_module.items()):
373
+ path = Path(rel_path)
374
+ if path.name in ENTRYPOINT_NAMES or path.parts[:1] == ("cmd",):
375
+ entries.append(
376
+ {
377
+ "path": rel_path,
378
+ "module": module_id,
379
+ "derivedFrom": "filename-heuristic",
380
+ "confidence": "heuristic",
381
+ }
382
+ )
383
+ return entries
384
+
385
+
386
+ def _language_distribution(file_to_module: dict[str, str]) -> list[dict[str, Any]]:
387
+ counts = Counter(
388
+ LANGUAGE_BY_SUFFIX.get(Path(rel_path).suffix, "Other") for rel_path in file_to_module
389
+ )
390
+ return [
391
+ {"language": language, "files": count, "derivedFrom": "extension-heuristic"}
392
+ for language, count in sorted(counts.items())
393
+ ]
394
+
395
+
396
+ def build_codebase_map(
397
+ project_root: Path,
398
+ *,
399
+ code_structure_path: Path | None = None,
400
+ fallback_reason: str | None = None,
401
+ ) -> dict[str, Any]:
402
+ """Build a deterministic tier-1 codebase-map artifact."""
403
+ project_root = project_root.resolve()
404
+ code_structure, source_home = _load_authored_code_structure(project_root, code_structure_path)
405
+ source_path = default_code_structure_path(project_root, code_structure_path)
406
+
407
+ if code_structure is not None:
408
+ modules, file_to_module, prefixes_by_module, degraded = _curated_modules(
409
+ project_root, code_structure
410
+ )
411
+ else:
412
+ modules, file_to_module, prefixes_by_module, degraded = _directory_modules(project_root)
413
+
414
+ content_hash_paths = list(file_to_module)
415
+ with suppress(ValueError):
416
+ content_hash_paths.append(source_path.resolve().relative_to(project_root).as_posix())
417
+
418
+ degraded.append(
419
+ {
420
+ "code": "AST-FREE-HEURISTICS",
421
+ "message": (
422
+ "Default extractor uses repository walking and import-line heuristics only; "
423
+ "no AST or language parser provider was configured."
424
+ ),
425
+ }
426
+ )
427
+ if fallback_reason:
428
+ degraded.append({"code": "PROVIDER-FALLBACK", "message": fallback_reason})
429
+
430
+ return {
431
+ "formatVersion": CODEBASE_MAP_FORMAT_VERSION,
432
+ "contractVersion": CODEBASE_PROVIDER_CONTRACT_VERSION,
433
+ "kind": CODEBASE_MAP_KIND,
434
+ "provider": {
435
+ "name": DEFAULT_PROVIDER_NAME,
436
+ "version": DEFAULT_PROVIDER_VERSION,
437
+ "mode": "default",
438
+ "degraded": True,
439
+ **({"fallbackReason": fallback_reason} if fallback_reason else {}),
440
+ },
441
+ "source": {
442
+ "projectRoot": str(project_root),
443
+ "codeStructurePath": str(source_path),
444
+ "codeStructureHome": source_home,
445
+ "contentHash": _source_content_hash(project_root, content_hash_paths),
446
+ },
447
+ "modules": modules,
448
+ "coupling": _coupling_edges(project_root, file_to_module, prefixes_by_module),
449
+ "entryPoints": _entry_points(file_to_module),
450
+ "languageDistribution": _language_distribution(file_to_module),
451
+ "degraded": degraded,
452
+ }
453
+
454
+
455
+ def config_error_to_dict(
456
+ path: Path, error: code_structure_validate.CodeStructureConfigError
457
+ ) -> dict[str, Any]:
458
+ """Return the structured config-error shape shared by codebase CLIs."""
459
+ return {
460
+ "path": str(path),
461
+ "ok": False,
462
+ "errors": [{"code": "CS-CONFIG", "message": str(error), "location": str(path)}],
463
+ "warnings": [],
464
+ }
465
+
466
+
467
+ def main(argv: list[str] | None = None) -> int:
468
+ """CLI entry point."""
469
+ parser = argparse.ArgumentParser(description="Emit the default codebase-map artifact.")
470
+ parser.add_argument("--project-root", default=".", help="Repository root to inspect.")
471
+ parser.add_argument("--path", help="Explicit vBRIEF containing codeStructure metadata.")
472
+ args = parser.parse_args(argv)
473
+
474
+ project_root = Path(args.project_root)
475
+ code_structure_path = Path(args.path) if args.path else None
476
+ try:
477
+ artifact = build_codebase_map(project_root, code_structure_path=code_structure_path)
478
+ except code_structure_validate.CodeStructureConfigError as exc:
479
+ print(
480
+ json.dumps(
481
+ config_error_to_dict(
482
+ default_code_structure_path(project_root, code_structure_path), exc
483
+ ),
484
+ indent=2,
485
+ sort_keys=True,
486
+ ),
487
+ file=sys.stderr,
488
+ )
489
+ return 2
490
+ print(json.dumps(artifact, indent=2, sort_keys=True))
491
+ return 0
492
+
493
+
494
+ if __name__ == "__main__":
495
+ sys.exit(main())