From 028f396e18cb23f889a399e2b1f129a33817d1b9 Mon Sep 17 00:00:00 2001 From: Madraka <8898640+Madraka@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:47:47 +0300 Subject: [PATCH] fix(core-ts): allow the collection index page at a permalink prefix set_collection_permalink refused /blog/{slug} while a page lived at /blog, the collection's listing page. Only pages strictly under a configured prefix conflict now, in checkPermalinks, its SQL guard (noPageUnder) and the reverse page-write check (checkPagePath, configuredPrefixFree "under"). RFC-0038 "Overlaps" and invariant 1 say so. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Madraka <8898640+Madraka@users.noreply.github.com> --- .changeset/collection-index-page.md | 5 ++++ apps/studio/test/collection-settings.test.tsx | 2 +- docs/rfcs/0038-collection-permalinks.md | 6 ++-- packages/api/src/testing-permalinks.ts | 11 ++++++- packages/core-ts/src/permalink-paths.ts | 30 ++++++++++--------- packages/core-ts/src/store/site-permalinks.ts | 17 ++++++----- packages/core-ts/src/testing-permalinks.ts | 27 +++++++++++++++-- packages/mcp-server/test/permalinks.test.ts | 11 ++++++- 8 files changed, 78 insertions(+), 31 deletions(-) create mode 100644 .changeset/collection-index-page.md diff --git a/.changeset/collection-index-page.md b/.changeset/collection-index-page.md new file mode 100644 index 00000000..8ab13add --- /dev/null +++ b/.changeset/collection-index-page.md @@ -0,0 +1,5 @@ +--- +"@cloudhal/core-ts": patch +--- + +A collection's template may now sit on top of a page at its prefix: `set_collection_permalink` with `posts` → `/blog/{slug}` no longer fails with `path_conflict` because a page lives at `/blog`. That page is the collection's index page (RFC-0038), so only pages strictly under the prefix conflict, in the template check, its SQL race guard (`noPageUnder`) and the reverse check on page writes. Studio's "Create listing page" now works for a collection with its own permalink too. diff --git a/apps/studio/test/collection-settings.test.tsx b/apps/studio/test/collection-settings.test.tsx index 0ab024f3..b951464e 100644 --- a/apps/studio/test/collection-settings.test.tsx +++ b/apps/studio/test/collection-settings.test.tsx @@ -116,7 +116,7 @@ describe("Collection settings", () => { status: 409, body: { error: "path_conflict", - message: 'collection "posts" at /about would cover page /about', + message: 'collection "posts" at /about would cover page /about/team', }, }); render(wrap()); diff --git a/docs/rfcs/0038-collection-permalinks.md b/docs/rfcs/0038-collection-permalinks.md index 659226be..e6488dd2 100644 --- a/docs/rfcs/0038-collection-permalinks.md +++ b/docs/rfcs/0038-collection-permalinks.md @@ -87,7 +87,7 @@ When tokens other than `{slug}` arrive, a prefix no longer describes the change. ### 4. Invariants -1. A template never overlaps another collection's template, a taxonomy archive's `basePath`, a page path, or a reserved path (`checkReservedPath`, `pathsOverlap`, and `entryAt` for the reverse check). A conflicting `updateSite` fails with `path_conflict`, the way Eleventy refuses duplicate URLs. +1. A template never overlaps another collection's template, a taxonomy archive's `basePath`, a page path under its prefix (the page at the prefix itself is the collection's index page, open question 3), or a reserved path (`checkReservedPath`, `pathsOverlap`, and `entryAt` for the reverse check). A conflicting `updateSite` fails with `path_conflict`, the way Eleventy refuses duplicate URLs. 2. The default is `//{slug}`: a site without `collections` renders exactly as before. 3. The collection key is never derived from the URL. Filters, templates, MCP tools and `ContentEntry.collection` keep using the key. 4. Changing a template never breaks a published URL: the old URL answers with a 301 to the new one. @@ -145,8 +145,8 @@ No new scopes: changing a template is a site update (`site:write`). In Studio a - **Redirects in the site's batch.** `SiteEngine.update` (`store/sites.ts`) compares `collectionPermalink(stored, key)` with `collectionPermalink(next, key)` for every key in either site (`changedPermalinks` in `permalinks.ts`). `store/site-permalinks.ts` plans one `RedirectPlan.move(oldPrefix, newPrefix, { match: "prefix", reason: "slug-change" })` per changed collection, as `updateTaxonomy` does for `archive.basePath`, and always moves (taxonomy archives do not check for published entries either). The plan's writes go into an `OpBatch` anchored on the site's new hash (`OpBatch.anchorOn(hashIs(site, hash))`), and its statements, `op_guards` assertions included, join the site CAS's batch. A failed assertion is treated as a missed CAS, so a stale or raced site write raises `ConflictError` and leaves no redirect. - **Every locale.** Redirects are per locale (RFC-0033) and entries in every locale share the v1 template, so the move is made for the default locale (untagged) and for each other site locale. `updateTaxonomy` moves only the default locale's redirects; that difference is deliberate here, since entries exist in every locale. - **Chains and loops** are `RedirectPlan`'s: moving again repoints the older redirects onto the new prefix, and moving back to the default drops the redirect that would point at itself. -- **Overlaps.** A changed template is checked against the effective prefixes of the other collections (configured ones, and the default `/` of collections with entries), every taxonomy archive base path (`pathsOverlap`), and, for a configured template, every page at or under its prefix, media URLs, `/search` and locale prefixes (`reserved_path`). A collection moved back to its default prefix keeps today's rule that a page under it wins. The site CAS carries race guards (`noArchiveOverlapping`, `noPageWithin` in `permalink-paths.ts`); a miss at the same rev re-runs the check for the `path_conflict` message. -- **The reverse.** Page writes (`checkPagePath`/`pageGuard` in `store/site-permalinks.ts`) and taxonomy writes (`#checkTaxonomy`/`#archiveGuard`) refuse a path in a configured prefix; their SQL guards read the site row's `collections` (`configuredPrefixFree`). +- **Overlaps.** A changed template is checked against the effective prefixes of the other collections (configured ones, and the default `/` of collections with entries), every taxonomy archive base path (`pathsOverlap`), and, for a configured template, every page under its prefix (a page at the prefix itself is the collection's index page, open question 3, and stays), media URLs, `/search` and locale prefixes (`reserved_path`). A collection moved back to its default prefix keeps today's rule that a page under it wins. The site CAS carries race guards (`noArchiveOverlapping`, `noPageUnder` in `permalink-paths.ts`); a miss at the same rev re-runs the check for the `path_conflict` message. +- **The reverse.** Page writes (`checkPagePath`/`pageGuard` in `store/site-permalinks.ts`) and taxonomy writes (`#checkTaxonomy`/`#archiveGuard`) refuse a path under a configured prefix (pages may sit at it); their SQL guards read the site row's `collections` (`configuredPrefixFree`). - **Search.** `planSearch` rewrites every entry row when the live site node's templates differ from the indexed snapshot's, so hrefs follow the move on the next publish. - **Rollback** restores the template with the site node; redirects stay, as invariant 5 says. diff --git a/packages/api/src/testing-permalinks.ts b/packages/api/src/testing-permalinks.ts index e85e683e..fdbb5978 100644 --- a/packages/api/src/testing-permalinks.ts +++ b/packages/api/src/testing-permalinks.ts @@ -68,6 +68,15 @@ export function describePermalinkApi(label: string, factory: ApiStoreFactory): v }); it("refuses an overlap with a page (409 path_conflict) and a reserved prefix (409 reserved_path)", async () => { + // A page at the prefix (/about) would be the collection's index page; one under it is not. + await store.createPage((await store.getSite(siteId)) as Site, { + siteId, + path: "/about/team", + title: "Team", + locale: "en", + status: "draft", + sections: [], + }); const current = await site(); const clash = await putSite({ ...current, @@ -75,7 +84,7 @@ export function describePermalinkApi(label: string, factory: ApiStoreFactory): v }); expect(clash.status).toBe(409); expect(clash.body.error).toBe("path_conflict"); - expect(clash.body.message).toContain("/about"); + expect(clash.body.message).toContain("/about/team"); const archive = await putSite({ ...current, diff --git a/packages/core-ts/src/permalink-paths.ts b/packages/core-ts/src/permalink-paths.ts index 899ee124..338c0d2f 100644 --- a/packages/core-ts/src/permalink-paths.ts +++ b/packages/core-ts/src/permalink-paths.ts @@ -11,9 +11,9 @@ export function pathsOverlap(a: string, b: string): boolean { return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`); } -/** `path` equals `base` or lies under it. */ -export function pathWithin(path: string, base: string): boolean { - return path === base || path.startsWith(`${base}/`); +/** `path` lies strictly under `base` (`/blog/x` under `/blog`, but not `/blog` itself). */ +export function pathUnder(path: string, base: string): boolean { + return path.startsWith(`${base}/`); } export interface CollectionPrefix { @@ -51,29 +51,31 @@ const PERMALINK = "json_extract(c.value, '$.permalink')"; const PREFIX = `substr(${PERMALINK}, 1, length(${PERMALINK}) - 7)`; /** - * Holds while no configured collection prefix in the site row's `collections` contains `path` - * (`within`: a page path) or overlaps it either way (`overlap`: an archive base path). + * Holds while no configured collection prefix in the site row's `collections` has `path` strictly + * under it (`under`: a page path; the page at the prefix itself is the collection's index page, + * RFC-0038) or overlaps it either way (`overlap`: an archive base path). */ export function configuredPrefixFree( siteId: string, path: string, - mode: "within" | "overlap", + mode: "under" | "overlap", ): Cond { - const within = `${PREFIX} = ? OR substr(?, 1, length(${PREFIX}) + 1) = ${PREFIX} || '/'`; - const cond = mode === "within" ? within : `${within} OR substr(${PREFIX}, 1, ?) = ?`; - const extra = mode === "within" ? [] : [path.length + 1, `${path}/`]; + const under = `substr(?, 1, length(${PREFIX}) + 1) = ${PREFIX} || '/'`; + const cond = + mode === "under" ? under : `${PREFIX} = ? OR ${under} OR substr(${PREFIX}, 1, ?) = ?`; + const params = mode === "under" ? [path] : [path, path, path.length + 1, `${path}/`]; return { sql: `NOT EXISTS (SELECT 1 FROM nodes s, json_each(s.body, '$.collections') c WHERE s.id = ? AND s.kind = 'site' AND ${PERMALINK} IS NOT NULL AND (${cond}))`, - params: [siteId, path, path, ...extra], + params: [siteId, ...params], }; } -/** Holds while no page of the site sits at `base` or under it. */ -export function noPageWithin(siteId: string, base: string): Cond { +/** Holds while no page of the site sits strictly under `base` (a page at `base` may stay). */ +export function noPageUnder(siteId: string, base: string): Cond { const path = "json_extract(body, '$.path')"; return { - sql: `NOT EXISTS (SELECT 1 FROM nodes WHERE site_id = ? AND kind = 'page' AND (${path} = ? OR substr(${path}, 1, ?) = ?))`, - params: [siteId, base, base.length + 1, `${base}/`], + sql: `NOT EXISTS (SELECT 1 FROM nodes WHERE site_id = ? AND kind = 'page' AND substr(${path}, 1, ?) = ?)`, + params: [siteId, base.length + 1, `${base}/`], }; } diff --git a/packages/core-ts/src/store/site-permalinks.ts b/packages/core-ts/src/store/site-permalinks.ts index 8b6995ca..27b85303 100644 --- a/packages/core-ts/src/store/site-permalinks.ts +++ b/packages/core-ts/src/store/site-permalinks.ts @@ -13,9 +13,9 @@ import { collectionPrefixes, configuredPrefixFree, noArchiveOverlapping, - noPageWithin, + noPageUnder, pathsOverlap, - pathWithin, + pathUnder, } from "../permalink-paths.ts"; import { changedPermalinks, type PermalinkChange } from "../permalinks.ts"; import { RedirectPlan, redirectLocale } from "../redirects.ts"; @@ -64,7 +64,7 @@ export async function planPermalinks( guard: and( ...changes.flatMap((c) => [ noArchiveOverlapping(next.id, c.to), - ...(c.configured ? [noPageWithin(next.id, c.to)] : []), + ...(c.configured ? [noPageUnder(next.id, c.to)] : []), ]), ), async statements(hash) { @@ -103,9 +103,10 @@ async function checkPermalinks( for (const tax of taxonomies) if (pathsOverlap(tax.archive.basePath, c.to)) conflict(`${at} collides with the ${tax.key} archive ${tax.archive.basePath}`); - // A default `/` keeps today's rule: a page there wins over an entry. + // A default `/` keeps today's rule: a page there wins over an entry. A page at + // the prefix itself is the collection's index page (RFC-0038 §"Out of scope" 3). if (!c.configured) continue; - const page = pages.find((p) => pathWithin(p.path, c.to)); + const page = pages.find((p) => pathUnder(p.path, c.to)); if (page) conflict(`${at} would cover page ${page.path}`, { pageId: page.id }); } } @@ -126,12 +127,12 @@ function conflict(message: string, details?: Record): never { throw new InvariantError("path_conflict", message, details); } -/** The reverse of invariant 1 for page writes: no page at or under a configured prefix. */ +/** The reverse of invariant 1 for page writes: no page under a configured prefix, only at it. */ export async function checkPagePath(ctx: StoreContext, page: Page, site?: Site): Promise { await ctx.tax.checkPagePath(page); const s = site ?? (await ctx.graph.getSite(page.siteId)); for (const { collection, prefix } of collectionPrefixes(s, [])) - if (pathWithin(page.path, prefix)) + if (pathUnder(page.path, prefix)) conflict(`page path ${page.path} lies in collection "${collection}" at ${prefix}`, { collection, }); @@ -141,6 +142,6 @@ export async function checkPagePath(ctx: StoreContext, page: Page, site?: Site): export function pageGuard(ctx: StoreContext, page: Page): Cond { return and( ctx.tax.pageGuard(page), - configuredPrefixFree(page.siteId, page.path, "within"), + configuredPrefixFree(page.siteId, page.path, "under"), ) as Cond; } diff --git a/packages/core-ts/src/testing-permalinks.ts b/packages/core-ts/src/testing-permalinks.ts index 4f37246c..9cecd35c 100644 --- a/packages/core-ts/src/testing-permalinks.ts +++ b/packages/core-ts/src/testing-permalinks.ts @@ -109,7 +109,7 @@ export function permalinksSuite(ctx: SuiteContext): void { expect(dry).toMatchObject({ rev: s.rev + 1, collections: next.collections }); expect((await fresh(site)).rev).toBe(s.rev); expect(await redirects(site)).toEqual([]); - const clash = { ...s, collections: { posts: { permalink: "/about/{slug}" } } }; + const clash = { ...s, collections: { posts: { permalink: "/tag/{slug}" } } }; expect(await code(ctx.store().updateSite(clash, { dryRun: true }))).toBe("path_conflict"); }); @@ -157,7 +157,6 @@ export function permalinksSuite(ctx: SuiteContext): void { tags: [], author: person, } as never); - expect(await code(move(site, "/about/{slug}"))).toBe("path_conflict"); expect(await code(move(site, "/work/{slug}"))).toBe("path_conflict"); expect(await code(move(site, "/category/{slug}"))).toBe("path_conflict"); expect(await code(move(site, "/tag/posts/{slug}"))).toBe("path_conflict"); @@ -188,7 +187,6 @@ export function permalinksSuite(ctx: SuiteContext): void { ({ site } = await page("/posts/landing")); // A page in the way is refused when the template moves there, not afterwards. site = await move(site, "/blog/{slug}"); - expect(await code(page("/blog"))).toBe("path_conflict"); expect(await code(page("/blog/about"))).toBe("path_conflict"); const about = (await store.listPages(site.id)).find((p) => p.path === "/about"); expect(about).toBeDefined(); @@ -213,6 +211,29 @@ export function permalinksSuite(ctx: SuiteContext): void { expect((await page("/posts/new")).page.path).toBe("/posts/new"); }); + it("§4.1: the page at a template's prefix is the collection's index page, not a conflict", async () => { + let site = await setup(); + const store = ctx.store(); + const page = (path: string) => + store.createPage(site, { + siteId: site.id, + path, + title: "P", + locale: "en", + status: "draft", + sections: [], + }); + // The listing page exists first; entries then move under it. Both writes run their SQL race + // guards (`noPageUnder`, `configuredPrefixFree`) in the batch, so those pass too. + ({ site } = await page("/blog")); + site = await move(site, "/blog/{slug}"); + expect(site.collections?.posts?.permalink).toBe("/blog/{slug}"); + // …or the template is there first and the listing page comes after. + site = await move(site, "/notes/{slug}"); + ({ site } = await page("/notes")); + expect((await store.listPages(site.id)).map((p) => p.path)).toContain("/notes"); + }); + it("§3: a stale site rev raises ConflictError and writes no redirect", async () => { const site = await setup(); const stale = await fresh(site); diff --git a/packages/mcp-server/test/permalinks.test.ts b/packages/mcp-server/test/permalinks.test.ts index 11e90033..9c86d83f 100644 --- a/packages/mcp-server/test/permalinks.test.ts +++ b/packages/mcp-server/test/permalinks.test.ts @@ -127,9 +127,18 @@ describe("set_collection_permalink (RFC-0038 §5)", () => { it("an overlap or a no-op is refused before a person is asked", async () => { const run = direct(w, "edits"); + // The page at /about would be the collection's index page; one under it is in the way. + await w.store.createPage(w.site, { + siteId: w.site.id, + path: "/about/team", + title: "Team", + locale: w.site.defaultLocale, + status: "draft", + sections: [], + }); await expect(run({ permalink: "/about/{slug}" })).rejects.toMatchObject({ code: "path_conflict", - message: expect.stringContaining("would cover page /about"), + message: expect.stringContaining("would cover page /about/team"), }); await expect(run({ permalink: "/tag/{slug}" })).rejects.toMatchObject({ code: "path_conflict",