Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(github): ignore codeblocks for pr task matching (#5328)

Will Hutchinson91417ab9f62e
diff --git a/crates/github/src/domain/models/mod.rs b/crates/github/src/domain/models/mod.rs
index 0fe78fb81a..794baa50f9 100644
--- a/crates/github/src/domain/models/mod.rs
+++ b/crates/github/src/domain/models/mod.rs
@@ -17,7 +17,7 @@ pub use pull_request::{
pub use sync::{
GithubAppInstallationSource, GithubInstallationAccessToken, GithubKey, GithubWebhookEventType,
MacroTaskId, ResolvedTeamTaskReference, TeamTaskReference, ValidatedGithubWebhookEvent,
- extract_github_mentions,
+ extract_github_mentions, strip_markdown_code,
};
/// Errors that can occur during github operations.
#[derive(Debug, thiserror::Error)]
diff --git a/crates/github/src/domain/models/sync.rs b/crates/github/src/domain/models/sync.rs
index b5011242f6..f954f74d43 100644
--- a/crates/github/src/domain/models/sync.rs
+++ b/crates/github/src/domain/models/sync.rs
@@ -90,16 +90,22 @@ impl ValidatedGithubWebhookEvent {
}
/// Extract all text fields worth searching for task IDs, based on event type.
+ ///
+ /// Markdown code (fenced blocks and inline spans) is stripped from prose
+ /// fields before they are returned: quoted diffs and code snippets are full
+ /// of `identifier-number` tokens (e.g. the Tailwind class `py-6`) that must
+ /// never be mistaken for task references. Branch names are kept verbatim —
+ /// they cannot contain markdown.
pub fn extract_searchable_text(&self) -> Vec<String> {
let mut texts = Vec::new();
match self.parsed_event_type() {
GithubWebhookEventType::PullRequest => {
if let Some(pr) = self.payload.get("pull_request") {
if let Some(s) = pr.get("title").and_then(|v| v.as_str()) {
- texts.push(s.to_string());
+ texts.push(strip_markdown_code(s));
}
if let Some(s) = pr.get("body").and_then(|v| v.as_str()) {
- texts.push(s.to_string());
+ texts.push(strip_markdown_code(s));
}
if let Some(s) = pr
.get("head")
@@ -118,7 +124,7 @@ impl ValidatedGithubWebhookEvent {
.and_then(|c| c.get("body"))
.and_then(|v| v.as_str())
{
- texts.push(s.to_string());
+ texts.push(strip_markdown_code(s));
}
}
GithubWebhookEventType::PullRequestReview => {
@@ -128,7 +134,7 @@ impl ValidatedGithubWebhookEvent {
.and_then(|r| r.get("body"))
.and_then(|v| v.as_str())
{
- texts.push(s.to_string());
+ texts.push(strip_markdown_code(s));
}
}
GithubWebhookEventType::CheckRun
@@ -292,10 +298,10 @@ impl ValidatedGithubWebhookEvent {
if let Some(pr) = pr {
if let Some(s) = pr.get("title").and_then(|v| v.as_str()) {
- texts.push(s.to_string());
+ texts.push(strip_markdown_code(s));
}
if let Some(s) = pr.get("body").and_then(|v| v.as_str()) {
- texts.push(s.to_string());
+ texts.push(strip_markdown_code(s));
}
if let Some(s) = pr
.get("head")
@@ -310,6 +316,114 @@ impl ValidatedGithubWebhookEvent {
}
}
+/// Remove markdown code from text before task reference extraction: fenced
+/// code blocks (``` or ~~~) and inline code spans (`...`).
+///
+/// Code-formatted text is where `identifier-number` tokens live — quoted
+/// diffs, CSS utility classes like `py-6`, config keys — and those must never
+/// be mistaken for team task references. Removed spans are replaced with a
+/// single space so the surrounding prose keeps its token boundaries.
+pub fn strip_markdown_code(text: &str) -> String {
+ strip_inline_code_spans(&strip_fenced_code_blocks(text))
+}
+
+/// Returns the fence marker (character and run length) opening or closing a
+/// fenced code block on this line, if any.
+fn fence_marker(line: &str) -> Option<(char, usize)> {
+ let trimmed = line.trim_start();
+ let first = trimmed.chars().next()?;
+ if first != '`' && first != '~' {
+ return None;
+ }
+ let run = trimmed.chars().take_while(|c| *c == first).count();
+ (run >= 3).then_some((first, run))
+}
+
+/// Drop every line belonging to a fenced code block, fences included. An
+/// unclosed fence swallows the rest of the text, matching how markdown
+/// renders it.
+fn strip_fenced_code_blocks(text: &str) -> String {
+ let mut kept = Vec::new();
+ let mut open_fence: Option<(char, usize)> = None;
+
+ for line in text.lines() {
+ match (open_fence, fence_marker(line)) {
+ // Closing fence: same character, at least as long, nothing else on
+ // the line after the marker.
+ (Some((open_char, open_run)), Some((close_char, close_run)))
+ if close_char == open_char
+ && close_run >= open_run
+ && line
+ .trim_start()
+ .trim_start_matches(open_char)
+ .trim()
+ .is_empty() =>
+ {
+ open_fence = None;
+ }
+ (Some(_), _) => {}
+ (None, Some(marker)) => {
+ open_fence = Some(marker);
+ }
+ (None, None) => kept.push(line),
+ }
+ }
+
+ kept.join("\n")
+}
+
+/// Drop inline code spans: a run of N backticks closed by the next run of
+/// exactly N backticks (CommonMark semantics). Unmatched backtick runs are
+/// kept as literal text.
+fn strip_inline_code_spans(text: &str) -> String {
+ let chars: Vec<char> = text.chars().collect();
+ let mut out = String::with_capacity(text.len());
+ let mut i = 0;
+
+ while i < chars.len() {
+ if chars[i] != '`' {
+ out.push(chars[i]);
+ i += 1;
+ continue;
+ }
+
+ let open_run = chars[i..].iter().take_while(|c| **c == '`').count();
+ let span_start = i + open_run;
+
+ // Find the next backtick run of exactly `open_run` length.
+ let mut j = span_start;
+ let mut close_at = None;
+ while j < chars.len() {
+ if chars[j] == '`' {
+ let run = chars[j..].iter().take_while(|c| **c == '`').count();
+ if run == open_run {
+ close_at = Some(j);
+ break;
+ }
+ j += run;
+ } else {
+ j += 1;
+ }
+ }
+
+ match close_at {
+ Some(close) => {
+ out.push(' ');
+ i = close + open_run;
+ }
+ None => {
+ // No closer: keep the backticks as literal text.
+ for _ in 0..open_run {
+ out.push('`');
+ }
+ i = span_start;
+ }
+ }
+ }
+
+ out
+}
+
/// Known GitHub webhook event types we handle.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GithubWebhookEventType {
diff --git a/crates/github/src/domain/models/test.rs b/crates/github/src/domain/models/test.rs
index c8856a2889..d9a6a74f98 100644
--- a/crates/github/src/domain/models/test.rs
+++ b/crates/github/src/domain/models/test.rs
@@ -934,6 +934,93 @@ fn extract_text_unknown_event() {
assert!(texts.is_empty());
}
+// ---------------------------------------------------------------------------
+// strip_markdown_code
+// ---------------------------------------------------------------------------
+
+#[test]
+fn strip_markdown_code_removes_inline_spans() {
+ let stripped = strip_markdown_code("switch the sidebar to `py-6` for spacing");
+ assert_eq!(stripped, "switch the sidebar to for spacing");
+ assert!(TeamTaskReference::extract_from_text(&stripped).is_empty());
+}
+
+#[test]
+fn strip_markdown_code_removes_fenced_blocks() {
+ let text = "Adjust padding:\n```css\n.sidebar { @apply py-6 px-4; }\n```\nDone.";
+ let stripped = strip_markdown_code(text);
+ assert_eq!(stripped, "Adjust padding:\nDone.");
+ assert!(TeamTaskReference::extract_from_text(&stripped).is_empty());
+}
+
+#[test]
+fn strip_markdown_code_removes_tilde_fences_and_language_tags() {
+ let text = "before\n~~~diff\n- pt-4\n+ py-6\n~~~\nafter";
+ assert_eq!(strip_markdown_code(text), "before\nafter");
+}
+
+#[test]
+fn strip_markdown_code_unclosed_fence_swallows_rest() {
+ let text = "intro\n```\npy-6 and db-27 live here";
+ assert_eq!(strip_markdown_code(text), "intro");
+}
+
+#[test]
+fn strip_markdown_code_double_backtick_spans() {
+ let stripped = strip_markdown_code("use ``a `py-6` class`` here");
+ assert_eq!(stripped, "use here");
+}
+
+#[test]
+fn strip_markdown_code_keeps_unmatched_backticks_and_prose_refs() {
+ let stripped = strip_markdown_code("odd ` backtick, but PY-6 stays a reference");
+ assert_eq!(stripped, "odd ` backtick, but PY-6 stays a reference");
+ assert_eq!(
+ TeamTaskReference::extract_from_text(&stripped),
+ vec![TeamTaskReference::new("py", 6).unwrap()]
+ );
+}
+
+#[test]
+fn strip_markdown_code_plain_text_unchanged() {
+ let text = "fixes py-6 and db-27 in prose";
+ assert_eq!(strip_markdown_code(text), text);
+}
+
+// Regression: dungeonbooks/guild#205 — a review quoting a Tailwind class list
+// (`py-6`) must not produce a task reference for a team with slug PY, while
+// the reference in the branch name still resolves.
+#[test]
+fn extract_text_strips_code_from_review_body() {
+ let payload = serde_json::json!({
+ "action": "submitted",
+ "review": {
+ "body": "Consider tightening the spacing:\n```tsx\n<aside class=\"py-6 px-4\">\n```\nOtherwise LGTM."
+ }
+ });
+ let event = ValidatedGithubWebhookEvent::new("pull_request_review".to_string(), payload);
+ let texts = event.extract_searchable_text();
+ assert_eq!(texts.len(), 1);
+ let refs = TeamTaskReference::extract_from_text(&texts.join(" "));
+ assert!(refs.is_empty());
+}
+
+#[test]
+fn extract_text_strips_code_from_pr_body_but_keeps_branch() {
+ let payload = serde_json::json!({
+ "action": "opened",
+ "pull_request": {
+ "title": "fix(dashboard): make the mobile sidebar dismissable",
+ "body": "Swap `pt-4` for `py-6` on the sheet container.",
+ "head": { "ref": "ptaranat/db-27-mobile-hard-to-tap-out-of-sidebar" }
+ }
+ });
+ let event = ValidatedGithubWebhookEvent::new("pull_request".to_string(), payload);
+ let texts = event.extract_searchable_text();
+ let refs = TeamTaskReference::extract_from_text(&texts.join(" "));
+ assert_eq!(refs, vec![TeamTaskReference::new("db", 27).unwrap()]);
+}
+
// ---------------------------------------------------------------------------
// ValidatedGithubWebhookEvent::extract_pr_context_text
// ---------------------------------------------------------------------------
diff --git a/crates/github/src/domain/service/sync/test.rs b/crates/github/src/domain/service/sync/test.rs
index 15fdf3abc6..4b86767306 100644
--- a/crates/github/src/domain/service/sync/test.rs
+++ b/crates/github/src/domain/service/sync/test.rs
@@ -1544,6 +1544,45 @@ async fn team_task_id_requires_installation_team_match() {
assert!(service.client.pr_comments().is_empty());
}
+// Regression for dungeonbooks/guild#205: a PR body/review quoting the
+// Tailwind class `py-6` in markdown code must not link team PY's task 6.
+#[tokio::test]
+async fn team_task_reference_inside_markdown_code_links_nothing() {
+ let task_id = MacroTaskId::from_uuid(&uuid::Uuid::parse_str(KNOWN_TASK_UUID).unwrap());
+ let team_id = uuid::Uuid::parse_str("eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee").unwrap();
+ let repo = StubSyncRepo::new().with_team_task_reference("12345", "py", 6, team_id, task_id);
+ let service = make_sync_service_with_repo(repo);
+
+ let event = ValidatedGithubWebhookEvent::new(
+ "pull_request".to_string(),
+ serde_json::json!({
+ "action": "opened",
+ "pull_request": {
+ "number": 205,
+ "title": "fix(dashboard): make the mobile sidebar dismissable",
+ "body": "Swap `pt-4` for `py-6` on the sheet container.\n```tsx\n<aside class=\"py-6 px-4\">\n```",
+ "head": { "ref": "ptaranat/mobile-sidebar-dismiss" }
+ },
+ "repository": {
+ "name": "guild",
+ "owner": { "login": "dungeonbooks" }
+ },
+ "installation": { "id": 12345 }
+ }),
+ );
+
+ let result = service.process_webhook_event(&event).await;
+ assert!(result.is_ok());
+
+ assert!(service.client.pr_comments().is_empty());
+ let tracked = service
+ .repo
+ .get_task_ids(GithubKey::new("dungeonbooks", "guild", 205))
+ .await
+ .unwrap();
+ assert!(tracked.is_empty());
+}
+
#[tokio::test]
async fn ambiguous_team_task_reference_links_nothing() {
// Two of the installation's teams share the slug "eng" (slugs are not