Skip to content

feat(core): RelationRepository (content-references data layer) - #1444

Merged
ascorbic merged 16 commits into
emdash-cms:mainfrom
MA2153:feat/content-references-repository
Jun 12, 2026
Merged

ascorbic merged 16 commits into
emdash-cms:mainfrom
MA2153:feat/content-references-repository

Conversation

@MA2153

@MA2153 MA2153 commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Adds RelationRepository, the application data-access layer over the content-references database schema that landed in #1367 (migration 043). It is the next incremental slice in the content-references line of work — schema-only previously, now a typed, tested repository on top.

The class deliberately mirrors TaxonomyRepository and owns both halves of the feature, exactly as taxonomy owns terms + content_taxonomies:

  • Relation definitions (_emdash_relations, row-per-locale, translation_group): create (with translationOf that inherits structural fields and joins the group), findById, findByName, findTranslations, list, findForCollection, update (labels only), delete (purges edges when the last translation of a group is removed).
  • Directed reference edges (_emdash_content_references, locale-agnostic, keyed by translation_group): addReference (append/dedupe), removeReference, getChildren (forward), getParents (backlink), setChildren (replace + positional sort_order), clearReferencesForGroup (entry-deletion cleanup primitive), and countChildren / countParents / countChildrenForParents (batched at SQL_BATCH_SIZE).

Scope (deliberately thin): this is a data layer only. There is no Zod, no request validation, and no API/route — those are the next slice. The repository trusts its typed inputs; collection-agreement and relation-existence validation belong to the future handler/API layer. clearReferencesForGroup is provided as the cleanup primitive, but wiring it into the content-delete path is also deferred to that slice.

Backwards-compatible and additive — a new exported class only; no existing behavior changes.

Part of the content-references effort (Discussion #386; schema groundwork in #1367).

Type of change

Checklist

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Claude Opus 4.8 (implementation via Claude Code subagents; per-task spec + code-quality review and a final holistic review)

Screenshots / test output

Test Files  1 passed (1)
     Tests  25 passed (25)

MA2153 and others added 15 commits June 12, 2026 17:55
…ow test

Address Task 1 code review: explain why a missing translationOf source
throws (translation_group is NOT NULL, no silent fallback), sharpen the
create() JSDoc, and assert the specific error message in the test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address Task 2 code review: make the list() locale-filter test
non-vacuous by adding a 'fr' row and asserting it is excluded, and
assert findForCollection results in returned order so the test guards
the ORDER BY. Clarify that findByName returns a single row.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address Task 3 code review: normalize the update() JSDoc block style,
rename the update test to match what it asserts (it does not check the
updated_at bump), and assert the anchor row survives a non-last-translation
delete (not just its edges).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address Task 4 code review: document that the default-append MAX→INSERT
in addReference is non-atomic (concurrent appends can collide and drop
one via onConflict), and cover removeReference of a nonexistent edge.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address Task 5 code review: collapse duplicate childGroups
first-occurrence-wins rather than relying on the insert's onConflict to
silently drop them, document the non-atomic delete+insert, and cover the
duplicate-input and unknown-relation no-op contracts.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address Task 6 code review: order the chunks value import before the
type import (matching seo.ts), use ?? 0 consistently in the batch
counter, replace the opaque "invariant 4" comment with a plain
explanation, and assert the unknown-relation zero-count path.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Per-task formatting was skipped during implementation (the full
pnpm format pass was OOM-ing this environment); apply oxfmt now.
Formatting-only — no behavior change, 24/24 tests still pass.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address final branch review: lock in that clearReferencesForGroup
removes a content group's edges across every relation (not just one),
and document that setChildren's onConflict is defensive, not a
concurrency guarantee.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@changeset-bot

changeset-bot Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 6051e2b

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@github-actions github-actions Bot added review/needs-review No maintainer or bot review yet area/core size/XL labels Jun 12, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Scope check

This PR changes 844 lines across 4 files. Large PRs are harder to review and more likely to be closed without review.

If this scope is intentional, no action needed. A maintainer will review it. If not, please consider splitting this into smaller PRs.

See CONTRIBUTING.md for contribution guidelines.

@pkg-pr-new

pkg-pr-new Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

npm i https://pkg.pr.new/@emdash-cms/admin@1444

@emdash-cms/auth

npm i https://pkg.pr.new/@emdash-cms/auth@1444

@emdash-cms/auth-atproto

npm i https://pkg.pr.new/@emdash-cms/auth-atproto@1444

@emdash-cms/blocks

npm i https://pkg.pr.new/@emdash-cms/blocks@1444

@emdash-cms/cloudflare

npm i https://pkg.pr.new/@emdash-cms/cloudflare@1444

@emdash-cms/contentful-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/contentful-to-portable-text@1444

emdash

npm i https://pkg.pr.new/emdash@1444

create-emdash

npm i https://pkg.pr.new/create-emdash@1444

@emdash-cms/gutenberg-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/gutenberg-to-portable-text@1444

@emdash-cms/plugin-cli

npm i https://pkg.pr.new/@emdash-cms/plugin-cli@1444

@emdash-cms/plugin-types

npm i https://pkg.pr.new/@emdash-cms/plugin-types@1444

@emdash-cms/registry-client

npm i https://pkg.pr.new/@emdash-cms/registry-client@1444

@emdash-cms/registry-lexicons

npm i https://pkg.pr.new/@emdash-cms/registry-lexicons@1444

@emdash-cms/sandbox-workerd

npm i https://pkg.pr.new/@emdash-cms/sandbox-workerd@1444

@emdash-cms/x402

npm i https://pkg.pr.new/@emdash-cms/x402@1444

@emdash-cms/plugin-ai-moderation

npm i https://pkg.pr.new/@emdash-cms/plugin-ai-moderation@1444

@emdash-cms/plugin-atproto

npm i https://pkg.pr.new/@emdash-cms/plugin-atproto@1444

@emdash-cms/plugin-audit-log

npm i https://pkg.pr.new/@emdash-cms/plugin-audit-log@1444

@emdash-cms/plugin-color

npm i https://pkg.pr.new/@emdash-cms/plugin-color@1444

@emdash-cms/plugin-embeds

npm i https://pkg.pr.new/@emdash-cms/plugin-embeds@1444

@emdash-cms/plugin-field-kit

npm i https://pkg.pr.new/@emdash-cms/plugin-field-kit@1444

@emdash-cms/plugin-forms

npm i https://pkg.pr.new/@emdash-cms/plugin-forms@1444

@emdash-cms/plugin-webhook-notifier

npm i https://pkg.pr.new/@emdash-cms/plugin-webhook-notifier@1444

commit: 6051e2b

"emdash": minor
---

Add `RelationRepository`: the application data-access layer over the content-references schema (migration `043`). Manages relation definitions (`_emdash_relations`, row-per-locale) and directed, locale-agnostic reference edges (`_emdash_content_references`). Additive — typed inputs, no API/validation surface yet (Zod schemas and routes arrive in a following slice). Provides `clearReferencesForGroup` as the entry-deletion cleanup primitive; wiring it into the content-delete path is deferred.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's nothing user-facing in this, is there? It's not changing behaviour in any way? I'd not include a changeset in that case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair.

@github-actions github-actions Bot added review/needs-rereview New commits since the last review and removed review/needs-review No maintainer or bot review yet labels Jun 12, 2026

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR introduces RelationRepository, the data-access layer over the content-references schema from migration 043. The implementation is clean, well-tested, and closely mirrors TaxonomyRepository — which is the correct precedent for this feature.

Approach judgment: The change is the right incremental slice. It stays within its stated scope (data layer only, no routes/validation), follows established repository patterns, links to the approved Discussion, and includes a changeset. The decision to fail loudly on a bad translationOf (rather than silently mint an orphan row) is safer than the analogous TaxonomyRepository behavior and is well justified by the non-nullable translation_group constraint.

What I checked:

  • SQL safety: no raw interpolation, proper Kysely parameterization throughout.
  • Locale handling: _emdash_relations queries filter by locale where appropriate; _emdash_content_references is locale-agnostic by design, matching the schema intent.
  • Index coverage: all queried columns in the new tables have appropriate indexes from migration 043.
  • Consistency with TaxonomyRepository: edge operations (add/remove/set/clear), translation group inheritance, and batch query chunking all follow the same patterns.
  • Test coverage: 25 tests, dialect-parametric via describeEachDialect, covering CRUD, translations, edge cases (unknown relation no-op, self-reference, duplicate collapse, empty setChildren, batch chunking), and the application-layer cascade on delete.
  • Changeset present and correctly describes the scope.

Headline conclusion: No issues found. The code is solid and ready to merge.

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clean, additive data-layer slice.

Approach judgment: This is the right next step for the content-references feature. A dedicated RelationRepository that mirrors TaxonomyRepository (owning both definitions and the edge junction) is the idiomatic EmDash pattern. Keeping Zod, routes, and delete-path wiring out of scope is correct — this is a repository-only PR and the boundaries are well documented.

What I checked:

  • SQL safety: No raw interpolation; Kysely builder used throughout.
  • Locale filtering: All queries against _emdash_relations that make sense (findByName, list, findForCollection) support optional locale. findById is a PK lookup and correctly skips locale.
  • Schema alignment: The code respects the migration 043 schema (translation_group NOT NULL on _emdash_relations; sort_order generated default on _emdash_content_references).
  • Translation-group handling: create with translationOf inherits structural fields and joins the group, blowing up on a missing source rather than silently minting an orphan (appropriate because the column is NOT NULL here, unlike taxonomies). update restricts mutations to localized labels only, matching the stated scope.
  • Edge operations: addReference, removeReference, getChildren, getParents, setChildren, clearReferencesForGroup, and the count methods all behave correctly. setChildren collapses duplicates and documents the non-atomic delete-then-insert trade-off.
  • Cascade behavior: delete purges edges only when the last translation of a group is removed, just like TaxonomyRepository.delete.
  • Batching: countChildrenForParents chunks at SQL_BATCH_SIZE for D1 bind-parameter limits.
  • Tests: 25 dialect-agnostic tests covering CRUD, translations, edge CRUD, duplicate handling, self-references, unknown-relation no-ops, empty-list clearing, and batching.
  • Changeset: Minor changeset present and well-described.

I did not find any logic bugs, regressions, security issues, or AGENTS.md convention violations. The implementation is sound and ready for the next slice (Zod schemas + routes).

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a solid, well-scoped data-layer slice. The PR mirrors TaxonomyRepository faithfully, uses Kysely safely (no raw interpolation), keeps locale filtering consistent, and has thorough test coverage (25 tests, including cross-dialect via describeEachDialect). The changeset is present, barrel-file exports follow convention, and the scope boundaries (no API/validation layer yet) are reasonable.

I checked:

  • SQL safety and parameterization
  • Schema alignment with migration 043
  • Pattern consistency against TaxonomyRepository
  • Edge cases: missing ids, unknown relations, empty arrays, duplicate children, self-reference
  • AGENTS.md conventions: changeset present, no UI strings to localize, no new migrations requiring index discipline, no content-table queries requiring locale filters

The implementation is functionally correct. I have one non-blocking suggestion about a misleading concurrency comment in addReference that mischaracterizes the race condition.

Headline: clean, additive, and ready to land after the doc fix.

* `sortOrder` defaults to append: max(sort_order)+1 within (relation, parent).
*
* The default-append MAX→INSERT is not atomic: concurrent appends without an
* explicit `sortOrder` may both read the same max and collide on sort_order,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[suggestion] The JSDoc says concurrent appends without an explicit sortOrder may "collide on sort_order, and onConflict silently drops the loser." This is misleading: the unique constraint on _emdash_content_references is (relation_group, parent_group, child_group) — it does not include sort_order. Two concurrent appends of different children would both succeed with the same sort_order value; there is no conflict for onConflict doNothing() to resolve. The onConflict only deduplicates identical (relation, parent, child) edges.

The comment should clarify that the race produces duplicate sort_order values (not insert conflicts) and that getChildren relies on id as the final tie-breaker. Suggested rephrase:

Suggested change
* explicit `sortOrder` may both read the same max and collide on sort_order,
* The default-append MAX→INSERT is not atomic: concurrent appends without an
* explicit `sortOrder` may both read the same max and receive duplicate
* sort_order values. Since the unique constraint is on
* (relation_group, parent_group, child_group), different children both insert
* successfully; only identical edges are dropped by onConflict. Callers
* needing strict ordering under concurrency should pass `sortOrder`
* explicitly (or serialize).

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR adds RelationRepository, a well-scoped, incremental data layer over the content-references schema from migration 043. The approach is sound: it mirrors TaxonomyRepository closely (row-per-locale definitions + locale-agnostic edges keyed by translation_group), which is the right architectural precedent for this feature. It is purely additive — a new exported class with no changes to existing behavior — and the author correctly defers validation, Zod schemas, and route wiring to the next slice.

I checked the implementation against TaxonomyRepository for consistency, reviewed the diff against origin/main, traced the migration schema, and verified AGENTS.md conventions (SQL safety via Kysely, no raw interpolation; no admin UI strings to localize; changeset present; scope discipline maintained).

The implementation is clean:

  • All Kysely queries are properly parameterized.
  • translation_group resolution and edge keying correctly follow the group-linking model.
  • delete handles the last-translation cascade exactly like TaxonomyRepository.delete.
  • countChildrenForParents chunks at SQL_BATCH_SIZE for D1 compatibility.
  • setChildren deduplicates before insert and documents its non-atomic delete-then-insert behavior.
  • Tests cover the 25 behavior paths they claim to, including edge cases (unknown relation no-ops, self-references, duplicate collapse, cross-relation cleanup, and batching past the chunk size).

I found no logic bugs, regressions, security issues, or convention violations. LGTM.

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clean, well-scoped data-layer slice that follows existing patterns and conventions.

Approach — This is the right next step for the content-references line of work. The repository mirrors TaxonomyRepository appropriately (owning both the definition table and the edge junction), and the decision to defer validation, routes, and delete-path wiring to the next slice is sound. The design is additive, backwards-compatible, and consistent with EmDash's architecture.

What I checked:

  • Read the full diff, the new RelationRepository, its tests, the barrel export, and the changeset.
  • Compared against TaxonomyRepository and migration 043 to verify pattern fidelity.
  • Checked AGENTS.md conventions: no raw SQL interpolation (Kysely used correctly), indexes present in the migration, changeset included, no UI strings to localize, no routes to authorize.
  • Traced edge cases: null/empty inputs, concurrent-append race (documented), unknown-relation no-ops, duplicate collapse in setChildren, last-translation cascade in delete, batch chunking at SQL_BATCH_SIZE.

Headline conclusion: The implementation is correct and well-tested. No bugs, regressions, or convention violations found. The 25 integration tests cover the surface area comprehensively. LGTM.

@MA2153

MA2153 commented Jun 12, 2026

Copy link
Copy Markdown
Contributor Author

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clean, focused data-layer slice that follows established patterns and ships with solid test coverage.

Approach judgment: This is the right next step for the content-references effort. Restricting the PR to the repository (no routes, no Zod) keeps the diff reviewable and the architecture consistent with how TaxonomyRepository owns terms + content_taxonomies. The parity with taxonomy is explicit and well documented.

What I checked:

  • SQL safety: 100 % Kysely query builder, no sql.raw interpolation, identifiers are hard-coded.
  • Schema alignment: types in database/types.ts match migration 043 (_emdash_relations, _emdash_content_references).
  • Indexes: migration creates covering indexes for all query paths (locale, translation_group, parent/child collection, and the composite unique on (translation_group, locale)).
  • Locale discipline: every read method accepts an optional locale filter and falls back deterministically; edges are keyed by translation_group so they are locale-agnostic, matching the taxonomy pivot pattern.
  • Conventions: changeset present, barrel export added, SQL_BATCH_SIZE chunking used for the batched count query.
  • Tests: 25 integration tests covering create (anchor + translation), read variants, localized update, delete cascade, edge CRUD, deduping, positional sort_order, self-reference, unknown-relation no-ops, and batch chunking.

No findings. The acknowledged non-atomicity in setChildren and the append race in addReference are documented, acceptable for this layer, and match existing repository behavior. clearReferencesForGroup is correctly exposed as an unconditional primitive; the caller in the future handler/API slice will be responsible for deciding when to invoke it (e.g., only after the last content translation is removed).

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review summary

Approach: Sound. This is the right next slice for the content-references effort — a typed, tested data layer over the schema from migration 043, deliberately mirroring TaxonomyRepository (row-per-locale definitions + translation_group-keyed edges). Keeping Zod, routes, and handler wiring out of this PR is the correct scope discipline.

What I checked:

  • SQL safety: Every query uses Kysely’s builder/tagged templates; no sql.raw() or string interpolation with variables.
  • AGENTS.md conventions: No admin UI strings / Lingui / RTL concerns (pure data layer). Locale filters are present on _emdash_relations queries where they belong; _emdash_content_references is locale-agnostic by design (edges keyed by translation_group), so omitting locale there is correct.
  • Schema alignment: Columns, constraints, and indexes match migration 043 exactly.
  • Siblings: Compared against TaxonomyRepository. The patterns (e.g. findBySlug → findByName, setTermsForEntry → setChildren, countEntriesForTerms → countChildrenForParents) are applied consistently. The minor divergence of throwing on a missing translationOf source (rather than silently minting a new group) is intentional and well documented.
  • Tests: 25 dialect-agnostic tests via describeEachDialect, covering creation, translation inheritance, CRUD, edge append/replace/dedupe, backlink traversal, self-references, batch counts across SQL_BATCH_SIZE, and application-layer cascade on last-translation deletion.
  • Changeset: The PR claims one was added; this is unverified offline but trusted from the checklist.

Headline conclusion: The implementation is clean, consistent with existing repositories, and introduces no regressions or AGENTS.md violations. I found no issues worth anchoring to a line.

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approach: Sound. This remains the right next slice for the content-references effort — a typed, tested data layer over the schema from migration 043, deliberately mirroring TaxonomyRepository. Keeping Zod, routes, and handler wiring out of scope is correct discipline.

What I checked:

  • Full diff of the three changed files (barrel export, repository, tests).
  • SQL safety: every query uses Kysely’s builder; no sql.raw() or string interpolation with variables.
  • Schema alignment: columns and table names match the documented migration 043 schema.
  • Edge cases: self-references, duplicate deduping, empty childGroups, unknown relation no-ops, missing translationOf throws, batch counts across SQL_BATCH_SIZE.
  • Concurrency/correctness: the documented non-atomicity of addReference append and setChildren delete-then-insert is acknowledged in comments; the application-layer cascade in delete mirrors TaxonomyRepository.
  • Locale discipline: _emdash_relations queries are correctly filtered by locale; _emdash_content_references is locale-agnostic by design (edges keyed by translation_group).
  • AGENTS.md conventions: no admin UI / Lingui / RTL concerns (pure data layer); .js extensions on internal imports; type-only exports in barrel file.

One blocking convention issue: The changeset that was added in 06a07ae1 was deleted in 6051e2b2, so the branch currently ships no changeset for a published-package feature. This needs to be fixed before merge.

Headline conclusion: The implementation is clean and introduces no regressions. Apart from the missing changeset, I found no line-level bugs or AGENTS.md violations.

export type { CreateBylineInput, UpdateBylineInput, ContentBylineInput } from "./byline.js";
export type * from "./types.js";
export { EmDashValidationError, InvalidCursorError, encodeCursor, decodeCursor } from "./types.js";
export { RelationRepository } from "./relation.js";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[needs fixing] The PR checklist claims a changeset was added, but the latest commit (6051e2b2) deletes .changeset/content-references-repository.md. As a result, HEAD contains no changeset for this new feature even though it exports a new class from a published package (packages/core).

AGENTS.md and CONTRIBUTING.md both require a changeset when a published package changes. The schema groundwork (content-references-schema.md) only covers migration 043; the repository slice is a separate additive feature that should carry its own minor changeset.

Fix: Restore the changeset (or add a fresh one) so release automation can version-bump the package correctly.

Suggested change
export { RelationRepository } from "./relation.js";
# packages/core/.changeset/content-references-repository.md
---
"@emdash/core": minor
---
feat(core): add RelationRepository for content-references data layer

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approach: Sound. This is the right next slice for the content-references effort — a typed, tested data layer over the schema from migration 043, deliberately mirroring TaxonomyRepository (row-per-locale definitions + translation_group-keyed edges). Keeping Zod, routes, and handler wiring out of this PR is the correct scope discipline.

What I checked:

  • SQL safety: Every query uses Kysely’s builder/tagged templates; no sql.raw() or string interpolation with variables.
  • AGENTS.md conventions: No admin UI strings / Lingui / RTL concerns (pure data layer). Locale filters are present on _emdash_relations queries where they belong; _emdash_content_references is locale-agnostic by design (edges keyed by translation_group), so omitting locale there is correct. Barrel file separates value and type exports correctly.
  • Schema alignment: Columns, constraints, and indexes match migration 043 exactly.
  • Siblings: Compared against TaxonomyRepository. The patterns (e.g. findBySlug → findByName, setTermsForEntry → setChildren, countEntriesForTerms → countChildrenForParents) are applied consistently. The intentional divergence of throwing on a missing translationOf source (rather than silently minting a new group) is well documented.
  • Tests: 25 dialect-agnostic tests via describeEachDialect, covering creation, translation inheritance, CRUD, edge append/replace/dedupe, backlink traversal, self-references, batch counts across SQL_BATCH_SIZE, and application-layer cascade on last-translation deletion.
  • Changeset: Verified against the diff. No changeset file is present in this PR, despite the checklist claiming one was added. The existing content-references-schema.md describes the schema PR (#1367), not this repository addition which exports new public API (RelationRepository and its types).

Headline conclusion: The implementation is clean, consistent with existing repositories, and introduces no regressions or AGENTS.md violations in the source code. The only confirmed gap is the missing changeset for this published-package change.

@@ -42,3 +42,10 @@ export { BylineRepository } from "./byline.js";
export type { CreateBylineInput, UpdateBylineInput, ContentBylineInput } from "./byline.js";
export type * from "./types.js";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[needs fixing] This PR adds a new exported public class (RelationRepository) and four new exported types from a published package, but no changeset file is included in the diff. The checklist claims a changeset was added and labeled minor, yet git diff --name-only shows only source code files. The existing .changeset/content-references-schema.md describes the schema groundwork from #1367, not this repository slice. AGENTS.md requires a changeset for published package changes — please add a new changeset (or update the existing one) that describes the addition of RelationRepository.

.where("relation_group", "=", relationGroup)
.where("parent_group", "=", parentGroup)
.executeTakeFirst();
order = max?.max === null || max?.max === undefined ? 0 : Number(max.max) + 1;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[suggestion] The sibling-count check and the edge-purge are not atomic. Under concurrent deletion of two translations from the same group, both threads can observe siblings.length > 0 before either delete commits, leaving edges orphaned when the last translation row is removed. This mirrors the same pattern in TaxonomyRepository.delete, so it is not a new regression, but wrapping the read-check-delete in a transaction (or using an atomic DELETE ... WHERE NOT EXISTS ( ... ) style cleanup) would harden it.

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of the content-references repository slice.

Approach: Still sound. The RelationRepository is the right next layer over migration 043, mirroring TaxonomyRepository correctly. The new cross-relation clearReferencesForGroup test (cdde3531) is a good addition.

What changed since prior approval:

  • Added test coverage for cross-relation purge in clearReferencesForGroup.
  • Deleted .changeset/content-references-repository.md in the final commit (6051e2b2).

Headline conclusion: The implementation remains clean and consistent, but the changeset deletion is a real AGENTS.md violation that needs to be fixed before merge.

Details:

  • Changeset: The PR checklist claims a changeset was added, and commit 06a07ae1 did add one. However, the latest commit 6051e2b2 deletes it. This PR exports a new RelationRepository class (plus its types) from the published emdash package — that is a user-facing API addition that requires a minor changeset. The schema changeset (content-references-schema.md) belongs to the earlier migration PR (#1367) and does not cover this repository layer. The deletion should be reverted.
  • Code: No new issues. SQL is Kysely-safe, locale filters are in the right places, tests cover the added behavior, and the repository stays consistent with TaxonomyRepository patterns.
  • No other AGENTS.md violations found.

* collection-agreement / relation-existence invariants in the handler. The repo
* does not resolve locale fallbacks — callers pass the locale they want.
*/
export class RelationRepository {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[needs fixing] This PR exports a new RelationRepository class and its types from the published emdash package (see packages/core/src/database/repositories/index.ts). That is an additive API change requiring a changeset per AGENTS.md.

Commit 06a07ae1 added .changeset/content-references-repository.md, but the latest commit 6051e2b2 deleted it. The existing content-references-schema.md changeset belongs to the earlier schema migration (#1367) and does not cover this repository layer. Please restore the deleted changeset so the release tooling can version-bump the package correctly.

Suggested change
export class RelationRepository {
// Please restore .changeset/content-references-repository.md
// (deleted in commit 6051e2b2).

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of PR #1444

Approach: Still sound. This remains the correct next slice for the content-references effort — a typed, tested data layer over the schema from migration 043, deliberately mirroring TaxonomyRepository.

What changed since the prior APPROVED review: The code has grown to include the complete edge CRUD (addReference, removeReference, getChildren, getParents, setChildren), the clearReferencesForGroup cleanup primitive, and batched count helpers (countChildren, countParents, countChildrenForParents). The implementation stays clean, consistent with existing repository patterns, and introduces no regressions in query safety or locale handling.

What I checked:

  • SQL safety: All queries remain Kysely builder only; no sql.raw() or interpolation.
  • AGENTS.md conventions: No admin UI strings / Lingui / RTL concerns (pure data layer). Locale filters are present on _emdash_relations queries where they belong; _emdash_content_references is locale-agnostic by design (edges keyed by translation_group), so omitting locale there is correct.
  • Schema and semantics: create correctly mints a fresh translation_group for anchor rows and inherits structural fields for translations. delete performs application-layer edge purge only when the last translation of a group is removed, mirroring TaxonomyRepository. setChildren deduplicates input with new Set to avoid gaps in positional sort_order, and documents the non-atomic delete-then-insert trade-off.
  • Tests: 25 dialect-agnostic tests via describeEachDialect, covering creation, translation inheritance, CRUD, edge append/replace/dedupe, backlink traversal, self-references, batch counts across SQL_BATCH_SIZE, application-layer cascade on last-translation deletion, and cross-relation clearReferencesForGroup cleanup.
  • Changeset: ⚠️ Unfixed from prior review context — now worse. The latest commit (6051e2b2) deletes .changeset/content-references-repository.md. The final diff against main therefore contains no changeset at all, even though packages/core is a published package and this PR adds a new feature. Per CONTRIBUTING.md, a changeset is required when a published package changes. The PR checklist still claims one was added. This needs to be restored before merge.

Headline conclusion: The implementation is clean and well-tested. The only remaining blocker-level issue is the missing changeset.

@ascorbic ascorbic left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks

@ascorbic
ascorbic merged commit 4809661 into emdash-cms:main Jun 12, 2026
75 of 77 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/core review/needs-rereview New commits since the last review size/XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants