Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 66 additions & 7 deletions apps/discord_bot/src/five08/discord_bot/cogs/crm.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1345,6 +1345,10 @@ async def confirm_create(
create_payload = self.crm_cog._build_resume_create_contact_payload(
file_content=self.file_content
)
self.crm_cog._populate_name_fields(
create_payload,
source_name=str(create_payload.get("name", "")).strip(),
)
target_contact = self.crm_cog.espo_api.request(
"POST", "Contact", create_payload
)
Expand DownExpand Up@@ -1375,6 +1379,8 @@ async def confirm_create(
)
except Exception as exc:
status_code = getattr(self.crm_cog.espo_api, "status_code", None)
error_detail = str(exc).strip() or "Unknown error"
status_note = f" (status {status_code})" if status_code else ""
logger.exception(
"Failed to create contact from resume filename=%s target_scope=%s inferred_meta=%s status_code=%s payload=%s",
self.filename,
Expand All@@ -1399,7 +1405,7 @@ async def confirm_create(
metadata=audit_metadata,
)
await interaction.followup.send(
"⚠️ Could not create a contact from this resume. "
f"⚠️ Could not create a contact from this resume: `{error_detail}`{status_note}. "
"Please provide `search_term` or `link_user`.",
ephemeral=True,
Comment on lines 1407 to 1410

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The user-facing failure message embeds error_detail = str(exc) verbatim. For EspoAPIError raised by the shared client, this may include boilerplate (e.g., "Wrong request, status code is …") and can duplicate the separately-appended status note, making the message noisy. Consider special-casing EspoAPIError to extract/display just the server reason (and escape/truncate any backticks/newlines) while keeping the full exception details only in logs/audit metadata.

Copilot uses AI. Check for mistakes.
)
Expand DownExpand Up@@ -1532,6 +1538,11 @@ def __init__(self, bot: commands.Bot) -> None:
discord_logs_webhook_wait=settings.discord_logs_webhook_wait,
)

@staticmethod
def _configured_linkedin_field() -> str:
"""Return the configured field for LinkedIn profile values."""
return str(getattr(settings, "crm_linkedin_field", "cLinkedInUrl"))

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_configured_linkedin_field() reads settings.crm_linkedin_field, but the bot Settings model doesn’t declare this field (so Pydantic Settings won’t load it from env/config and it will always fall back). Also, if the attribute were ever present but None, str(None) would yield the literal string "None". Consider adding an explicit crm_linkedin_field: str = "cLinkedInUrl" to the Settings schema (and validating/stripping it here, falling back when empty).

Suggested change
returnstr(getattr(settings, "crm_linkedin_field", "cLinkedInUrl"))
default_field="cLinkedInUrl"
raw_value=getattr(settings, "crm_linkedin_field", None)
ifnotisinstance(raw_value, str):
returndefault_field
value=raw_value.strip()
returnvalueordefault_field

Copilot uses AI. Check for mistakes.

def _audit_command(
self,
*,
Expand DownExpand Up@@ -3280,6 +3291,26 @@ def _to_values(raw_values: Any) -> list[str]:

return "\nParsed resume identifiers: " + "; ".join(summary_parts)

def _build_resume_parsed_identity_summary(self, file_content: bytes) -> str:
"""Build a short display summary of parsed contact identity fields."""
hints = self._extract_resume_contact_hints(file_content)
parsed_name = str(hints.get("name") or "").strip()
if not parsed_name:
parsed_name = self._extract_resume_name_fallback(file_content)

emails = hints.get("emails", [])
if not isinstance(emails, list):
emails = []
primary_email = "No email parsed"
if emails:
raw_email = str(emails[0]).strip()
if raw_email:
primary_email = raw_email

return (
f"\nParsed contact details: name=`{parsed_name}`, email=`{primary_email}`"
)
Comment on lines +3309 to +3312

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The parsed name/email are interpolated directly into inline-code backticks. If the extracted name/email contains a backtick, it can break formatting and potentially hide/alter surrounding text. Consider sanitizing (e.g., replace/backslash-escape backticks and truncate to a safe length) before embedding user/LLM-derived values into Discord messages.

Copilot uses AI. Check for mistakes.

def _extract_resume_name_hint(self, file_content: bytes) -> str:
"""Best-effort contact name extraction from resume text."""
hints = self._extract_resume_contact_hints(file_content)
Expand All@@ -3288,6 +3319,18 @@ def _extract_resume_name_hint(self, file_content: bytes) -> str:
return extracted_name
return self._extract_resume_name_fallback(file_content)

def _populate_name_fields(
self, payload: dict[str, str], *, source_name: str
) -> None:
"""Populate firstName and lastName fields for CRM contact creation payloads."""
first_name, last_name = self.resume_extractor.split_name(
full_name=source_name,
first_name_hint=str(payload.get("firstName", "")).strip() or None,
last_name_hint=str(payload.get("lastName", "")).strip() or None,
)
Comment on lines +3326 to +3330

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_populate_name_fields() calls resume_extractor.split_name(), which will invoke an additional LLM call whenever the OpenAI client is configured. In the resume-upload path you already may have done an LLM extraction, so this can introduce an extra API request (latency/cost/failure surface) just to split the name. Consider using heuristic-only splitting here, or plumbing through extracted first_name/last_name hints from the resume profile to avoid triggering another model call.

Copilot uses AI. Check for mistakes.
payload["firstName"] = first_name
payload["lastName"] = last_name

def _build_resume_create_contact_payload(
self, file_content: bytes
) -> dict[str, str]:
Expand All@@ -3312,6 +3355,7 @@ def _build_resume_create_contact_payload(
"type": "Prospect",
"name": contact_name,
}
self._populate_name_fields(payload, source_name=contact_name)
if emails:
primary_email = emails[0]
if primary_email.endswith("@508.dev"):
Expand All@@ -3321,7 +3365,7 @@ def _build_resume_create_contact_payload(
if github_usernames:
payload["cGitHubUsername"] = github_usernames[0]
if linkedin_urls:
payload["cLinkedInUrl"] = linkedin_urls[0]
payload[self._configured_linkedin_field()] = linkedin_urls[0]
phone = hints.get("phone")
if isinstance(phone, str) and phone.strip():
payload["phoneNumber"] = phone.strip()
Expand DownExpand Up@@ -3370,17 +3414,30 @@ def _build_contact_payload_for_link_user(
parsed_name = str(payload.get("name", "")).strip()
if not parsed_name or parsed_name == "Resume Candidate":
payload["name"] = self._fallback_contact_name_for_discord_user(user)
self._populate_name_fields(
payload, source_name=str(payload.get("name", "")).strip()
)
payload.update(self._discord_link_fields(user))
return payload

async def _search_contacts_by_field(
self, *, field: str, value: str, max_size: int = 10
) -> list[dict[str, Any]]:
"""Search contacts using an exact field equals match."""
select_fields = [
"id",
"name",
"emailAddress",
"c508Email",
"cDiscordUsername",
"cGitHubUsername",
]
if field not in select_fields:
select_fields.append(field)
search_params = {
"where": [{"type": "equals", "attribute": field, "value": value}],
"maxSize": max_size,
"select": "id,name,emailAddress,c508Email,cDiscordUsername,cGitHubUsername,cLinkedInUrl",
"select": ",".join(select_fields),
}

response = self.espo_api.request("GET", "Contact", search_params)
Expand DownExpand Up@@ -3450,7 +3507,7 @@ async def _infer_contact_from_resume(
for linkedin_url in linkedin_urls:
attempts.append({"method": "linkedin", "value": linkedin_url})
contacts = await self._search_contacts_by_field(
field="cLinkedInUrl", value=linkedin_url
field=self._configured_linkedin_field(), value=linkedin_url
)
if len(contacts) == 1:
return contacts[0], {
Expand DownExpand Up@@ -4948,7 +5005,7 @@ async def update_contact(
if linkedin is not None:
clean_linkedin = linkedin.strip()
if clean_linkedin:
update_data["cLinkedInUrl"] = clean_linkedin
update_data[self._configured_linkedin_field()] = clean_linkedin
requested_updates.append("linkedin")

if rate_range is not None:
Expand DownExpand Up@@ -5028,9 +5085,10 @@ async def update_contact(
inline=True,
)
if "linkedin" in requested_updates:
linkedin_field = self._configured_linkedin_field()
embed.add_field(
name="🔗 LinkedIn",
value=update_data["cLinkedInUrl"],
value=update_data[linkedin_field],
inline=True,
)
if "skills" in requested_updates:
Expand DownExpand Up@@ -5605,7 +5663,8 @@ async def upload_resume(
await interaction.followup.send(
"⚠️ Could not find a unique contact from this resume. "
"Would you like to create a new contact from the parsed details?"
+ inferred_attempts_text,
+ inferred_attempts_text
+ self._build_resume_parsed_identity_summary(file_content),
view=view,
ephemeral=True,
)
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Fix resume contact inference and LinkedIn field handling by michaelmwu · Pull Request #129 · 508-dev/508-workflows · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 66 additions & 7 deletions apps/discord_bot/src/five08/discord_bot/cogs/crm.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1345,6 +1345,10 @@ async def confirm_create(
create_payload = self.crm_cog._build_resume_create_contact_payload(
file_content=self.file_content
)
self.crm_cog._populate_name_fields(
create_payload,
source_name=str(create_payload.get("name", "")).strip(),
)
target_contact = self.crm_cog.espo_api.request(
"POST", "Contact", create_payload
)
Expand DownExpand Up@@ -1375,6 +1379,8 @@ async def confirm_create(
)
except Exception as exc:
status_code = getattr(self.crm_cog.espo_api, "status_code", None)
error_detail = str(exc).strip() or "Unknown error"
status_note = f" (status {status_code})" if status_code else ""
logger.exception(
"Failed to create contact from resume filename=%s target_scope=%s inferred_meta=%s status_code=%s payload=%s",
self.filename,
Expand All@@ -1399,7 +1405,7 @@ async def confirm_create(
metadata=audit_metadata,
)
await interaction.followup.send(
"⚠️ Could not create a contact from this resume. "
f"⚠️ Could not create a contact from this resume: `{error_detail}`{status_note}. "
"Please provide `search_term` or `link_user`.",
ephemeral=True,
Comment on lines 1407 to 1410

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The user-facing failure message embeds error_detail = str(exc) verbatim. For EspoAPIError raised by the shared client, this may include boilerplate (e.g., "Wrong request, status code is …") and can duplicate the separately-appended status note, making the message noisy. Consider special-casing EspoAPIError to extract/display just the server reason (and escape/truncate any backticks/newlines) while keeping the full exception details only in logs/audit metadata.

Copilot uses AI. Check for mistakes.
)
Expand DownExpand Up@@ -1532,6 +1538,11 @@ def __init__(self, bot: commands.Bot) -> None:
discord_logs_webhook_wait=settings.discord_logs_webhook_wait,
)

@staticmethod
def _configured_linkedin_field() -> str:
"""Return the configured field for LinkedIn profile values."""
return str(getattr(settings, "crm_linkedin_field", "cLinkedInUrl"))

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_configured_linkedin_field() reads settings.crm_linkedin_field, but the bot Settings model doesn’t declare this field (so Pydantic Settings won’t load it from env/config and it will always fall back). Also, if the attribute were ever present but None, str(None) would yield the literal string "None". Consider adding an explicit crm_linkedin_field: str = "cLinkedInUrl" to the Settings schema (and validating/stripping it here, falling back when empty).

Suggested change
returnstr(getattr(settings, "crm_linkedin_field", "cLinkedInUrl"))
default_field="cLinkedInUrl"
raw_value=getattr(settings, "crm_linkedin_field", None)
ifnotisinstance(raw_value, str):
returndefault_field
value=raw_value.strip()
returnvalueordefault_field

Copilot uses AI. Check for mistakes.

def _audit_command(
self,
*,
Expand DownExpand Up@@ -3280,6 +3291,26 @@ def _to_values(raw_values: Any) -> list[str]:

return "\nParsed resume identifiers: " + "; ".join(summary_parts)

def _build_resume_parsed_identity_summary(self, file_content: bytes) -> str:
"""Build a short display summary of parsed contact identity fields."""
hints = self._extract_resume_contact_hints(file_content)
parsed_name = str(hints.get("name") or "").strip()
if not parsed_name:
parsed_name = self._extract_resume_name_fallback(file_content)

emails = hints.get("emails", [])
if not isinstance(emails, list):
emails = []
primary_email = "No email parsed"
if emails:
raw_email = str(emails[0]).strip()
if raw_email:
primary_email = raw_email

return (
f"\nParsed contact details: name=`{parsed_name}`, email=`{primary_email}`"
)
Comment on lines +3309 to +3312

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The parsed name/email are interpolated directly into inline-code backticks. If the extracted name/email contains a backtick, it can break formatting and potentially hide/alter surrounding text. Consider sanitizing (e.g., replace/backslash-escape backticks and truncate to a safe length) before embedding user/LLM-derived values into Discord messages.

Copilot uses AI. Check for mistakes.

def _extract_resume_name_hint(self, file_content: bytes) -> str:
"""Best-effort contact name extraction from resume text."""
hints = self._extract_resume_contact_hints(file_content)
Expand All@@ -3288,6 +3319,18 @@ def _extract_resume_name_hint(self, file_content: bytes) -> str:
return extracted_name
return self._extract_resume_name_fallback(file_content)

def _populate_name_fields(
self, payload: dict[str, str], *, source_name: str
) -> None:
"""Populate firstName and lastName fields for CRM contact creation payloads."""
first_name, last_name = self.resume_extractor.split_name(
full_name=source_name,
first_name_hint=str(payload.get("firstName", "")).strip() or None,
last_name_hint=str(payload.get("lastName", "")).strip() or None,
)
Comment on lines +3326 to +3330

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_populate_name_fields() calls resume_extractor.split_name(), which will invoke an additional LLM call whenever the OpenAI client is configured. In the resume-upload path you already may have done an LLM extraction, so this can introduce an extra API request (latency/cost/failure surface) just to split the name. Consider using heuristic-only splitting here, or plumbing through extracted first_name/last_name hints from the resume profile to avoid triggering another model call.

Copilot uses AI. Check for mistakes.
payload["firstName"] = first_name
payload["lastName"] = last_name

def _build_resume_create_contact_payload(
self, file_content: bytes
) -> dict[str, str]:
Expand All@@ -3312,6 +3355,7 @@ def _build_resume_create_contact_payload(
"type": "Prospect",
"name": contact_name,
}
self._populate_name_fields(payload, source_name=contact_name)
if emails:
primary_email = emails[0]
if primary_email.endswith("@508.dev"):
Expand All@@ -3321,7 +3365,7 @@ def _build_resume_create_contact_payload(
if github_usernames:
payload["cGitHubUsername"] = github_usernames[0]
if linkedin_urls:
payload["cLinkedInUrl"] = linkedin_urls[0]
payload[self._configured_linkedin_field()] = linkedin_urls[0]
phone = hints.get("phone")
if isinstance(phone, str) and phone.strip():
payload["phoneNumber"] = phone.strip()
Expand DownExpand Up@@ -3370,17 +3414,30 @@ def _build_contact_payload_for_link_user(
parsed_name = str(payload.get("name", "")).strip()
if not parsed_name or parsed_name == "Resume Candidate":
payload["name"] = self._fallback_contact_name_for_discord_user(user)
self._populate_name_fields(
payload, source_name=str(payload.get("name", "")).strip()
)
payload.update(self._discord_link_fields(user))
return payload

async def _search_contacts_by_field(
self, *, field: str, value: str, max_size: int = 10
) -> list[dict[str, Any]]:
"""Search contacts using an exact field equals match."""
select_fields = [
"id",
"name",
"emailAddress",
"c508Email",
"cDiscordUsername",
"cGitHubUsername",
]
if field not in select_fields:
select_fields.append(field)
search_params = {
"where": [{"type": "equals", "attribute": field, "value": value}],
"maxSize": max_size,
"select": "id,name,emailAddress,c508Email,cDiscordUsername,cGitHubUsername,cLinkedInUrl",
"select": ",".join(select_fields),
}

response = self.espo_api.request("GET", "Contact", search_params)
Expand DownExpand Up@@ -3450,7 +3507,7 @@ async def _infer_contact_from_resume(
for linkedin_url in linkedin_urls:
attempts.append({"method": "linkedin", "value": linkedin_url})
contacts = await self._search_contacts_by_field(
field="cLinkedInUrl", value=linkedin_url
field=self._configured_linkedin_field(), value=linkedin_url
)
if len(contacts) == 1:
return contacts[0], {
Expand DownExpand Up@@ -4948,7 +5005,7 @@ async def update_contact(
if linkedin is not None:
clean_linkedin = linkedin.strip()
if clean_linkedin:
update_data["cLinkedInUrl"] = clean_linkedin
update_data[self._configured_linkedin_field()] = clean_linkedin
requested_updates.append("linkedin")

if rate_range is not None:
Expand DownExpand Up@@ -5028,9 +5085,10 @@ async def update_contact(
inline=True,
)
if "linkedin" in requested_updates:
linkedin_field = self._configured_linkedin_field()
embed.add_field(
name="🔗 LinkedIn",
value=update_data["cLinkedInUrl"],
value=update_data[linkedin_field],
inline=True,
)
if "skills" in requested_updates:
Expand DownExpand Up@@ -5605,7 +5663,8 @@ async def upload_resume(
await interaction.followup.send(
"⚠️ Could not find a unique contact from this resume. "
"Would you like to create a new contact from the parsed details?"
+ inferred_attempts_text,
+ inferred_attempts_text
+ self._build_resume_parsed_identity_summary(file_content),
view=view,
ephemeral=True,
)
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Fix resume contact inference and LinkedIn field handling by michaelmwu · Pull Request #129 · 508-dev/508-workflows · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 66 additions & 7 deletions apps/discord_bot/src/five08/discord_bot/cogs/crm.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1345,6 +1345,10 @@ async def confirm_create(
create_payload = self.crm_cog._build_resume_create_contact_payload(
file_content=self.file_content
)
self.crm_cog._populate_name_fields(
create_payload,
source_name=str(create_payload.get("name", "")).strip(),
)
target_contact = self.crm_cog.espo_api.request(
"POST", "Contact", create_payload
)
Expand DownExpand Up@@ -1375,6 +1379,8 @@ async def confirm_create(
)
except Exception as exc:
status_code = getattr(self.crm_cog.espo_api, "status_code", None)
error_detail = str(exc).strip() or "Unknown error"
status_note = f" (status {status_code})" if status_code else ""
logger.exception(
"Failed to create contact from resume filename=%s target_scope=%s inferred_meta=%s status_code=%s payload=%s",
self.filename,
Expand All@@ -1399,7 +1405,7 @@ async def confirm_create(
metadata=audit_metadata,
)
await interaction.followup.send(
"⚠️ Could not create a contact from this resume. "
f"⚠️ Could not create a contact from this resume: `{error_detail}`{status_note}. "
"Please provide `search_term` or `link_user`.",
ephemeral=True,
Comment on lines 1407 to 1410

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The user-facing failure message embeds error_detail = str(exc) verbatim. For EspoAPIError raised by the shared client, this may include boilerplate (e.g., "Wrong request, status code is …") and can duplicate the separately-appended status note, making the message noisy. Consider special-casing EspoAPIError to extract/display just the server reason (and escape/truncate any backticks/newlines) while keeping the full exception details only in logs/audit metadata.

Copilot uses AI. Check for mistakes.
)
Expand DownExpand Up@@ -1532,6 +1538,11 @@ def __init__(self, bot: commands.Bot) -> None:
discord_logs_webhook_wait=settings.discord_logs_webhook_wait,
)

@staticmethod
def _configured_linkedin_field() -> str:
"""Return the configured field for LinkedIn profile values."""
return str(getattr(settings, "crm_linkedin_field", "cLinkedInUrl"))

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_configured_linkedin_field() reads settings.crm_linkedin_field, but the bot Settings model doesn’t declare this field (so Pydantic Settings won’t load it from env/config and it will always fall back). Also, if the attribute were ever present but None, str(None) would yield the literal string "None". Consider adding an explicit crm_linkedin_field: str = "cLinkedInUrl" to the Settings schema (and validating/stripping it here, falling back when empty).

Suggested change
returnstr(getattr(settings, "crm_linkedin_field", "cLinkedInUrl"))
default_field="cLinkedInUrl"
raw_value=getattr(settings, "crm_linkedin_field", None)
ifnotisinstance(raw_value, str):
returndefault_field
value=raw_value.strip()
returnvalueordefault_field

Copilot uses AI. Check for mistakes.

def _audit_command(
self,
*,
Expand DownExpand Up@@ -3280,6 +3291,26 @@ def _to_values(raw_values: Any) -> list[str]:

return "\nParsed resume identifiers: " + "; ".join(summary_parts)

def _build_resume_parsed_identity_summary(self, file_content: bytes) -> str:
"""Build a short display summary of parsed contact identity fields."""
hints = self._extract_resume_contact_hints(file_content)
parsed_name = str(hints.get("name") or "").strip()
if not parsed_name:
parsed_name = self._extract_resume_name_fallback(file_content)

emails = hints.get("emails", [])
if not isinstance(emails, list):
emails = []
primary_email = "No email parsed"
if emails:
raw_email = str(emails[0]).strip()
if raw_email:
primary_email = raw_email

return (
f"\nParsed contact details: name=`{parsed_name}`, email=`{primary_email}`"
)
Comment on lines +3309 to +3312

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The parsed name/email are interpolated directly into inline-code backticks. If the extracted name/email contains a backtick, it can break formatting and potentially hide/alter surrounding text. Consider sanitizing (e.g., replace/backslash-escape backticks and truncate to a safe length) before embedding user/LLM-derived values into Discord messages.

Copilot uses AI. Check for mistakes.

def _extract_resume_name_hint(self, file_content: bytes) -> str:
"""Best-effort contact name extraction from resume text."""
hints = self._extract_resume_contact_hints(file_content)
Expand All@@ -3288,6 +3319,18 @@ def _extract_resume_name_hint(self, file_content: bytes) -> str:
return extracted_name
return self._extract_resume_name_fallback(file_content)

def _populate_name_fields(
self, payload: dict[str, str], *, source_name: str
) -> None:
"""Populate firstName and lastName fields for CRM contact creation payloads."""
first_name, last_name = self.resume_extractor.split_name(
full_name=source_name,
first_name_hint=str(payload.get("firstName", "")).strip() or None,
last_name_hint=str(payload.get("lastName", "")).strip() or None,
)
Comment on lines +3326 to +3330

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_populate_name_fields() calls resume_extractor.split_name(), which will invoke an additional LLM call whenever the OpenAI client is configured. In the resume-upload path you already may have done an LLM extraction, so this can introduce an extra API request (latency/cost/failure surface) just to split the name. Consider using heuristic-only splitting here, or plumbing through extracted first_name/last_name hints from the resume profile to avoid triggering another model call.

Copilot uses AI. Check for mistakes.
payload["firstName"] = first_name
payload["lastName"] = last_name

def _build_resume_create_contact_payload(
self, file_content: bytes
) -> dict[str, str]:
Expand All@@ -3312,6 +3355,7 @@ def _build_resume_create_contact_payload(
"type": "Prospect",
"name": contact_name,
}
self._populate_name_fields(payload, source_name=contact_name)
if emails:
primary_email = emails[0]
if primary_email.endswith("@508.dev"):
Expand All@@ -3321,7 +3365,7 @@ def _build_resume_create_contact_payload(
if github_usernames:
payload["cGitHubUsername"] = github_usernames[0]
if linkedin_urls:
payload["cLinkedInUrl"] = linkedin_urls[0]
payload[self._configured_linkedin_field()] = linkedin_urls[0]
phone = hints.get("phone")
if isinstance(phone, str) and phone.strip():
payload["phoneNumber"] = phone.strip()
Expand DownExpand Up@@ -3370,17 +3414,30 @@ def _build_contact_payload_for_link_user(
parsed_name = str(payload.get("name", "")).strip()
if not parsed_name or parsed_name == "Resume Candidate":
payload["name"] = self._fallback_contact_name_for_discord_user(user)
self._populate_name_fields(
payload, source_name=str(payload.get("name", "")).strip()
)
payload.update(self._discord_link_fields(user))
return payload

async def _search_contacts_by_field(
self, *, field: str, value: str, max_size: int = 10
) -> list[dict[str, Any]]:
"""Search contacts using an exact field equals match."""
select_fields = [
"id",
"name",
"emailAddress",
"c508Email",
"cDiscordUsername",
"cGitHubUsername",
]
if field not in select_fields:
select_fields.append(field)
search_params = {
"where": [{"type": "equals", "attribute": field, "value": value}],
"maxSize": max_size,
"select": "id,name,emailAddress,c508Email,cDiscordUsername,cGitHubUsername,cLinkedInUrl",
"select": ",".join(select_fields),
}

response = self.espo_api.request("GET", "Contact", search_params)
Expand DownExpand Up@@ -3450,7 +3507,7 @@ async def _infer_contact_from_resume(
for linkedin_url in linkedin_urls:
attempts.append({"method": "linkedin", "value": linkedin_url})
contacts = await self._search_contacts_by_field(
field="cLinkedInUrl", value=linkedin_url
field=self._configured_linkedin_field(), value=linkedin_url
)
if len(contacts) == 1:
return contacts[0], {
Expand DownExpand Up@@ -4948,7 +5005,7 @@ async def update_contact(
if linkedin is not None:
clean_linkedin = linkedin.strip()
if clean_linkedin:
update_data["cLinkedInUrl"] = clean_linkedin
update_data[self._configured_linkedin_field()] = clean_linkedin
requested_updates.append("linkedin")

if rate_range is not None:
Expand DownExpand Up@@ -5028,9 +5085,10 @@ async def update_contact(
inline=True,
)
if "linkedin" in requested_updates:
linkedin_field = self._configured_linkedin_field()
embed.add_field(
name="🔗 LinkedIn",
value=update_data["cLinkedInUrl"],
value=update_data[linkedin_field],
inline=True,
)
if "skills" in requested_updates:
Expand DownExpand Up@@ -5605,7 +5663,8 @@ async def upload_resume(
await interaction.followup.send(
"⚠️ Could not find a unique contact from this resume. "
"Would you like to create a new contact from the parsed details?"
+ inferred_attempts_text,
+ inferred_attempts_text
+ self._build_resume_parsed_identity_summary(file_content),
view=view,
ephemeral=True,
)
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Fix resume contact inference and LinkedIn field handling by michaelmwu · Pull Request #129 · 508-dev/508-workflows · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 66 additions & 7 deletions apps/discord_bot/src/five08/discord_bot/cogs/crm.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1345,6 +1345,10 @@ async def confirm_create(
create_payload = self.crm_cog._build_resume_create_contact_payload(
file_content=self.file_content
)
self.crm_cog._populate_name_fields(
create_payload,
source_name=str(create_payload.get("name", "")).strip(),
)
target_contact = self.crm_cog.espo_api.request(
"POST", "Contact", create_payload
)
Expand DownExpand Up@@ -1375,6 +1379,8 @@ async def confirm_create(
)
except Exception as exc:
status_code = getattr(self.crm_cog.espo_api, "status_code", None)
error_detail = str(exc).strip() or "Unknown error"
status_note = f" (status {status_code})" if status_code else ""
logger.exception(
"Failed to create contact from resume filename=%s target_scope=%s inferred_meta=%s status_code=%s payload=%s",
self.filename,
Expand All@@ -1399,7 +1405,7 @@ async def confirm_create(
metadata=audit_metadata,
)
await interaction.followup.send(
"⚠️ Could not create a contact from this resume. "
f"⚠️ Could not create a contact from this resume: `{error_detail}`{status_note}. "
"Please provide `search_term` or `link_user`.",
ephemeral=True,
Comment on lines 1407 to 1410

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The user-facing failure message embeds error_detail = str(exc) verbatim. For EspoAPIError raised by the shared client, this may include boilerplate (e.g., "Wrong request, status code is …") and can duplicate the separately-appended status note, making the message noisy. Consider special-casing EspoAPIError to extract/display just the server reason (and escape/truncate any backticks/newlines) while keeping the full exception details only in logs/audit metadata.

Copilot uses AI. Check for mistakes.
)
Expand DownExpand Up@@ -1532,6 +1538,11 @@ def __init__(self, bot: commands.Bot) -> None:
discord_logs_webhook_wait=settings.discord_logs_webhook_wait,
)

@staticmethod
def _configured_linkedin_field() -> str:
"""Return the configured field for LinkedIn profile values."""
return str(getattr(settings, "crm_linkedin_field", "cLinkedInUrl"))

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_configured_linkedin_field() reads settings.crm_linkedin_field, but the bot Settings model doesn’t declare this field (so Pydantic Settings won’t load it from env/config and it will always fall back). Also, if the attribute were ever present but None, str(None) would yield the literal string "None". Consider adding an explicit crm_linkedin_field: str = "cLinkedInUrl" to the Settings schema (and validating/stripping it here, falling back when empty).

Suggested change
returnstr(getattr(settings, "crm_linkedin_field", "cLinkedInUrl"))
default_field="cLinkedInUrl"
raw_value=getattr(settings, "crm_linkedin_field", None)
ifnotisinstance(raw_value, str):
returndefault_field
value=raw_value.strip()
returnvalueordefault_field

Copilot uses AI. Check for mistakes.

def _audit_command(
self,
*,
Expand DownExpand Up@@ -3280,6 +3291,26 @@ def _to_values(raw_values: Any) -> list[str]:

return "\nParsed resume identifiers: " + "; ".join(summary_parts)

def _build_resume_parsed_identity_summary(self, file_content: bytes) -> str:
"""Build a short display summary of parsed contact identity fields."""
hints = self._extract_resume_contact_hints(file_content)
parsed_name = str(hints.get("name") or "").strip()
if not parsed_name:
parsed_name = self._extract_resume_name_fallback(file_content)

emails = hints.get("emails", [])
if not isinstance(emails, list):
emails = []
primary_email = "No email parsed"
if emails:
raw_email = str(emails[0]).strip()
if raw_email:
primary_email = raw_email

return (
f"\nParsed contact details: name=`{parsed_name}`, email=`{primary_email}`"
)
Comment on lines +3309 to +3312

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The parsed name/email are interpolated directly into inline-code backticks. If the extracted name/email contains a backtick, it can break formatting and potentially hide/alter surrounding text. Consider sanitizing (e.g., replace/backslash-escape backticks and truncate to a safe length) before embedding user/LLM-derived values into Discord messages.

Copilot uses AI. Check for mistakes.

def _extract_resume_name_hint(self, file_content: bytes) -> str:
"""Best-effort contact name extraction from resume text."""
hints = self._extract_resume_contact_hints(file_content)
Expand All@@ -3288,6 +3319,18 @@ def _extract_resume_name_hint(self, file_content: bytes) -> str:
return extracted_name
return self._extract_resume_name_fallback(file_content)

def _populate_name_fields(
self, payload: dict[str, str], *, source_name: str
) -> None:
"""Populate firstName and lastName fields for CRM contact creation payloads."""
first_name, last_name = self.resume_extractor.split_name(
full_name=source_name,
first_name_hint=str(payload.get("firstName", "")).strip() or None,
last_name_hint=str(payload.get("lastName", "")).strip() or None,
)
Comment on lines +3326 to +3330

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_populate_name_fields() calls resume_extractor.split_name(), which will invoke an additional LLM call whenever the OpenAI client is configured. In the resume-upload path you already may have done an LLM extraction, so this can introduce an extra API request (latency/cost/failure surface) just to split the name. Consider using heuristic-only splitting here, or plumbing through extracted first_name/last_name hints from the resume profile to avoid triggering another model call.

Copilot uses AI. Check for mistakes.
payload["firstName"] = first_name
payload["lastName"] = last_name

def _build_resume_create_contact_payload(
self, file_content: bytes
) -> dict[str, str]:
Expand All@@ -3312,6 +3355,7 @@ def _build_resume_create_contact_payload(
"type": "Prospect",
"name": contact_name,
}
self._populate_name_fields(payload, source_name=contact_name)
if emails:
primary_email = emails[0]
if primary_email.endswith("@508.dev"):
Expand All@@ -3321,7 +3365,7 @@ def _build_resume_create_contact_payload(
if github_usernames:
payload["cGitHubUsername"] = github_usernames[0]
if linkedin_urls:
payload["cLinkedInUrl"] = linkedin_urls[0]
payload[self._configured_linkedin_field()] = linkedin_urls[0]
phone = hints.get("phone")
if isinstance(phone, str) and phone.strip():
payload["phoneNumber"] = phone.strip()
Expand DownExpand Up@@ -3370,17 +3414,30 @@ def _build_contact_payload_for_link_user(
parsed_name = str(payload.get("name", "")).strip()
if not parsed_name or parsed_name == "Resume Candidate":
payload["name"] = self._fallback_contact_name_for_discord_user(user)
self._populate_name_fields(
payload, source_name=str(payload.get("name", "")).strip()
)
payload.update(self._discord_link_fields(user))
return payload

async def _search_contacts_by_field(
self, *, field: str, value: str, max_size: int = 10
) -> list[dict[str, Any]]:
"""Search contacts using an exact field equals match."""
select_fields = [
"id",
"name",
"emailAddress",
"c508Email",
"cDiscordUsername",
"cGitHubUsername",
]
if field not in select_fields:
select_fields.append(field)
search_params = {
"where": [{"type": "equals", "attribute": field, "value": value}],
"maxSize": max_size,
"select": "id,name,emailAddress,c508Email,cDiscordUsername,cGitHubUsername,cLinkedInUrl",
"select": ",".join(select_fields),
}

response = self.espo_api.request("GET", "Contact", search_params)
Expand DownExpand Up@@ -3450,7 +3507,7 @@ async def _infer_contact_from_resume(
for linkedin_url in linkedin_urls:
attempts.append({"method": "linkedin", "value": linkedin_url})
contacts = await self._search_contacts_by_field(
field="cLinkedInUrl", value=linkedin_url
field=self._configured_linkedin_field(), value=linkedin_url
)
if len(contacts) == 1:
return contacts[0], {
Expand DownExpand Up@@ -4948,7 +5005,7 @@ async def update_contact(
if linkedin is not None:
clean_linkedin = linkedin.strip()
if clean_linkedin:
update_data["cLinkedInUrl"] = clean_linkedin
update_data[self._configured_linkedin_field()] = clean_linkedin
requested_updates.append("linkedin")

if rate_range is not None:
Expand DownExpand Up@@ -5028,9 +5085,10 @@ async def update_contact(
inline=True,
)
if "linkedin" in requested_updates:
linkedin_field = self._configured_linkedin_field()
embed.add_field(
name="🔗 LinkedIn",
value=update_data["cLinkedInUrl"],
value=update_data[linkedin_field],
inline=True,
)
if "skills" in requested_updates:
Expand DownExpand Up@@ -5605,7 +5663,8 @@ async def upload_resume(
await interaction.followup.send(
"⚠️ Could not find a unique contact from this resume. "
"Would you like to create a new contact from the parsed details?"
+ inferred_attempts_text,
+ inferred_attempts_text
+ self._build_resume_parsed_identity_summary(file_content),
view=view,
ephemeral=True,
)
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Fix resume contact inference and LinkedIn field handling by michaelmwu · Pull Request #129 · 508-dev/508-workflows · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 66 additions & 7 deletions apps/discord_bot/src/five08/discord_bot/cogs/crm.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1345,6 +1345,10 @@ async def confirm_create(
create_payload = self.crm_cog._build_resume_create_contact_payload(
file_content=self.file_content
)
self.crm_cog._populate_name_fields(
create_payload,
source_name=str(create_payload.get("name", "")).strip(),
)
target_contact = self.crm_cog.espo_api.request(
"POST", "Contact", create_payload
)
Expand DownExpand Up@@ -1375,6 +1379,8 @@ async def confirm_create(
)
except Exception as exc:
status_code = getattr(self.crm_cog.espo_api, "status_code", None)
error_detail = str(exc).strip() or "Unknown error"
status_note = f" (status {status_code})" if status_code else ""
logger.exception(
"Failed to create contact from resume filename=%s target_scope=%s inferred_meta=%s status_code=%s payload=%s",
self.filename,
Expand All@@ -1399,7 +1405,7 @@ async def confirm_create(
metadata=audit_metadata,
)
await interaction.followup.send(
"⚠️ Could not create a contact from this resume. "
f"⚠️ Could not create a contact from this resume: `{error_detail}`{status_note}. "
"Please provide `search_term` or `link_user`.",
ephemeral=True,
Comment on lines 1407 to 1410

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The user-facing failure message embeds error_detail = str(exc) verbatim. For EspoAPIError raised by the shared client, this may include boilerplate (e.g., "Wrong request, status code is …") and can duplicate the separately-appended status note, making the message noisy. Consider special-casing EspoAPIError to extract/display just the server reason (and escape/truncate any backticks/newlines) while keeping the full exception details only in logs/audit metadata.

Copilot uses AI. Check for mistakes.
)
Expand DownExpand Up@@ -1532,6 +1538,11 @@ def __init__(self, bot: commands.Bot) -> None:
discord_logs_webhook_wait=settings.discord_logs_webhook_wait,
)

@staticmethod
def _configured_linkedin_field() -> str:
"""Return the configured field for LinkedIn profile values."""
return str(getattr(settings, "crm_linkedin_field", "cLinkedInUrl"))

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_configured_linkedin_field() reads settings.crm_linkedin_field, but the bot Settings model doesn’t declare this field (so Pydantic Settings won’t load it from env/config and it will always fall back). Also, if the attribute were ever present but None, str(None) would yield the literal string "None". Consider adding an explicit crm_linkedin_field: str = "cLinkedInUrl" to the Settings schema (and validating/stripping it here, falling back when empty).

Suggested change
returnstr(getattr(settings, "crm_linkedin_field", "cLinkedInUrl"))
default_field="cLinkedInUrl"
raw_value=getattr(settings, "crm_linkedin_field", None)
ifnotisinstance(raw_value, str):
returndefault_field
value=raw_value.strip()
returnvalueordefault_field

Copilot uses AI. Check for mistakes.

def _audit_command(
self,
*,
Expand DownExpand Up@@ -3280,6 +3291,26 @@ def _to_values(raw_values: Any) -> list[str]:

return "\nParsed resume identifiers: " + "; ".join(summary_parts)

def _build_resume_parsed_identity_summary(self, file_content: bytes) -> str:
"""Build a short display summary of parsed contact identity fields."""
hints = self._extract_resume_contact_hints(file_content)
parsed_name = str(hints.get("name") or "").strip()
if not parsed_name:
parsed_name = self._extract_resume_name_fallback(file_content)

emails = hints.get("emails", [])
if not isinstance(emails, list):
emails = []
primary_email = "No email parsed"
if emails:
raw_email = str(emails[0]).strip()
if raw_email:
primary_email = raw_email

return (
f"\nParsed contact details: name=`{parsed_name}`, email=`{primary_email}`"
)
Comment on lines +3309 to +3312

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The parsed name/email are interpolated directly into inline-code backticks. If the extracted name/email contains a backtick, it can break formatting and potentially hide/alter surrounding text. Consider sanitizing (e.g., replace/backslash-escape backticks and truncate to a safe length) before embedding user/LLM-derived values into Discord messages.

Copilot uses AI. Check for mistakes.

def _extract_resume_name_hint(self, file_content: bytes) -> str:
"""Best-effort contact name extraction from resume text."""
hints = self._extract_resume_contact_hints(file_content)
Expand All@@ -3288,6 +3319,18 @@ def _extract_resume_name_hint(self, file_content: bytes) -> str:
return extracted_name
return self._extract_resume_name_fallback(file_content)

def _populate_name_fields(
self, payload: dict[str, str], *, source_name: str
) -> None:
"""Populate firstName and lastName fields for CRM contact creation payloads."""
first_name, last_name = self.resume_extractor.split_name(
full_name=source_name,
first_name_hint=str(payload.get("firstName", "")).strip() or None,
last_name_hint=str(payload.get("lastName", "")).strip() or None,
)
Comment on lines +3326 to +3330

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_populate_name_fields() calls resume_extractor.split_name(), which will invoke an additional LLM call whenever the OpenAI client is configured. In the resume-upload path you already may have done an LLM extraction, so this can introduce an extra API request (latency/cost/failure surface) just to split the name. Consider using heuristic-only splitting here, or plumbing through extracted first_name/last_name hints from the resume profile to avoid triggering another model call.

Copilot uses AI. Check for mistakes.
payload["firstName"] = first_name
payload["lastName"] = last_name

def _build_resume_create_contact_payload(
self, file_content: bytes
) -> dict[str, str]:
Expand All@@ -3312,6 +3355,7 @@ def _build_resume_create_contact_payload(
"type": "Prospect",
"name": contact_name,
}
self._populate_name_fields(payload, source_name=contact_name)
if emails:
primary_email = emails[0]
if primary_email.endswith("@508.dev"):
Expand All@@ -3321,7 +3365,7 @@ def _build_resume_create_contact_payload(
if github_usernames:
payload["cGitHubUsername"] = github_usernames[0]
if linkedin_urls:
payload["cLinkedInUrl"] = linkedin_urls[0]
payload[self._configured_linkedin_field()] = linkedin_urls[0]
phone = hints.get("phone")
if isinstance(phone, str) and phone.strip():
payload["phoneNumber"] = phone.strip()
Expand DownExpand Up@@ -3370,17 +3414,30 @@ def _build_contact_payload_for_link_user(
parsed_name = str(payload.get("name", "")).strip()
if not parsed_name or parsed_name == "Resume Candidate":
payload["name"] = self._fallback_contact_name_for_discord_user(user)
self._populate_name_fields(
payload, source_name=str(payload.get("name", "")).strip()
)
payload.update(self._discord_link_fields(user))
return payload

async def _search_contacts_by_field(
self, *, field: str, value: str, max_size: int = 10
) -> list[dict[str, Any]]:
"""Search contacts using an exact field equals match."""
select_fields = [
"id",
"name",
"emailAddress",
"c508Email",
"cDiscordUsername",
"cGitHubUsername",
]
if field not in select_fields:
select_fields.append(field)
search_params = {
"where": [{"type": "equals", "attribute": field, "value": value}],
"maxSize": max_size,
"select": "id,name,emailAddress,c508Email,cDiscordUsername,cGitHubUsername,cLinkedInUrl",
"select": ",".join(select_fields),
}

response = self.espo_api.request("GET", "Contact", search_params)
Expand DownExpand Up@@ -3450,7 +3507,7 @@ async def _infer_contact_from_resume(
for linkedin_url in linkedin_urls:
attempts.append({"method": "linkedin", "value": linkedin_url})
contacts = await self._search_contacts_by_field(
field="cLinkedInUrl", value=linkedin_url
field=self._configured_linkedin_field(), value=linkedin_url
)
if len(contacts) == 1:
return contacts[0], {
Expand DownExpand Up@@ -4948,7 +5005,7 @@ async def update_contact(
if linkedin is not None:
clean_linkedin = linkedin.strip()
if clean_linkedin:
update_data["cLinkedInUrl"] = clean_linkedin
update_data[self._configured_linkedin_field()] = clean_linkedin
requested_updates.append("linkedin")

if rate_range is not None:
Expand DownExpand Up@@ -5028,9 +5085,10 @@ async def update_contact(
inline=True,
)
if "linkedin" in requested_updates:
linkedin_field = self._configured_linkedin_field()
embed.add_field(
name="🔗 LinkedIn",
value=update_data["cLinkedInUrl"],
value=update_data[linkedin_field],
inline=True,
)
if "skills" in requested_updates:
Expand DownExpand Up@@ -5605,7 +5663,8 @@ async def upload_resume(
await interaction.followup.send(
"⚠️ Could not find a unique contact from this resume. "
"Would you like to create a new contact from the parsed details?"
+ inferred_attempts_text,
+ inferred_attempts_text
+ self._build_resume_parsed_identity_summary(file_content),
view=view,
ephemeral=True,
)
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Fix resume contact inference and LinkedIn field handling by michaelmwu · Pull Request #129 · 508-dev/508-workflows · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 66 additions & 7 deletions apps/discord_bot/src/five08/discord_bot/cogs/crm.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1345,6 +1345,10 @@ async def confirm_create(
create_payload = self.crm_cog._build_resume_create_contact_payload(
file_content=self.file_content
)
self.crm_cog._populate_name_fields(
create_payload,
source_name=str(create_payload.get("name", "")).strip(),
)
target_contact = self.crm_cog.espo_api.request(
"POST", "Contact", create_payload
)
Expand DownExpand Up@@ -1375,6 +1379,8 @@ async def confirm_create(
)
except Exception as exc:
status_code = getattr(self.crm_cog.espo_api, "status_code", None)
error_detail = str(exc).strip() or "Unknown error"
status_note = f" (status {status_code})" if status_code else ""
logger.exception(
"Failed to create contact from resume filename=%s target_scope=%s inferred_meta=%s status_code=%s payload=%s",
self.filename,
Expand All@@ -1399,7 +1405,7 @@ async def confirm_create(
metadata=audit_metadata,
)
await interaction.followup.send(
"⚠️ Could not create a contact from this resume. "
f"⚠️ Could not create a contact from this resume: `{error_detail}`{status_note}. "
"Please provide `search_term` or `link_user`.",
ephemeral=True,
Comment on lines 1407 to 1410

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The user-facing failure message embeds error_detail = str(exc) verbatim. For EspoAPIError raised by the shared client, this may include boilerplate (e.g., "Wrong request, status code is …") and can duplicate the separately-appended status note, making the message noisy. Consider special-casing EspoAPIError to extract/display just the server reason (and escape/truncate any backticks/newlines) while keeping the full exception details only in logs/audit metadata.

Copilot uses AI. Check for mistakes.
)
Expand DownExpand Up@@ -1532,6 +1538,11 @@ def __init__(self, bot: commands.Bot) -> None:
discord_logs_webhook_wait=settings.discord_logs_webhook_wait,
)

@staticmethod
def _configured_linkedin_field() -> str:
"""Return the configured field for LinkedIn profile values."""
return str(getattr(settings, "crm_linkedin_field", "cLinkedInUrl"))

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_configured_linkedin_field() reads settings.crm_linkedin_field, but the bot Settings model doesn’t declare this field (so Pydantic Settings won’t load it from env/config and it will always fall back). Also, if the attribute were ever present but None, str(None) would yield the literal string "None". Consider adding an explicit crm_linkedin_field: str = "cLinkedInUrl" to the Settings schema (and validating/stripping it here, falling back when empty).

Suggested change
returnstr(getattr(settings, "crm_linkedin_field", "cLinkedInUrl"))
default_field="cLinkedInUrl"
raw_value=getattr(settings, "crm_linkedin_field", None)
ifnotisinstance(raw_value, str):
returndefault_field
value=raw_value.strip()
returnvalueordefault_field

Copilot uses AI. Check for mistakes.

def _audit_command(
self,
*,
Expand DownExpand Up@@ -3280,6 +3291,26 @@ def _to_values(raw_values: Any) -> list[str]:

return "\nParsed resume identifiers: " + "; ".join(summary_parts)

def _build_resume_parsed_identity_summary(self, file_content: bytes) -> str:
"""Build a short display summary of parsed contact identity fields."""
hints = self._extract_resume_contact_hints(file_content)
parsed_name = str(hints.get("name") or "").strip()
if not parsed_name:
parsed_name = self._extract_resume_name_fallback(file_content)

emails = hints.get("emails", [])
if not isinstance(emails, list):
emails = []
primary_email = "No email parsed"
if emails:
raw_email = str(emails[0]).strip()
if raw_email:
primary_email = raw_email

return (
f"\nParsed contact details: name=`{parsed_name}`, email=`{primary_email}`"
)
Comment on lines +3309 to +3312

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The parsed name/email are interpolated directly into inline-code backticks. If the extracted name/email contains a backtick, it can break formatting and potentially hide/alter surrounding text. Consider sanitizing (e.g., replace/backslash-escape backticks and truncate to a safe length) before embedding user/LLM-derived values into Discord messages.

Copilot uses AI. Check for mistakes.

def _extract_resume_name_hint(self, file_content: bytes) -> str:
"""Best-effort contact name extraction from resume text."""
hints = self._extract_resume_contact_hints(file_content)
Expand All@@ -3288,6 +3319,18 @@ def _extract_resume_name_hint(self, file_content: bytes) -> str:
return extracted_name
return self._extract_resume_name_fallback(file_content)

def _populate_name_fields(
self, payload: dict[str, str], *, source_name: str
) -> None:
"""Populate firstName and lastName fields for CRM contact creation payloads."""
first_name, last_name = self.resume_extractor.split_name(
full_name=source_name,
first_name_hint=str(payload.get("firstName", "")).strip() or None,
last_name_hint=str(payload.get("lastName", "")).strip() or None,
)
Comment on lines +3326 to +3330

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_populate_name_fields() calls resume_extractor.split_name(), which will invoke an additional LLM call whenever the OpenAI client is configured. In the resume-upload path you already may have done an LLM extraction, so this can introduce an extra API request (latency/cost/failure surface) just to split the name. Consider using heuristic-only splitting here, or plumbing through extracted first_name/last_name hints from the resume profile to avoid triggering another model call.

Copilot uses AI. Check for mistakes.
payload["firstName"] = first_name
payload["lastName"] = last_name

def _build_resume_create_contact_payload(
self, file_content: bytes
) -> dict[str, str]:
Expand All@@ -3312,6 +3355,7 @@ def _build_resume_create_contact_payload(
"type": "Prospect",
"name": contact_name,
}
self._populate_name_fields(payload, source_name=contact_name)
if emails:
primary_email = emails[0]
if primary_email.endswith("@508.dev"):
Expand All@@ -3321,7 +3365,7 @@ def _build_resume_create_contact_payload(
if github_usernames:
payload["cGitHubUsername"] = github_usernames[0]
if linkedin_urls:
payload["cLinkedInUrl"] = linkedin_urls[0]
payload[self._configured_linkedin_field()] = linkedin_urls[0]
phone = hints.get("phone")
if isinstance(phone, str) and phone.strip():
payload["phoneNumber"] = phone.strip()
Expand DownExpand Up@@ -3370,17 +3414,30 @@ def _build_contact_payload_for_link_user(
parsed_name = str(payload.get("name", "")).strip()
if not parsed_name or parsed_name == "Resume Candidate":
payload["name"] = self._fallback_contact_name_for_discord_user(user)
self._populate_name_fields(
payload, source_name=str(payload.get("name", "")).strip()
)
payload.update(self._discord_link_fields(user))
return payload

async def _search_contacts_by_field(
self, *, field: str, value: str, max_size: int = 10
) -> list[dict[str, Any]]:
"""Search contacts using an exact field equals match."""
select_fields = [
"id",
"name",
"emailAddress",
"c508Email",
"cDiscordUsername",
"cGitHubUsername",
]
if field not in select_fields:
select_fields.append(field)
search_params = {
"where": [{"type": "equals", "attribute": field, "value": value}],
"maxSize": max_size,
"select": "id,name,emailAddress,c508Email,cDiscordUsername,cGitHubUsername,cLinkedInUrl",
"select": ",".join(select_fields),
}

response = self.espo_api.request("GET", "Contact", search_params)
Expand DownExpand Up@@ -3450,7 +3507,7 @@ async def _infer_contact_from_resume(
for linkedin_url in linkedin_urls:
attempts.append({"method": "linkedin", "value": linkedin_url})
contacts = await self._search_contacts_by_field(
field="cLinkedInUrl", value=linkedin_url
field=self._configured_linkedin_field(), value=linkedin_url
)
if len(contacts) == 1:
return contacts[0], {
Expand DownExpand Up@@ -4948,7 +5005,7 @@ async def update_contact(
if linkedin is not None:
clean_linkedin = linkedin.strip()
if clean_linkedin:
update_data["cLinkedInUrl"] = clean_linkedin
update_data[self._configured_linkedin_field()] = clean_linkedin
requested_updates.append("linkedin")

if rate_range is not None:
Expand DownExpand Up@@ -5028,9 +5085,10 @@ async def update_contact(
inline=True,
)
if "linkedin" in requested_updates:
linkedin_field = self._configured_linkedin_field()
embed.add_field(
name="🔗 LinkedIn",
value=update_data["cLinkedInUrl"],
value=update_data[linkedin_field],
inline=True,
)
if "skills" in requested_updates:
Expand DownExpand Up@@ -5605,7 +5663,8 @@ async def upload_resume(
await interaction.followup.send(
"⚠️ Could not find a unique contact from this resume. "
"Would you like to create a new contact from the parsed details?"
+ inferred_attempts_text,
+ inferred_attempts_text
+ self._build_resume_parsed_identity_summary(file_content),
view=view,
ephemeral=True,
)
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Fix resume contact inference and LinkedIn field handling by michaelmwu · Pull Request #129 · 508-dev/508-workflows · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 66 additions & 7 deletions apps/discord_bot/src/five08/discord_bot/cogs/crm.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1345,6 +1345,10 @@ async def confirm_create(
create_payload = self.crm_cog._build_resume_create_contact_payload(
file_content=self.file_content
)
self.crm_cog._populate_name_fields(
create_payload,
source_name=str(create_payload.get("name", "")).strip(),
)
target_contact = self.crm_cog.espo_api.request(
"POST", "Contact", create_payload
)
Expand DownExpand Up@@ -1375,6 +1379,8 @@ async def confirm_create(
)
except Exception as exc:
status_code = getattr(self.crm_cog.espo_api, "status_code", None)
error_detail = str(exc).strip() or "Unknown error"
status_note = f" (status {status_code})" if status_code else ""
logger.exception(
"Failed to create contact from resume filename=%s target_scope=%s inferred_meta=%s status_code=%s payload=%s",
self.filename,
Expand All@@ -1399,7 +1405,7 @@ async def confirm_create(
metadata=audit_metadata,
)
await interaction.followup.send(
"⚠️ Could not create a contact from this resume. "
f"⚠️ Could not create a contact from this resume: `{error_detail}`{status_note}. "
"Please provide `search_term` or `link_user`.",
ephemeral=True,
Comment on lines 1407 to 1410

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The user-facing failure message embeds error_detail = str(exc) verbatim. For EspoAPIError raised by the shared client, this may include boilerplate (e.g., "Wrong request, status code is …") and can duplicate the separately-appended status note, making the message noisy. Consider special-casing EspoAPIError to extract/display just the server reason (and escape/truncate any backticks/newlines) while keeping the full exception details only in logs/audit metadata.

Copilot uses AI. Check for mistakes.
)
Expand DownExpand Up@@ -1532,6 +1538,11 @@ def __init__(self, bot: commands.Bot) -> None:
discord_logs_webhook_wait=settings.discord_logs_webhook_wait,
)

@staticmethod
def _configured_linkedin_field() -> str:
"""Return the configured field for LinkedIn profile values."""
return str(getattr(settings, "crm_linkedin_field", "cLinkedInUrl"))

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_configured_linkedin_field() reads settings.crm_linkedin_field, but the bot Settings model doesn’t declare this field (so Pydantic Settings won’t load it from env/config and it will always fall back). Also, if the attribute were ever present but None, str(None) would yield the literal string "None". Consider adding an explicit crm_linkedin_field: str = "cLinkedInUrl" to the Settings schema (and validating/stripping it here, falling back when empty).

Suggested change
returnstr(getattr(settings, "crm_linkedin_field", "cLinkedInUrl"))
default_field="cLinkedInUrl"
raw_value=getattr(settings, "crm_linkedin_field", None)
ifnotisinstance(raw_value, str):
returndefault_field
value=raw_value.strip()
returnvalueordefault_field

Copilot uses AI. Check for mistakes.

def _audit_command(
self,
*,
Expand DownExpand Up@@ -3280,6 +3291,26 @@ def _to_values(raw_values: Any) -> list[str]:

return "\nParsed resume identifiers: " + "; ".join(summary_parts)

def _build_resume_parsed_identity_summary(self, file_content: bytes) -> str:
"""Build a short display summary of parsed contact identity fields."""
hints = self._extract_resume_contact_hints(file_content)
parsed_name = str(hints.get("name") or "").strip()
if not parsed_name:
parsed_name = self._extract_resume_name_fallback(file_content)

emails = hints.get("emails", [])
if not isinstance(emails, list):
emails = []
primary_email = "No email parsed"
if emails:
raw_email = str(emails[0]).strip()
if raw_email:
primary_email = raw_email

return (
f"\nParsed contact details: name=`{parsed_name}`, email=`{primary_email}`"
)
Comment on lines +3309 to +3312

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The parsed name/email are interpolated directly into inline-code backticks. If the extracted name/email contains a backtick, it can break formatting and potentially hide/alter surrounding text. Consider sanitizing (e.g., replace/backslash-escape backticks and truncate to a safe length) before embedding user/LLM-derived values into Discord messages.

Copilot uses AI. Check for mistakes.

def _extract_resume_name_hint(self, file_content: bytes) -> str:
"""Best-effort contact name extraction from resume text."""
hints = self._extract_resume_contact_hints(file_content)
Expand All@@ -3288,6 +3319,18 @@ def _extract_resume_name_hint(self, file_content: bytes) -> str:
return extracted_name
return self._extract_resume_name_fallback(file_content)

def _populate_name_fields(
self, payload: dict[str, str], *, source_name: str
) -> None:
"""Populate firstName and lastName fields for CRM contact creation payloads."""
first_name, last_name = self.resume_extractor.split_name(
full_name=source_name,
first_name_hint=str(payload.get("firstName", "")).strip() or None,
last_name_hint=str(payload.get("lastName", "")).strip() or None,
)
Comment on lines +3326 to +3330

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_populate_name_fields() calls resume_extractor.split_name(), which will invoke an additional LLM call whenever the OpenAI client is configured. In the resume-upload path you already may have done an LLM extraction, so this can introduce an extra API request (latency/cost/failure surface) just to split the name. Consider using heuristic-only splitting here, or plumbing through extracted first_name/last_name hints from the resume profile to avoid triggering another model call.

Copilot uses AI. Check for mistakes.
payload["firstName"] = first_name
payload["lastName"] = last_name

def _build_resume_create_contact_payload(
self, file_content: bytes
) -> dict[str, str]:
Expand All@@ -3312,6 +3355,7 @@ def _build_resume_create_contact_payload(
"type": "Prospect",
"name": contact_name,
}
self._populate_name_fields(payload, source_name=contact_name)
if emails:
primary_email = emails[0]
if primary_email.endswith("@508.dev"):
Expand All@@ -3321,7 +3365,7 @@ def _build_resume_create_contact_payload(
if github_usernames:
payload["cGitHubUsername"] = github_usernames[0]
if linkedin_urls:
payload["cLinkedInUrl"] = linkedin_urls[0]
payload[self._configured_linkedin_field()] = linkedin_urls[0]
phone = hints.get("phone")
if isinstance(phone, str) and phone.strip():
payload["phoneNumber"] = phone.strip()
Expand DownExpand Up@@ -3370,17 +3414,30 @@ def _build_contact_payload_for_link_user(
parsed_name = str(payload.get("name", "")).strip()
if not parsed_name or parsed_name == "Resume Candidate":
payload["name"] = self._fallback_contact_name_for_discord_user(user)
self._populate_name_fields(
payload, source_name=str(payload.get("name", "")).strip()
)
payload.update(self._discord_link_fields(user))
return payload

async def _search_contacts_by_field(
self, *, field: str, value: str, max_size: int = 10
) -> list[dict[str, Any]]:
"""Search contacts using an exact field equals match."""
select_fields = [
"id",
"name",
"emailAddress",
"c508Email",
"cDiscordUsername",
"cGitHubUsername",
]
if field not in select_fields:
select_fields.append(field)
search_params = {
"where": [{"type": "equals", "attribute": field, "value": value}],
"maxSize": max_size,
"select": "id,name,emailAddress,c508Email,cDiscordUsername,cGitHubUsername,cLinkedInUrl",
"select": ",".join(select_fields),
}

response = self.espo_api.request("GET", "Contact", search_params)
Expand DownExpand Up@@ -3450,7 +3507,7 @@ async def _infer_contact_from_resume(
for linkedin_url in linkedin_urls:
attempts.append({"method": "linkedin", "value": linkedin_url})
contacts = await self._search_contacts_by_field(
field="cLinkedInUrl", value=linkedin_url
field=self._configured_linkedin_field(), value=linkedin_url
)
if len(contacts) == 1:
return contacts[0], {
Expand DownExpand Up@@ -4948,7 +5005,7 @@ async def update_contact(
if linkedin is not None:
clean_linkedin = linkedin.strip()
if clean_linkedin:
update_data["cLinkedInUrl"] = clean_linkedin
update_data[self._configured_linkedin_field()] = clean_linkedin
requested_updates.append("linkedin")

if rate_range is not None:
Expand DownExpand Up@@ -5028,9 +5085,10 @@ async def update_contact(
inline=True,
)
if "linkedin" in requested_updates:
linkedin_field = self._configured_linkedin_field()
embed.add_field(
name="🔗 LinkedIn",
value=update_data["cLinkedInUrl"],
value=update_data[linkedin_field],
inline=True,
)
if "skills" in requested_updates:
Expand DownExpand Up@@ -5605,7 +5663,8 @@ async def upload_resume(
await interaction.followup.send(
"⚠️ Could not find a unique contact from this resume. "
"Would you like to create a new contact from the parsed details?"
+ inferred_attempts_text,
+ inferred_attempts_text
+ self._build_resume_parsed_identity_summary(file_content),
view=view,
ephemeral=True,
)
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); Fix resume contact inference and LinkedIn field handling by michaelmwu · Pull Request #129 · 508-dev/508-workflows · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 66 additions & 7 deletions apps/discord_bot/src/five08/discord_bot/cogs/crm.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1345,6 +1345,10 @@ async def confirm_create(
create_payload = self.crm_cog._build_resume_create_contact_payload(
file_content=self.file_content
)
self.crm_cog._populate_name_fields(
create_payload,
source_name=str(create_payload.get("name", "")).strip(),
)
target_contact = self.crm_cog.espo_api.request(
"POST", "Contact", create_payload
)
Expand DownExpand Up@@ -1375,6 +1379,8 @@ async def confirm_create(
)
except Exception as exc:
status_code = getattr(self.crm_cog.espo_api, "status_code", None)
error_detail = str(exc).strip() or "Unknown error"
status_note = f" (status {status_code})" if status_code else ""
logger.exception(
"Failed to create contact from resume filename=%s target_scope=%s inferred_meta=%s status_code=%s payload=%s",
self.filename,
Expand All@@ -1399,7 +1405,7 @@ async def confirm_create(
metadata=audit_metadata,
)
await interaction.followup.send(
"⚠️ Could not create a contact from this resume. "
f"⚠️ Could not create a contact from this resume: `{error_detail}`{status_note}. "
"Please provide `search_term` or `link_user`.",
ephemeral=True,
Comment on lines 1407 to 1410

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The user-facing failure message embeds error_detail = str(exc) verbatim. For EspoAPIError raised by the shared client, this may include boilerplate (e.g., "Wrong request, status code is …") and can duplicate the separately-appended status note, making the message noisy. Consider special-casing EspoAPIError to extract/display just the server reason (and escape/truncate any backticks/newlines) while keeping the full exception details only in logs/audit metadata.

Copilot uses AI. Check for mistakes.
)
Expand DownExpand Up@@ -1532,6 +1538,11 @@ def __init__(self, bot: commands.Bot) -> None:
discord_logs_webhook_wait=settings.discord_logs_webhook_wait,
)

@staticmethod
def _configured_linkedin_field() -> str:
"""Return the configured field for LinkedIn profile values."""
return str(getattr(settings, "crm_linkedin_field", "cLinkedInUrl"))

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_configured_linkedin_field() reads settings.crm_linkedin_field, but the bot Settings model doesn’t declare this field (so Pydantic Settings won’t load it from env/config and it will always fall back). Also, if the attribute were ever present but None, str(None) would yield the literal string "None". Consider adding an explicit crm_linkedin_field: str = "cLinkedInUrl" to the Settings schema (and validating/stripping it here, falling back when empty).

Suggested change
returnstr(getattr(settings, "crm_linkedin_field", "cLinkedInUrl"))
default_field="cLinkedInUrl"
raw_value=getattr(settings, "crm_linkedin_field", None)
ifnotisinstance(raw_value, str):
returndefault_field
value=raw_value.strip()
returnvalueordefault_field

Copilot uses AI. Check for mistakes.

def _audit_command(
self,
*,
Expand DownExpand Up@@ -3280,6 +3291,26 @@ def _to_values(raw_values: Any) -> list[str]:

return "\nParsed resume identifiers: " + "; ".join(summary_parts)

def _build_resume_parsed_identity_summary(self, file_content: bytes) -> str:
"""Build a short display summary of parsed contact identity fields."""
hints = self._extract_resume_contact_hints(file_content)
parsed_name = str(hints.get("name") or "").strip()
if not parsed_name:
parsed_name = self._extract_resume_name_fallback(file_content)

emails = hints.get("emails", [])
if not isinstance(emails, list):
emails = []
primary_email = "No email parsed"
if emails:
raw_email = str(emails[0]).strip()
if raw_email:
primary_email = raw_email

return (
f"\nParsed contact details: name=`{parsed_name}`, email=`{primary_email}`"
)
Comment on lines +3309 to +3312

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The parsed name/email are interpolated directly into inline-code backticks. If the extracted name/email contains a backtick, it can break formatting and potentially hide/alter surrounding text. Consider sanitizing (e.g., replace/backslash-escape backticks and truncate to a safe length) before embedding user/LLM-derived values into Discord messages.

Copilot uses AI. Check for mistakes.

def _extract_resume_name_hint(self, file_content: bytes) -> str:
"""Best-effort contact name extraction from resume text."""
hints = self._extract_resume_contact_hints(file_content)
Expand All@@ -3288,6 +3319,18 @@ def _extract_resume_name_hint(self, file_content: bytes) -> str:
return extracted_name
return self._extract_resume_name_fallback(file_content)

def _populate_name_fields(
self, payload: dict[str, str], *, source_name: str
) -> None:
"""Populate firstName and lastName fields for CRM contact creation payloads."""
first_name, last_name = self.resume_extractor.split_name(
full_name=source_name,
first_name_hint=str(payload.get("firstName", "")).strip() or None,
last_name_hint=str(payload.get("lastName", "")).strip() or None,
)
Comment on lines +3326 to +3330

CopilotAIMar 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_populate_name_fields() calls resume_extractor.split_name(), which will invoke an additional LLM call whenever the OpenAI client is configured. In the resume-upload path you already may have done an LLM extraction, so this can introduce an extra API request (latency/cost/failure surface) just to split the name. Consider using heuristic-only splitting here, or plumbing through extracted first_name/last_name hints from the resume profile to avoid triggering another model call.

Copilot uses AI. Check for mistakes.
payload["firstName"] = first_name
payload["lastName"] = last_name

def _build_resume_create_contact_payload(
self, file_content: bytes
) -> dict[str, str]:
Expand All@@ -3312,6 +3355,7 @@ def _build_resume_create_contact_payload(
"type": "Prospect",
"name": contact_name,
}
self._populate_name_fields(payload, source_name=contact_name)
if emails:
primary_email = emails[0]
if primary_email.endswith("@508.dev"):
Expand All@@ -3321,7 +3365,7 @@ def _build_resume_create_contact_payload(
if github_usernames:
payload["cGitHubUsername"] = github_usernames[0]
if linkedin_urls:
payload["cLinkedInUrl"] = linkedin_urls[0]
payload[self._configured_linkedin_field()] = linkedin_urls[0]
phone = hints.get("phone")
if isinstance(phone, str) and phone.strip():
payload["phoneNumber"] = phone.strip()
Expand DownExpand Up@@ -3370,17 +3414,30 @@ def _build_contact_payload_for_link_user(
parsed_name = str(payload.get("name", "")).strip()
if not parsed_name or parsed_name == "Resume Candidate":
payload["name"] = self._fallback_contact_name_for_discord_user(user)
self._populate_name_fields(
payload, source_name=str(payload.get("name", "")).strip()
)
payload.update(self._discord_link_fields(user))
return payload

async def _search_contacts_by_field(
self, *, field: str, value: str, max_size: int = 10
) -> list[dict[str, Any]]:
"""Search contacts using an exact field equals match."""
select_fields = [
"id",
"name",
"emailAddress",
"c508Email",
"cDiscordUsername",
"cGitHubUsername",
]
if field not in select_fields:
select_fields.append(field)
search_params = {
"where": [{"type": "equals", "attribute": field, "value": value}],
"maxSize": max_size,
"select": "id,name,emailAddress,c508Email,cDiscordUsername,cGitHubUsername,cLinkedInUrl",
"select": ",".join(select_fields),
}

response = self.espo_api.request("GET", "Contact", search_params)
Expand DownExpand Up@@ -3450,7 +3507,7 @@ async def _infer_contact_from_resume(
for linkedin_url in linkedin_urls:
attempts.append({"method": "linkedin", "value": linkedin_url})
contacts = await self._search_contacts_by_field(
field="cLinkedInUrl", value=linkedin_url
field=self._configured_linkedin_field(), value=linkedin_url
)
if len(contacts) == 1:
return contacts[0], {
Expand DownExpand Up@@ -4948,7 +5005,7 @@ async def update_contact(
if linkedin is not None:
clean_linkedin = linkedin.strip()
if clean_linkedin:
update_data["cLinkedInUrl"] = clean_linkedin
update_data[self._configured_linkedin_field()] = clean_linkedin
requested_updates.append("linkedin")

if rate_range is not None:
Expand DownExpand Up@@ -5028,9 +5085,10 @@ async def update_contact(
inline=True,
)
if "linkedin" in requested_updates:
linkedin_field = self._configured_linkedin_field()
embed.add_field(
name="🔗 LinkedIn",
value=update_data["cLinkedInUrl"],
value=update_data[linkedin_field],
inline=True,
)
if "skills" in requested_updates:
Expand DownExpand Up@@ -5605,7 +5663,8 @@ async def upload_resume(
await interaction.followup.send(
"⚠️ Could not find a unique contact from this resume. "
"Would you like to create a new contact from the parsed details?"
+ inferred_attempts_text,
+ inferred_attempts_text
+ self._build_resume_parsed_identity_summary(file_content),
view=view,
ephemeral=True,
)
Expand Down
Loading
Loading