mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 11:59:26 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Chat replies, comments and documents render Markdown through
`MarkdownBody`. Task links in that Markdown become company-aware links
> - `parseIssueReferenceFromHref` turned every task link into an
unprefixed `/issues/<id>` path. The router then added the viewer's
active company prefix
> - In chat-eval cohort 4 (`access.other-company`), a reply in company
COM linked `/BIR/issues/BIR-1`. The chat rendered it as
`/COM/issues/BIR-1`, which points into the wrong company
> - This pull request keeps the company that a task link names: an
explicit `/BIR/issues/...` prefix, or an identifier whose prefix belongs
to a known company
> - The benefit is that a link to another company's task opens that
company's task, not a same-numbered task or an error in the current
company
## Linked Issues or Issue Description
**What happened?**
A chat reply in company COM contained `[BIR-1](/BIR/issues/BIR-1)`. The
rendered link pointed to `/COM/issues/BIR-1`.
**Expected behavior**
A task link that names a company keeps that company: `/BIR/issues/BIR-1`
stays `/BIR/issues/BIR-1`. A bare `BIR-1` or `/issues/BIR-1` goes to BIR
when BIR is a company that the viewer knows.
**Steps to reproduce**
1. Have two companies, COM and BIR.
2. In a COM chat or comment, render the Markdown
`[BIR-1](/BIR/issues/BIR-1)`.
3. Inspect the link. Its `href` is `/COM/issues/BIR-1`.
**Paperclip version or commit**
master at f1aef0cb58.
## What Changed
- `ui/src/lib/issue-reference.ts`: a new `issueHref` builds the internal
link. It keeps the company prefix of an explicit `/PREFIX/issues/...`
path. When the path has no prefix, it uses the identifier's prefix if
that prefix is in the known company prefixes. Otherwise the link stays
`/issues/<id>` and resolves in the active company, as before.
- `ui/src/components/MarkdownBody.tsx`: passes the known company
prefixes to the explicit-link path too (the auto-link path already had
them).
- Tests: a red/green unit test with the recorded shape in
`issue-reference.test.ts`, and a rendered test in
`MarkdownBody.test.tsx` (COM and BIR known; explicit, bare and
unprefixed BIR links all render `/BIR/issues/BIR-1`). Existing
expectations that asserted the stripped `/issues/<id>` form now assert
the company-prefixed form.
## Verification
- `cd ui && npx vitest run src/components/MarkdownBody.test.tsx
src/lib/issue-reference.test.ts src/lib/company-routes.test.ts`: 105
tests pass.
- Red/green: with `issue-reference.ts` and `MarkdownBody.tsx` from
`origin/master`, the new tests fail (`/issues/BIR-1` instead of
`/BIR/issues/BIR-1`). With the change, they pass.
- `pnpm check:token-gates` is clean. `tsc -p ui/tsconfig.json` reports
only existing errors in
`ui/storybook/support/feature-map/FeatureOverview.tsx`, which this
change does not touch.
- A paid chat-eval run with this change is linked in a comment below.
## Risks
- Same-company links now carry the explicit prefix (`/COM/issues/COM-1`
instead of `/issues/COM-1` resolved to the same place). The route is the
same.
- An explicit link with a bare identifier as its target (`[x](JIRA-2)`)
is now gated by known company prefixes like auto-linked text. Such a
link to a non-Paperclip key stays an ordinary link.
- Low risk otherwise: no API, data or saved state changes.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code
execution in Claude Code.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
203 lines
6.9 KiB
TypeScript
203 lines
6.9 KiB
TypeScript
import { extractCompanyPrefixFromPath } from "./company-routes.js";
|
|
type MarkdownNode = {
|
|
type: string;
|
|
value?: string;
|
|
url?: string;
|
|
children?: MarkdownNode[];
|
|
};
|
|
|
|
const BARE_ISSUE_IDENTIFIER_RE = /^[A-Z][A-Z0-9]*-\d+$/i;
|
|
const ISSUE_SCHEME_RE = /^issue:\/\/:?([^?#\s]+)([?#].*)?$/i;
|
|
const ISSUE_REFERENCE_TOKEN_RE = /issue:\/\/:?[^\s<>()]+|https?:\/\/[^\s<>()]+|\/(?:[^\s<>()/]+\/)*issues\/[A-Z][A-Z0-9]*-\d+(?=$|[\s<>)\],.;!?:])|\b[A-Z][A-Z0-9]*-\d+\b/gi;
|
|
|
|
export function parseIssuePathIdFromPath(pathOrUrl: string | null | undefined): string | null {
|
|
if (!pathOrUrl) return null;
|
|
const value = pathOrUrl.trim();
|
|
if (!value) return null;
|
|
if (/^https?:\/\//i.test(value)) return null;
|
|
const pathname = value.split(/[?#]/, 1)[0]!;
|
|
|
|
const segments = pathname.split("/").filter(Boolean);
|
|
const issueIndex = segments.findIndex((segment) => segment === "issues");
|
|
if (issueIndex === -1 || issueIndex === segments.length - 1) return null;
|
|
const issuePathId = decodeURIComponent(segments[issueIndex + 1] ?? "");
|
|
if (!issuePathId || issuePathId.startsWith(":")) return null;
|
|
return BARE_ISSUE_IDENTIFIER_RE.test(issuePathId) ? issuePathId.toUpperCase() : issuePathId;
|
|
}
|
|
|
|
export function parseIssueReferenceFromHref(
|
|
href: string | null | undefined,
|
|
knownPrefixes?: Set<string>,
|
|
) {
|
|
if (!href) return null;
|
|
const trimmed = href.trim();
|
|
const issueSchemeMatch = trimmed.match(ISSUE_SCHEME_RE);
|
|
if (issueSchemeMatch?.[1]) {
|
|
const issuePathId = decodeURIComponent(issueSchemeMatch[1]);
|
|
return {
|
|
issuePathId,
|
|
href: issueHref(issuePathId, issueSchemeMatch[2] ?? "", null, knownPrefixes),
|
|
};
|
|
}
|
|
|
|
const pathId = parseIssuePathIdFromPath(href);
|
|
if (pathId) {
|
|
return {
|
|
issuePathId: pathId,
|
|
href: issueHref(
|
|
pathId,
|
|
trimmed.match(/[?#].*$/)?.[0] ?? "",
|
|
extractCompanyPrefixFromPath(trimmed.split(/[?#]/, 1)[0]!),
|
|
knownPrefixes,
|
|
),
|
|
};
|
|
}
|
|
|
|
if (!BARE_ISSUE_IDENTIFIER_RE.test(trimmed)) return null;
|
|
const normalized = trimmed.toUpperCase();
|
|
// Only auto-link a bare IDENT-123 token when its prefix belongs to a known
|
|
// company. An empty or omitted set means "prefixes unknown" -> stay permissive
|
|
// (preserves behavior during initial load and in provider-less render
|
|
// surfaces). The issue:// scheme and /issues/ path forms handled above are
|
|
// never gated -- they are deliberate references, not accidental foreign keys.
|
|
if (knownPrefixes && knownPrefixes.size > 0) {
|
|
const prefix = normalized.split("-")[0];
|
|
if (!prefix || !knownPrefixes.has(prefix)) return null;
|
|
}
|
|
return {
|
|
issuePathId: normalized,
|
|
href: issueHref(normalized, "", null, knownPrefixes),
|
|
};
|
|
}
|
|
|
|
function issueHref(
|
|
issuePathId: string,
|
|
suffix: string,
|
|
pathCompanyPrefix: string | null,
|
|
knownPrefixes?: Set<string>,
|
|
): string {
|
|
const identifierPrefix = BARE_ISSUE_IDENTIFIER_RE.test(issuePathId)
|
|
? issuePathId.split("-")[0]!.toUpperCase()
|
|
: null;
|
|
const companyPrefix =
|
|
pathCompanyPrefix ??
|
|
(identifierPrefix && knownPrefixes?.has(identifierPrefix) ? identifierPrefix : null);
|
|
const path = `/issues/${encodeURIComponent(issuePathId)}${suffix}`;
|
|
return companyPrefix ? `/${companyPrefix}${path}` : path;
|
|
}
|
|
|
|
function splitTrailingPunctuation(token: string) {
|
|
let core = token;
|
|
let trailing = "";
|
|
|
|
while (core.length > 0) {
|
|
const lastChar = core.at(-1);
|
|
if (!lastChar || !/[),.;!?:\]]/.test(lastChar)) break;
|
|
if (lastChar === ")") {
|
|
const openCount = (core.match(/\(/g) ?? []).length;
|
|
const closeCount = (core.match(/\)/g) ?? []).length;
|
|
if (closeCount <= openCount) break;
|
|
}
|
|
if (lastChar === "]") {
|
|
const openCount = (core.match(/\[/g) ?? []).length;
|
|
const closeCount = (core.match(/\]/g) ?? []).length;
|
|
if (closeCount <= openCount) break;
|
|
}
|
|
trailing = `${lastChar}${trailing}`;
|
|
core = core.slice(0, -1);
|
|
}
|
|
|
|
return { core, trailing };
|
|
}
|
|
|
|
function createIssueLinkNode(value: string, href: string, childType: "text" | "inlineCode" = "text"): MarkdownNode {
|
|
return {
|
|
type: "link",
|
|
url: href,
|
|
children: [{ type: childType, value }],
|
|
};
|
|
}
|
|
|
|
function linkifyIssueReferencesInText(value: string, knownPrefixes?: Set<string>): MarkdownNode[] | null {
|
|
const nodes: MarkdownNode[] = [];
|
|
let cursor = 0;
|
|
let matched = false;
|
|
|
|
for (const match of value.matchAll(ISSUE_REFERENCE_TOKEN_RE)) {
|
|
const raw = match[0];
|
|
if (!raw) continue;
|
|
|
|
const start = match.index ?? 0;
|
|
const end = start + raw.length;
|
|
const { core, trailing } = splitTrailingPunctuation(raw);
|
|
const issueRef = parseIssueReferenceFromHref(core, knownPrefixes);
|
|
if (!issueRef) continue;
|
|
|
|
matched = true;
|
|
if (start > cursor) {
|
|
nodes.push({ type: "text", value: value.slice(cursor, start) });
|
|
}
|
|
nodes.push(createIssueLinkNode(core, issueRef.href));
|
|
if (trailing) {
|
|
nodes.push({ type: "text", value: trailing });
|
|
}
|
|
cursor = end;
|
|
}
|
|
|
|
if (!matched) return null;
|
|
if (cursor < value.length) {
|
|
nodes.push({ type: "text", value: value.slice(cursor) });
|
|
}
|
|
return nodes;
|
|
}
|
|
|
|
function rewriteMarkdownTree(node: MarkdownNode, knownPrefixes?: Set<string>) {
|
|
if (!Array.isArray(node.children) || node.children.length === 0) return;
|
|
if (node.type === "link" || node.type === "linkReference" || node.type === "code" || node.type === "definition" || node.type === "html") {
|
|
return;
|
|
}
|
|
|
|
const nextChildren: MarkdownNode[] = [];
|
|
for (const child of node.children) {
|
|
if (child.type === "inlineCode" && typeof child.value === "string") {
|
|
const issueRef = parseIssueReferenceFromHref(child.value, knownPrefixes);
|
|
if (issueRef) {
|
|
nextChildren.push(createIssueLinkNode(child.value, issueRef.href, "inlineCode"));
|
|
continue;
|
|
}
|
|
}
|
|
|
|
if (child.type === "text" && typeof child.value === "string") {
|
|
const linked = linkifyIssueReferencesInText(child.value, knownPrefixes);
|
|
if (linked) {
|
|
nextChildren.push(...linked);
|
|
continue;
|
|
}
|
|
}
|
|
|
|
rewriteMarkdownTree(child, knownPrefixes);
|
|
nextChildren.push(child);
|
|
}
|
|
node.children = nextChildren;
|
|
}
|
|
|
|
export interface RemarkLinkIssueReferencesOptions {
|
|
/**
|
|
* Company issue prefixes that are eligible for auto-linking. When provided
|
|
* and non-empty, a bare IDENT-123 token only becomes an issue link if its
|
|
* prefix is in this set -- this keeps foreign tracker keys (e.g. a Jira
|
|
* "TREE-604") from linking to non-existent Paperclip issues. Omit or pass an
|
|
* empty list to keep the legacy permissive behavior (link any IDENT-123).
|
|
*/
|
|
knownPrefixes?: string[];
|
|
}
|
|
|
|
export function remarkLinkIssueReferences(options?: RemarkLinkIssueReferencesOptions) {
|
|
const knownPrefixes = options?.knownPrefixes && options.knownPrefixes.length > 0
|
|
? new Set(options.knownPrefixes.map((prefix) => prefix.toUpperCase()))
|
|
: undefined;
|
|
return (tree: MarkdownNode) => {
|
|
rewriteMarkdownTree(tree, knownPrefixes);
|
|
};
|
|
}
|