Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

link bare issue references in CoS agent summaries to the run's own tracker

[._.]/ Adam Eivy1ad402b15133
diff --git a/client/src/components/cos/MarkdownOutput.jsx b/client/src/components/cos/MarkdownOutput.jsx
index feec9b69a6..24f0b19a3c 100644
--- a/client/src/components/cos/MarkdownOutput.jsx
+++ b/client/src/components/cos/MarkdownOutput.jsx
@@ -10,13 +10,32 @@ const INLINE_RE = /(!\[[^\]]*\]\([^)]+\)|`[^`]*`|\*\*[^*]+\*\*|\*[^*]+\*|(?<!\w)
const safeSrc = (url) => (/^(https?:\/\/|\/[^/])/.test(url) ? url : null);
-function parseInline(text) {
+const LINK_CLASS = 'text-port-accent hover:underline';
+
+// Literal text — outside code spans, links, and image syntax — is the ONE place
+// an optional `linkifyText` resolver gets to add links of its own. This renderer
+// is shared across unrelated domains, so it knows only the segment shape the
+// resolver returns; what counts as a reference, and where it points, stays with
+// the caller that holds the record (components/cos/tabs/AgentCard.jsx).
+function renderText(text, linkifyText, key) {
+ const segments = linkifyText ? linkifyText(text) : null;
+ // The common case by far: nothing to link. Hand back the bare string so the
+ // no-reference path costs exactly what it did before the resolver existed.
+ if (!segments || (segments.length === 1 && typeof segments[0] === 'string')) return [text];
+ return segments.map((seg, i) => (
+ seg?.url
+ ? <a key={`${key}-${i}`} href={seg.url} className={LINK_CLASS} target="_blank" rel="noopener noreferrer">{seg.ref}</a>
+ : seg
+ ));
+}
+
+function parseInline(text, linkifyText) {
const parts = [];
let last = 0;
let m;
INLINE_RE.lastIndex = 0;
while ((m = INLINE_RE.exec(text)) !== null) {
- if (m.index > last) parts.push(text.slice(last, m.index));
+ if (m.index > last) parts.push(...renderText(text.slice(last, m.index), linkifyText, `t${m.index}`));
const s = m[0];
if (s[0] === '!') {
const im = s.match(/^!\[([^\]]*)\]\(([^)]+)\)/);
@@ -30,21 +49,21 @@ function parseInline(text) {
} else if (s[0] === '`') {
parts.push(<code key={m.index} className="bg-port-bg px-1 py-0.5 rounded text-port-accent font-mono text-xs break-all">{s.slice(1, -1)}</code>);
} else if (s.startsWith('**')) {
- parts.push(<strong key={m.index} className="text-white font-semibold">{s.slice(2, -2)}</strong>);
+ parts.push(<strong key={m.index} className="text-white font-semibold">{renderText(s.slice(2, -2), linkifyText, `b${m.index}`)}</strong>);
} else if (s[0] === '*' || s[0] === '_') {
- parts.push(<em key={m.index} className="text-gray-300 italic">{s.slice(1, -1)}</em>);
+ parts.push(<em key={m.index} className="text-gray-300 italic">{renderText(s.slice(1, -1), linkifyText, `i${m.index}`)}</em>);
} else {
const lm = s.match(/\[([^\]]+)\]\(([^)]+)\)/);
if (lm) {
const href = safeSrc(lm[2]);
parts.push(href
- ? <a key={m.index} href={href} className="text-port-accent hover:underline" target="_blank" rel="noopener noreferrer">{lm[1]}</a>
+ ? <a key={m.index} href={href} className={LINK_CLASS} target="_blank" rel="noopener noreferrer">{lm[1]}</a>
: <span key={m.index} className="text-port-accent">{lm[1]}</span>);
}
}
last = m.index + s.length;
}
- if (last < text.length) parts.push(text.slice(last));
+ if (last < text.length) parts.push(...renderText(text.slice(last), linkifyText, `t${last}`));
return parts;
}
@@ -60,7 +79,7 @@ const H_STYLES = [
'text-xs font-semibold text-gray-300 mt-2 mb-0.5',
];
-function parseBlocks(md, baseLevel) {
+function parseBlocks(md, baseLevel, linkifyText) {
const lines = (md || '').split('\n');
const blocks = [];
let i = 0;
@@ -83,7 +102,7 @@ function parseBlocks(md, baseLevel) {
const hm = line.match(/^(#{1,6})\s+(.*)/);
if (hm) {
const Tag = `h${Math.min(6, baseLevel + hm[1].length - 1)}`;
- blocks.push(<Tag key={i} className={H_STYLES[hm[1].length - 1]}>{parseInline(hm[2])}</Tag>);
+ blocks.push(<Tag key={i} className={H_STYLES[hm[1].length - 1]}>{parseInline(hm[2], linkifyText)}</Tag>);
i++; continue;
}
@@ -97,7 +116,7 @@ function parseBlocks(md, baseLevel) {
if (line.startsWith('> ')) {
const bqLines = [];
while (i < lines.length && lines[i].startsWith('> ')) { bqLines.push(lines[i].slice(2)); i++; }
- blocks.push(<blockquote key={`bq${i}`} className="border-l-2 border-port-accent/50 pl-2 my-1 text-gray-400 italic">{bqLines.map((l, j) => <p key={j} className="text-xs text-gray-300 my-0.5">{parseInline(l)}</p>)}</blockquote>);
+ blocks.push(<blockquote key={`bq${i}`} className="border-l-2 border-port-accent/50 pl-2 my-1 text-gray-400 italic">{bqLines.map((l, j) => <p key={j} className="text-xs text-gray-300 my-0.5">{parseInline(l, linkifyText)}</p>)}</blockquote>);
continue;
}
@@ -105,7 +124,7 @@ function parseBlocks(md, baseLevel) {
if (/^[-*+] /.test(line)) {
const items = [];
while (i < lines.length && /^[-*+] /.test(lines[i])) { items.push(lines[i].replace(/^[-*+] /, '')); i++; }
- blocks.push(<ul key={`ul${i}`} className="my-0.5 pl-4 space-y-0.5">{items.map((it, j) => <li key={j} className="text-xs text-gray-300 list-disc">{parseInline(it)}</li>)}</ul>);
+ blocks.push(<ul key={`ul${i}`} className="my-0.5 pl-4 space-y-0.5">{items.map((it, j) => <li key={j} className="text-xs text-gray-300 list-disc">{parseInline(it, linkifyText)}</li>)}</ul>);
continue;
}
@@ -113,7 +132,7 @@ function parseBlocks(md, baseLevel) {
if (/^\d+\. /.test(line)) {
const items = [];
while (i < lines.length && /^\d+\. /.test(lines[i])) { items.push(lines[i].replace(/^\d+\. /, '')); i++; }
- blocks.push(<ol key={`ol${i}`} className="my-0.5 pl-4 space-y-0.5 list-decimal">{items.map((it, j) => <li key={j} className="text-xs text-gray-300">{parseInline(it)}</li>)}</ol>);
+ blocks.push(<ol key={`ol${i}`} className="my-0.5 pl-4 space-y-0.5 list-decimal">{items.map((it, j) => <li key={j} className="text-xs text-gray-300">{parseInline(it, linkifyText)}</li>)}</ol>);
continue;
}
@@ -127,8 +146,8 @@ function parseBlocks(md, baseLevel) {
blocks.push(
<div key={`tbl${i}`} className="overflow-x-auto my-1">
<table className="text-xs border-collapse w-full">
- <thead className="border-b border-port-border"><tr className="border-b border-port-border/50">{headers.map((h, j) => <th key={j} className="text-left px-2 py-1 text-gray-400 font-medium">{parseInline(h)}</th>)}</tr></thead>
- <tbody>{rows.map((row, j) => <tr key={j} className="border-b border-port-border/50">{row.map((cell, k) => <td key={k} className="px-2 py-1 text-gray-300">{parseInline(cell)}</td>)}</tr>)}</tbody>
+ <thead className="border-b border-port-border"><tr className="border-b border-port-border/50">{headers.map((h, j) => <th key={j} className="text-left px-2 py-1 text-gray-400 font-medium">{parseInline(h, linkifyText)}</th>)}</tr></thead>
+ <tbody>{rows.map((row, j) => <tr key={j} className="border-b border-port-border/50">{row.map((cell, k) => <td key={k} className="px-2 py-1 text-gray-300">{parseInline(cell, linkifyText)}</td>)}</tr>)}</tbody>
</table>
</div>
);
@@ -144,17 +163,21 @@ function parseBlocks(md, baseLevel) {
if (lines[i].includes('|') && RE_TABLE_SEP.test(lines[i + 1] || '')) break;
para.push(lines[i]); i++;
}
- if (para.length) blocks.push(<p key={`p${i}`} className="text-xs text-gray-300 my-0.5">{parseInline(para.join(' '))}</p>);
+ if (para.length) blocks.push(<p key={`p${i}`} className="text-xs text-gray-300 my-0.5">{parseInline(para.join(' '), linkifyText)}</p>);
if (para.length === 0) i++; // skip unconsumed line to prevent infinite loop
}
return blocks;
}
-export default function MarkdownOutput({ content, baseLevel = 3 }) {
+// `linkifyText(text) => Array<string | { ref, url }>` optionally turns spans of
+// literal text into links — how a CoS run card resolves the bare `#7640` an
+// agent wrote in its summary against that run's own tracker. Omit it and the
+// text renders exactly as before.
+export default function MarkdownOutput({ content, baseLevel = 3, linkifyText = null }) {
return (
<div className="markdown-output min-w-0 overflow-hidden break-words">
- {parseBlocks(content, baseLevel)}
+ {parseBlocks(content, baseLevel, linkifyText)}
</div>
);
}
diff --git a/client/src/components/cos/MarkdownOutput.test.jsx b/client/src/components/cos/MarkdownOutput.test.jsx
index 458f2542b8..70bd0b565e 100644
--- a/client/src/components/cos/MarkdownOutput.test.jsx
+++ b/client/src/components/cos/MarkdownOutput.test.jsx
@@ -75,3 +75,37 @@ describe('MarkdownOutput heading levels', () => {
expect(screen.getByRole('heading', { level: 6, name: 'Three' }).tagName).toBe('H6');
});
});
+
+// The renderer takes a resolver, not a repository (#7676): what counts as a
+// reference and where it points belongs to the caller that holds the record.
+describe('linkifyText resolver', () => {
+ // A stand-in for lib/issueRefs.js — deliberately not that module, so these
+ // assertions pin the RENDERER contract and not the issue-ref pattern.
+ const linkifyText = (text) => text.split(/(#\d+)/).map(seg =>
+ /^#\d+$/.test(seg) ? { ref: seg, url: `https://forge.example.com/issues/${seg.slice(1)}` } : seg
+ ).filter(Boolean);
+ const link = (name) => screen.getByRole('link', { name });
+
+ it('links resolver segments inside paragraphs, headings, list items, and bold runs', () => {
+ render(<MarkdownOutput content={'Closes #1.\n\n## Fixes #2\n\n- refs #3\n\n**and #4**'} linkifyText={linkifyText} />);
+ for (const n of [1, 2, 3, 4]) {
+ expect(link(`#${n}`)).toHaveAttribute('href', `https://forge.example.com/issues/${n}`);
+ }
+ });
+
+ it('never offers the resolver text inside a code span or a fenced block', () => {
+ render(<MarkdownOutput content={'use `#7640` here\n\n```\ngrep #7640\n```'} linkifyText={linkifyText} />);
+ expect(screen.queryByRole('link')).toBeNull();
+ });
+
+ it('does not let the resolver rewrite an existing markdown link', () => {
+ render(<MarkdownOutput content="[#7640](https://example.com/elsewhere)" linkifyText={linkifyText} />);
+ expect(link('#7640')).toHaveAttribute('href', 'https://example.com/elsewhere');
+ });
+
+ it('renders plain text when no resolver is passed', () => {
+ render(<MarkdownOutput content="Closes #7640" />);
+ expect(screen.queryByRole('link')).toBeNull();
+ expect(screen.getByText('Closes #7640')).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/cos/OutputBlocks.jsx b/client/src/components/cos/OutputBlocks.jsx
index 9471a2c92d..1ee0bc6d69 100644
--- a/client/src/components/cos/OutputBlocks.jsx
+++ b/client/src/components/cos/OutputBlocks.jsx
@@ -16,7 +16,7 @@ export const isLifecycleLine = (line) =>
const INITIAL_BLOCKS = 80;
const LOAD_MORE_BLOCKS = 120;
-function renderBlock(block, i) {
+function renderBlock(block, i, linkifyText) {
if (block.type === 'tool') {
const line = block.line;
if (line.startsWith('🔧')) {
@@ -33,10 +33,12 @@ function renderBlock(block, i) {
if (block.type === 'lifecycle') {
return <div key={i} className="py-0.5 text-xs text-gray-400 break-words">{block.line}</div>;
}
- return <MarkdownOutput key={i} content={block.content} />;
+ return <MarkdownOutput key={i} content={block.content} linkifyText={linkifyText} />;
}
-export default function OutputBlocks({ output }) {
+// `linkifyText` is forwarded to MarkdownOutput so a caller that knows the
+// record (a CoS run and its tracker) can link the bare `#7640` in its prose.
+export default function OutputBlocks({ output, linkifyText = null }) {
const [visibleCount, setVisibleCount] = useState(INITIAL_BLOCKS);
// Group consecutive lines: tool lines render as monospace, lifecycle markers
@@ -73,7 +75,7 @@ export default function OutputBlocks({ output }) {
return (
<div className="space-y-0.5 min-w-0 overflow-hidden">
- {blocks.slice(0, visibleCount).map(renderBlock)}
+ {blocks.slice(0, visibleCount).map((block, i) => renderBlock(block, i, linkifyText))}
{hasMore && (
<button
onClick={() => setVisibleCount(prev => prev + LOAD_MORE_BLOCKS)}
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index cfe1920f4d..7de69d49d6 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -39,6 +39,7 @@ import { useAutoRefetch } from '../../../hooks/useAutoRefetch';
import ConfirmButtonPair from '../../ui/ConfirmButtonPair';
import { useConfirmDelete } from '../../../hooks/useConfirmDelete';
import { AgentProgress, AgentRuntimeStatus } from './AgentRuntimeStatus';
+import { agentIssueLinkifier } from '../../../lib/issueRefs';
// Pre-compiled regexes for normalizeDescriptionToMarkdown
// Avoid lookbehind to support older Safari/iOS runtimes
@@ -86,6 +87,7 @@ function TaskDescription({ agent, remote }) {
const [hydrated, setHydrated] = useState(null);
const text = hydrated ?? preview;
const md = useMemo(() => normalizeDescriptionToMarkdown(text), [text]);
+ const linkifyIssues = useMemo(() => agentIssueLinkifier(agent), [agent]);
// `!remote` for the same reason the transcript fetch below carries it: a peer's
// agent id means nothing to THIS instance's /cos/agents/:id, so hydrating it
// would either 404 or read a local run that happens to share the id.
@@ -109,7 +111,7 @@ function TaskDescription({ agent, remote }) {
forceToggle={clipped}
onExpand={clipped ? hydrate : null}
>
- <MarkdownOutput content={md} />
+ <MarkdownOutput content={md} linkifyText={linkifyIssues} />
</CollapsibleText>
</div>
);
@@ -239,6 +241,9 @@ function GoalFidelityPanel({ review }) {
export default function AgentCard({ agent, onPause, onKill, onDelete, onResume, onRelaunch, completed, paused = false, liveOutput, durations, onFeedbackChange, remote, peerName, initiallyExpanded = false }) {
const [expanded, setExpanded] = useState(initiallyExpanded);
const [now, setNow] = useState(Date.now());
+ // Every surface of this card that renders the agent's own prose resolves a
+ // bare `#7640` against the run's tracker through the one resolver.
+ const linkifyIssues = useMemo(() => agentIssueLinkifier(agent), [agent]);
const [fullOutput, setFullOutput] = useState(null);
const [loadingOutput, setLoadingOutput] = useState(false);
// Pipeline stage output: track which stage tab is active and cached outputs per stage agentId
@@ -994,7 +999,7 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
<Sparkles size={10} aria-hidden="true" className="text-emerald-400" />
Task Summary
</div>
- {agent.metadata?.taskSummary && <MarkdownOutput content={agent.metadata.taskSummary} />}
+ {agent.metadata?.taskSummary && <MarkdownOutput content={agent.metadata.taskSummary} linkifyText={linkifyIssues} />}
{agent.metadata?.malwareScan?.reportUrl && (
<a
href={api.normalizeBrainScanReportPath(agent.metadata.malwareScan.reportUrl)}
@@ -1168,7 +1173,7 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
return (
<>
<TranscriptTruncationNotice transcript={stageOut} />
- {stageOut.lines.length > 0 && <OutputBlocks key={activeStage.agentId} output={stageOut.lines} />}
+ {stageOut.lines.length > 0 && <OutputBlocks key={activeStage.agentId} output={stageOut.lines} linkifyText={linkifyIssues} />}
</>
);
}
@@ -1192,7 +1197,7 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
return (
<>
{truncated && <TranscriptTruncationNotice transcript={fullOutput} />}
- {output.length > 0 && <OutputBlocks output={output} />}
+ {output.length > 0 && <OutputBlocks output={output} linkifyText={linkifyIssues} />}
</>
);
}
diff --git a/client/src/components/cos/tabs/AgentCard.test.jsx b/client/src/components/cos/tabs/AgentCard.test.jsx
index cd51f7a47a..18899e40c2 100644
--- a/client/src/components/cos/tabs/AgentCard.test.jsx
+++ b/client/src/components/cos/tabs/AgentCard.test.jsx
@@ -885,3 +885,24 @@ describe('AgentCard truncated task description', () => {
expect(api.hydrateCosAgentDescription).not.toHaveBeenCalled();
});
});
+
+// End-to-end for #7676: the run record carries its tracker, so a bare `#N` the
+// agent wrote in its own sentinel summary is followable from the card. The
+// pattern lives in lib/issueRefs.test.js — this pins the WIRING, the half that
+// silently regresses when a prop is dropped in a refactor.
+it('links a task-summary issue reference at the tracker the run was stamped with', () => {
+ render(
+ <MemoryRouter>
+ <AgentCard
+ agent={{ ...agent, metadata: {
+ ...agent.metadata,
+ taskSummary: 'Closes #7640.',
+ repoIssueUrl: 'https://github.com/atomantic/PortOS/issues',
+ } }}
+ completed
+ />
+ </MemoryRouter>
+ );
+ expect(screen.getByRole('link', { name: '#7640' }))
+ .toHaveAttribute('href', 'https://github.com/atomantic/PortOS/issues/7640');
+});
diff --git a/client/src/hooks/useAgentFeedbackToast.jsx b/client/src/hooks/useAgentFeedbackToast.jsx
index 2b0460c70a..cb26b289da 100644
--- a/client/src/hooks/useAgentFeedbackToast.jsx
+++ b/client/src/hooks/useAgentFeedbackToast.jsx
@@ -5,6 +5,7 @@ import socket from '../services/socket';
import * as api from '../services/api';
import OutputBlocks from '../components/cos/OutputBlocks';
import { isAgentHandoff } from '../lib/agentOutcome';
+import { agentIssueLinkifier } from '../lib/issueRefs';
const AUTO_DISMISS_MS = 15000;
@@ -94,7 +95,7 @@ function AgentFeedbackToast({ t, agentData, onFeedback }) {
Loading output...
</div>
) : output.length > 0 ? (
- <OutputBlocks output={output} />
+ <OutputBlocks output={output} linkifyText={agentIssueLinkifier(agentData)} />
) : (
<div className="text-xs text-gray-500">No output captured</div>
)}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 79cd9f78fd..65797b6d61 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -77,6 +77,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `slashdoCatalog.js` | The Agent Operations buttons. `SLASHDO_WORKFLOWS` is `server/lib/slashdoCatalog.js`'s list decorated with a per-command Tailwind tone, and `slashdoWorkflowsForApp(isSwiftApp)` filters it through the server's own `slashdoWorkflowAppliesTo` — so the panel cannot be a workflow short. `SLASHDO_NAMESPACE` + `slashdoLabel(command)` (the `/do:x` UI spelling) stay local: the server module that owns the namespace reaches for the provider registry. |
| `isSafeHref.js` | Pure http(s)-only scheme check (`isSafeHref`) for user-supplied URL fields rendered as a clickable `<a href>` — rejects `javascript:`/`data:`/etc. stored-XSS payloads. Re-exported from `server/lib/isSafeHref.js`; `utils/urlNormalize.js` re-exports it again as `isHttpUrl`. |
| `issueLength.js` | The Length Profile picker's helpers. `LENGTH_PROFILES`, `DEFAULT_LENGTH_PROFILE` and the `CUSTOM_*` bounds are re-exported from `server/lib/issueLength.js` (the same profiles the server computes targets from); `clampInt` and `summarizeLengthProfile` are client-only form/display helpers. |
+| `issueRefs.js` | Bare forge issue references (`#7640`) in rendered markdown. `splitIssueRefs(text, issueUrlBase)` splits literal text into strings and `{ ref, url }` segments; `agentIssueLinkifier(agent)` is the `linkifyText` resolver for one CoS run, reading the tracker base the server stamped at spawn (`agent.metadata.repoIssueUrl`, built by `server/lib/workTracker.js#repoIssueUrlBase`). Holds NO forge knowledge — it appends a number to a base the server already shaped — and declines a qualified `owner/repo#7640`, which that base cannot retarget. Render-time only: nothing is rewritten on disk, so a run from before the stamp renders plain text. |
| `musicDuration.js` | Lyric-aware MiniMax Music 3 duration analysis: section/word detection, ending-cushioned auto-duration recommendations, and cap warnings. Mirrors `server/lib/musicDuration.js`. |
## Pipeline / image-gen defaults
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 6625a111e2..e92d4db617 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -60,6 +60,7 @@ export * from './installFailureTask.js';
export * from './letteringDensity.js';
export * from './isSafeHref.js';
export * from './issueLength.js';
+export * from './issueRefs.js';
export * from './musicDuration.js';
export * from './muscriptorModels.js';
export * from './pipelineImageDefaults.js';
diff --git a/client/src/lib/issueRefs.js b/client/src/lib/issueRefs.js
new file mode 100644
index 0000000000..98588c27a5
--- /dev/null
+++ b/client/src/lib/issueRefs.js
@@ -0,0 +1,87 @@
+/**
+ * Bare forge issue references in rendered markdown — the `#7640` a CoS agent
+ * writes in its own completion summary — turned into clickable links.
+ *
+ * The agent is not asked to build the link: it has no reliable way to know the
+ * forge host, and a hand-built URL would be one more thing to get wrong. The
+ * run record already carries `agent.metadata.repoIssueUrl`, the tracker base
+ * the server resolved at spawn (`server/lib/workTracker.js#repoIssueUrlBase`,
+ * where the app's own `workTracker` pin settles a self-hosted forge). So this
+ * module appends a number and holds NO forge knowledge — no host parsing, no
+ * GitHub-vs-GitLab classification, nothing that could disagree with the server.
+ *
+ * Render-time only: nothing is rewritten on disk, so a record from before the
+ * stamp shipped renders the plain text it always did.
+ *
+ * Pure and React-free — it returns segments, and the caller
+ * (`components/cos/MarkdownOutput.jsx`) decides what an anchor looks like.
+ */
+
+// A reference is `#` plus an issue number, and the pattern is built to DECLINE
+// rather than mislink — a wrong link is followed, a missing one is merely read.
+//
+// The lookbehind rejects the contexts where a `#` is part of something else: a
+// word character (`v1.2.3#4`, `abc#1`), another `#` (`##2`), an entity's `&`
+// (`&#123;`), a path or URL separator (`server/lib/foo.js#12`, `.../pull/7#9`),
+// a hyphen (`utf-8#3`), and the `:`/`=` that introduce a compact CSS or
+// attribute value (`color:#336`) — transcripts of work in a styled repo print
+// those routinely.
+//
+// The number itself must not lead with a zero and runs at most five digits,
+// which is what separates a citation from the rest of the hex colors (`#000`,
+// `#336699`, `#12345678`) that survive the lookbehind. A six-digit issue is
+// beyond any tracker PortOS links to, and declining one costs a link; linking a
+// colour costs a reader a 404 they were told was an issue.
+//
+// A qualified `owner/repo#12` is deliberately NOT matched: the stamped base
+// names one repository and cannot be retargeted at another, so the honest
+// outcome is plain text rather than a same-numbered issue in the wrong repo.
+// The `\/` in the lookbehind is what declines it — the `#` there follows `o`.
+const ISSUE_REF_RE = /(?<![\w#&/:=-])#([1-9]\d{0,4})(?!\w)/g;
+
+/**
+ * Split plain text into literal strings and issue references.
+ *
+ * The caller must hand this text that is already OUTSIDE code spans, links, and
+ * image syntax: in markdown, a `#7640` in a code span is a literal, and one
+ * inside an existing `[…](…)` already has a destination.
+ *
+ * @param {string} text
+ * @param {string|null|undefined} issueUrlBase — `agent.metadata.repoIssueUrl`
+ * @returns {Array<string | { ref: string, url: string }>} the input as a single
+ * string when there is no tracker to resolve against, or nothing to link.
+ */
+export function splitIssueRefs(text, issueUrlBase) {
+ // `indexOf` before the regex: the overwhelming majority of text runs in a
+ // rendered transcript contain no `#` at all, and this path runs per run, per
+ // re-render, on every streamed frame.
+ if (!issueUrlBase || typeof text !== 'string' || !text.includes('#')) return [text];
+ const base = issueUrlBase.replace(/\/+$/, '');
+ const parts = [];
+ let last = 0;
+ let m;
+ ISSUE_REF_RE.lastIndex = 0;
+ while ((m = ISSUE_REF_RE.exec(text)) !== null) {
+ if (m.index > last) parts.push(text.slice(last, m.index));
+ parts.push({ ref: m[0], url: `${base}/${m[1]}` });
+ last = m.index + m[0].length;
+ }
+ if (last < text.length) parts.push(text.slice(last));
+ return parts;
+}
+
+/**
+ * The `linkifyText` resolver for one CoS run, or null when the run predates the
+ * `repoIssueUrl` stamp (its markdown then renders as plain text, unchanged).
+ *
+ * Lives here so every surface that renders a run's prose — the summary, the
+ * transcript, the task description, the completion toast — is one line rather
+ * than its own copy of "read the metadata, close over the base".
+ *
+ * @param {{metadata?: {repoIssueUrl?: string|null}}|null} agent
+ * @returns {((text: string) => Array<string | { ref: string, url: string }>) | null}
+ */
+export function agentIssueLinkifier(agent) {
+ const base = agent?.metadata?.repoIssueUrl;
+ return base ? (text) => splitIssueRefs(text, base) : null;
+}
diff --git a/client/src/lib/issueRefs.test.js b/client/src/lib/issueRefs.test.js
new file mode 100644
index 0000000000..e5d9642224
--- /dev/null
+++ b/client/src/lib/issueRefs.test.js
@@ -0,0 +1,64 @@
+import { describe, it, expect } from 'vitest';
+import { agentIssueLinkifier, splitIssueRefs } from './issueRefs';
+
+const BASE = 'https://github.com/atomantic/PortOS/issues';
+
+// Only the segments the renderer turns into anchors.
+const refs = (text, base = BASE) => splitIssueRefs(text, base).filter(p => typeof p !== 'string');
+
+describe('splitIssueRefs', () => {
+ it('links every reference and keeps the surrounding prose intact', () => {
+ expect(splitIssueRefs('Closes #7640, refs #22.', BASE)).toEqual([
+ 'Closes ',
+ { ref: '#7640', url: `${BASE}/7640` },
+ ', refs ',
+ { ref: '#22', url: `${BASE}/22` },
+ '.',
+ ]);
+ });
+
+ it('appends to a GitLab base exactly as the server shaped it', () => {
+ const gitlab = 'https://gitlab.example.com/group/sub/proj/-/issues';
+ expect(refs('see #12', gitlab)).toEqual([
+ { ref: '#12', url: `${gitlab}/12` },
+ ]);
+ });
+
+ // The pattern's job is to DECLINE: a wrong link gets followed, a missing one
+ // is merely read. Each row is a distinct false-positive class.
+ it.each([
+ ['a version suffix', 'shipped in v1.2.3#4'],
+ ['a repeated hash', 'heading ##2 here'],
+ ['an HTML entity', 'literal &#123; brace'],
+ ['a source-line anchor', 'server/lib/foo.js#12 is the spot'],
+ ['a URL fragment', 'https://github.com/a/b/pull/7#22 was merged'],
+ ['a non-numeric anchor', 'README.md#L12 and #Lx'],
+ ['a trailing word character', '#12abc'],
+ ['a six-digit hex colour', 'use color: #336699 for the border'],
+ ['a compact CSS colour', 'span{color:#336}'],
+ ['a zero-led hex colour', 'border 1px solid #000 here'],
+ // The stamped base names one repository and cannot be retargeted, so the
+ // honest outcome is plain text — never the same number in the wrong repo.
+ ['a cross-repo reference', 'see atomantic/slashdo#12'],
+ ])('leaves %s alone', (_label, text) => {
+ expect(refs(text)).toEqual([]);
+ });
+
+ it('returns the input untouched when there is no tracker, or nothing to link', () => {
+ expect(splitIssueRefs('Closes #7640', null)).toEqual(['Closes #7640']);
+ expect(splitIssueRefs('no references here', BASE)).toEqual(['no references here']);
+ });
+
+ it('tolerates a trailing slash on the stamped base', () => {
+ expect(refs('#7', `${BASE}/`)).toEqual([{ ref: '#7', url: `${BASE}/7` }]);
+ });
+});
+
+describe('agentIssueLinkifier', () => {
+ it('resolves against the run record, and is null for a run predating the stamp', () => {
+ const resolve = agentIssueLinkifier({ metadata: { repoIssueUrl: BASE } });
+ expect(resolve('Closes #7640')).toContainEqual({ ref: '#7640', url: `${BASE}/7640` });
+ expect(agentIssueLinkifier({ metadata: {} })).toBeNull();
+ expect(agentIssueLinkifier(null)).toBeNull();
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 6a4e250911..0edf6a5135 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -644,7 +644,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `userActionTypes.js` | Closed vocabulary for the operator-action ledger (`user_action_events`, #5594 / #5596): `USER_ACTION_TYPES` (CoS task/feedback/schedule + settings + instance-feature toggles + event-only creative/Brain pointers), `USER_ACTION_ACTORS` (`user` / `mind` / `schedule` / `system`), and the `isUserActionType` / `isUserActionActor` predicates. `recordUserAction` (`services/userActions.js`) throws on a type absent from the list, so a typo fails a test instead of writing a row nothing can filter on. |
| `uuid.js` | `v4()` thin wrapper over the global `crypto.randomUUID()`. Import-free, so a leaf the browser imports may reach it without a Node built-in — importable, not browser-callable: `randomUUID` needs a secure context there, so client code mints through `client/src/lib/uuid.js`. |
| `versionUtils.js` | `compareSemver(a, b)` — semver ordering (-1/0/1) with pre-release precedence and build-metadata stripping. Shared by the self-update checker (`updateChecker.js`) and the local-LLM Ollama update detector (`localLlm.js`). Inputs must be `v`-stripped. |
-| `workTracker.js` | `WORK_TRACKERS`/`CONCRETE_WORK_TRACKERS`/`DEFAULT_WORK_TRACKER`, `workTrackerLabel`, `hostToWorkTracker`, `isGithubHost` (GitHub-family host test — github.com + enterprise github.*; enterprise-aware replacement for the github.com-only `isGithub` gate), `githubRepoSpec(origin)` (host-qualified `HOST/OWNER/REPO` selector for `gh --repo`, or null for a non-GitHub origin — pairs the isGithubHost gate with the selector so prWatcher/branchReconcile/issueReconcile share one "resolvable GitHub repo" definition), `forgeCliForTracker`, `isFileTracker` (true when the tracker records work as repo files — PLAN.md — so an agent's proposal necessarily dirties the worktree; false for github/gitlab/jira), `trackerToClaimTaskType`, `hostFromOriginUrl` (subgroup-tolerant, ssh-alias-aware host parse), pure `resolveWorkTracker({configured,host})`, async `resolveAppWorkTracker(app)` — resolves a managed app's autonomous work source (PLAN.md / GitHub / GitLab / JIRA), defaulting `'auto'` to the git origin host. Async `resolveRepoForgeTarget(repoPath)` — the ONE definition of "which forge can we query for this checkout", returning `{ forge, fullName, repoSpec, apiHost }` (enterprise-aware `gh --repo` selector for GitHub; `repoSpec: null` for GitLab, which `glab` resolves from its cwd) or null for a non-forge origin; shared by `issueReconcile.js` and `appIssues.js`. Async `resolveAppForgeTarget(app, {repoPath})` — the composed `resolveAppWorkTracker` + `resolveRepoForgeTarget` for callers holding the managed-app record, returning `{ tracker, target }` with the app's github/gitlab pin threaded in as `preferredForge` (so a self-hosted forge on a hostname matching neither pattern still resolves); use this instead of re-threading the pin by hand. Also owns the `{trackerInstructions}` prompt block shared by the TRACKER-FILING task types (types that read the app read-only and deliver findings as tracker items, not a commit): `TRACKER_FILING_PRESETS` (per-task-type slug prefix / label / body requirements — `reference-watch`, `ux`, `repo-study`), `TRACKER_FILING_TASK_TYPES` (derived from the presets, so a gated type always has wording), `extraIssueLabels` / `formatForgeCategoryLabelFlags` (category + metric-slug labels + `plan` as repeated `--label` flags), and `formatTrackerInstructions(tracker, options)` which renders the plan/github/gitlab/jira block (reference-watch is the default option set, so a bare call stays byte-identical for it). Consumed by the `claim-work` router in `cosTaskGenerator.js`, `referenceRepos.js`, and `routes/apps.js`. |
+| `workTracker.js` | `WORK_TRACKERS`/`CONCRETE_WORK_TRACKERS`/`DEFAULT_WORK_TRACKER`, `workTrackerLabel`, `hostToWorkTracker`, `isGithubHost` (GitHub-family host test — github.com + enterprise github.*; enterprise-aware replacement for the github.com-only `isGithub` gate), `githubRepoSpec(origin)` (host-qualified `HOST/OWNER/REPO` selector for `gh --repo`, or null for a non-GitHub origin — pairs the isGithubHost gate with the selector so prWatcher/branchReconcile/issueReconcile share one "resolvable GitHub repo" definition), `forgeCliForTracker`, `isFileTracker` (true when the tracker records work as repo files — PLAN.md — so an agent's proposal necessarily dirties the worktree; false for github/gitlab/jira), `trackerToClaimTaskType`, `hostFromOriginUrl` (subgroup-tolerant, ssh-alias-aware host parse), pure `resolveWorkTracker({configured,host})`, async `resolveAppWorkTracker(app)` — resolves a managed app's autonomous work source (PLAN.md / GitHub / GitLab / JIRA), defaulting `'auto'` to the git origin host. Async `resolveRepoForgeTarget(repoPath)` — the ONE definition of "which forge can we query for this checkout", returning `{ forge, fullName, repoSpec, apiHost }` (enterprise-aware `gh --repo` selector for GitHub; `repoSpec: null` for GitLab, which `glab` resolves from its cwd) or null for a non-forge origin; shared by `issueReconcile.js` and `appIssues.js`. Async `resolveAppForgeTarget(app, {repoPath})` — the composed `resolveAppWorkTracker` + `resolveRepoForgeTarget` for callers holding the managed-app record, returning `{ tracker, target }` with the app's github/gitlab pin threaded in as `preferredForge` (so a self-hosted forge on a hostname matching neither pattern still resolves); use this instead of re-threading the pin by hand. Also owns the `{trackerInstructions}` prompt block shared by the TRACKER-FILING task types (types that read the app read-only and deliver findings as tracker items, not a commit): `TRACKER_FILING_PRESETS` (per-task-type slug prefix / label / body requirements — `reference-watch`, `ux`, `repo-study`), `TRACKER_FILING_TASK_TYPES` (derived from the presets, so a gated type always has wording), `extraIssueLabels` / `formatForgeCategoryLabelFlags` (category + metric-slug labels + `plan` as repeated `--label` flags), and `formatTrackerInstructions(tracker, options)` which renders the plan/github/gitlab/jira block (reference-watch is the default option set, so a bare call stays byte-identical for it). Consumed by the `claim-work` router in `cosTaskGenerator.js`, `referenceRepos.js`, and `routes/apps.js`. Also `repoIssueUrlBase(target)` — the browsable issue-tracker base URL for a resolved forge target (`/-/issues` on GitLab, `/issues` elsewhere), so a caller stamps a finished base onto its record and nothing downstream has to classify a host. |
| `eidoverseProxyRoutes.js` | Allowlist + path helpers for the same-origin Eidoverse reverse-proxy on `:5555` (`/eidoverse-host` prefix strip and root routes like `/ws` / `/version` while the host is active). Shared by `services/eidoverseProxy.js` so the main server and the optional `:5563` bridge stay in sync with eidoverse-worlds `server/routes.ts`. |
| `workspaceRoots.js` | Shared allow-list for routes that take a caller-supplied filesystem path. `isWithinAllowedRoots(realPath)` is the single complete test — on Windows it also allows any lettered non-system drive (`D:\code`), which appears in no root, so never render `ALLOWED_WORKSPACE_ROOTS` as "the directories you may use". `outsideAllowedRootsMessage(realPath, { field })` formats a redacted server-only diagnostic with the rejected realpath and every checked root. Also `ALLOWED_WORKSPACE_ROOTS` (defaults + `PORTOS_WORKSPACE_ROOTS`, split on the platform path delimiter — `;` on Windows — and symlink-resolved), `isWithinRoot(resolvedPath, root)` (separator-safe containment), and `WORKSPACE_ROOTS_CONFIGURED` (true when the operator set the env var — lets a permissive-by-default route like `routes/detect.js` opt into confinement). Defaults cover home plus wherever the platform mounts secondary volumes: `/tmp` + `/Users` + `/Volumes` + `/mnt` + `/media` + `/opt` on POSIX; home + the temp dir plus the non-system-drive rule on Windows, where those POSIX literals would resolve to whatever drive the process happens to be on. Used by `routes/commands.js`, `routes/scaffold.js`, and `routes/git.js` (always scoped) and `routes/detect.js` (scoped only when configured). |
| `zodCompat.js` | Zod 4 compatibility helpers. `partialWithoutDefaults(objectSchema)` — like `.partial()` but strips inner field defaults first, so a PATCH/update schema doesn't inject (and clobber) the stored values of fields the caller didn't send. Use for any update schema derived from a defaulted base. Also home to the provider-reference zod forms (#7564) — `providerRefSchema` / `providerRefFieldSchema` (a preset id OR a composite `harness.method@service[+bootstrap]`, per `providerRef.js`) and `presetProviderIdSchema` (preset-only) — because `cosValidation.js` needs them and must not import validation.js. |
diff --git a/server/lib/agentRegistrationRecord.js b/server/lib/agentRegistrationRecord.js
index cdfe72c0bc..663afc21b2 100644
--- a/server/lib/agentRegistrationRecord.js
+++ b/server/lib/agentRegistrationRecord.js
@@ -42,6 +42,7 @@ export function buildAgentRegistration({
instanceId,
workspacePath,
sourceWorkspace,
+ repoIssueUrl,
primaryCheckoutBaseline,
worktreeInfo,
explicitWorktree,
@@ -72,6 +73,19 @@ export function buildAgentRegistration({
// worktree. Non-throwing: an unreadable checkout yields null, which the
// detector reads as "nothing to check".
primaryCheckoutBaseline,
+ // The issue-tracker base URL of the repository this run worked in, already
+ // shaped for its forge (`repoIssueUrlBase`) so the browser appends a number
+ // and knows nothing about forges. It is what a bare `#7640` in the agent's
+ // own completion summary refers to, so the run card renders that reference
+ // as a link without the agent having to build a URL it has no reliable way
+ // to know.
+ //
+ // Stamped rather than resolved at render time for the two reasons the
+ // baseline above is: it is immutable run provenance (re-pointing an app at
+ // a different origin later must not silently relabel finished runs), and
+ // the alternative is a `git` shell-out per card render. A record written
+ // before this shipped carries null, which the card reads as plain text.
+ repoIssueUrl,
worktreeBranch: worktreeInfo?.branchName || null,
isWorktree: !!worktreeInfo,
isPersistentWorktree: !!worktreeInfo?.isPersistentWorktree,
diff --git a/server/lib/workTracker.js b/server/lib/workTracker.js
index 2b3ec942e3..d6a19b4657 100644
--- a/server/lib/workTracker.js
+++ b/server/lib/workTracker.js
@@ -591,6 +591,7 @@ export async function resolveRepoForgeTarget(repoPath, { preferredForge = null }
fullName: origin.fullName,
repoSpec: githubSpec,
apiHost: githubApiHost(origin.host),
+ webHost: githubApiHost(origin.host),
};
}
// Reuse the URL `getOriginInfo` already read rather than spawning a second
@@ -605,6 +606,7 @@ export async function resolveRepoForgeTarget(repoPath, { preferredForge = null }
fullName: origin?.fullName || gitlabProjectPath(originUrl) || host,
repoSpec: null,
apiHost: null,
+ webHost: host,
};
}
if (preferredForge === 'github' && origin?.fullName && host) {
@@ -613,11 +615,38 @@ export async function resolveRepoForgeTarget(repoPath, { preferredForge = null }
fullName: origin.fullName,
repoSpec: `${host}/${origin.fullName}`,
apiHost: githubApiHost(host),
+ webHost: githubApiHost(host),
};
}
return null;
}
+/**
+ * The browsable issue-tracker base URL for a resolved forge target — append
+ * `/<number>` for one issue. GitLab nests its tracker under `/-/`; the
+ * GitHub family serves it directly off the project path (and redirects a pull
+ * request's number there, so one base covers both kinds of reference).
+ *
+ * This is where the forge-shape knowledge STOPS: a caller stamps the finished
+ * base onto its record, so nothing downstream — least of all the browser — has
+ * to classify a hostname or know that GitLab spells the path differently. That
+ * matters because hostname classification is not authoritative: a self-hosted
+ * forge on a neutral domain is resolved only by the user's own `workTracker`
+ * pin, which `resolveAppForgeTarget` has already applied by the time a target
+ * reaches here.
+ *
+ * Null when the target can't name a project: `resolveRepoForgeTarget` falls
+ * `fullName` back to the bare host for an unparseable GitLab remote, which
+ * would otherwise compose `https://host/host/-/issues`.
+ *
+ * @param {{forge:string, fullName:string|null, webHost:string|null}|null} target
+ * @returns {string|null}
+ */
+export function repoIssueUrlBase(target) {
+ if (!target?.webHost || !target.fullName || target.fullName === target.webHost) return null;
+ return `https://${target.webHost}/${target.fullName}/${target.forge === 'gitlab' ? '-/issues' : 'issues'}`;
+}
+
/**
* Composed `resolveAppWorkTracker` + `resolveRepoForgeTarget` for callers that
* hold the managed-app record (not just a bare `repoPath`): resolve the app's
diff --git a/server/lib/workTracker.test.js b/server/lib/workTracker.test.js
index 3948b31c96..93897df933 100644
--- a/server/lib/workTracker.test.js
+++ b/server/lib/workTracker.test.js
@@ -9,7 +9,7 @@ vi.mock('./gitRemote.js', () => ({
}));
import { getOriginInfo, readOriginRemoteUrl } from './gitRemote.js';
-import { resolveAppForgeTarget } from './workTracker.js';
+import { repoIssueUrlBase, resolveAppForgeTarget } from './workTracker.js';
import {
WORK_TRACKERS,
CONCRETE_WORK_TRACKERS,
@@ -312,3 +312,47 @@ describe('resolveAppForgeTarget', () => {
expect(target).toBeNull();
});
});
+
+// The base a run card stamps and the browser appends a number to. Composed
+// against the REAL resolver rather than hand-built targets, because the case
+// worth pinning is the one a hostname cannot answer: a self-hosted forge whose
+// domain spells neither "github." nor "gitlab.", where only the app's own pin
+// decides whether the tracker path is `/issues` or `/-/issues`.
+describe('repoIssueUrlBase', () => {
+ const CUSTOM = { host: 'git.example-corp.com', fullName: 'acme/widget', url: '[email protected]:acme/widget.git' };
+
+ const useOrigin = ({ host, fullName, url, isGithub = false }) => {
+ getOriginInfo.mockResolvedValue({ isGithub, host, fullName });
+ readOriginRemoteUrl.mockResolvedValue(url);
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('nests the tracker under /-/ for a gitlab-pinned self-hosted origin', async () => {
+ useOrigin(CUSTOM);
+ const { target } = await resolveAppForgeTarget({ repoPath: '/repo', workTracker: 'gitlab' });
+ expect(repoIssueUrlBase(target)).toBe('https://git.example-corp.com/acme/widget/-/issues');
+ });
+
+ it('serves it off the project path for the github family, enterprise included', async () => {
+ useOrigin({ host: 'github.com', fullName: 'acme/widget', url: '[email protected]:acme/widget.git', isGithub: true });
+ const gh = await resolveAppForgeTarget({ repoPath: '/repo', workTracker: 'auto' });
+ expect(repoIssueUrlBase(gh.target)).toBe('https://github.com/acme/widget/issues');
+
+ useOrigin(CUSTOM);
+ const enterprise = await resolveAppForgeTarget({ repoPath: '/repo', workTracker: 'github' });
+ expect(repoIssueUrlBase(enterprise.target)).toBe('https://git.example-corp.com/acme/widget/issues');
+ });
+
+ it('is null when nothing named a queryable project', async () => {
+ useOrigin(CUSTOM);
+ const { target } = await resolveAppForgeTarget({ repoPath: '/repo', workTracker: 'plan' });
+ expect(target).toBeNull();
+ expect(repoIssueUrlBase(target)).toBeNull();
+ // The GitLab branch falls `fullName` back to the bare host for an
+ // unparseable remote; that must not compose `https://host/host/-/issues`.
+ expect(repoIssueUrlBase({ forge: 'gitlab', fullName: 'git.example-corp.com', webHost: 'git.example-corp.com' })).toBeNull();
+ });
+});
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 1d9c02a231..325fd203f3 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -54,6 +54,7 @@ import { analyzeAgentFailure } from './agentErrorAnalysis.js';
import { createAgentRun } from './agentRunTracking.js';
import { appendRunEvent } from './agentRunEventLog.js';
import { committedDuringRun, toEpochMs } from '../lib/gitCommitProbe.js';
+import { repoIssueUrlBase, resolveAppForgeTarget, resolveRepoForgeTarget } from '../lib/workTracker.js';
import { capturePrimaryCheckoutState } from '../lib/primaryCheckoutGuard.js';
import { buildAgentPrompt, getAppWorkspace, isClaimFlowTask, promptOpensOwnPr } from './agentPromptBuilder.js';
import { isOllamaClaudeProvider, isClaudeCommand, providerSuppliesGithubToken } from '../lib/providerModels.js';
@@ -506,7 +507,7 @@ async function runAgentSpawn(task) {
cosEvents.emit('agent:error', { taskId: task.id, error: prep.reason });
return null;
}
- const { workspacePath, resolvedAppName, worktreeInfo, jiraTicket, jiraBranchName, explicitWorktree } = prep;
+ const { workspacePath, resolvedApp, resolvedAppName, worktreeInfo, jiraTicket, jiraBranchName, explicitWorktree } = prep;
if (worktreeInfo?.branchName && !worktreeInfo.existingBranch && !worktreeInfo.isPersistentWorktree) {
spawnWorktree = { branchName: worktreeInfo.branchName };
}
@@ -677,20 +678,35 @@ async function runAgentSpawn(task) {
// `isTruthyMetaFn` argument — which is exactly the split that made a claim
// run badge itself "main".
const claimFlowTask = isClaimFlowTask(task, isTruthyMeta);
+ // Two independent reads of two different checkouts — run them together
+ // rather than letting the object literal below serialize them.
+ //
+ // The forge target is where a bare `#7640` in this run's own summary points.
+ // Resolved through the shared resolver (not a hostname guess) so the app's
+ // own `workTracker` pin decides for a self-hosted forge, and read from the
+ // WORKSPACE so a run on a managed app links to THAT app's tracker.
+ //
+ // `primaryCheckoutBaseline` is the branch-jack baseline (#3680): the primary
+ // checkout's branch + HEAD at the instant this worktree agent started.
+ // finalizeAgent re-reads it at the end of the run — every spawn mode funnels
+ // through that one chokepoint — and fails the run when the primary moved,
+ // instead of recording a silent "completed" for an agent that wrote
+ // unreviewed commits outside its worktree. Non-throwing: an unreadable
+ // checkout yields null, which the detector reads as "nothing to check".
+ const [forgeTarget, primaryCheckoutBaseline] = await Promise.all([
+ resolvedApp
+ ? resolveAppForgeTarget(resolvedApp, { repoPath: workspacePath }).then(r => r.target)
+ : resolveRepoForgeTarget(workspacePath),
+ sourceWorkspace ? capturePrimaryCheckoutState(sourceWorkspace) : null,
+ ]);
await registerAgent(agentId, task.id, buildAgentRegistration({
task,
provider,
instanceId,
workspacePath,
sourceWorkspace,
- // Branch-jack baseline (#3680): the primary checkout's branch + HEAD at the
- // instant this worktree agent started. finalizeAgent re-reads it at the end
- // of the run — every spawn mode funnels through that one chokepoint — and
- // fails the run when the primary moved, instead of recording a silent
- // "completed" for an agent that wrote unreviewed commits outside its
- // worktree. Non-throwing: an unreadable checkout yields null, which the
- // detector reads as "nothing to check".
- primaryCheckoutBaseline: sourceWorkspace ? await capturePrimaryCheckoutState(sourceWorkspace) : null,
+ repoIssueUrl: repoIssueUrlBase(forgeTarget),
+ primaryCheckoutBaseline,
worktreeInfo,
explicitWorktree,
jiraBranchName,
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index 9e76423511..fce77159ab 100644
--- a/server/services/agentWorkspacePrep.js
+++ b/server/services/agentWorkspacePrep.js
@@ -16,7 +16,7 @@ import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';
* must finish are returned as a discriminated result so the caller can fire
* `cleanupOnError` + the matching `agent:deferred` / `agent:error` event:
*
- * { outcome: 'ready', workspacePath, resolvedAppName, worktreeInfo, jiraTicket, jiraBranchName, explicitWorktree }
+ * { outcome: 'ready', workspacePath, resolvedApp, resolvedAppName, worktreeInfo, jiraTicket, jiraBranchName, explicitWorktree }
* { outcome: 'deferred', reason, deferReason, branch } // git conflict — task re-queued
* { outcome: 'blocked', reason } // explicit worktree requested but creation failed
* // (`worktree-busy` blocks are a TIMED pause and revive themselves)
@@ -272,7 +272,7 @@ export async function prepareAgentWorkspace({ agentId, task }) {
const { privateSecurityScratchCwd } = await import('../lib/privateSecuritySandbox.js');
const workspacePath = privateSecurityScratchCwd(agentId);
await ensureDir(workspacePath);
- return { outcome: 'ready', workspacePath, resolvedAppName: null, worktreeInfo: null,
+ return { outcome: 'ready', workspacePath, resolvedApp: null, resolvedAppName: null, worktreeInfo: null,
jiraTicket: null, jiraBranchName: null, explicitWorktree: false };
}
@@ -298,6 +298,7 @@ export async function prepareAgentWorkspace({ agentId, task }) {
return {
outcome: 'ready',
workspacePath,
+ resolvedApp: null,
resolvedAppName: null,
worktreeInfo: null,
jiraTicket: null,
@@ -318,9 +319,14 @@ export async function prepareAgentWorkspace({ agentId, task }) {
let workspacePath = task.metadata?.app
? await getAppWorkspace(task.metadata.app)
: ROOT_DIR;
- const resolvedAppName = task.metadata?.app
- ? (await getAppById(task.metadata.app).catch(() => null))?.name || null
+ // The record itself, not just its name: the spawn also needs its `workTracker`
+ // pin to resolve the forge behind the workspace's origin (a self-hosted forge
+ // on a neutral domain is classified by that pin alone), and reading it twice
+ // would be two `getAppById` calls for one record.
+ const resolvedApp = task.metadata?.app
+ ? await getAppById(task.metadata.app).catch(() => null)
: null;
+ const resolvedAppName = resolvedApp?.name || null;
// Refuse to run an agent whose app didn't resolve to a usable directory.
// Previously both failures fell through to the PortOS root and the agent
@@ -562,6 +568,7 @@ export async function prepareAgentWorkspace({ agentId, task }) {
return {
outcome: 'ready',
workspacePath,
+ resolvedApp,
resolvedAppName,
worktreeInfo,
jiraTicket,