Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

refactor(open-knowledge): remove dead /api/diff endpoint (#1741)

Andrew Mikofalvy1895e47a02ff
diff --git a/packages/app/tests/integration/api-error-envelope/diff.test.ts b/packages/app/tests/integration/api-error-envelope/diff.test.ts
deleted file mode 100644
index ade486b49..000000000
--- a/packages/app/tests/integration/api-error-envelope/diff.test.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
-import { join } from 'node:path';
-import {
- DiffSuccessSchema,
- ProblemDetailsSchema,
- SaveVersionSuccessSchema,
-} from '@inkeep/open-knowledge-core';
-import { createTestServer, pollDiskContentStable, type TestServer } from '../test-harness';
-
-let server: TestServer;
-
-beforeAll(async () => {
- server = await createTestServer();
-});
-
-afterAll(async () => {
- await server.cleanup();
-});
-
-describe('diff envelope (RFC 9457)', () => {
- test('happy path emits flat diff body parseable as DiffSuccessSchema', async () => {
- const docName = `diff-happy-${crypto.randomUUID().slice(0, 8)}`;
- await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ docName, markdown: '# Hello\n', position: 'replace' }),
- });
- await pollDiskContentStable(
- join(server.contentDir, `${docName}.md`),
- (c) => c.includes('# Hello'),
- { timeoutMs: 5000, settleMs: 100 },
- );
- const saveRes = await fetch(`http://127.0.0.1:${server.port}/api/save-version`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ docName }),
- });
- expect(saveRes.status).toBe(200);
- const saveBody = SaveVersionSuccessSchema.parse(await saveRes.json());
- const refMatch = saveBody.checkpointRef.match(/([0-9a-f]{40})$/);
- expect(refMatch).not.toBeNull();
- const sha = refMatch?.[1] ?? '';
- expect(sha).toMatch(/^[0-9a-f]{40}$/);
-
- const res = await fetch(
- `http://127.0.0.1:${server.port}/api/diff?docName=${encodeURIComponent(docName)}&to=${sha}`,
- );
- expect(res.status).toBe(200);
- expect(res.headers.get('content-type')).toBe('application/json');
- const body = await res.json();
- const parsed = DiffSuccessSchema.safeParse(body);
- expect(parsed.success).toBe(true);
- if (parsed.success) {
- expect(Array.isArray(parsed.data.lines)).toBe(true);
- expect(typeof parsed.data.additions).toBe('number');
- expect(typeof parsed.data.deletions).toBe('number');
- }
- });
-
- test('missing `to` query param emits problem+json invalid-request', async () => {
- const res = await fetch(`http://127.0.0.1:${server.port}/api/diff?docName=test-doc`);
- expect(res.status).toBe(400);
- expect(res.headers.get('content-type')).toBe('application/problem+json');
- const body = await res.json();
- const parsed = ProblemDetailsSchema.safeParse(body);
- expect(parsed.success).toBe(true);
- if (parsed.success) {
- expect(parsed.data.type).toBe('urn:ok:error:invalid-request');
- }
- });
-
- test('valid `to` SHA without commit emits problem+json doc-not-found', async () => {
- const fakeSha = '0123456789abcdef0123456789abcdef01234567';
- const res = await fetch(
- `http://127.0.0.1:${server.port}/api/diff?docName=test-doc&to=${fakeSha}`,
- );
- expect(res.status).toBe(404);
- expect(res.headers.get('content-type')).toBe('application/problem+json');
- const body = await res.json();
- const parsed = ProblemDetailsSchema.safeParse(body);
- expect(parsed.success).toBe(true);
- if (parsed.success) {
- expect(parsed.data.type).toBe('urn:ok:error:doc-not-found');
- }
- });
-
- test('method-not-allowed on POST emits problem+json with Allow: GET', async () => {
- const res = await fetch(`http://127.0.0.1:${server.port}/api/diff?docName=test-doc`, {
- method: 'POST',
- });
- expect(res.status).toBe(405);
- expect(res.headers.get('content-type')).toBe('application/problem+json');
- expect(res.headers.get('allow')).toBe('GET');
- const body = await res.json();
- const parsed = ProblemDetailsSchema.safeParse(body);
- expect(parsed.success).toBe(true);
- if (parsed.success) {
- expect(parsed.data.type).toBe('urn:ok:error:method-not-allowed');
- }
- });
-});
diff --git a/packages/app/tests/integration/attribution-sweep-coverage.test.ts b/packages/app/tests/integration/attribution-sweep-coverage.test.ts
index ae69223d8..d2df99dea 100644
--- a/packages/app/tests/integration/attribution-sweep-coverage.test.ts
+++ b/packages/app/tests/integration/attribution-sweep-coverage.test.ts
@@ -61,7 +61,6 @@ const EXEMPT_HANDLERS = new Set([
'handlePageHeadings',
'handleHistory',
'handleHistoryVersion',
- 'handleDiff',
'handleMetricsReconciliation',
'handleMetricsParseHealth',
'handleMetricsAgentPresence',
diff --git a/packages/app/tests/integration/conflict-gate-coverage.test.ts b/packages/app/tests/integration/conflict-gate-coverage.test.ts
index b43876ae1..9993b1e45 100644
--- a/packages/app/tests/integration/conflict-gate-coverage.test.ts
+++ b/packages/app/tests/integration/conflict-gate-coverage.test.ts
@@ -43,7 +43,6 @@ const EXEMPT_HANDLERS = new Set([
'handlePageHeadings',
'handleHistory',
'handleHistoryVersion',
- 'handleDiff',
'handleMetricsReconciliation',
'handleMetricsParseHealth',
'handleMetricsAgentPresence',
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 5285ac91b..ba8715e79 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -503,10 +503,6 @@ export {
DeletePathRequestSchema,
type DeletePathSuccess,
DeletePathSuccessSchema,
- type DiffLine as ApiDiffLine,
- DiffLineSchema,
- type DiffSuccess,
- DiffSuccessSchema,
type DiskEditReconciledWarning,
DiskEditReconciledWarningSchema,
type DocumentListEntry,
@@ -875,8 +871,6 @@ export type {
export type { Identity } from './types/identity.ts';
export type { Principal } from './types/principal.ts';
export type {
- DiffLine,
- DiffLineType,
EntryType,
ShadowContributor,
TimelineEntry,
diff --git a/packages/core/src/schemas/api/history.ts b/packages/core/src/schemas/api/history.ts
index 2fcd288fe..4e8550afd 100644
--- a/packages/core/src/schemas/api/history.ts
+++ b/packages/core/src/schemas/api/history.ts
@@ -73,23 +73,6 @@ export const HistoryVersionSuccessSchema = z
.loose() satisfies StandardSchemaV1;
export type HistoryVersionSuccess = z.infer<typeof HistoryVersionSuccessSchema>;
-export const DiffLineSchema = z
- .object({
- type: z.enum(['added', 'removed', 'unchanged']),
- text: z.string(),
- })
- .loose() satisfies StandardSchemaV1;
-export type DiffLine = z.infer<typeof DiffLineSchema>;
-
-export const DiffSuccessSchema = z
- .object({
- lines: z.array(DiffLineSchema),
- additions: z.number().int().nonnegative(),
- deletions: z.number().int().nonnegative(),
- })
- .loose() satisfies StandardSchemaV1;
-export type DiffSuccess = z.infer<typeof DiffSuccessSchema>;
-
export const WorkspaceSuccessSchema = z
.object({
contentDir: z.string().min(1),
diff --git a/packages/core/src/types/timeline.ts b/packages/core/src/types/timeline.ts
index da2e35604..d6f869f27 100644
--- a/packages/core/src/types/timeline.ts
+++ b/packages/core/src/types/timeline.ts
@@ -14,10 +14,3 @@ export interface TimelineEntry {
contributors: ShadowContributor[];
checkpoint: ParsedCheckpoint | null;
}
-
-export type DiffLineType = 'added' | 'removed' | 'unchanged';
-
-export interface DiffLine {
- type: DiffLineType;
- text: string;
-}
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 277f0b1eb..c5386a68b 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -60,7 +60,6 @@ import {
DeadLinksSuccessSchema,
DeletePathRequestSchema,
DeletePathSuccessSchema,
- DiffSuccessSchema,
type DiskEditReconciledWarning,
type DocumentListEntry,
DocumentListSuccessSchema,
@@ -183,7 +182,6 @@ import {
resolveGitDirDetailed,
} from '@inkeep/open-knowledge-core/shadow-repo-layout';
import busboy from 'busboy';
-import { diffLines } from 'diff';
import { fileTypeFromFile } from 'file-type';
import { parse as parseYaml } from 'yaml';
import { captureEffect } from './activity-log.ts';
@@ -5372,148 +5370,6 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
}
}
- const handleDiff = withValidation(
- EmptyRequestSchema,
- async (req, res) => {
- const shadow = shadowRef?.current;
- if (!shadow) {
- errorResponse(
- res,
- 503,
- 'urn:ok:error:shadow-not-configured',
- 'Shadow repo not configured.',
- { handler: 'diff' },
- );
- return;
- }
-
- const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
- const docName = url.searchParams.get('docName') ?? '';
- const from = url.searchParams.get('from') ?? '';
- const to = url.searchParams.get('to') ?? '';
-
- if (!to || !/^[0-9a-f]{40}$/i.test(to)) {
- errorResponse(
- res,
- 400,
- 'urn:ok:error:invalid-request',
- "'to' must be a valid 40-char commit SHA.",
- { handler: 'diff' },
- );
- return;
- }
-
- const resolvedContentRoot = contentRoot ?? '.';
- const pathResult = safeDocPath(docName, resolvedContentRoot);
- if ('error' in pathResult) {
- errorResponse(res, 400, 'urn:ok:error:invalid-request', pathResult.error, {
- handler: 'diff',
- });
- return;
- }
- const sg = shadowGit(shadow);
- const branch = getCurrentBranch?.() ?? 'main';
-
- const renameLogIndex = getOrLoadRenameLogIndex(shadow.gitDir);
- const ancestorCache = createAncestorShaSetCache();
- const pathFor = (name: string): string => {
- const p = safeDocPath(name, resolvedContentRoot);
- return 'error' in p ? `${name}.md` : p.path;
- };
-
- try {
- const toHistoricalPath = await resolveDocPathAtCommit(
- shadow,
- docName,
- to,
- branch,
- renameLogIndex,
- pathFor,
- ancestorCache,
- );
- if (toHistoricalPath === null) {
- errorResponse(
- res,
- 404,
- 'urn:ok:error:doc-not-found',
- 'Document did not exist at the target version.',
- { handler: 'diff' },
- );
- return;
- }
- const toContent = await sg.raw('show', `${to}:${toHistoricalPath}`);
-
- let fromContent: string;
- if (from && /^[0-9a-f]{40}$/i.test(from)) {
- const fromHistoricalPath = await resolveDocPathAtCommit(
- shadow,
- docName,
- from,
- branch,
- renameLogIndex,
- pathFor,
- ancestorCache,
- );
- if (fromHistoricalPath === null) {
- errorResponse(
- res,
- 404,
- 'urn:ok:error:doc-not-found',
- 'Document did not exist at the source version.',
- { handler: 'diff' },
- );
- return;
- }
- fromContent = await sg.raw('show', `${from}:${fromHistoricalPath}`);
- } else {
- const doc = hocuspocus.documents.get(docName);
- if (!doc) {
- errorResponse(
- res,
- 409,
- 'urn:ok:error:doc-not-open',
- 'Document is not currently open — open it in the editor first.',
- { handler: 'diff' },
- );
- return;
- }
- fromContent = doc.getText('source').toString();
- }
-
- const fromBody = stripFrontmatter(fromContent).body;
- const toBody = stripFrontmatter(toContent).body;
- const changes = diffLines(fromBody, toBody);
-
- const lines: { type: 'added' | 'removed' | 'unchanged'; text: string }[] = [];
- let additions = 0;
- let deletions = 0;
- for (const change of changes) {
- const changeLines = change.value.replace(/\n$/, '').split('\n');
- const type = change.added ? 'added' : change.removed ? 'removed' : 'unchanged';
- for (const text of changeLines) {
- lines.push({ type, text });
- }
- if (change.added) additions += changeLines.length;
- if (change.removed) deletions += changeLines.length;
- }
-
- successResponse(
- res,
- 200,
- DiffSuccessSchema,
- { lines, additions, deletions },
- { handler: 'diff' },
- );
- } catch (e) {
- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Internal server error.', {
- handler: 'diff',
- cause: e,
- });
- }
- },
- { handler: 'diff', method: 'GET', skipBodyParse: true },
- );
-
const handleRollback = withValidation(
RollbackRequestSchema,
async (_req, res, body) => {
@@ -11094,7 +10950,6 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
'/api/agent-burst-diff': handleAgentBurstDiff,
'/api/save-version': handleSaveVersion,
'/api/history': handleHistory,
- '/api/diff': handleDiff,
'/api/rollback': handleRollback,
'/api/metrics/reconciliation': handleMetricsReconciliation,
'/api/metrics/parse-health': handleMetricsParseHealth,