suppa-mcp-2 1.2.2 → 1.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,7 +16,7 @@ import { basename } from "node:path";
16
16
  import { config } from "../config.js";
17
17
  import * as tenants from "../tenants.js";
18
18
  import { makeRequest, makeRequestRawBytes, searchEntity, selectEntity, insertEntity, updateEntity, removeEntity, } from "../httpClient.js";
19
- import { buildFileUpload, makeFilter, jsonResponse, parseJsonParam } from "../utils.js";
19
+ import { buildFileUpload, makeFilter, jsonResponse, parseJsonParam, mergeListProblems, } from "../utils.js";
20
20
  // Builder field types that accept file uploads.
21
21
  export const FILE_FIELD_TYPES = ["file", "multi-file"];
22
22
  export const RELATION_FIELD_TYPES = [
@@ -44,6 +44,35 @@ export const VALID_FIELD_TYPES = [
44
44
  "multi-file",
45
45
  ...RELATION_FIELD_TYPES,
46
46
  ];
47
+ // Field types the builder groups as "Relation types" — their values live in a
48
+ // join/side table, not in a column of this table.
49
+ // (docs/superpowers/specs/captures/api-entity-builder-builder.txt:63 —
50
+ // "Relation types: many-to-one, one-to-many, many-to-many, many-to-many-backref,
51
+ // enum, multi-enum, file, multi-file.")
52
+ export const RELATION_LIKE_FIELD_TYPES = [
53
+ ...RELATION_FIELD_TYPES,
54
+ "enum",
55
+ "multi-enum",
56
+ "file",
57
+ "multi-file",
58
+ ];
59
+ // Where `defaultValue` does NOT apply. builder.txt:43 — "defaultValue | string |
60
+ // false | Default value. Not applicable to relations, enums, or unique fields."
61
+ // So: every relation-like type above, plus ANY type when unique is set.
62
+ // (`notNull` has its own, narrower exclusion — builder.txt:41: "Not applicable to
63
+ // many-to-many / multi-enum" — and is still sent for the rest.)
64
+ export const NO_DEFAULT_VALUE_FIELD_TYPES = RELATION_LIKE_FIELD_TYPES;
65
+ /**
66
+ * True when `defaultValue` is applicable to this field — and therefore when
67
+ * `notNull` on it also demands one. Recorded evidence for that demand, on the
68
+ * types where the default DOES apply: the builder answers HTTP 400
69
+ * "`defaultValue` is required when creating a field with `notNull: true`" (an
70
+ * empty string is rejected too). Where the default does not apply the builder
71
+ * takes `notNull` alone, so no default is required — and none is sent.
72
+ */
73
+ export function defaultValueApplies(fieldType, unique = false) {
74
+ return !unique && !RELATION_LIKE_FIELD_TYPES.includes(fieldType);
75
+ }
47
76
  // ---------------------------------------------------------------------------
48
77
  // Multi-language titles
49
78
  // ---------------------------------------------------------------------------
@@ -282,15 +311,21 @@ export async function createEntity(name, title, titleFieldName = "title", autoTi
282
311
  };
283
312
  const result = await makeRequest("POST", "/api/core/builder/create-entity", body);
284
313
  let titleFieldResult = null;
314
+ let representative = null;
285
315
  if (autoTitleField && titleFieldName) {
286
316
  titleFieldResult = _parseMaybe(await addField(name, titleFieldName, titleFieldType, titleObj));
317
+ // Make the freshly-created title field the entity's representative, so
318
+ // records show a label instead of an id everywhere in the UI. 5 tries, the
319
+ // same as set_title_field: the field was created a moment ago and the schema
320
+ // read is eventually consistent, so a single try reports a false "not found"
321
+ // and — worse — never sends the /update at all.
322
+ representative = _representativeResult(await _setRepresentative(name, titleFieldName, 5));
287
323
  }
288
- // NOTE: we deliberately do NOT auto-set the representative field here. The only
289
- // builder endpoint that accepts it (POST /builder/{entity}/update with
290
- // {representativeField:{id}}) proved unreliable in live testing (worked on some
291
- // entities, returned HTTP 500 on others) — too risky to run on every create.
292
- // Use suppa_set_title_field explicitly, or set the representative in the UI.
293
- return jsonResponse({ entity: result, title_field: titleFieldResult });
324
+ return jsonResponse({
325
+ entity: result,
326
+ title_field: titleFieldResult,
327
+ representative_field: representative,
328
+ });
294
329
  }
295
330
  /**
296
331
  * Create a tabular part (ТЧ / "таблична частина") — an owned child sub-table
@@ -333,14 +368,19 @@ export async function createTabularPart(parentEntity, name, title, titleFieldNam
333
368
  };
334
369
  const result = await makeRequest("POST", "/api/core/builder/create-entity", body);
335
370
  let titleFieldResult = null;
371
+ let representative = null;
336
372
  if (autoTitleField && titleFieldName) {
337
373
  titleFieldResult = _parseMaybe(await addField(entityName, titleFieldName, titleFieldType, titleObj));
374
+ // 5 tries — see create_entity: the field is brand new and the schema read
375
+ // that resolves its id is eventually consistent.
376
+ representative = _representativeResult(await _setRepresentative(entityName, titleFieldName, 5));
338
377
  }
339
378
  return jsonResponse({
340
379
  tabular_part: result,
341
380
  entity_name: entityName,
342
381
  parent_entity: parentEntity,
343
382
  title_field: titleFieldResult,
383
+ representative_field: representative,
344
384
  });
345
385
  }
346
386
  /**
@@ -365,36 +405,67 @@ function _parseMaybe(result) {
365
405
  return result;
366
406
  }
367
407
  }
368
- /** Return the numeric id of a field on an entity, or None if absent. */
369
- async function _fieldId(entityName, fieldName) {
370
- const schema = await makeRequest("GET", `/api/core/schema/${entityName}`);
371
- for (const f of _extractFields(schema)) {
372
- if (f.name === fieldName) {
373
- return f.id;
408
+ /**
409
+ * Return the numeric id of a field on an entity, or null if absent.
410
+ *
411
+ * Retries on the SAME schedule as the representative confirmation below: the
412
+ * schema read is eventually consistent, so a field created moments ago can be
413
+ * missing from the first read. Without the retry the create path would skip the
414
+ * /update POST entirely and report "field not found" for a field that exists —
415
+ * a false negative, not a real failure.
416
+ */
417
+ async function _fieldId(entityName, fieldName, tries = 1) {
418
+ const attempts = Math.max(1, tries);
419
+ for (let i = 0; i < attempts; i++) {
420
+ const schema = await makeRequest("GET", `/api/core/schema/${entityName}`);
421
+ for (const f of _extractFields(schema)) {
422
+ if (f.name === fieldName) {
423
+ return f.id;
424
+ }
425
+ }
426
+ if (i + 1 < attempts) {
427
+ await sleep(_schemaRetryMs);
374
428
  }
375
429
  }
376
430
  return null;
377
431
  }
432
+ /** Delay between eventually-consistent schema re-reads (field id + representative). */
433
+ let _schemaRetryMs = 2000;
434
+ /** Test hook: shrink the re-read delay so offline suites do not sleep for real. */
435
+ export function _setSchemaRetryMs(ms) {
436
+ _schemaRetryMs = ms;
437
+ }
378
438
  /**
379
439
  * Make `field_name` the entity's representative (display-title) field.
380
440
  *
381
- * Uses ``POST /api/core/builder/{entity}/update`` with
382
- * ``{"representativeField": {"id": <fieldId>}}``. CAVEAT: in live testing this
383
- * endpoint was unreliable — it set the representative on some entities but
384
- * returned HTTP 500 on others — so the error is surfaced (not swallowed) and
385
- * callers must treat it as best-effort. The schema read is eventually-
386
- * consistent, so confirmation polls up to ``verify_tries`` times. Returns
387
- * ``[confirmed, representative_value, error_or_None]``.
441
+ * WIRE FORMAT: ``POST /api/core/builder/{entity}/update`` with
442
+ * ``{"representativeFieldId": <fieldId>}`` — a NUMBER, per
443
+ * docs/superpowers/specs/captures/api-entity-builder-builder.txt:218
444
+ * ("representativeFieldId | number | false | Representative field ID."). Note the
445
+ * asymmetry with the read: the REQUEST takes the id, the schema RESPONSE returns
446
+ * ``representativeField`` as an object. This server used to send that response
447
+ * shape (``{"representativeField": {"id": …}}``), an unknown key.
448
+ *
449
+ * STILL UNEXPLAINED — recorded, not deleted: in live testing this endpoint set
450
+ * the representative on some entities and answered HTTP 500 on others. A wrong
451
+ * key cannot produce a 500, so the wire-format fix above does NOT account for
452
+ * that observation and it may still be there. Hence the error is REPORTED rather
453
+ * than thrown — the entity and its field exist either way — and the caller can
454
+ * retry. The schema read is eventually consistent, so both the field-id lookup
455
+ * and the confirmation poll up to ``verify_tries`` times.
456
+ * Returns ``[confirmed, representative_value, error_or_None]``.
388
457
  */
389
458
  async function _setRepresentative(entityName, fieldName, verifyTries = 1) {
390
- const fid = await _fieldId(entityName, fieldName);
459
+ const fid = await _fieldId(entityName, fieldName, verifyTries);
391
460
  if (fid === null || fid === undefined) {
392
461
  return [false, null, `field '${fieldName}' not found on '${entityName}'`];
393
462
  }
394
463
  let error = null;
395
464
  try {
396
465
  await makeRequest("POST", `/api/core/builder/${entityName}/update`, {
397
- representativeField: { id: fid },
466
+ // builder.txt:218 — the request key is representativeFieldId (number);
467
+ // representativeField (object) is the RESPONSE shape and is dropped here.
468
+ representativeFieldId: fid,
398
469
  });
399
470
  }
400
471
  catch (ex) {
@@ -419,7 +490,7 @@ async function _setRepresentative(entityName, fieldName, verifyTries = 1) {
419
490
  return [true, rep, null];
420
491
  }
421
492
  if (i + 1 < tries) {
422
- await sleep(2000);
493
+ await sleep(_schemaRetryMs);
423
494
  }
424
495
  }
425
496
  return [false, rep, error];
@@ -427,15 +498,36 @@ async function _setRepresentative(entityName, fieldName, verifyTries = 1) {
427
498
  function sleep(ms) {
428
499
  return new Promise((resolve) => setTimeout(resolve, ms));
429
500
  }
501
+ /**
502
+ * What an unconfirmed representative means, in the caller's words. One text,
503
+ * used by both create_* (via `_representativeResult`) and `set_title_field`, so
504
+ * the two paths never explain the same state differently.
505
+ */
506
+ function _representativeNote(confirmed, error) {
507
+ if (confirmed) {
508
+ return null;
509
+ }
510
+ return ("Representative not confirmed by the schema read (it is eventually " +
511
+ "consistent). The field exists; re-check the entity in a moment, or set " +
512
+ "the display field in the UI. " +
513
+ (error ? `(error: ${error})` : ""));
514
+ }
515
+ /**
516
+ * Shape `_setRepresentative`'s tuple for a create-* response. Reported, never
517
+ * thrown: the entity and its title field exist either way, and the confirming
518
+ * schema read is eventually consistent — which is exactly what `note` says when
519
+ * the confirmation did not land.
520
+ */
521
+ function _representativeResult([confirmed, value, error]) {
522
+ return { set: confirmed, value, error, note: _representativeNote(confirmed, error) };
523
+ }
430
524
  /**
431
525
  * Make `field_name` the entity's display-title (representative) field.
432
526
  *
433
- * Creates the field (multi-language) if it is missing, then makes a BEST-EFFORT
434
- * attempt to set it as the entity's representative via the builder update
435
- * endpoint. That endpoint proved unreliable in live testing (HTTP 500 on some
436
- * entities), so a failure here does not raise — it is reported in the result,
437
- * and the field is still created. Set the representative in the UI if the API
438
- * attempt fails.
527
+ * Creates the field (multi-language) if it is missing, then sets it as the
528
+ * entity's representative via the builder update endpoint. A failure does not
529
+ * raise — it is reported in the result and the field is still created — because
530
+ * the schema read used for confirmation is eventually consistent.
439
531
  */
440
532
  export async function setTitleField(entityName, fieldName) {
441
533
  const schema = await makeRequest("GET", `/api/core/schema/${entityName}`);
@@ -445,14 +537,7 @@ export async function setTitleField(entityName, fieldName) {
445
537
  created = _parseMaybe(await addField(entityName, fieldName, "multi-language", fieldName));
446
538
  }
447
539
  const [confirmed, rep, error] = await _setRepresentative(entityName, fieldName, 5);
448
- let note = null;
449
- if (!confirmed) {
450
- note =
451
- "Representative not confirmed via API — the builder update endpoint " +
452
- "is unreliable (often HTTP 500). The field exists; set it as the " +
453
- "display field in the UI. " +
454
- (error ? `(error: ${error})` : "");
455
- }
540
+ const note = _representativeNote(confirmed, error);
456
541
  return jsonResponse({
457
542
  entity: entityName,
458
543
  title_field: fieldName,
@@ -551,9 +636,16 @@ async function _relationPreflight(entityName, fieldName, relationType, relationE
551
636
  * For relation fields, provide relation_entity. For enum fields, provide enum_name.
552
637
  * Constraints: max_length/min_length (text), decimal_places (numeric),
553
638
  * min_value/max_value/only_positive (numeric).
639
+ * required=true makes the column NOT NULL and REQUIRES default_value (a SQL
640
+ * expression or literal, e.g. '0', 'false', "'draft'", 'now()') — the builder
641
+ * refuses notNull without one. Exempt, because defaultValue does not apply to
642
+ * them at all: relation types (many-to-one / many-to-many / many-to-many-backref),
643
+ * enum and multi-enum, file and multi-file, and any unique field. The call is
644
+ * refused before any request if an applicable default is missing; no default is
645
+ * ever invented.
554
646
  */
555
647
  export async function addField(entityName, fieldName, fieldType, title, opts = {}) {
556
- const { required = false, unique = false, relationEntity = null, enumName = null, subType = null, maxLength = null, minLength = null, decimalPlaces = null, minValue = null, maxValue = null, onlyPositive = false, } = opts;
648
+ const { required = false, defaultValue = null, unique = false, relationEntity = null, enumName = null, subType = null, maxLength = null, minLength = null, decimalPlaces = null, minValue = null, maxValue = null, onlyPositive = false, } = opts;
557
649
  // The platform has no relation type literally called "relation"; a foreign
558
650
  // key is "many-to-one" with the target entity in `relationTarget`.
559
651
  let resolvedType = fieldType === "relation" ? "many-to-one" : fieldType;
@@ -601,6 +693,36 @@ export async function addField(entityName, fieldName, fieldType, title, opts = {
601
693
  "with suppa_add_enum_values.",
602
694
  });
603
695
  }
696
+ // NOT NULL needs a default — but ONLY where a default is applicable at all.
697
+ // builder.txt:43 (docs/superpowers/specs/captures/api-entity-builder-builder.txt)
698
+ // rules defaultValue out for relations, enums and unique fields; on everything
699
+ // else the builder rejects `notNull: true` on its own (HTTP 400 "`defaultValue`
700
+ // is required when creating a field with `notNull: true`") and rejects an
701
+ // empty-string default as well. There we refuse BEFORE the request instead of
702
+ // inventing a value: what an empty row should hold is a data-semantics decision
703
+ // that belongs to the caller, and guessing it would silently write a value
704
+ // nobody chose.
705
+ const defaultText = defaultValue === null || defaultValue === undefined ? "" : String(defaultValue);
706
+ const typeNeedsDefault = defaultValueApplies(resolvedType, unique);
707
+ if (required && typeNeedsDefault && defaultText.trim() === "") {
708
+ return jsonResponse({
709
+ error: `Refused: required=true needs default_value. The builder rejects a notNull field ` +
710
+ "without one (HTTP 400: \"`defaultValue` is required when creating a field with " +
711
+ `\`notNull: true\`\"), and an empty string does not count. Pass default_value — the ` +
712
+ "value every row without an explicit one gets — as a SQL expression or literal, or " +
713
+ "leave required=false and add the constraint later once the column is populated. " +
714
+ "This server will not pick a default for you: that would silently decide your data semantics.",
715
+ examples: [
716
+ `suppa_add_field(entity_name="${entityName}", field_name="${fieldName}", ` +
717
+ `field_type="${resolvedType}", required=true, default_value="0") # literal`,
718
+ `suppa_add_field(entity_name="${entityName}", field_name="${fieldName}", ` +
719
+ `field_type="${resolvedType}", required=true, default_value="now()") # SQL expression ` +
720
+ "(quote text literals inside the string: \"'draft'\")",
721
+ ],
722
+ no_default_needed_for: [...NO_DEFAULT_VALUE_FIELD_TYPES],
723
+ no_default_needed_when: "unique=true (defaultValue does not apply to a unique field)",
724
+ });
725
+ }
604
726
  // Relation pre-flight: verify the target exists and the field is new, so we
605
727
  // never leave a dangling or duplicate relation on the entity. May correct a
606
728
  // case-only target-name mismatch.
@@ -612,13 +734,26 @@ export async function addField(entityName, fieldName, fieldType, title, opts = {
612
734
  }
613
735
  relTarget = pf.relationEntity;
614
736
  }
737
+ // The builder reads `notNull`, NOT `required` — an unknown key is dropped
738
+ // without complaint, which is why every field this server used to create came
739
+ // out nullable while the tool reported success. The TOOL parameter stays
740
+ // `required`; only the wire key changed.
741
+ // Wire keys per docs/superpowers/specs/captures/api-entity-builder-builder.txt:
742
+ // notNull :41, unique :42, defaultValue :43, subType :40, relationTarget :44,
743
+ // maxLength :49, minLength :50, maxValue :51, minValue :52, isOnlyPositive :53,
744
+ // decimalPlaces :55, title :56.
615
745
  const fieldDef = {
616
746
  name: fieldName,
617
747
  type: resolvedType,
618
748
  title: await _expandTitle(title, fieldName),
619
- required,
749
+ notNull: required,
620
750
  unique,
621
751
  };
752
+ // builder.txt:43 — "Not applicable to relations, enums, or unique fields":
753
+ // sending it there is at best ignored, so it is never emitted.
754
+ if (defaultText.trim() !== "" && typeNeedsDefault) {
755
+ fieldDef.defaultValue = defaultText;
756
+ }
622
757
  if (subType) {
623
758
  fieldDef.subType = subType;
624
759
  }
@@ -772,7 +907,9 @@ function _shapeProblemsFromDefs(defs, fields) {
772
907
  else if (_MULTI_REF_TYPES.includes(ftype) &&
773
908
  !(isRef(val) || (Array.isArray(val) && val.every((x) => isRef(x))))) {
774
909
  problems.push(`'${key}' is a ${ftype} field — write it as [{"id": N}, ...] ` +
775
- `(got ${_truncJson(val)}).`);
910
+ `(got ${_truncJson(val)}). The list you send REPLACES the stored one: ` +
911
+ "to ADD items pass the field name in merge_json, to REMOVE only the " +
912
+ "listed items pass it in unmerge_json (suppa_update_record).");
776
913
  }
777
914
  }
778
915
  return problems;
@@ -886,7 +1023,63 @@ async function _validateRecordWrite(entityName, fields) {
886
1023
  };
887
1024
  }
888
1025
  }
889
- return { entityName };
1026
+ // The defs travel back so the caller does not re-read the schema to decide
1027
+ // which written fields are actually list-valued (see `_replacedListNames`).
1028
+ return { entityName, defs: defs && defs.length > 0 ? defs : null };
1029
+ }
1030
+ // The only field types whose stored value IS a list, so the only ones an update
1031
+ // can replace wholesale and the only ones merge/unmerge applies to. Types from
1032
+ // the builder's relation group (api-entity-builder-builder.txt:63). A `json`
1033
+ // column may perfectly well hold a JSON array — that is ONE value being
1034
+ // overwritten, not a list of links being wiped, and warning about it is noise.
1035
+ const LIST_VALUED_FIELD_TYPES = new Set([
1036
+ "many-to-many",
1037
+ "many-to-many-backref",
1038
+ "one-to-many",
1039
+ "multi-enum",
1040
+ "multi-file",
1041
+ ]);
1042
+ /**
1043
+ * Names of the fields this write REPLACES wholesale: list-valued per the schema,
1044
+ * written with an array, and not opted out via merge/unmerge.
1045
+ *
1046
+ * `defs === null` means the schema could not be read — then the array shape is
1047
+ * all we have, so we still warn. A spurious warning is noise; a missing one can
1048
+ * mean a silently wiped list.
1049
+ */
1050
+ function _replacedListNames(defs, fields, merge, unmerge) {
1051
+ const typeByName = new Map();
1052
+ for (const d of defs ?? []) {
1053
+ if (typeof d.name === "string") {
1054
+ typeByName.set(d.name, String(d.type ?? ""));
1055
+ }
1056
+ }
1057
+ return Object.entries(fields)
1058
+ .filter(([k, val]) => {
1059
+ if (!Array.isArray(val) || merge.includes(k) || unmerge.includes(k)) {
1060
+ return false;
1061
+ }
1062
+ const type = typeByName.get(k);
1063
+ return type === undefined ? defs === null : LIST_VALUED_FIELD_TYPES.has(type);
1064
+ })
1065
+ .map(([k]) => k);
1066
+ }
1067
+ /**
1068
+ * Same answer as `_replacedListNames`, for a caller that has no field defs — the
1069
+ * confirm-gate preview, which must name the lists a write would wipe BEFORE the
1070
+ * user approves it. Reads the schema best-effort; a failure degrades to the
1071
+ * value-shape heuristic rather than dropping the warning.
1072
+ */
1073
+ export async function previewReplacedLists(entityName, fields, merge = [], unmerge = []) {
1074
+ let defs = null;
1075
+ try {
1076
+ const found = _extractFields(await makeRequest("GET", `/api/core/schema/${entityName}`));
1077
+ defs = found.length > 0 ? found : null;
1078
+ }
1079
+ catch {
1080
+ defs = null;
1081
+ }
1082
+ return _replacedListNames(defs, fields, merge, unmerge);
890
1083
  }
891
1084
  /**
892
1085
  * Create a new record in any entity. fields_json: JSON object of field values.
@@ -910,28 +1103,67 @@ export async function createRecord(entityName, fieldsJson) {
910
1103
  const result = await insertEntity(v.entityName, [fields]);
911
1104
  return jsonResponse(result && result.length ? result[0] : null);
912
1105
  }
1106
+ /** Parse a merge_json/unmerge_json parameter into a list of field names. */
1107
+ function _parseNameList(raw, param) {
1108
+ if (raw === null || raw === undefined || raw === "") {
1109
+ return [];
1110
+ }
1111
+ const parsed = parseJsonParam(raw, param, "array");
1112
+ const bad = parsed.filter((n) => typeof n !== "string" || !n.trim());
1113
+ if (bad.length > 0) {
1114
+ throw new Error(`Parameter '${param}' must be a JSON array of field NAMES, e.g. ["watchers"] ` +
1115
+ `— got ${jsonResponse(parsed).slice(0, 60)}.`);
1116
+ }
1117
+ return parsed.map((n) => n.trim());
1118
+ }
913
1119
  /**
914
1120
  * Update a record in any entity. fields_json: JSON object of field values to update.
915
1121
  *
916
1122
  * Relation/enum values are shape-checked against the schema first (see
917
1123
  * create_record) — malformed shapes are refused instead of silently nulled.
918
- * Returns an explicit status: {updated:true, id, entity, changedFields} on
919
- * success, or {updated:false, reason} when the platform reports no change.
1124
+ *
1125
+ * A list-valued field is REPLACED by what you send. merge_json / unmerge_json
1126
+ * (arrays of field names, each of which must also be in fields_json with an
1127
+ * array value) switch those fields to add / remove instead; the pairing is
1128
+ * checked before the request, because a name the platform cannot line up is
1129
+ * ignored there — the list would be replaced and the call would still report
1130
+ * success. A list written without merge/unmerge comes back with an explicit
1131
+ * warning, so "added a watcher" can never read as clean when it wiped the rest.
1132
+ *
1133
+ * Returns {updated:true, id, entity, changedFields[, mergedFields, unmergedFields,
1134
+ * warning]} on success, or {updated:false, reason} when the platform reports no
1135
+ * change.
920
1136
  */
921
- export async function updateRecord(entityName, recordId, fieldsJson) {
1137
+ export async function updateRecord(entityName, recordId, fieldsJson, mergeJson = null, unmergeJson = null) {
922
1138
  let fields;
1139
+ let merge;
1140
+ let unmerge;
923
1141
  try {
924
1142
  fields = parseJsonParam(fieldsJson, "fields_json", "object");
1143
+ merge = _parseNameList(mergeJson, "merge_json");
1144
+ unmerge = _parseNameList(unmergeJson, "unmerge_json");
925
1145
  }
926
1146
  catch (e) {
927
1147
  return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
928
1148
  }
1149
+ const mergeProblems = mergeListProblems(fields, merge, unmerge);
1150
+ if (mergeProblems.length > 0) {
1151
+ return jsonResponse({
1152
+ error: "Refused: the merge/unmerge lists do not line up with fields_json. Nothing " +
1153
+ "was written — sending this would have REPLACED the list instead of " +
1154
+ "adding to it, and reported success.",
1155
+ problems: mergeProblems,
1156
+ hint: 'merge_json/unmerge_json take field NAMES (e.g. ["watchers"]); each name ' +
1157
+ 'must also appear in fields_json with an array value (e.g. {"watchers": ' +
1158
+ '[{"id": 15}]}), and no name may be in both lists.',
1159
+ });
1160
+ }
929
1161
  const v = await _validateRecordWrite(entityName, fields);
930
1162
  if (v.error) {
931
1163
  return v.error;
932
1164
  }
933
1165
  entityName = v.entityName;
934
- const result = await updateEntity(entityName, recordId, fields);
1166
+ const result = await updateEntity(entityName, recordId, fields, merge, unmerge);
935
1167
  if (!result || (Array.isArray(result) && result.length === 0)) {
936
1168
  return jsonResponse({
937
1169
  updated: false,
@@ -941,13 +1173,28 @@ export async function updateRecord(entityName, recordId, fieldsJson) {
941
1173
  "deleted, or the values matched the stored ones (no-op).",
942
1174
  });
943
1175
  }
944
- return jsonResponse({
1176
+ const out = {
945
1177
  updated: true,
946
1178
  id: recordId,
947
1179
  entity: entityName,
948
1180
  changedFields: Object.keys(fields),
949
- result: Array.isArray(result) && result.length ? result[0] : result,
950
- });
1181
+ };
1182
+ if (merge.length > 0) {
1183
+ out.mergedFields = merge;
1184
+ }
1185
+ if (unmerge.length > 0) {
1186
+ out.unmergedFields = unmerge;
1187
+ }
1188
+ const replacedLists = _replacedListNames(v.defs ?? null, fields, merge, unmerge);
1189
+ if (replacedLists.length > 0) {
1190
+ out.warning =
1191
+ `The ENTIRE list in [${replacedLists.join(", ")}] was REPLACED by the values ` +
1192
+ "sent — items that were stored before and not repeated here are now gone. " +
1193
+ "To add items instead, re-send with merge_json; to remove only the listed " +
1194
+ "items, use unmerge_json.";
1195
+ }
1196
+ out.result = Array.isArray(result) && result.length ? result[0] : result;
1197
+ return jsonResponse(out);
951
1198
  }
952
1199
  /**
953
1200
  * Pull the field list out of an entity schema, tolerant of response shape.
@@ -1109,7 +1356,9 @@ export async function attachFileToRecord(entityName, recordId, filePath, fieldNa
1109
1356
  }
1110
1357
  }
1111
1358
  /**
1112
- * Delete a record (instance) from any entity.
1359
+ * SOFT-delete a record (instance) from any entity: the platform sets deletedAt
1360
+ * and keeps the row, so this is reversible (restore is UI-only until 1.3.0) —
1361
+ * it is not a permanent purge. The record does vanish from normal reads.
1113
1362
  *
1114
1363
  * Removes a single instance, NOT the entity/schema. By design this module is
1115
1364
  * add-only at the schema level (create_entity / add_field / add_enum_values) —