Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): warn that an empty folder's share link can never work (#3011)

miles-kt-inkeep9bed9928e4bf
diff --git a/.changeset/share-empty-folder-verdict.md b/.changeset/share-empty-folder-verdict.md
new file mode 100644
index 000000000..877067581
--- /dev/null
+++ b/.changeset/share-empty-folder-verdict.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Sharing a folder with no documents in it now says so plainly instead of promising the link will work after the next sync. Git has no way to represent an empty folder, so the minted link 404s for the recipient and no push would ever fix it — but the share popover offered "Enable auto-sync", "How to push manually" and "Sync now", and running a sync turned the warning into "Synced. The link is up to date." over a link that still went nowhere. The popover now shows a warning naming the only real remedy, adding a document, and offers no sync buttons at all. The `share_link` MCP tool relays the same sentence to agents rather than the push advice, and the freshness signal on `POST /api/share/construct-url` gained an `empty` verdict so the two cases are also tellable apart in the logs. Folders that genuinely just need a push are unaffected, and a doc reports exactly as before at any size, including zero bytes.
diff --git a/docs/content/features/share.mdx b/docs/content/features/share.mdx
index 5c1ac8195..c0660db33 100644
--- a/docs/content/features/share.mdx
+++ b/docs/content/features/share.mdx
@@ -29,8 +29,9 @@ A share link points at GitHub, but your local edits only reach GitHub through au
- **Not on GitHub yet.** The target has never been pushed, so the link won't resolve until it is. With auto-sync off, the row offers **Enable auto-sync** and **How to push manually**; with auto-sync on, it offers **Sync now** and clears itself once the push lands.
- **Unpushed changes.** The target is on GitHub but has local edits that aren't, so recipients see the last pushed version. With auto-sync on this stays silent — the next sync closes the gap.
+- **Empty folder.** The folder holds nothing Git can track — it has no documents, or everything inside it is ignored — so the link won't resolve, and unlike the never-pushed case no push will fix it. The row names the only remedy, adding a document, and offers no sync actions at all. Only folders reach this state: a doc is trackable at any size, including zero bytes.
-If you don't have write access to the repo, the row explains that instead of offering a push action. The check is local, adds no network round-trip, and never blocks sharing: if it can't run, the link still copies with no warning. Folder shares get the same treatment as docs. Links minted by an agent get the same check: the [`share_link` MCP tool](/docs/reference/mcp) prepends the warning to its response so the agent can relay it with the link.
+If you don't have write access to the repo, the row explains that instead of offering a push action. The check is local, adds no network round-trip, and never blocks sharing: if it can't run, the link still copies with no warning. Folder shares get the same treatment as docs, and can additionally hit the empty-folder case above, which a doc never can. Links minted by an agent get the same check: the [`share_link` MCP tool](/docs/reference/mcp) prepends the warning to its response so the agent can relay it with the link.
## Opening a share link
diff --git a/packages/app/src/components/ShareFreshnessWarning.dom.test.tsx b/packages/app/src/components/ShareFreshnessWarning.dom.test.tsx
index 01f18ddd3..85799dbbc 100644
--- a/packages/app/src/components/ShareFreshnessWarning.dom.test.tsx
+++ b/packages/app/src/components/ShareFreshnessWarning.dom.test.tsx
@@ -32,7 +32,7 @@ vi.doMock('@/lib/config-provider', () => ({
}),
}));
-const { ShareFreshnessWarning } = await import('./ShareFreshnessWarning');
+const { ShareFreshnessWarning, shareFreshnessRowVisible } = await import('./ShareFreshnessWarning');
function makeStatus(overrides: Partial<GitSyncStatus> = {}): GitSyncStatus {
return {
@@ -312,3 +312,95 @@ describe('ShareFreshnessWarning — recovery CTAs (FR4/FR5)', () => {
expect(screen.queryByRole('link', { name: /How to push manually/ })).toBeNull();
});
});
+
+describe('ShareFreshnessWarning — empty folder', () => {
+ const FACT = "The link won't work until you add a tracked document.";
+
+ test('sync off: states the folder is empty and offers no remedy', () => {
+ render(
+ <ShareFreshnessWarning
+ freshness="empty"
+ status={makeStatus({ syncEnabled: false })}
+ kind="folder"
+ />,
+ );
+ const row = screen.getByTestId('share-freshness-row');
+ const text = row.textContent ?? '';
+ expect(text).toContain("Git can't track this folder");
+ expect(text).toContain(FACT);
+ // Nothing here claims a push would help.
+ expect(text).not.toContain("isn't on GitHub yet");
+ expect(text).not.toContain("hasn't synced to GitHub yet");
+ // Every CTA is a dead end for a folder git cannot represent.
+ expect(screen.queryByRole('button', { name: 'Enable auto-sync' })).toBeNull();
+ expect(screen.queryByRole('link', { name: /How to push manually/ })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Sync now' })).toBeNull();
+ });
+
+ test('sync on: renders the same row — auto-sync cannot resolve this state', () => {
+ render(
+ <ShareFreshnessWarning
+ freshness="empty"
+ status={makeStatus({ syncEnabled: true, state: 'idle' })}
+ kind="folder"
+ />,
+ );
+ const text = screen.getByTestId('share-freshness-row').textContent ?? '';
+ expect(text).toContain("Git can't track this folder");
+ expect(text).toContain(FACT);
+ expect(screen.queryByRole('button', { name: 'Sync now' })).toBeNull();
+ });
+
+ test('carries the strong icon whether or not auto-sync is on', () => {
+ const { rerender } = render(
+ <ShareFreshnessWarning
+ freshness="empty"
+ status={makeStatus({ syncEnabled: false })}
+ kind="folder"
+ />,
+ );
+ expect(
+ screen.getByTestId('share-freshness-row').querySelector('svg.lucide-triangle-alert'),
+ ).not.toBeNull();
+ rerender(
+ <ShareFreshnessWarning
+ freshness="empty"
+ status={makeStatus({ syncEnabled: true, state: 'idle' })}
+ kind="folder"
+ />,
+ );
+ expect(
+ screen.getByTestId('share-freshness-row').querySelector('svg.lucide-triangle-alert'),
+ ).not.toBeNull();
+ });
+
+ test('a completed sync never turns the row into an all-clear', () => {
+ const { rerender } = render(
+ <ShareFreshnessWarning
+ freshness="empty"
+ status={makeStatus({ syncEnabled: true, state: 'idle', lastSyncUtc: null })}
+ kind="folder"
+ />,
+ );
+ // A sync completes elsewhere (the auto-sync cadence) and bumps lastSyncUtc.
+ rerender(
+ <ShareFreshnessWarning
+ freshness="empty"
+ status={makeStatus({
+ syncEnabled: true,
+ state: 'idle',
+ lastSyncUtc: '2026-07-02T12:00:00Z',
+ })}
+ kind="folder"
+ />,
+ );
+ const text = screen.getByTestId('share-freshness-row').textContent ?? '';
+ expect(text).not.toContain('Synced. The link is up to date.');
+ expect(text).toContain("Git can't track this folder");
+ });
+
+ test('the popover sizes for the row in both sync states', () => {
+ expect(shareFreshnessRowVisible('empty', makeStatus({ syncEnabled: false }))).toBe(true);
+ expect(shareFreshnessRowVisible('empty', makeStatus({ syncEnabled: true }))).toBe(true);
+ });
+});
diff --git a/packages/app/src/components/ShareFreshnessWarning.tsx b/packages/app/src/components/ShareFreshnessWarning.tsx
index 044114c6f..81d925bd2 100644
--- a/packages/app/src/components/ShareFreshnessWarning.tsx
+++ b/packages/app/src/components/ShareFreshnessWarning.tsx
@@ -33,12 +33,14 @@ const PUSH_DOCS_URL = 'https://git-scm.com/docs/git-push';
/**
* Whether the warning row renders for `(freshness, status)`. The share popover
* reads this to size itself before the row mounts. `current` / omitted freshness
- * never warns; `stale` with auto-sync ON is the ratified silent cell.
+ * never warns; `stale` with auto-sync ON is the ratified silent cell. `empty`
+ * warns unconditionally — no sync setting makes an untrackable folder shareable.
*/
export function shareFreshnessRowVisible(
freshness: ShareFreshness | undefined,
status: GitSyncStatus | null,
): boolean {
+ if (freshness === 'empty') return true;
if (freshness !== 'stale' && freshness !== 'absent') return false;
if (freshness === 'stale' && status?.syncEnabled === true) return false;
return true;
@@ -99,6 +101,21 @@ export function ShareFreshnessWarning({ freshness, status, kind }: ShareFreshnes
const rowClass =
'flex items-start gap-2 rounded-md border border-dashed border-border bg-muted/40 p-2 text-xs text-muted-foreground';
+ // Ahead of every other branch on purpose: no CTA on this row is a real
+ // remedy, and no completed sync turns it into an all-clear, because nothing
+ // a push can carry is missing. Adding a document is the only way out, so the
+ // row states that and stops.
+ if (freshness === 'empty') {
+ return (
+ <div className={rowClass} data-testid="share-freshness-row">
+ <TriangleAlert className="mt-0.5 size-3.5 shrink-0" aria-hidden="true" />
+ <span>
+ {t`Git can't track this folder — it's empty or contains only ignored files. The link won't work until you add a tracked document.`}
+ </span>
+ </div>
+ );
+ }
+
if (syncNow === 'synced') {
return (
<div className={rowClass} data-testid="share-freshness-row">
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 5de908694..dbb0d4ea5 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -2198,6 +2198,9 @@
"eTsJYJ": ["description"],
"eVPynQ": ["Open <0><1>", ["verificationUri"], "</1><2/></0> and enter this code:"],
"eaHUxx": ["Files toolbar"],
+ "eazHgv": [
+ "Git can't track this folder — it's empty or contains only ignored files. The link won't work until you add a tracked document."
+ ],
"el312q": ["Install skills into"],
"emgiet": ["Authoritative content; mirrored verbatim everywhere it's referenced."],
"enPTnx": ["line ", ["displayLine"]],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 6c1b362e2..73565bf00 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -4496,6 +4496,10 @@ msgstr "Get product updates in your inbox."
msgid "Get set up"
msgstr "Get set up"
+#: src/components/ShareFreshnessWarning.tsx
+msgid "Git can't track this folder — it's empty or contains only ignored files. The link won't work until you add a tracked document."
+msgstr "Git can't track this folder — it's empty or contains only ignored files. The link won't work until you add a tracked document."
+
#: src/components/settings/SharingSection.tsx
#: src/components/SkillsSidebarSection.tsx
msgid "git configuration is unavailable"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 26723cab5..008a18929 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -2198,6 +2198,9 @@
"eTsJYJ": ["ďēśćŕĩƥţĩōń"],
"eVPynQ": ["Ōƥēń <0><1>", ["verificationUri"], "</1><2/></0> àńď ēńţēŕ ţĥĩś ćōďē:"],
"eaHUxx": ["Ƒĩĺēś ţōōĺƀàŕ"],
+ "eazHgv": [
+ "Ĝĩţ ćàń'ţ ţŕàćķ ţĥĩś ƒōĺďēŕ — ĩţ'ś ēḿƥţŷ ōŕ ćōńţàĩńś ōńĺŷ ĩĝńōŕēď ƒĩĺēś. Ţĥē ĺĩńķ ŵōń'ţ ŵōŕķ ũńţĩĺ ŷōũ àďď à ţŕàćķēď ďōćũḿēńţ."
+ ],
"el312q": ["Ĩńśţàĺĺ śķĩĺĺś ĩńţō"],
"emgiet": ["Àũţĥōŕĩţàţĩvē ćōńţēńţ; ḿĩŕŕōŕēď vēŕƀàţĩḿ ēvēŕŷŵĥēŕē ĩţ'ś ŕēƒēŕēńćēď."],
"enPTnx": ["ĺĩńē ", ["displayLine"]],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 4cac890fd..04f5e4355 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -4492,6 +4492,10 @@ msgstr ""
msgid "Get set up"
msgstr ""
+#: src/components/ShareFreshnessWarning.tsx
+msgid "Git can't track this folder — it's empty or contains only ignored files. The link won't work until you add a tracked document."
+msgstr ""
+
#: src/components/settings/SharingSection.tsx
#: src/components/SkillsSidebarSection.tsx
msgid "git configuration is unavailable"
diff --git a/packages/core/src/schemas/api/share.test.ts b/packages/core/src/schemas/api/share.test.ts
index 198f0807c..789169c7b 100644
--- a/packages/core/src/schemas/api/share.test.ts
+++ b/packages/core/src/schemas/api/share.test.ts
@@ -245,8 +245,12 @@ describe('isBranchNotFoundGitError', () => {
});
describe('ShareFreshnessSchema (closed v1 enum)', () => {
- test('accepts the three v1 freshness states', () => {
- for (const value of ['current', 'stale', 'absent'] as const) {
+ test('accepts every freshness state the contract declares', () => {
+ // `empty` is the verdict for a folder git holds no object for: unlike
+ // `absent`, no push resolves it, so it cannot be folded into `absent`
+ // without the enum promising a remedy that does not exist.
+ for (const value of ['current', 'stale', 'absent', 'empty'] as const) {
+ expect(ShareFreshnessSchema.safeParse(value).success).toBe(true);
expect(ShareFreshnessSchema.parse(value)).toBe(value);
}
});
@@ -273,7 +277,10 @@ describe('ShareConstructUrlResponseSchema freshness field', () => {
});
test('each valid freshness value round-trips on the success variant', () => {
- for (const value of ['current', 'stale', 'absent'] as const) {
+ // The field is `.catch(undefined)`, so a value the enum does not carry is
+ // stripped silently rather than rejected — a verdict missing from the enum
+ // reaches no consumer at all.
+ for (const value of ['current', 'stale', 'absent', 'empty'] as const) {
const parsed = ShareConstructUrlResponseSchema.parse({ ...successBase, freshness: value });
expect(parsed.ok).toBe(true);
if (parsed.ok) expect(parsed.freshness).toBe(value);
diff --git a/packages/core/src/schemas/api/share.ts b/packages/core/src/schemas/api/share.ts
index b149ca273..a4b12edba 100644
--- a/packages/core/src/schemas/api/share.ts
+++ b/packages/core/src/schemas/api/share.ts
@@ -93,15 +93,19 @@ export type ShareConstructUrlErrorCode = z.infer<typeof ShareConstructUrlErrorCo
* reads the last pushed version until a push lands.
* - `absent` — the target isn't on origin at all, so the minted link 404s for
* the recipient until it's pushed.
+ * - `empty` — a shared folder holding nothing git can track. Git has no object
+ * for a folder with zero blobs, so unlike `absent` this is NOT push-fixable:
+ * no push resolves it, and the only remedy is adding a document.
*
- * Closed enum for v1. Producers only ever emit these three; consumers parse
- * tolerantly (see the `freshness` field below), so a value a newer server
- * adds degrades to "no signal" on an older client rather than a parse failure.
+ * Closed enum. Consumers parse tolerantly (see the `freshness` field below),
+ * so a value a newer server adds degrades to "no signal" on an older client
+ * rather than a parse failure.
*/
export const ShareFreshnessSchema = z.enum([
'current',
'stale',
'absent',
+ 'empty',
]) satisfies StandardSchemaV1;
export type ShareFreshness = z.infer<typeof ShareFreshnessSchema>;
@@ -116,7 +120,8 @@ export type ShareFreshness = z.infer<typeof ShareFreshnessSchema>;
*
* The success variant also carries an optional `freshness` signal
* (`ShareFreshnessSchema`) describing whether the shared target is current /
- * stale / absent vs. origin; it is omitted whenever the signal is unavailable.
+ * stale / absent / empty vs. origin (`empty` is the folder-only,
+ * not-push-fixable case); it is omitted whenever the signal is unavailable.
*
* Schemas are `.loose()` per the file-wide convention for forward-compat;
* adding fields (e.g., `defaultBranch` for splash branch-indicator hints)
diff --git a/packages/server/src/mcp/tools/output-schema-strictness.test.ts b/packages/server/src/mcp/tools/output-schema-strictness.test.ts
index db51e5487..7c19fa0c6 100644
--- a/packages/server/src/mcp/tools/output-schema-strictness.test.ts
+++ b/packages/server/src/mcp/tools/output-schema-strictness.test.ts
@@ -389,10 +389,21 @@ describe('share_link outputSchema admits the freshness success payloads (S3)', (
...base,
text: 'Share link for doc `notes` on branch `main`:\nhttps://openknowledge.ai/d/enc',
};
+ // A folder git holds no object for. The declared enum is what AJV compiles
+ // into the client-side check, so a verdict the tool emits but the enum omits
+ // costs the agent the WHOLE result, not just the warning.
+ const withEmptyFreshness = {
+ ...base,
+ sharedUrl: 'https://github.com/o/r/tree/main/hollow',
+ resolvedKind: 'folder',
+ freshness: 'empty',
+ text: "Git can't track this folder — it's empty or contains only ignored files. The link won't work until you add a tracked document.\n\nShare link for folder `hollow` on branch `main`:\nhttps://openknowledge.ai/d/enc",
+ };
for (const [label, payload] of [
['success with freshness', withFreshness],
['success without freshness (happy-path passthrough)', withoutFreshness],
+ ['success with the empty-folder verdict', withEmptyFreshness],
] as const) {
test(`${label} structuredContent validates against the compiled share_link schema`, () => {
const validator = new AjvJsonSchemaValidator();
diff --git a/packages/server/src/mcp/tools/share-link.test.ts b/packages/server/src/mcp/tools/share-link.test.ts
index 534ecd55f..50ce0264f 100644
--- a/packages/server/src/mcp/tools/share-link.test.ts
+++ b/packages/server/src/mcp/tools/share-link.test.ts
@@ -19,6 +19,7 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { hostname, tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'vitest';
+import type { z } from 'zod';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { type FetchTestServer, startFetchTestServer } from './fetch-test-server.test-helper.ts';
import { register, type ShareLinkDeps } from './share-link.ts';
@@ -37,6 +38,8 @@ interface RegisteredTool {
name: string;
description: string;
inputSchema?: Record<string, unknown>;
+ /** Raw Zod shape the tool declares; each field is parseable on its own. */
+ outputSchema?: Record<string, z.ZodType>;
handler: (args: { path: string; kind?: 'doc' | 'folder'; cwd?: string }) => Promise<ToolResult>;
}
@@ -45,13 +48,18 @@ function createFakeServer() {
const server = {
registerTool(
name: string,
- cfg: { description?: string; inputSchema?: Record<string, unknown> },
+ cfg: {
+ description?: string;
+ inputSchema?: Record<string, unknown>;
+ outputSchema?: Record<string, z.ZodType>;
+ },
handler: RegisteredTool['handler'],
) {
registered = {
name,
description: cfg.description ?? '',
inputSchema: cfg.inputSchema,
+ outputSchema: cfg.outputSchema,
handler,
};
},
@@ -789,6 +797,31 @@ describe('share_link — freshness relay (FR6)', () => {
expect(result.content[0]?.text?.startsWith('Share link for')).toBe(true);
});
+ test('relays the empty-folder sentence instead of a push remedy', async () => {
+ await mkdir(resolve(tmpDir, 'hollow'), { recursive: true });
+ mockResponse = { status: 200, body: { ...successBody(), freshness: 'empty' } };
+ const { server, getTool } = createFakeServer();
+ register(server, makeDeps(baseUrl));
+ const result = await getTool().handler({ path: 'hollow' });
+ expect(result.structuredContent).toMatchObject({ ok: true, freshness: 'empty' });
+ const text = result.content[0]?.text ?? '';
+ expect(text).toContain("Git can't track this folder");
+ expect(text).toContain(
+ "it's empty or contains only ignored files. The link won't work until you add a tracked document.",
+ );
+ // The agent must not relay a remedy no push can deliver.
+ expect(text).not.toContain("isn't on GitHub yet");
+ });
+
+ test('declares the empty verdict in the output schema so strict clients accept it', () => {
+ const { server, getTool } = createFakeServer();
+ register(server, makeDeps(baseUrl));
+ // Claude validates `structuredContent` against this schema with AJV, so a
+ // verdict the tool can emit but the schema omits is rejected client-side.
+ const freshnessSchema = getTool().outputSchema?.freshness;
+ expect(freshnessSchema?.safeParse('empty').success).toBe(true);
+ });
+
test('tolerates an unknown freshness value: no warning, field omitted, tool still succeeds (D21)', async () => {
await writeFile(resolve(tmpDir, 'notes.md'), '# notes');
mockResponse = { status: 200, body: { ...successBody(), freshness: 'catching-up' } };
diff --git a/packages/server/src/mcp/tools/share-link.ts b/packages/server/src/mcp/tools/share-link.ts
index 6b024d04d..784dc3fa3 100644
--- a/packages/server/src/mcp/tools/share-link.ts
+++ b/packages/server/src/mcp/tools/share-link.ts
@@ -19,6 +19,7 @@ import {
type ShareConstructUrlErrorCode,
ShareConstructUrlResponseSchema,
type ShareFreshness,
+ ShareFreshnessSchema,
} from '@inkeep/open-knowledge-core';
import { z } from 'zod';
import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';
@@ -69,9 +70,10 @@ interface ShareLinkSuccess {
/**
* The relayable warning an agent prepends to a share link when the target
* isn't current on origin — the `share_link` mirror of the popover's fact line
- * (kind substitutes doc/folder). `current` and `undefined` (the fail-open and
- * unknown-value cases) get no warning, so an older client that can't interpret
- * a newer freshness value degrades to silence rather than a bad relay.
+ * (kind substitutes doc/folder, except in the folder-only `empty` branch).
+ * `current` and `undefined` (the fail-open and unknown-value cases) get no
+ * warning, so an older client that can't interpret a newer freshness value
+ * degrades to silence rather than a bad relay.
*/
function freshnessWarning(freshness: ShareFreshness | undefined, kind: ShareKind): string {
if (freshness === 'absent') {
@@ -80,6 +82,12 @@ function freshnessWarning(freshness: ShareFreshness | undefined, kind: ShareKind
if (freshness === 'stale') {
return `This ${kind} has unpushed changes. Recipients will see the last pushed version.\n\n`;
}
+ if (freshness === 'empty') {
+ // Hardcodes "folder" rather than substituting `kind`: the producer in
+ // freshness.ts emits `empty` only for `kind === 'folder'`, so a doc never
+ // reaches this branch.
+ return `Git can't track this folder — it's empty or contains only ignored files. The link won't work until you add a tracked document.\n\n`;
+ }
return '';
}
@@ -285,12 +293,14 @@ const OutputSchema = outputSchemaWithText({
.enum(['doc', 'folder'])
.optional()
.describe('Kind the target resolved to (success only).'),
- freshness: z
- .enum(['current', 'stale', 'absent'])
- .optional()
- .describe(
- 'Whether the shared target matches origin (success only): current, stale (unpushed edits), or absent (not on origin). Omitted when the probe could not run.',
- ),
+ // Reuses the canonical enum rather than restating it. A strict client (AJV)
+ // rejects the whole `structuredContent` when the declared schema and the
+ // emitted value disagree, so a hand-maintained copy here turns any future
+ // widening of `ShareFreshnessSchema` into a runtime rejection with no
+ // compile-time warning. Importing it makes the two diverge-proof.
+ freshness: ShareFreshnessSchema.optional().describe(
+ 'Whether the shared target matches origin (success only): current, stale (unpushed edits), absent (not on origin, a push fixes it), or empty (a folder holding nothing git can track, which no push fixes). Omitted when the probe could not run.',
+ ),
error: z
.enum([
'no-remote',
diff --git a/packages/server/src/share/construct-url.test.ts b/packages/server/src/share/construct-url.test.ts
index 521eb55b7..6320f37e6 100644
--- a/packages/server/src/share/construct-url.test.ts
+++ b/packages/server/src/share/construct-url.test.ts
@@ -3,7 +3,7 @@ import { mkdtemp, rm } from 'node:fs/promises';
import type { Server } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { decodeShareUrl } from '@inkeep/open-knowledge-core';
+import { decodeShareUrl, ShareFreshnessSchema } from '@inkeep/open-knowledge-core';
import { afterEach, describe, expect, test } from 'vitest';
import { loggerFactory, PinoLogger } from '../logger.ts';
import {
@@ -634,6 +634,29 @@ describe('emitShareConstructUrlLog telemetry', () => {
expect(records[0]).toMatchObject({ result: 'invalid-path', kind: 'doc' });
});
+ test('records every freshness verdict distinctly, including the one no push resolves', () => {
+ // Ops discrimination: a share that is dead forever must not land in the
+ // same log bucket as one the next push fixes. Driven off the contract's own
+ // enum so a verdict added to it can never reach the log as a silent
+ // synonym of another.
+ const verdicts = ShareFreshnessSchema.options;
+ const records = captureLog(() => {
+ for (const freshness of verdicts) {
+ emitShareConstructUrlLog('ok', { branchExists: true, kind: 'folder', freshness });
+ }
+ });
+ const logged = records.map((r) => r.freshness);
+ expect(logged).toContain('empty');
+ expect(logged).toContain('absent');
+ expect(records.find((r) => r.freshness === 'empty')).toMatchObject({
+ action: 'construct-url',
+ result: 'ok',
+ kind: 'folder',
+ freshness: 'empty',
+ });
+ expect(new Set(logged).size).toBe(verdicts.length);
+ });
+
test('omits kind + branchExists when opts absent', () => {
const records = captureLog(() => emitShareConstructUrlLog('no-remote'));
expect(records[0]).not.toHaveProperty('kind');
diff --git a/packages/server/src/share/construct-url.ts b/packages/server/src/share/construct-url.ts
index f7fdd2437..1fa572bb7 100644
--- a/packages/server/src/share/construct-url.ts
+++ b/packages/server/src/share/construct-url.ts
@@ -104,7 +104,7 @@ export function buildGitHubTreeUrl(
/**
* Emit one structured ops log line per request. All fields are non-PII (no
* project path, no doc filename, no URL bytes). `kind` (`'doc' | 'folder'`)
- * and `freshness` (`'current' | 'stale' | 'absent'`) are bounded enums, so
+ * and `freshness` (`'current' | 'stale' | 'absent' | 'empty'`) are bounded enums, so
* they're safe as span/log attributes per the cardinality STOP rule.
* `freshness` is omitted when the probe couldn't run (fail-open).
*/
diff --git a/packages/server/src/share/endpoint-real-git.test.ts b/packages/server/src/share/endpoint-real-git.test.ts
index 1b41ab017..5432df0ca 100644
--- a/packages/server/src/share/endpoint-real-git.test.ts
+++ b/packages/server/src/share/endpoint-real-git.test.ts
@@ -41,6 +41,25 @@ async function postTargetStatus(port: number, body: unknown): Promise<Response>
});
}
+async function postConstructUrl(port: number, body: unknown): Promise<Response> {
+ return fetch(`http://127.0.0.1:${port}/api/share/construct-url`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+}
+
+/**
+ * Point the triangle's sender at a github.com URL so the handler's origin gate
+ * classifies it as a GitHub remote and reaches the freshness probe. Every probe
+ * downstream (`rev-parse` / `cat-file` / `diff` / `status`) reads local refs, so
+ * the unreachable URL is never contacted and the real push already recorded
+ * `refs/remotes/origin/<branch>`.
+ */
+function repointOriginAtGitHub(t: GitTriangle): void {
+ t.git(t.senderDir, ['remote', 'set-url', 'origin', 'https://github.com/o/r.git']);
+}
+
async function getBranchInfo(
port: number,
query: { branch: string; path: string; kind: 'doc' | 'folder' },
@@ -155,6 +174,66 @@ describe('GET /api/git/branch-info (shareTargetOnOriginBranch over HTTP)', () =>
});
});
+describe('POST /api/share/construct-url (freshness computed through the endpoint)', () => {
+ test('a folder holding no files reports the empty verdict on the wire', async () => {
+ const t = newTriangle();
+ t.mkdirWorkingTree('hollow');
+ repointOriginAtGitHub(t);
+
+ rig = await bootEndpointServer({ projectDir: t.senderDir });
+ const res = await postConstructUrl(rig.port, { kind: 'folder', folderPath: 'hollow' });
+
+ expect(res.status).toBe(200);
+ const json = (await res.json()) as Record<string, unknown>;
+ // The whole composition, not just the producer: the response schema's
+ // `.catch(undefined)` strips a freshness value its enum does not carry, so
+ // an unwidened enum returns 200 with the field silently gone — no error, no
+ // log, and the client sees "no signal" instead of the warning.
+ expect(json).toMatchObject({
+ ok: true,
+ branch: t.branch,
+ sharedUrl: 'https://github.com/o/r/tree/main/hollow',
+ freshness: 'empty',
+ });
+ });
+
+ test('a folder holding an untracked doc still reports absent — a push does fix that one', async () => {
+ const t = newTriangle();
+ t.writeWorkingTree('drafts/note.md', '# draft\n');
+ repointOriginAtGitHub(t);
+
+ rig = await bootEndpointServer({ projectDir: t.senderDir });
+ const res = await postConstructUrl(rig.port, { kind: 'folder', folderPath: 'drafts' });
+
+ expect(res.status).toBe(200);
+ expect((await res.json()) as Record<string, unknown>).toMatchObject({
+ ok: true,
+ freshness: 'absent',
+ });
+ });
+
+ test('a folder whose only contents are gitignored reports empty on the wire', async () => {
+ const t = newTriangle();
+ t.seedAndPush('.gitignore', 'scratch/\n');
+ t.writeWorkingTree('scratch/note.md', '# ignored\n');
+ repointOriginAtGitHub(t);
+
+ rig = await bootEndpointServer({ projectDir: t.senderDir });
+ const res = await postConstructUrl(rig.port, { kind: 'folder', folderPath: 'scratch' });
+
+ expect(res.status).toBe(200);
+ // The sharpest cell, and the one most likely to regress into `absent`: the
+ // folder looks populated on disk but is invisible to git, so the untracked
+ // probe comes back empty exactly as it does for a bare directory. Pinned at
+ // the endpoint tier because that is where the verdict has to survive the
+ // response schema to reach a client.
+ expect((await res.json()) as Record<string, unknown>).toMatchObject({
+ ok: true,
+ freshness: 'empty',
+ });
+ });
+});
+
describe('target-status fetch timeout', () => {
test('a hanging credentialed fetch is bounded by the block timeout and degrades to unknown', async () => {
const t = newTriangle();
diff --git a/packages/server/src/share/freshness.test.ts b/packages/server/src/share/freshness.test.ts
index fd1fb76a7..e71a6809f 100644
--- a/packages/server/src/share/freshness.test.ts
+++ b/packages/server/src/share/freshness.test.ts
@@ -81,12 +81,81 @@ describe('computeShareFreshness — folder drift cells', () => {
});
});
+describe('computeShareFreshness — folder with no git-trackable content', () => {
+ test('a folder holding no files is empty, not absent', async () => {
+ const t = newTriangle();
+ t.mkdirWorkingTree('hollow');
+ expect(await computeShareFreshness(t.senderDir, t.branch, 'hollow', 'folder')).toBe('empty');
+ });
+
+ test('a folder holding only empty subfolders is empty', async () => {
+ const t = newTriangle();
+ t.mkdirWorkingTree('outer/inner/deeper');
+ expect(await computeShareFreshness(t.senderDir, t.branch, 'outer', 'folder')).toBe('empty');
+ });
+
+ test('a folder whose only contents are gitignored is empty', async () => {
+ const t = newTriangle();
+ t.seedAndPush('.gitignore', 'scratch/\n');
+ t.writeWorkingTree('scratch/note.md', '# ignored\n');
+ expect(await computeShareFreshness(t.senderDir, t.branch, 'scratch', 'folder')).toBe('empty');
+ });
+
+ test('a push leaves the verdict unchanged — the state a push cannot resolve', async () => {
+ const t = newTriangle();
+ t.mkdirWorkingTree('hollow');
+ expect(await computeShareFreshness(t.senderDir, t.branch, 'hollow', 'folder')).toBe('empty');
+ // `git add -A` finds nothing to stage, so this pushes the base commit
+ // again: the folder is in exactly the same place afterwards.
+ t.git(t.senderDir, ['add', '-A']);
+ t.git(t.senderDir, ['push', 'origin', t.branch]);
+ expect(await computeShareFreshness(t.senderDir, t.branch, 'hollow', 'folder')).toBe('empty');
+ });
+});
+
+describe('computeShareFreshness — push-fixable folders stay absent', () => {
+ test('a folder holding one untracked doc is absent (a push puts it on origin)', async () => {
+ const t = newTriangle();
+ t.mkdirWorkingTree('drafts');
+ t.writeWorkingTree('drafts/x.md', 'unstaged\n');
+ expect(await computeShareFreshness(t.senderDir, t.branch, 'drafts', 'folder')).toBe('absent');
+ });
+
+ test('a folder committed but never pushed is absent', async () => {
+ const t = newTriangle();
+ t.writeWorkingTree('later/y.md', 'committed, not pushed\n');
+ t.git(t.senderDir, ['add', '--', 'later/y.md']);
+ t.git(t.senderDir, ['commit', '-m', 'add later/y.md (unpushed)']);
+ expect(await computeShareFreshness(t.senderDir, t.branch, 'later', 'folder')).toBe('absent');
+ });
+
+ test('a folder holding only .ok metadata is absent — that folder does push', async () => {
+ const t = newTriangle();
+ t.writeWorkingTree('meta/.ok/folder.yml', 'title: Meta\n');
+ expect(await computeShareFreshness(t.senderDir, t.branch, 'meta', 'folder')).toBe('absent');
+ });
+
+ test('a zero-byte doc is absent, then current across a sync — a file is trackable at any size', async () => {
+ const t = newTriangle();
+ t.writeWorkingTree('blank.md', '');
+ expect(await computeShareFreshness(t.senderDir, t.branch, 'blank.md', 'doc')).toBe('absent');
+ t.seedAndPush('blank.md', '');
+ expect(await computeShareFreshness(t.senderDir, t.branch, 'blank.md', 'doc')).toBe('current');
+ });
+});
+
describe('computeShareFreshness — content-root folder share (empty path)', () => {
test('a clean content root is current (root tree exists; pathspec falls back to ".")', async () => {
const t = newTriangle();
expect(await computeShareFreshness(t.senderDir, t.branch, '', 'folder')).toBe('current');
});
+ test('an empty subfolder does not make the content root empty', async () => {
+ const t = newTriangle();
+ t.mkdirWorkingTree('hollow');
+ expect(await computeShareFreshness(t.senderDir, t.branch, '', 'folder')).toBe('current');
+ });
+
test('an uncommitted edit anywhere under the content root is stale', async () => {
const t = newTriangle();
t.writeWorkingTree('README.md', '# base changed, not committed\n');
diff --git a/packages/server/src/share/freshness.ts b/packages/server/src/share/freshness.ts
index 743739aa0..2cda5c13a 100644
--- a/packages/server/src/share/freshness.ts
+++ b/packages/server/src/share/freshness.ts
@@ -2,7 +2,7 @@
* Send-side freshness probe for `POST /api/share/construct-url`: does the
* shared target match what origin has? Three local-only git reads against
* `refs/remotes/origin/<branch>` — never a fetch — run in parallel and combine
- * into `current` / `stale` / `absent`.
+ * into `current` / `stale` / `absent` / `empty`.
*
* simple-git's `raw` rejects on non-empty stderr, not on exit code (see
* `git-branch-info.ts`), so the exit-1 `diff --quiet` from the verified recipe
@@ -62,7 +62,14 @@ export async function computeShareFreshness(
git.raw(['status', '--porcelain', '--untracked-files=all', '--', pathspec]),
]);
- if (!present) return 'absent';
+ if (!present) {
+ // A folder absent from the ref with nothing to push is absent forever:
+ // git has no object for a folder holding zero blobs, so a push cannot
+ // put it on origin. Gated on `folder` because a doc is trackable at any
+ // size — a zero-byte file is absent now and current after a sync.
+ if (kind === 'folder' && trackedDiff.trim() === '' && untracked.trim() === '') return 'empty';
+ return 'absent';
+ }
// Tracked drift (committed-unpushed or uncommitted) surfaces in the diff;
// a brand-new untracked file beneath a shared folder surfaces only in
// status. Either makes the recipient's copy differ from what they'd see.
diff --git a/packages/server/src/share/git-fixture.test-helper.ts b/packages/server/src/share/git-fixture.test-helper.ts
index 301469f70..5ae5bc2fc 100644
--- a/packages/server/src/share/git-fixture.test-helper.ts
+++ b/packages/server/src/share/git-fixture.test-helper.ts
@@ -18,6 +18,8 @@
* folder) is stale
* - `commitWithoutPush` -> a seeded path edited + committed but not pushed
* is stale (origin keeps the old blob)
+ * - `mkdirWorkingTree` -> a folder holding zero blobs, which git cannot
+ * represent and no push can put on origin
* and the receive-side legs (`renameOnOrigin` / `renameFolderOnOrigin` /
* `deleteOnOrigin`) advance origin so a receiver clone observes the move.
* `deleteInReceiverWorkingTree` / `renameInReceiverWorkingTree` mutate the
@@ -49,6 +51,14 @@ export interface GitTriangle {
* seeded folder, is stale.
*/
writeWorkingTree(relPath: string, content: string): void;
+ /**
+ * Sender: create a directory (recursively) and nothing else. The only
+ * primitive that produces a folder holding zero blobs — every sibling writes
+ * a file, so a directory otherwise exists only as a by-product of one. Git
+ * has no object for such a folder, so it can never reach origin: the state
+ * where "not on origin" and "a push would fix it" come apart.
+ */
+ mkdirWorkingTree(relPath: string): void;
/** Sender: overwrite + commit a seeded path but do NOT push (origin keeps the old blob). */
commitWithoutPush(relPath: string, content: string): void;
/** Sender -> origin: `git mv` a file + commit + push (origin gains `newRel`, loses `oldRel`). */
@@ -159,6 +169,9 @@ export function createGitTriangle(opts: { branch?: string } = {}): GitTriangle {
writeWorkingTree(relPath, content) {
writeFile(senderDir, relPath, content);
},
+ mkdirWorkingTree(relPath) {
+ mkdirSync(join(senderDir, relPath), { recursive: true });
+ },
commitWithoutPush(relPath, content) {
writeFile(senderDir, relPath, content);
git(senderDir, ['add', '--', relPath]);
diff --git a/packages/server/src/share/git-fixture.test.ts b/packages/server/src/share/git-fixture.test.ts
index a838d30d5..b50209699 100644
--- a/packages/server/src/share/git-fixture.test.ts
+++ b/packages/server/src/share/git-fixture.test.ts
@@ -77,6 +77,21 @@ describe('createGitTriangle — send-side freshness drift cells', () => {
).not.toBe('');
});
+ test('a bare directory: absent from the ref with both drift probes silent -> empty', () => {
+ const t = newTriangle();
+ t.mkdirWorkingTree('hollow');
+ const ref = `origin/${t.branch}`;
+ // The cell that separates "not on origin yet" from "not representable in
+ // git": all three probes must be silent at once. A placeholder file added
+ // to this primitive would still miss the ref, but would light up status —
+ // and every `empty` verdict downstream would quietly become `absent`.
+ expect(gitExit(t.senderDir, ['cat-file', '-e', `${ref}:hollow`])).not.toBe(0);
+ expect(t.git(t.senderDir, ['diff', '--name-only', ref, '--', 'hollow'])).toBe('');
+ expect(
+ t.git(t.senderDir, ['status', '--porcelain', '--untracked-files=all', '--', 'hollow']),
+ ).toBe('');
+ });
+
test('a clean pushed symlink: unchanged -> current, and stored as a symlink (mode 120000)', () => {
const t = newTriangle();
t.seedSymlinkAndPush('link.md', 'target.md', '# target\n');