hackbot-runtime 0.1.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 (38) hide show
  1. hackbot_runtime/__init__.py +24 -0
  2. hackbot_runtime/actions/__init__.py +41 -0
  3. hackbot_runtime/actions/action_records.py +51 -0
  4. hackbot_runtime/actions/agents.py +55 -0
  5. hackbot_runtime/actions/bugzilla.py +232 -0
  6. hackbot_runtime/actions/claude_sdk.py +49 -0
  7. hackbot_runtime/actions/email.py +152 -0
  8. hackbot_runtime/actions/feedback.py +60 -0
  9. hackbot_runtime/actions/github.py +208 -0
  10. hackbot_runtime/actions/mcp_server.py +39 -0
  11. hackbot_runtime/actions/phabricator.py +234 -0
  12. hackbot_runtime/actions/recorder.py +146 -0
  13. hackbot_runtime/actions/slack.py +101 -0
  14. hackbot_runtime/actions/testrail.py +206 -0
  15. hackbot_runtime/actions/tools.py +46 -0
  16. hackbot_runtime/actions/try_server.py +166 -0
  17. hackbot_runtime/artifacts.py +89 -0
  18. hackbot_runtime/changes.py +431 -0
  19. hackbot_runtime/claude.py +96 -0
  20. hackbot_runtime/codex.py +366 -0
  21. hackbot_runtime/config.py +82 -0
  22. hackbot_runtime/context.py +362 -0
  23. hackbot_runtime/errors.py +7 -0
  24. hackbot_runtime/providers.py +46 -0
  25. hackbot_runtime/pull_request.py +130 -0
  26. hackbot_runtime/results.py +13 -0
  27. hackbot_runtime/revision.py +238 -0
  28. hackbot_runtime/runtime.py +244 -0
  29. hackbot_runtime/searchfox.py +182 -0
  30. hackbot_runtime/slack_kit.py +51 -0
  31. hackbot_runtime/source.py +157 -0
  32. hackbot_runtime/tracing.py +230 -0
  33. hackbot_runtime/transcript.py +61 -0
  34. hackbot_runtime/uploader.py +76 -0
  35. hackbot_runtime/wif.py +359 -0
  36. hackbot_runtime-0.1.0.dist-info/METADATA +25 -0
  37. hackbot_runtime-0.1.0.dist-info/RECORD +38 -0
  38. hackbot_runtime-0.1.0.dist-info/WHEEL +4 -0
@@ -0,0 +1,238 @@
1
+ """Check an agent's source tree out at a Phabricator revision, stack included."""
2
+
3
+ import logging
4
+ import subprocess
5
+ from pathlib import Path
6
+ from typing import TYPE_CHECKING, NamedTuple
7
+
8
+ from phabricator_client import (
9
+ PhabricatorClient,
10
+ PhabricatorSettings,
11
+ UnresolvedCommitError,
12
+ )
13
+
14
+ from hackbot_runtime import changes
15
+
16
+ if TYPE_CHECKING:
17
+ from hackbot_runtime.context import HackbotContext
18
+
19
+ log = logging.getLogger(__name__)
20
+
21
+ # The broker mounts its read-only Conduit proxy here; PhabricatorClient appends
22
+ # `/api/<method>` the same way it would against a real Phabricator instance.
23
+ _PROXY_MOUNT = "/phabricator"
24
+
25
+ # The token the agent sends to the proxy. Not a secret — the proxy discards it
26
+ # and substitutes the real Conduit key — but it has to be *a* token, and
27
+ # PhabricatorSettings requires the 32 characters a real one has.
28
+ _PROXY_API_TOKEN = "hackbot-broker-proxy-placeholder"
29
+
30
+
31
+ class Patch(NamedTuple):
32
+ """One revision's latest diff, with what is needed to commit it as its own.
33
+
34
+ ``author`` is ``"Name <email>"`` from the commit the diff was built from, or
35
+ ``None`` when Phabricator has none to give (a diff uploaded through the web
36
+ UI, say).
37
+ """
38
+
39
+ revision_id: int
40
+ title: str
41
+ raw_diff: str
42
+ author: str | None
43
+
44
+ @property
45
+ def commit_message(self) -> str:
46
+ """A message that says which revision the change came from, and why.
47
+
48
+ The revisions below the target get a commit each rather than one
49
+ squashed lump, so that reading `git log` or `git blame` in the checkout
50
+ attributes each change to the revision it came from instead of to
51
+ hackbot.
52
+ """
53
+ return (
54
+ f"D{self.revision_id}: {self.title}\n\n"
55
+ "Replayed by hackbot from Phabricator to rebuild the base of the "
56
+ "revision it was asked to work on. Not the original commit."
57
+ )
58
+
59
+
60
+ class Stack(NamedTuple):
61
+ """Everything needed to reproduce a revision's tree, oldest first.
62
+
63
+ ``base_commit`` is a full, fetchable hash: the landed commit underneath the
64
+ whole stack. ``ancestors`` are the unlanded revisions between that commit
65
+ and ``target``, and is empty when the revision is not stacked on anything.
66
+ """
67
+
68
+ base_commit: str
69
+ ancestors: list[Patch]
70
+ target: Patch
71
+
72
+
73
+ async def checkout_revision(
74
+ ctx: HackbotContext,
75
+ revision_id: int,
76
+ broker_url: str,
77
+ depth: int | None = None,
78
+ ) -> None:
79
+ """Prepare the source so it matches ``D<revision_id>`` before the agent runs.
80
+
81
+ Raises :class:`RuntimeError` if the stack cannot be resolved or a diff does
82
+ not apply, so the run fails visibly rather than editing the wrong tree.
83
+ """
84
+ client = PhabricatorClient(
85
+ PhabricatorSettings(
86
+ url=f"{broker_url.rstrip('/')}{_PROXY_MOUNT}",
87
+ api_key=_PROXY_API_TOKEN,
88
+ )
89
+ )
90
+ stack = await _resolve_stack(client, revision_id)
91
+
92
+ # Prepare the checkout explicitly at the stack's base commit. Must run
93
+ # before anything else touches the source (prepare_repo raises otherwise).
94
+ repo = await ctx.prepare_repo(ref=stack.base_commit, depth=depth)
95
+ log.info(
96
+ "Checking out D%s (base %s) before running the agent",
97
+ revision_id,
98
+ stack.base_commit,
99
+ )
100
+
101
+ if stack.ancestors:
102
+ below = ", ".join(f"D{patch.revision_id}" for patch in stack.ancestors)
103
+ log.info("D%s is stacked on %s; replaying them first", revision_id, below)
104
+ for patch in stack.ancestors:
105
+ _apply(repo, patch)
106
+
107
+ # Whatever was seeded above is the agent's starting point, not its work.
108
+ ctx.record_source_base()
109
+
110
+ _apply(repo, stack.target, should_commit=False)
111
+
112
+
113
+ async def _resolve_stack(client: PhabricatorClient, revision_id: int) -> Stack:
114
+ """Collect the patches reproducing ``D<revision_id>``, bottom of the stack up."""
115
+ target = await client.search_revision_by_id(revision_id)
116
+ if target is None:
117
+ raise RuntimeError(f"D{revision_id} not found")
118
+
119
+ ancestors = await _live_ancestors(client, target)
120
+ ordered = [*ancestors, target]
121
+
122
+ base: str | None = None
123
+ patches: list[Patch] = []
124
+ for revision in ordered:
125
+ diff = await client.query_latest_diff(revision["id"])
126
+ if diff is None:
127
+ raise RuntimeError(f"D{revision['id']} has no diffs to apply")
128
+ if base is None:
129
+ # Only the bottom revision's base matters: everything above it is
130
+ # reproduced by replaying diffs, not by checking anything out.
131
+ if not diff.base_commit:
132
+ raise RuntimeError(
133
+ f"D{revision['id']} records no base commit; nothing to apply onto."
134
+ )
135
+ # Expand it: moz-phab records an abbreviated hash for a repo the
136
+ # size of firefox, and git can only fetch a full object id.
137
+ try:
138
+ base = await client.resolve_commit(diff.base_commit)
139
+ except UnresolvedCommitError:
140
+ if not diff.first_public_parent:
141
+ raise
142
+ log.info(
143
+ "D%s base %s is not imported; using first public parent %s.",
144
+ revision["id"],
145
+ diff.base_commit,
146
+ diff.first_public_parent,
147
+ )
148
+ base = await client.resolve_commit(diff.first_public_parent)
149
+
150
+ patches.append(
151
+ Patch(
152
+ revision_id=revision["id"],
153
+ title=revision["fields"].get("title") or "",
154
+ raw_diff=await client.get_raw_diff(diff.id),
155
+ author=diff.author,
156
+ )
157
+ )
158
+
159
+ return Stack(base_commit=base, ancestors=patches[:-1], target=patches[-1])
160
+
161
+
162
+ def _ancestor_phids(stack_graph: dict[str, list[str]], target_phid: str) -> list[str]:
163
+ """Walk a revision's ancestors in ``stackGraph``, direct parent first.
164
+
165
+ ``stackGraph`` maps each revision in the stack to its parents, and is part
166
+ of what ``differential.revision.search`` returns. Only a linear chain can be
167
+ replayed as a sequence of patches, so anything else is refused: more than
168
+ one parent, or a cycle.
169
+
170
+ ``moz-phab patch`` stops the walk instead of refusing on a cycle, which
171
+ leaves it patching a truncated stack. Refusing is the deliberate difference:
172
+ a cycle has no oldest-first order, so a truncated one would be applied onto
173
+ the wrong base, and the point of this module is to fail rather than hand the
174
+ agent a tree that is not the revision.
175
+ """
176
+ ancestors: list[str] = []
177
+ seen = {target_phid}
178
+ current = target_phid
179
+ while True:
180
+ parents = stack_graph.get(current) or []
181
+ if not parents:
182
+ return ancestors
183
+ if len(parents) > 1:
184
+ raise RuntimeError(
185
+ "hackbot cannot reconstruct a non-linear stack: "
186
+ f"{current} has {len(parents)} parents."
187
+ )
188
+ parent = parents[0]
189
+ if parent in seen:
190
+ raise RuntimeError(
191
+ "hackbot cannot reconstruct a stack that depends on itself: "
192
+ f"{parent} is already below {target_phid}."
193
+ )
194
+ seen.add(parent)
195
+ ancestors.append(parent)
196
+ current = parent
197
+
198
+
199
+ async def _live_ancestors(client: PhabricatorClient, target: dict) -> list[dict]:
200
+ """The revisions below ``target`` worth replaying, oldest first.
201
+
202
+ Abandoned ancestors are dropped, as are any Conduit does not return (an
203
+ unreadable revision, say) — the same choice ``moz-phab patch`` makes. When
204
+ one in the middle of the stack goes, the remaining diffs will not apply and
205
+ :func:`_apply` reports which revision failed.
206
+ """
207
+ phids = _ancestor_phids(target["fields"]["stackGraph"], target["phid"])
208
+ if not phids:
209
+ return []
210
+ by_phid = {rev["phid"]: rev for rev in await client.search_revisions(phids)}
211
+ return [
212
+ by_phid[phid]
213
+ for phid in reversed(phids) # root first, direct parent last
214
+ if phid in by_phid and by_phid[phid]["fields"]["status"]["value"] != "abandoned"
215
+ ]
216
+
217
+
218
+ def _apply(repo: Path, patch: Patch, should_commit: bool = True) -> None:
219
+ """Apply one revision's diff to ``repo``'s working tree."""
220
+ result = subprocess.run(
221
+ ["git", "-C", str(repo), "apply"],
222
+ input=patch.raw_diff.encode(),
223
+ capture_output=True,
224
+ )
225
+ if result.returncode != 0:
226
+ # By far the likeliest cause is a stack whose parent was updated without
227
+ # its children being rebased: each revision's latest diff is applied in
228
+ # order, so a diff written against an older version of the one below it
229
+ # will not match. Nothing hackbot can retry fixes that.
230
+ raise RuntimeError(
231
+ f"Could not apply the diff for D{patch.revision_id}: "
232
+ f"{result.stderr.decode().strip()}. If the revisions below it were "
233
+ "updated without this one being rebased onto them, that stack has "
234
+ "to be rebased before hackbot can reproduce it."
235
+ )
236
+
237
+ if should_commit:
238
+ changes.commit_all(repo, patch.commit_message, author=patch.author)
@@ -0,0 +1,244 @@
1
+ import asyncio
2
+ import contextlib
3
+ import inspect
4
+ import logging
5
+ import os
6
+ import sys
7
+ import traceback
8
+ from collections.abc import Awaitable, Callable, Iterator
9
+ from pathlib import Path
10
+ from typing import NoReturn
11
+
12
+ import sentry_sdk
13
+ from pydantic import ValidationError
14
+
15
+ from hackbot_runtime import wif
16
+ from hackbot_runtime.config import HackbotConfig, load_config
17
+ from hackbot_runtime.context import HackbotContext
18
+ from hackbot_runtime.results import HackbotAgentResult
19
+ from hackbot_runtime.tracing import resolve_agent_name, trace_agent
20
+
21
+ log = logging.getLogger("hackbot_runtime")
22
+
23
+ # An agent's main() returns a HackbotAgentResult on success; to fail the run it
24
+ # raises (AgentError, or any exception). The runtime turns that outcome into
25
+ # summary.json + an exit code.
26
+ Findings = HackbotAgentResult
27
+ AgentMain = Callable[[HackbotContext], Findings]
28
+ AsyncAgentMain = Callable[[HackbotContext], Awaitable[Findings]]
29
+
30
+ # What run()/run_async() accept to locate an agent's hackbot.toml: a path to it,
31
+ # an already-parsed config, or None to auto-discover ``hackbot.toml`` (in the
32
+ # working directory or above the entry point's module).
33
+ ConfigArg = Path | HackbotConfig | None
34
+
35
+ _CONFIG_NAME = "hackbot.toml"
36
+ _SUMMARY_NAME = "summary.json"
37
+ _AGENT_LOG_KEY = "logs/agent.log"
38
+
39
+
40
+ @contextlib.contextmanager
41
+ def _configure_auth() -> Iterator[None]:
42
+ """Set up the model-provider credentials for the run.
43
+
44
+ Anthropic and OpenAI both support GCP Workload Identity Federation, so in
45
+ deployment neither needs a long-lived key in the agent container; each falls
46
+ back to its API-key env var locally.
47
+ """
48
+ anthropic_config = wif.AnthropicWifSettings.from_env()
49
+ openai_config = wif.OpenAIWifSettings.from_env()
50
+
51
+ with wif.configure(anthropic_config), wif.configure(openai_config):
52
+ yield
53
+
54
+
55
+ def _configure_sentry(entrypoint: Callable) -> None:
56
+ dsn = os.environ.get("SENTRY_DSN")
57
+ if not dsn:
58
+ return
59
+ sentry_sdk.init(dsn=dsn)
60
+ sentry_sdk.set_tag("agent", resolve_agent_name(entrypoint))
61
+
62
+
63
+ def _configure_logging() -> None:
64
+ if not logging.getLogger().handlers:
65
+ logging.basicConfig(
66
+ level=logging.INFO,
67
+ stream=sys.stderr,
68
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
69
+ )
70
+
71
+
72
+ def _ok_payload(ctx: HackbotContext, findings: dict) -> dict:
73
+ # Actions are recorded via ctx.actions; the agent never carries them.
74
+ return {
75
+ "status": "ok",
76
+ "error": None,
77
+ "findings": findings,
78
+ "actions": ctx.actions.list_actions(),
79
+ }
80
+
81
+
82
+ def _error_payload(
83
+ ctx: HackbotContext, error: str, *, traceback_str: str | None = None
84
+ ) -> dict:
85
+ return {
86
+ "status": "error",
87
+ "error": error,
88
+ "findings": {"traceback": traceback_str} if traceback_str else {},
89
+ "actions": ctx.actions.list_actions(),
90
+ }
91
+
92
+
93
+ def _discover_config_path(entrypoint: Callable) -> Path | None:
94
+ """Locate ``hackbot.toml`` for an agent that didn't pass one explicitly.
95
+
96
+ Agents keep ``hackbot.toml`` at their agent root (alongside ``pyproject.toml``
97
+ / ``Dockerfile``), above the ``hackbot_agents`` package. Two layouts to cover:
98
+
99
+ - **Deployed image**: the package is installed into site-packages, but the
100
+ Dockerfile copies ``hackbot.toml`` into the working directory — so check
101
+ the cwd first.
102
+ - **Editable checkout / tests**: the entry point's module lives under the
103
+ agent root, so walk up from it until the toml turns up.
104
+ """
105
+ cwd_candidate = Path.cwd() / _CONFIG_NAME
106
+ if cwd_candidate.exists():
107
+ return cwd_candidate
108
+ try:
109
+ module_file = inspect.getsourcefile(entrypoint)
110
+ except TypeError:
111
+ module_file = None
112
+ if module_file:
113
+ for parent in Path(module_file).resolve().parents:
114
+ candidate = parent / _CONFIG_NAME
115
+ if candidate.exists():
116
+ return candidate
117
+ return None
118
+
119
+
120
+ def _resolve_config(entrypoint: Callable, config: ConfigArg) -> HackbotConfig:
121
+ if isinstance(config, HackbotConfig):
122
+ parsed = config
123
+ else:
124
+ path = config if isinstance(config, Path) else _discover_config_path(entrypoint)
125
+ parsed = load_config(path) if path else HackbotConfig()
126
+ parsed.agent_name = resolve_agent_name(entrypoint)
127
+ return parsed
128
+
129
+
130
+ def _load_hackbot(entrypoint: Callable, config: ConfigArg) -> HackbotContext | None:
131
+ """Build the HackbotContext (and its inner env-derived Context).
132
+
133
+ ``config`` may be a path to a ``hackbot.toml``, an already-parsed
134
+ :class:`HackbotConfig`, or ``None`` to auto-discover the toml (cwd or above
135
+ the entry point's module), falling back to an empty config when there's none.
136
+ """
137
+ parsed = _resolve_config(entrypoint, config)
138
+ try:
139
+ return HackbotContext.from_config_obj(parsed)
140
+ except ValidationError as exc:
141
+ log.error(
142
+ "Failed to load HackbotContext from env; no summary can be written.\n%s",
143
+ exc,
144
+ )
145
+ return None
146
+
147
+
148
+ def _publish_log(ctx: HackbotContext) -> None:
149
+ """Publish the run log under the canonical key, if the agent wrote one."""
150
+ if ctx.log_path.exists():
151
+ ctx.publish_file(_AGENT_LOG_KEY, ctx.log_path, "text/plain; charset=utf-8")
152
+
153
+
154
+ def _finish(ctx: HackbotContext, outcome: object) -> int:
155
+ """Write summary.json from the agent's outcome and return the exit code.
156
+
157
+ ``outcome`` is the agent's :class:`HackbotAgentResult` on success, or the
158
+ exception it raised on failure.
159
+ """
160
+ if isinstance(outcome, BaseException):
161
+ payload = _error_payload(
162
+ ctx,
163
+ f"{type(outcome).__name__}: {outcome}",
164
+ traceback_str=traceback.format_exc(),
165
+ )
166
+ exit_code = 1
167
+ elif isinstance(outcome, HackbotAgentResult):
168
+ payload = _ok_payload(ctx, outcome.model_dump())
169
+ exit_code = 0
170
+ else:
171
+ # Contract violation: not a HackbotAgentResult or an exception.
172
+ msg = f"Agent returned {type(outcome).__name__}; expected a HackbotAgentResult"
173
+ log.error(msg)
174
+ payload = _error_payload(ctx, msg)
175
+ exit_code = 1
176
+ payload["agent_version"] = ctx.config.agent_version
177
+
178
+ try:
179
+ _publish_log(ctx)
180
+ except Exception:
181
+ log.exception("Failed to publish agent log")
182
+
183
+ try:
184
+ ctx.publish_changes()
185
+ except Exception:
186
+ log.exception("Failed to publish source changes")
187
+
188
+ # Upload when a signed policy is configured, else write into the local
189
+ # artifacts dir (so local/compose/direct runs leave it on the host).
190
+ try:
191
+ ctx.publish_json(_SUMMARY_NAME, payload)
192
+ except Exception:
193
+ log.exception("Failed to publish summary.json")
194
+ return 1 if exit_code == 0 else exit_code
195
+
196
+ if ctx.uploader is None:
197
+ log.info(
198
+ "RESULTS_POLICY_URL not configured; wrote summary to %s.",
199
+ ctx.run_artifacts_dir / _SUMMARY_NAME,
200
+ )
201
+
202
+ return exit_code
203
+
204
+
205
+ def run(entrypoint: AgentMain, config: ConfigArg = None) -> NoReturn:
206
+ _configure_sentry(entrypoint)
207
+ _configure_logging()
208
+ ctx = _load_hackbot(entrypoint, config)
209
+ if ctx is None:
210
+ raise SystemExit(2)
211
+ sentry_sdk.set_tag("run_id", ctx.run_id)
212
+
213
+ try:
214
+ with _configure_auth():
215
+ if ctx.parent_run_id:
216
+ ctx.fetch_parent_artifacts()
217
+ with trace_agent(entrypoint, ctx.run_id, ctx.config.tracing.weave_project):
218
+ outcome: object = entrypoint(ctx)
219
+ except Exception as exc:
220
+ log.exception("Agent raised an exception")
221
+ outcome = exc
222
+
223
+ raise SystemExit(_finish(ctx, outcome))
224
+
225
+
226
+ def run_async(entrypoint: AsyncAgentMain, config: ConfigArg = None) -> NoReturn:
227
+ _configure_sentry(entrypoint)
228
+ _configure_logging()
229
+ ctx = _load_hackbot(entrypoint, config)
230
+ if ctx is None:
231
+ raise SystemExit(2)
232
+ sentry_sdk.set_tag("run_id", ctx.run_id)
233
+
234
+ try:
235
+ with _configure_auth():
236
+ if ctx.parent_run_id:
237
+ ctx.fetch_parent_artifacts()
238
+ with trace_agent(entrypoint, ctx.run_id, ctx.config.tracing.weave_project):
239
+ outcome: object = asyncio.run(entrypoint(ctx))
240
+ except Exception as exc:
241
+ log.exception("Agent raised an exception")
242
+ outcome = exc
243
+
244
+ raise SystemExit(_finish(ctx, outcome))
@@ -0,0 +1,182 @@
1
+ """Expand Searchfox permalink placeholders in recorded Bugzilla comments.
2
+
3
+ A permalink pins a file to a revision, so a source reference in a triage comment
4
+ keeps pointing at the code that was actually reasoned about even after the tree
5
+ moves on. Rather than have the agent write (and risk mangling) a 40-character
6
+ SHA, it writes a placeholder and this module substitutes the prefix:
7
+
8
+ [browser/base/content/browser.js#412]({{searchfox.permalink}}/browser/base/content/browser.js#412)
9
+
10
+ Mirrors the ``{{actions.<action_id>.url}}`` convention, but expands at *record* time
11
+ rather than apply time: unlike a prior action's result, the revision is known
12
+ before the agent runs, and expanding early means the comment awaiting review in
13
+ ``summary.json`` shows the real URLs a human can click.
14
+ """
15
+
16
+ import logging
17
+ import re
18
+ from collections.abc import Callable
19
+ from pathlib import Path
20
+
21
+ log = logging.getLogger(__name__)
22
+
23
+ # Searchfox renamed the Firefox tree from "mozilla-central" to "firefox-main"
24
+ # when it moved to git; the old name only 301-redirects.
25
+ TREE = "firefox-main"
26
+
27
+ _BASE_URL = f"https://searchfox.org/{TREE}"
28
+ _USER_AGENT = "bugbug-hackbot-runtime"
29
+
30
+ PLACEHOLDER = "{{searchfox.permalink}}"
31
+ # Tolerate inner whitespace — the agent writes this by hand.
32
+ _PLACEHOLDER = r"\{\{\s*searchfox\.permalink\s*\}\}"
33
+ # The placeholder as the whole URL of a Markdown link, so an unresolvable target
34
+ # can be degraded by unwrapping the link rather than just dropping its href.
35
+ _LINKED_PLACEHOLDER_RE = re.compile(
36
+ rf"\[(?P<label>[^\]\n]*)\]\(\s*{_PLACEHOLDER}(?P<target>[^)\s]*)\s*\)"
37
+ )
38
+ # The placeholder anywhere else, with whatever path the agent appended to it.
39
+ _BARE_PLACEHOLDER_RE = re.compile(rf"{_PLACEHOLDER}(?P<target>\S*)")
40
+
41
+ # Every Searchfox *file* page carries the permalink its own UI would produce, as
42
+ # the href of the "Create a revision-specific link" panel item — which is the
43
+ # revision the index was built from. Any stable file works as the probe; a
44
+ # top-level moz.build is about as permanent as the tree gets.
45
+ _PROBE_PATH = "toolkit/moz.build"
46
+ _PROBE_URL = f"{_BASE_URL}/source/{_PROBE_PATH}"
47
+ _PANEL_PERMALINK_RE = re.compile(
48
+ rf'<a id="panel-permalink" href="/{TREE}/rev/(?P<rev>[0-9a-f]{{40}})/'
49
+ )
50
+
51
+
52
+ def permalink_prefix(rev: str | None) -> str:
53
+ """The URL prefix :data:`PLACEHOLDER` expands to.
54
+
55
+ With no revision this degrades to Searchfox's revision-agnostic ``/source/``
56
+ prefix: still a working link to the right file, just following the tip
57
+ instead of pinned. That beats leaving an unexpanded placeholder (or a bare
58
+ path) in a comment a human is about to read.
59
+ """
60
+ return f"{_BASE_URL}/rev/{rev}" if rev else f"{_BASE_URL}/source"
61
+
62
+
63
+ async def resolve_index_revision(*, client=None, timeout: float = 10.0) -> str | None:
64
+ """Return the git SHA Searchfox's index is pinned to, or ``None``.
65
+
66
+ Reads the permalink Searchfox publishes on a file page, so the revision is
67
+ by construction one Searchfox can serve.
68
+
69
+ Note this is deliberately *not* the checked-out repo's base commit. Searchfox
70
+ only serves ``/rev/<sha>`` for revisions it has indexed, and its index runs
71
+ behind the tip of ``firefox.git`` by hours (83 commits / ~20h when measured);
72
+ the checkout's HEAD therefore 500s for about a day after a run — exactly the
73
+ window in which someone reads the triage comment.
74
+
75
+ Never raises: a caller that cannot get a revision should fall back to a
76
+ revision-agnostic link rather than fail its run. ``client`` accepts an
77
+ httpx-like async client for testing; when omitted, ``httpx`` is used.
78
+ """
79
+ try:
80
+ if client is None:
81
+ import httpx
82
+
83
+ async with httpx.AsyncClient(
84
+ timeout=timeout, follow_redirects=True
85
+ ) as owned:
86
+ resp = await owned.get(_PROBE_URL, headers={"User-Agent": _USER_AGENT})
87
+ else:
88
+ resp = await client.get(_PROBE_URL, headers={"User-Agent": _USER_AGENT})
89
+ if resp.status_code != 200:
90
+ log.warning("searchfox %s returned HTTP %s", _PROBE_PATH, resp.status_code)
91
+ return None
92
+ match = _PANEL_PERMALINK_RE.search(resp.text)
93
+ except Exception as e:
94
+ log.warning("could not resolve the searchfox index revision: %s", e)
95
+ return None
96
+
97
+ if match is None:
98
+ log.warning("no permalink found on the searchfox %s page", _PROBE_PATH)
99
+ return None
100
+ return match.group("rev")
101
+
102
+
103
+ def _join(prefix: str, target: str) -> str:
104
+ if not target:
105
+ return prefix.rstrip("/")
106
+ return f"{prefix.rstrip('/')}/{target.lstrip('/')}"
107
+
108
+
109
+ def _target_path(target: str) -> str:
110
+ """The repo-relative path in a placeholder target, minus any ``#`` anchor."""
111
+ return target.lstrip("/").split("#", 1)[0]
112
+
113
+
114
+ def expand_placeholders(
115
+ text: str, prefix: str, *, repo_root: Path | None = None
116
+ ) -> str:
117
+ """Replace every :data:`PLACEHOLDER` in ``text`` with ``prefix``.
118
+
119
+ With ``repo_root``, a placeholder whose path does not exist in the checkout
120
+ is *not* linked: a Markdown link is unwrapped to its backticked label, and a
121
+ bare placeholder degrades to its backticked path. Models do occasionally
122
+ name a file that isn't there, and a plausible-looking permalink to a
123
+ nonexistent path is worse than plain text — it 404s for whoever clicks it.
124
+
125
+ The check is a heuristic, not a proof: the checkout and the revision the
126
+ links are pinned to are hours apart, so a file added in between exists
127
+ locally but not on Searchfox (and one deleted in between, vice versa). It
128
+ catches the common case, which is an invented path.
129
+ """
130
+
131
+ def _linkable(target: str) -> bool:
132
+ if repo_root is None:
133
+ return True
134
+ path = _target_path(target)
135
+ # Nothing to verify (bare placeholder, or anchor only) — let it expand.
136
+ return not path or (repo_root / path).is_file()
137
+
138
+ def _link(match: re.Match[str]) -> str:
139
+ label, target = match.group("label"), match.group("target")
140
+ if _linkable(target):
141
+ return f"[{label}]({_join(prefix, target)})"
142
+ log.warning(
143
+ "not linking %r: no such file in the checkout (left as plain text)",
144
+ _target_path(target),
145
+ )
146
+ return f"`{label}`"
147
+
148
+ def _bare(match: re.Match[str]) -> str:
149
+ target = match.group("target")
150
+ if _linkable(target):
151
+ return _join(prefix, target)
152
+ log.warning(
153
+ "not linking %r: no such file in the checkout (left as plain text)",
154
+ _target_path(target),
155
+ )
156
+ return f"`{target.lstrip('/')}`"
157
+
158
+ # Links first, so their placeholders are consumed before the bare pass.
159
+ text = _LINKED_PLACEHOLDER_RE.sub(_link, text)
160
+ return _BARE_PLACEHOLDER_RE.sub(_bare, text)
161
+
162
+
163
+ def permalink_hook(
164
+ prefix: str, repo_root: Path | None = None
165
+ ) -> Callable[[dict], None]:
166
+ """An action hook that expands permalink placeholders in a comment's text.
167
+
168
+ Register for ``bugzilla.add_comment``; the recorded comment then carries real
169
+ URLs instead of placeholders. ``repo_root`` is the agent's source checkout,
170
+ used to skip linking paths that do not exist (see
171
+ :func:`expand_placeholders`).
172
+ """
173
+
174
+ def hook(action: dict) -> None:
175
+ params = action.get("params")
176
+ if not isinstance(params, dict):
177
+ return
178
+ text = params.get("text")
179
+ if isinstance(text, str):
180
+ params["text"] = expand_placeholders(text, prefix, repo_root=repo_root)
181
+
182
+ return hook