Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Link doc sections, document custom in-app agents (PRD-7882, PRD-7541) (#4945)

Abraham58780be4f107
diff --git a/.changeset/prd-7541-custom-agent-log-redaction.md b/.changeset/prd-7541-custom-agent-log-redaction.md
new file mode 100644
index 000000000..d9a0d1ced
--- /dev/null
+++ b/.changeset/prd-7541-custom-agent-log-redaction.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+A rejected `.ok/local/acp-agents.json` entry is now logged by its position, id and the rule it broke, and a file that is not valid JSON or not a JSON array is logged without any of its text, so `env` values never reach the server log.
diff --git a/.changeset/prd-7882-7541-section-links-custom-agents.md b/.changeset/prd-7882-7541-section-links-custom-agents.md
new file mode 100644
index 000000000..8e2faeac6
--- /dev/null
+++ b/.changeset/prd-7882-7541-section-links-custom-agents.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+The project skill now tells agents to link the section of a long document they mean, and a chat link written as `./path.md#heading` or `/path.md#heading` opens that doc at the heading in the app instead of a browser.
diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdx
index 73749548f..74720e8d8 100644
--- a/docs/content/features/editor.mdx
+++ b/docs/content/features/editor.mdx
@@ -96,6 +96,7 @@ Links work the way they do in the editors you already know:
- **Type a URL, then press space or enter.** A full URL (`https://…`, `www.…`, or an email address) becomes a link when you press space or enter after it. Plain words and filenames like `AGENTS.md` are left alone, and one `Cmd+Z` turns a conversion back into plain text.
- **Paste or drag in a URL.** Pasted (or dropped) on its own, it becomes a link. Pasted over selected text, it links that text instead — the text stays, the URL becomes its destination. `Cmd+Shift+V` pastes plain, with no linking.
- **Type `[text](url)`.** Closing the parenthesis converts the markdown shorthand into a real link; `Cmd+Z` restores the literal text.
+- **Link to a section.** Append `#` and the heading's slug to a doc link — `[text](./spec.md#data-model-v2)` — and the WYSIWYG editor opens the doc scrolled to that heading (the source editor ignores the fragment and opens at the top). The slug is the heading text in lowercase with accents dropped, every run of characters that aren't letters or digits replaced by one hyphen, and hyphens trimmed from both ends: `## Data model: v2` becomes `data-model-v2`, `## FAQ:` becomes `faq`, and a second identical heading in the same doc gets `-1`. Agents write the same form in chat, so a reply about one part of a long spec can take you straight to it.
- **Press `Cmd+K` with text selected.** The link popover opens with the URL field focused, pre-filled from your clipboard when it holds a URL. With the cursor inside an existing link, `Cmd+K` opens that link for editing. With no selection, `Cmd+K` keeps opening the command palette, as everywhere else. To reach the command palette while text is selected, use `Cmd+P` (`Ctrl+P` on Windows / Linux), which always opens it.
## Right-click menu and spell check
@@ -146,6 +147,28 @@ When a catalog-managed agent that OpenKnowledge launches through npx fails becau
A startup error ending with "Try again after an allowed release becomes available." means the requested adapter has no eligible release under that policy. Retry after one becomes eligible; OpenKnowledge does not disable your cooldown. Acquisition contacts your configured package registry or Python index; see [network requests](../reference/what-open-knowledge-writes.mdx#what-leaves-your-machine).
+### Add your own in-app agent
+
+In-app agents speak the [Agent Client Protocol](https://agentclientprotocol.com) (ACP): OpenKnowledge starts the agent as a subprocess, hands it the project's MCP tools and the [project skill](./skills/built-in-skills.mdx#project-scope), and gates its permission requests in the chat. The catalog lists the agents published to the ACP registry, and any other agent that speaks ACP over stdio can join it on your machine.
+
+Create `.ok/local/acp-agents.json` inside the project, a JSON array with one entry per agent:
+
+```json
+[
+ { "id": "omp", "name": "oh-my-pi", "command": "omp", "args": ["acp"] }
+]
+```
+
+`id` may only use letters, digits, `_` and `-`; `name` is what the launcher shows; `command` plus the optional `args` are what OpenKnowledge spawns, and an optional `env` object of string values is added to the agent's environment. A bare command name is looked up on the PATH of the process that runs the OpenKnowledge server; on macOS and Linux, OpenKnowledge also asks your login shell for its PATH and merges that in, so a command that only your shell can see is still found from a desktop app launched from the Dock or Finder. That merge is skipped when the entry's `env` sets `PATH` itself, and it does not exist on Windows, so in those cases either install the command in a standard location or give its absolute path. A `command` written as a path (it contains a `/`, or a `\` on Windows) is never looked up and is used exactly as written. An entry that breaks those rules is dropped with a warning in the [server log](../reference/what-open-knowledge-writes.mdx#while-a-project-is-open), and a file that is not valid JSON, or whose top level is not an array, is ignored as a whole with the same kind of warning. The file lives under `.ok/local/`, which the project's [`.ok/.gitignore`](../reference/what-open-knowledge-writes.mdx#setting-up-a-project) keeps out of your commits, so each machine normally keeps its own list.
+
+<Callout type="warn">
+ **Review a committed `acp-agents.json` before you open the Agents panel.** For a project you did not set up, read the file's `command`, `args` and `env` first. The ignore rule only keeps your own copy out of your commits; it does not vet a file someone else committed. An entry that is switched on runs its command exactly as written, and the switch is stored by agent id rather than per project, so an id you turned on elsewhere is already on in that clone. A chat starts the agent's command as soon as its thread is created, and an Agents panel that opens empty starts a thread by itself with your default agent, or the first enabled one.
+</Callout>
+
+OpenKnowledge reads the file every time it builds the agent catalog, so once it is saved, open **Settings → Agent connections** (the **Configure agents** row in the launcher menus goes there too). A new custom agent starts folded under **In app**, because nothing has turned it on yet: expand the **Show more** button there (its label counts the folded entries) or type the agent's name in the search box, then turn it on. The agent then appears in the **In app** section of the [Open with AI](#open-with-ai) menu and the **Ask AI** agent picker, and its conversations run in the Agents panel like any other, with the same MCP tools and permission prompts. The npx cache retry described above applies only to catalog-managed agents; a custom command is launched exactly as written.
+
+To make an agent appear for everyone without per-machine configuration, publish its manifest to the ACP registry; it then flows into the catalog on its own.
+
### From a text selection
Select text in the WYSIWYG editor and the selection bubble menu shows a **Comment** button (Sparkles icon) alongside the formatting controls. Clicking it — or pressing `Cmd+Shift+M` — opens a composer on the selection. What you write there is a [comment](/docs/features/comments): it goes into the project's comment queue rather than to an agent, and you hand a batch of comments over as a separate, deliberate step from the **Comments** tab.
diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdx
index cb7905067..ff7c3d1bb 100644
--- a/docs/content/reference/what-open-knowledge-writes.mdx
+++ b/docs/content/reference/what-open-knowledge-writes.mdx
@@ -121,6 +121,7 @@ The app runs a collaboration server for the open project. It writes runtime stat
| `.ok/local/conflicts.json` | Every conflict the app is holding a document for, including conflicts that involve no remote. A row for OpenKnowledge's own merge of the editor against disk embeds up to three full copies of the document body, so **keep this file while any conflict is open**. Deleting it loses those copies. If the app cannot read the file, it renames it to `conflicts.json.corrupt-<timestamp>` and leaves it in place | In-project, gitignored |
| `.ok/local/stale-external-writes.json` | Recovery snapshot for a rejected stale external save. It can hold the acknowledged, rejected, and retained document text. Protection expires after 30 minutes, but an unresolved snapshot stays until you resolve the conflict | In-project, gitignored |
| `.ok/local/state.json`, `.ok/local/last-spawn-error.log` | State-schema manifest and the last detached-spawn error log | In-project, gitignored |
+| `.ok/local/acp-agents.json` | Read, not written: your own list of [custom in-app agents](../features/editor.mdx#add-your-own-in-app-agent), re-read every time the agent catalog is built | In-project, gitignored |
| `.ok/local/acp-launch-failures.log` | In-app agent launches that failed: when, which agent, why, and the last lines the agent printed before it exited, so a bug report shows the cause without a re-run. Starts over once it passes 256 KB | In-project, gitignored |
| `.ok/local/last-server-exit.json` | Why the collaboration server the app started last exited — a timestamp, its process id, the exit code, the signal that ended it, and which part of the app was watching. One record, overwritten on each exit; a server the app only attached to, or one you started yourself with `ok start`, leaves none. No document content or paths | In-project, gitignored |
| `.ok/local/last-server-crash.json` | The collaboration server's own account of a crash it did not survive — a timestamp, the error message and stack, its process id, and how long it had been running. Written by the server itself, so it covers `ok start` too. Holds the most recent crash only | In-project, gitignored |
@@ -249,6 +250,7 @@ On Windows, Claude Desktop and OpenCode configs live under `%APPDATA%\Claude\` a
| `.ok/local/conflicts.json` | Every conflict the app is holding a document for, including conflicts that involve no remote. A row for OpenKnowledge's own merge of the editor against disk embeds up to three full copies of the document body, so **keep this file while any conflict is open**. Deleting it loses those copies. If the app cannot read the file, it renames it to `conflicts.json.corrupt-<timestamp>` and leaves it in place | In-project, gitignored |
| `.ok/local/stale-external-writes.json` | Recovery snapshot for a rejected stale external save. It can hold the acknowledged, rejected, and retained document text. Protection expires after 30 minutes, but an unresolved snapshot stays until you resolve the conflict | In-project, gitignored |
| `.ok/local/state.json`, `.ok/local/last-spawn-error.log` | State-schema manifest and the last detached-spawn error log | In-project, gitignored |
+| `.ok/local/acp-agents.json` | Read, not written: your own list of [custom in-app agents](../features/editor.mdx#add-your-own-in-app-agent), re-read every time the agent catalog is built | In-project, gitignored |
| `.ok/local/acp-launch-failures.log` | In-app agent launches that failed: when, which agent, why, and the last lines the agent printed before it exited, so a bug report shows the cause without a re-run. Starts over once it passes 256 KB | In-project, gitignored |
| `.ok/local/last-server-crash.json` | The server's own account of a crash it did not survive — a timestamp, the error message and stack, its process id, and how long it had been running. Holds the most recent crash only | In-project, gitignored |
| `.ok/local/telemetry/spans-*.jsonl` | Local diagnostic spans, rotated at ~50 MB | In-project, gitignored |
diff --git a/packages/app/src/components/acp/AgentMarkdown.dom.test.tsx b/packages/app/src/components/acp/AgentMarkdown.dom.test.tsx
index 50a565620..3e6a25e34 100644
--- a/packages/app/src/components/acp/AgentMarkdown.dom.test.tsx
+++ b/packages/app/src/components/acp/AgentMarkdown.dom.test.tsx
@@ -136,6 +136,27 @@ describe('AgentMarkdown doc-path links', () => {
expect(container.textContent).not.toContain('[blocked]');
});
+ test('a section link written as ./path.md#slug, the form the project skill prescribes, opens the doc at that heading in-app', () => {
+ const { container } = renderWithResolver(
+ 'The schema is under [Data model](./reports/foo/REPORT.md#data-model).',
+ );
+
+ const anchor = container.querySelector('[data-testid="agent-thread-doc-link"]');
+ expect(anchor?.getAttribute('href')).toBe('#/reports/foo/REPORT#data-model');
+ expect(anchor?.getAttribute('target')).toBeNull();
+ expect(container.textContent).not.toContain('[blocked]');
+ });
+
+ test('a section link written as /path.md#slug, the content-root form, opens the doc at that heading in-app', () => {
+ const { container } = renderWithResolver(
+ 'The schema is under [Data model](/reports/foo/REPORT.md#data-model).',
+ );
+
+ const anchor = container.querySelector('[data-testid="agent-thread-doc-link"]');
+ expect(anchor?.getAttribute('href')).toBe('#/reports/foo/REPORT#data-model');
+ expect(anchor?.getAttribute('target')).toBeNull();
+ });
+
test('a markdown link to a file: URL of a workspace doc opens in-app too', () => {
const { container } = renderWithResolver(
'[the report](file:///Users/abraham/repo/public/open-knowledge/reports/foo/REPORT.md)',
diff --git a/packages/app/src/components/acp/doc-path-links.test.ts b/packages/app/src/components/acp/doc-path-links.test.ts
index 827ef0494..04eea811e 100644
--- a/packages/app/src/components/acp/doc-path-links.test.ts
+++ b/packages/app/src/components/acp/doc-path-links.test.ts
@@ -112,6 +112,72 @@ describe('buildDocPathResolver', () => {
expect(resolve?.('reports/foo/REPORT.md#somewhere')).toBe('reports/foo/REPORT');
});
+ test('a leading ./ is dropped — the form the project skill tells agents to write', () => {
+ const resolve = buildDocPathResolver({
+ workspace,
+ pages: new Set(['reports/foo/REPORT']),
+ });
+ expect(resolve?.('./reports/foo/REPORT.md')).toBe('reports/foo/REPORT');
+ expect(resolve?.('./REPORT.md')).toBe('reports/foo/REPORT');
+ expect(resolve?.('././reports/foo/REPORT.md')).toBe('reports/foo/REPORT');
+ });
+
+ test('a ../ path stays unresolved — chat has no document to resolve it against', () => {
+ const resolve = buildDocPathResolver({
+ workspace,
+ pages: new Set(['reports/foo/REPORT']),
+ });
+ expect(resolve?.('../reports/foo/REPORT.md')).toBeNull();
+ });
+
+ test('a /-rooted path means the content root, as in the editor, and must match a doc exactly', () => {
+ const resolve = buildDocPathResolver({
+ workspace,
+ pages: new Set(['reports/foo/REPORT']),
+ });
+ expect(resolve?.('/reports/foo/REPORT.md')).toBe('reports/foo/REPORT');
+ expect(resolve?.('/REPORT.md')).toBeNull();
+ });
+
+ test('a /-rooted path follows the editor resolver for dot segments and //, but chat still needs a markdown extension', () => {
+ const resolve = buildDocPathResolver({
+ workspace,
+ pages: new Set(['reports/foo/REPORT']),
+ });
+ expect(resolve?.('/reports/foo/./REPORT.md')).toBe('reports/foo/REPORT');
+ expect(resolve?.('//reports/foo/REPORT.md')).toBeNull();
+ expect(resolve?.('/reports/foo/REPORT')).toBeNull();
+ });
+
+ test('a /-rooted token without a markdown extension never links, even when a page has that name', () => {
+ const resolve = buildDocPathResolver({
+ workspace,
+ pages: new Set(['settings', 'docs']),
+ });
+ expect(resolve?.('/settings')).toBeNull();
+ expect(resolve?.('/settings?tab=1')).toBeNull();
+ expect(resolve?.('/docs/')).toBeNull();
+ expect(resolve?.('/settings.md')).toBe('settings');
+ });
+
+ test('a /-rooted path arrives already decoded, so a literal % in a doc name still matches', () => {
+ const resolve = buildDocPathResolver({
+ workspace,
+ pages: new Set(['notes/a%20b']),
+ });
+ expect(resolve?.('/notes/a%20b.md')).toBe('notes/a%20b');
+ });
+
+ test('a leading .\\ is dropped under a Windows workspace too', () => {
+ const resolve = buildDocPathResolver({
+ workspace: windowsWorkspace,
+ pages: new Set(['reports/foo/REPORT']),
+ });
+ expect(resolve?.('.\\public\\open-knowledge\\reports\\foo\\REPORT.md')).toBe(
+ 'reports/foo/REPORT',
+ );
+ });
+
test('dot-segment paths link when they are in the tracked page set (.changeset/, .github/, …)', () => {
const resolve = buildDocPathResolver({
workspace,
@@ -415,6 +481,61 @@ describe('remarkDocPathLinks', () => {
}
});
+ test('a section link written as ./path.md#slug, the form the project skill prescribes, becomes the in-app route', () => {
+ const tree = makeTree([
+ {
+ type: 'paragraph',
+ children: [
+ {
+ type: 'link',
+ url: './reports/foo/REPORT.md#findings',
+ children: [{ type: 'text', value: 'Findings' }],
+ },
+ ],
+ },
+ ]);
+ setDocPathResolver(resolve);
+ remarkDocPathLinks()()(tree);
+ expect(tree.children?.[0]?.children?.[0]?.url).toBe('#/reports/foo/REPORT#findings');
+ });
+
+ test('a section link written as /path.md#slug, the content-root form the skill also allows, becomes the in-app route', () => {
+ const tree = makeTree([
+ {
+ type: 'paragraph',
+ children: [
+ {
+ type: 'link',
+ url: '/reports/foo/REPORT.md#findings',
+ children: [{ type: 'text', value: 'Findings' }],
+ },
+ ],
+ },
+ ]);
+ setDocPathResolver(resolve);
+ remarkDocPathLinks()()(tree);
+ expect(tree.children?.[0]?.children?.[0]?.url).toBe('#/reports/foo/REPORT#findings');
+ });
+
+ test('a /-rooted web route in agent prose stays as written, as inline code and as a link', () => {
+ const routes = buildDocPathResolver({ workspace, pages: new Set(['settings', 'docs']) });
+ const tree = makeTree([
+ {
+ type: 'paragraph',
+ children: [
+ { type: 'inlineCode', value: '/settings' },
+ { type: 'text', value: ' and ' },
+ { type: 'link', url: '/settings', children: [{ type: 'text', value: 'Settings' }] },
+ ],
+ },
+ ]);
+ setDocPathResolver(routes);
+ remarkDocPathLinks()()(tree);
+ const kids = tree.children?.[0]?.children ?? [];
+ expect(kids[0]?.type).toBe('inlineCode');
+ expect(kids[2]?.url).toBe('/settings');
+ });
+
test('a fragment on a backticked or prose path rides along too', () => {
const tree = makeTree([
{
diff --git a/packages/app/src/components/acp/doc-path-links.ts b/packages/app/src/components/acp/doc-path-links.ts
index 7dbedbe45..f922f380f 100644
--- a/packages/app/src/components/acp/doc-path-links.ts
+++ b/packages/app/src/components/acp/doc-path-links.ts
@@ -1,4 +1,4 @@
-import { decodeHrefPath, isExternalHref } from '@inkeep/open-knowledge-core';
+import { decodeHrefPath, isExternalHref, resolveInternalHref } from '@inkeep/open-knowledge-core';
import { docNameFromAbsolutePath } from '@/components/acp/follow-file';
import { hashFromDocName } from '@/lib/doc-hash';
import type { Workspace } from '@/lib/workspace-paths';
@@ -6,6 +6,7 @@ import type { Workspace } from '@/lib/workspace-paths';
export type DocPathResolver = (candidate: string) => string | null;
const DOC_PATH_REGEX = /(?<![A-Za-z0-9_./@-])[A-Za-z0-9_./@-]+\.(?:md|mdx)\b(?:#[A-Za-z0-9_-]+)?/g;
+const LEADING_DOT_SEGMENTS_RE = /^(?:\.[\\/])+/;
export interface BuildDocPathResolverInput {
readonly workspace: Workspace | null;
@@ -18,12 +19,20 @@ export function buildDocPathResolver(input: BuildDocPathResolverInput): DocPathR
return (candidate: string): string | null => {
const hashIdx = candidate.indexOf('#');
- const path = (hashIdx === -1 ? candidate : candidate.slice(0, hashIdx)).replace(/^@/, '');
+ const path = (hashIdx === -1 ? candidate : candidate.slice(0, hashIdx))
+ .replace(/^@/, '')
+ .replace(LEADING_DOT_SEGMENTS_RE, '');
if (path === '') return null;
const asAbsolute = docNameFromAbsolutePath(path, workspace);
if (asAbsolute !== null && pages.has(asAbsolute)) return asAbsolute;
+ if (path.startsWith('/')) {
+ if (stripMarkdownExt(path) === null) return null;
+ const rooted = resolveInternalHref(path.replaceAll('%', '%25'), '')?.docName ?? null;
+ return rooted !== null && pages.has(rooted) ? rooted : null;
+ }
+
const composed = joinWorkspaceRelative(workspace, path);
if (composed !== null) {
const composedDoc = docNameFromAbsolutePath(composed, workspace);
diff --git a/packages/server/assets/skills/project/SKILL.md b/packages/server/assets/skills/project/SKILL.md
index 1b379fb46..38a539b99 100644
--- a/packages/server/assets/skills/project/SKILL.md
+++ b/packages/server/assets/skills/project/SKILL.md
@@ -79,7 +79,7 @@ KB docs are factual artifacts: every claim traceable, and **the source lives ins
- **No evidence?** Search and ingest the result, OR mark `(TODO: needs source)`, OR don't write the claim. Do NOT fabricate — unsourced speculation rots into untraceable tribal lore.
## Linking — standard markdown links (MUST)
-Link every noun-phrase that names another document — `[text](./relative/path.md)` — and link liberally. **Every link must resolve to a doc that exists by the time you're done** (a same-pass forward-reference you create later in the pass is fine; for one that genuinely won't exist, leave the mention as plain prose + a tracked task). Never backtick a link (`` `[text](./foo.md)` `` is a bug) and never use HTML `<a>`. **After every `write`/`edit`, read `brokenLinks`: fix reported `href`s; `[]` means all links resolve unless `brokenLinkSuppression` withheld reserved-log findings; those are not yours to repair.** `audit` is authoritative; its same marker carries the same meaning. External web sources are NOT inline body links (see Grounding). Full rule set + the `[[Page]]` legacy note: `references/linking.md`.
+Link every noun-phrase that names another document — `[text](./relative/path.md)` — and link liberally. To point at one section of a long doc, in chat replies too, link `./path.md#heading-slug`. **Every link must resolve to a doc that exists by the time you're done** (a same-pass forward-reference you create later in the pass is fine; for one that genuinely won't exist, leave the mention as plain prose + a tracked task). Never backtick a link (`` `[text](./foo.md)` `` is a bug) and never use HTML `<a>`. **After every `write`/`edit`, read `brokenLinks`: fix reported `href`s; `[]` means all links resolve unless `brokenLinkSuppression` withheld reserved-log findings; those are not yours to repair.** `audit` is authoritative; its same marker carries the same meaning. External web sources are NOT inline body links (see Grounding). Full rule set, slug rule + the `[[Page]]` legacy note: `references/linking.md`.
## Folders, frontmatter, templates
diff --git a/packages/server/assets/skills/project/references/linking.md b/packages/server/assets/skills/project/references/linking.md
index 4cb2bbc3a..c3679e105 100644
--- a/packages/server/assets/skills/project/references/linking.md
+++ b/packages/server/assets/skills/project/references/linking.md
@@ -6,6 +6,7 @@
- **Never glue `./` onto a content-root path.** `./wiki/modules/tasks`, written from a doc already inside `wiki/`, resolves to the doubled garbage `wiki/wiki/modules/tasks` — correct resolution of a malformed path, i.e. a silently broken link. Pick ONE form: a relative path from your doc (`./tasks.md`, `../modules/tasks.md`), or a `/`-rooted absolute path (`/wiki/modules/tasks.md`). The `./` prefix and a content-root path never combine.
- **External web sources are NOT inline body links.** Per the Grounding rule, web URLs live in the `source_url:` frontmatter of an ingested doc under `external-sources/` (or the project's equivalent raw-sources folder); the body cites the local path: `[source name](./external-sources/source-slug.md)`. A raw `[source](https://...)` inline in the body is a TODO, not a citation — see Grounding for the closed-loop contract.
- **Internal cross-refs between OK docs** → `[text](./other-doc.md)` — link liberally to aid navigation.
+- **Link the section when you mean one part of a long document** — `[text](./spec.md#heading-slug)`, in docs and in chat replies alike, so the reader lands on the heading instead of scrolling a long file (in the WYSIWYG editor; the source editor ignores the fragment and opens at the top). In a chat reply there is no document for a relative path to start from: write the path from the content root, as `./specs/spec.md#heading-slug` or `/specs/spec.md#heading-slug`, never with `../`, which the chat cannot resolve. The slug is the heading's text lowercased, accents dropped, with each run of characters that are not letters or digits replaced by one `-` and edge hyphens removed (`## Data model: v2` → `#data-model-v2`); the second identical heading in a doc gets `-1`, the third `-2`. Copy the heading text rather than guessing: `brokenLinks` and `audit` check only the path before `#`, so a wrong slug still resolves as a link to the top of the doc.
- **Every link must resolve to a doc that exists by the time you're done.** Within a single multi-doc authoring pass, linking a page you'll create later in the same pass is fine — `brokenLinks` reports it as `no-such-doc` until the target lands, an expected transient forward-reference rather than a wrong-path error. What's not acceptable is *leaving* a dead link behind: create the target in the same pass, or record it as a tracked task (`TaskCreate`, or your host's task tool — if the host has none, tell the user) and leave the mention as plain prose.
- **Never wrap a link in backticks.** `` `[text](./foo.md)` `` is a bug — the backticks make it render as literal code rather than a link.
- **Never use HTML anchors** (`<a href="...">`). Markdown link syntax only.
diff --git a/packages/server/src/acp/registry.test.ts b/packages/server/src/acp/registry.test.ts
index fb0135290..28cc8c44e 100644
--- a/packages/server/src/acp/registry.test.ts
+++ b/packages/server/src/acp/registry.test.ts
@@ -1,7 +1,7 @@
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { afterEach, describe, expect, test } from 'vitest';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { getLogger } from '../logger.ts';
import {
ACP_AGENT_EDITOR_IDS,
@@ -151,6 +151,10 @@ describe('normalizeAgentDisplayName', () => {
});
describe('loadCustomAgents', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
test('returns valid entries, drops malformed ones, tolerates a missing file', async () => {
const localDir = tmp();
expect(await loadCustomAgents(localDir, log)).toEqual([]);
@@ -166,6 +170,76 @@ describe('loadCustomAgents', () => {
expect(agents).toHaveLength(1);
expect(agents[0]?.id).toBe('my-agent');
});
+
+ test('a rejected entry is logged by index, id and reason, never with its env values', async () => {
+ const localDir = tmp();
+ const warn = vi.spyOn(log, 'warn');
+ writeFileSync(
+ join(localDir, 'acp-agents.json'),
+ JSON.stringify([
+ { id: 'bad id!', name: 'Nope', command: 'x', env: { OPENAI_API_KEY: 'sk-live-secret' } },
+ ]),
+ );
+ expect(await loadCustomAgents(localDir, log)).toEqual([]);
+ expect(warn).toHaveBeenCalledOnce();
+ expect(warn.mock.calls[0]?.[0]).toEqual({
+ index: 0,
+ id: 'bad id!',
+ problem: expect.stringContaining('id'),
+ });
+ expect(JSON.stringify(warn.mock.calls)).not.toContain('sk-live-secret');
+ });
+
+ test('each field rule rejects on its own and names itself as the reason', async () => {
+ const localDir = tmp();
+ const warn = vi.spyOn(log, 'warn');
+ writeFileSync(
+ join(localDir, 'acp-agents.json'),
+ JSON.stringify([
+ { id: 'bad-name', name: 5, command: 'x' },
+ { id: 'bad-command', name: 'n', command: '' },
+ { id: 'bad-args', name: 'n', command: 'x', args: ['a', 1] },
+ { id: 'bad-env', name: 'n', command: 'x', env: { KEY: 1 } },
+ { id: 'fine', name: 'n', command: 'x', args: ['a'], env: { KEY: 'v' } },
+ ]),
+ );
+ const agents = await loadCustomAgents(localDir, log);
+ expect(agents.map((a) => a.id)).toEqual(['fine']);
+ expect(warn.mock.calls.map((call) => call[0])).toEqual([
+ { index: 0, id: 'bad-name', problem: expect.stringContaining('name') },
+ { index: 1, id: 'bad-command', problem: expect.stringContaining('command') },
+ { index: 2, id: 'bad-args', problem: expect.stringContaining('args') },
+ { index: 3, id: 'bad-env', problem: expect.stringContaining('env') },
+ ]);
+ });
+
+ test('a parse failure is logged without any text from the file', async () => {
+ const localDir = tmp();
+ const warn = vi.spyOn(log, 'warn');
+ writeFileSync(
+ join(localDir, 'acp-agents.json'),
+ '[{"id":"x","name":"x","command":"x","env":{"OPENAI_API_KEY":"sk-live-secret"} oops}]',
+ );
+ expect(await loadCustomAgents(localDir, log)).toEqual([]);
+ expect(warn).toHaveBeenCalledOnce();
+ expect(warn.mock.calls[0]?.[0]).toEqual({ error: 'SyntaxError', position: expect.any(Number) });
+ expect(JSON.stringify(warn.mock.calls)).not.toContain('sk-live-secret');
+ });
+
+ test('a file whose top level is not an array is ignored with a warning, like invalid JSON', async () => {
+ const localDir = tmp();
+ const warn = vi.spyOn(log, 'warn');
+ writeFileSync(
+ join(localDir, 'acp-agents.json'),
+ JSON.stringify({ id: 'solo', name: 'Solo', command: 'solo' }),
+ );
+ expect(await loadCustomAgents(localDir, log)).toEqual([]);
+ expect(warn).toHaveBeenCalledWith(expect.anything(), expect.stringContaining('JSON array'));
+ warn.mockClear();
+ writeFileSync(join(localDir, 'acp-agents.json'), '{not json');
+ expect(await loadCustomAgents(localDir, log)).toEqual([]);
+ expect(warn).toHaveBeenCalledWith(expect.anything(), expect.stringContaining('not valid JSON'));
+ });
});
describe('registryPlatformKey', () => {
diff --git a/packages/server/src/acp/registry.ts b/packages/server/src/acp/registry.ts
index 6c0ac6abf..3348990d2 100644
--- a/packages/server/src/acp/registry.ts
+++ b/packages/server/src/acp/registry.ts
@@ -216,37 +216,83 @@ export async function loadCustomAgents(
try {
parsed = JSON.parse(text);
} catch (err) {
- log.warn({ err }, `[acp-registry] ${CUSTOM_AGENTS_FILE} is not valid JSON — ignoring`);
+ log.warn(
+ { error: err instanceof Error ? err.name : 'unknown', position: jsonErrorPosition(err) },
+ `[acp-registry] ${CUSTOM_AGENTS_FILE} is not valid JSON — ignoring`,
+ );
+ return [];
+ }
+ if (!Array.isArray(parsed)) {
+ log.warn(
+ { topLevel: parsed === null ? 'null' : typeof parsed },
+ `[acp-registry] ${CUSTOM_AGENTS_FILE} must be a JSON array of agents — ignoring`,
+ );
return [];
}
- if (!Array.isArray(parsed)) return [];
const valid: CustomAgentEntry[] = [];
- for (const entry of parsed) {
- const e = entry as Record<string, unknown>;
- if (
- typeof e?.id === 'string' &&
- /^[a-zA-Z0-9_-]+$/.test(e.id) &&
- typeof e.name === 'string' &&
- typeof e.command === 'string' &&
- e.command.length > 0 &&
- (e.args === undefined ||
- (Array.isArray(e.args) && e.args.every((a) => typeof a === 'string'))) &&
- (e.env === undefined ||
- (typeof e.env === 'object' &&
- e.env !== null &&
- !Array.isArray(e.env) &&
- Object.values(e.env).every((v) => typeof v === 'string')))
- ) {
- valid.push({
- id: e.id,
- name: e.name,
- command: e.command,
- args: e.args as string[] | undefined,
- env: (e.env as Record<string, string> | undefined) ?? undefined,
- });
+ for (const [index, raw] of parsed.entries()) {
+ const result = parseCustomAgentEntry(raw);
+ if (result.ok) {
+ valid.push(result.entry);
} else {
- log.warn({ entry }, `[acp-registry] dropping malformed ${CUSTOM_AGENTS_FILE} entry`);
+ log.warn(
+ { index, id: result.id, problem: result.problem },
+ `[acp-registry] dropping malformed ${CUSTOM_AGENTS_FILE} entry`,
+ );
}
}
return valid;
}
+
+function jsonErrorPosition(err: unknown): number | undefined {
+ if (!(err instanceof Error)) return undefined;
+ const match = /at position (\d+)/.exec(err.message);
+ return match === null ? undefined : Number(match[1]);
+}
+
+type ParsedCustomAgentEntry =
+ | { ok: true; entry: CustomAgentEntry }
+ | { ok: false; id: string | undefined; problem: string };
+
+function parseCustomAgentEntry(raw: unknown): ParsedCustomAgentEntry {
+ const e = (typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? raw : {}) as Record<
+ string,
+ unknown
+ >;
+ const id = typeof e.id === 'string' ? e.id : undefined;
+ const reject = (problem: string): ParsedCustomAgentEntry => ({ ok: false, id, problem });
+ if (id === undefined || !/^[a-zA-Z0-9_-]+$/.test(id)) {
+ return reject('id must use only letters, digits, _ and -');
+ }
+ if (typeof e.name !== 'string') return reject('name must be a string');
+ if (typeof e.command !== 'string' || e.command.length === 0) {
+ return reject('command must be a non-empty string');
+ }
+ if (
+ e.args !== undefined &&
+ !(Array.isArray(e.args) && e.args.every((a) => typeof a === 'string'))
+ ) {
+ return reject('args must be an array of strings');
+ }
+ if (
+ e.env !== undefined &&
+ !(
+ typeof e.env === 'object' &&
+ e.env !== null &&
+ !Array.isArray(e.env) &&
+ Object.values(e.env).every((v) => typeof v === 'string')
+ )
+ ) {
+ return reject('env must be an object of string values');
+ }
+ return {
+ ok: true,
+ entry: {
+ id,
+ name: e.name,
+ command: e.command,
+ args: e.args as string[] | undefined,
+ env: (e.env as Record<string, string> | undefined) ?? undefined,
+ },
+ };
+}
diff --git a/packages/server/src/skill-linking-contract.test.ts b/packages/server/src/skill-linking-contract.test.ts
index 3dcf714c9..c00fb9831 100644
--- a/packages/server/src/skill-linking-contract.test.ts
+++ b/packages/server/src/skill-linking-contract.test.ts
@@ -25,6 +25,12 @@ describe('bundled project skill — link-authoring contract', () => {
expect(skill).toContain('references/linking.md');
});
+ test('core and linking reference carry the section-link form', () => {
+ expect(skill).toContain('#heading-slug');
+ expect(linking).toContain('#heading-slug');
+ expect(linking).toContain('in chat replies');
+ });
+
test('linking reference states relative is the recommended default + the no-hybrid rule', () => {
expect(linking).toContain('the recommended default');
expect(linking).toContain('Never glue `./` onto a content-root path');