Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: commit grounded catalog relationships atomically (#7900)

Adam Eivyb3e7fda5ab77
diff --git a/docs/API.md b/docs/API.md
index 338461da51..1a47750836 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -970,3 +970,14 @@ Common error codes:
- `VALIDATION_ERROR` - Invalid request data
- `COMMAND_NOT_ALLOWED` - Shell command not in allowlist
- `INTERNAL_ERROR` - Server error
+
+
+### Catalog scrap graph commits
+
+`POST /api/catalog/scraps/:id/commit` accepts up to 200 `accepted` entries and an optional `relationships` array (at most 1,000 edges). Each explicit edge has `fromDraftId`, `toDraftId`, `kind`, and nonempty `evidence` (at most 400 characters). When the array is present, every accepted entry needs a unique nonempty `draftId` (at most 120 characters); both endpoints must be accepted IDs and self-edges are rejected. Draft IDs stay outside persisted payloads. Renaming or reordering entries does not change endpoint identity.
+
+The server validates the graph before embedding or writing. Duplicate directed tuples create one edge, retaining every distinct evidence passage in the source ingredient's existing `payload.evidence` field with the kind and target name. Bible entries keep their evidence arrays (20 passages, 500 characters each including the contextual prefix); light entries keep string evidence, or arrays when supplied. Overflow is rejected explicitly, never truncated. The existing 200KB payload limit still applies after evidence enrichment.
+
+`relationships: []` means no edges. Omitting `relationships` preserves legacy all-pairs `related-to` links for batches of 2–25 entries. Explicit graphs work above that legacy batch limit. Supported kinds include `owned-by` (inverse: Owns) and `used-by` (inverse: Uses); using an object does not establish ownership. The caller must supply only grounded, accepted facts.
+
+Ingredients, source links, optional `universeRef` bindings, and edges commit in one transaction. No existing records are backfilled. The relation wire shape and existing evidence fields are unchanged; unknown relation kinds continue to round-trip through peer sync. Structured extraction and relationship review are tracked separately under #7895.
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 5dee1149b5..ffdbf9bcb7 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -32,7 +32,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
**Examples.**
- `catalog_ingredients` — typed creative records with JSONB payload, tags, embeddings, generated `search_tsv`, soft delete, sync sequence.
- `catalog_ingredient_refs` — homing links from an ingredient to the universe/series/creative-director/issue/work that consumes it. Since #7615, `POST /scraps/:id/commit` (the paste→extract→review ingest flow, plus bulk-import's long-standing `defaults.universeRef`) writes one `ref_kind='universe'` row per committed ingredient in the same transaction as the ingredient insert — the role is derived from the ingredient's type (`universeRefRoleForType` in `server/services/catalogDB/refs.js`) unless the caller overrides it. Omitting `universeRef` at commit time leaves the ingredient unlinked (the catalog's "Raw" bucket), exactly as before #7615.
-- `catalog_ingredient_relations` — directed ingredient→ingredient graph edges (the strongest argument for Postgres as the catalog graph store). Since #7615, committing a scrap also mints one `related-to` edge per unordered pair among the ingredients extracted from that scrap in one batch (bounded to batches of 25 or fewer), so a single source's extractions land as a connected cluster instead of isolated nodes.
+- `catalog_ingredient_relations` — directed ingredient→ingredient graph edges. Scrap commits with explicit `relationships` write only the reviewed edges (including none for `[]`), atomically with ingredients, source links, and universe refs. Legacy callers omitting the field still receive one `related-to` edge per unordered pair in batches of 2–25. The additive graph API is documented in [API.md](API.md#catalog-scrap-graph-commits).
- `catalog_scraps` / `catalog_ingredient_sources` — the catalog's SECOND grouping seam alongside refs (universe/series/work): a scrap is the raw pasted/imported text an ingredient was extracted from, and `catalog_ingredient_sources` links `(ingredient_id, scrap_id)` with an optional `span`. The ingredient detail page's `GET /ingredients/:id/details` joins the scrap's `title` onto each source link and batches every sibling ingredient extracted from the SAME scrap (`listSiblingIngredientsBySource`) in the one round-trip, so "what else came out of this piece?" is a rendered list, never a second fetch. `GET /ingredients?scrapId=<id>` (and `/catalog?scrap=<id>` client-side) filters the catalog to one scrap's whole extraction set — a provenance dimension orthogonal to the universe/series ref filters, so it composes with them rather than joining their mutual-exclusivity rule (#7617).
- `memories` / `memory_links` — long-term memory + pgvector similarity.
- `post_runs` / `post_attempts` — normalized MeatSpace POST test, benchmark, and training history. A run owns its planned composition and lifecycle timestamps; attempts carry queryable module/drill, difficulty/config version, correctness/score, latency/completion, hint/confidence, input mode, and scorer provenance, with the compatibility payload retained in JSONB. The complete attempt set is replaced in one transaction and stable client ids make retries idempotent. Migrated from `data/meatspace/post-sessions.json` and `post-training-log.json` by `server/scripts/migratePostRunsToDB.js`; the sources are parked as `.imported` recovery copies. **Intentionally machine-local — never federated** because cognitive-performance history is personal activity data. Adapter: `server/services/postRunStore.js` (legacy JSON only under the dev/test file escape hatch).
diff --git a/server/lib/catalogTypes.js b/server/lib/catalogTypes.js
index f1fd40c34d..c86f75466e 100644
--- a/server/lib/catalogTypes.js
+++ b/server/lib/catalogTypes.js
@@ -453,6 +453,8 @@ export function canonicalTagKey(label) {
const RELATION_REGISTRY = [
{ id: 'appears-in', label: 'Appears in', inverseLabel: 'Features' },
{ id: 'lives-in', label: 'Lives in', inverseLabel: 'Home of' },
+ { id: 'owned-by', label: 'Owned by', inverseLabel: 'Owns' },
+ { id: 'used-by', label: 'Used by', inverseLabel: 'Uses' },
{ id: 'created-by', label: 'Created by', inverseLabel: 'Creator of' },
{ id: 'parent-of', label: 'Parent of', inverseLabel: 'Child of' },
{ id: 'variant-of', label: 'Variant of', inverseLabel: 'Has variant' },
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index 0d778e589c..9008de3993 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -18,6 +18,7 @@ import {
MEDIA_KIND_IDS,
USER_TYPE_FIELD_KINDS,
isActiveType,
+ getActiveCatalogType,
} from './catalogTypes.js';
import { csvIdsParam } from './sharedSchemas.js';
import { SCRAP_SOURCE_KIND_IDS } from './catalogSourceKinds.js';
@@ -409,12 +410,73 @@ export const catalogMediaVoiceMemoSchema = z.object({
// today's behavior exactly: source link only, no homing ref.
export const catalogScrapCommitSchema = z.object({
accepted: z.array(catalogIngredientCreateSchema.extend({
+ // Extraction-local identity, never an ingredient ID or payload field.
+ draftId: z.string().trim().min(1).max(120).optional(),
// Optional source-span hint (server forwards as-is to linkIngredientToSource).
span: z.record(z.string(), z.unknown()).optional(),
})).min(0).max(200),
+ // Omitted preserves legacy clustering; [] explicitly means no edges.
+ relationships: z.array(z.object({
+ fromDraftId: z.string().trim().min(1).max(120),
+ toDraftId: z.string().trim().min(1).max(120),
+ kind: z.enum(RELATION_KINDS),
+ evidence: z.string().trim().min(1).max(400),
+ }).strict()).max(1000).optional(),
universeRef: z.string().trim().min(1).max(120).optional(),
role: z.string().trim().min(1).max(64).optional(),
-}).strict();
+}).strict().superRefine((body, ctx) => {
+ if (body.relationships === undefined) return;
+ const ids = new Set();
+ body.accepted.forEach((entry, index) => {
+ if (!entry.draftId || ids.has(entry.draftId)) {
+ ctx.addIssue({ code: 'custom', path: ['accepted', index, 'draftId'], message: 'Explicit graphs require unique draft IDs on every accepted entry' });
+ }
+ ids.add(entry.draftId);
+ });
+ body.relationships.forEach((edge, index) => {
+ if (!ids.has(edge.fromDraftId) || !ids.has(edge.toDraftId)) {
+ ctx.addIssue({ code: 'custom', path: ['relationships', index], message: 'Relationship endpoints must be accepted draft IDs' });
+ }
+ if (edge.fromDraftId === edge.toDraftId) {
+ ctx.addIssue({ code: 'custom', path: ['relationships', index], message: 'Self relationships are not allowed' });
+ }
+ });
+}).transform((body, ctx) => {
+ if (body.relationships === undefined) return body;
+ // One database edge per directed tuple, retaining each distinct evidence
+ // passage in the source payload's EXISTING evidence field. No draft IDs or
+ // new payload shape travel to older peers.
+ const entries = new Map(body.accepted.map(entry => [entry.draftId, entry]));
+ const edges = new Map();
+ const evidenceById = new Map();
+ for (const edge of body.relationships) {
+ const key = JSON.stringify([edge.fromDraftId, edge.toDraftId, edge.kind]);
+ if (!edges.has(key)) edges.set(key, edge);
+ const line = `${edge.kind} → ${entries.get(edge.toDraftId).name}: ${edge.evidence}`.replace(/\s+/g, ' ');
+ if (!evidenceById.has(edge.fromDraftId)) evidenceById.set(edge.fromDraftId, new Set());
+ evidenceById.get(edge.fromDraftId).add(line);
+ }
+ const accepted = body.accepted.map((entry, index) => {
+ const added = evidenceById.get(entry.draftId);
+ if (!added) return entry;
+ const original = entry.payload?.evidence;
+ const bible = getActiveCatalogType(entry.type)?.extractionShape === 'bible';
+ const existing = Array.isArray(original) ? original : typeof original === 'string' && original ? (bible ? [original] : original.split('\n')) : [];
+ const evidence = [...new Set([...existing, ...added])];
+ if (bible && (evidence.length > BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX ||
+ evidence.some(line => typeof line !== 'string' || line.length > BIBLE_LIMITS.EVIDENCE_ITEM_MAX))) {
+ ctx.addIssue({ code: 'custom', path: ['accepted', index, 'payload', 'evidence'], message: 'Grounded evidence exceeds the bible evidence capacity; shorten evidence or accept fewer links' });
+ return z.NEVER;
+ }
+ const enriched = { ...entry.payload, evidence: bible || Array.isArray(original) ? evidence : evidence.join('\n') };
+ if (JSON.stringify(enriched).length > 200_000) {
+ ctx.addIssue({ code: 'custom', path: ['accepted', index, 'payload'], message: 'Grounded payload exceeds 200KB JSON size cap' });
+ return z.NEVER;
+ }
+ return { ...entry, payload: enriched };
+ });
+ return { ...body, accepted, relationships: [...edges.values()] };
+});
// /scraps/:id/extract — optional provider/model override (e.g., a Brain
// handoff carrying the user's selected local route). Empty body is valid.
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index e3ecbc915b..239635f25c 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -177,6 +177,7 @@ router.post('/scraps/:id/commit', asyncHandler(async (req, res) => {
const created = await catalogDB.commitScrap({
scrapId: scrap.id,
accepted: body.accepted,
+ ...(body.relationships !== undefined ? { relationships: body.relationships } : {}),
embeds,
universeRef: body.universeRef,
role: body.role,
diff --git a/server/routes/catalog.test.js b/server/routes/catalog.test.js
index d3f503aab9..5b09798548 100644
--- a/server/routes/catalog.test.js
+++ b/server/routes/catalog.test.js
@@ -411,6 +411,75 @@ describe.skipIf(!runDb)('POST /api/catalog/scraps/:id/commit — universe bindin
}
});
+ it('persists reviewed ownership/use edges and evidence through reload without draft metadata', async () => {
+ const scrap = await catalogDB.createScrap({ rawText: 'Example Owner lends an inherited pistol to Example Companion.' });
+ createdScrapIds.add(scrap.id);
+ const response = await request(makeApp()).post(`/api/catalog/scraps/${scrap.id}/commit`).send({
+ accepted: [
+ { draftId: 'pistol', type: 'object', name: 'Example Inherited Pistol' },
+ { draftId: 'owner', type: 'character', name: 'Example Owner' },
+ { draftId: 'user', type: 'character', name: 'Example Companion' },
+ ],
+ relationships: [
+ { fromDraftId: 'pistol', toDraftId: 'owner', kind: 'owned-by', evidence: 'The owner inherited the pistol.' },
+ { fromDraftId: 'pistol', toDraftId: 'user', kind: 'used-by', evidence: 'The companion borrowed the pistol.' },
+ ],
+ universeRef: UNI,
+ });
+ expect(response.status).toBe(201);
+ for (const row of response.body.ingredients) createdIngredientIds.add(row.id);
+ const [pistol, owner, user] = response.body.ingredients;
+ const reloaded = await catalogDB.getIngredient(pistol.id);
+ expect(reloaded.payload.evidence).toEqual([
+ 'owned-by → Example Owner: The owner inherited the pistol.',
+ 'used-by → Example Companion: The companion borrowed the pistol.',
+ ]);
+ expect(reloaded.payload).not.toHaveProperty('draftId');
+ const relations = await catalogDB.listRelationsForIngredient(pistol.id);
+ expect(relations.outbound).toEqual(expect.arrayContaining([
+ expect.objectContaining({ toId: owner.id, kind: 'owned-by' }),
+ expect.objectContaining({ toId: user.id, kind: 'used-by' }),
+ ]));
+ expect(relations.outbound).toHaveLength(2);
+ expect((await catalogDB.listRelationsForIngredient(owner.id)).inbound)
+ .toEqual([expect.objectContaining({ fromId: pistol.id, kind: 'owned-by' })]);
+ });
+
+ it('rolls back source links, universe refs, ingredients and earlier edges on a relation failure', async () => {
+ const scrap = await catalogDB.createScrap({ rawText: 'Example relation rollback source' });
+ createdScrapIds.add(scrap.id);
+ const refs = await import('../services/catalogDB/refs.js');
+ const realLink = refs.linkIngredientRelation;
+ const linkedIds = new Set();
+ let calls = 0;
+ const spy = vi.spyOn(refs, 'linkIngredientRelation').mockImplementation(async (from, to, kind, options) => {
+ linkedIds.add(from);
+ linkedIds.add(to);
+ if (++calls === 2) throw new Error('Injected second relation failure');
+ return realLink(from, to, kind, options);
+ });
+ try {
+ await expect(catalogDB.commitScrap({
+ scrapId: scrap.id, universeRef: UNI,
+ accepted: ['a', 'b', 'c'].map(draftId => ({ draftId, type: 'idea', name: 'Example ' + draftId })),
+ relationships: [
+ { fromDraftId: 'a', toDraftId: 'b', kind: 'references', evidence: 'A references B.' },
+ { fromDraftId: 'a', toDraftId: 'c', kind: 'references', evidence: 'A references C.' },
+ ],
+ })).rejects.toThrow('Injected second relation failure');
+ } finally {
+ spy.mockRestore();
+ }
+ expect(calls).toBe(2);
+ for (const id of linkedIds) {
+ expect(await catalogDB.getIngredient(id)).toBeNull();
+ expect(await catalogDB.listSourcesForIngredient(id)).toEqual([]);
+ expect(await catalogDB.listRefsForIngredient(id)).toEqual([]);
+ }
+ const edges = await query('SELECT * FROM catalog_ingredient_relations WHERE from_id = ANY($1::text[])', [[...linkedIds]]);
+ expect(edges.rows).toEqual([]);
+ });
+
it('rolls back every ingredient, ref, and relation edge on a mid-batch failure', async () => {
const scrap = await catalogDB.createScrap({ rawText: `Commit rollback source ${NONCE}` });
createdScrapIds.add(scrap.id);
diff --git a/server/routes/catalogParsedBodies.test.js b/server/routes/catalogParsedBodies.test.js
index faa311745e..9065873ef9 100644
--- a/server/routes/catalogParsedBodies.test.js
+++ b/server/routes/catalogParsedBodies.test.js
@@ -50,7 +50,7 @@ const router = (await import('./catalog.js')).default;
function makeApp() {
const app = express();
- app.use(express.json());
+ app.use(express.json({ limit: '4mb' }));
app.use('/api/catalog', router);
app.use(errorMiddleware);
return app;
@@ -70,6 +70,52 @@ beforeEach(() => {
mocks.updateUniverse.mockResolvedValue(null);
});
+describe('Catalog explicit draft graphs', () => {
+ const accepted = [
+ { draftId: 'owner', type: 'character', name: 'Example Owner' },
+ { draftId: 'object', type: 'object', name: 'Inherited Pistol' },
+ ];
+ const edge = { fromDraftId: 'object', toDraftId: 'owner', kind: 'owned-by', evidence: 'The owner inherited the pistol.' };
+
+ it('normalizes repeated edges without losing evidence before embedding and committing', async () => {
+ const response = await request(makeApp()).post('/api/catalog/scraps/scrap-1/commit').send({
+ accepted,
+ relationships: [edge, { ...edge, evidence: 'The inscription names the owner.' }, edge],
+ });
+ expect(response.status).toBe(201);
+ const body = mocks.commitScrap.mock.calls[0][0];
+ expect(body.relationships).toEqual([edge]);
+ expect(body.accepted[1].payload.evidence).toEqual([
+ 'owned-by → Example Owner: The owner inherited the pistol.',
+ 'owned-by → Example Owner: The inscription names the owner.',
+ ]);
+ expect(mocks.ingredientEmbedSeed).toHaveBeenNthCalledWith(2, body.accepted[1]);
+ });
+
+ it('forwards explicit empty graphs without reverting to omitted legacy behavior', async () => {
+ const response = await request(makeApp()).post('/api/catalog/scraps/scrap-1/commit')
+ .send({ accepted, relationships: [] });
+ expect(response.status).toBe(201);
+ expect(mocks.commitScrap.mock.calls[0][0]).toMatchObject({ accepted, relationships: [] });
+ });
+
+ it.each([
+ ['dangling endpoint', { accepted, relationships: [{ ...edge, toDraftId: 'absent' }] }],
+ ['duplicate ID', { accepted: [accepted[0], { ...accepted[1], draftId: 'owner' }], relationships: [] }],
+ ['missing ID', { accepted: [{ type: 'idea', name: 'Example' }], relationships: [] }],
+ ['self edge', { accepted, relationships: [{ ...edge, toDraftId: 'object' }] }],
+ ['unknown kind', { accepted, relationships: [{ ...edge, kind: 'imaginary-kind' }] }],
+ ['entry overflow', { accepted: Array.from({ length: 201 }, (_, i) => ({ ...accepted[0], draftId: String(i) })), relationships: [] }],
+ ['edge overflow', { accepted, relationships: Array.from({ length: 1001 }, () => edge) }],
+ ['evidence overflow', { accepted, relationships: Array.from({ length: 21 }, (_, i) => ({ ...edge, evidence: 'Passage ' + i })) }],
+ ])('rejects %s before embeddings or writes', async (_name, body) => {
+ const response = await request(makeApp()).post('/api/catalog/scraps/scrap-1/commit').send(body);
+ expect(response.status).toBe(400);
+ expect(mocks.embedBatch).not.toHaveBeenCalled();
+ expect(mocks.commitScrap).not.toHaveBeenCalled();
+ });
+});
+
describe('Catalog parsed write bodies', () => {
it('creates with the normalized type and does not persist or embed an unknown type', async () => {
const created = await request(makeApp())
diff --git a/server/services/catalogDB.commit.test.js b/server/services/catalogDB.commit.test.js
index b154e928bd..c4aa57925e 100644
--- a/server/services/catalogDB.commit.test.js
+++ b/server/services/catalogDB.commit.test.js
@@ -39,6 +39,40 @@ beforeEach(() => {
mocks.linkIngredientRelation.mockResolvedValue(undefined);
});
+describe('explicit graph commits', () => {
+ const accepted = Array.from({ length: 26 }, (_, i) => ({
+ draftId: 'draft-' + i, type: 'idea', name: 'Renamed Idea ' + i,
+ }));
+ const edge = { fromDraftId: 'draft-25', toDraftId: 'draft-0', kind: 'references', evidence: 'The final idea references the first.' };
+
+ it('maps reordered draft IDs and writes only requested directed edges above the legacy cap', async () => {
+ mocks.createIngredient.mockImplementation(async ({ name }) => ({ id: 'stored-' + name }));
+ await commitScrap({ scrapId: 'example-scrap', accepted: [...accepted].reverse(), relationships: [edge] });
+ expect(mocks.linkIngredientRelation).toHaveBeenCalledExactlyOnceWith(
+ 'stored-Renamed Idea 25', 'stored-Renamed Idea 0', 'references', { client: mocks.client },
+ );
+ expect(mocks.createIngredient.mock.calls[0][0]).not.toHaveProperty('draftId');
+ expect(mocks.createIngredient.mock.calls[0][0].payload).not.toHaveProperty('draftId');
+ });
+
+ it('never creates pairs for explicit [] and validates direct callers before opening a transaction', async () => {
+ mocks.createIngredient.mockImplementation(async ({ name }) => ({ id: 'stored-' + name }));
+ await commitScrap({ scrapId: 'example-scrap', accepted: accepted.slice(0, 2), relationships: [] });
+ expect(mocks.linkIngredientRelation).not.toHaveBeenCalled();
+ mocks.withTransaction.mockClear();
+ await expect(commitScrap({ accepted, relationships: [{ ...edge, toDraftId: 'missing' }] })).rejects.toThrow();
+ expect(mocks.withTransaction).not.toHaveBeenCalled();
+ });
+
+ it('propagates a relation-write failure to the transaction owner', async () => {
+ mocks.createIngredient.mockImplementation(async ({ name }) => ({ id: 'stored-' + name }));
+ const failure = new Error('relation write failed');
+ mocks.linkIngredientRelation.mockRejectedValue(failure);
+ await expect(commitScrap({ scrapId: 'example-scrap', accepted, relationships: [edge], universeRef: 'example-universe' }))
+ .rejects.toBe(failure);
+ });
+});
+
describe('commitScrap', () => {
it('creates accepted ingredients and source links on one transaction client', async () => {
mocks.createIngredient
diff --git a/server/services/catalogDB/commit.js b/server/services/catalogDB/commit.js
index 48a1805eab..510bfb01b0 100644
--- a/server/services/catalogDB/commit.js
+++ b/server/services/catalogDB/commit.js
@@ -5,11 +5,12 @@
* cannot accidentally persist only part of a scrap's accepted extraction.
*/
+import { catalogScrapCommitSchema } from '../../lib/catalogValidation.js';
import { withTransaction } from '../../lib/db.js';
import { createIngredient } from './ingredients.js';
import { linkIngredientToSource, linkIngredientToRef, linkIngredientRelation, universeRefRoleForType } from './refs.js';
-// Same-batch `related-to` edges connect a single scrap's extractions into one
+// Legacy same-batch `related-to` edges connect a single scrap's extractions into one
// cluster instead of N isolated nodes (#7615). Bounded: a batch above this
// size mints none — the schema allows up to 200 accepted rows, which would be
// 19,900 edges for every unordered pair at the cap.
@@ -24,9 +25,14 @@ const RELATION_BATCH_LIMIT = 25;
* mid-batch failure rolls back ingredients, refs, and relations together.
* Omitting it reproduces prior behavior exactly (source link only).
*/
-export async function commitScrap({ scrapId, accepted = [], embeds = [], universeRef = null, role = null } = {}) {
+export async function commitScrap({ scrapId, accepted = [], embeds = [], universeRef = null, role = null, relationships } = {}) {
+ // Service callers receive the same pre-write guarantees as HTTP callers.
+ if (relationships !== undefined) {
+ ({ accepted, relationships } = catalogScrapCommitSchema.parse({ accepted, relationships }));
+ }
return withTransaction(async (client) => {
const created = [];
+ const ids = new Map();
for (let i = 0; i < accepted.length; i++) {
const draft = accepted[i];
const embedding = embeds[i];
@@ -49,6 +55,7 @@ export async function commitScrap({ scrapId, accepted = [], embeds = [], univers
);
}
created.push(ingredient);
+ if (draft.draftId) ids.set(draft.draftId, ingredient.id);
}
// Mint one `related-to` edge per unordered pair among this batch's
@@ -56,7 +63,11 @@ export async function commitScrap({ scrapId, accepted = [], embeds = [], univers
// Deterministic direction: from_id = the lexicographically smaller id —
// the PK is (from_id, to_id, kind), so an arbitrary direction would let a
// re-commit create a reciprocal duplicate instead of reviving the same row.
- if (created.length >= 2 && created.length <= RELATION_BATCH_LIMIT) {
+ if (relationships !== undefined) {
+ for (const edge of relationships) {
+ await linkIngredientRelation(ids.get(edge.fromDraftId), ids.get(edge.toDraftId), edge.kind, { client });
+ }
+ } else if (created.length >= 2 && created.length <= RELATION_BATCH_LIMIT) {
for (let i = 0; i < created.length; i++) {
for (let j = i + 1; j < created.length; j++) {
const [fromId, toId] = created[i].id < created[j].id