stead 0.5.0__py3-none-any.whl

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 (139) hide show
  1. ctx/__init__.py +7 -0
  2. ctx/__main__.py +9 -0
  3. ctx/_bundled_factories/context-maintenance/FACTORY.md +37 -0
  4. ctx/_bundled_factories/context-maintenance/evals/eval-maintenance-broken-relation.json +7 -0
  5. ctx/_bundled_factories/context-maintenance/evals/eval-maintenance-clean.json +7 -0
  6. ctx/_bundled_factories/context-maintenance/evals/eval-maintenance-duplicates.json +7 -0
  7. ctx/_bundled_factories/context-maintenance/evals/eval-maintenance-inbox.json +7 -0
  8. ctx/_bundled_factories/context-maintenance/evals/eval-maintenance-stale.json +7 -0
  9. ctx/_bundled_factories/context-maintenance/prompts/v1.md +19 -0
  10. ctx/_bundled_factories/feature-builder/FACTORY.md +160 -0
  11. ctx/_bundled_factories/feature-builder/evals/eval-feature-builtin-method.json +1 -0
  12. ctx/_bundled_factories/feature-builder/evals/eval-feature-clear-spec.json +1 -0
  13. ctx/_bundled_factories/feature-builder/evals/eval-feature-duplicate-work.json +1 -0
  14. ctx/_bundled_factories/feature-builder/evals/eval-feature-spec-kit-method.json +1 -0
  15. ctx/_bundled_factories/feature-builder/evals/eval-feature-spec-kit-vague.json +1 -0
  16. ctx/_bundled_factories/feature-builder/evals/eval-feature-vague-spec.json +1 -0
  17. ctx/_bundled_factories/feature-builder/evals/pipeline/pipeline-add-greeting-flag.json +16 -0
  18. ctx/_bundled_factories/feature-builder/evals/pipeline/pipeline-broken-check-detected.json +15 -0
  19. ctx/_bundled_factories/feature-builder/evals/pipeline/pipeline-js-slug-helper.json +16 -0
  20. ctx/_bundled_factories/feature-builder/prompts/v1.md +101 -0
  21. ctx/_bundled_factories/feature-builder/prompts/v2.md +177 -0
  22. ctx/_bundled_factories/weekly-contribution-digest/FACTORY.md +88 -0
  23. ctx/_bundled_factories/weekly-contribution-digest/evals/eval-digest-ci-failure.json +1 -0
  24. ctx/_bundled_factories/weekly-contribution-digest/evals/eval-digest-empty-cache.json +1 -0
  25. ctx/_bundled_factories/weekly-contribution-digest/evals/eval-digest-multi-repo.json +1 -0
  26. ctx/_bundled_factories/weekly-contribution-digest/prompts/v1.md +48 -0
  27. ctx/_bundled_factories/weekly-project-status/FACTORY.md +71 -0
  28. ctx/_bundled_factories/weekly-project-status/evals/eval-status-blocked-project.json +1 -0
  29. ctx/_bundled_factories/weekly-project-status/evals/eval-status-happy-path.json +1 -0
  30. ctx/_bundled_factories/weekly-project-status/evals/eval-status-thin-context.json +1 -0
  31. ctx/_bundled_factories/weekly-project-status/prompts/v1.md +32 -0
  32. ctx/accounts.py +350 -0
  33. ctx/acp_server.py +976 -0
  34. ctx/actors.py +64 -0
  35. ctx/agent.py +2344 -0
  36. ctx/agent_address.py +781 -0
  37. ctx/agent_exports.py +724 -0
  38. ctx/agent_git.py +704 -0
  39. ctx/agent_prompts.py +298 -0
  40. ctx/agent_tools.py +256 -0
  41. ctx/audit.py +97 -0
  42. ctx/autonomy.py +344 -0
  43. ctx/backup.py +387 -0
  44. ctx/bench.py +473 -0
  45. ctx/bundle.py +442 -0
  46. ctx/chatops.py +370 -0
  47. ctx/ci_hooks.py +128 -0
  48. ctx/cli.py +2018 -0
  49. ctx/cli_handlers.py +2248 -0
  50. ctx/cockpit/events_forms.js +835 -0
  51. ctx/cockpit/events_pipeline.js +1353 -0
  52. ctx/cockpit/events_ui.js +1302 -0
  53. ctx/cockpit/palette.js +146 -0
  54. ctx/cockpit/state.js +666 -0
  55. ctx/cockpit/styles.css +834 -0
  56. ctx/cockpit/views_core.js +661 -0
  57. ctx/cockpit/views_pipeline.js +1183 -0
  58. ctx/cockpit/views_spaces.js +1468 -0
  59. ctx/cockpit.html +61 -0
  60. ctx/commands.py +499 -0
  61. ctx/comment.py +233 -0
  62. ctx/config.py +563 -0
  63. ctx/context_bench.py +220 -0
  64. ctx/context_sync.py +235 -0
  65. ctx/db.py +519 -0
  66. ctx/deliver.py +105 -0
  67. ctx/demo.py +338 -0
  68. ctx/devcontainer.py +850 -0
  69. ctx/doctor.py +376 -0
  70. ctx/drift.py +565 -0
  71. ctx/events.py +142 -0
  72. ctx/executor.py +713 -0
  73. ctx/factory.py +1384 -0
  74. ctx/federation.py +397 -0
  75. ctx/forge.py +358 -0
  76. ctx/frontmatter.py +157 -0
  77. ctx/gc.py +275 -0
  78. ctx/graph.py +434 -0
  79. ctx/inbox_import.py +341 -0
  80. ctx/integrations.py +214 -0
  81. ctx/isolation.py +665 -0
  82. ctx/issue_file.py +228 -0
  83. ctx/local_review.py +205 -0
  84. ctx/lsp.py +493 -0
  85. ctx/mcp_server.py +1806 -0
  86. ctx/merge.py +286 -0
  87. ctx/metrics.py +232 -0
  88. ctx/model_evals.py +431 -0
  89. ctx/models.py +953 -0
  90. ctx/notify.py +304 -0
  91. ctx/objects.py +111 -0
  92. ctx/onboard.py +419 -0
  93. ctx/otel.py +397 -0
  94. ctx/output_compress.py +180 -0
  95. ctx/patch.py +407 -0
  96. ctx/pipeline_eval.py +586 -0
  97. ctx/plan_paths.py +200 -0
  98. ctx/pr_triage.py +625 -0
  99. ctx/proof.py +90 -0
  100. ctx/publish.py +270 -0
  101. ctx/repair.py +250 -0
  102. ctx/repo_map.py +1320 -0
  103. ctx/review.py +672 -0
  104. ctx/safety.py +667 -0
  105. ctx/sarif.py +175 -0
  106. ctx/scaffold.py +199 -0
  107. ctx/schedule.py +590 -0
  108. ctx/schema.sql +180 -0
  109. ctx/search.py +249 -0
  110. ctx/semantic.py +1007 -0
  111. ctx/sessions.py +265 -0
  112. ctx/slop.py +725 -0
  113. ctx/spec.py +1528 -0
  114. ctx/spec_split.py +588 -0
  115. ctx/spend.py +200 -0
  116. ctx/stack.py +719 -0
  117. ctx/stead_publish.py +578 -0
  118. ctx/steer.py +151 -0
  119. ctx/sync.py +628 -0
  120. ctx/task_query.py +36 -0
  121. ctx/tasks.py +449 -0
  122. ctx/test_quality.py +1007 -0
  123. ctx/tracker.py +1063 -0
  124. ctx/ui.py +1761 -0
  125. ctx/ui_routes.py +2427 -0
  126. ctx/ui_server.py +1333 -0
  127. ctx/ui_snapshot.py +1238 -0
  128. ctx/util.py +132 -0
  129. ctx/wiki.py +492 -0
  130. ctx/wiki_store.py +169 -0
  131. ctx/writeback.py +1403 -0
  132. stead/__init__.py +5 -0
  133. stead/__main__.py +6 -0
  134. stead-0.5.0.dist-info/METADATA +204 -0
  135. stead-0.5.0.dist-info/RECORD +139 -0
  136. stead-0.5.0.dist-info/WHEEL +5 -0
  137. stead-0.5.0.dist-info/entry_points.txt +2 -0
  138. stead-0.5.0.dist-info/licenses/LICENSE +201 -0
  139. stead-0.5.0.dist-info/top_level.txt +2 -0
ctx/forge.py ADDED
@@ -0,0 +1,358 @@
1
+ """Pluggable forge adapter boundary (#238).
2
+
3
+ Isolates GitHub-specific ``gh`` CLI calls behind a minimal adapter interface so
4
+ GitLab (``glab``), Gitea/Forgejo, or local-only git checkouts can be targeted
5
+ without duplicating pipeline, containment, or confirmation-gating logic.
6
+
7
+ GitHub (``gh``) remains the zero-dependency default.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ from pathlib import Path
14
+ from typing import Protocol
15
+ from urllib.parse import quote, urlparse
16
+
17
+ FORGES = ("github", "gitlab", "forgejo", "local")
18
+
19
+
20
+ class ForgeError(Exception):
21
+ pass
22
+
23
+
24
+ class ForgeAdapter(Protocol):
25
+ kind: str
26
+
27
+ def create_pr(self, code: Path, *, base: str, head: str, title: str,
28
+ body: str, draft: bool, runner) -> str:
29
+ """Create a pull/merge request and return its URL."""
30
+
31
+ def comment_issue(self, code: Path, *, number: int, body: str, runner) -> str:
32
+ """Post a comment on an upstream issue."""
33
+
34
+ def view_pr(self, code: Path, *, branch: str, runner) -> dict:
35
+ """Inspect the open PR/MR for a branch."""
36
+
37
+ def merge_pr(self, code: Path, *, number: int, method: str,
38
+ expected_sha: str, runner) -> str:
39
+ """Merge a verified PR/MR."""
40
+
41
+ def fetch_ci_logs(self, code: Path, *, branch: str, runner) -> dict:
42
+ """Return failed checks and trimmed failure logs for a branch."""
43
+
44
+ def create_issue(self, code: Path, *, repo_slug: str, title: str,
45
+ body: str, labels: list[str], runner) -> str:
46
+ """Create an upstream issue and return raw CLI output containing its URL."""
47
+
48
+ def check_branch_protection(self, code: Path, *, default_branch: str, runner) -> bool:
49
+ """Return True if the default branch enforces required checks/protection."""
50
+
51
+
52
+ class GitHubCliAdapter:
53
+ """Default zero-dependency adapter backed by the open-source ``gh`` CLI."""
54
+
55
+ kind = "github"
56
+
57
+ def create_pr(self, code: Path, *, base: str, head: str, title: str,
58
+ body: str, draft: bool, runner) -> str:
59
+ argv = [
60
+ "gh", "pr", "create",
61
+ "--base", base, "--head", head,
62
+ "--title", title, "--body", body,
63
+ ]
64
+ if draft:
65
+ argv.append("--draft")
66
+ return str(runner(argv, code)).strip()
67
+
68
+ def comment_issue(self, code: Path, *, number: int, body: str, runner) -> str:
69
+ return str(runner(["gh", "issue", "comment", str(number), "--body", body], code)).strip()
70
+
71
+ def view_pr(self, code: Path, *, branch: str, runner) -> dict:
72
+ raw = runner([
73
+ "gh", "pr", "view", branch, "--json",
74
+ "number,url,state,isDraft,baseRefName,headRefName,headRefOid,statusCheckRollup",
75
+ ], code)
76
+ try:
77
+ data = json.loads(raw)
78
+ except json.JSONDecodeError as exc:
79
+ raise ForgeError("could not parse gh pr view output") from exc
80
+ if not isinstance(data, dict):
81
+ raise ForgeError("unexpected gh pr view payload")
82
+ return data
83
+
84
+ def merge_pr(self, code: Path, *, number: int, method: str,
85
+ expected_sha: str, runner) -> str:
86
+ flag = {"squash": "--squash", "rebase": "--rebase"}.get(method, "--merge")
87
+ argv = ["gh", "pr", "merge", str(number), flag]
88
+ if expected_sha:
89
+ argv += ["--match-head-commit", expected_sha]
90
+ return str(runner(argv, code)).strip()
91
+
92
+ def fetch_ci_logs(self, code: Path, *, branch: str, runner) -> dict:
93
+ raw = str(runner(["gh", "pr", "checks", branch, "--json", "name,state,link"], code))
94
+ try:
95
+ checks = json.loads(raw or "[]")
96
+ except json.JSONDecodeError:
97
+ checks = []
98
+ failed = [
99
+ c for c in checks
100
+ if isinstance(c, dict)
101
+ and str(c.get("state") or "").upper() in ("FAILURE", "ERROR", "CANCELLED", "TIMED_OUT", "FAIL")
102
+ ]
103
+ if not failed:
104
+ return {"failed_checks": [], "log": ""}
105
+ log_chunks: list[str] = []
106
+ for chk in failed[:3]:
107
+ name = str(chk.get("name") or "check")
108
+ link = str(chk.get("link") or "")
109
+ run_id = ""
110
+ if "/runs/" in link:
111
+ tail = link.split("/runs/", 1)[1]
112
+ run_id = tail.split("/", 1)[0].split("?", 1)[0]
113
+ if run_id.isdigit():
114
+ try:
115
+ out = str(runner(["gh", "run", "view", run_id, "--log-failed"], code))
116
+ log_chunks.append(f"=== {name} (run {run_id}) ===\n{out[-3000:]}")
117
+ except Exception:
118
+ log_chunks.append(f"=== {name} ===\n(failed to fetch run log)")
119
+ else:
120
+ log_chunks.append(f"=== {name} ===\nstate={chk.get('state')} link={link}")
121
+ return {
122
+ "failed_checks": [str(c.get("name") or "check") for c in failed],
123
+ "log": "\n\n".join(log_chunks)[-8000:],
124
+ }
125
+
126
+ def create_issue(self, code: Path, *, repo_slug: str, title: str,
127
+ body: str, labels: list[str], runner) -> str:
128
+ argv = ["gh", "issue", "create", "--repo", repo_slug, "--title", title, "--body", body]
129
+ for lbl in labels:
130
+ if str(lbl).strip():
131
+ argv += ["--label", str(lbl).strip()]
132
+ return str(runner(argv, code)).strip()
133
+
134
+ def check_branch_protection(self, code: Path, *, default_branch: str, runner) -> bool:
135
+ raw = str(runner(["gh", "api", f"repos/{{owner}}/{{repo}}/branches/{default_branch}/protection"], code))
136
+ try:
137
+ data = json.loads(raw or "{}")
138
+ except json.JSONDecodeError:
139
+ return False
140
+ rsc = data.get("required_status_checks") if isinstance(data, dict) else None
141
+ return isinstance(rsc, dict) and bool(rsc.get("contexts") or rsc.get("checks"))
142
+
143
+
144
+ class GitLabCliAdapter:
145
+ """Adapter backed by the open-source ``glab`` CLI for GitLab repositories."""
146
+
147
+ kind = "gitlab"
148
+
149
+ def create_pr(self, code: Path, *, base: str, head: str, title: str,
150
+ body: str, draft: bool, runner) -> str:
151
+ mr_title = f"Draft: {title}" if draft and not title.lower().startswith("draft:") else title
152
+ argv = [
153
+ "glab", "mr", "create",
154
+ "--target-branch", base, "--source-branch", head,
155
+ "--title", mr_title, "--description", body, "--yes",
156
+ ]
157
+ if draft:
158
+ argv.append("--draft")
159
+ return str(runner(argv, code)).strip()
160
+
161
+ def comment_issue(self, code: Path, *, number: int, body: str, runner) -> str:
162
+ return str(runner(["glab", "issue", "note", str(number), "--message", body], code)).strip()
163
+
164
+ def view_pr(self, code: Path, *, branch: str, runner) -> dict:
165
+ raw = runner(["glab", "mr", "view", branch, "--output", "json"], code)
166
+ try:
167
+ data = json.loads(raw)
168
+ except json.JSONDecodeError as exc:
169
+ raise ForgeError("could not parse glab mr view output") from exc
170
+ if not isinstance(data, dict):
171
+ raise ForgeError("unexpected glab mr view payload")
172
+ pipeline = data.get("head_pipeline") or data.get("pipeline")
173
+ rollup: list[dict] = []
174
+ if isinstance(pipeline, dict) and pipeline.get("status"):
175
+ pstat = str(pipeline.get("status") or "").lower()
176
+ if pstat == "success":
177
+ rollup.append({"name": "gitlab-pipeline", "status": "COMPLETED", "conclusion": "SUCCESS"})
178
+ elif pstat in ("failed", "canceled", "cancelled"):
179
+ rollup.append({"name": "gitlab-pipeline", "status": "COMPLETED", "conclusion": "FAILURE"})
180
+ else:
181
+ rollup.append({"name": "gitlab-pipeline", "status": "IN_PROGRESS", "conclusion": ""})
182
+ raw_state = str(data.get("state") or "").strip().lower()
183
+ norm_state = "OPEN" if raw_state in ("opened", "open", "reopened") else raw_state.upper()
184
+ return {
185
+ "number": data.get("iid"),
186
+ "url": data.get("web_url") or "",
187
+ "state": norm_state,
188
+ "isDraft": bool(data.get("draft") or data.get("work_in_progress")),
189
+ "baseRefName": data.get("target_branch") or "",
190
+ "headRefName": data.get("source_branch") or "",
191
+ "headRefOid": data.get("sha") or "",
192
+ "statusCheckRollup": rollup,
193
+ }
194
+
195
+ def merge_pr(self, code: Path, *, number: int, method: str,
196
+ expected_sha: str, runner) -> str:
197
+ argv = ["glab", "mr", "merge", str(number), "--yes"]
198
+ if method == "squash":
199
+ argv.append("--squash")
200
+ elif method == "rebase":
201
+ argv.append("--rebase")
202
+ if expected_sha:
203
+ argv += ["--sha", expected_sha]
204
+ return str(runner(argv, code)).strip()
205
+
206
+ def fetch_ci_logs(self, code: Path, *, branch: str, runner) -> dict:
207
+ raw = str(runner(["glab", "ci", "status", "--branch", branch], code))
208
+ failed = [line.strip() for line in raw.splitlines() if "failed" in line.lower()]
209
+ if not failed:
210
+ return {"failed_checks": [], "log": ""}
211
+ try:
212
+ trace = str(runner(["glab", "ci", "trace", "--branch", branch], code))
213
+ except Exception:
214
+ trace = raw
215
+ return {"failed_checks": failed[:5], "log": trace[-8000:]}
216
+
217
+ def create_issue(self, code: Path, *, repo_slug: str, title: str,
218
+ body: str, labels: list[str], runner) -> str:
219
+ argv = ["glab", "issue", "create", "--title", title, "--description", body, "--yes"]
220
+ if labels:
221
+ argv += ["--label", ",".join(str(lbl).strip() for lbl in labels if str(lbl).strip())]
222
+ return str(runner(argv, code)).strip()
223
+
224
+ def check_branch_protection(self, code: Path, *, default_branch: str, runner) -> bool:
225
+ try:
226
+ encoded_branch = quote(default_branch, safe="")
227
+ raw_branch = str(runner(["glab", "api", f"projects/:id/protected_branches/{encoded_branch}"], code))
228
+ bdata = json.loads(raw_branch or "{}")
229
+ if not (isinstance(bdata, dict) and bdata.get("name")):
230
+ return False
231
+ raw_proj = str(runner(["glab", "api", "projects/:id"], code))
232
+ pdata = json.loads(raw_proj or "{}")
233
+ return isinstance(pdata, dict) and bool(pdata.get("only_allow_merge_if_pipeline_succeeds"))
234
+ except Exception:
235
+ return False
236
+
237
+
238
+ class ForgejoCliAdapter:
239
+ """Adapter backed by the open-source ``tea`` CLI for Forgejo / Gitea repositories."""
240
+
241
+ kind = "forgejo"
242
+
243
+ def create_pr(self, code: Path, *, base: str, head: str, title: str,
244
+ body: str, draft: bool, runner) -> str:
245
+ pr_title = f"WIP: {title}" if draft and not title.lower().startswith(("wip:", "draft:")) else title
246
+ argv = [
247
+ "tea", "pulls", "create",
248
+ "--base", base, "--head", head,
249
+ "--title", pr_title, "--description", body,
250
+ ]
251
+ return str(runner(argv, code)).strip()
252
+
253
+ def comment_issue(self, code: Path, *, number: int, body: str, runner) -> str:
254
+ return str(runner(["tea", "comment", str(number), body], code)).strip()
255
+
256
+ def view_pr(self, code: Path, *, branch: str, runner) -> dict:
257
+ raw = runner(["tea", "pulls", "list", "--state", "open", "--output", "json"], code)
258
+ try:
259
+ items = json.loads(raw or "[]")
260
+ except json.JSONDecodeError as exc:
261
+ raise ForgeError("could not parse tea pulls output") from exc
262
+ if not isinstance(items, list):
263
+ raise ForgeError("unexpected tea pulls payload")
264
+ for item in items:
265
+ if not isinstance(item, dict):
266
+ continue
267
+ head = item.get("head")
268
+ head_ref = head.get("ref") if isinstance(head, dict) else str(item.get("head_branch") or "")
269
+ if head_ref == branch:
270
+ base = item.get("base")
271
+ base_ref = base.get("ref") if isinstance(base, dict) else str(item.get("base_branch") or "")
272
+ head_sha = head.get("sha") if isinstance(head, dict) else str(item.get("head_sha") or "")
273
+ raw_state = str(item.get("state") or "open").strip().lower()
274
+ return {
275
+ "number": item.get("index") or item.get("number"),
276
+ "url": item.get("url") or item.get("html_url") or "",
277
+ "state": "OPEN" if raw_state in ("open", "opened") else raw_state.upper(),
278
+ "isDraft": bool(item.get("draft") or str(item.get("title") or "").lower().startswith(("wip:", "draft:"))),
279
+ "baseRefName": base_ref,
280
+ "headRefName": head_ref,
281
+ "headRefOid": head_sha,
282
+ "statusCheckRollup": [],
283
+ }
284
+ raise ForgeError(f"no open pull request found for branch {branch}")
285
+
286
+ def merge_pr(self, code: Path, *, number: int, method: str,
287
+ expected_sha: str, runner) -> str:
288
+ style = method if method in ("merge", "squash", "rebase") else "merge"
289
+ argv = ["tea", "pulls", "merge", str(number), "--style", style]
290
+ return str(runner(argv, code)).strip()
291
+
292
+ def fetch_ci_logs(self, code: Path, *, branch: str, runner) -> dict:
293
+ return {"failed_checks": [], "log": ""}
294
+
295
+ def create_issue(self, code: Path, *, repo_slug: str, title: str,
296
+ body: str, labels: list[str], runner) -> str:
297
+ argv = ["tea", "issues", "create", "--title", title, "--description", body]
298
+ if labels:
299
+ argv += ["--labels", ",".join(str(lbl).strip() for lbl in labels if str(lbl).strip())]
300
+ return str(runner(argv, code)).strip()
301
+
302
+ def check_branch_protection(self, code: Path, *, default_branch: str, runner) -> bool:
303
+ return False
304
+
305
+
306
+ class LocalGitAdapter:
307
+ """Local-only adapter for air-gapped or local-git repositories (no remote writes)."""
308
+
309
+ kind = "local"
310
+
311
+ def create_pr(self, code: Path, *, base: str, head: str, title: str,
312
+ body: str, draft: bool, runner) -> str:
313
+ raise ForgeError("repo uses forge: local — remote PR creation is disabled")
314
+
315
+ def comment_issue(self, code: Path, *, number: int, body: str, runner) -> str:
316
+ raise ForgeError("repo uses forge: local — remote issue comments are disabled")
317
+
318
+ def view_pr(self, code: Path, *, branch: str, runner) -> dict:
319
+ raise ForgeError("repo uses forge: local — no remote PR to view")
320
+
321
+ def merge_pr(self, code: Path, *, number: int, method: str,
322
+ expected_sha: str, runner) -> str:
323
+ raise ForgeError("repo uses forge: local — remote PR merge is disabled")
324
+
325
+ def fetch_ci_logs(self, code: Path, *, branch: str, runner) -> dict:
326
+ raise ForgeError("repo uses forge: local — no remote CI logs available")
327
+
328
+ def create_issue(self, code: Path, *, repo_slug: str, title: str,
329
+ body: str, labels: list[str], runner) -> str:
330
+ raise ForgeError("repo uses forge: local — remote issue creation is disabled")
331
+
332
+ def check_branch_protection(self, code: Path, *, default_branch: str, runner) -> bool:
333
+ return False
334
+
335
+
336
+ _ADAPTERS: dict[str, ForgeAdapter] = {
337
+ "github": GitHubCliAdapter(),
338
+ "gitlab": GitLabCliAdapter(),
339
+ "forgejo": ForgejoCliAdapter(),
340
+ "local": LocalGitAdapter(),
341
+ }
342
+
343
+
344
+ def adapter_for_repo(repo_meta: dict) -> ForgeAdapter:
345
+ """Resolve the forge adapter for ``repo_meta`` (default: GitHub ``gh``)."""
346
+ explicit = str(repo_meta.get("forge") or "").strip().lower()
347
+ if explicit:
348
+ adapter = _ADAPTERS.get(explicit)
349
+ if adapter is None:
350
+ raise ForgeError(f"unsupported forge {explicit!r} (expected one of {', '.join(FORGES)})")
351
+ return adapter
352
+ url = str(repo_meta.get("url") or "").strip()
353
+ host = (urlparse(url).hostname or "").lower()
354
+ if host == "gitlab.com" or host.endswith(".gitlab.com"):
355
+ return _ADAPTERS["gitlab"]
356
+ if host == "codeberg.org" or host.startswith(("forgejo.", "gitea.")):
357
+ return _ADAPTERS["forgejo"]
358
+ return _ADAPTERS["github"]
ctx/frontmatter.py ADDED
@@ -0,0 +1,157 @@
1
+ """Minimal, deterministic YAML-subset frontmatter reader/writer.
2
+
3
+ Stdlib only by design: the supported subset is deliberately flat so ANY tool
4
+ can parse it (see CONVENTIONS.md). Supported syntax:
5
+
6
+ - ``key: value`` scalars (strings; optional single/double quotes)
7
+ - inline lists: ``key: [a, b, c]``
8
+ - block lists: ``key:`` followed by ``- item`` lines
9
+ - ``#`` comments and blank lines
10
+
11
+ Not supported: nested maps, anchors, multiline scalars. Values are always
12
+ strings or lists of strings; dates remain ISO strings.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import re
18
+
19
+ # Key order used when writing, so files are deterministic and diff-friendly.
20
+ _KEY_ORDER = ["id", "type", "title", "created", "updated", "status", "project",
21
+ "repo", "kind", "number", "url", "role", "state", "ci", "review",
22
+ "method", "visibility", "actor", "default_branch", "contributing", "notes",
23
+ "trigger", "reach", "code_path", "source_run",
24
+ "superseded_by", "related", "depends_on", "parent_spec", "tags"]
25
+
26
+ _LIST_ITEM = re.compile(r"^\s*-\s+(.*)$")
27
+
28
+
29
+ def _unquote(value: str) -> str:
30
+ value = value.strip()
31
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
32
+ inner = value[1:-1]
33
+ if value[0] == '"':
34
+ inner = inner.replace('\\"', '"').replace("\\\\", "\\")
35
+ return inner
36
+ return value
37
+
38
+
39
+ def _split_inline(item: str) -> list[str]:
40
+ inner = item.strip()[1:-1].strip()
41
+ if not inner:
42
+ return []
43
+ parts: list[str] = []
44
+ buf: list[str] = []
45
+ quote: str | None = None
46
+ escaped = False
47
+ for ch in inner:
48
+ if escaped:
49
+ buf.append(ch)
50
+ escaped = False
51
+ continue
52
+ if quote == '"' and ch == "\\":
53
+ buf.append(ch)
54
+ escaped = True
55
+ continue
56
+ if quote:
57
+ buf.append(ch)
58
+ if ch == quote:
59
+ quote = None
60
+ continue
61
+ if ch in "\"'" and not "".join(buf).strip():
62
+ quote = ch
63
+ buf.append(ch)
64
+ elif ch == ",":
65
+ parts.append(_unquote("".join(buf)))
66
+ buf = []
67
+ else:
68
+ buf.append(ch)
69
+ parts.append(_unquote("".join(buf)))
70
+ return parts
71
+
72
+
73
+ def parse(text: str) -> tuple[dict, str]:
74
+ """Split a markdown document into (frontmatter dict, body).
75
+
76
+ Returns ({}, full_text) when no frontmatter block is present.
77
+ Raises ValueError on malformed blocks or unsupported syntax.
78
+ """
79
+ lines = text.splitlines()
80
+ if not lines or lines[0].strip() != "---":
81
+ return {}, text
82
+ try:
83
+ end = next(i for i in range(1, len(lines)) if lines[i].strip() == "---")
84
+ except StopIteration as exc:
85
+ raise ValueError("frontmatter block opened with '---' but never closed") from exc
86
+
87
+ meta: dict = {}
88
+ pending_key: str | None = None
89
+ for raw in lines[1:end]:
90
+ line = raw.rstrip()
91
+ stripped = line.strip()
92
+ if not stripped or stripped.startswith("#"):
93
+ continue
94
+ item = _LIST_ITEM.match(line)
95
+ if item and pending_key is not None:
96
+ meta[pending_key].append(_unquote(item.group(1)))
97
+ continue
98
+ if ":" not in stripped:
99
+ raise ValueError(f"unsupported frontmatter line: {raw!r}")
100
+ key, _, value = stripped.partition(":")
101
+ key = key.strip()
102
+ value = value.strip()
103
+ # flat schema: inline list, block list header, or scalar value (hashes inside scalars are preserved)
104
+ if value.startswith("["):
105
+ if not value.endswith("]"):
106
+ raise ValueError(f"malformed inline list for key {key!r}")
107
+ meta[key] = _split_inline(value)
108
+ pending_key = None
109
+ elif value == "":
110
+ meta[key] = []
111
+ pending_key = key
112
+ else:
113
+ meta[key] = _unquote(value)
114
+ pending_key = None
115
+ body = "\n".join(lines[end + 1:]).lstrip("\n")
116
+ return meta, body
117
+
118
+
119
+ _LINE_SEPARATORS = "\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029"
120
+
121
+
122
+ def _fmt_scalar(value: str, *, in_list: bool = False) -> str:
123
+ # Flat YAML subset forbids multiline scalars; collapsing every separator
124
+ # that str.splitlines() treats as a line break prevents frontmatter key
125
+ # injection or block termination when writing untrusted text.
126
+ if any(ch in value for ch in _LINE_SEPARATORS):
127
+ value = " ".join(value.splitlines()).strip()
128
+ needs_quote = (
129
+ value == "" or value != value.strip() or ":" in value or "#" in value
130
+ or value.startswith(("[", "-", "'", '"'))
131
+ or (in_list and ("," in value or "]" in value))
132
+ )
133
+ if needs_quote:
134
+ escaped = value.replace("\\", "\\\\").replace('"', '\\"')
135
+ return f'"{escaped}"'
136
+ return value
137
+
138
+
139
+ def dumps(meta: dict, body: str) -> str:
140
+ """Serialize (frontmatter dict, body) back to markdown text.
141
+
142
+ Keys are emitted in a stable order; unknown keys follow alphabetically.
143
+ """
144
+ keys = [k for k in _KEY_ORDER if k in meta]
145
+ keys += sorted(k for k in meta if k not in _KEY_ORDER)
146
+ out = ["---"]
147
+ for key in keys:
148
+ key_s = str(key)
149
+ if any(ch in key_s for ch in _LINE_SEPARATORS + ":"):
150
+ raise ValueError(f"invalid frontmatter key: {key!r}")
151
+ value = meta[key]
152
+ if isinstance(value, list):
153
+ out.append(f"{key_s}: [{', '.join(_fmt_scalar(str(v), in_list=True) for v in value)}]")
154
+ else:
155
+ out.append(f"{key_s}: {_fmt_scalar(str(value))}")
156
+ out.append("---")
157
+ return "\n".join(out) + "\n\n" + body.lstrip("\n")