fix(server): turn agents' made-up-host Paperclip links into relative routes (#21762)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents post chat replies and task comments that link board pages and
attachments
> - Some models invent a hostname for these links, such as
`https://paperclip.local/COM/agents/<id>` or
`https://paperclip/api/attachments/<id>/content`
> - Those hosts do not exist, so the person clicks a broken link
> - The chat guidance already says never to invent a hostname, but a
model can still do it
> - This pull request rewrites such links to relative app routes before
an agent comment is saved, and adds the rule to the Paperclip skill
> - The benefit is that every board and attachment link an agent writes
opens, on whatever origin the reader uses

## Linked Issues or Issue Description

**What happened?**
Chat-eval cohort 16 (OpenCode with
`openrouter/deepseek/deepseek-v4.1-flash-1017`, master 819f61f1fd). In
`agents.edit-instructions`, the reply linked Morgan as
`[Morgan](https://paperclip.local/COM/agents/<id>)`. In
`onboarding.first-work`, the worker's summary linked its attachments as
`https://paperclip/api/attachments/<id>/content`. Neither host exists.

**Expected behavior**
An agent's link to a Paperclip board or API route opens. Genuine
external links, the instance's own origin, and links inside code stay as
written.

**Steps to reproduce**
Post an agent comment that contains
`[Morgan](https://paperclip.local/<PREFIX>/agents/<id>)`. Before this
change it is stored as written. After it, the stored body links
`/<PREFIX>/agents/<id>`.

## What Changed

- New `server/src/services/agent-invented-host-links.ts`. It rewrites an
absolute link to a relative route only when all of these are true:
- The host is made up: `paperclip`, or `paperclip.<reserved TLD>`
(`local`, `localhost`, `internal`, `test`, `example`, `invalid`, `lan`),
or a loopback host.
- The path is a known board route (`/<PREFIX>/<board root>…`) or, on a
made-up Paperclip host only, `/api/…`.
- A loopback host (`localhost`, `127.x`, `[::1]`) qualifies only for a
board route under the comment's own company prefix. A local app that the
agent built keeps its link, including its `/api` paths.
  - The origin is not this instance's configured public origin.
  - The link is outside fenced and inline code.
- Markdown link targets keep their place. Bare links and autolinks
become Markdown links, so they stay clickable.
- `issueService.addComment` applies it to agent-authored comments,
before the redaction and dedupe steps, so a retried identical comment
still deduplicates. The run-presentation check still compares the text
that the agent wrote. People's comments are not changed.
- `skills/paperclip/SKILL.md` now tells agents to write board and
attachment links as relative paths and never add a hostname.

## Verification

- `pnpm vitest run
server/src/services/agent-invented-host-links.test.ts` (19 tests):
recorded cohort 16 links are rewritten. Negative controls stay
unchanged: external links, a production Paperclip host, the instance's
own origin, local app links, another prefix on localhost, a non-route
path, another single-label host, inline code, a fence, and relative
links.
- `server/src/__tests__/issues-service.test.ts` new case: an agent
comment is stored with the relative route, and a person's identical
comment is stored as written. It fails on master and passes with this
change.
- Per-message cost (local tsx micro-benchmark): the gate on a comment
with no candidate host takes 0.3 µs (500 chars), 1.2 µs (2 KB) and 4.7
µs (8 KB). Only when a candidate exists does it read the company prefix
(one indexed select) and the public origin (config read once per
process), and rewrite (4–40 µs). Nothing runs before a turn starts.
- `server` typecheck passes.

## Risks

- A link on a made-up host to a board route of another company prefix
becomes relative. It opens that route on the reader's instance, where
access checks still apply.
- External channels that cannot resolve relative links already get
relative links from agents today. This change does not alter their
delivery.

## Model Used

- Claude, `claude-opus-5-5` (Claude Code agent with tool use and code
execution).

## 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>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-15 08:44:06 -06:00
1 parent 348ed0ae10
commit eb65fc0941
5 files changed
+280 -2

No files matched your search

@@ -7046,4 +7046,13 @@ describeEmbeddedPostgres("issueService.addComment createdByRunId", () => {
.where(eq(issueComments.createdByRunId, runId));
expect(duplicates).toHaveLength(1);
});
it("stores an agent's made-up-host board link as a relative route, and a person's as written", async () => {
const [{ issuePrefix }] = await db.select({ issuePrefix: companies.issuePrefix }).from(companies).where(eq(companies.id, companyId));
const written = `I updated [Morgan](https://paperclip.local/${issuePrefix}/agents/${agentId}); see [docs](https://docs.github.com/a).`;
const agentComment = await svc.addComment(issueId, written, { agentId });
expect(agentComment.body).toBe(`I updated [Morgan](/${issuePrefix}/agents/${agentId}); see [docs](https://docs.github.com/a).`);
const userComment = await svc.addComment(issueId, written, { userId: "board-user" });
expect(userComment.body).toBe(written);
});
});
@@ -0,0 +1,74 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { BOARD_ROUTE_ROOTS, mayContainInventedHostLink, relativizeInventedHostLinks, type InventedHostLinkContext } from "./agent-invented-host-links.js";
const context: InventedHostLinkContext = { companyPrefix: "COM", ownOrigin: "https://board.example.com" };
const rewrite = (text: string, overrides: Partial<InventedHostLinkContext> = {}) =>
relativizeInventedHostLinks(text, { ...context, ...overrides });
describe("invented-host Paperclip links", () => {
it("rewrites the recorded cohort 16 reply link to a relative route", () => {
// Recorded from chat-eval cohort 16 (agents.edit-instructions).
const reply = "Done — I added the rule to [Morgan](https://paperclip.local/COM/agents/1fffd0bf-177a-4f4f-bb58-008160e407d5)'s persistent instructions in AGENTS.md.";
expect(rewrite(reply)).toBe("Done — I added the rule to [Morgan](/COM/agents/1fffd0bf-177a-4f4f-bb58-008160e407d5)'s persistent instructions in AGENTS.md.");
});
it("rewrites the recorded cohort 16 attachment link on host paperclip", () => {
// Recorded from chat-eval cohort 16 (onboarding.first-work worker comment).
expect(rewrite("[index.html](https://paperclip/api/attachments/29ddbfd9-3dfc-4798-87d4-84fb99e68764/content)"))
.toBe("[index.html](/api/attachments/29ddbfd9-3dfc-4798-87d4-84fb99e68764/content)");
});
it.each([
["a bare link with sentence punctuation", "See https://paperclip.local/COM/issues/COM-2.", "See [/COM/issues/COM-2](/COM/issues/COM-2)."],
["an autolink", "Open <https://paperclip/COM/approvals/a1>", "Open [/COM/approvals/a1](/COM/approvals/a1)"],
["a query and hash", "[plan](http://paperclip.internal:3100/COM/issues/COM-2#document-plan)", "[plan](/COM/issues/COM-2#document-plan)"],
["a localhost board link under this company's prefix", "[COM-2](http://localhost:3100/COM/issues/COM-2)", "[COM-2](/COM/issues/COM-2)"],
["an angle-bracket link destination", "[Morgan](<https://paperclip.local/COM/agents/morgan>)", "[Morgan](</COM/agents/morgan>)"],
["a reference definition", "See [Morgan].\n\n[Morgan]: https://paperclip.local/COM/agents/morgan", "See [Morgan].\n\n[Morgan]: /COM/agents/morgan"],
["an angle-bracket reference definition", "[Morgan]: <https://paperclip/COM/agents/morgan>", "[Morgan]: </COM/agents/morgan>"],
["an IPv6 loopback link", "[COM-2](http://[::1]:3100/COM/issues/COM-2)", "[COM-2](/COM/issues/COM-2)"],
["a profile page", "[Morgan](https://paperclip.local/COM/u/morgan)", "[Morgan](/COM/u/morgan)"],
["a link after quoted prose", "> Morgan said so.\n\nSee [COM-2](https://paperclip/COM/issues/COM-2).", "> Morgan said so.\n\nSee [COM-2](/COM/issues/COM-2)."],
["a loopback link under this company's prefix in lower case", "[case](http://127.0.0.1:3100/com/cases/COM-C1)", "[case](/com/cases/COM-C1)"],
])("rewrites %s", (_label, text, expected) => {
expect(rewrite(text)).toBe(expected);
});
it.each([
["a genuine external link", "[docs](https://docs.github.com/COM/issues/1)"],
["a production Paperclip host", "[COM-2](https://paperclip.staging.paperclip.app/COM/issues/COM-2)"],
["this instance's own origin", "[COM-2](https://board.example.com/COM/issues/COM-2)"],
["a local app the agent built", "Open http://localhost:5173/ and call http://localhost:3000/api/hello."],
["a localhost route under another prefix", "[x](http://localhost:3100/V1/projects)"],
["a non-route path on an invented host", "[x](https://paperclip.local/about)"],
["a single-label host other than paperclip", "[build](http://jenkins/api/json)"],
["a link in inline code", "Run `curl https://paperclip/api/issues/COM-1` to check."],
["a link in a fence", "```sh\ncurl https://paperclip.local/COM/issues/COM-1\n```"],
["a link in a fence inside a block quote", "> ```sh\n> curl https://paperclip/api/issues/COM-1\n> ```"],
["a link in a fence inside a list item", "1. Run:\n ```sh\n curl https://paperclip/api/issues/COM-1\n ```"],
["a link in an indented code block", "Run this:\n\n curl https://paperclip/api/issues/COM-1\n echo done"],
["a link in inline code across lines", "Run `curl\nhttps://paperclip/api/issues/COM-1` to check."],
["a link in double-backtick code", "Run ``curl https://paperclip/api/issues/COM-1`` now."],
["a relative link", "[COM-2](/COM/issues/COM-2)"],
])("leaves %s alone", (_label, text) => {
expect(rewrite(text)).toBe(text);
});
it("knows every board route root the app serves", () => {
const source = readFileSync(new URL("../../../ui/src/lib/company-routes.ts", import.meta.url), "utf8");
const block = /const BOARD_ROUTE_ROOTS = new Set\(\[([\s\S]*?)\]\)/.exec(source)?.[1] ?? "";
const roots = [...block.matchAll(/"([^"]+)"/g)].map(match => match[1]!);
expect(roots.length).toBeGreaterThan(10);
expect(roots.filter(root => !BOARD_ROUTE_ROOTS.has(root))).toEqual([]);
});
it("keeps a localhost link when the company prefix is unknown", () => {
expect(rewrite("[COM-2](http://localhost:3100/COM/issues/COM-2)", { companyPrefix: null })).toBe("[COM-2](http://localhost:3100/COM/issues/COM-2)");
});
it("skips ordinary prose without parsing", () => {
expect(mayContainInventedHostLink("Saved [COM-2](/COM/issues/COM-2) and https://github.com/x/y.")).toBe(false);
expect(mayContainInventedHostLink("see https://paperclip/api/x")).toBe(true);
});
});
@@ -0,0 +1,184 @@
/**
* Agents sometimes write a Paperclip link with a hostname they made up, such
* as https://paperclip.local/COM/agents/<id> or https://paperclip/api/...
* Neither host exists, so the link does not open. When the path is a known
* board or API route, the relative form opens on whatever origin the reader
* already uses. Every other link, and anything inside code, is left alone.
*/
import { loadConfig } from "../config.js";
// Board route roots after the company prefix: every root in
// ui/src/lib/company-routes.ts (a test keeps them aligned), plus the case and
// status pages agents are told to link.
export const BOARD_ROUTE_ROOTS = new Set([
"dashboard", "companies", "company", "skills", "teams-catalog", "org", "agents", "chats", "apps",
"projects", "workspaces", "execution-workspaces", "issues", "tasks", "routines", "goals", "artifacts",
"tools", "approvals", "costs", "usage", "activity", "audit", "decisions", "inbox", "board-chat", "u",
"design-guide", "search", "settings", "timeline", "cases", "status", "status-cards",
]);
const URL_PATTERN = /https?:\/\/(?:\[[0-9A-Fa-f:.]+\](?::\d+)?|[^\s/?#()<>[\]"'`]+)[^\s()<>[\]"'`]*/gi;
// A cheap test before any parsing: the text links one of the hosts below.
const CANDIDATE_PATTERN = /https?:\/\/(?:[^\s/@]*@)?(?:[a-z0-9-]+\.)*(?:paperclip(?:[.:/]|\s|$)|localhost|127\.|0\.0\.0\.0|\[::1\])/i;
const RESERVED_TLDS = new Set(["local", "localhost", "internal", "test", "example", "invalid", "lan"]);
export type InventedHostLinkContext = {
/** This company's issue prefix, such as COM. */
companyPrefix: string | null;
/** This instance's own public origin; its links are never rewritten. */
ownOrigin: string | null;
};
/** A host that only ever names Paperclip and resolves nowhere public. */
function isInventedPaperclipHost(hostname: string): boolean {
if (hostname === "paperclip") return true;
const labels = hostname.split(".");
return labels.length >= 2 && labels.at(-2) === "paperclip" && RESERVED_TLDS.has(labels.at(-1)!);
}
function isLoopbackHost(hostname: string): boolean {
return hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "[::1]"
|| hostname === "0.0.0.0" || /^127(?:\.\d{1,3}){3}$/.test(hostname);
}
export function mayContainInventedHostLink(text: string): boolean {
return text.includes("://") && CANDIDATE_PATTERN.test(text);
}
/**
* The relative app route for an absolute link on a made-up Paperclip host, or
* null to leave the link alone. A loopback host can be a real local app the
* agent built, so it qualifies only for a board route under this company's
* own prefix, never for an /api path.
*/
function relativeRoute(raw: string, context: InventedHostLinkContext): string | null {
let url: URL;
try {
url = new URL(raw);
} catch {
return null;
}
const hostname = url.hostname.toLowerCase();
const invented = isInventedPaperclipHost(hostname);
if (!invented && !isLoopbackHost(hostname)) return null;
if (context.ownOrigin && url.origin === context.ownOrigin) return null;
const [, prefix = "", rootSegment = ""] = url.pathname.split("/");
const route = `${url.pathname}${url.search}${url.hash}`;
if (prefix === "api") return invented && rootSegment ? route : null;
if (!/^[A-Za-z][A-Za-z0-9]{0,15}$/.test(prefix) || !BOARD_ROUTE_ROOTS.has(rootSegment.toLowerCase())) return null;
if (invented) return route;
return context.companyPrefix && prefix.toUpperCase() === context.companyPrefix.toUpperCase() ? route : null;
}
// A Markdown reference definition up to its destination: `[id]: <`.
const REFERENCE_DEFINITION = /(?:^|\n) {0,3}\[[^\]\n]+\]:[ \t]*<?$/;
/**
* The text with every Markdown code region blanked, keeping offsets: fenced
* blocks (also inside block quotes or list items), indented code blocks, and
* inline code spans, which may cross lines within a paragraph.
*/
function maskCode(text: string): string {
const lines = text.split("\n");
let fence: { char: string; length: number } | null = null;
let previousBlank = true;
let inIndentedBlock = false;
const masked = lines.map(line => {
const body = line.replace(/^(?:[ \t]*>)+[ \t]?/, "");
const marker = /^[ \t]*(`{3,}|~{3,})(.*)$/.exec(body);
const blank = !body.trim();
let code = false;
if (fence) {
code = true;
if (marker && marker[1]![0] === fence.char && marker[1]!.length >= fence.length && !marker[2]!.trim()) fence = null;
} else if (marker && !(marker[1]![0] === "`" && marker[2]!.includes("`"))) {
fence = { char: marker[1]![0]!, length: marker[1]!.length };
code = true;
} else if (!blank && /^(?: {4}|\t)/.test(body) && (previousBlank || inIndentedBlock)) {
code = true;
}
inIndentedBlock = code && !fence && !marker ? true : blank ? inIndentedBlock : false;
previousBlank = blank;
return code ? " ".repeat(line.length) : line;
}).join("\n");
// Inline spans: a backtick run closes at the next run of the same length in
// its paragraph; an escaped backtick opens nothing.
const chars = masked.split("");
for (let index = 0; index < masked.length; index += 1) {
if (masked[index] === "\\") {
index += 1;
continue;
}
if (masked[index] !== "`") continue;
let length = 1;
while (masked[index + length] === "`") length += 1;
const paragraphEnd = masked.indexOf("\n\n", index);
const limit = paragraphEnd < 0 ? masked.length : paragraphEnd;
let close = -1;
for (let at = index + length; at < limit; at += 1) {
if (masked[at] !== "`") continue;
let run = 1;
while (masked[at + run] === "`") run += 1;
if (run === length) {
close = at;
break;
}
at += run - 1;
}
if (close < 0) {
index += length - 1;
continue;
}
for (let at = index; at < close + length; at += 1) if (chars[at] !== "\n") chars[at] = " ";
index = close + length - 1;
}
return chars.join("");
}
/** Rewrite made-up-host Paperclip links outside Markdown code. */
export function relativizeInventedHostLinks(text: string, context: InventedHostLinkContext): string {
if (!mayContainInventedHostLink(text)) return text;
const masked = maskCode(text);
let result = "";
let cursor = 0;
for (const match of masked.matchAll(URL_PATTERN)) {
const offset = match.index!;
// Sentence punctuation after a bare link is not part of it.
const raw = match[0].replace(/[.,;:!?]+$/, "");
const route = relativeRoute(raw, context);
if (!route) continue;
const before = text.slice(Math.max(0, offset - 3), offset);
const end = offset + raw.length;
// A link destination (inline, angle-bracketed or a reference definition),
// link text, or an attribute value keeps its place. An autolink or a bare
// link becomes a Markdown link so it stays clickable.
const autolink = before.endsWith("<") && text[end] === ">" && !before.endsWith("](<") && !REFERENCE_DEFINITION.test(text.slice(0, offset));
const inPlace = !autolink && (before.endsWith("](") || before.endsWith("](<") || before.endsWith("[")
|| /["'=]$/.test(before) || REFERENCE_DEFINITION.test(text.slice(Math.max(0, offset - 300), offset)));
if (autolink) {
result += `${text.slice(cursor, offset - 1)}[${route}](${route})`;
cursor = end + 1;
} else {
result += `${text.slice(cursor, offset)}${inPlace ? route : `[${route}](${route})`}`;
cursor = end;
}
}
return cursor === 0 ? text : result + text.slice(cursor);
}
let cachedOwnOrigin: string | null | undefined;
/**
* This instance's configured public origin. Read once per process, and only
* when a candidate link appears, because loading the config reads its file.
*/
export function instancePublicOrigin(): string | null {
if (cachedOwnOrigin !== undefined) return cachedOwnOrigin;
try {
const base = loadConfig().authPublicBaseUrl;
cachedOwnOrigin = base ? new URL(base).origin : null;
} catch {
cachedOwnOrigin = null;
}
return cachedOwnOrigin;
}
+12 -1
View File
@@ -1,5 +1,6 @@
import { recordMcpAttachmentCleanup, type McpAttachmentCleanup } from "./public-mcp/upload-cleanup.js";
import { assertAgentInteraction } from "./agent-interaction-policy.js";
import { instancePublicOrigin, mayContainInventedHostLink, relativizeInventedHostLinks } from "./agent-invented-host-links.js";
import { currentPluginInteractionOrigin } from "./plugin-interaction-context.js";
import type { IssueDisplayStatus } from "@paperclipai/shared";
import { issueDisplayStatusSql } from "./issue-display-status.js";
@@ -13676,7 +13677,17 @@ export function issueService(db: Db) {
enabled: (await instanceSettings.getGeneral({ db: dbOrTx }))
.censorUsernameInLogs,
};
const redactedBody = redactCurrentUserText(body, currentUserRedactionOptions);
// An agent's link on a made-up host (https://paperclip.local/...) does
// not open; its board or API route does. The run-presentation check above
// still compares the text the agent wrote.
const linkedBody = actor.agentId && mayContainInventedHostLink(body)
? relativizeInventedHostLinks(body, {
companyPrefix: await dbOrTx.select({ issuePrefix: companies.issuePrefix }).from(companies)
.where(eq(companies.id, issue.companyId)).then((rows: Array<{ issuePrefix: string }>) => rows[0]?.issuePrefix ?? null),
ownOrigin: instancePublicOrigin(),
})
: body;
const redactedBody = redactCurrentUserText(linkedBody, currentUserRedactionOptions);
if (actor.userId && options?.clientRequestId) {
const [existing] = await dbOrTx.select().from(issueComments).where(and(eq(issueComments.issueId, issueId),
eq(issueComments.authorUserId, actor.userId), eq(issueComments.clientRequestId, options.clientRequestId)));
+1 -1
View File
@@ -658,7 +658,7 @@ Never leave bare ticket ids in issue descriptions or comments when a clickable i
- Approvals: `/<prefix>/approvals/<approval-id>`
- Runs: `/<prefix>/agents/<agent-url-key-or-id>/runs/<run-id>`
Do NOT use unprefixed paths like `/issues/PAP-123` or `/agents/cto` — always include the company prefix.
Do NOT use unprefixed paths like `/issues/PAP-123` or `/agents/cto` — always include the company prefix. Write these links, and attachment links such as `/api/attachments/<id>/content`, as relative paths: never add a hostname you were not given, such as `https://paperclip`, `https://paperclip.local` or `http://localhost`, because that host does not open for the reader.
**Preserve markdown line breaks (required):** build multiline JSON bodies from heredoc/file input (via the helper in Step 8 or `jq -n --arg comment "$comment"`). Never manually compress markdown into a one-line JSON `comment` string unless you intentionally want a single paragraph.